def gnuplot(f, *between): ''' Plot the function f within the optional limits *between ''' # Create an instance of the gnuplot class graph = Gnuplot() # Get the full file name and root_file_name (excluding extension) file_name, root_file_name = graph.file_name, graph.root_file_name # Plot the function graph.plot_function(f, *between) # Return a string / html representation of the graph return StrWithHtml('Image saved to ' + file_name, '''<img src="{}.svg" style="width: 100%" />'''.format(root_file_name))
def main(): """ Main interface """ parser = _create_parser() args = parser.parse_args() if len(sys.argv) == 1: parser.print_usage() parser.exit(status=1) elif args.countries: print("\n".join(map(str, data.countries()))) sys.exit() elif args.states: print("\n".join(map(str, data.states()))) sys.exit() region = data.read(args.region) if not region: print(f"Region '{args.region}' not found.") sys.exit(1) title = f"COVID-19 Infections ({region})" with tempfile.NamedTemporaryFile(mode="w") as datfile: for stats in region.daily_stats(): datfile.write(f"{stats.date}\t{stats.cases}\t{stats.avg}\n") datfile.flush() gnuplot = Gnuplot("./covid.gp", args.terminal, args.output) gnuplot.set_var("datfile", datfile.name) gnuplot.set_var("title", title) gnuplot.run()
def gnuplot(self, reg): ##################################################################### "plot with gnuplot" ##################################################################### if not self.__dict__.has_key('gp'): self.gp = Gnuplot() CQLRIO.DumpSamples('samples.dat', self.reg) if self.p.GetDimensions() == 1: CQLRIO.Distrib(reg) self.plot_to_file('distrib.dat', 100) self.gp.send('load "clop.gpi"') elif self.p.GetDimensions() == 2: CQLRIO.Distrib(reg) self.plot_to_file_2d('distrib.dat', 40) self.gp.send('load "samples2d.gpi"')
def _plot_non_consecutive_graph(self, graph_type): """TODO: Docstring for _plot_non_consecutive_graph. :returns: TODO """ cuts = Cut.all_cuts(self.cube) with open('output/detailed_output.csv', 'a', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow([graph_type]) writer.writerow(['filename', 'dependant', 'parameters']) for i, cut in enumerate(cuts): self.cube.populate_cut(cut) with Gnuplot() as plot: plot.output = "%s_cut_%d" % (graph_type, i) plot.xlabel = cut.dep plot.benchdata = self._format_data_for_gnuplot( cut, graph_type) plot.run() writer.writerow( [plot.output, cut.dep, cut.parameters.items()])
def plot( self, font_fname=None ) : plt = Gnuplot() plt.open() plt.xlabel( "Time (s)" ) plt.ylabel( "$$$ spent (estimate)" ) plt.set_style( "linespoints" ) plots = [] labels = [] for i in range( self.nplayers ) : player = self.kwr.players[i] if not player.is_player() : continue pair = self.split( self.spents[ i ] ) if not pair : continue ts, costs = pair plt.plot( ts, costs ) labels.append( sanitize_name( player, xor=True ) ) plt.legend( labels ) plt.show() plt.close()
def plot_unit_distribution( self ) : color = 1 for i in range( self.nplayers ) : player = self.kwr.players[i] if not player.is_player() : continue plt = Gnuplot() plt.open() histo = self.units[ i ] plt.write( 'set style fill solid\n' ) plt.write( 'set key off\n' ) plt.write( 'set boxwidth 0.5\n' ) plt.write( 'set title "%s"\n' % sanitize_name( player ) ) n_kinds = len( histo ) plt.write( 'set xrange[-1:%d]\n' % n_kinds ) # set X tics, 45 degress rotated. cmd = "set xtics (" i = 0 items = [] for unit, cnt in histo.items() : items.append( '"%s" %d' % ( unit, i ) ) i += 1 cmd += ", ".join( items ) cmd += ") rotate by 45 right\n" plt.write( cmd ) # write values on the graph (labels) #i = 0 #for unit, cnt in histo.items() : # cmd = 'set label "%d" at %d,%d\n' % ( cnt, i, cnt+5 ) # plt.write( cmd ) # i += 1 # y range, manually. max_cnt = 0 for unit, cnt in histo.items() : max_cnt = max( max_cnt, cnt ) print( max_cnt ) plt.write( "set yrange [0:%f]\n" % ( 1.2*max_cnt ) ) # feed data cmd = 'plot "-" using 0:1 with boxes linecolor %s, ' % color cmd += "'-' using 0:1:1 with labels offset 0, 1\n" plt.write( cmd ) for unit, cnt in histo.items() : plt.write( str(cnt) + "\n" ) plt.write( 'e\n' ) for unit, cnt in histo.items() : plt.write( str(cnt) + "\n" ) plt.write( 'e\n' ) color += 1 plt.close()
def plot( self, interval, font_fname=None ) : plt = Gnuplot() plt.open() cmds_at_second = self.group_commands_by_time() counts_at_second = self.count_player_actions( interval, cmds_at_second ) # actions counted for that second... ts = [ t for t in range( len( counts_at_second ) ) ] apmss = self.make_apmss( interval, counts_at_second ) #apmss[pid][t] = apm at time t, of player pid. plt.xlabel( "Time (s)" ) plt.ylabel( "APM" ) labels = [] for i in range( self.nplayers ) : player = self.kwr.players[i] if not player.is_player() : continue plt.plot( ts, apmss[ i ] ) name = sanitize_name( player, xor=True ) labels.append( name ) # touch up label of the curve # draw legend plt.legend( labels ) avg_apms = self.calc_avg_apm( cmds_at_second ) avg_apm_texts = self.avg_apm2txts( avg_apms ) # draw peak arrow. self.draw_peak_labels( plt, apmss ) # now the plot begins. plt.write( 'plot \\\n' ) # begin the plot command. color = 1 for pid in range( self.nplayers ) : player = self.kwr.players[pid] if not player.is_player() : continue #name = sanitize_name( player, xor=True ) #print( name, avg_apms[ pid ] ) plt.write( "%f title \"%s\" linecolor %d linetype 0 linewidth 2, \\\n" % ( avg_apms[ pid ], avg_apm_texts[pid], color ) ) color += 1 plt.data_plot_command() # plot apm(player, t) data. plt.close()
class Experiment: ######################################################################### "contains all data for an experiment: results, sampling policy, etc." ######################################################################### def __init__(self, p): ##################################################################### "constructor" ##################################################################### self.p = p self.res = CResults(p.GetDimensions()) def seed(self, n): ##################################################################### "seed random elements of the experiment" ##################################################################### self.sp.Seed(n) self.p.Seed(n + 1) def add_clop(self): ##################################################################### "add reg (and me) to this experiment" ##################################################################### self.reg = CRegression(self.res, CPFQuadratic(self.p.GetDimensions())) self.me = CMERegressionMAPMax(self.reg) def reset(self): ##################################################################### "reset" ##################################################################### self.res.Reset() def max(self): ##################################################################### "convert vectord to a list" ##################################################################### v = vectord(self.p.GetDimensions()) if self.me.MaxParameter(v): result = [] for i in range(v.size()): result.append(v[i]) return result else: return None def run(self, n, trace = False): ##################################################################### "collect n samples" ##################################################################### for i in range(n): v = self.sp.NextSample(self.res.GetSamples()) r = self.p.GetOutcome(v) if r == COutcome.Unknown: return self.res.AddSample(v, r) if trace: print "%6d" % i, r, v, self.max() self.res.Refresh(); def gnuplot(self, reg): ##################################################################### "plot with gnuplot" ##################################################################### if not self.__dict__.has_key('gp'): self.gp = Gnuplot() CQLRIO.DumpSamples('samples.dat', self.reg) if self.p.GetDimensions() == 1: CQLRIO.Distrib(reg) self.plot_to_file('distrib.dat', 100) self.gp.send('load "clop.gpi"') elif self.p.GetDimensions() == 2: CQLRIO.Distrib(reg) self.plot_to_file_2d('distrib.dat', 40) self.gp.send('load "samples2d.gpi"') def new_gnuplot(self, reg): ##################################################################### "create a new gnuplot window" ##################################################################### self.gp = Gnuplot() self.gnuplot(reg) def plot_to_file(self, filename, resolution): ##################################################################### "write 1D model data to a file" ##################################################################### f = open(filename, 'w') for i in range(resolution + 1): x = doubleArray(1) x[0] = -1.0 + (2.0 * i) / resolution f.write("%f %f %f\n" % (x[0], self.p.GetProba(x), self.p.GetStrength(x))) def plot_to_file_2d(self, filename, resolution): ##################################################################### "write 2D model data to a file" ##################################################################### f = open(filename, 'w') for i in range(resolution + 1): x = -1.0 + (2.0 * i) / resolution for j in range(resolution + 1): y = -1.0 + (2.0 * j) / resolution v = doubleArray(2) v[0] = x v[1] = y f.write("%f %f %f %f\n" % (x, y, self.p.GetProba(v), self.p.GetStrength(v))) f.write('\n') def experiment_setup(self): ##################################################################### "get a CArtificialExperiment for CRepeatThreads" ##################################################################### return CArtificialExperiment(self.p, self.sp, self.me, self.res)
def new_gnuplot(self, reg): ##################################################################### "create a new gnuplot window" ##################################################################### self.gp = Gnuplot() self.gnuplot(reg)
def plot_orbit(self, plotfile, nsamp=100): coeffs = self.coeffs[0].T coords = self.coords / 1e3 t = self.time time = np.linspace(self.t_start, self.t_stop, nsamp) if self.centered: time_cent = time - self.t_mean poly = np.asarray([ np.polyval(coeffs[ii, :], time_cent) + mean_coords[ii] for ii in range(3) ]).T else: poly = np.asarray( [np.polyval(coeffs[ii, :], time) for ii in range(3)]).T poly /= 1e3 gpt = Gnuplot() gpt.output(plotfile, term="pngcairo", fontsize=8) gpt.axis_format("x", "") gpt.margins(bmargin=3.5) gpt("set tics font ',8'") gpt.multiplot(3, portrait=True, title="Fit of orbital vectors - " "degree of polynom: {}".format(self.deg)) ylabels = ("X [km]", "Y [km]", "Z [km]") for ii in range(3): gpt.ylabel(ylabels[ii]) points = gpt.data(t, coords[:, ii], title="Orbital coordinates", vith=linedef(point_type="empty_circle")) fit = gpt.data(time, poly[:, ii], title="Fitted polynom", vith="lines") if ii == 2: gpt("set format x") gpt.xlabel("Time [s]") gpt.plot(points, fit)