def _draw_image(self, bbox=None): if self.image_output is None: return with self.image_output: image = Image.fromarray(self.current_image) if bbox is not None: draw = ImageDraw.Draw(image) draw.rectangle(bbox, fill=None, outline="red") display.display( pil2ipyimage(image, height=self.height, width=self.width))
def display_as_html_image(animation, show=True, *args, **kwargs): from IPython import display try: if show: animation._init_draw() for _ in animation.frame_seq: if show: fig = plt.gcf() display.display(fig) animation._step() if show: display.clear_output(wait=True) except KeyboardInterrupt: display.clear_output(wait=False)
def interact(self): self.itcs.positionMasts(self.mastCoords, self.mastHeights) swExtent = self.mastCoords.min(axis=0) neExtent = self.mastCoords.max(axis=0) w = widgets.interactive( self.posPlatform, xPlat=widgets.FloatSliderWidget(min=swExtent[0], max=neExtent[0], value=self.platCoord[0], step=1.0), yPlat=widgets.FloatSliderWidget(min=swExtent[1], max=neExtent[1], value=self.platCoord[1], step=1.0), height=widgets.FloatSliderWidget(min=0, max=200, value=self.platHeight), weight=widgets.FloatSliderWidget(min=0, max=1000, value=500) ) display.display(w)
def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and plot them too if len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) # pause a bit so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf())
def attempt_colab_login(app_url): """This renders an iframe to wandb in the hopes it posts back an api key""" from google.colab import output from google.colab._message import MessageError from IPython import display display.display( display.Javascript(""" window._wandbApiKey = new Promise((resolve, reject) => { function loadScript(url) { return new Promise(function(resolve, reject) { let newScript = document.createElement("script"); newScript.onerror = reject; newScript.onload = resolve; document.body.appendChild(newScript); newScript.src = url; }); } loadScript("https://cdn.jsdelivr.net/npm/postmate/build/postmate.min.js").then(() => { const iframe = document.createElement('iframe') iframe.style.cssText = "width:0;height:0;border:none" document.body.appendChild(iframe) const handshake = new Postmate({ container: iframe, url: '%s/authorize' }); const timeout = setTimeout(() => reject("Couldn't auto authenticate"), 5000) handshake.then(function(child) { child.on('authorize', data => { clearTimeout(timeout) resolve(data) }); }); }) }); """ # noqa: E501 % app_url.replace("http:", "https:"))) try: return output.eval_js("_wandbApiKey") except MessageError: return None
def display(self): hlayout = Layout(display='flex', flex_flow='row', align_items='stretch', border='none', width='100%') vbox = VBox(children=[ self.text, self.label_answer, self.label_query, self.label_expression ]) vbox.layout.width = '70%' interact = widgets.interactive(self._next_image, idx=(0, len(self.images) - 1)) interact.layout.height = '550px' self.image_output = interact.out if self.camera: vbox_images = VBox( children=[self.image_output, self.camera, self.image_recorder]) else: vbox_images = VBox(children=[interact]) display.display(HBox(children=[vbox_images, vbox], layout=hlayout))
def interact(self): self.itcs.positionMasts(self.mastCoords, self.mastHeights) swExtent = self.mastCoords.min(axis=0) neExtent = self.mastCoords.max(axis=0) w = widgets.interactive( self.posPlatform, xPlat=widgets.FloatSliderWidget(min=swExtent[0], max=neExtent[0], value=self.platCoord[0], step=1.0), yPlat=widgets.FloatSliderWidget(min=swExtent[1], max=neExtent[1], value=self.platCoord[1], step=1.0), height=widgets.FloatSliderWidget(min=0, max=200, value=self.platHeight), weight=widgets.FloatSliderWidget(min=0, max=1000, value=500)) display.display(w)
def __init__(self, atoms, carbon_labels=True, names=None, width=400, height=350, display=False, _forcebig=False, **kwargs): self.atoms = getattr(atoms, 'atoms', atoms) if not _forcebig and len(self.atoms) > self.MAXATOMS: raise ValueError('Refusing to draw more than 200 atoms in 2D visualization. ' 'Override this with _forcebig=True') if names is None: names = [] for atom in self.atoms: if atom.formal_charge == 0: names.append(atom.name) else: names.append(atom.name + _charge_str(atom.formal_charge)) self.names = names self.atom_indices = {atom: i for i, atom in enumerate(self.atoms)} self.selection_group = None self.selection_id = None self.width = width self.height = height self.uuid = 'mol2d'+str(uuid.uuid4()) self.carbon_labels = carbon_labels self._clicks_enabled = False self.graph = self.to_graph(self.atoms) super().__init__(layout=ipy.Layout(width=str(width), height=str(height))) if display: dsp.display(self)
def posPlatform(self, xPlat, yPlat, height, weight): def tableRow(title, form, vals): return '<tr><th>' + title + '</th>' + ' '.join([('<td>' + form + '</td>').format(x) for x in vals]) + '</tr>\n' okay = self.itcs.positionPlatform([xPlat, yPlat], height, weight) if not okay: print 'One or more cables would need to be in compression to position the platform {}m above ({},{})'.format(height,xPlat,yPlat) return d, zt, zg = self.itcs.getTerrainBeneathCables(resolution=10) zc, mc = self.itcs.getCableClearance(d, zt) if mc < 1.0: attr = ' style="color:red;"' else: attr = '' s = '<table>\n' s += tableRow('Cable', '{}', range(1, 4)) s += tableRow('Length [m]', '{:0.0f}', [self.itcs.tcs.c[i].length() for i in range(3)]) s += tableRow('Tension [N]', '{:0.0f}', self.itcs.tcs.tensionAtMasts()) s += '</table>\n' s += '<p{}>Minimum canopy clearance: {:0.2f}m</p>\n'.format(attr, mc) display.display(HTML(s)) plt.figure(figsize=(12,8)) ax = plt.subplot(111, aspect='equal') pres.showInstallation2d(ax, self.itcs, [0,500], [1500,1500], showPlat=True) plt.figure(figsize=(12,8)) axt = range(3) axb = range(3) # fig, axes = plt.subplots(ncols=3, nrows=2, sharex=True, sharey=True) # plt.setp(axes.flat, aspect=1.0, adjustable='box') axt[0] = plt.subplot(231, aspect='equal') axt[1] = plt.subplot(232, sharex=axt[0], sharey=axt[0]) #, aspect='equal') axt[2] = plt.subplot(233, sharex=axt[0], sharey=axt[0]) #, aspect='equal') axb[0] = plt.subplot(234, sharex=axt[0]) axb[1] = plt.subplot(235, sharex=axt[0], sharey=axb[0]) axb[2] = plt.subplot(236, sharex=axt[0], sharey=axb[0]) plt.setp(axt[1].get_yticklabels(), visible=False) plt.setp(axt[2].get_yticklabels(), visible=False) plt.setp(axb[1].get_yticklabels(), visible=False) plt.setp(axb[2].get_yticklabels(), visible=False) axt[0].set_ylabel('elevation [m]') axb[0].set_ylabel('clearance from canopy [m]') for i in range(3): plt.setp(axt[i].get_xticklabels(), visible=False) axt[i].plot(d[i], zc[i], 'b-') axt[i].plot(d[i], zt[i], 'g-') axt[i].plot(d[i], zg[i], 'g-') axt[i].plot(d[i][-1], zc[i][-1], 'ro') axt[i].plot([0, 5], [zc[i][0], zg[i][0]], 'r-') axb[i].set_xlabel('distance from mast {} [m]'.format(i+1)) axb[i].plot(d[i], zc[i] - zt[i], 'b')
def posPlatform(self, xPlat, yPlat, height, weight): def tableRow(title, form, vals): return '<tr><th>' + title + '</th>' + ' '.join([ ('<td>' + form + '</td>').format(x) for x in vals ]) + '</tr>\n' okay = self.itcs.positionPlatform([xPlat, yPlat], height, weight) if not okay: print 'One or more cables would need to be in compression to position the platform {}m above ({},{})'.format( height, xPlat, yPlat) return d, zt, zg = self.itcs.getTerrainBeneathCables(resolution=10) zc, mc = self.itcs.getCableClearance(d, zt) if mc < 1.0: attr = ' style="color:red;"' else: attr = '' s = '<table>\n' s += tableRow('Cable', '{}', range(1, 4)) s += tableRow('Length [m]', '{:0.0f}', [self.itcs.tcs.c[i].length() for i in range(3)]) s += tableRow('Tension [N]', '{:0.0f}', self.itcs.tcs.tensionAtMasts()) s += '</table>\n' s += '<p{}>Minimum canopy clearance: {:0.2f}m</p>\n'.format(attr, mc) display.display(HTML(s)) plt.figure(figsize=(12, 8)) ax = plt.subplot(111, aspect='equal') pres.showInstallation2d(ax, self.itcs, [0, 500], [1500, 1500], showPlat=True) plt.figure(figsize=(12, 8)) axt = range(3) axb = range(3) # fig, axes = plt.subplots(ncols=3, nrows=2, sharex=True, sharey=True) # plt.setp(axes.flat, aspect=1.0, adjustable='box') axt[0] = plt.subplot(231, aspect='equal') axt[1] = plt.subplot(232, sharex=axt[0], sharey=axt[0]) #, aspect='equal') axt[2] = plt.subplot(233, sharex=axt[0], sharey=axt[0]) #, aspect='equal') axb[0] = plt.subplot(234, sharex=axt[0]) axb[1] = plt.subplot(235, sharex=axt[0], sharey=axb[0]) axb[2] = plt.subplot(236, sharex=axt[0], sharey=axb[0]) plt.setp(axt[1].get_yticklabels(), visible=False) plt.setp(axt[2].get_yticklabels(), visible=False) plt.setp(axb[1].get_yticklabels(), visible=False) plt.setp(axb[2].get_yticklabels(), visible=False) axt[0].set_ylabel('elevation [m]') axb[0].set_ylabel('clearance from canopy [m]') for i in range(3): plt.setp(axt[i].get_xticklabels(), visible=False) axt[i].plot(d[i], zc[i], 'b-') axt[i].plot(d[i], zt[i], 'g-') axt[i].plot(d[i], zg[i], 'g-') axt[i].plot(d[i][-1], zc[i][-1], 'ro') axt[i].plot([0, 5], [zc[i][0], zg[i][0]], 'r-') axb[i].set_xlabel('distance from mast {} [m]'.format(i + 1)) axb[i].plot(d[i], zc[i] - zt[i], 'b')
P = [] for i in range(0, swarmsize): P.append(Particle()) gBest_fitness = float('inf') gBest_position = [None] * len(P[0].getCurrPosition()) # matplotlib inline import time import pylab as pl from IPython import display if (D == 1): pl.plot(function_to_predict["X"], function_to_predict["Y"]) display.clear_output(wait=True) display.display(pl.gcf()) time.sleep(1.0) if (D == 2): ax = plt.axes(projection='3d') ax.plot3D( function_to_predict["X"], function_to_predict["Y"], function_to_predict["Z"], 'o' ) #,function_to_predict["X"], function_to_predict["Y"], function_to_predict["Z"], '-o') display.clear_output(wait=True) display.display(pl.gcf()) time.sleep(1.0) #PSO old_y = []