def mover(co_ords, tempature): m = 0 # counter co_work = cpy(co_ords) while m <= M: # print(m) m += 1 co_olds = rand_select(co_work) co_new = cpy(co_olds) axis = random.choice((0, 1)) sign = random.choice((+1, -1)) co_new[0, axis] = co_new[0, axis] + delta * sign if sum(co_new[0]**2) > R**2: m -= 1 continue e_old = list(all_energy(co_olds)) e_new = zeroth_energy(co_new, e_old) change_e = abs(sum(e_old)) - abs(sum(e_new)) # print (change_e) # if change_e <= 0: # print('change_e=%f\t change/t=%f exp=%f'%(change_e, change_e / tempature, exp(change_e / tempature) )) if change_e >= 0: co_work = cpy(co_new) continue elif random.rand() < exp(change_e / tempature): co_work = cpy(co_new) continue else: continue return co_work
def get_tran_matrices_v2(td, rd, A, unknown_state_reward=-9999): print("Updated:unknown_state_reward: {} ".format(unknown_state_reward)) td = cpy(td) rd = cpy(rd) td["unknown_state"] = {} rd["unknown_state"] = {} for a in A: td["unknown_state"][a] = {"unknown_state": 1} rd["unknown_state"][a] = unknown_state_reward max_ns_count = max([len(td[s][a]) for s in td for a in td[s]]) tranMatrix = defaultdict(lambda: []) rewardMatrix = defaultdict(lambda: []) tranMatrixIndexes = defaultdict(lambda: []) state_to_index = {s: i for i, s in enumerate(td)} index_to_state = {i: s for i, s in enumerate(td)} for i, s in enumerate(td): for j, a in enumerate(A): next_state_probabilities = [ td[s][a][ns] for ns in td[s][a] ] if a in td[s] else [] # probabilities next_state_indexes = [ state_to_index[ns] if ns in state_to_index else state_to_index["unknown_state"] for ns in td[s][a] ] if a in td[s] else [] # indexes next_state_probabilities += [0] * ( max_ns_count - len(next_state_probabilities) ) if a in td[s] else [1 / max_ns_count] * max_ns_count # padding next_state_indexes += [state_to_index["unknown_state"]] * ( max_ns_count - len(next_state_indexes)) # padding assert len(next_state_indexes) == len(next_state_probabilities) tranMatrix[a].append(next_state_probabilities) rewardMatrix[a].append([rd[s][a]] * len(next_state_probabilities) if a in rd[s] else [unknown_state_reward] * len(next_state_probabilities)) tranMatrixIndexes[a].append(next_state_indexes) tranProbMatrix = np.array([tranMatrix[a] for a in tranMatrix]) rewardValMatrix = np.array([rewardMatrix[a] for a in rewardMatrix]) tranMatrixStateIndexes = np.array( [tranMatrixIndexes[a] for a in tranMatrixIndexes]) action_index_to_action = {i: a for i, a in enumerate(tranProbMatrix)} return tranProbMatrix, rewardValMatrix, action_index_to_action, tranMatrixStateIndexes, state_to_index, index_to_state
def relaycallback(bot, event): """ this is the callbacks that handles the responses to questions. """ # determine where the event came from e = cpy(event) origin = e.channel e.isrelayed = True e.headlines = True try: # loop over relays for origin for botname, type, target in relay.data[origin]: try: logging.debug('trying relay of %s to (%s,%s)' % (origin, type, target)) #if target == origin: continue # tests to prevent looping if botname == bot.cfg.name and origin == target: continue # check whether relay is blocked if block.data.has_key(origin): if [botname, type, target] in block.data[origin]: continue # retrieve the bot from fleet (based on type) fleet = getfleet() outbot = fleet.byname(botname) if not outbot: outbot = fleet.makebot(type, botname) if outbot: logging.info('relay - outbot found - %s - %s' % (outbot.cfg.name, outbot.type)) # we got bot .. use it to send the relayed message if e.nick == bot.cfg.nick: txt = "[!] %s" % e.txt else: txt = "[%s] %s" % (e.nick, e.txt) if event: t = "[%s]" % outbot.cfg.nick logging.debug("relay - sending to %s (%s)" % (target, outbot.cfg.name)) txt = stripcolor(txt) outbot.outnocb(target, txt, "normal", event=e) else: logging.info("can't find bot for (%s,%s,%s)" % (botname, type, target)) except Exception, ex: handle_exception() except KeyError: pass
def next_(self): self.f_ind += 1 if self.f_ind >= len(self.wav_files): self.show_saved.set('No more wav files. You are done!') self.f_ind -= 1 self.show_filename.set('displaying file #{} ({})'.format( self.f_ind, self.curr_filename())) # figure out what next d_ind should be highest = -1 for filename in os.listdir(self.save_folder): if self.curr_filename().split( '.')[0] in filename: # if voc pertains to current file ind = int(filename.split('-')[-1].split('.')[0]) if ind > highest: highest = cpy(ind) self.d_ind = highest + 1 self.show_mini.set('working on mini clip #{}'.format(self.d_ind)) self.curr_clip = AudioClip( os.path.join(self.data_folder, self.curr_filename())) # get audioclip viewable_pil = Image.fromarray( (self.curr_clip.spec * 255).astype('uint8')) self.temp = img = ImageTk.PhotoImage(image=viewable_pil) self.canvas_img2 = self.canvas.itemconfig(self.canvas_img1, image=img) if self.curr_rect_id: self.canvas.delete(self.curr_rect_id)
def generate_new_state(self, lst): grid = cpy(self.grid) for el in lst: grid[el[0]][el[1]] = self.current_player new_state = GameState(self.opponent(), grid) return new_state
def OnButtonAppend(evt): if len(self.data) == 1: btnUP.Enable(True) btnDOWN.Enable(True) elif len(self.data) == MAX_CHAR: MessageBox(self.panel, text.message1 % MAX_CHAR, text.messBoxTit1, wx.ICON_EXCLAMATION, plugin=self, time=10) evt.Skip() return replCtrl.ChangeValue("") sel = charListCtrl.GetSelection() + 1 self.data.insert(sel, cpy(EMPTY_CHAR)) charListCtrl.InsertStringItem(sel, "") SelRow(sel) charListCtrl.EnsureVisible(sel) ResetPattern() userCharLabelCtrl.ChangeValue("") userCharLabelCtrl.SetFocus() btnApp.Enable(False) btnDEL.Enable(True) self.panel.dialog.buttonRow.okButton.Enable(False) evt.Skip()
def score(pred, gt, chunk_size): diff = np.subtract(pred, gt) counts = { FALSE_POS: 0, FALSE_NEG: 0, } contig = 1 prev = diff[0] for curr in diff[1:]: if curr == prev: contig += 1 else: if contig >= chunk_size: if prev != 0: counts[prev] += contig contig = 1 prev = cpy(curr) if contig >= chunk_size: if prev != 0: counts[prev] += contig return { 'false pos': round(counts[FALSE_POS] / len(diff) * 100, 1), 'false neg': round(counts[FALSE_NEG] / len(diff) * 100, 1) }
def draw_squares(img, square_points): modified_img = cpy(img) # Time to print the squares over the image for square in square_points: x, y, width, height = square s_origin = (x, y) s_opposite = (x+width, y+height) cv2.rectangle(modified_img, s_origin, s_opposite, (0, 0, 255), 1) return modified_img
def rand_friend_list(NAME, name): friend_list = cpy(NAME) # yourself cannot be your friend friend_list.remove(name) n = random.randint(0, len(friend_list)) random.shuffle(friend_list) return sorted([friend_list.pop() for i in range(n)])
def zeroth_energy(co_ords, full_energy): # find energy of 0th co-ord to all others, en_new = cpy(full_energy) lst = [] for j in range(1, N): lst.append([co_ords[0], co_ords[j]]) for x, val in enumerate(it.starmap(E, lst)): en_new[x] = val return en_new
def __init__(self, parent, plugin): self.plugin = plugin wx.Dialog.__init__(self, parent, -1, style=wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE | wx.CLOSE_BOX | wx.TAB_TRAVERSAL, name=plugin.text.suffTitle) self.SetIcon(self.plugin.info.icon.GetWxIcon()) self.panel = parent self.suffixes = cpy(self.panel.suffixes)
def __init__(self, parent, plugin): self.plugin = plugin wx.Dialog.__init__( self, parent, -1, style = wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE | wx.CLOSE_BOX | wx.TAB_TRAVERSAL, name = plugin.text.suffTitle ) self.SetIcon(self.plugin.info.icon.GetWxIcon()) self.panel = parent self.suffixes = cpy(self.panel.suffixes)
def get_filtered_df(df_filter, dtf, _lowcut_freq, _highcut_freq): """ Filters the dataframe with bandpass df_filter """ dtf_aux = dtf.copy() for column in dtf.columns.values: df_column = cpy(dtf[column]) dtf_aux[column] = bandpass_filter(df_filter, df_column, _lowcut_freq, _highcut_freq) return dtf_aux
def __copy__(self): new = Project() # new.name = self.name + '*' for item in self.__dir__(): # if item == 'name': # continue item = "_" + item data = getattr(self, item) # if isinstance(data, (Project,NDDataset, Script)): # setattr(new, item, data.copy()) # elif item in ['_datasets', '_projects', '_scripts']: # # else: setattr(new, item, cpy(data)) return new
def handleCarIn(self,tmpCar): self.FSA.decideLane(tmpCar) this = tmpCar.lane other = "Right" if this == "Right": other = "Left" start = {"Left" : None , "Right" : None} for item in self.drivers: if item.journey > 0: break lane = item.lane start[lane] = item if start[this] == None: self.drivers.append(cpy(tmpCar)) self.inCar += 1 return True elif start[other] == None: tmpCar.lane = other self.drivers.append(cpy(tmpCar)) self.inCar += 1 return True else: return False
def copy(x, depth=0, max_depth=10): assert depth <= max_depth log_debug('copy', x, depth, max_depth) c = cpy(x) if isinstance(c, list): for i in range(len(c)): c[i] = copy(c[i], depth + 1) return c if isinstance(c, tuple): return tuple(copy(t, depth + 1) for t in c) if isinstance(c, dict): for k, v in c.items(): c[k] = copy(v, depth + 1) return c if is_myobj(c): c.__dict__.update(copy(c.__dict__, depth + 1)) return c
def relaycallback(bot, event): """ this is the callbacks that handles the responses to questions. """ # determine where the event came from #event.isrelayed = True e = cpy(event) origin = unicode((bot.cfg.name, e.channel)) e.isrelayed = True e.headlines = True try: # loop over relays for origin for botname, type, target in relay.data[origin]: try: logging.debug('trying relay of %s to (%s,%s)' % (origin, type, target)) #if target == origin: continue # tests to prevent looping if origin == (botname, target): continue # check whether relay is blocked if block.data.has_key(origin): if [botname, type, target] in block.data[origin]: continue # retrieve the bot from fleet (based on type) fleet = getfleet() outbot = fleet.byname(botname) if not outbot: outbot = fleet.makebot(type, botname) if outbot: logging.info('outbot found - %s - %s' % (outbot.cfg.name, outbot.type)) # we got bot .. use it to send the relayed message if e.nick == bot.cfg.nick: txt = "[!] %s" % e.txt else: txt = "[%s] %s" % (e.nick, e.txt) if event: t = "[%s]" % outbot.cfg.nick logging.debug("sending to %s (%s)" % (target, outbot.cfg.name)) txt = outbot.normalize(txt) txt = stripcolor(txt) outbot.putonqueue(-1, target, txt, "normal", event=e) else: logging.info("can't find bot for (%s,%s,%s)" % (botname, type, target)) except Exception, ex: handle_exception() except KeyError: pass
def save_checkpoint(self, fp=None): state = { 'epoch': self.epoch_num, 'best_net': self.best_net.state_dict(), 'curr_net': self.net.state_dict(), 'opt': self.opt.state_dict() } if fp is None: highest = -1 for filename in os.listdir('./checkpoints'): if '.pth.tar' in filename: ind = int(filename.split('.')[0].split('-')[-1]) if ind > highest: highest = cpy(ind) torch.save(state, 'checkpoint-{}.pth.tar'.format(highest + 1)) else: torch.save(state, fp)
def onBurn(evt): if self.data == [cpy(EMPTY_CHAR)]: MessageBox(self.panel, text.message3, text.messBoxTit4, wx.ICON_EXCLAMATION, plugin=self, time=10) return if not self.GetConnected(): MessageBox(self.panel, text.message2, text.messBoxTit2, wx.ICON_EXCLAMATION, plugin=self, time=10) return max = 1 + len(self.data) dlg = wx.ProgressDialog(self.text.progress, self.text.wait, maximum=max, parent=self.panel, style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL) dlg.SetIcon(self.info.icon.GetWxIcon()) keepGoing = True count = 0 for i, ch in enumerate(self.data): event = CreateEvent(None, 0, 0, None) item = list(ch[2]) item.append(i) item.append(ord(ch[1])) self.queue.put(((COMMANDS["Burn"], item), event)) eg.actionThread.WaitOnEvent(event) count += 1 (keepGoing, skip) = dlg.Update(count) self.queue.put(((COMMANDS["Burn"], (len(self.data), )), event)) count += 1 eg.actionThread.WaitOnEvent(event) (keepGoing, skip) = dlg.Update(count, self.text.done) self.eechars = len(self.data)
def __init__(self, obj, copy=True, **kwargs): self.original_shape = None # if a dtype kwarg has been supplied, use that dtype = kwargs.get('dtype', self.datatype) if isinstance(obj, self.__class__): if copy: self.data = obj.data.copy() else: self.data = obj.data self.original_shape = cpy(obj.original_shape) return if not isinstance(obj, np.ndarray): obj = np.array(obj, dtype=dtype, copy=copy) else: obj = obj.astype(dtype, copy=copy) # check dimensions if obj.ndim == 0: # input is a single value self.data = obj.reshape(1, 1) elif obj.ndim == 1: self.data = obj.reshape((obj.size, 1)) elif obj.ndim == 2: self.data = obj elif obj.ndim > 2: # separate by last dimension, flattening all other dimensions # NB: the order of unravelling here is numpy's default 'C' method # the same ordering is used by the 'flat' iterator nd = obj.shape[-1] ndata = obj[..., 0].size # record original shape for later rebuilding self.original_shape = obj[..., 0].shape dim_arrs = [] for i in range(nd): dim_arrs.append(obj[..., i].flatten()) self.data = np.vstack(dim_arrs).transpose()
def make_safe_move(self): """ Returns a safe cell to choose on the Minesweeper board. The move must be known to be safe, and not already a move that has been made. This function may use the knowledge in self.mines, self.safes and self.moves_made, but should not modify any of those values. """ # makes a deepcopy of safes cause I am afraid of soft copies safe = cpy(self.safes) # initialize move to none move = None # happens while move is not a safe valid move while move in self.moves_made or move in self.mines or move is None: # none safe move possible return None if len(safe) == 0: return None move = safe.pop() return move
def runTest(template_test,type_id): tmpTest1 = cpy(template_test) tmpTest1.setFSA(test_type[type_id]) pointer = 0 totalCar = len(drivers_list) f2.write("Rule : " + test_type[type_id] + "\n") for j in xrange(tmpTest1.testTime): tmpTest1.clearCrash() tmpTest1.handleCarOut() if pointer < totalCar and show_time[pointer] <= j: if tmpTest1.handleCarIn(drivers_list[pointer]): pointer += 1 tmpTest1.finish() tmpTest1.makeDecision() tmpTest1.handleCrash() if j % 60 == 59: f2.write(str(len(tmpTest1.drivers) * 1.0 / tmpTest1.road.numberOfPiece)) f2.write(" , ") f2.write("\n") f1.write("Rule : " + test_type[type_id] + " " + str({"carIn" : tmpTest1.inCar , "carOut" : tmpTest1.receiveCar , "carCrash" : tmpTest1.crashCar}) + "\n")
def OnButtonDel(evt): sel = charListCtrl.GetSelection() charListCtrl.DeleteItem(sel) self.data.pop(sel) lngth = len(self.data) if lngth > 0: if sel == lngth: sel = lngth - 1 charListCtrl.SetSelection(sel) else: userCharLabelCtrl.ChangeValue("") self.data = [cpy(EMPTY_CHAR)] sel = 0 charListCtrl.InsertStringItem(0, "") btnDEL.Enable(False) FillData(self.data[sel]) SelRow(sel) charListCtrl.EnsureVisible(sel) userCharLabelCtrl.SetFocus() validation() if len(self.data) == 1: btnUP.Enable(False) btnDOWN.Enable(False) evt.Skip()
def plot_2D(dataset, method=None, **kwargs): """ Plot of 2D array. Parameters ---------- dataset : |NDDataset| The dataset to plot. method : ['stack', 'map', 'image'] , optional The method of plot of the dataset, which will determine the plotter to use. Default method is given 'stack' but this can be changed using ``dataset.preference.method_2D``. **kwargs Optional keyword parameters (see Other Parameters). Other Parameters ---------------- {0} See Also -------- plot_map plot_stack plot_image plot_surface plot_waterfall """ # Get preferences # ------------------------------------------------------------------------ prefs = dataset.preferences # before going further, check if the style is passed in the parameters style = kwargs.pop("style", None) if style is not None: prefs.style = style # else we assume this has been set before calling plot() prefs.set_latex_font(prefs.font.family) # reset latex settings # Redirections ? # ------------------------------------------------------------------------ # should we redirect the plotting to another method if dataset._squeeze_ndim < 2: return dataset.plot_1D(**kwargs) # if plotly execute plotly routine not this one if kwargs.get("use_plotly", prefs.use_plotly): return dataset.plotly(**kwargs) # do not display colorbar if it's not a surface plot # except if we have asked to d so # often we do need to plot only data when plotting on top of a previous plot data_only = kwargs.get("data_only", False) # Get the data to plot # --------------------------------------------------------------- # if we want to plot the transposed dataset transposed = kwargs.get("transposed", False) if transposed: new = dataset.copy().T # transpose dataset nameadd = ".T" else: new = dataset # .copy() nameadd = "" new = new.squeeze() if kwargs.get("y_reverse", False): new = new[::-1] # Figure setup # ------------------------------------------------------------------------ method = new._figure_setup(ndim=2, method=method, **kwargs) ax = new.ndaxes["main"] ax.name = ax.name + nameadd # Other properties that can be passed as arguments # ------------------------------------------------------------------------ lw = kwargs.get("linewidth", kwargs.get("lw", prefs.lines_linewidth)) alpha = kwargs.get("calpha", prefs.contour_alpha) number_x_labels = prefs.number_of_x_labels number_y_labels = prefs.number_of_y_labels number_z_labels = prefs.number_of_z_labels if method in ["waterfall"]: nxl = number_x_labels * 2 nyl = number_z_labels * 2 elif method in ["stack"]: nxl = number_x_labels nyl = number_z_labels else: nxl = number_x_labels nyl = number_y_labels ax.xaxis.set_major_locator(MaxNLocator(nbins=nxl)) ax.yaxis.set_major_locator(MaxNLocator(nbins=nyl)) if method not in ["surface"]: ax.xaxis.set_ticks_position("bottom") ax.yaxis.set_ticks_position("left") # the next lines are to avoid multipliers in axis scale formatter = ScalarFormatter(useOffset=False) ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) # ------------------------------------------------------------------------ # Set axis # ------------------------------------------------------------------------ # set the abscissa axis # ------------------------------------------------------------------------ # the actual dimension name is the last in the new.dims list dimx = new.dims[-1] x = getattr(new, dimx) if x is not None and x.implements("CoordSet"): # if several coords, take the default ones: x = x.default xsize = new.shape[-1] show_x_points = False if x is not None and hasattr(x, "show_datapoints"): show_x_points = x.show_datapoints if show_x_points: # remove data and units for display x = LinearCoord.arange(xsize) discrete_data = False if x is not None and (not x.is_empty or x.is_labeled): xdata = x.data if not np.any(xdata): if x.is_labeled: discrete_data = True # take into account the fact that sometimes axis have just labels xdata = range(1, len(x.labels) + 1) else: xdata = range(xsize) xl = [xdata[0], xdata[-1]] xl.sort() if xsize < number_x_labels + 1: # extend the axis so that the labels are not too close to the limits inc = abs(xdata[1] - xdata[0]) * 0.5 xl = [xl[0] - inc, xl[1] + inc] if data_only: xl = ax.get_xlim() xlim = list(kwargs.get("xlim", xl)) xlim.sort() xlim[-1] = min(xlim[-1], xl[-1]) xlim[0] = max(xlim[0], xl[0]) if kwargs.get("x_reverse", kwargs.get("reverse", x.reversed if x else False)): xlim.reverse() ax.set_xlim(xlim) xscale = kwargs.get("xscale", "linear") ax.set_xscale(xscale) # , nonpositive='mask') # set the ordinates axis # ------------------------------------------------------------------------ # the actual dimension name is the second in the new.dims list dimy = new.dims[-2] y = getattr(new, dimy) if y is not None and y.implements("CoordSet"): # if several coords, take the default ones: y = y.default ysize = new.shape[-2] show_y_points = False if y is not None and hasattr(y, "show_datapoints"): show_y_points = y.show_datapoints if show_y_points: # remove data and units for display y = LinearCoord.arange(ysize) if y is not None and (not y.is_empty or y.is_labeled): ydata = y.data if not np.any(ydata): if y.is_labeled: ydata = range(1, len(y.labels) + 1) else: ydata = range(ysize) yl = [ydata[0], ydata[-1]] yl.sort() if ysize < number_y_labels + 1: # extend the axis so that the labels are not too close to the limits inc = abs(ydata[1] - ydata[0]) * 0.5 yl = [yl[0] - inc, yl[1] + inc] if data_only: yl = ax.get_ylim() ylim = list(kwargs.get("ylim", yl)) ylim.sort() ylim[-1] = min(ylim[-1], yl[-1]) ylim[0] = max(ylim[0], yl[0]) yscale = kwargs.get("yscale", "linear") ax.set_yscale(yscale) # z intensity (by default we plot real component of the data) # ------------------------------------------------------------------------ if not kwargs.get("imag", False): zdata = new.real.masked_data else: zdata = ( new.RI.masked_data ) # new.imag.masked_data #TODO: quaternion case (3 imag.components) zlim = kwargs.get("zlim", (np.ma.min(zdata), np.ma.max(zdata))) if method in ["stack", "waterfall"]: # the z axis info # --------------- # zl = (np.min(np.ma.min(ys)), np.max(np.ma.max(ys))) amp = 0 # np.ma.ptp(zdata) / 50. zl = (np.min(np.ma.min(zdata) - amp), np.max(np.ma.max(zdata)) + amp) zlim = list(kwargs.get("zlim", zl)) zlim.sort() z_reverse = kwargs.get("z_reverse", False) if z_reverse: zlim.reverse() # set the limits # --------------- if yscale == "log" and min(zlim) <= 0: # set the limits wrt smallest and largest strictly positive values ax.set_ylim( 10 ** (int(np.log10(np.amin(np.abs(zdata)))) - 1), 10 ** (int(np.log10(np.amax(np.abs(zdata)))) + 1), ) else: ax.set_ylim(zlim) else: # the y axis info # ---------------- if data_only: ylim = ax.get_ylim() ylim = list(kwargs.get("ylim", ylim)) ylim.sort() y_reverse = kwargs.get("y_reverse", y.reversed if y else False) if y_reverse: ylim.reverse() # set the limits # ---------------- ax.set_ylim(ylim) # ------------------------------------------------------------------------ # plot the dataset # ------------------------------------------------------------------------ ax.grid(prefs.axes_grid) normalize = kwargs.get("normalize", None) cmap = kwargs.get("colormap", kwargs.get("cmap", prefs.colormap)) if method in ["map", "image", "surface"]: zmin, zmax = zlim zmin = min(zmin, -zmax) zmax = max(-zmin, zmax) norm = mpl.colors.Normalize(vmin=zmin, vmax=zmax) if method in ["surface"]: X, Y = np.meshgrid(xdata, ydata) Z = zdata.copy() # masker data not taken into account in surface plot Z[dataset.mask] = np.nan # Plot the surface. #TODO : improve this (or remove it) antialiased = kwargs.get("antialiased", prefs.antialiased) rcount = kwargs.get("rcount", prefs.rcount) ccount = kwargs.get("ccount", prefs.ccount) ax.set_facecolor("w") ax.plot_surface( X, Y, Z, cmap=cmap, linewidth=lw, antialiased=antialiased, rcount=rcount, ccount=ccount, edgecolor="k", norm=norm, ) if method in ["waterfall"]: _plot_waterfall(ax, new, xdata, ydata, zdata, prefs, xlim, ylim, zlim, **kwargs) elif method in ["image"]: cmap = kwargs.get("cmap", kwargs.get("image_cmap", prefs.image_cmap)) if discrete_data: method = "map" else: kwargs["nlevels"] = 500 if not hasattr(new, "clevels") or new.clevels is None: new.clevels = _get_clevels(zdata, prefs, **kwargs) c = ax.contourf(xdata, ydata, zdata, new.clevels, alpha=alpha) c.set_cmap(cmap) c.set_norm(norm) elif method in ["map"]: if discrete_data: _colormap = plt.get_cmap(cmap) scalarMap = mpl.cm.ScalarMappable(norm=norm, cmap=_colormap) # marker = kwargs.get('marker', kwargs.get('m', None)) markersize = kwargs.get("markersize", kwargs.get("ms", 5.0)) # markevery = kwargs.get('markevery', kwargs.get('me', 1)) for i in ydata: for j in xdata: (li,) = ax.plot(j, i, lw=lw, marker="o", markersize=markersize) li.set_color(scalarMap.to_rgba(zdata[i - 1, j - 1])) else: # contour plot # ------------- if not hasattr(new, "clevels") or new.clevels is None: new.clevels = _get_clevels(zdata, prefs, **kwargs) c = ax.contour(xdata, ydata, zdata, new.clevels, linewidths=lw, alpha=alpha) c.set_cmap(cmap) c.set_norm(norm) elif method in ["stack"]: # stack plot # ---------- # now plot the collection of lines # -------------------------------- # map colors using the colormap vmin, vmax = ylim norm = mpl.colors.Normalize( vmin=vmin, vmax=vmax ) # we normalize to the max time if normalize is not None: norm.vmax = normalize _colormap = plt.get_cmap(cmap) scalarMap = mpl.cm.ScalarMappable(norm=norm, cmap=_colormap) # we display the line in the reverse order, so that the last # are behind the first. clear = kwargs.get("clear", True) lines = [] if not clear and not transposed: lines.extend(ax.lines) # keep the old lines line0 = mpl.lines.Line2D(xdata, zdata[0], lw=lw, picker=True) for i in range(zdata.shape[0]): li = cpy(line0) li.set_ydata(zdata[i]) lines.append(li) li.set_color(scalarMap.to_rgba(ydata[i])) fmt = kwargs.get("label_fmt", "{:.5f}") li.set_label(fmt.format(ydata[i])) li.set_zorder(zdata.shape[0] + 1 - i) # store the full set of lines new._ax_lines = lines[:] # but display only a subset of them in order to accelerate the drawing maxlines = kwargs.get("maxlines", prefs.max_lines_in_stack) setpy = max(len(new._ax_lines) // maxlines, 1) for line in new._ax_lines[::setpy]: ax.add_line(line) if data_only or method in ["waterfall"]: # if data only (we will not set axes and labels # it was probably done already in a previous plot new._plot_resume(dataset, **kwargs) return ax # display a title # ------------------------------------------------------------------------ title = kwargs.get("title", None) if title: ax.set_title(title) elif kwargs.get("plottitle", False): ax.set_title(new.name) # ------------------------------------------------------------------------ # labels # ------------------------------------------------------------------------ # x label # ------------------------------------------------------------------------ xlabel = kwargs.get("xlabel", None) if show_x_points: xlabel = "data points" if not xlabel: xlabel = make_label(x, new.dims[-1]) ax.set_xlabel(xlabel) uselabelx = kwargs.get("uselabel_x", False) if ( x and x.is_labeled and (uselabelx or not np.any(x.data)) and len(x.labels) < number_x_labels + 1 ): # TODO refine this to use different orders of labels ax.set_xticks(xdata) ax.set_xticklabels(x.labels) # y label # ------------------------------------------------------------------------ ylabel = kwargs.get("ylabel", None) if show_y_points: ylabel = "data points" if not ylabel: if method in ["stack"]: ylabel = make_label(new, "values") else: ylabel = make_label(y, new.dims[-2]) # y tick labels uselabely = kwargs.get("uselabel_y", False) if ( y and y.is_labeled and (uselabely or not np.any(y.data)) and len(y.labels) < number_y_labels ): # TODO refine this to use different orders of labels ax.set_yticks(ydata) ax.set_yticklabels(y.labels) # z label # ------------------------------------------------------------------------ zlabel = kwargs.get("zlabel", None) if not zlabel: if method in ["stack"]: zlabel = make_label(y, new.dims[-2]) elif method in ["surface"]: zlabel = make_label(new, "values") ax.set_zlabel(zlabel) else: zlabel = make_label(new, "z") # do we display the ordinate axis? if kwargs.get("show_y", True): ax.set_ylabel(ylabel) else: ax.set_yticks([]) if "colorbar" in new.ndaxes: if "surface" not in method and (not hasattr(new, "_axcb") or not new._axcb): axec = new.ndaxes["colorbar"] axec.name = axec.name + nameadd new._axcb = mpl.colorbar.ColorbarBase( axec, cmap=plt.get_cmap(cmap), norm=norm ) new._axcb.set_label(zlabel) # else: # new._fig.colorbar(surf, shrink=0.5, aspect=10) # do we display the zero line if kwargs.get("show_zero", False): ax.haxlines() new._plot_resume(dataset, **kwargs) return ax
def Configure(self, Prefix="Remote", remotes=[], suffixes=None): egEventInit = eg.EventGhostEvent.__init__ text = self.text self.remotes = cpy(remotes) del remotes panel = eg.ConfigPanel(self, resizable=True) if not suffixes: from eg.Classes.IrDecoder.Rc6 import MCE_REMOTE as MCE suffixes = list(MCE.itervalues()) panel.suffixes = suffixes def TestUse(val): rem = None for item in self.remotes: for button in item[2]: if button[2] == val: rem = item[0] break if rem: break return rem panel.testUse = TestUse leftSizer = wx.BoxSizer(wx.VERTICAL) box1 = wx.StaticBox(panel, -1, "") eventSizer = wx.StaticBoxSizer(box1, wx.VERTICAL) prefLabel = wx.StaticText(panel, -1, text.prefix) prefText = wx.TextCtrl(panel, -1, Prefix) prefLabel2 = wx.StaticText(panel, -1, text.nativePrefix) prefText2 = wx.TextCtrl(panel, -1, "") buttonsListCtrl = wx.ListCtrl(panel, -1, style=wx.LC_REPORT | wx.VSCROLL | wx.LC_VRULES | wx.LC_HRULES | wx.LC_SINGLE_SEL) self.back = buttonsListCtrl.GetBackgroundColour() self.fore = buttonsListCtrl.GetForegroundColour() self.selBack = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT) self.selFore = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT) suffText = wx.TextCtrl(panel, -1, "", style=wx.TE_READONLY) suffText.SetToolTipString(text.suffToolTip) labelText = wx.TextCtrl(panel, -1, "") suffChoice = wx.Choice(panel, -1, choices=panel.suffixes) def UpdateChoices(): suffChoice.Clear() suffChoice.AppendItems(panel.suffixes) panel.updateChoices = UpdateChoices evtPrefSizer = wx.BoxSizer(wx.HORIZONTAL) evtPrefSizer.Add(prefLabel, 0, wx.TOP, 3) evtPrefSizer.Add(prefText, 1, wx.EXPAND | wx.LEFT, 5) eventSizer.Add(evtPrefSizer, 0, wx.EXPAND | wx.TOP, 4) suffButton = wx.Button(panel, -1, text.suffixes) eventSizer.Add(suffButton, 0, wx.EXPAND | wx.TOP, 8) remListSizer = wx.GridBagSizer(1, 10) box2 = wx.StaticBox(panel, -1, "") rightStatSizer = wx.StaticBoxSizer(box2, wx.VERTICAL) rightSizer = wx.GridBagSizer(8, 1) rightStatSizer.Add(rightSizer, 1, wx.EXPAND) remListLabel = wx.StaticText(panel, -1, text.menuPreview) listBoxCtrl = wx.ListBox(panel, -1, style=wx.LB_SINGLE | wx.LB_NEEDED_SB) labelLbl = wx.StaticText(panel, -1, text.label) labelCtrl = wx.TextCtrl(panel, -1, '') #Buttons 'Delete', 'Import', 'Export' and 'Insert new' lenLst = [panel.GetTextExtent(item)[0] for item in text.buttons] btn = wx.Button(panel, -1, text.buttons[lenLst.index(max(lenLst))]) sz = btn.GetSize() btn.Destroy() btnDEL = wx.Button(panel, -1, text.buttons[0], size=sz) btnApp = wx.Button(panel, -1, text.buttons[1], size=sz) btnImp = wx.Button(panel, -1, text.buttons[2], size=sz) btnExp = wx.Button(panel, -1, text.buttons[3], size=sz) def EnableBtns(enable): btnDEL.Enable(enable) btnImp.Enable(enable) btnExp.Enable(enable) def EnableLabel(enable): labelCtrl.Enable(enable) labelLbl.Enable(enable) EnableBtns(False) EnableLabel(False) lenLst = [panel.GetTextExtent(item)[0] for item in text.buttons2] btn = wx.Button(panel, -1, text.buttons2[lenLst.index(max(lenLst))]) sz = btn.GetSize() btn.Destroy() delEvent = wx.Button(panel, -1, text.buttons2[0], size=sz) clearEvents = wx.Button(panel, -1, text.buttons2[1], size=sz) addEvent = wx.Button(panel, -1, text.buttons2[2], size=sz) duplEvent = wx.Button(panel, -1, text.buttons2[3], size=sz) #Button UP bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_UP, wx.ART_OTHER, (16, 16)) btnUP = wx.BitmapButton(panel, -1, bmp) btnUP.Enable(False) #Button DOWN bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_DOWN, wx.ART_OTHER, (16, 16)) btnDOWN = wx.BitmapButton(panel, -1, bmp) btnDOWN.Enable(False) leftSizer.Add(eventSizer, 0, wx.EXPAND) leftSizer.Add(remListSizer, 1, wx.EXPAND | wx.TOP, 15) leftSizer.Add((1, 4)) mainSizer = wx.BoxSizer(wx.HORIZONTAL) mainSizer.Add(leftSizer, 0, wx.EXPAND) mainSizer.Add(rightStatSizer, 1, wx.LEFT | wx.EXPAND, 24) panel.sizer.Add(mainSizer, 1, wx.EXPAND) def EnableCtrls(enable): suffText.Enable(enable) labelText.Enable(enable) suffChoice.Enable(enable) if enable: eg.EventGhostEvent.__init__ = EventRemap else: eg.EventGhostEvent.__init__ = egEventInit def ResetCtrls(): suffText.ChangeValue("") labelText.ChangeValue("") suffChoice.SetSelection(-1) def FillButtonsList(item): buttonsListCtrl.DeleteAllItems() for row in range(len(item[2])): buttonsListCtrl.InsertStringItem(row, item[2][row][0]) buttonsListCtrl.SetStringItem(row, 1, item[2][row][1]) buttonsListCtrl.SetStringItem(row, 2, item[2][row][2]) def FillRemoteForm(item): self.oldSel = -1 prefText2.SetValue(item[1]) enable = item[1] != "" addEvent.Enable(enable) ResetCtrls() FillButtonsList(item) clearEvents.Enable(len(item[2]) > 0) EnableButtonsRight(False) duplEvent.Enable(False) EnableCtrls(False) evtPrefSizer2 = wx.BoxSizer(wx.HORIZONTAL) evtPrefSizer2.Add((-1, 1), 1, wx.EXPAND) evtPrefSizer2.Add(prefLabel2, 0, wx.TOP, 3) evtPrefSizer2.Add(prefText2, 0, wx.LEFT, 5) w = 0 for i, colLabel in enumerate(text.header): buttonsListCtrl.InsertColumn(i, colLabel) buttonsListCtrl.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER) w += buttonsListCtrl.GetColumnWidth(i) buttonsListCtrl.SetSize( (w + SYS_VSCROLL_X + buttonsListCtrl.GetWindowBorderSize()[0], -1)) w0 = buttonsListCtrl.GetColumnWidth(0) w1 = buttonsListCtrl.GetColumnWidth(1) w2 = buttonsListCtrl.GetColumnWidth(2) suffText.SetMinSize((w0 - 1, -1)) labelText.SetMinSize((w1 - 1, -1)) suffChoice.SetMinSize((w2 - 1, -1)) rightSizer.Add(evtPrefSizer2, (0, 0), (1, 4), flag=wx.EXPAND | wx.TOP, border=4) rightSizer.Add(buttonsListCtrl, (1, 0), (5, 4), flag=wx.EXPAND) rightSizer.Add(delEvent, (1, 4), flag=wx.TOP | wx.ALIGN_RIGHT, border=24) rightSizer.Add(clearEvents, (2, 4), flag=wx.ALIGN_RIGHT) brdr = 8 + SYS_VSCROLL_X + buttonsListCtrl.GetWindowBorderSize()[0] rightSizer.Add(btnUP, (3, 4), flag=wx.LEFT, border=brdr) rightSizer.Add(btnDOWN, (4, 4), flag=wx.LEFT, border=brdr) rightSizer.Add(duplEvent, (5, 4), flag=wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT) rightSizer.Add(suffText, (6, 0), flag=wx.EXPAND | wx.LEFT, border=1) rightSizer.Add(labelText, (6, 1), flag=wx.EXPAND | wx.LEFT, border=1) rightSizer.Add(suffChoice, (6, 2), flag=wx.EXPAND | wx.LEFT, border=1) rightSizer.Add(addEvent, (6, 4), flag=wx.LEFT, border=brdr) rightSizer.AddGrowableRow(5) rightSizer.AddGrowableCol(0, w0) rightSizer.AddGrowableCol(1, w1) rightSizer.AddGrowableCol(2, w2) remListSizer.Add(remListLabel, (0, 0)) remListSizer.Add(listBoxCtrl, (1, 0), (4, 1), flag=wx.EXPAND) remListSizer.Add(labelLbl, (5, 0), flag=wx.TOP, border=8) remListSizer.Add(labelCtrl, (6, 0), flag=wx.EXPAND) remListSizer.Add(btnDEL, (1, 1)) remListSizer.Add(btnImp, (2, 1), flag=wx.TOP, border=8) remListSizer.Add(btnExp, (3, 1), flag=wx.TOP, border=8) remListSizer.Add((-1, 1), (4, 1)) remListSizer.Add(btnApp, (6, 1)) remListSizer.AddGrowableRow(4) panel.sizer.Layout() def EnableLeftSide(enable): EnableBtns(enable) EnableLabel(enable) btnApp.Enable(enable) remListLabel.Enable(enable) listBoxCtrl.Enable(enable) labelLbl.Enable(enable) labelCtrl.Enable(enable) def SetWidth(): w0 = suffText.GetSize()[0] + 1 w1 = labelText.GetSize()[0] + 1 w2 = suffChoice.GetSize()[0] + 1 buttonsListCtrl.SetSize( (w0 + w1 + w2 + SYS_VSCROLL_X + buttonsListCtrl.GetWindowBorderSize()[0], -1)) buttonsListCtrl.SetColumnWidth(0, w0) buttonsListCtrl.SetColumnWidth(1, w1) buttonsListCtrl.SetColumnWidth(2, w2) def OnSize(event): wx.CallAfter(SetWidth) panel.Update() event.Skip() panel.Bind(wx.EVT_SIZE, OnSize) def OnDelEvent(evt): rem = listBoxCtrl.GetSelection() self.remotes[rem][2].pop(self.oldSel) buttonsListCtrl.DeleteItem(self.oldSel) lngth = len(self.remotes[rem][2]) prefText2.Enable(True) if lngth == 0: self.oldSel = -1 OnPrefText2() ResetCtrls() evt.Skip() return elif self.oldSel == lngth: row = lngth - 1 else: row = self.oldSel self.oldSel = -1 SelRow(row) suffText.ChangeValue(buttonsListCtrl.GetItemText(row)) labelText.ChangeValue(buttonsListCtrl.GetItem(row, 1).GetText()) suffChoice.SetStringSelection( buttonsListCtrl.GetItem(row, 2).GetText()) OnPrefText2() Validation() evt.Skip() delEvent.Bind(wx.EVT_BUTTON, OnDelEvent) def OnClearEvents(evt): rem = listBoxCtrl.GetSelection() self.remotes[rem][2] = [] buttonsListCtrl.DeleteAllItems() self.oldSel = -1 EnableLeftSide(True) prefText2.Enable(True) OnPrefText2() ResetCtrls() evt.Skip() clearEvents.Bind(wx.EVT_BUTTON, OnClearEvents) def onButtonDelete(evt): sel = listBoxCtrl.GetSelection() listBoxCtrl.Delete(sel) self.remotes.pop(sel) lngth = len(self.remotes) if lngth > 0: if sel == lngth: sel = lngth - 1 listBoxCtrl.SetSelection(sel) onClick() else: labelCtrl.ChangeValue("") EnableBtns(False) item = ["", "", []] FillRemoteForm(item) evt.Skip() btnDEL.Bind(wx.EVT_BUTTON, onButtonDelete) def OnLabelChange(evt): flag = False sel = listBoxCtrl.GetSelection() label = labelCtrl.GetValue() self.remotes[sel][0] = label listBoxCtrl.SetString(sel, label) enable = label != "" if enable: if [n[0] for n in self.remotes].count(label) == 1: flag = True EnableBtns(enable) panel.dialog.buttonRow.okButton.Enable(flag) btnApp.Enable(flag) item = self.remotes[sel] prefText2.Enable(flag) OnPrefText2() if not flag: addEvent.Enable(False) evt.Skip() labelCtrl.Bind(wx.EVT_TEXT, OnLabelChange) def OnButtonAppend(evt): EnableLabel(True) item = ["", "", []] self.remotes.append(item) listBoxCtrl.Append("") listBoxCtrl.SetSelection(listBoxCtrl.GetCount() - 1) prefText2.ChangeValue("") labelCtrl.SetValue("") FillRemoteForm(item) labelCtrl.SetFocus() addEvent.Enable(False) evt.Skip() btnApp.Bind(wx.EVT_BUTTON, OnButtonAppend) def EnableButtonsRight(enable): delEvent.Enable(enable) if enable: rem = listBoxCtrl.GetSelection() if len(self.remotes[rem][2]) < 2: enable = False btnUP.Enable(enable) btnDOWN.Enable(enable) def OnPrefText2(evt=None): global prefix prefix = prefText2.GetValue() rem = listBoxCtrl.GetSelection() if rem > -1: self.remotes[rem][1] = prefix s = None if prefix != "": #Conflict test: for i in range(len(self.remotes)): rmt = self.remotes[i] if prefix != rmt[1] or i == rem: continue for suff in self.remotes[rem][2]: for sf in rmt[2]: if suff[0] == sf[0] and suff[2] != sf[2]: s = suff[0] n = rmt[0] n0 = suff[2] n1 = sf[2] break if s: break if s: break if s: MessageBox( panel, text.message4 % (prefix, prefix, s, n0, n, n1), text.messBoxTit2, wx.ICON_EXCLAMATION, plugin=self, ) EnableLeftSide(False) panel.dialog.buttonRow.okButton.Enable(False) else: EnableLeftSide(True) panel.dialog.buttonRow.okButton.Enable(True) enable = prefix != "" and not s buttonsListCtrl.Enable(enable) if not enable or len(self.remotes[rem][2]) == 0: addEvent.Enable(False) duplEvent.Enable(False) EnableButtonsRight(False) clearEvents.Enable(False) EnableCtrls(False) elif enable and len(self.remotes[rem][2]) > 0: clearEvents.Enable(True) if self.oldSel != -1: EnableButtonsRight(True) duplEvent.Enable(True) EnableCtrls(True) else: EnableButtonsRight(False) duplEvent.Enable(False) EnableCtrls(False) if enable and len(self.remotes[rem][2]) == 0: addEvent.Enable(True) if evt: evt.Skip() prefText2.Bind(wx.EVT_TEXT, OnPrefText2) def Validation(): flag = True strng = suffText.GetValue() prfx = prefText2.GetValue() rem = listBoxCtrl.GetSelection() newSuff = suffChoice.GetStringSelection() name = None sfx = None for i in range(len(self.remotes)): item = self.remotes[i] if i == rem or item[1] != prfx: continue for suff in item[2]: if suff[0] == strng and suff[2] != newSuff: name = item[0] sfx = suff[2] break if name: break if name: MessageBox( panel, text.message2 % (prfx, strng, newSuff, sfx, name), text.messBoxTit2, wx.ICON_EXCLAMATION, plugin=self, ) flag = False if [item[0] for item in self.remotes[rem][2]].count(strng) > 1: suffText.SetValue("") MessageBox(panel, text.message6 % (strng), text.messBoxTit3, wx.ICON_EXCLAMATION, plugin=self, time=7) if strng == "": flag = False if labelText.GetValue().strip() == "": flag = False if suffChoice.GetSelection() == -1: flag = False addEvent.Enable(flag) duplEvent.Enable(flag) prefText2.Enable(flag) EnableLeftSide(flag) panel.dialog.buttonRow.okButton.Enable(flag) def EventRemap(self, suffix="", payload=None, prefix="Main", source=eg): SetSuffix(prefix, suffix) self.string = "%s.%s" % (prefix, suffix) self.prefix = prefix self.suffix = suffix self.payload = payload self.source = source self.time = clock() self.isEnded = False self.shouldEnd = Event() self.upFuncList = [] def SetSuffix(eventPrefix, eventSuffix): if prefix == eventPrefix: suffText.SetValue(eventSuffix) def OnButtonAddEvent(evt): if self.oldSel == -1: self.oldSel = buttonsListCtrl.GetItemCount() - 1 row = self.oldSel + 1 self.remotes[listBoxCtrl.GetSelection()][2].insert( row, ["", "", ""]) buttonsListCtrl.InsertStringItem(row, "") buttonsListCtrl.SetStringItem(row, 1, "") buttonsListCtrl.SetStringItem(row, 2, "") buttonsListCtrl.EnsureVisible(row) SelRow(row) EnableCtrls(True) addEvent.Enable(False) duplEvent.Enable(False) clearEvents.Enable(True) prefText2.Enable(False) EnableLeftSide(False) panel.dialog.buttonRow.okButton.Enable(False) ResetCtrls() EnableButtonsRight(True) evt.Skip() addEvent.Bind(wx.EVT_BUTTON, OnButtonAddEvent) def OnButtonDuplEvent(evt): addEvent.Enable(False) duplEvent.Enable(False) panel.dialog.buttonRow.okButton.Enable(False) suffText.ChangeValue("") strng1 = labelText.GetValue() strng2 = suffChoice.GetStringSelection() row = self.oldSel + 1 self.remotes[listBoxCtrl.GetSelection()][2].insert( row, ["", strng1, strng2]) buttonsListCtrl.InsertStringItem(row, "") buttonsListCtrl.SetStringItem(row, 1, strng1) buttonsListCtrl.SetStringItem(row, 2, strng2) SelRow(row) buttonsListCtrl.EnsureVisible(row) evt.Skip() duplEvent.Bind(wx.EVT_BUTTON, OnButtonDuplEvent) def OnSuffText(evt): strng = evt.GetString() self.remotes[listBoxCtrl.GetSelection()][2][self.oldSel][0] = strng buttonsListCtrl.SetStringItem(self.oldSel, 0, strng) Validation() evt.Skip() suffText.Bind(wx.EVT_TEXT, OnSuffText) def OnLabelText(evt): strng = labelText.GetValue() self.remotes[listBoxCtrl.GetSelection()][2][self.oldSel][1] = strng buttonsListCtrl.SetStringItem(self.oldSel, 1, strng) Validation() evt.Skip() labelText.Bind(wx.EVT_TEXT, OnLabelText) def OnSuffChoice(evt): strng = suffChoice.GetStringSelection() self.remotes[listBoxCtrl.GetSelection()][2][self.oldSel][2] = strng buttonsListCtrl.SetStringItem(self.oldSel, 2, strng) duplEvent.Enable(True) Validation() evt.Skip() suffChoice.Bind(wx.EVT_CHOICE, OnSuffChoice) def SelRow(row): if row != self.oldSel: if self.oldSel in range(buttonsListCtrl.GetItemCount()): item = buttonsListCtrl.GetItem(self.oldSel) item.SetTextColour(self.fore) item.SetBackgroundColour(self.back) buttonsListCtrl.SetItem(item) self.oldSel = row if buttonsListCtrl.GetItemBackgroundColour(row) != self.selBack: item = buttonsListCtrl.GetItem(row) item.SetTextColour(self.selFore) item.SetBackgroundColour(self.selBack) buttonsListCtrl.SetItem(item) def OnSuffixSelect(evt): row = evt.GetIndex() buttonsListCtrl.SetItemState(row, 0, wx.LIST_STATE_SELECTED) if row == self.oldSel: evt.Skip() return if not addEvent.IsEnabled() and self.oldSel > -1: old = self.oldSel self.oldSel = row SelRow(old) PlaySound('SystemExclamation', SND_ASYNC) evt.Skip() return EnableCtrls(True) SelRow(row) duplEvent.Enable(True) EnableButtonsRight(True) suffText.ChangeValue(buttonsListCtrl.GetItemText(row)) labelText.ChangeValue(buttonsListCtrl.GetItem(row, 1).GetText()) suffChoice.SetStringSelection( buttonsListCtrl.GetItem(row, 2).GetText()) evt.Skip() buttonsListCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, OnSuffixSelect) def OnBtnExp(evt): ix = listBoxCtrl.GetSelection() name = self.remotes[ix][0] dlg = wx.FileDialog(panel, message=text.save % name, defaultDir=eg.configDir, defaultFile=name, wildcard=text.wildcard, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: self.dataToXml(self.remotes[ix], dlg.GetPath()) dlg.Destroy() evt.Skip() btnExp.Bind(wx.EVT_BUTTON, OnBtnExp) def OnBtnImp(evt): ix = listBoxCtrl.GetSelection() dlg = wx.FileDialog(panel, message=text.choose % self.remotes[ix][0], defaultDir=eg.configDir, defaultFile="", wildcard=text.wildcard, style=wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: filePath = dlg.GetPath() item = self.xmlToData(filePath) dlg.Destroy() else: dlg.Destroy() evt.Skip() return if not item: MessageBox( panel, text.message5 % path.split(dlg.GetPath())[1], text.messBoxTit1, wx.ICON_EXCLAMATION, plugin=self, ) evt.Skip() return #Conflict test: s = None for i in range(len(self.remotes)): rem = self.remotes[i] if item[1] != rem[1] or i == ix: continue for suff in item[2]: for sf in rem[2]: if suff[0] == sf[0] and suff[2] != sf[2]: s = suff[0] n = rem[0] n0 = suff[2] n1 = sf[2] break if s: break if s: break if s: MessageBox( panel, text.message3 % (item[1], s, n0, n, n1), text.messBoxTit2, wx.ICON_EXCLAMATION, plugin=self, ) evt.Skip() return else: for suff in item[2]: if suff[2] not in panel.suffixes: panel.suffixes.append(suff[2]) item[0] = self.remotes[ix][0] self.remotes[ix] = item FillRemoteForm(item) evt.Skip() btnImp.Bind(wx.EVT_BUTTON, OnBtnImp) def OnSuffButton(evt): dlg = SuffixesFrame( parent=panel, plugin=self, ) dlg.Centre() wx.CallAfter(dlg.ShowSuffixesFrame) evt.Skip() suffButton.Bind(wx.EVT_BUTTON, OnSuffButton) def onButtonUp(evt): rem = listBoxCtrl.GetSelection() newSel, suffixes = Move(self.remotes[rem][2], self.oldSel, -1) self.remotes[rem][2] = suffixes FillButtonsList(self.remotes[rem]) SelRow(newSel) buttonsListCtrl.EnsureVisible(self.oldSel) evt.Skip() btnUP.Bind(wx.EVT_BUTTON, onButtonUp) def onButtonDown(evt): rem = listBoxCtrl.GetSelection() newSel, suffixes = Move(self.remotes[rem][2], self.oldSel, 1) self.remotes[rem][2] = suffixes FillButtonsList(self.remotes[rem]) SelRow(newSel) buttonsListCtrl.EnsureVisible(self.oldSel) evt.Skip() btnDOWN.Bind(wx.EVT_BUTTON, onButtonDown) def OnApplyBtn(evt): panel.dialog.buttonRow.applyButton.Enable(False) #evt.Skip() => applyButton work is only fictive !!! panel.dialog.buttonRow.applyButton.Bind(wx.EVT_BUTTON, OnApplyBtn) def OnCloseBox(evt): eg.EventGhostEvent.__init__ = egEventInit evt.Skip() panel.dialog.Bind(wx.EVT_CLOSE, OnCloseBox) panel.dialog.buttonRow.cancelButton.Bind(wx.EVT_BUTTON, OnCloseBox) def onClick(evt=None, init=False): if init: listBoxCtrl.Set([n[0] for n in self.remotes]) if listBoxCtrl.GetCount(): listBoxCtrl.SetSelection(0) if listBoxCtrl.GetCount(): rem = listBoxCtrl.GetSelection() item = self.remotes[rem] FillRemoteForm(self.remotes[rem]) EnableBtns(True) EnableLabel(True) else: item = ["", "", []] labelCtrl.ChangeValue(item[0]) FillRemoteForm(item) listBoxCtrl.SetFocus() if evt: evt.Skip() listBoxCtrl.Bind(wx.EVT_LISTBOX, onClick) onClick(init=True) while panel.Affirmed(): eg.EventGhostEvent.__init__ = egEventInit panel.SetResult(prefText.GetValue(), self.remotes, panel.suffixes)
def plotvars(BB,Wi=None,short=False,Nob=False,bx=bx,mode="save",formatf=["pdf","svg","pgn"][0]): outputs={1:cpy(indict),2:cpy(indict),3:cpy(indict)} axs=(0,-2,-1) hol=[WAR,bs][BB] WV = wid if (Wi is None) else WAR[Wi] ding=0 BS= np.array(hol) if BB==1 else bs[bsvi] if BB==0: WS=np.array(hol) wu=np.unique(WS).shape[0] bu=np.unique(BS).shape[0] BD="{}Weight_{}".format(wu, "no-B_" if No_B else " {}B({})_".format(bu,bsvi)) if BB==0 else "{}Bias_{}W({})_".format(bu,wu,Wi if not(Wi is None) else "wid") if short:#subsample data for bb in hol:#bb are upscaled 5 times #print(bb) #print('B',bs[bsvi],'B') if BB==1: print('W',wid,'W') print('B',bb,'B') #print(wid.shape,bb.shape) d1=vecvari10(inputcols, WV,BB=0, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) d2=vecvari10(inputcols, WV,BB=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) d3=vecvari10(inputcols, WV,BB=0,BS=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)#-vecvari10(inputcols, wid,noB=0, B=bb,square=0,sqrt=0,verbose=0) p1=vecvari1(inputcols, WV, B=bb,BB=0,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) p2=vecvari1(inputcols, WV, B=bb,BB=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) p3=vecvari1(inputcols, WV, B=bb,BB=0,BS=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) elif BB==0: if Nob: bval=None else: bval=bs[bsvi] print('W',bb,'W') print('B',bval,'B') print(bb.shape,bs[9].shape) d1=vecvari10(inputcols, bb,BB=0, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) p1=vecvari1(inputcols, bb,BB=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) d2=vecvari10(inputcols, bb,BB=0,BS=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) p2=vecvari1(inputcols, bb,BB=0, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) d3=vecvari10(inputcols, bb,BB=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) p3=vecvari1(inputcols, bb,BB=0,BS=1, B=bval,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) for iou,out in enumerate([(d1,d2,d3),(p1,p2,p3),(d1-p1,d2-p2,d3-p3)]): if iou==0: ding+=1 iou+=1 #print(iou) #print(out.mean(axs).shape) out1=out[0] out2=out[1] out3=out[2]#out1-out2 [outputs[iou]['1mean'].append(oo) for oo in out1.mean(axs)] [outputs[iou]['1max'].append(oo) for oo in out1.max(axs)] [outputs[iou]['1min'].append(oo) for oo in out1.min(axs)] [outputs[iou]['2mean'].append(oo) for oo in out2.mean(axs)] [outputs[iou]['2max'].append(oo) for oo in out2.max(axs)] [outputs[iou]['2min'].append(oo) for oo in out2.min(axs)] [outputs[iou]['mean'].append(oo) for oo in out3.mean(axs)] [outputs[iou]['max'].append(oo) for oo in out3.max(axs)] [outputs[iou]['min'].append(oo) for oo in out3.min(axs)] else:#do each data point for kl in hol: for bb in kl: bb=np.broadcast_to(bb, kl.shape) #print(bb[:,0]) #print('B',bs[bsvi],'B') if BB==1: print('W',wid,'W') print('B',bb,'B') #print(wid.shape,bb.shape) d1=vecvari10(inputcols, wid,BB=0, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) d2=vecvari10(inputcols, wid,BB=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) d3=vecvari10(inputcols, wid,BB=0,BS=1, B=bb,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v)#-vecvari10(inputcols, wid,noB=0, B=bb,square=0,sqrt=0,verbose=0) p1=vecvari1(inputcols, wid, B=bb,BB=0,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) p2=vecvari1(inputcols, wid, B=bb,BB=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) p3=vecvari1(inputcols, wid, B=bb,BB=0,BS=1,sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) elif BB==0: if Nob: bval=None else: bval=bs[bsvi] print('W',bb,'W') print('B',bval,'B') print(bb.shape,bs[9].shape) print(bb.shape,bs[9].shape) d1=vecvari10(inputcols, bb,BB=0, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) p1=vecvari1(inputcols, bb,BB=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) d2=vecvari10(inputcols, bb,BB=0,BS=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) p2=vecvari1(inputcols, bb,BB=0, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) d3=vecvari10(inputcols, bb,BB=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[0],v3=v3v) p3=vecvari1(inputcols, bb,BB=0,BS=1, B=bs[bsvi],sqrt=sqrtv,verbose=0,mulb=mulbv,mul2=mul2v,sizz=sizz[1],v3=v3v) for iou,out in enumerate([(d1,d2,d3),(p1,p2,p3),(d1-p1,d2-p2,d3-p3)]): if iou==0: ding+=1 iou+=1 #print(iou) #print(out.mean(axs).shape) out1=out[0] out2=out[1] out3=out[2]#out1-out2 outputs[iou]['1mean'].append(out1.mean()) outputs[iou]['1max'].append(out1.max()) outputs[iou]['1min'].append(out1.min()) outputs[iou]['2mean'].append(out2.mean()) outputs[iou]['2max'].append(out2.max()) outputs[iou]['2min'].append(out2.min()) outputs[iou]['mean'].append(out3.mean()) outputs[iou]['max'].append(out3.max()) outputs[iou]['min'].append(out3.min()) #bx=bxx#np.linspace(0, bxx[-1], num=outputs[1]['mean'].__len__(), dtype=np.float32) #print(ding,(np.array(outputs[1]['mean']),np.array(outputs[2]['mean']))) #print([outputs[d]['min'] for d in outputs ]) tree=1#tree plots instead of one ylog=[1,1,0]#set wich plot to have the y axes as a log coloros=["xkcd:racing green","xkcd:bright pink","xkcd:raw umber", "xkcd:bright orange", "xkcd:barney purple","xkcd:light green", "xkcd:piss yellow","xkcd:bright aqua","xkcd:fire engine red",] markers=['+--','*--','x-']#markers for each group of plot mks=[8,6,6]#size of the markers ALPH=0.58#alpha of the plot if tree: #tree plots fig, axs = plt.subplots(3, 1) #fig.set_xscale('log') plt.axis([0,np.amax(bs[-1]),min(outputs[3]['min']),max([max(outputs[d]['max']) for d in outputs ])]) f1=plt.subplot(311) f1y=outputs[1] plt.plot(bx,f1y['1mean'],markers[0],color=coloros[0],markersize=mks[0],alpha=ALPH,) plt.plot(bx,f1y['1max'],markers[0],color=coloros[1],markersize=mks[0],alpha=ALPH,) plt.plot(bx,f1y['1min'],markers[0],color=coloros[2],markersize=mks[0],alpha=ALPH,) plt.plot(bx,f1y['2mean'],markers[1],color=coloros[3],markersize=mks[1],alpha=ALPH,) plt.plot(bx,f1y['2max'],markers[1],color=coloros[4],markersize=mks[1],alpha=ALPH,) plt.plot(bx,f1y['2min'],markers[1],color=coloros[5],markersize=mks[1],alpha=ALPH,) plt.plot(bx,f1y['mean'],markers[2],color=coloros[6],markersize=mks[2],alpha=ALPH,) plt.plot(bx,f1y['max'],markers[2],color=coloros[7],markersize=mks[2],alpha=ALPH,) plt.plot(bx,f1y['min'],markers[2],color=coloros[8],markersize=mks[2],alpha=ALPH,) plt.setp(f1.set_xscale('log')) plt.setp(f1.set_title('{},vecvari10,V3:{},sizz:{},mulb:{},mul2v:{}'.format(BD,v3v,sizz,mulbv,mul2v))) if ylog[0]: plt.setp(f1.set_yscale('log')) f2=plt.subplot(312,sharex=f1)#,sharey=f1) f2y=outputs[2] plt.plot(bx,f2y['1mean'],markers[0],color=coloros[0],markersize=mks[0],alpha=ALPH,) plt.plot( bx,f2y['1max'],markers[0],color=coloros[1],markersize=mks[0],alpha=ALPH,) plt.plot( bx,f2y['1min'],markers[0],color=coloros[2],markersize=mks[0],alpha=ALPH,) plt.plot(bx,f2y['2mean'],markers[1],color=coloros[3],markersize=mks[1],alpha=ALPH,) plt.plot(bx,f2y['2max'],markers[1],color=coloros[4],markersize=mks[1],alpha=ALPH,) plt.plot( bx,f2y['2min'],markers[1],color=coloros[5],markersize=mks[1],alpha=ALPH,) plt.plot(bx,f2y['mean'],markers[2],color=coloros[6],markersize=mks[2],alpha=ALPH,) plt.plot(bx,f2y['max'],markers[2],color=coloros[7],markersize=mks[2],alpha=ALPH,) plt.plot(bx,f2y['min'],markers[2],color=coloros[8],markersize=mks[2],alpha=ALPH,) plt.setp(f2.set_xscale('log')) plt.setp(f2.set_title('{},vecvari1,V3:{},sizz:{},mulb:{},mul2v:{}'.format(BD,v3v,sizz,mulbv,mul2v))) if ylog[1]: plt.setp(f2.set_yscale('log')) f3=plt.subplot(313,sharex=f1)#,sharey=f1) f3y=outputs[3] plt.plot(bx,f3y['1mean'],markers[0],color=coloros[0],markersize=mks[0],alpha=ALPH,) plt.plot( bx,f3y['1max'],markers[0],color=coloros[1],markersize=mks[0],alpha=ALPH,) plt.plot( bx,f3y['1min'],markers[0],color=coloros[2],markersize=mks[0],alpha=ALPH,) plt.plot(bx,f3y['2mean'],markers[1],color=coloros[3],markersize=mks[1],alpha=ALPH,) plt.plot(bx,f3y['2max'],markers[1],color=coloros[4],markersize=mks[1],alpha=ALPH,) plt.plot( bx,f3y['2min'],markers[1],color=coloros[5],markersize=mks[1],alpha=ALPH,) plt.plot(bx,f3y['mean'],markers[2],color=coloros[6],markersize=mks[2],alpha=ALPH,) plt.plot(bx,f3y['max'],markers[2],color=coloros[7],markersize=mks[2],alpha=ALPH,) plt.plot(bx,f3y['min'],markers[2],color=coloros[8],markersize=mks[2],alpha=ALPH,) plt.setp(f3.set_xscale('log')) plt.setp(f3.set_title('{},vecvari10-vecvari1,V3:{},sizz:{},mulb:{},mul2v:{}'.format(BD,v3v,sizz,mulbv,mul2v))) if ylog[2]: plt.setp(f3.set_yscale('log')) else: #all in one plot fig=plt.figure(1, figsize=(10,10)) #plt.yscale('log') #plt.xscale('log') plt.axis([0,max(bx),min(outputs[3]['min']),max([max(outputs[d]['max']) for d in outputs ])]) #plt.Axes.set_yscale(ax,'log') #plt.Axes.set_xscale(ax,'log') fg=plt.plot(bx,outputs[1]['mean'],'gs-',bx,outputs[1]['max'],'bs-',bx,outputs[1]['min'],'rs-', bx,outputs[2]['mean'],'go-',bx,outputs[2]['max'],'bo-',bx,outputs[2]['min'],'ro-', bx,outputs[3]['mean'],'yH-',bx,outputs[3]['max'],'mH-',bx,outputs[3]['min'],'cH-',markersize=6) #print(fg) #plt.setp(fg,plt.yscale('log')) #plt.setp(fg,plt.xscale('log')) for I in range(3): I+=1 print(outputs[I]['mean'][0],outputs[I]['mean'][9*4],outputs[I]['mean'][-1]) print(outputs[I]['max'][0],outputs[I]['max'][9*4],outputs[I]['max'][-1]) print(outputs[I]['min'][0],outputs[I]['min'][9*4],outputs[I]['min'][-1]) #plt.ion() plt.tight_layout(pad=1, h_pad=0.35, w_pad=0.35,rect=(0,0.07,1,1)) plt.legend(['BB:0,BS:0, mean','BB:0,BS:0, max','BB:0,BS:0, min', 'BB:1,BS:0, mean','BB:1,BS:0, max','BB:1,BS:0, min', 'BB:0,BS:1, mean','BB:0,BS:1, max','BB:0,BS:1, min'],markerfirst=True, bbox_to_anchor=(0,0,1,0), loc=2, ncol=3, mode="expand", borderaxespad=0.5) #https://matplotlib.org/users/legend_guide.html if mode=="save": outf=".//varplots//{}siz{}_ml{}_ml2{}_v3{}_rt{}.{}".format(BD,sizz,mulbv,mul2v,v3v,sqrtv,formatf) print(outf) plt.savefig(outf,format=formatf) #exit() else: plt.show()
def Configure( self, Prefix = "Remote", remotes = [], suffixes = None ): egEventInit = eg.EventGhostEvent.__init__ text = self.text self.remotes = cpy(remotes) del remotes panel = eg.ConfigPanel(self, resizable = True) if not suffixes: from eg.Classes.IrDecoder.Rc6 import MCE_REMOTE as MCE suffixes = list(MCE.itervalues()) panel.suffixes = suffixes def TestUse(val): rem = None for item in self.remotes: for button in item[2]: if button[2]==val: rem = item[0] break if rem: break return rem panel.testUse = TestUse leftSizer = wx.BoxSizer(wx.VERTICAL) box1 = wx.StaticBox(panel, -1, "") eventSizer = wx.StaticBoxSizer(box1, wx.VERTICAL) prefLabel = wx.StaticText(panel, -1, text.prefix) prefText = wx.TextCtrl(panel, -1, Prefix) prefLabel2 = wx.StaticText(panel, -1, text.nativePrefix) prefText2 = wx.TextCtrl(panel, -1, "") buttonsListCtrl = wx.ListCtrl(panel, -1, style=wx.LC_REPORT | wx.VSCROLL|wx.LC_VRULES |wx.LC_HRULES |wx.LC_SINGLE_SEL) self.back = buttonsListCtrl.GetBackgroundColour() self.fore = buttonsListCtrl.GetForegroundColour() self.selBack = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT) self.selFore = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT) suffText = wx.TextCtrl(panel, -1, "", style = wx.TE_READONLY ) suffText.SetToolTipString(text.suffToolTip) labelText = wx.TextCtrl(panel, -1, "") suffChoice = wx.Choice(panel, -1, choices = panel.suffixes) def UpdateChoices(): suffChoice.Clear() suffChoice.AppendItems(panel.suffixes) panel.updateChoices = UpdateChoices evtPrefSizer = wx.BoxSizer(wx.HORIZONTAL) evtPrefSizer.Add(prefLabel, 0, wx.TOP, 3) evtPrefSizer.Add(prefText, 1, wx.EXPAND|wx.LEFT, 5) eventSizer.Add(evtPrefSizer, 0, wx.EXPAND|wx.TOP, 4) suffButton = wx.Button(panel, -1, text.suffixes) eventSizer.Add(suffButton, 0, wx.EXPAND|wx.TOP, 8) remListSizer = wx.GridBagSizer(1, 10) box2 = wx.StaticBox(panel, -1, "") rightStatSizer = wx.StaticBoxSizer(box2, wx.VERTICAL) rightSizer = wx.GridBagSizer(8, 1) rightStatSizer.Add(rightSizer, 1, wx.EXPAND) remListLabel=wx.StaticText(panel, -1, text.menuPreview) listBoxCtrl = wx.ListBox( panel,-1, style = wx.LB_SINGLE | wx.LB_NEEDED_SB ) labelLbl = wx.StaticText(panel, -1, text.label) labelCtrl = wx.TextCtrl(panel, -1, '') #Buttons 'Delete', 'Import', 'Export' and 'Insert new' lenLst = [panel.GetTextExtent(item)[0] for item in text.buttons] btn = wx.Button(panel,-1,text.buttons[lenLst.index(max(lenLst))]) sz = btn.GetSize() btn.Destroy() btnDEL = wx.Button(panel, -1, text.buttons[0], size = sz) btnApp = wx.Button(panel, -1, text.buttons[1], size = sz) btnImp = wx.Button(panel, -1, text.buttons[2], size = sz) btnExp = wx.Button(panel, -1, text.buttons[3], size = sz) def EnableBtns(enable): btnDEL.Enable(enable) btnImp.Enable(enable) btnExp.Enable(enable) def EnableLabel(enable): labelCtrl.Enable(enable) labelLbl.Enable(enable) EnableBtns(False) EnableLabel(False) lenLst = [panel.GetTextExtent(item)[0] for item in text.buttons2] btn = wx.Button(panel,-1,text.buttons2[lenLst.index(max(lenLst))]) sz = btn.GetSize() btn.Destroy() delEvent = wx.Button(panel, -1, text.buttons2[0], size = sz) clearEvents = wx.Button(panel, -1, text.buttons2[1], size = sz) addEvent = wx.Button(panel, -1, text.buttons2[2], size = sz) duplEvent = wx.Button(panel, -1, text.buttons2[3], size = sz) #Button UP bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_UP, wx.ART_OTHER, (16, 16)) btnUP = wx.BitmapButton(panel, -1, bmp) btnUP.Enable(False) #Button DOWN bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_DOWN, wx.ART_OTHER, (16, 16)) btnDOWN = wx.BitmapButton(panel, -1, bmp) btnDOWN.Enable(False) leftSizer.Add(eventSizer, 0, wx.EXPAND) leftSizer.Add(remListSizer,1,wx.EXPAND|wx.TOP, 15) leftSizer.Add((1,4)) mainSizer = wx.BoxSizer(wx.HORIZONTAL) mainSizer.Add(leftSizer, 0, wx.EXPAND) mainSizer.Add(rightStatSizer, 1, wx.LEFT | wx.EXPAND, 24) panel.sizer.Add(mainSizer, 1, wx.EXPAND) def EnableCtrls(enable): suffText.Enable(enable) labelText.Enable(enable) suffChoice.Enable(enable) if enable: eg.EventGhostEvent.__init__ = EventRemap else: eg.EventGhostEvent.__init__ = egEventInit def ResetCtrls(): suffText.ChangeValue("") labelText.ChangeValue("") suffChoice.SetSelection(-1) def FillButtonsList(item): buttonsListCtrl.DeleteAllItems() for row in range(len(item[2])): buttonsListCtrl.InsertStringItem(row, item[2][row][0]) buttonsListCtrl.SetStringItem(row, 1, item[2][row][1]) buttonsListCtrl.SetStringItem(row, 2, item[2][row][2]) def FillRemoteForm(item): self.oldSel = -1 prefText2.SetValue(item[1]) enable = item[1] != "" addEvent.Enable(enable) ResetCtrls() FillButtonsList(item) clearEvents.Enable(len(item[2]) > 0) EnableButtonsRight(False) duplEvent.Enable(False) EnableCtrls(False) evtPrefSizer2 = wx.BoxSizer(wx.HORIZONTAL) evtPrefSizer2.Add((-1, 1), 1, wx.EXPAND) evtPrefSizer2.Add(prefLabel2, 0, wx.TOP, 3) evtPrefSizer2.Add(prefText2, 0, wx.LEFT, 5) w = 0 for i, colLabel in enumerate(text.header): buttonsListCtrl.InsertColumn(i, colLabel) buttonsListCtrl.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER) w += buttonsListCtrl.GetColumnWidth(i) buttonsListCtrl.SetSize((w+SYS_VSCROLL_X+buttonsListCtrl.GetWindowBorderSize()[0], -1)) w0 = buttonsListCtrl.GetColumnWidth(0) w1 = buttonsListCtrl.GetColumnWidth(1) w2 = buttonsListCtrl.GetColumnWidth(2) suffText.SetMinSize((w0-1, -1)) labelText.SetMinSize((w1-1, -1)) suffChoice.SetMinSize((w2-1, -1)) rightSizer.Add(evtPrefSizer2,(0,0), (1,4),flag = wx.EXPAND|wx.TOP,border = 4) rightSizer.Add(buttonsListCtrl,(1,0),(5,4),flag = wx.EXPAND) rightSizer.Add(delEvent,(1,4), flag= wx.TOP|wx.ALIGN_RIGHT, border = 24) rightSizer.Add(clearEvents,(2,4), flag = wx.ALIGN_RIGHT) brdr = 8 + SYS_VSCROLL_X + buttonsListCtrl.GetWindowBorderSize()[0] rightSizer.Add(btnUP,(3,4), flag = wx.LEFT, border = brdr) rightSizer.Add(btnDOWN,(4,4), flag = wx.LEFT, border = brdr) rightSizer.Add(duplEvent,(5,4), flag = wx.ALIGN_BOTTOM|wx.ALIGN_RIGHT) rightSizer.Add(suffText,(6,0),flag = wx.EXPAND|wx.LEFT, border = 1) rightSizer.Add(labelText,(6,1),flag = wx.EXPAND|wx.LEFT, border = 1) rightSizer.Add(suffChoice,(6,2),flag = wx.EXPAND|wx.LEFT, border = 1) rightSizer.Add(addEvent,(6,4), flag = wx.LEFT, border = brdr) rightSizer.AddGrowableRow(5) rightSizer.AddGrowableCol(0,w0) rightSizer.AddGrowableCol(1,w1) rightSizer.AddGrowableCol(2,w2) remListSizer.Add(remListLabel,(0,0)) remListSizer.Add(listBoxCtrl,(1,0),(4,1), flag = wx.EXPAND) remListSizer.Add(labelLbl,(5,0), flag = wx.TOP, border = 8) remListSizer.Add(labelCtrl,(6,0), flag = wx.EXPAND) remListSizer.Add(btnDEL,(1,1)) remListSizer.Add(btnImp,(2,1), flag = wx.TOP, border = 8) remListSizer.Add(btnExp,(3,1), flag = wx.TOP, border = 8) remListSizer.Add((-1, 1),(4,1)) remListSizer.Add(btnApp,(6,1)) remListSizer.AddGrowableRow(4) panel.sizer.Layout() def EnableLeftSide(enable): EnableBtns(enable) EnableLabel(enable) btnApp.Enable(enable) remListLabel.Enable(enable) listBoxCtrl.Enable(enable) labelLbl.Enable(enable) labelCtrl.Enable(enable) def SetWidth(): w0 = suffText.GetSize()[0]+1 w1 = labelText.GetSize()[0]+1 w2 = suffChoice.GetSize()[0]+1 buttonsListCtrl.SetSize((w0+w1+w2+SYS_VSCROLL_X + buttonsListCtrl.GetWindowBorderSize()[0], -1)) buttonsListCtrl.SetColumnWidth(0, w0) buttonsListCtrl.SetColumnWidth(1, w1) buttonsListCtrl.SetColumnWidth(2, w2) def OnSize(event): wx.CallAfter(SetWidth) panel.Update() event.Skip() panel.Bind(wx.EVT_SIZE, OnSize) def OnDelEvent(evt): rem = listBoxCtrl.GetSelection() self.remotes[rem][2].pop(self.oldSel) buttonsListCtrl.DeleteItem(self.oldSel) lngth = len(self.remotes[rem][2]) prefText2.Enable(True) if lngth == 0: self.oldSel = -1 OnPrefText2() ResetCtrls() evt.Skip() return elif self.oldSel == lngth: row = lngth - 1 else: row = self.oldSel self.oldSel = -1 SelRow(row) suffText.ChangeValue(buttonsListCtrl.GetItemText(row)) labelText.ChangeValue(buttonsListCtrl.GetItem(row, 1).GetText()) suffChoice.SetStringSelection(buttonsListCtrl.GetItem(row, 2).GetText()) OnPrefText2() Validation() evt.Skip() delEvent.Bind(wx.EVT_BUTTON, OnDelEvent) def OnClearEvents(evt): rem = listBoxCtrl.GetSelection() self.remotes[rem][2] = [] buttonsListCtrl.DeleteAllItems() self.oldSel = -1 EnableLeftSide(True) prefText2.Enable(True) OnPrefText2() ResetCtrls() evt.Skip() clearEvents.Bind(wx.EVT_BUTTON, OnClearEvents) def onButtonDelete(evt): sel = listBoxCtrl.GetSelection() listBoxCtrl.Delete(sel) self.remotes.pop(sel) lngth = len(self.remotes) if lngth > 0: if sel == lngth: sel = lngth - 1 listBoxCtrl.SetSelection(sel) onClick() else: labelCtrl.ChangeValue("") EnableBtns(False) item = ["", "", []] FillRemoteForm(item) evt.Skip() btnDEL.Bind(wx.EVT_BUTTON, onButtonDelete) def OnLabelChange(evt): flag = False sel = listBoxCtrl.GetSelection() label = labelCtrl.GetValue() self.remotes[sel][0] = label listBoxCtrl.SetString(sel, label) enable = label != "" if enable: if [n[0] for n in self.remotes].count(label) == 1: flag = True EnableBtns(enable) panel.dialog.buttonRow.okButton.Enable(flag) btnApp.Enable(flag) item = self.remotes[sel] prefText2.Enable(flag) OnPrefText2() if not flag: addEvent.Enable(False) evt.Skip() labelCtrl.Bind(wx.EVT_TEXT, OnLabelChange) def OnButtonAppend(evt): EnableLabel(True) item = ["","",[]] self.remotes.append(item) listBoxCtrl.Append("") listBoxCtrl.SetSelection(listBoxCtrl.GetCount()-1) prefText2.ChangeValue("") labelCtrl.SetValue("") FillRemoteForm(item) labelCtrl.SetFocus() addEvent.Enable(False) evt.Skip() btnApp.Bind(wx.EVT_BUTTON, OnButtonAppend) def EnableButtonsRight(enable): delEvent.Enable(enable) if enable: rem = listBoxCtrl.GetSelection() if len(self.remotes[rem][2]) < 2: enable = False btnUP.Enable(enable) btnDOWN.Enable(enable) def OnPrefText2(evt = None): global prefix prefix = prefText2.GetValue() rem = listBoxCtrl.GetSelection() if rem > -1: self.remotes[rem][1] = prefix s = None if prefix != "": #Conflict test: for i in range(len(self.remotes)): rmt = self.remotes[i] if prefix != rmt[1] or i == rem: continue for suff in self.remotes[rem][2]: for sf in rmt[2]: if suff[0] == sf[0] and suff[2] != sf[2]: s = suff[0] n = rmt[0] n0 = suff[2] n1 = sf[2] break if s: break if s: break if s: MessageBox( panel, text.message4 % (prefix, prefix, s, n0, n, n1), text.messBoxTit2, wx.ICON_EXCLAMATION, plugin = self, ) EnableLeftSide(False) panel.dialog.buttonRow.okButton.Enable(False) else: EnableLeftSide(True) panel.dialog.buttonRow.okButton.Enable(True) enable = prefix != "" and not s buttonsListCtrl.Enable(enable) if not enable or len(self.remotes[rem][2]) == 0: addEvent.Enable(False) duplEvent.Enable(False) EnableButtonsRight(False) clearEvents.Enable(False) EnableCtrls(False) elif enable and len(self.remotes[rem][2]) > 0: clearEvents.Enable(True) if self.oldSel != -1: EnableButtonsRight(True) duplEvent.Enable(True) EnableCtrls(True) else: EnableButtonsRight(False) duplEvent.Enable(False) EnableCtrls(False) if enable and len(self.remotes[rem][2]) == 0: addEvent.Enable(True) if evt: evt.Skip() prefText2.Bind(wx.EVT_TEXT, OnPrefText2) def Validation(): flag = True strng = suffText.GetValue() prfx = prefText2.GetValue() rem = listBoxCtrl.GetSelection() newSuff = suffChoice.GetStringSelection() name = None sfx = None for i in range(len(self.remotes)): item = self.remotes[i] if i == rem or item[1] != prfx: continue for suff in item[2]: if suff[0] == strng and suff[2] != newSuff: name = item[0] sfx = suff[2] break if name: break if name: MessageBox( panel, text.message2 % (prfx,strng,newSuff,sfx,name), text.messBoxTit2, wx.ICON_EXCLAMATION, plugin = self, ) flag = False if [item[0] for item in self.remotes[rem][2]].count(strng) > 1: suffText.SetValue("") MessageBox( panel, text.message6 % (strng), text.messBoxTit3, wx.ICON_EXCLAMATION, plugin = self, time = 7 ) if strng == "": flag = False if labelText.GetValue().strip() == "": flag = False if suffChoice.GetSelection() == -1: flag = False addEvent.Enable(flag) duplEvent.Enable(flag) prefText2.Enable(flag) EnableLeftSide(flag) panel.dialog.buttonRow.okButton.Enable(flag) def EventRemap(self, suffix = "", payload = None, prefix = "Main", source = eg): SetSuffix(prefix, suffix) self.string = "%s.%s" % (prefix, suffix) self.prefix = prefix self.suffix = suffix self.payload = payload self.source = source self.time = clock() self.isEnded = False self.shouldEnd = Event() self.upFuncList = [] def SetSuffix(eventPrefix, eventSuffix): if prefix == eventPrefix: suffText.SetValue(eventSuffix) def OnButtonAddEvent(evt): if self.oldSel == -1: self.oldSel = buttonsListCtrl.GetItemCount() - 1 row = self.oldSel + 1 self.remotes[listBoxCtrl.GetSelection()][2].insert(row,["", "", ""]) buttonsListCtrl.InsertStringItem(row, "") buttonsListCtrl.SetStringItem(row, 1, "") buttonsListCtrl.SetStringItem(row, 2, "") buttonsListCtrl.EnsureVisible(row) SelRow(row) EnableCtrls(True) addEvent.Enable(False) duplEvent.Enable(False) clearEvents.Enable(True) prefText2.Enable(False) EnableLeftSide(False) panel.dialog.buttonRow.okButton.Enable(False) ResetCtrls() EnableButtonsRight(True) evt.Skip() addEvent.Bind(wx.EVT_BUTTON, OnButtonAddEvent) def OnButtonDuplEvent(evt): addEvent.Enable(False) duplEvent.Enable(False) panel.dialog.buttonRow.okButton.Enable(False) suffText.ChangeValue("") strng1 = labelText.GetValue() strng2 = suffChoice.GetStringSelection() row = self.oldSel + 1 self.remotes[listBoxCtrl.GetSelection()][2].insert(row, ["", strng1, strng2]) buttonsListCtrl.InsertStringItem(row, "") buttonsListCtrl.SetStringItem(row, 1, strng1) buttonsListCtrl.SetStringItem(row, 2, strng2) SelRow(row) buttonsListCtrl.EnsureVisible(row) evt.Skip() duplEvent.Bind(wx.EVT_BUTTON, OnButtonDuplEvent) def OnSuffText(evt): strng = evt.GetString() self.remotes[listBoxCtrl.GetSelection()][2][self.oldSel][0] = strng buttonsListCtrl.SetStringItem(self.oldSel, 0, strng) Validation() evt.Skip() suffText.Bind(wx.EVT_TEXT, OnSuffText) def OnLabelText(evt): strng = labelText.GetValue() self.remotes[listBoxCtrl.GetSelection()][2][self.oldSel][1] = strng buttonsListCtrl.SetStringItem(self.oldSel, 1, strng) Validation() evt.Skip() labelText.Bind(wx.EVT_TEXT, OnLabelText) def OnSuffChoice(evt): strng = suffChoice.GetStringSelection() self.remotes[listBoxCtrl.GetSelection()][2][self.oldSel][2] = strng buttonsListCtrl.SetStringItem(self.oldSel, 2, strng) duplEvent.Enable(True) Validation() evt.Skip() suffChoice.Bind(wx.EVT_CHOICE, OnSuffChoice) def SelRow(row): if row != self.oldSel: if self.oldSel in range(buttonsListCtrl.GetItemCount()): item = buttonsListCtrl.GetItem(self.oldSel) item.SetTextColour(self.fore) item.SetBackgroundColour(self.back) buttonsListCtrl.SetItem(item) self.oldSel = row if buttonsListCtrl.GetItemBackgroundColour(row) != self.selBack: item = buttonsListCtrl.GetItem(row) item.SetTextColour(self.selFore) item.SetBackgroundColour(self.selBack) buttonsListCtrl.SetItem(item) def OnSuffixSelect(evt): row = evt.GetIndex() buttonsListCtrl.SetItemState(row, 0, wx.LIST_STATE_SELECTED) if row == self.oldSel: evt.Skip() return if not addEvent.IsEnabled() and self.oldSel > -1: old = self.oldSel self.oldSel = row SelRow(old) PlaySound('SystemExclamation', SND_ASYNC) evt.Skip() return EnableCtrls(True) SelRow(row) duplEvent.Enable(True) EnableButtonsRight(True) suffText.ChangeValue(buttonsListCtrl.GetItemText(row)) labelText.ChangeValue(buttonsListCtrl.GetItem(row, 1).GetText()) suffChoice.SetStringSelection(buttonsListCtrl.GetItem(row, 2).GetText()) evt.Skip() buttonsListCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, OnSuffixSelect) def OnBtnExp(evt): ix = listBoxCtrl.GetSelection() name = self.remotes[ix][0] dlg = wx.FileDialog( panel, message = text.save % name, defaultDir = eg.configDir, defaultFile = name, wildcard = text.wildcard, style=wx.SAVE ) if dlg.ShowModal() == wx.ID_OK: self.dataToXml(self.remotes[ix], dlg.GetPath()) dlg.Destroy() evt.Skip() btnExp.Bind(wx.EVT_BUTTON, OnBtnExp) def OnBtnImp(evt): ix = listBoxCtrl.GetSelection() dlg = wx.FileDialog( panel, message = text.choose % self.remotes[ix][0], defaultDir = eg.configDir, defaultFile = "", wildcard = text.wildcard, style = wx.OPEN | wx.CHANGE_DIR ) if dlg.ShowModal() == wx.ID_OK: filePath = dlg.GetPath() item = self.xmlToData(filePath) dlg.Destroy() else: dlg.Destroy() evt.Skip() return if not item: MessageBox( panel, text.message5 % path.split(dlg.GetPath())[1], text.messBoxTit1, wx.ICON_EXCLAMATION, plugin = self, ) evt.Skip() return #Conflict test: s = None for i in range(len(self.remotes)): rem = self.remotes[i] if item[1] != rem[1] or i == ix: continue for suff in item[2]: for sf in rem[2]: if suff[0] == sf[0] and suff[2] != sf[2]: s = suff[0] n = rem[0] n0 = suff[2] n1 = sf[2] break if s: break if s: break if s: MessageBox( panel, text.message3 % (item[1], s, n0, n, n1), text.messBoxTit2, wx.ICON_EXCLAMATION, plugin = self, ) evt.Skip() return else: for suff in item[2]: if suff[2] not in panel.suffixes: panel.suffixes.append(suff[2]) item[0] = self.remotes[ix][0] self.remotes[ix] = item FillRemoteForm(item) evt.Skip() btnImp.Bind(wx.EVT_BUTTON, OnBtnImp) def OnSuffButton(evt): dlg = SuffixesFrame( parent = panel, plugin = self, ) dlg.Centre() wx.CallAfter(dlg.ShowSuffixesFrame) evt.Skip() suffButton.Bind(wx.EVT_BUTTON, OnSuffButton) def onButtonUp(evt): rem = listBoxCtrl.GetSelection() newSel, suffixes = Move(self.remotes[rem][2], self.oldSel, -1) self.remotes[rem][2] = suffixes FillButtonsList(self.remotes[rem]) SelRow(newSel) buttonsListCtrl.EnsureVisible(self.oldSel) evt.Skip() btnUP.Bind(wx.EVT_BUTTON, onButtonUp) def onButtonDown(evt): rem = listBoxCtrl.GetSelection() newSel, suffixes = Move(self.remotes[rem][2], self.oldSel, 1) self.remotes[rem][2] = suffixes FillButtonsList(self.remotes[rem]) SelRow(newSel) buttonsListCtrl.EnsureVisible(self.oldSel) evt.Skip() btnDOWN.Bind(wx.EVT_BUTTON, onButtonDown) def OnApplyBtn(evt): panel.dialog.buttonRow.applyButton.Enable(False) #evt.Skip() => applyButton work is only fictive !!! panel.dialog.buttonRow.applyButton.Bind(wx.EVT_BUTTON, OnApplyBtn) def OnCloseBox(evt): eg.EventGhostEvent.__init__ = egEventInit evt.Skip() panel.dialog.Bind(wx.EVT_CLOSE, OnCloseBox) panel.dialog.buttonRow.cancelButton.Bind(wx.EVT_BUTTON, OnCloseBox) def onClick(evt = None, init = False): if init: listBoxCtrl.Set([n[0] for n in self.remotes]) if listBoxCtrl.GetCount(): listBoxCtrl.SetSelection(0) if listBoxCtrl.GetCount(): rem = listBoxCtrl.GetSelection() item = self.remotes[rem] FillRemoteForm(self.remotes[rem]) EnableBtns(True) EnableLabel(True) else: item = ["", "", []] labelCtrl.ChangeValue(item[0]) FillRemoteForm(item) listBoxCtrl.SetFocus() if evt: evt.Skip() listBoxCtrl.Bind(wx.EVT_LISTBOX, onClick) onClick(init = True) while panel.Affirmed(): eg.EventGhostEvent.__init__ = egEventInit panel.SetResult(prefText.GetValue(), self.remotes, panel.suffixes)
def Configure(self, userchars=[]): panel = eg.ConfigPanel(self) panel.GetParent().GetParent().SetIcon(self.info.icon.GetWxIcon()) self.panel = panel self.data = cpy(userchars) if self.data == []: self.data = [cpy(EMPTY_CHAR)] text = self.text jpg_0 = b64decode(SQUARE_0) stream_0 = StringIO(jpg_0) jpg_1 = b64decode(SQUARE_1) stream_1 = StringIO(jpg_1) self.bitmaps = (wx.BitmapFromImage(wx.ImageFromStream(stream_0)), wx.BitmapFromImage(wx.ImageFromStream(stream_1))) self.ids = {} def onClick(evt): id = evt.GetId() bm = wx.FindWindowById(id) oldVal = bm.GetValue() row, bit = self.ids[id] newVal = int(not oldVal) bm.SetBitmapExt(self.bitmaps[newVal], newVal) wx.CallAfter(validation, True) evt.Skip() patternSizer = wx.GridBagSizer(-2, -2) for r in range(8): for c in range(4, -1, -1): id = wx.NewId() self.ids[id] = (r, c) bitmap = ExtStaticBitmap(panel, id, self.bitmaps[0], (26, 26)) bitmap.SetValue(0) patternSizer.Add(bitmap, (r, 4 - c)) bitmap.Bind(wx.EVT_LEFT_DOWN, onClick) leftSizer = wx.BoxSizer(wx.VERTICAL) rightSizer = wx.BoxSizer(wx.VERTICAL) leftSizer = wx.GridBagSizer(1, 3) previewLbl = wx.StaticText(panel, -1, text.userCharList) charListCtrl = MyListCtrl(panel, -1, size=wx.Size(40, -1), style=wx.LC_SINGLE_SEL | wx.LC_NO_HEADER | wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES) #Button UP bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_UP, wx.ART_OTHER, (16, 16)) btnUP = wx.BitmapButton(panel, -1, bmp) btnUP.Enable(False) #Button DOWN bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_DOWN, wx.ART_OTHER, (16, 16)) btnDOWN = wx.BitmapButton(panel, -1, bmp) btnDOWN.Enable(False) #Buttons 'Delete' and 'Insert new' lenLst = [panel.GetTextExtent(item)[0] for item in text.buttons] dummBttn = wx.Button(panel, -1, text.buttons[(lenLst).index(max(lenLst))]) sz = dummBttn.GetSize() dummBttn.Destroy() btnDEL = wx.Button(panel, -1, text.buttons[0], size=sz) btnApp = wx.Button(panel, -1, text.buttons[1], size=sz) btnIMP = wx.Button(panel, -1, text.buttons[2], size=sz) btnEXP = wx.Button(panel, -1, text.buttons[3], size=sz) btnDEL.Enable(False) btnApp.Enable(False) labelLbl = wx.StaticText(panel, -1, text.userCharLabel) userCharLabelCtrl = wx.TextCtrl( panel, -1, '', size=wx.Size(40, -1), ) leftSizer.Add(previewLbl, (0, 0), flag=wx.TOP, border=-2) leftSizer.Add(charListCtrl, (1, 0), (6, 1), flag=wx.TOP | wx.EXPAND) leftSizer.Add(btnUP, (1, 1)) leftSizer.Add(btnDOWN, (2, 1), flag=wx.TOP, border=2) leftSizer.Add(btnDEL, (3, 1), flag=wx.TOP, border=2) leftSizer.AddGrowableRow(4, 1) leftSizer.Add((-1, 20), (4, 1), flag=wx.EXPAND) leftSizer.Add(btnIMP, (5, 1), flag=wx.BOTTOM, border=2) leftSizer.Add(btnEXP, (6, 1)) leftSizer.Add(labelLbl, (7, 0), flag=wx.TOP, border=6) leftSizer.Add(userCharLabelCtrl, (8, 0), flag=wx.EXPAND) leftSizer.Add(btnApp, (8, 1), flag=ACV) topSizer = wx.BoxSizer(wx.HORIZONTAL) topSizer.Add(leftSizer, 1, wx.EXPAND) topSizer.Add((-1, -1), 0, wx.LEFT | wx.RIGHT | wx.EXPAND, 10) topSizer.Add(rightSizer, 0, wx.ALIGN_RIGHT) replLbl = wx.StaticText(panel, -1, text.replLabel) replCtrl = wx.TextCtrl( panel, -1, '', size=wx.Size(24, -1), ) font = wx.Font(15, wx.MODERN, wx.NORMAL, wx.BOLD) replCtrl.SetFont(font) userCharLabelCtrl.SetFont(font) charListCtrl.SetFont(font) replSizer = wx.BoxSizer(wx.HORIZONTAL) replSizer.Add(replLbl, 0, ACV) replSizer.Add((-1, -1), 1, wx.EXPAND) replSizer.Add(replCtrl, 0, wx.ALIGN_RIGHT) rightSizer.Add(patternSizer, 0, wx.ALIGN_RIGHT) rightSizer.Add(replSizer, 0, wx.TOP | wx.ALIGN_LEFT | wx.EXPAND, 5) btn0 = wx.Button(panel.dialog, -1, text.burn) panel.sizer.Add(topSizer, 1, wx.EXPAND | wx.ALL, 5) def GetPattern(): val = [0, 0, 0, 0, 0, 0, 0, 0] for id in self.ids: bm = wx.FindWindowById(id) row, bit = self.ids[id] val[row] += bm.GetValue() * 2**bit return val def SetPattern(pttrn): for id in self.ids: bm = wx.FindWindowById(id) row, bit = self.ids[id] val = int(pttrn[row] & 2**bit > 0) bm.SetBitmapExt(self.bitmaps[val], val) def ResetPattern(): SetPattern([0, 0, 0, 0, 0, 0, 0, 0]) def FillData(item): userCharLabelCtrl.ChangeValue(item[0]) replCtrl.ChangeValue(item[1]) SetPattern(item[2]) def Fill_ListCtrl(): charListCtrl.DeleteAllItems() for i, chr in enumerate(self.data): charListCtrl.InsertStringItem(i, chr[0]) def SelRow(row): charListCtrl.SelRow(row) self.oldSel = row def Init_panel(): FillData(self.data[0]) Fill_ListCtrl() SelRow(0) btnUP.Enable(True) btnDOWN.Enable(True) btnDEL.Enable(True) btnApp.Enable(True) if len(self.data): Init_panel() def validation(patt=False): flag = True label = userCharLabelCtrl.GetValue() if len(label) != 1: flag = False else: if len([i[0] for i in self.data if i[0] == label]) != 1: flag = False repl = replCtrl.GetValue() if len(repl) != 1 or len(repr(repl)) > 4: flag = False pttrn = GetPattern() if pttrn == [0, 0, 0, 0, 0, 0, 0, 0]: flag = False elif patt: self.data[self.oldSel][2] = pttrn self.panel.dialog.buttonRow.okButton.Enable(flag) btnApp.Enable(flag) def OnLabelText(evt): strng = userCharLabelCtrl.GetValue() ix = charListCtrl.GetSelection() if ix == -1: if charListCtrl.GetItemCount() == 0: charListCtrl.InsertItem(wx.ListItem()) ix = 0 SelRow(0) self.data[ix][0] = strng charListCtrl.SetStringItem(ix, 0, strng) validation() evt.Skip() userCharLabelCtrl.Bind(wx.EVT_TEXT, OnLabelText) def OnReplCtrl(evt): ix = charListCtrl.GetSelection() oldVal = self.data[ix][1] repl = replCtrl.GetValue() if len(repl) > 1: MessageBox( self.panel, text.message8 % (repl), text.messBoxTit8, wx.ICON_EXCLAMATION, plugin=self, ) replCtrl.ChangeValue(oldVal) evt.Skip() return elif len(repr(repl)) > 4: MessageBox( self.panel, text.message7 % (repl), text.messBoxTit7, wx.ICON_EXCLAMATION, plugin=self, ) replCtrl.ChangeValue(oldVal) evt.Skip() return if ix == -1: if charListCtrl.GetItemCount() == 0: charListCtrl.InsertItem(wx.ListItem()) ix = 0 SelRow(0) self.data[ix][1] = repl validation() evt.Skip() replCtrl.Bind(wx.EVT_TEXT, OnReplCtrl) def OnCharSelect(evt): row = evt.GetIndex() charListCtrl.SetItemState(row, 0, wx.LIST_STATE_SELECTED) if row == self.oldSel: evt.Skip() return SelRow(row) userCharLabelCtrl.ChangeValue( charListCtrl.GetItem(row, 1).GetText()) evt.Skip() charListCtrl.Bind(wx.EVT_LIST_ITEM_SELECTED, OnCharSelect) def OnButtonAppend(evt): if len(self.data) == 1: btnUP.Enable(True) btnDOWN.Enable(True) elif len(self.data) == MAX_CHAR: MessageBox(self.panel, text.message1 % MAX_CHAR, text.messBoxTit1, wx.ICON_EXCLAMATION, plugin=self, time=10) evt.Skip() return replCtrl.ChangeValue("") sel = charListCtrl.GetSelection() + 1 self.data.insert(sel, cpy(EMPTY_CHAR)) charListCtrl.InsertStringItem(sel, "") SelRow(sel) charListCtrl.EnsureVisible(sel) ResetPattern() userCharLabelCtrl.ChangeValue("") userCharLabelCtrl.SetFocus() btnApp.Enable(False) btnDEL.Enable(True) self.panel.dialog.buttonRow.okButton.Enable(False) evt.Skip() btnApp.Bind(wx.EVT_BUTTON, OnButtonAppend) def OnButtonDel(evt): sel = charListCtrl.GetSelection() charListCtrl.DeleteItem(sel) self.data.pop(sel) lngth = len(self.data) if lngth > 0: if sel == lngth: sel = lngth - 1 charListCtrl.SetSelection(sel) else: userCharLabelCtrl.ChangeValue("") self.data = [cpy(EMPTY_CHAR)] sel = 0 charListCtrl.InsertStringItem(0, "") btnDEL.Enable(False) FillData(self.data[sel]) SelRow(sel) charListCtrl.EnsureVisible(sel) userCharLabelCtrl.SetFocus() validation() if len(self.data) == 1: btnUP.Enable(False) btnDOWN.Enable(False) evt.Skip() btnDEL.Bind(wx.EVT_BUTTON, OnButtonDel) def onButtonUp(evt): newSel, self.data = Move(self.data, self.oldSel, -1) Fill_ListCtrl() SelRow(newSel) charListCtrl.EnsureVisible(newSel) evt.Skip() btnUP.Bind(wx.EVT_BUTTON, onButtonUp) def onButtonDown(evt): newSel, self.data = Move(self.data, self.oldSel, 1) Fill_ListCtrl() SelRow(newSel) charListCtrl.EnsureVisible(newSel) evt.Skip() btnDOWN.Bind(wx.EVT_BUTTON, onButtonDown) def OnBtnEXP(evt): ix = charListCtrl.GetSelection() dlg = wx.FileDialog(panel, message=text.save, defaultDir=eg.configDir, defaultFile="Digispark-LCD.xml", wildcard=text.wildcard, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: self.dataToXml(self.data, dlg.GetPath(), splitext(dlg.GetFilename())[0]) dlg.Destroy() evt.Skip() btnEXP.Bind(wx.EVT_BUTTON, OnBtnEXP) def OnBtnIMP(evt): dlg = wx.FileDialog(panel, message=text.choose, defaultDir=eg.configDir, defaultFile="", wildcard=text.wildcard, style=wx.OPEN | wx.CHANGE_DIR) if dlg.ShowModal() == wx.ID_OK: filePath = dlg.GetPath() newdata = self.xmlToData(filePath) dlg.Destroy() else: dlg.Destroy() evt.Skip() return if not newdata: MessageBox( self.panel, text.message5 % path.split(dlg.GetPath())[1], text.messBoxTit1, wx.ICON_EXCLAMATION, plugin=self, ) evt.Skip() return if len(newdata): self.data = newdata Init_panel() else: MessageBox( self.panel, text.message4 % path.split(dlg.GetPath())[1], text.messBoxTit4, wx.ICON_EXCLAMATION, plugin=self, ) evt.Skip() btnIMP.Bind(wx.EVT_BUTTON, OnBtnIMP) def OnCharSelect(evt): row = evt.GetIndex() item = self.data[row] FillData(item) SelRow(row) validation() evt.Skip() charListCtrl.Bind(wx.EVT_LIST_ITEM_FOCUSED, OnCharSelect) def onBurn(evt): if self.data == [cpy(EMPTY_CHAR)]: MessageBox(self.panel, text.message3, text.messBoxTit4, wx.ICON_EXCLAMATION, plugin=self, time=10) return if not self.GetConnected(): MessageBox(self.panel, text.message2, text.messBoxTit2, wx.ICON_EXCLAMATION, plugin=self, time=10) return max = 1 + len(self.data) dlg = wx.ProgressDialog(self.text.progress, self.text.wait, maximum=max, parent=self.panel, style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL) dlg.SetIcon(self.info.icon.GetWxIcon()) keepGoing = True count = 0 for i, ch in enumerate(self.data): event = CreateEvent(None, 0, 0, None) item = list(ch[2]) item.append(i) item.append(ord(ch[1])) self.queue.put(((COMMANDS["Burn"], item), event)) eg.actionThread.WaitOnEvent(event) count += 1 (keepGoing, skip) = dlg.Update(count) self.queue.put(((COMMANDS["Burn"], (len(self.data), )), event)) count += 1 eg.actionThread.WaitOnEvent(event) (keepGoing, skip) = dlg.Update(count, self.text.done) self.eechars = len(self.data) btn0.Bind(wx.EVT_BUTTON, onBurn) panel.dialog.buttonRow.Add(btn0) while panel.Affirmed(): if self.data == [cpy(EMPTY_CHAR)]: self.data = [] panel.SetResult(self.data, )
# In[29]: # ax = sns.barplot(data = pd_df[(pd_df["all_method_success"]==1) & # (pd_df["Method"].isin(filtered_method_list))], # y = "node_explored",x = "MAP" , hue= "Method") # # plt.savefig("node_explored_bar_plot.eps") # In[30]: # plt.gcf().clear() # plt.clf() # In[13]: plot_df = cpy(pd_df[(pd_df["all_method_success"] == 1) & (pd_df["Method"].isin(filtered_method_list))]) plot_df["node_explored"] = pd.to_numeric(plot_df["node_explored"]) plt.figure(figsize=(6, 6)) ax = sns.boxplot( data=plot_df, y="node_explored", hue="MAP", order=["prm_4000", "gng", "gng_top", "gng_top_feedback", "prm_2000"], x="Method") plt.subplots_adjust(bottom=0.25) ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right', # fontweight='light', # fontsize='x-large'
def plot_2D(dataset, **kwargs): """ PLot of 2D array. Parameters ---------- dataset : :class:`~spectrochempy.ddataset.nddataset.NDDataset` The dataset to plot. ax : |Axes| instance. Optional The axe where to plot. The default is the current axe or to create a new one if is None. clear : `bool`, optional, default=`True` Should we plot on the ax previously used or create a new figure?. figsize : tuple, optional The figure size expressed as a tuple (w,h) in inch. Other Parameters ----------------- method : ['stack', 'map', 'image', 'surface', 'waterfall'] , optional The method of plot of the dataset, which will determine the plotter to use. Default is stack fontsize : int, optional The font size in pixels, default is 10 (or read from preferences). style : str autolayout : `bool`, optional, default=True if True, layout will be set automatically. output : str A string containing a path to a filename. The output format is deduced from the extension of the filename. If the filename has no extension, the value of the rc parameter savefig.format is used. dpi : [ None | scalar > 0] The resolution in dots per inch. If None it will default to the value savefig.dpi in the matplotlibrc file. colorbar : transposed : clear : ax : twinx : use_plotly : bool, optional Should we use plotly instead of mpl for plotting. Default to `preferences.use_plotly` (default=False) data_only : `bool` [optional, default=`False`] Only the plot is done. No addition of axes or label specifications (current if any or automatic settings are kept. method : str [optional among ``map``, ``stack``, ``image`` or ``3D``] The type of plot, projections : `bool` [optional, default=False] style : str, optional, default='notebook' Matplotlib stylesheet (use `available_style` to get a list of available styles for plotting reverse : `bool` or None [optional, default=None In principle, coordinates run from left to right, except for wavenumbers (e.g., FTIR spectra) or ppm (e.g., NMR), that spectrochempy will try to guess. But if reverse is set, then this is the setting which will be taken into account. x_reverse : `bool` or None [optional, default=None kwargs : additional keywords """ # Get preferences # ------------------------------------------------------------------------------------------------------------------ prefs = dataset.preferences # before going further, check if the style is passed in the parameters style = kwargs.pop('style', None) if style is not None: prefs.style = style # else we assume this has been set before calling plot() prefs.set_latex_font(prefs.font.family) # reset latex settings # Redirections ? # ------------------------------------------------------------------------------------------------------------------ # should we redirect the plotting to another method if dataset._squeeze_ndim < 2: return dataset.plot_1D(**kwargs) # if plotly execute plotly routine not this one if kwargs.get('use_plotly', prefs.use_plotly): return dataset.plotly(**kwargs) # Method of plot # ------------------------------------------------------------------------------------------------------------------ method = kwargs.get('method', prefs.method_2D) # do not display colorbar if it's not a surface plot # except if we have asked to d so # often we do need to plot only data when plotting on top of a previous plot data_only = kwargs.get('data_only', False) # Get the data to plot # ------------------------------------------------------------------------------------------------------------------- # if we want to plot the transposed dataset transposed = kwargs.get('transposed', False) if transposed: new = dataset.copy().T # transpose dataset nameadd = '.T' else: new = dataset # .copy() nameadd = '' new = new.squeeze() if kwargs.get('y_reverse', False): new = new[::-1] # Figure setup # ------------------------------------------------------------------------------------------------------------------ new._figure_setup(ndim=2, **kwargs) ax = new.ndaxes['main'] ax.name = ax.name + nameadd # Other properties that can be passed as arguments # ------------------------------------------------------------------------------------------------------------------ lw = kwargs.get('linewidth', kwargs.get('lw', prefs.lines_linewidth)) alpha = kwargs.get('calpha', prefs.contour_alpha) number_x_labels = prefs.number_of_x_labels number_y_labels = prefs.number_of_y_labels number_z_labels = prefs.number_of_z_labels if method in ['waterfall']: nxl = number_x_labels * 2 nyl = number_z_labels * 2 elif method in ['stack']: nxl = number_x_labels nyl = number_z_labels else: nxl = number_x_labels nyl = number_y_labels ax.xaxis.set_major_locator(MaxNLocator(nbins=nxl)) ax.yaxis.set_major_locator(MaxNLocator(nbins=nyl)) if method not in ['surface']: ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # the next lines are to avoid multipliers in axis scale formatter = ScalarFormatter(useOffset=False) ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) # ------------------------------------------------------------------------------------------------------------------ # Set axis # ------------------------------------------------------------------------------------------------------------------ # set the abscissa axis # ------------------------------------------------------------------------------------------------------------------ # the actual dimension name is the last in the new.dims list dimx = new.dims[-1] x = getattr(new, dimx) if x is not None and x.implements('CoordSet'): # if several coords, take the default ones: x = x.default xsize = new.shape[-1] show_x_points = False if x is not None and hasattr(x, 'show_datapoints'): show_x_points = x.show_datapoints if show_x_points: # remove data and units for display x = LinearCoord.arange(xsize) discrete_data = False if x is not None and (not x.is_empty or x.is_labeled): xdata = x.data if not np.any(xdata): if x.is_labeled: discrete_data = True # take into account the fact that sometimes axis have just labels xdata = range(1, len(x.labels) + 1) else: xdata = range(xsize) xl = [xdata[0], xdata[-1]] xl.sort() if xsize < number_x_labels + 1: # extend the axis so that the labels are not too close to the limits inc = abs(xdata[1] - xdata[0]) * .5 xl = [xl[0] - inc, xl[1] + inc] if data_only: xl = ax.get_xlim() xlim = list(kwargs.get('xlim', xl)) xlim.sort() xlim[-1] = min(xlim[-1], xl[-1]) xlim[0] = max(xlim[0], xl[0]) if kwargs.get('x_reverse', kwargs.get('reverse', x.reversed if x else False)): xlim.reverse() ax.set_xlim(xlim) xscale = kwargs.get("xscale", "linear") ax.set_xscale(xscale) # , nonpositive='mask') # set the ordinates axis # ------------------------------------------------------------------------------------------------------------------ # the actual dimension name is the second in the new.dims list dimy = new.dims[-2] y = getattr(new, dimy) if y is not None and y.implements('CoordSet'): # if several coords, take the default ones: y = y.default ysize = new.shape[-2] show_y_points = False if y is not None and hasattr(y, 'show_datapoints'): show_y_points = y.show_datapoints if show_y_points: # remove data and units for display y = LinearCoord.arange(ysize) if y is not None and (not y.is_empty or y.is_labeled): ydata = y.data if not np.any(ydata): if y.is_labeled: ydata = range(1, len(y.labels) + 1) else: ydata = range(ysize) yl = [ydata[0], ydata[-1]] yl.sort() if ysize < number_y_labels + 1: # extend the axis so that the labels are not too close to the limits inc = abs(ydata[1] - ydata[0]) * .5 yl = [yl[0] - inc, yl[1] + inc] if data_only: yl = ax.get_ylim() ylim = list(kwargs.get("ylim", yl)) ylim.sort() ylim[-1] = min(ylim[-1], yl[-1]) ylim[0] = max(ylim[0], yl[0]) yscale = kwargs.get("yscale", "linear") ax.set_yscale(yscale) # z intensity (by default we plot real component of the data) # ------------------------------------------------------------------------------------------------------------------ if not kwargs.get('imag', False): zdata = new.real.masked_data else: zdata = new.RI.masked_data # new.imag.masked_data #TODO: quaternion case (3 imag.components) zlim = kwargs.get('zlim', (np.ma.min(zdata), np.ma.max(zdata))) if method in ['stack', 'waterfall']: # the z axis info # --------------- # zl = (np.min(np.ma.min(ys)), np.max(np.ma.max(ys))) amp = 0 # np.ma.ptp(zdata) / 50. zl = (np.min(np.ma.min(zdata) - amp), np.max(np.ma.max(zdata)) + amp) zlim = list(kwargs.get('zlim', zl)) zlim.sort() z_reverse = kwargs.get('z_reverse', False) if z_reverse: zlim.reverse() # set the limits # --------------- if yscale == "log" and min(zlim) <= 0: # set the limits wrt smallest and largest strictly positive values ax.set_ylim(10**(int(np.log10(np.amin(np.abs(zdata)))) - 1), 10**(int(np.log10(np.amax(np.abs(zdata)))) + 1)) else: ax.set_ylim(zlim) else: # the y axis info # ---------------- if data_only: ylim = ax.get_ylim() ylim = list(kwargs.get('ylim', ylim)) ylim.sort() y_reverse = kwargs.get('y_reverse', y.reversed if y else False) if y_reverse: ylim.reverse() # set the limits # ---------------- ax.set_ylim(ylim) # ------------------------------------------------------------------------------------------------------------------ # plot the dataset # ------------------------------------------------------------------------------------------------------------------ ax.grid(prefs.axes_grid) normalize = kwargs.get('normalize', None) cmap = kwargs.get('colormap', kwargs.get('cmap', prefs.colormap)) if method in ['map', 'image', 'surface']: zmin, zmax = zlim zmin = min(zmin, -zmax) zmax = max(-zmin, zmax) norm = mpl.colors.Normalize(vmin=zmin, vmax=zmax) if method in ['surface']: X, Y = np.meshgrid(xdata, ydata) Z = zdata.copy() # masker data not taken into account in surface plot Z[dataset.mask] = np.nan # Plot the surface. #TODO : improve this (or remove it) antialiased = kwargs.get('antialiased', prefs.antialiased) rcount = kwargs.get('rcount', prefs.rcount) ccount = kwargs.get('ccount', prefs.ccount) ax.set_facecolor('w') ax.plot_surface( X, Y, Z, cmap=cmap, linewidth=lw, antialiased=antialiased, rcount=rcount, ccount=ccount, edgecolor='k', norm=norm, ) if method in ['waterfall']: _plot_waterfall(ax, new, xdata, ydata, zdata, prefs, xlim, ylim, zlim, **kwargs) elif method in ['image']: cmap = kwargs.get('cmap', kwargs.get('image_cmap', prefs.image_cmap)) if discrete_data: method = 'map' else: kwargs['nlevels'] = 500 if not hasattr(new, 'clevels') or new.clevels is None: new.clevels = _get_clevels(zdata, prefs, **kwargs) c = ax.contourf(xdata, ydata, zdata, new.clevels, alpha=alpha) c.set_cmap(cmap) c.set_norm(norm) elif method in ['map']: if discrete_data: _colormap = plt.get_cmap(cmap) scalarMap = mpl.cm.ScalarMappable(norm=norm, cmap=_colormap) # marker = kwargs.get('marker', kwargs.get('m', None)) markersize = kwargs.get('markersize', kwargs.get('ms', 5.)) # markevery = kwargs.get('markevery', kwargs.get('me', 1)) for i in ydata: for j in xdata: li, = ax.plot(j, i, lw=lw, marker='o', markersize=markersize) li.set_color(scalarMap.to_rgba(zdata[i - 1, j - 1])) else: # contour plot # ------------- if not hasattr(new, 'clevels') or new.clevels is None: new.clevels = _get_clevels(zdata, prefs, **kwargs) c = ax.contour(xdata, ydata, zdata, new.clevels, linewidths=lw, alpha=alpha) c.set_cmap(cmap) c.set_norm(norm) elif method in ['stack']: # stack plot # ---------- # now plot the collection of lines # -------------------------------- # map colors using the colormap vmin, vmax = ylim norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) # we normalize to the max time if normalize is not None: norm.vmax = normalize _colormap = plt.get_cmap(cmap) scalarMap = mpl.cm.ScalarMappable(norm=norm, cmap=_colormap) # we display the line in the reverse order, so that the last # are behind the first. clear = kwargs.get('clear', True) lines = [] if not clear and not transposed: lines.extend(ax.lines) # keep the old lines line0, = ax.plot(xdata, zdata[0], lw=lw, picker=True) for i in range(zdata.shape[0]): li = cpy(line0) li.set_ydata(zdata[i]) lines.append(li) li.set_color(scalarMap.to_rgba(ydata[i])) fmt = kwargs.get('label_fmt', "{:.5f}") li.set_label(fmt.format(ydata[i])) li.set_zorder(zdata.shape[0] + 1 - i) # store the full set of lines new._ax_lines = lines[:] # but display only a subset of them in order to accelerate the drawing maxlines = kwargs.get('maxlines', prefs.max_lines_in_stack) setpy = max(len(new._ax_lines) // maxlines, 1) ax.lines = new._ax_lines[::setpy] # displayed ax lines if data_only or method in ['waterfall']: # if data only (we will not set axes and labels # it was probably done already in a previous plot new._plot_resume(dataset, **kwargs) return ax # display a title # ------------------------------------------------------------------------------------------------------------------ title = kwargs.get('title', None) if title: ax.set_title(title) elif kwargs.get('plottitle', False): ax.set_title(new.name) # ------------------------------------------------------------------------------------------------------------------ # labels # ------------------------------------------------------------------------------------------------------------------ # x label # ------------------------------------------------------------------------------------------------------------------ xlabel = kwargs.get("xlabel", None) if show_x_points: xlabel = 'data points' if not xlabel: xlabel = make_label(x, new.dims[-1]) ax.set_xlabel(xlabel) uselabelx = kwargs.get('uselabel_x', False) if x and x.is_labeled and (uselabelx or not np.any(x.data)) and len( x.labels) < number_x_labels + 1: # TODO refine this to use different orders of labels ax.set_xticks(xdata) ax.set_xticklabels(x.labels) # y label # ------------------------------------------------------------------------------------------------------------------ ylabel = kwargs.get("ylabel", None) if show_y_points: ylabel = 'data points' if not ylabel: if method in ['stack']: ylabel = make_label(new, 'values') else: ylabel = make_label(y, new.dims[-2]) # y tick labels uselabely = kwargs.get('uselabel_y', False) if y and y.is_labeled and (uselabely or not np.any( y.data)) and len(y.labels) < number_y_labels: # TODO refine this to use different orders of labels ax.set_yticks(ydata) ax.set_yticklabels(y.labels) # z label # ------------------------------------------------------------------------------------------------------------------ zlabel = kwargs.get("zlabel", None) if not zlabel: if method in ['stack']: zlabel = make_label(y, new.dims[-2]) elif method in ['surface']: zlabel = make_label(new, 'values') ax.set_zlabel(zlabel) else: zlabel = make_label(new, 'z') # do we display the ordinate axis? if kwargs.get('show_y', True): ax.set_ylabel(ylabel) else: ax.set_yticks([]) if 'colorbar' in new.ndaxes: if 'surface' not in method and (not hasattr(new, '_axcb') or not new._axcb): axec = new.ndaxes['colorbar'] axec.name = axec.name + nameadd new._axcb = mpl.colorbar.ColorbarBase(axec, cmap=plt.get_cmap(cmap), norm=norm) new._axcb.set_label(zlabel) # else: # new._fig.colorbar(surf, shrink=0.5, aspect=10) # do we display the zero line if kwargs.get('show_zero', False): ax.haxlines() new._plot_resume(dataset, **kwargs) return ax
def Configure( self, prefix = None, debug = 3, host = "ws://", port = 80, password = "", dummy = "", proxy = ["", 0, "", ""] ): prefix = self.name if prefix is None else prefix if not isinstance(proxy[3], eg.Password): p = eg.Password(None) p.Set("") proxy[3] = p text = self.text panel = eg.ConfigPanel(self) panel.proxy = cpy(proxy) if not isinstance(password, eg.Password): passw = eg.Password(None) passw.Set(password) else: passw = password debugLabel2 = wx.StaticText(panel, -1, text.debug2) debugCtrl = eg.SpinIntCtrl( panel, -1, debug, min = 1, max = 5 ) debugSizer = wx.BoxSizer(wx.HORIZONTAL) debugSizer.Add(debugCtrl, 0, wx.RIGHT, 5) debugSizer.Add( debugLabel2, 0, flag = ACV) prefixCtrl = panel.TextCtrl(prefix) hostCtrl = panel.TextCtrl(host) portCtrl = panel.SpinIntCtrl(port, min = 1, max = 65535) passwordCtrl = wx.TextCtrl(panel, -1, passw.Get(), style = wx.TE_PASSWORD) labels = ( panel.StaticText(text.prefix), panel.StaticText(text.host), panel.StaticText(text.port), panel.StaticText(text.password), panel.StaticText(text.debug) ) eg.EqualizeWidths(labels) topSizer = wx.FlexGridSizer(2, 2, 5, 5) topSizer.Add(labels[0], 0, ACV|wx.LEFT,10) topSizer.Add(prefixCtrl,0,wx.EXPAND|wx.LEFT,5) topSizer.Add(labels[4], 0, ACV|wx.LEFT,10) topSizer.Add(debugSizer,0,wx.EXPAND|wx.LEFT,5) sizer = wx.FlexGridSizer(3, 2, 5, 5) sizer.AddGrowableCol(1) sizer.Add(labels[1], 0, ACV) sizer.Add(hostCtrl,0) sizer.Add(labels[2], 0, ACV) sizer.Add(portCtrl) sizer.Add(labels[3], 0, ACV) sizer.Add(passwordCtrl) staticBox = wx.StaticBox(panel, label=text.server) staticBoxSizer = wx.StaticBoxSizer(staticBox, wx.VERTICAL) staticBoxSizer.Add(sizer, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 5) panel.sizer.Add(topSizer, 0, wx.EXPAND|wx.TOP|wx.BOTTOM,5) panel.sizer.Add(staticBoxSizer, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 10) proxyBtn = wx.Button(panel.dialog, -1, text.proxyTitle) def onProxyBtn(evt): dlg = ProxyDialog( parent = panel, plugin = self, labels = text.headers, data = panel.proxy, ) wx.CallAfter( dlg.ShowProxyDlg, text.proxyTitle ) evt.Skip() proxyBtn.Bind(wx.EVT_BUTTON, onProxyBtn) panel.dialog.buttonRow.Add(proxyBtn) while panel.Affirmed(): oldPassw = passw.Get() newPassw = passwordCtrl.GetValue() if oldPassw != newPassw: passw.Set(newPassw) dummy = str(ttime()) if proxy[3].Get() != panel.proxy[3].Get(): dummy = str(ttime()) panel.SetResult( prefixCtrl.GetValue(), debugCtrl.GetValue(), hostCtrl.GetValue(), portCtrl.GetValue(), passw, dummy, panel.proxy )
def train(self, max_epochs, patience): print('{:>8}{:>8}{:>8}{:>8}{:>8}{:>8}'.format('epoch', 'tr_acc', 'vs_acc', 'tr_loss', 'vs_loss', 'time')) self.net.to(self.device) count_no_change = 0 best_val_acc = 0 for epoch in range(max_epochs): self.epoch_num += 1 start_time = time() self.net.train() if self.sch: self.sch.step() # preds = [] # delete running_loss = 0. for i, (xs, ts) in enumerate(self.tr_data): xs, ts = xs.to(self.device), ts.to(self.device) self.opt.zero_grad() zs = self.net(xs) loss = self.loss_fun(zs, ts) # _, pred = torch.max(zs, dim=1) # delete # preds.extend(pred.cpu().detach().numpy()) # delete loss.backward() self.opt.step() running_loss += loss.item() / len(xs) curr_tr_loss = round(running_loss / (i + 1), 4) curr_tr_acc = round(self.test_accuracy(self.tr_data, self.net), 4) self.tr_loss.append(curr_tr_loss) # print('% of 1s predicted: ', round(np.sum(preds) / len(preds), 3)) self.net.eval() running_loss = 0. for i, (xs, ts) in enumerate(self.vs_data): xs, ts = xs.to(self.device), ts.to(self.device) zs = self.net(xs) _, pred = torch.max(zs, dim=1) loss = self.loss_fun(zs, ts) running_loss += loss.item() / len(xs) curr_vs_loss = round(running_loss / (i + 1), 4) curr_vs_acc = round(self.test_accuracy(self.vs_data, self.net), 4) self.vs_loss.append(curr_vs_loss) epoch_time = round(time() - start_time, 1) print('{:8}{:8}{:8}{:8}{:8}{:8}'.format(self.epoch_num, curr_tr_acc, curr_vs_acc, curr_tr_loss, curr_vs_loss, epoch_time)) if curr_vs_acc > best_val_acc: best_val_acc = cpy(curr_vs_acc) self.best_net = cpy(self.net) count_no_change = 0 else: count_no_change += 1 if count_no_change == patience: break print('Finished Training')
ba1=np.broadcast_to(np.array([I]),(1,3,1,1)) bs.append(ba1*e) [bx.append(O) for O in np.reshape(bax*e,(5,)).tolist()] #bxa=np.array(bx) #print(WAR[0].shape,WAR[0]) #print(bs[0].shape,bs[0]) #print(bx) #exit() #print(bxx) isodata=0#100 if isodata: inputcols=np.broadcast_to(np.array([isodata],dtype=np.float32),inputcols.shape) indict={'mean':[],'max':[],'min':[],'1mean':[],'1max':[],'1min':[],'2mean':[],'2max':[],'2min':[],} outputs={1:cpy(indict),2:cpy(indict),3:cpy(indict)} sizz=(0,0) wid=np.broadcast_to(wid, (numout,*wid.shape[1:])) sqrtv=0#square root output? mulbv=0#use mulb 1 mul2v=1# use mul2 v3v=0#value of the v3 alg bsvi=-1#9 print(len(bs),bs[0]) def plotvars(BB,Wi=None,short=False,Nob=False,bx=bx,mode="save",formatf=["pdf","svg","pgn"][0]): outputs={1:cpy(indict),2:cpy(indict),3:cpy(indict)} axs=(0,-2,-1) hol=[WAR,bs][BB] WV = wid if (Wi is None) else WAR[Wi] ding=0 BS= np.array(hol) if BB==1 else bs[bsvi]
def gpu_value_iteration(S, A, reward_dict, tran_dict, seed_value=None, unknown_value=0, true_action_prob=0.9, beta=0.99, epsilon=0.01, workers_num=4, verbose=True, max_threads=1000): import pycuda.autoinit # tran_dict, reward_dict = sanitize_transitions st = time.time() tranProbMatrix, rewardMatrix, action_index_to_action, tranMatrixStateIndexes, state_to_index, index_to_state = \ get_tran_matrices_v2(tran_dict, reward_dict, A) et = time.time() print("tiem to get matris:{}".format(et - st)) Tran_prob_Matrix, Tran_index_Matrix, Reward_Matrix = tranProbMatrix.astype( 'float32'), tranMatrixStateIndexes.astype( 'float32'), rewardMatrix.astype('float32') ACTION_COUNT, number_of_states, number_of_connections = Tran_prob_Matrix.shape assert Tran_prob_Matrix.shape == Tran_index_Matrix.shape == Reward_Matrix.shape print(tranProbMatrix.shape, rewardMatrix.shape, tranMatrixStateIndexes.shape) Value_Vector = np.random.randint(1, size=(number_of_states, 1)).astype('float32').reshape(-1) # print(Value_Vector) ROW_COUNT = Tran_prob_Matrix.shape[1] COL_COUNT = Tran_prob_Matrix.shape[2] print(ACTION_COUNT, ROW_COUNT, COL_COUNT) assert Tran_prob_Matrix.shape == Tran_index_Matrix.shape ################################################################################################ st = time.time() new_value_vector_cpu = VI_SOLVER_GPU(Tran_prob_Matrix, Tran_index_Matrix, Reward_Matrix, Value_Vector, no_of_backups=1000, epsilon=epsilon, verbose=verbose, max_threads=max_threads) gpu_time = time.time() - st print(gpu_time) final_value_vector = new_value_vector_cpu #.get().reshape(-1) V_t = defaultdict(lambda: 0) for i, v in enumerate(final_value_vector): V_t[index_to_state[i]] = v # assert "end_state" in V_t # assert "end_state" in tran_dict # assert "end_state" in reward_dict assert "unknown_state" not in tran_dict # import pdb; pdb.set_trace(); # print(V_t["end_state"]) V_t = {k: V_t[k] for k in tran_dict} pi = get_pi_from_value(cpy(V_t), A, tran_dict, reward_dict, beta) # # assert "end_state" in pi # assert "end_state" in V_t assert "unknown_state" not in V_t return V_t, pi
def getDeceivingWar(nblocks, kblocks, n): score = 0 for i in range(n): nchosen = min(nblocks) if (min(nblocks) < min(kblocks)): ntold = max(kblocks) - 0.000001 else: ntold = max(kblocks) + 0.000001 largerks = filter(lambda e: e > ntold, kblocks) kchosen = min(largerks) if len(largerks) > 0 else min(kblocks) if nchosen > kchosen: score += 1 nblocks.remove(nchosen) kblocks.remove(kchosen) return score for problem in range(int(fi.readline())): n = int(fi.readline()) nblocks = map(float, fi.readline().split(" ")) kblocks = map(float, fi.readline().split(" ")) print "Case #%d: %d %d" % (problem + 1, getDeceivingWar(cpy(nblocks), cpy(kblocks), n), getWar(cpy(nblocks), cpy(kblocks), n))
def handleCarIn(self,tmpCar): self.drivers.append(cpy(tmpCar)) self.inCar += 1