def plot_images_as_subplots(list_of_plot_args, plot_name, width, height, invert_y=False, invert_x=False, figsize=None, turn_on_agg=True): if turn_on_agg: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt lengths = [len(a) for a in list_of_plot_args] if len(list(filter(lambda x: x != lengths[0], lengths))) > 0: raise ValueError("list_of_plot_args has elements of different lengths!") if figsize is None: f, axarr = plt.subplots(lengths[0], len(lengths)) else: f, axarr = plt.subplots(lengths[0], len(lengths), figsize=figsize) for n, v in enumerate(list_of_plot_args): for i, X_i in enumerate(v): axarr[i, n].matshow(X_i.reshape(width, height), cmap="gray", interpolation="none") axarr[i, n].axis('off') if invert_y: axarr[i, n].set_ylim(axarr[i, n].get_ylim()[::-1]) if invert_x: axarr[i, n].set_xlim(axarr[i, n].get_xlim()[::-1]) plt.tight_layout() plt.savefig(plot_name + ".png")
def load(self): self.initTranslations() cfg = SimuVis4.Globals.config cfgsec = self.name.lower() if not cfg.has_section(cfgsec): cfg.add_section(cfgsec) cfg.set_def(cfgsec, 'set_default_backend', 'yes') cfg.set_def(cfgsec, 'zoom_step_factor', '0.189207115002721') cfg.set_def(cfgsec, 'mouse_wheel_step', '15') glb = SimuVis4.Globals import matplotlib if matplotlib.__version__ < mplMinVersion or matplotlib.__version__ > mplMaxVersion: SimuVis4.Globals.logger.error(unicode(QCoreApplication.translate('MatPlot', 'MatPlot: need matplotlib version between %s and %s, but found %s')) % \ (mplMinVersion, mplMaxVersion, matplotlib.__version__)) return False self.matplotlib = matplotlib if cfg.getboolean(cfgsec, 'set_default_backend'): try: sys.path.append(os.path.split(__file__)[0]) matplotlib.use('module://backend_sv4agg') except: pass import backend_sv4agg self.backend_sv4agg = backend_sv4agg dpath = matplotlib.rcParams['datapath'] tmp = os.path.join(dpath, 'images') if os.path.isdir(tmp): dpath = tmp winIcon = QIcon(os.path.join(dpath, 'matplotlib.png')) testAction = QAction(winIcon, QCoreApplication.translate('MatPlot', '&MatPlot/PyLab Test'), SimuVis4.Globals.mainWin) testAction.setStatusTip(QCoreApplication.translate('MatPlot', 'Show a matplotlib/pylab test window')) QWidget.connect(testAction, SIGNAL("triggered()"), self.test) SimuVis4.Globals.mainWin.plugInMenu.addAction(testAction) return True
def importModules(verbose=True): global matplotlib,xmlplot # If MatPlotLib if already loaded, we are done: return. if matplotlib is not None: return # Configure MatPlotLib backend and numerical library. # (should be done before any modules that use MatPlotLib are loaded) import matplotlib #matplotlib.rcParams['numerix'] = 'numpy' matplotlib.use('Qt4Agg') # Add the GOTM-GUI directory to the search path and import the common # GOTM-GUI module (needed for command line parsing). path = sys.path[:] if not hasattr(sys,'frozen'): rootdir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(rootdir, '../xmlstore')) sys.path.append(os.path.join(rootdir, '../xmlplot')) # Import remaining GOTM-GUI modules try: import xmlplot.data,xmlplot.plot,xmlplot.gui_qt4 except ImportError,e: print 'Unable to import xmlplot (%s). Please ensure that it is installed.' % e sys.exit(1)
def setUpClass(cls): try: import matplotlib as mpl mpl.use("Agg", warn=False) except ImportError: raise nose.SkipTest
def plot_gen(ping, now, t, nans, host, interactive=False, size="1280x640"): ''' Generates ping vs time plot ''' if not interactive: import matplotlib matplotlib.use("Agg") # no need to load gui toolkit, can run headless import matplotlib.pyplot as plt size = [int(dim) for dim in size.split('x')] datestr = now[0].ctime().split() datestr = datestr[0] + " " + datestr[1] + " " + datestr[2] + " " + datestr[-1] plt.figure(figsize=(size[0]/80.,size[1]/80.)) # dpi is 80 plt.plot(now[~nans], ping[~nans], drawstyle='steps', marker='+') plt.title("Ping Results for {0}".format(host)) plt.ylabel("Latency [ms]") plt.xlabel("Time, {0} [GMT -{1} hrs]".format(datestr, time.timezone/3600)) plt.xticks(size=10) plt.yticks(size=10) plt.ylim(ping[~nans].min()-5, ping[~nans].max()+5) # plot packet losses start = [] finish = [] for i in range(len(nans)): if nans[i] == True: if i == 0: start.append(i) elif nans[i] != nans[i-1]: start.append(i) #if i != len(nans) and nans[i+1] != nans[i]: # finish.append(i) # add the red bars for bad pings for i in range(len(start)): plt.axvspan(now[start[i]], now[finish[i]+1], color='red') return plt
def setup(nopatch=False, figsize="4.0, 3.0"): """Setup gterm-aware matplotlib. Note: Must be called before importing matplotlib If nopatch, do not patch the draw/figure/show functions of pyplot/pylab. """ import matplotlib matplotlib.use("Agg") if figsize: matplotlib.rcParams["figure.figsize"] = figsize import matplotlib.pyplot import pylab pyplot_dict["new_cell"] = False pyplot_dict["new_plot"] = True pyplot_dict["drawing"] = False pyplot_dict["draw"] = matplotlib.pyplot.draw pyplot_dict["figure"] = matplotlib.pyplot.figure pyplot_dict["show"] = matplotlib.pyplot.show if not nopatch: matplotlib.pyplot.draw_if_interactive = draw_if_interactive pylab.draw_if_interactive = draw_if_interactive matplotlib.pyplot.draw = draw matplotlib.pyplot.figure = figure matplotlib.pyplot.show = show pylab.draw = draw pylab.figure = figure pylab.show = show
def showKernel(dataOrMatrix, fileName = None, useLabels = True, **args) : labels = None if hasattr(dataOrMatrix, 'type') and dataOrMatrix.type == 'dataset' : data = dataOrMatrix k = data.getKernelMatrix() labels = data.labels else : k = dataOrMatrix if 'labels' in args : labels = args['labels'] import matplotlib if fileName is not None and fileName.find('.eps') > 0 : matplotlib.use('PS') from matplotlib import pylab pylab.matshow(k) #pylab.show() if useLabels and labels.L is not None : numPatterns = 0 for i in range(labels.numClasses) : numPatterns += labels.classSize[i] #pylab.figtext(0.05, float(numPatterns) / len(labels), labels.classLabels[i]) #pylab.figtext(float(numPatterns) / len(labels), 0.05, labels.classLabels[i]) pylab.axhline(numPatterns, color = 'black', linewidth = 1) pylab.axvline(numPatterns, color = 'black', linewidth = 1) pylab.axis([0, len(labels), 0, len(labels)]) if fileName is not None : pylab.savefig(fileName) pylab.close()
def hist(nndist, **kwds): if 'output' in kwds: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt # handle formatting keywords linewidth = kwds.get('linewidth', 3) #plt.rc('text', usetex=True) plt.rc('font', family='serif') n, bins, patches = plt.hist(nndist, normed=True, bins=100) width = bins[1] - bins[0] ax1 = plt.gca() ax2 = plt.twinx() ax2.plot(bins[:-1], width*np.cumsum(n), 'r-', linewidth=linewidth) ax2.set_ylim(top=1.0) tics = ax1.get_yticks(); ax1.set_yticks(tics[1:]) tics = ax2.get_yticks(); ax2.set_yticks(tics[1:]) ax1.set_xlabel(r"d ($\mu$m)") ax1.set_ylabel(r"PDF") ax2.set_ylabel(r"CDF", color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') # check scalar descriptors median_dist = np.median(nndist) ax1.axvline(median_dist, color='gray', linewidth=linewidth) # handle keywords if 'title' in kwds: plt.title(kwds['title']) if 'output' in kwds: plt.draw() plt.savefig(kwds['output']) else: plt.show()
def screeplot(self, type="barplot", **kwargs): """ Produce the scree plot :param type: type of plot. "barplot" and "lines" currently supported :param show: if False, the plot is not shown. matplotlib show method is blocking. :return: None """ # check for matplotlib. exit if absent. try: imp.find_module('matplotlib') import matplotlib if 'server' in kwargs.keys() and kwargs['server']: matplotlib.use('Agg', warn=False) import matplotlib.pyplot as plt except ImportError: print "matplotlib is required for this function!" return variances = [s**2 for s in self._model_json['output']['importance'].cell_values[0][1:]] plt.xlabel('Components') plt.ylabel('Variances') plt.title('Scree Plot') plt.xticks(range(1,len(variances)+1)) if type == "barplot": plt.bar(range(1,len(variances)+1), variances) elif type == "lines": plt.plot(range(1,len(variances)+1), variances, 'b--') if not ('server' in kwargs.keys() and kwargs['server']): plt.show()
def setUpClass(cls): try: import matplotlib as mpl mpl.use("Agg", warn=False) except ImportError: import nose raise nose.SkipTest("matplotlib not installed")
def testTelescope(self): import matplotlib matplotlib.use('AGG') import matplotlib.mlab as ml import pylab as pl import time w0 = 8.0 k = 2*np.pi/3.0 gb = GaussianBeam(w0, k) lens = ThinLens(150, 150) gb2 = lens*gb self.assertAlmostEqual(gb2._z0, gb._z0 + 2*150.0) lens2 = ThinLens(300, 600) gb3 = lens2*gb2 self.assertAlmostEqual(gb3._z0, gb2._z0 + 2*300.0) self.assertAlmostEqual(gb._w0, gb3._w0/2.0) z = np.arange(0, 150) z2 = np.arange(150, 600) z3 = np.arange(600, 900) pl.plot(z, gb.w(z, k), z2, gb2.w(z2, k), z3, gb3.w(z3, k)) pl.grid() pl.xlabel('z') pl.ylabel('w') pl.savefig('testTelescope1.png') time.sleep(0.1) pl.close('all')
def plot_scatter_iamondb_example(X, title=None, index=None, ax=None, equal=True, save=True): if save: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt if ax is None: f, ax = plt.subplots() down = np.where(X[:, 0] == 0)[0] up = np.where(X[:, 0] == 1)[0] ax.scatter(X[down, 1], X[down, 2], color="steelblue") ax.scatter(X[up, 1], X[up, 2], color="darkred") ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) if equal: ax.set_aspect('equal') if title is not None: plt.title(title) if ax is None: if not save: plt.show() else: if index is None: t = time.time() else: t = index plt.savefig("scatter_%i.png" % t)
def __init__(self, controllers, recipelist, server=myserver.myserver(host="0.0.0.0", port=8080)): self.count = 0 self.wapp = Bottle() self.controllers = controllers self.recipelist = recipelist self.server = server self.stages = {} self.runningRecipeName = "" self.selectedRecipeName = "" self.recipeObject = None self.switchdict = {"lights": True, "camera": False, "sound": True} matplotlib.use("Agg") # Routing statements self.wapp.route("/status", "GET", self.statusPage) self.wapp.route("/", "GET", self.indexPage) self.wapp.route("/start", "GET", self.commandPage) self.wapp.route("/start", "POST", self.doCommand) self.wapp.route("/recipelist", "GET", self.recipeliststatusPage) self.wapp.route("/recipelist", "POST", self.dorecipeliststatus) self.wapp.route("/debugStages", "GET", self.debugStages) self.wapp.route("/readrecipes", "GET", self.getTestRecipeList) self.wapp.route("/switchlist", "GET", self.switchliststatusPage) self.wapp.route("/switchlist", "POST", self.doswitchliststatus) self.wapp.route("/temp", "GET", self.tempPage) self.wapp.route("/ingredients", "GET", self.ingredientsPage) self.wapp.route("/static/<filename>", "GET", self.server_static) self.s2b = stages2beer.s2b(controllers, self.stages) self.dl = ctrl.datalogger(controllers)
def _savePlot(self, data, filename): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot(data) plt.savefig(filename)
def plot_lines_iamondb_example(X, title=None, index=None, ax=None, equal=True, save=True): if save: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt if ax is None: f, ax = plt.subplots() points = list(np.where(X[:, 0] > 0)[0]) start_points = [0] + points stop_points = points + [len(X)] ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) for start, stop in zip(start_points, stop_points): # Hack to actually separate lines... ax.plot(X[start + 2:stop, 1], X[start + 2:stop, 2], color="black") if equal: ax.set_aspect('equal') if title is not None: plt.title(title) if ax is None: if not save: plt.show() else: if index is None: t = time.time() else: t = index plt.savefig("lines_%i.png" % t)
def saveDebug_pyresample(weight_sum, filename): """ Save image for debugging onto map with grid and coastlines using pyresample """ import matplotlib matplotlib.use('AGG', warn=False) from pyresample import plot import matplotlib.pyplot as plt import matplotlib.cm as cm new_image = np.array(255.0 * weight_sum / np.max(weight_sum), 'uint8') bmap = plot.area_def2basemap(pc(Satellites.outwidth, Satellites.outheight), resolution='c') bmap.drawcoastlines(linewidth=0.2, color='red') bmap.drawmeridians(np.arange(-180, 180, 10), linewidth=0.2, color='red') bmap.drawparallels(np.arange(-90, 90, 10), linewidth=0.2, color='red') bmap.imshow(new_image, origin='upper', vmin=0, vmax=255, cmap=cm.Greys_r) # @UndefinedVariable # plt.show() i = datetime.datetime.utcnow() plt.text(0, -75, "%s UTC" % i.isoformat(), color='green', size=15, horizontalalignment='center') plt.savefig(filename, bbox_inches='tight', pad_inches=0, dpi=400) plt.close()
def activate_matplotlib(backend): """Activate the given backend and set interactive to True.""" import matplotlib if backend.startswith('module://'): # Work around bug in matplotlib: matplotlib.use converts the # backend_id to lowercase even if a module name is specified! matplotlib.rcParams['backend'] = backend else: matplotlib.use(backend) matplotlib.interactive(True) # This must be imported last in the matplotlib series, after # backend/interactivity choices have been made import matplotlib.pylab as pylab # XXX For now leave this commented out, but depending on discussions with # mpl-dev, we may be able to allow interactive switching... #import matplotlib.pyplot #matplotlib.pyplot.switch_backend(backend) pylab.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
def make_surface_plots(con_image,reg_file,subject_id,thr,sd): import matplotlib matplotlib.use('Agg') import os def make_image(zstat_path,bbreg_path): name_path = os.path.join(os.getcwd(),os.path.split(zstat_path)[1]+'_reg_surface.mgh') systemcommand ='mri_vol2surf --mov %s --reg %s --hemi lh --projfrac-max 0 1 0.1 --o %s --out_type mgh --sd %s'%(zstat_path,bbreg_path,name_path, sd) print systemcommand os.system(systemcommand) return name_path def make_brain(subject_id,image_path): from surfer import Brain hemi = 'lh' surface = 'inflated' brain = Brain(subject_id, hemi, surface) brain.add_overlay(image_path,min=thr) outpath = os.path.join(os.getcwd(),os.path.split(image_path)[1]+'_surf.png') brain.save_montage(outpath) return outpath surface_ims = [] surface_mgzs = [] for con in con_image: surf_mgz = make_image(format(con),reg_file) surface_mgzs.append(surf_mgz) surface_ims.append(make_brain(subject_id,surf_mgz)) return surface_ims, surface_mgzs
def ensure_pyplot(self): """ Ensures that pyplot has been imported into the embedded IPython shell. Also, makes sure to set the backend appropriately if not set already. """ # We are here if the @figure pseudo decorator was used. Thus, it's # possible that we could be here even if python_mplbackend were set to # `None`. That's also strange and perhaps worthy of raising an # exception, but for now, we just set the backend to 'agg'. if not self._pyplot_imported: if 'matplotlib.backends' not in sys.modules: # Then ipython_matplotlib was set to None but there was a # call to the @figure decorator (and ipython_execlines did # not set a backend). #raise Exception("No backend was set, but @figure was used!") import matplotlib matplotlib.use('agg') # Always import pyplot into embedded shell. self.process_input_line('import matplotlib.pyplot as plt', store_history=False) self._pyplot_imported = True
def create_cdf_fig(in_file, out_file, title): min_y = [] avg_y = [] max_y = [] with open(in_file ,'r') as dat: for line in dat: if len(line) > 0: sp = line.split(' ') if len(sp) < 4: continue min_y.append(float(sp[1])) avg_y.append(float(sp[2])) max_y.append(float(sp[3])) min_x, min__y = get_cdf(min_y) avg_x, avg__y = get_cdf(avg_y) max_x, max__y = get_cdf(max_y) ax = plt.subplot(1, 1, 1) plt.plot(min_x, min__y, label="Min") plt.plot(avg_x, avg__y, label="Avg") plt.plot(max_x, max__y, label="Max") matplotlib.use('Agg') plt.legend(loc='upper left') plt.xlabel("Fraction") plt.ylabel("RTT (ms)") plt.title(title) plt.savefig(out_file) plt.clf()
def _setup_matplotlib(self): # If we don't have matplotlib installed don't bother continuing try: import matplotlib except ImportError: return # Make sure custom backends are available in the PYTHONPATH rootdir = os.environ.get('ZEPPELIN_HOME', os.getcwd()) mpl_path = os.path.join(rootdir, 'interpreter', 'lib', 'python') if mpl_path not in sys.path: sys.path.append(mpl_path) # Finally check if backend exists, and if so configure as appropriate try: matplotlib.use('module://backend_zinline') import backend_zinline # Everything looks good so make config assuming that we are using # an inline backend self._displayhook = backend_zinline.displayhook self.configure_mpl(width=600, height=400, dpi=72, fontsize=10, interactive=True, format='png', context=self.z) except ImportError: # Fall back to Agg if no custom backend installed matplotlib.use('Agg') warnings.warn("Unable to load inline matplotlib backend, " "falling back to Agg")
def plot_dist_matrix(matrix, fasta_names, heatmap_out, dendrogram_out): """Cluster the distance matrix hierarchically and plot using seaborn. Average linkage method is used.""" # Load required modules for plotting import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from scipy.cluster.hierarchy import dendrogram, linkage # Create pdm = pd.DataFrame(matrix, index=fasta_names, columns=fasta_names) # Plot heatmap figsizex = max(10, len(fasta_names) / 4) clustergrid = sns.clustermap(pdm, metric='euclidean', method='average', figsize=(figsizex, figsizex)) clustergrid.savefig(heatmap_out) # Plot dendrogram sns.set_style('white') figsizey = max(10, len(fasta_names) / 8) f, ax = plt.subplots(figsize=(figsizex, figsizey)) link = linkage(pdm, metric='euclidean', method='average') dendrogram(link, labels=pdm.index, ax=ax) no_spine = {'left': True, 'bottom': True, 'right': True, 'top': True} sns.despine(**no_spine) plt.xticks(rotation=90) f.tight_layout() plt.savefig(dendrogram_out)
def plot(self, path, only=None, title=None): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec _only = set(only) if only is not None else set(self.ssmap.values()) rmap = dict([(v,k) for (k,v) in self.ssmap.iteritems()]) only = set([rmap.get(name) for name in _only]) stats = self.stats() xaxis = np.array(sorted(stats.keys())) totals = np.zeros(len(xaxis)) ss_perc = collections.defaultdict(lambda: np.zeros(len(xaxis))) for i, x in enumerate(xaxis): total = sum(stats[x].values()) totals[i] = total for ss, count in stats[x].iteritems(): if ss in only: name = ss else: name = 'other' ss_perc[name][i] += 100 * count / float(total) self.colormap['other'] = 'black' self.ssmap['other'] = 'other' xaxis /= 10.**3 # convert to ns gs = gridspec.GridSpec(2, 1, hspace=0, height_ratios=[1,10]) # frame counts plt.subplot(gs[0]) plt.title(title) ax = plt.gca() plt.bar(xaxis, totals, 1, color='grey', alpha=.5) ax.yaxis.tick_right() ax.yaxis.set_label_position('right') plt.ylabel('#') ax.yaxis.set_major_locator(plt.MaxNLocator(2)) ax.xaxis.set_visible(False) # ax.spines['bottom'].set_visible(False) # ax.xaxis.set_ticks_position('none') # aggregate SS data plt.subplot(gs[1]) for ss in ss_perc.keys(): color = self.colormap[ss] color = color if not color == '#FFFFFF' else 'black' style = ':' if color is 'black' else '-' plt.plot(xaxis, ss_perc[ss], linestyle=style, color=color, label=self.ssmap[ss], lw=3, alpha=.6) plt.ylabel('%') plt.xlabel('Time (ns)') ax = plt.gca() # ax.tick_params('x', labeltop='off') # ax.spines['top'].set_visible(False) # ax.xaxis.set_ticks_position('none') plt.legend(loc='best', fontsize=9, frameon=False, ncol=len(self.ssmap)/2) plt.savefig(path, bbox_inches='tight')
def setup(): # The baseline images are created in this locale, so we should use # it during all of the tests. import locale import warnings from matplotlib.backends import backend_agg, backend_pdf, backend_svg try: locale.setlocale(locale.LC_ALL, str('en_US.UTF-8')) except locale.Error: try: locale.setlocale(locale.LC_ALL, str('English_United States.1252')) except locale.Error: warnings.warn( "Could not set locale to English/United States. " "Some date-related tests may fail") use('Agg', warn=False) # use Agg backend for these tests # These settings *must* be hardcoded for running the comparison # tests and are not necessarily the default values as specified in # rcsetup.py rcdefaults() # Start with all defaults set_font_settings_for_testing()
def __init__(self,master,title): Toplevel.__init__(self,master) self.master = master from __init__ import MATPLOTLIB_BACKEND if MATPLOTLIB_BACKEND != None: print "manipulator: Setting matplotlib backend to \"TkAgg\"." import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from matplotlib import pyplot self.title(title) self.resizable(True,True) self.fig = pyplot.figure() pyplot.ion() self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1) self.update() self.experiments = []
def matplotAnimationLibMovie(): # Use matplotlib's animation library to directly output an mp4. import numpy as np import matplotlib matplotlib.use('TKAgg') from matplotlib import pyplot as plt from matplotlib import animation def update_line(num, data, line): line.set_data(data[...,:num]) return line, fig1 = plt.figure() data = np.random.rand(2, 25) l, = plt.plot([], [], 'r-') plt.xlim(0, 1) plt.ylim(0, 1) plt.xlabel('x') plt.title('test') line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l), interval=50, blit=True) line_ani.save('outLines.mp4') fig2 = plt.figure() x = np.arange(-9, 10) y = np.arange(-9, 10).reshape(-1, 1) base = np.hypot(x, y) ims = [] for add in np.arange(15): ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),)) im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000, blit=True) im_ani.save('outSurface.mp4', metadata={'artist':'Guido'})
def run_tests(self): import matplotlib matplotlib.use('agg') import nose from matplotlib.testing.noseclasses import KnownFailure from matplotlib import default_test_modules as testmodules from matplotlib import font_manager import time # Make sure the font caches are created before starting any possibly # parallel tests if font_manager._fmcache is not None: while not os.path.exists(font_manager._fmcache): time.sleep(0.5) plugins = [KnownFailure] # Nose doesn't automatically instantiate all of the plugins in the # child processes, so we have to provide the multiprocess plugin # with a list. from nose.plugins import multiprocess multiprocess._instantiate_plugins = plugins if self.omit_pep8: testmodules.remove('matplotlib.tests.test_coding_standards') elif self.pep8_only: testmodules = ['matplotlib.tests.test_coding_standards'] nose.main(addplugins=[x() for x in plugins], defaultTest=testmodules, argv=['nosetests'] + self.test_args, exit=True)
def create_figures(data): import numpy as np print "# Creating figure ..." # prepare matplotlib import matplotlib matplotlib.rc("font",**{"family":"sans-serif"}) matplotlib.rcParams.update({'font.size': 14}) matplotlib.rc("text", usetex=True) matplotlib.use("PDF") import matplotlib.pyplot as plt # KSP plt.figure(1) n, bins, patches = plt.hist(data[:, 1], bins = 50, fc = "k", ec = "w") plt.xticks(range(300, 1001, 100), range(300, 1001, 100)) plt.yticks(range(0, 17, 2), range(0, 17, 2)) plt.xlabel("Model years") plt.ylabel("Occurrence") plt.savefig("parameterrange-ksp", bbox_inches = "tight") # SNES plt.figure(2) n, bins, patches = plt.hist(data[:, 0], bins = 50, fc = "k", ec = "w") plt.xticks(range(5, 46, 5), range(5, 46, 5)) plt.yticks(range(0, 15, 2), range(0, 15, 2)) plt.xlabel("Newton steps") plt.ylabel("Occurrence") plt.savefig("parameterrange-snes", bbox_inches = "tight")
def begin(self): # # We monkey-patch javabridge.start_vm here in order to # set up the ImageJ event bus (actually # org.bushe.swing.event.ThreadSafeEventService) to not start # its cleanup thread which semi-buggy hangs around forever # and prevents Java from exiting. # def patch_start_vm(*args, **kwargs): jvm_args = list(args[0]) + [ "-Dloci.bioformats.loaded=true", "-Djava.util.prefs.PreferencesFactory="+ "org.cellprofiler.headlesspreferences"+ ".HeadlessPreferencesFactory"] # # Find the ij1patcher # if hasattr(sys, 'frozen') and sys.platform == 'win32': root = os.path.dirname(sys.argv[0]) else: root = os.path.dirname(__file__) jardir = os.path.join(root, "imagej", "jars") patchers = sorted([ x for x in os.listdir(jardir) if x.startswith("ij1-patcher") and x.endswith(".jar")]) if len(patchers) > 0: jvm_args.append( "-javaagent:%s=init" % os.path.join(jardir, patchers[-1])) result = start_vm(jvm_args, *args[1:], **kwargs) if javabridge.get_env() is not None: try: event_service_cls = javabridge.JClassWrapper( "org.bushe.swing.event.ThreadSafeEventService") event_service_cls.CLEANUP_PERIOD_MS_DEFAULT = None except: pass return result patch_start_vm.func_globals["start_vm"] = javabridge.start_vm javabridge.start_vm = patch_start_vm if "CP_EXAMPLEIMAGES" in os.environ: self.temp_exampleimages = None else: self.temp_exampleimages = tempfile.mkdtemp(prefix="cpexampleimages") if "CP_TEMPIMAGES" in os.environ: self.temp_images = None else: self.temp_images = tempfile.mkdtemp(prefix="cptempimages") # # Set up matplotlib for WXAgg if in frozen mode # otherwise it looks for TK which isn't there # if hasattr(sys, 'frozen'): import matplotlib matplotlib.use("WXAgg") try: from ilastik.core.jobMachine import GLOBAL_WM GLOBAL_WM.set_thread_count(1) except: pass
def footprint_area(cat,ngal=1,mask=None,nside=4096,nest=True,label=''): import healpy as hp import matplotlib matplotlib.use ('agg') import matplotlib.pyplot as plt # plt.style.use('/home/troxel/SVA1/SVA1StyleSheet.mplstyle') from matplotlib.colors import LogNorm import pylab mask=CatalogMethods.check_mask(cat.coadd,mask) if not hasattr(cat, 'pix'): cat.pix=CatalogMethods.radec_to_hpix(cat.ra,cat.dec,nside=nside,nest=True) area=hp.nside2pixarea(nside)*(180./np.pi)**2 print 'pixel area (arcmin)', area*60**2 mask1=np.bincount(cat.pix[mask])>ngal print 'footprint area (degree)', np.sum(mask1)*area pix=np.arange(len(mask1))[mask1] print pix tmp=np.zeros((12*nside**2), dtype=[('hpix','int')]) tmp['hpix'][pix.astype(int)]=1 print tmp['hpix'][pix.astype(int)] fio.write('footprint_hpix'+label+'.fits.gz',tmp,clobber=True) tmp2=np.zeros(12*nside**2) tmp2[tmp.astype(int)]=1 hp.cartview(tmp2,nest=True) plt.savefig('footprint_hpix'+label+'.png') plt.close() return
import sys import keras import time from keras.models import load_model #from keras.layers import Dense, Activation, Dropout, Conv2D, Conv2DTranspose, MaxPool2D, Flatten, Reshape, Input, add, subtract, MaxPooling2D, AveragePooling2D, UpSampling2D, average, Concatenate, concatenate, LeakyReLU, Lambda, GlobalAveragePooling2D from keras.layers.normalization import BatchNormalization from keras.utils.vis_utils import plot_model from keras import backend as K from keras import optimizers, regularizers from keras.optimizers import Adam from keras.callbacks import TensorBoard import tensorflow as tf import numpy as np import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable, ImageGrid ########### from glob import glob import os from shutil import copyfile ######################################### ######################################### batch_size = 16 # specification of the problem size img_rows = 16
import os import numpy as np from scipy.interpolate import interp1d import matplotlib matplotlib.use('Agg') import pylab as pl import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib as mpl import matplotlib.patheffects as PathEffects import matplotlib.gridspec as gridspec import glob from matplotlib import rc rc('font', **{'family': 'serif', 'serif': ['Times', 'Palatino']}) rc('text', usetex=True) mpl.rcParams['xtick.major.size'] = 8 mpl.rcParams['ytick.major.size'] = 8 mpl.rcParams['xtick.labelsize'] = 18 mpl.rcParams['ytick.labelsize'] = 18 kval = 0.1 Nbrane = 1e7 pressFac = 1e-6 eCDM = 0.00 Fname = 'StandardUniverse_FieldEvolution_{:.4e}.dat'.format(kval) Svname = 'StandardField_kval_{:.4e}.pdf'.format(kval) #Fname = 'MultiBrane_FieldEvolution_{:.4e}_Nbrane_{:.0e}_PressFac_{:.2e}_eCDM_{:.2e}.dat'.format(kval, Nbrane, pressFac, eCDM) #Svname = 'MultiverseField_kval_{:.4e}_Nbrane_{:.0e}_PressFac_{:.2e}_eCDM_{:.2e}.pdf'.format(kval, Nbrane, pressFac, eCDM)
import reedsolo import random import matplotlib matplotlib.use("Pdf") import matplotlib.pyplot as plt import math # Factorial of a number def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1)) # Calculation of packet decoding error probability def PDEP(p, N, nk): min = (nk/2)+1 pdep=0 for k in range(min, N+1): # Calculate PDP with the formula from literature pdep += (float(factorial(N))/(factorial(k)*factorial(N-k)))*(p**k)*((1-p)**(N-k)) return pdep # Iteration of the best N-K values def NK(p, K): arr = [0] * 9 for i in range(9): nk = (i+1)*2 arr[i] += (float(K)/(nk+K)) * (1-PDEP(p, (K+nk), nk)) return (arr.index(max(arr))+1)*2 # Init reedsolo.init_tables(0x11d)
import matplotlib matplotlib.use('TkAgg') from matplotlib.collections import PolyCollection import matplotlib.pyplot as plt import numpy as np # Fixing random state for reproducibility np.random.seed(19680801) def polygon_under_graph(xlist, ylist): """ Construct the vertex list which defines the polygon filling the space under the (xlist, ylist) line graph. Assumes the xs are in ascending order. """ return [(xlist[0], 0.), *zip(xlist, ylist), (xlist[-1], 0.)] ax = plt.figure().add_subplot(projection='3d') # Make verts a list such that verts[i] is a list of (x, y) pairs defining # polygon i. verts = [] # Set up the x sequence xs = np.linspace(0., 10., 26) # The ith polygon will appear on the plane y = zs[i] zs = range(4) for i in zs:
print(M + a[:, np.newaxis]) #(3,2) #these rules apply to all binary ufuncs print(np.logaddexp(M, a[:, np.newaxis])) ##Broadcasting in practice print("#center an array") X = np.random.random((10, 3)) Xmean = X.mean(0) print(Xmean) X_centered = X - Xmean print(X_centered.mean(0)) ##plotting a 2d function #x & y have 50 steps from 0 to 5 x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 50)[:, np.newaxis] z = np.sin(x)**10 + np.cos(10 + y * x) * np.cos(x) import matplotlib matplotlib.use('TKagg') import matplotlib.pyplot as plt plt.imshow(z, origin='lower', extent=[0, 5, 0, 5], cmap='viridis') plt.colorbar() plt.show()
def pytest_configure(config): matplotlib.use('agg', force=True) matplotlib._called_from_pytest = True matplotlib._init_tests()
import os import matplotlib as mpl import numpy as np from queue import Queue from tensor2tensor.bin import t2t_trainer # pylint: disable=unused-import from tensor2tensor.layers import common_video from tensor2tensor.utils import registry from tensor2tensor.utils import trainer_lib from tensor2tensor.utils import usr_dir import tensorflow.compat.v1 as tf from tensorflow.compat.v1 import estimator as tf_estimator mpl.use("Agg") flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_integer("num_steps", 100, "Number of prediction steps.") flags.DEFINE_integer("fps", 10, "Generated gif FPS.") flags.DEFINE_string("output_gif", None, "Output path to save the gif.") def main(_): tf.logging.set_verbosity(tf.logging.INFO) trainer_lib.set_random_seed(FLAGS.random_seed) usr_dir.import_usr_dir(FLAGS.t2t_usr_dir) # Create hparams hparams = trainer_lib.create_hparams(FLAGS.hparams_set,
# modificação saídas horárias NOV2018 # # Autora: 1T(RM2-T) Andressa D'Agostini # # Ultima modificação: 1T(T) Liana 12FEV2021 # #-----------------------------------------------------# from matplotlib import pyplot as plt from matplotlib import colors from netCDF4 import Dataset import datetime, time import os, sys import matplotlib.pylab as plab import pyresample as pr import numpy as np import math import matplotlib as mpl mpl.use('Agg') # Force matplotlib to not use any Xwindows backend. import datetime, time if len(sys.argv) < 3: print('+------------Utilização-------+') print(' ') print(' ww3_tabela_Drake.py mod HH ') print(' ') print(' ex: '+sys.argv[0]+' gfs 00 ') print('+-----------------------------+') sys.exit(1) print('Inicio') mod = sys.argv[1]
@author: Levan Tsinadze """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import os import re import editdistance from keras import backend as K import keras.callbacks from keras.preprocessing import image import matplotlib as mpl mpl.use('Agg') import pylab from scipy import ndimage import cairocffi as cairo from geocr import font_storadge as _fonts from geocr.character_translator import translate_to_geo from geocr.cnn_files import training_file import numpy as np _files = training_file() OUTPUT_DIR = _files.model_dir IMG_DIR = _files.join_and_init_path(_files.data_root, 'images') # this creates larger "blotches" of noise which look
# Tasker Menu Bar class import tkinter as tk from tkinter import ttk import math import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import numpy as np from tkinter import ttk from tkinter.filedialog import askopenfilename from tkinter import messagebox import webbrowser from PIL import ImageTk, Image, ImageDraw import PIL from datetime import datetime, timedelta from spacecraft2 import spacecraft from multicolumnlistbox import MultiListbox from TaskerPoint import Point import MenuBar class TaskerMenuBar(tk.Frame): """ Creates the menubar for use in the Tasker GUI. Builds each of the menu items, and attaches functions to each. :ivar Application master: Parent application of the menu bar :ivar subscribers: List of subscribers
import matplotlib matplotlib.use('WXAgg') import pylab as pl import numpy as np from mayavi import mlab from mayavi.core.ui.mayavi_scene import MayaviScene def get_world_to_view_matrix(mlab_scene): """returns the 4x4 matrix that is a concatenation of the modelview transform and perspective transform. Takes as input an mlab scene object.""" if not isinstance(mlab_scene, MayaviScene): raise TypeError('argument must be an instance of MayaviScene') # The VTK method needs the aspect ratio and near and far clipping planes # in order to return the proper transform. So we query the current scene # object to get the parameters we need. scene_size = tuple(mlab_scene.get_size()) clip_range = mlab_scene.camera.clipping_range aspect_ratio = float(scene_size[0])/float(scene_size[1]) # this actually just gets a vtk matrix object, we can't really do anything with it yet vtk_comb_trans_mat = mlab_scene.camera.get_composite_projection_transform_matrix( aspect_ratio, clip_range[0], clip_range[1]) # get the vtk mat as a numpy array np_comb_trans_mat = vtk_comb_trans_mat.to_array()
def plotter(fdict): """ Go """ import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import matplotlib.colors as mpcolors ctx = get_autoplot_context(fdict, get_description()) station = ctx['station'] gddbase = ctx['gddbase'] base = ctx['base'] ceil = ctx['ceil'] nt = NetworkTable(ctx['network']) today = ctx['date'] byear = nt.sts[station]['archive_begin'].year eyear = today.year + 1 pgconn = get_dbconn('coop') cursor = pgconn.cursor() table = "alldata_%s" % (station[:2],) cursor.execute("""SELECT year, extract(doy from day), gddxx(%s, %s, high,low), low from """+table+""" where station = %s and year > %s and day < %s """, (base, ceil, station, byear, today)) gdd = np.zeros((eyear-byear, 366), 'f') freezes = np.zeros((eyear-byear), 'f') freezes[:] = 400.0 for row in cursor: gdd[int(row[0]) - byear, int(row[1]) - 1] = row[2] if row[1] > 180 and row[3] < 32 and row[1] < freezes[row[0] - byear]: freezes[int(row[0]) - byear] = row[1] for i, freeze in enumerate(freezes): gdd[i, int(freeze):] = 0.0 idx = int(today.strftime("%j")) - 1 apr1 = int(datetime.datetime(2000, 4, 1).strftime("%j")) - 1 jun30 = int(datetime.datetime(2000, 6, 30).strftime("%j")) - 1 sep1 = int(datetime.datetime(2000, 9, 1).strftime("%j")) - 1 oct31 = int(datetime.datetime(2000, 10, 31).strftime("%j")) - 1 # Replace all years with the last year's data scenario_gdd = gdd * 1 scenario_gdd[:-1, :idx] = gdd[-1, :idx] # store our probs probs = np.zeros((oct31 - sep1, jun30 - apr1), 'f') scenario_probs = np.zeros((oct31 - sep1, jun30 - apr1), 'f') rows = [] for x in range(apr1, jun30): for y in range(sep1, oct31): sums = np.where(np.sum(gdd[:-1, x:y], 1) >= gddbase, 1, 0) probs[y-sep1, x-apr1] = sum(sums) / float(len(sums)) * 100.0 sums = np.where(np.sum(scenario_gdd[:-1, x:y], 1) >= gddbase, 1, 0) scenario_probs[y-sep1, x-apr1] = ( sum(sums) / float(len(sums)) * 100.0) rows.append(dict(x=x, y=y, prob=probs[y-sep1, x-apr1], scenario_probs=scenario_probs[y-sep1, x-apr1])) df = pd.DataFrame(rows) probs = np.where(probs < 0.1, -1, probs) scenario_probs = np.where(scenario_probs < 0.1, -1, scenario_probs) (fig, ax) = plt.subplots(1, 2, sharey=True, figsize=(8, 6)) cmap = plt.get_cmap('jet') cmap.set_under('white') norm = mpcolors.BoundaryNorm(np.arange(0, 101, 5), cmap.N) ax[0].imshow(np.flipud(probs), aspect='auto', extent=[apr1, jun30, sep1, oct31], interpolation='nearest', vmin=0, vmax=100, cmap=cmap, norm=norm) ax[0].grid(True) ax[0].set_title("Overall Frequencies") ax[0].set_xticks((91, 106, 121, 136, 152, 167)) ax[0].set_ylabel("Growing Season End Date") ax[0].set_xlabel("Growing Season Begin Date") ax[0].set_xticklabels(('Apr 1', '15', 'May 1', '15', 'Jun 1', '15')) ax[0].set_yticks((244, 251, 258, 265, 274, 281, 288, 295, 305)) ax[0].set_yticklabels(('Sep 1', 'Sep 8', 'Sep 15', 'Sep 22', 'Oct 1', 'Oct 8', 'Oct 15', 'Oct 22', 'Nov')) res = ax[1].imshow(np.flipud(scenario_probs), aspect='auto', extent=[apr1, jun30, sep1, oct31], interpolation='nearest', vmin=0, vmax=100, cmap=cmap, norm=norm) ax[1].grid(True) ax[1].set_title("Scenario after %s" % (today.strftime("%-d %B %Y"), )) ax[1].set_xticks((91, 106, 121, 136, 152, 167)) ax[1].set_xticklabels(('Apr 1', '15', 'May 1', '15', 'Jun 1', '15')) ax[1].set_xlabel("Growing Season Begin Date") fig.subplots_adjust(bottom=0.20, top=0.85) cbar_ax = fig.add_axes([0.05, 0.06, 0.85, 0.05]) fig.colorbar(res, cax=cbar_ax, orientation='horizontal') fig.text(0.5, 0.90, ("%s-%s %s GDDs\n" "Frequency [%%] of reaching %.0f GDDs (%.0f/%.0f) " "prior to first freeze" ) % (byear, eyear-1, nt.sts[station]['name'], gddbase, base, ceil), fontsize=14, ha='center') return fig, df
# Import packages import csv import cv2 import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt print("Matplotlib backend selected to allow plotting on AWS") import os import sklearn from sklearn.model_selection import train_test_split from keras.regularizers import l2, activity_l2 from keras.models import Sequential, load_model from keras.layers import Flatten, Dense, Lambda, Dropout, Activation from keras.callbacks import EarlyStopping, ModelCheckpoint from keras.layers.convolutional import Convolution2D, Cropping2D from keras.layers.pooling import MaxPooling2D from keras import optimizers from random import shuffle #Load samples samples = [] with open('./edata/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: samples.append(line) samples = samples[1:] #train_samples, validation_samples = train_test_split(samples, test_size=0.2) # Load lists of images and angles images, angles = [], []
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantid workbench. # # from __future__ import (absolute_import, division, print_function) import matplotlib matplotlib.use('Agg') # noqa: E402 import unittest from mantid.py3compat import mock from mantidqt.widgets.samplelogs.model import SampleLogsModel from mantidqt.widgets.samplelogs.presenter import SampleLogs from mantidqt.widgets.samplelogs.view import SampleLogsView class SampleLogsTest(unittest.TestCase): def setUp(self): self.view = mock.Mock(spec=SampleLogsView) self.view.get_row_log_name = mock.Mock(return_value="Speed5") self.view.get_selected_row_indexes = mock.Mock(return_value=[5]) self.view.get_exp = mock.Mock(return_value=1) self.model = mock.Mock(spec=SampleLogsModel) self.model.get_ws = mock.Mock(return_value='ws')
import matplotlib matplotlib.use('nbAgg') import numpy as np import matplotlib.pyplot as plt import example_utils def main(): fig, axes = example_utils.setup_axes() basic_bar(axes[0]) tornado(axes[1]) general(axes[2]) example_utils.title(fig, '"ax.bar(...)": Plot rectangles') fig.savefig('bar_example.png', facecolor='none') plt.show() def basic_bar(ax): y = [1, 3, 4, 5.5, 3, 2] err = [0.2, 1, 2.5, 1, 1, 0.5] x = np.arange(len(y)) ax.bar(x, y, yerr=err, color='lightblue', ecolor='black') ax.margins(0.05) ax.set_ylim(bottom=0) example_utils.label(ax, 'bar(x, y, yerr=e)')
import matplotlib matplotlib.use("PS") import numpy as np # linear algebra import modin.pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt # Matlab-style plotting import seaborn as sns color = sns.color_palette() sns.set_style("darkgrid") import warnings def ignore_warn(*args, **kwargs): pass warnings.warn = ignore_warn # ignore annoying warning (from sklearn and seaborn) from scipy import stats from scipy.stats import norm, skew # for some statistics pd.set_option( "display.float_format", lambda x: "{:.3f}".format(x)) # Limiting floats output to 3 decimal points train = pd.read_csv("train.csv") test = pd.read_csv("test.csv") train.head(5) test.head(5) print("The train data size before dropping Id feature is : {} ".format( train.shape)) print("The test data size before dropping Id feature is : {} ".format(
#!/usr/bin/python # -*-coding:Utf-8 -* import sys from utils import * import matplotlib matplotlib.use("Qt5Agg") from PyQt5 import QtWidgets from PyQt5.QtCore import * from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.widgets import RectangleSelector # Module for Spectrogram plotting import numpy as np import essentia.standard as es from essentia import array from scipy.fftpack import fft from scipy.signal import get_window import matplotlib.pyplot as plt from matplotlib.lines import Line2D from threading import Thread import time
# USAGE # python train_simple_nn.py --dataset animals --model output/simple_nn.model --label-bin output/simple_nn_lb.pickle --plot output/simple_nn_plot.png # set the matplotlib backend so figures can be saved in the background import matplotlib matplotlib.use("Agg") # import the necessary packages from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import SGD from imutils import paths import matplotlib.pyplot as plt import numpy as np import argparse import random import pickle import cv2 import os # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-d", "--dataset", required=True, help="path to input dataset of images") ap.add_argument("-m", "--model", required=True, help="path to output trained model") ap.add_argument("-l", "--label-bin", required=True, help="path to output label binarizer")
import os import tensorflow as tf import numpy as np from imageio import imread import matplotlib from src.flowlib import read_flow, flow_to_image matplotlib.use('TKAgg') import matplotlib.pyplot as plt _preprocessing_ops = tf.load_op_library( tf.resource_loader.get_path_to_datafile("./src/ops/build/preprocessing.so")) def display(img, c): plt.subplot(int('22' + str(c + 1))) plt.imshow(img[0, :, :, :]) def main(): """ .Input("image_a: float32") .Input("image_b: float32") .Attr("crop: list(int) >= 2") .Attr("params_a_name: list(string)") .Attr("params_a_rand_type: list(string)") .Attr("params_a_exp: list(bool)") .Attr("params_a_mean: list(float32)") .Attr("params_a_spread: list(float32)") .Attr("params_a_prob: list(float32)") .Attr("params_b_name: list(string)") .Attr("params_b_rand_type: list(string)")
## Toshihiro Tanizawa ## [email protected] ## began at 2016-06-15(Wed) 17:10:17 ## fixed grid() and pack() problem on 2016-06-21(Tue) 18:29:40 ## ## various bug fixes and updates by Steve Morgan on 3/28/2020 import matplotlib #System check added by Steve Morgan import platform #SM 3/28/2020 #if platform.system() == 'Windows': #SM 3/28/2020 backend = 'TkAgg' #SM 3/28/2020 #else: #SM 3/28/2020 # backend = 'Qt5Agg' #SM 3/28/2020 matplotlib.use(backend) #SM 3/28/2020 import matplotlib.pyplot as plt #SM 3/28/2020 ## version check added by Hiroki Sayama on 01/08/2019 import sys if sys.version_info[0] == 3: # Python 3 from tkinter import * from tkinter.ttk import Notebook else: # Python 2 from Tkinter import * from ttk import Notebook ## suppressing matplotlib deprecation warnings (especially with subplot) by Hiroki Sayama on 06/29/2020 import warnings warnings.filterwarnings("ignore", category = matplotlib.cbook.MatplotlibDeprecationWarning)
#------------------------------close_encounters.py-----------------------------# #------------------------------------------------------------------------------# #--------------------------Created by Mark Giovinazzi--------------------------# #------------------------------------------------------------------------------# #-This program was created for the purpose of recording parameters for systems-# #-containing both stars + planets every few iterations during close encounters-# #------------------------------------------------------------------------------# #---------------------------Date Created: 11/17/2017---------------------------# #------------------------Date Last Modified: 01/03/2018------------------------# #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# #-------------------------------Import Libraries-------------------------------# #------------------------------------------------------------------------------# import matplotlib; matplotlib.use('agg') # first set the proper backend import sys; sys.path.insert(0, 'GitHub/Tycho/src') # specify path to create.py #from create import planetary_systems # load planetary_systems in from create.py from amuse.lab import * from amuse.plot import * import numpy as np, matplotlib.pyplot as plt, pickle import os # Push everything off so that we can run this job first! sys.stdout.flush() # not sure if I need to have this?i #------------------------------------------------------------------------------# #------The following function supervises a collision system in generality------# #------------------------------------------------------------------------------# def run_collision(bodies, t_max, dt, identifier):
""" Load pp, plot and save """ import os, sys import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from matplotlib import rc from matplotlib.font_manager import FontProperties from matplotlib import rcParams from mpl_toolkits.basemap import Basemap rc('font', family = 'serif', serif = 'cmr10') rc('text', usetex=True) rcParams['text.usetex']=True rcParams['text.latex.unicode']=True rcParams['font.family']='serif' rcParams['font.serif']='cmr10' import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.cm as mpl_cm import numpy as np
#################################################### # Dependencies #################################################### import os.path import argparse, os import numpy as np from tqdm import trange from pathlib import Path import platform import matplotlib as mpl if os.environ.get("DLClight", default=False) == "True": mpl.use( "AGG" ) # anti-grain geometry engine #https://matplotlib.org/faq/usage_faq.html elif platform.system() == "Darwin": mpl.use("WxAgg") # TkAgg else: mpl.use("TkAgg") import matplotlib.pyplot as plt from deeplabcut.utils import auxiliaryfunctions, auxfun_multianimal, visualization from deeplabcut.utils.video_processor import ( VideoProcessorCV as vp, ) # used to CreateVideo from matplotlib.animation import FFMpegWriter from skimage.util import img_as_ubyte from skimage.draw import circle, line_aa def get_segment_indices(bodyparts2connect, all_bpts):
import sys sys.path.insert(0, './include') import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib import lines import sebcolour as sc # Set plotting defaults matplotlib.use('TkAgg') # cleaner likely to work fnt = {'family': 'DejaVu Sans', 'weight': 'regular', 'size': 14} matplotlib.rc('font', **fnt) sdata = np.genfromtxt('postproc/sensitivity_guide1.csv', delimiter=",", names=True) # Loop through data, making up 4 graphs for the different metrics F1, ((ax1, ax2, ax3, ax4)) = plt.subplots(1, 4, sharey=False, figsize=(9, 4)) # Have 5 angles and 5 gains (currently) honda = np.zeros([5, 5], dtype=float) sos = np.zeros([5, 5], dtype=float) area = np.zeros([5, 5], dtype=float) locn = np.zeros([5, 5], dtype=float) eta = np.zeros([5, 5], dtype=float) idx_p1 = { -34.0: int(0), -14.0: int(1),
gsa = getattr(self.grid_scanner, param) uia = getattr(self, param + '_view') uia.model().setStringList([str(x) for x in gsa]) def renew_axes_ui(self): n = int(self.num_axes.text()) self.grid_scanner.num_axes = n for param in ['axes', 'axes_names', 'size', 'step', 'init']: self.update_param(param) if __name__ == '__main__': import sys from nplab.instrument.stage import DummyStage import matplotlib matplotlib.use('Qt4Agg') from nplab.ui.mpl_gui import FigureCanvasWithDeferredDraw as FigureCanvas from matplotlib.figure import Figure import cProfile import pstats test = 'qt' if test == 'qt': template = GridScanQt else: template = GridScan class DummyGridScan(template): def __init__(self): super(DummyGridScan, self).__init__() self.estimated_step_time = 0.0005
from __future__ import division import praw import sys import prawcore import re import cPickle as pickle import datetime import numpy as np import os import requests import time import collections import operator import matplotlib as mpl mpl.use('agg') import matplotlib.pyplot as plt # read in USER_NAME, CLIENT_ID, CLIENT_SECRET, subreddit_name, movie_users_file non_movie_titles = [ 'Subreddit Suggestions', ] # movies where reviews have been parsed # these are movies that we will score against movie_to_guesses = {} # for specific summer contest movie_to_guesses_contest = {}
''' Created on Apr 20, 2012 @author: jeven ''' import matplotlib matplotlib.use("AGG") from matplotlib import pyplot as plt import numpy as np import TableIO from Config import * def PowerPlot(k, ps): """ Output a png image of the plot of the power spectrum after interpolation and extrapolation """ print " Producing Power Spectrum Plot" plt.clf() plt.title('Logarithmic Matter Power Spectrum') plt.grid(True) plt.xlabel(r'Wavenumber, $\log(k)$') plt.ylabel(r'Power, $\log[P(k)]$') linetypes = ['r-', 'b-', 'g-', 'm-', 'k-'] if len(config.WDM) + 1 > len(linetypes): print "WARNING: more power spectra (", len( config.WDM), ") than linetypes (", len( linetypes), "), some will be used twice."
import numpy as np import matplotlib matplotlib.use('pdf') import matplotlib.pyplot as plt K = 15 # A_t cf = 100 ch = 2 gamma = 0.95 cmax = 200 # max number of customers Amin = 1 Amax = 5 max_iter = 1e7 tol = 1e-7 T = 500 # p1 # enumeration def enumeration(K, cf, ch, max_iter, cmax, tol, Amin, Amax): Qfunc = np.array([[0.0 for _ in range(2)] for _ in range(cmax+5)]) # Q(s,a) Qfunc_prev = np.array([[0.0 for _ in range(2)] for _ in range(cmax+5)]) # Q(s,a) for t in range(T,-1,-1): for a in range(2): for s in range(cmax+1): s_prime = max(0, s - a*K) # next state before incoming customers rew = -(cf*a + ch*s) # expectation of max EQ = 0 # sample traj
# See the License for the specific language governing permissions and # limitations under the License. ## pix2pix caffe interference # cityscapes A to B #%% import package import argparse import caffe import cv2 import numpy as np import os import matplotlib matplotlib.use('PS') import matplotlib.pyplot as plt import skimage.io as io #%% define functions def norm_image(IMG): # output scale: [0,1] output = (IMG - np.min(IMG)) / (np.max(IMG) - np.min(IMG)) # normalize [0,255] output1 = output * 255 # assure integer 8bit output1 = output1.astype('uint8') return output1
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A set of functions that are used for visualization. These functions often receive an image, perform some visualization on the image. The functions do not return a value, instead they modify the image itself. """ import collections import functools # Set headless-friendly backend. import matplotlib; matplotlib.use('Agg') # pylint: disable=multiple-statements import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top import numpy as np import PIL.Image as Image import PIL.ImageColor as ImageColor import PIL.ImageDraw as ImageDraw import PIL.ImageFont as ImageFont import six import tensorflow as tf from object_detection.core import standard_fields as fields _TITLE_LEFT_MARGIN = 10 _TITLE_TOP_MARGIN = 10 STANDARD_COLORS = [