Exemplo n.º 1
0
def init( ):
    global camkii_
    # initlialize gnuplot.
    with open( 'tmp.dat', 'w' ) as f:
        f.write( '1 1 1 1 1' )
    pg.c( 'set terminal x11' )
    pg.c( 'set xrange [0:500]; set yrange [0:500]; set zrange [0:500]' )
    pg.c( 'set ticslevel 0' )
    pg.c( 'set view 240,30' )
    pg.c( 'splot "tmp.dat" u 1:2:3:5 with p pt variable notitle' )
Exemplo n.º 2
0
def init( ):
    # initlialize gnuplot.
    # Replot does not work in multiplot mode.
    with open( tmp_file_, 'w' ) as f:
        f.write( '1 1 1 1 1' )
    pg.c( 'set terminal x11 noraise' )
    pg.c( 'set xrange [0:500]; set yrange [0:500]; set zrange [0:500]' )
    pg.c( 'set ticslevel 0' )
    pg.c( 'set view 240,30' )
    pg.c( 'splot "%s" u 1:2:3:4:5 with p pt variable notitle' % tmp_file_ )
    return True
Exemplo n.º 3
0
def plot3dMSR(uc_3):

    hyperPoints = cdf.getMSR_ND(uc_s, N=190)

    gp.s(np.transpose(hyperPoints), filename="plot3dMSR.dat")
    gp.c('set ticslevel 0')
    gp.c('unset key')
    gp.figure('0')
    c_plot = 'splot "plot3dMSR.dat" with lines ' 
    print c_plot                   
    gp.c(c_plot)
Exemplo n.º 4
0
def simulate_step( i ):
    global camkiis_, grid_
    global dt_

    # Update the state of each camkii
    temp = camkiis_[:]
    [ cam.step( camkiis_ ) for cam in temp ]

    if i % 100 == 0:
        np.savetxt( "tmp.dat", np.array( pos_ ) )
        pg.c( 'set title "Time=%.3f"'% (i*dt_) )
        pg.c( 'replot' )

    if i % 100 == 0:
        outfile = os.path.join( image_dir_, '%08d.png' % i )
        save_gnuplot( i, outfile  )
Exemplo n.º 5
0
def plot( pos ):
    global init_
    if not init_:
        init( )
        init_ = True

    if len( pos ) < 1:
        print( 'No data' )
        return False

    with open( tmp_file_, 'w' ) as f:
        for l in pos:
            f.write( l )

    pg.c( 'replot' )
    return True
Exemplo n.º 6
0
    def load_and_go(self, gpFolder=False):
        '''
        # gpfolder is a switch to make gnuplot change folder if required
        simply executes the sub definitions
        loads data,
        normalizes to SI units,
        calculates differential resistances
        '''
        self.loaddata()
        self.loadCcor()
        self.norm_to_SI()
        self.make_cvals()
        if not os.path.exists(self.resultfolder):
            os.makedirs(self.resultfolder)

        if gpFolder:
            gp.c('cd "' + self.resultfolder + '"')
Exemplo n.º 7
0
def main( ):
    Q = [1/6.0] * 6
    results = [ ]
    with open( "tmp.dat", "w" ) as  f:
        for i in range( 10000 ):
            P = generate_probs( )
            d = KL_divergence( P, Q )
            results.append( (P, d, entropy(P) ) )
            f.write( "%g %g\n" % (d, entropy(P)) )

    pg.c( 'set ylabel "H(E)"' )
    pg.c( 'set xlabel "D(E||Q), Q is uniform"' )
    pg.c( 'set terminal pdf; set output "problem2.pdf"; ' )
    pg.c( 'plot "tmp.dat" using 1:2 w p title "KL distance V/S entropy"' )
Exemplo n.º 8
0
    def fitData(self, xmin: float, xmax: float, filename=""):
        # fun right here

        fitlog_del = open("fit.log", "w")
        fitlog_del.close()

        arrX = []
        arrY = []
        arrErrY = []

        for i in range(len(self.dataArray[0])):

            if xmin <= self.dataArray[0][i] <= xmax:
                arrX.append(self.dataArray[0][i])
                arrY.append(self.dataArray[1][i])
                arrErrY.append(self.dataArray[2][i])

        gp.s([arrX, arrY, arrErrY], "tmp.dat")

        gp.c("m=%f" % self.mpar)
        gp.c("b=%f" % self.bpar)
        gp.c("f_reta(x)=m*x+b")

        viaStr = "m, b, "
        gaussStr = ""
        paramNumber = 2
        for i in range(len(self.Apars)):
            gp.c("A%d=%f" % (i, self.Apars[i]))
            gp.c("mu%d=%f" % (i, self.mupars[i]))
            gp.c("sig%d=%f" % (i, self.sigpars[i]))

            if i != 0:
                gaussStr += "+"
                viaStr += ", "
            gaussStr += "A%d/(sqrt(2*pi)*sig%d) * exp( -0.5*((x-mu%d)/sig%d)**2)" % (
                i, i, i, i)
            viaStr += "A%d, mu%d, sig%d" % (i, i, i)
            paramNumber += 3

        gp.c("ftot(x)=" + gaussStr + "+m*x+b")
        gp.c("fit ftot(x) 'tmp.dat' u 1:2:3 yerrors via " + viaStr)

        gp.c(
            "plot 'tmp.dat' u 1:2:3 w yerrorbars t 'Data', ftot(x) t 'f({/Symbol b})'"
        )
        if len(filename) != 0:
            gp.pdf(filename)

        time.sleep(0.1)  # needed to create the fit.log file in time
        # then view file fit.log to get parameters

        fitlog = open("fit.log", "r")
        fileLines = fitlog.readlines()
        fitlog.close()

        if len(fileLines) == 0:
            time.sleep(0.3)
            fitlog = open("fit.log", "r")
            fileLines = fitlog.readlines()
            fitlog.close()

        chi2 = 0
        paramspos = 0
        paramStr = []
        paramVal = []
        paramErr = []
        for i in range(len(fileLines)):
            if "(reduced chisquare) = WSSR/ndf" in fileLines[i]:
                chi2 = float(fileLines[i].split(" : ")[1])

            if "Final set of parameters" in fileLines[i]:
                paramspos = i

            if paramspos != 0 and paramspos + 1 < i < paramspos + 2 + paramNumber:
                paramStr.append(fileLines[i].split(" ")[0])

                pars = fileLines[i].split(" = ")[1]
                paramVal.append(float(pars.split()[0]))
                paramErr.append(float(pars.split(" +/- ")[1].split()[0]))

        # print("chi2: ", chi2)
        # for i in range(len(paramStr)):
        #     print(paramStr[i], paramVal[i], paramErr[i])

        return [chi2, paramStr, paramVal, paramErr]
Exemplo n.º 9
0
    def plot_maps(self):
        x_lim, y_lim = [None,None], [None,None]
        color_lim = self.colorbarlims

        if self.maptype == "map":
            plotdata = self.map_out*1e6
            if color_lim[0] is None or color_lim[1] is None:
                color_lim[1] = 1*np.std(plotdata)
                color_lim[0] = -color_lim[1]
            print("Portion of map inside crange: %.3f" % (np.sum(np.abs(plotdata) < color_lim[1])/np.size(plotdata)))
        elif self.maptype == "rms":
            plotdata = self.rms_out*1e6
            if color_lim[0] is None or color_lim[1] is None:
                color_lim = 0, 1*np.std(plotdata)
            print("Portion of map inside crange: %.3f" % (np.sum(np.abs(plotdata) < color_lim[1])/np.size(plotdata)))
        elif self.maptype == "hit":
            plotdata = self.hit_out
            if color_lim[0] is None or color_lim[1] is None:
                color_lim = np.min(plotdata), np.max(plotdata)
        elif self.maptype == "map_rms":
            plotdata = self.map_out/self.rms_out
        elif self.maptype == "var":
            plotdata = self.var_out
        elif self.maptype == "feed":
            plotdata = self.feed_out
        # elif self.maptype == "sim":
        #     plotdata = self.sim_out
        # elif self.maptype == "sim_rms":
        #     plotdata = self.simrms_out
        plotdata = np.ma.masked_where(self.hit_out < 1, plotdata)
        # plotdata[self.hit_out < 1] = np.nan

        x, y = self.x, self.y
        dx = x[1] - x[0]
        x_lim[0] = x[0] - 0.5*dx; x_lim[1] = x[-1] + 0.5*dx
        dy = y[1] - y[0]
        y_lim[0] = y[1] - 0.5*dy; y_lim[1] = y[-1] + 0.5*dy

        if USE_GNUPLOT:
            import PyGnuplot as gp
            
            gp.s(plotdata)
            gp.c('set term png')
            gp.c('set output "%s"' % (self.outpath + self.outname + ".png"))
            if color_lim[0] is not None and color_lim[1] is not None:
                gp.c('set cbrange [%d:%d]' % (color_lim[0], color_lim[1]))
            #gp.c('set size ratio %f' % ((y_lim[1]-y_lim[0])/(x_lim[1]-x_lim[0])))
            gp.c('set size ratio -1' % ((y_lim[1]-y_lim[0])/(x_lim[1]-x_lim[0])))
            gp.c("set xrange[%f:%f]" % (x_lim[0], x_lim[1]))
            gp.c("set yrange[%f:%f]" % (y_lim[0], y_lim[1]))
            gp.c('set datafile missing "--"')
            gp.c('plot "tmp.dat" matrix using (%f+$1*%f):(%f+$2*%f):3 with image title ""' % (x_lim[0], dx, y_lim[0], dy))

        else:
            import matplotlib.pyplot as plt
            import matplotlib
            import copy
            matplotlib.use("Agg")  # No idea what this is. It resolves an error when writing gif/mp4.
            cmap_name = "CMRmap"
            cmap = copy.copy(plt.get_cmap(cmap_name))
            cmap.set_bad("0.8", 1) # Set color of masked elements to gray.
            fig, ax = plt.subplots(figsize=(10,6))
            ax.set_ylabel('Declination [deg]')
            ax.set_xlabel('Right Ascension [deg]')
            aspect = dx/dy
            if self.plottype == "png":
                img = ax.imshow(plotdata, extent=(x_lim[0],x_lim[1],y_lim[0],y_lim[1]), interpolation='nearest',
                                    aspect=aspect, cmap=cmap, origin='lower',
                                    vmin=color_lim[0], vmax=color_lim[1])

                title = self.make_title()
                ax.set_title(title)
                # ax.set_title("Sideband: %s | Channel: %d | Freq: %.3f GHz" % (self.sideband_names[s], i%64, self.freq[s,f]))
                cbar = fig.colorbar(img)
                cbar.set_label("$\mu K$")
                fig.savefig(self.outpath + self.outname + ".png")

            elif self.plottype in ["mp4", "gif"]:
                import matplotlib.animation as animation

                img = ax.imshow(plotdata[0,0], extent=(x_lim[0],x_lim[1],y_lim[0],y_lim[1]), interpolation='nearest',
                                    aspect=aspect, cmap=cmap, origin='lower',
                                    vmin=color_lim[0], vmax=color_lim[1])
                cbar = fig.colorbar(img)
                cbar.set_label("$\mu K$")

                if self.plottype == "mp4": # The first handful of frames stutter a lot (no idea why),
                    holdframes = 4         # so we render some static frames first (only an issue with mp4).
                else:
                    holdframes = 0

                def update(i):
                    if i < holdframes:
                        i = 0
                    else:
                        i -= holdframes
                    f = i%len(self.frequencies)
                    s = i//len(self.frequencies)
                    img.set_data(plotdata[s,f])
                    title = "Maptype: " + self.maptype + " | " + str(self.filename).split("/")[-1] + "\n"
                    title += "Sideband %s | Channel %d | Freq %.2f GHz" % (self.sideband_names[s], i%64+1, self.freq[s,f])
                    ax.set_title(title)
                    return [img]
                ani = animation.FuncAnimation(fig, update, frames=len(self.frequencies)*len(self.sidebands)+holdframes, interval=200, blit=False, repeat_delay=1000)

                if self.plottype == "gif":
                    ani.save(self.outpath + self.outname + ".gif", writer="imagemagick")
                elif self.plottype == "mp4":
                    ani.save(self.outpath + self.outname + ".mp4", writer="ffmpeg")
                                          transcoder_no)]['profile'].extend([
                                              previous_measurements['quality'],
                                              after_measurements['quality']
                                          ])
                else:
                    spectators_and_trans.update({
                        (client_id, transcoder_no): {
                            'mean_opinion_score': [
                                previous_measurements['mean_opinion_score'],
                                after_measurements['mean_opinion_score']
                            ],
                            'frame_rate': [
                                previous_measurements['framerate_on'],
                                after_measurements['framerate_on']
                            ],
                            'profile': [
                                previous_measurements['quality'],
                                after_measurements['quality']
                            ]
                        }
                    })
        for key in spectators_and_trans.keys():
            for metric in spectators_and_trans[key].keys():
                filename = spectator_data.format(scenario_dir, run, key[1],
                                                 key[0], metric)
                if not os.path.exists(os.path.dirname(filename)):
                    os.makedirs(os.path.dirname(filename))
                X = spectators_and_trans[key][metric]
                Y = list(range(0, len(spectators_and_trans[key][metric])))
                gp.s([Y, X], filename)
Exemplo n.º 11
0
def plot_amplitude(maxima, suffix, det):
    plot_name = '00_amplitude'
    dummy, fname = tempfile.mkstemp(prefix='tmp_amplitude_%03d' % det,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_name, det_feat = detector_name(det)
    xmin = cfg.cfg.getfloat("plot", "ampl_min", fallback=0.)
    xmax = cfg.cfg.getfloat("plot", "ampl_max", fallback=1.)
    xbin = cfg.cfg.getfloat("plot", "ampl_bin", fallback=1000)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    #values, edges = np.histogram(maxima, bins=1500, range=(xmin, xmax), density=False)
    values, edges = np.histogram(maxima, bins=1500, density=False)
    gp_set_defaults()
    gp.c('set label "' + det_name + ' ' + det_feat +
         ' - amplitude spectrum" at graph 0, graph 1.04 noenhanced')
    gp.c('set log y')
    gp.c('set log x')
    gp.c('set ylabel "Events / V"')
    gp.c('set xlabel "Amplitude (V)"')
    gp.s([edges[:-1], values], filename=fname)
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot [][0.5:] "' + fname + '" u 1:2 not w histep lt 6')
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 12
0
def plot_done(det):
    det_name, det_feat = detector_name(det)
    gp.c('system("touch ".odir."/%s/done")' % det_name)
Exemplo n.º 13
0
def plot_correlations(peaks_a, peaks_max_a, det_a, peaks_b, peaks_max_b, det_b,
                      suffix):
    plot_name = '40_corr_peaks'
    if len(peaks_a) == 0:
        return
    dummy, fname = tempfile.mkstemp(prefix='tmp_corr_peaks_%03d' % det_a,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_a_name, det_a_feat = detector_name(det_a)
    det_b_name, det_b_feat = detector_name(det_b)
    # the output directory corresponds to the detector on the x-axis
    os.makedirs(os.path.join(cfg.global_odir, det_a_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    gp_set_defaults()
    gp.c('set label "' + det_a_name + ' ' + det_a_feat + ' (x-axis), ' +
         det_b_name + ' ' + det_b_feat +
         ' (y-axis)" at graph 0, graph 1.04 noenhanced')
    gp.s([peaks_max_a, peaks_max_b], filename=fname)
    gp.c('set auto fix')
    gp.c('set log x')
    gp.c('set log y')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c('set xlabel "Amplitude (V) - Detector: %s %s"' %
         (det_a_name, det_a_feat))
    gp.c('set ylabel "Amplitude (V) - Detector: %s %s"' %
         (det_b_name, det_b_feat))
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_a_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot [][:15e-6] "' + fname + '"' +
             " u ($1):($2) not w p lt 6 pt 7 ps 0.125")
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
            read_element = read_line[i].split() 
            dic[int(read_element[0])] = [int(read_element[1])]
            dic[int(read_element[0])].append(int(read_element[2]))
        f.close()
dic = {}
readfile(dic)
with open('eil51_optimal.txt') as f:
        a = []
        r = f.read()
        read_line = r.split()               
        for i in range(len(read_line)):
            a.append(int(read_line.pop(0)))
        f.close()
#gp.s([X,Y,Z])
#gp.c('replot "tmp.dat" u 1:3')
#gp.p('myfigure.jpg')
filename = 'data/optimal.txt'
with open(filename,'w') as f:
    f.truncate(0)
    f.close()
for i in range(len(a)+1):
    with open(filename,'a') as f:
        
           
        f.write(str(dic[a[i%len(a)]][0]))
        f.write(' ')
        f.write(str(dic[a[i%len(a)]][1]))
        f.write('\n')
        f.close()
gp.c('plot "data/optimal.txt" u 1:2 with linespoints linewidth 2')
Exemplo n.º 15
0
import PyGnuplot as gp
import numpy as np

gp.c('set terminal png size 1000,700 enhanced font "Helvetica,20"')
gp.c("set output 'output4.png'")
gp.c(
    'set title "Comparision between FSAM-IComP and MFSAM-IComP(m=n)";set xlabel "Number of users";set ylabel "Number of allocations"'
)
gp.c('set yrange [0:520]')
gp.c('set style fill pattern 2 border lt -1')
gp.c('set boxwidth 0.1')
gp.c("plot 'mfsam1.txt' using ($0):3:xtic(1) with boxes title 'FSAM-IComP', \
	''using ($0+0.1):4 with boxes title 'MFSAM-IComP'")
# reshape from [samples, timesteps] into [samples, timesteps, features] - we have multiple samples, so input data needs to include number of variables/features being supplied/expected
X = X.reshape((X.shape[0], X.shape[1], n_features))

# We have created the structure of the model so now we have to fit the model to our training dataset
model.fit(X, y, epochs=1000, verbose=0)

# demonstrate prediction
x_input = array(testSet)
x_input = x_input.reshape((1, n_steps, n_features)) #Suggests a single sample of n_steps?
yhat = model.predict(x_input, verbose=0)
print (x_input)
print(yhat)

x_input_list = []
for i in x_input:
    for j in i:
        for k in j:
            x_input_list.append(k)

prediction_list = []
for i in range(len(x_input_list)-1):
    prediction_list.append(None)
prediction_list.append(yhat[0][0])

#pg.s([x_input_list, yhat], filename='CNN_output.out')  # save data into a file
pg.s([x_input_list, prediction_list], filename='CNN_output.out')  # save data into a file
pg.c('set title "CNN_output"; set xlabel "x-axis"; set ylabel "y-axis"')
pg.c('set key center top')
pg.c("plot 'CNN_output.out' u 1 t 'x\_input = Test Set'")  # plot test set
pg.c("replot  'CNN_output.out' u 2  t 'yhat = Predicted value'")
Exemplo n.º 17
0
def plotData(req):
    # g = Gnuplot.Gnuplot(persist =1)
    if req == 1:
        gp.c('set terminal qt 2 title "Logistic function"')
    else:
        gp.c('set terminal qt 2 title "Neural Network"')
    gp.c(
        "set palette model RGB defined ( 0 'red', 1 'green', 2 'blue', 3 'black')"
    )
    gp.c("unset key")
    gp.c('set xrange [-2:2]')
    gp.c('set yrange [-2:2]')
    gp.c('plot "p2.dat" using 2:3:1 with points palette')
Exemplo n.º 18
0
#! /usr/bin/env python2

import PyGnuplot as gp
import numpy as np
X = np.arange(10)
Y = np.sin(X / (2 * np.pi))

Z = Y**2.0
gp.s([X, Y, Z])
gp.c('plot "tmp.dat" u 1:2 w lp')
gp.c('replot "tmp.dat" u 1:3 w lp')
gp.p('myfigure.ps')
Exemplo n.º 19
0
XZinput = open("2D.gp", "r")
XZoutput = open("output/2DPyOut.gp", "w")

#guardar el documento como lista de strings
XZstrList = XZinput.readlines()

#leer lista y remplazar los valores donde hay keywords
for i in range(len(XZstrList)):
    if kw1 == XZstrList[i]:
        XZstrList[i] = str('M1=' + M1 + '\n')
    if kw2 == XZstrList[i]:
        XZstrList[i] = str('M2=' + M2 + '\n')
    if kwCline == XZstrList[i]:
        XZstrList[i] = str('plot f(x) t \'V\' ls ' + chline + '\n')
    if i != 2 and i != 3:
        gp.c(XZstrList[i])

##crear el documento nuevo y cerrar ambos
XZoutput.writelines(XZstrList)
XZinput.close()
XZoutput.close()

time.sleep(0.5)

print('De la gráfica localice los tres máximos y computelos: \n')

xA = (str(input('Posición x del primer máximo: ')))
xB = (str(input('Posición x del segundo máximo: ')))
xC = (str(input('Posición x del tercer máximo: ')))

#keywords
Exemplo n.º 20
0
def plot_fft_rate(freq, power, suffix, det):
    plot_name = 'XX_fft_rate'
    dummy, fname = tempfile.mkstemp(prefix='tmp_fft_rate_%03d' % det,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_name, det_feat = detector_name(det)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    gp_set_defaults()
    gp.c('set label "' + det_name + ' ' + det_feat +
         '" at graph 0, graph 1.04 noenhanced')
    gp.s([freq, power], filename=fname)
    gp.c('set auto fix')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c('set log y')
    gp.c('set ylabel ""')
    gp.c('set xlabel "Frequency (1/min)"')
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot [][] "' + fname + '" u ($1 * 60):2 not w l lt 6')
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 21
0
def plot_fft_data(freq, power, suffix, det):
    plot_name = '30_fft_data'
    dummy, fname = tempfile.mkstemp(prefix='tmp_fft_data_%03d' % det,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_name, det_feat = detector_name(det)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    gp_set_defaults()
    gp.c('set label "' + det_name + ' ' + det_feat +
         '" at graph 0, graph 1.04 noenhanced')
    gp.s([freq, power], filename=fname)
    gp.c('set auto fix')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c('set log y')
    gp.c('set mytics 10')
    gp.c('set log x')
    gp.c('set mxtics 10')
    #gp.c('set ylabel "Power Spectral Density (V^2 / Hz)"')
    gp.c('set ylabel "Noise FFT (V / √Hz)"')
    gp.c('set format y "10^{%L}"')
    gp.c('set xlabel "Frequency (Hz)"')
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot [1:][] "' + fname + '" u 1:(sqrt($2)) not w l lt 6')
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 22
0
def t1q2_2():
    open('q2-2.pts', 'w').close()

    gp.c('set terminal png')
    gp.c('set xrange[-6:6]')
    gp.c('set yrange[-6:6]')
    gp.c('set grid')
    gp.c('set xzeroaxis lw 2')
    gp.c('set yzeroaxis lw 2')
    gp.c('set output "t1q2_2.png"')

    estimate()
    gp.c('plot "q2-2.pts" with lp title "taylor", x*cos(x) + 1')
Exemplo n.º 23
0
def plot_correlation_deltat(det_a, det_b, deltat, suffix):
    plot_name = '41_corr_deltat'
    if len(deltat) == 0:
        return
    dummy, fname = tempfile.mkstemp(prefix='tmp_corr_deltat_%03d' % det_a,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_a_name, det_a_feat = detector_name(det_a)
    det_b_name, det_b_feat = detector_name(det_b)
    # the output directory corresponds to the detector on the x-axis
    os.makedirs(os.path.join(cfg.global_odir, det_a_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    gp_set_defaults()
    gp.c('set label "' + det_a_name + ' ' + det_a_feat + ', ' + det_b_name +
         ' ' + det_b_feat + '" at graph 0, graph 1.04 noenhanced')
    values, edges = np.histogram(np.multiply(deltat,
                                             1e3 / cfg.params.sampling_freq),
                                 bins=1500,
                                 density=False)  # convert deltat in ms
    gp.s([edges[:-1], values], filename=fname)
    gp.c('set log y')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c(
        'set xlabel "Peak time %s %s - time of the closest peak of %s %s (ms)"'
        % (det_a_name, det_a_feat, det_b_name, det_b_feat))
    gp.c('set ylabel "Number of events"')
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_a_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot [-15000:15000] "' + fname + '"' +
             " u 1:2 not w histep lt 6")
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 24
0
import PyGnuplot as gp
import numpy as np

gp.c('set style fill transparent solid 0.5 noborder')
gp.c('set title "Result";set xlabel "x-axis";set ylabel "y-axis"')
gp.c('set yrange [0:1500];set key center top')
gp.c('set xrange [10:100];set key center top')
gp.c(
    "plot 'utility_random.txt' using 1:($2) with linespoints lc 19 lw 3 title 'Random utility"
)
gp.c(
    "replot 'utility_random.txt' using 1:($3) with linespoints lc 6 lw 4 dt 3 title 'Random 1"
)
#gp.c("replot 'utility_random.txt' using 1:($4) with linespoints lc 19 lw 2 title 'utility 3")
#gp.c("replot 'utility_random.txt' using 1:($5) with linespoints lc 19 lw 2 title 'utility 4")
gp.c(
    "replot 'utility_random.txt' using 1:($3):($4) with filledcurves lc 17 fs transparent solid 0.2 notitle"
)
Exemplo n.º 25
0
def gp_set_defaults():
    gp.c('reset')
    gp.c('set encoding utf8')
    gp.c('set minussign')
    gp.c('set mxtics 5')
    gp.c('set mytics 5')
    gp.c('set grid')
    gp.c('set key samplen 1.5')
    gp.c('set tmargin 2.5')
    gp.c(
        'set label "{/=16:Bold CUPID/CROSS }{/=14:Italic Data Quality Monitoring}{/:Normal \\ }" at graph 0, graph 1.1'
    )
    gp.c('set label "{/=16 Canfranc}" at graph 1, graph 1.1 right')
    gp.c(
        'set label 101 "Last updated on ".system("date -u \\"+%a %e %b %Y %R:%S %Z\\"") at screen .975, graph 1 rotate by 90 right font ",12" tc "#999999"'
    )
    gp.c('hour(x) = x / ' + str(cfg.params.sampling_freq) + ' / 3600.')
    gp.c('odir = "' + cfg.global_odir + '/"')
    if cfg.tmpdir == '':
        cfg.tmpdir = tempfile.mkdtemp(prefix='tmp_out_', dir='.')
Exemplo n.º 26
0
import PyGnuplot as gp
import numpy as np

gp.c('set style fill transparent solid 0.5 noborder')
gp.c('set title "Result";set xlabel "x-axis";set ylabel "y-axis"')
gp.c('set yrange [0:1500];set key center top')
gp.c('set xrange [10:100];set key center top')
gp.c('set style fill transparent solid 0.5 noborder')
gp.c('set title "Result";set xlabel "number of tasks";set ylabel "Utility of IOT devices"')
gp.c("plot 'utility_random.txt' using 1:($2) with linespoints lc 10 lw 2 title 'utility random")
gp.c("replot 'utility_random.txt' using 1:($2) with linespoints lc 19 lw 2 title 'utility 1")
gp.c("replot 'utility_random.txt' using 1:($3) with linespoints lc 19 lw 2 title 'utility 2")
gp.c("replot 'utility_random.txt' using 1:($4) with linespoints lc 19 lw 2 title 'utility 3")
gp.c("replot 'utility_random.txt' using 1:($5) with linespoints lc 19 lw 2 title 'utility 4")
gp.c("replot 'utility_random.txt using 1:($4):($5) with filledcurves lc 3 fs transparent solid 0.5")
Exemplo n.º 27
0
def plot_peaks(peaks, peaks_max, suffix, det):
    plot_name = '20_peaks'
    if len(peaks) == 0:
        return
    dummy, fname = tempfile.mkstemp(prefix='tmp_peaks_%03d' % det,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_name, det_feat = detector_name(det)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    gp_set_defaults()
    gp.c('set label "' + det_name + ' ' + det_feat +
         ' - signal peaks" at graph 0, graph 1.04 noenhanced')
    gp.s([peaks, peaks_max], filename=fname)
    gp.c('set auto fix')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c('set log y')
    gp.c('set ylabel "Amplitude (V)"')
    gp.c('set xlabel "Time (h)"')
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot "' + fname + '"' +
             " u (hour($1)):($2) not w p pt 6 ps 0.125 lt 6")
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 28
0
def t1q2():
    open('arquivos.pts', 'w').close()
    open('sorted.pts', 'w').close()
    open('unsorted.pts', 'w').close()

    estimate()

    gp.c('set terminal png')
    gp.c('set xrange[-6:6]')
    gp.c('set yrange[-6:6]')
    gp.c('set grid')
    gp.c('set xzeroaxis lw 2')
    gp.c('set yzeroaxis lw 2')
    gp.c('set output "t1q2.png"')
    gp.c('plot "arquivos.pts" with lp title "aproximação", x*cos(x) + 1')
def main(*args):
    try:

        dv_file = int(sys.argv[1])
        cxn = labrad.connect()
        dv = cxn.data_vault
        dv.cd(['', 'he_level'])
        dv.open(dv_file)
        x, y = dv.get_ex_t()
        x = np.array(x)
        xp = np.zeros(len(x))
        y = np.array(y)
        for k in range(0, len(x)):
            structtime = time.localtime(x[k])
            xp[k] = structtime.tm_hour + float(structtime.tm_min) / 60

        gp.s(
            [xp, y]
        )  #,filename='"C:\\Users\\Feldman Lab\\code\\Setup_BF122019\\LabRAD-Device-Electrical_Measurement-ONline_Software-pyqt5\\DEMONS GUI\\Scripts\\tmp.dat"')
        title = time.strftime("%a, %d %b %Y", time.localtime(x[0]))
        time.sleep(2)
        gp.c(
            'set terminal wxt size 500,500 position -1900,400 enhanced persist'
        )
        gp.c('set title ' + '"' + title + '"')
        gp.c('set xlabel "hours"')
        gp.c('set ylabel "percent"')
        gp.c('plot "tmp.dat" w lp')

    except Exception as e:
        print(e)
Exemplo n.º 30
0
import PyGnuplot as gp
import numpy as np

gp.c('set title "Result";set xlabel "x-axis";set ylabel "y-axis"')
gp.c('set yrange [0:6000]')
gp.c('set xrange [10:100]')
gp.c("plot 'total_budget.txt' u 1:2 w l t 'Budget")
gp.c("replot 'normal.txt' u 1:2 w l t 'Payment normal")
gp.c("replot 'bid_sum.txt' u 1:2 w l t 'bid_sum")
Exemplo n.º 31
0
def SciPlot(*vect,
            aprx=[3, 2],
            xlabel="x-axis",
            ylabel="y-axis",
            title="",
            name="SVGplot",
            label="",
            size=[15, 9],
            origKeys="",
            aprxKeys=""):
    num = len(vect)
    half = num / 2
    if num % 2 != 0:
        print("wrong number of variables")
        pass

    for i in range(int(half)):
        # save data into a file t.out
        pg.s([vect[2 * i], vect[2 * i + 1]],
             filename='dataOrig{0}.out'.format(i))

    vect = list(vect)
    for i in range(len(vect)):
        vect[i] = list(map(lambda x: float(x), vect[i]))

    OrKeysVect = 0
    if str(type(origKeys)) == "<class 'str'>":
        OrKeysVect = [origKeys] + ["" for i in range(int(half))]
    else:
        OrKeysVect = [origKeys[i] for i in range(len(origKeys))
                      ] + ["" for j in range(int(half - len(origKeys)))]

    ApKeysVect = 0
    if str(type(aprxKeys)) == "<class 'str'>":
        ApKeysVect = [aprxKeys] + ["" for i in range(int(half))]
    else:
        ApKeysVect = [aprxKeys[i] for i in range(aprxKeys)
                      ] + ["" for j in range(int(half - len(aprxKeys)))]

    aprxVect = 0
    if aprx[1] == 0 or aprx[1] == 1 or aprx[1] == 2:
        aprxVect = [aprx for i in range(int(half))]
    else:
        aprxVect = [aprx[i] for i in range(len(aprx))
                    ] + [aprx[0] for j in range(int(half - len(aprx)))]

    koeffs = [
        aprox.AprxCoeffs(vect[2 * i], vect[2 * i + 1], aprx=aprxVect[i])
        for i in range(int(half))
    ]
    arrs = [
        (np.linspace(min(vect[2 * i]), max(vect[2 * i]), 50),
         aprox.Polin_func2(np.linspace(min(vect[2 * i]), max(vect[2 * i]), 50),
                           koeffs[i])) for i in range(int(half))
    ]

    imprtArr = []
    for i in range(len(arrs)):
        imprtArr += arrs[i]

    for i in range(int(half)):
        pg.s([imprtArr[2 * i], imprtArr[2 * i + 1]],
             filename='dataAprx{0}.out'.format(i))

# commText = 'set autoscale; set grid\n\
# set mxtics 4\n\
# set mytics 4\n\
# set tics nomirror\n\
# set border 3 front lw 3\n\
# set style line 1 lc rgb "#8b1a0e" pt 1 ps 1 lt 1 lw 3\n\
# set style line 2 lc rgb "#5e9c36" pt 6 ps 1 lt 1 lw 3\n\
# set title "{0}"\n\
# set xlabel "{1}\\n{3}"; set ylabel "{2}"\n\
# set terminal epslatex newstyle color solid size {4}cm, {5}cm # размеры рисунка можно варьировать как угодно\n\
# set output "testplot.tex"\n'.format(title, xlabel, ylabel, label, size[0], size[1])

    tex_header = '\documentclass[12pt]{article}\n\
% Подключаем всяко-разное, задаем кодировку, язык и прочие параметры по вкусу\n\
\\usepackage[OT1,T2A]{fontenc}\n\
\\usepackage[utf8]{inputenc}\n\
\\usepackage[english,russian]{babel}\n\
\\usepackage{amsmath,amssymb,amsfonts,textcomp,latexsym,pb-diagram,amsopn}\n\
\\usepackage{cite,enumerate,float,indentfirst}\n\
\\usepackage{graphicx,xcolor}\n\
% Порядку для задаем размер полей страницы, дальше это нам пригодится\n\
\\usepackage[left=2mm, right=2mm, top=2mm, bottom=2mm]{geometry}\n\
% Включаем Gnuplottex\n\
\\usepackage{gnuplottex}\n\
\\begin{document}\n\
\\begin{figure}\n\
  \\centering\n\
  \\begin{gnuplot}\n\  '

    commText = "set terminal epslatex newstyle color size 17cm,8cm\n\
   set xzeroaxis lt -1\n\
   set yzeroaxis lt -1\n\
   set mxtics 4\n\
   set mytic 4\n\
   set autoscale\n\
   set tics nomirror out scale 0.75\n\
   set border 3 front lw 3\n\
   set style line 1 lt 1 lw 4 lc rgb '#4682b4' pt -1 \n\
   set style line 2 lt 1 lw 4 lc rgb '#ee0000' pt -1 \n\
   set style line 3 lt 1 lw 4 lc rgb '#008800' pt -1\n\
   set style line 4 lt 1 lw 4 lc rgb '#888800' pt -1\n\
   set style line 5 lt 1 lw 4 lc rgb '#00aaaa' pt -1\n\
   set style line 6 lt 1 lw 4 lc rgb '#cc0000' pt -1\n\
   set key bottom right   \n\
   set grid xtics lc rgb '#555555' lw 1 lt 0\n\
   set grid ytics lc rgb '#555555' lw 1 lt 0;"

    commGraph = "set title '{0}'\n\
set xlabel '{1}'\n\
set ylabel '{2}'\n  ".format(title, xlabel, ylabel, label, size[0], size[1])

    firstPlot = "plot 'dataOrig0.out' u 1:2 w p ps 3 ti '{0}',\\\n".format(
        OrKeysVect[0])

    orPlots = [
        "\t 'dataOrig{0}.out' u 1:2 w p ps 3 ti '{1}',\\\n".format(
            i + 1, OrKeysVect[i + 1]) for i in range(int(half) - 1)
    ]
    SorPlots = ''
    for i in range(len(orPlots)):
        SorPlots += orPlots[i]

    apPlots = [
        "\t 'dataAprx{0}.out' u 1:2 w l lw 5 ti '{1}',\\\n".format(
            i, ApKeysVect[i]) for i in range(len(arrs))
    ]
    SapPlots = ''
    for i in range(len(apPlots)):
        SapPlots += apPlots[i]

    tex_end = '\\end{gnuplot}\n\
\\end{figure}\n\
\\end{document}'

    with open("build.tex", 'w') as outfile:
        outfile.write(tex_header + commText + commGraph + firstPlot +
                      SorPlots + SapPlots + tex_end)

    scriptText = 'latex --shell-escape build.tex;\n\
dvips build.dvi;\n\
ps2pdf build.ps;\n\
pdfcrop build.pdf;\n\
pdf2svg build.pdf {0}.svg\n\
pdftoppm build-crop.pdf {0} -png;\n'.format(name)

    with open("script.sh", 'w') as outfile:
        outfile.write(scriptText)

    os.system("chmod +x script.sh; ./script.sh")
    return 1
Exemplo n.º 32
0
def plot_graphs_modes_markers(agreg_step):
    '''Funkce vykreslí grafy podle dat ve vstupních souborech a uloží je ve formátu PDF do složky output/graphs'''

    #agreguj_data_rezie_modes_markers(agreg_step)
    #priprav_data_pro_sloupcovy_graf_rezie_nizky_bitrate_modes_markers()
    #priprav_data_pro_sloupcovy_graf_rezie_vysoky_bitrate_modes_markers()
    '''# histogram rezie pro nizky bitrate
    pg.c('set xlabel "ZABEZPEČENÍ"; set ylabel "REŽIE ZABEZPEČENÍ [ % ]"')
    pg.c('unset key; set style data histogram; set style fill solid border; set style histogram clustered')
    pg.c("plot for [COL=2:3] 'output/graphs_data/agreg/histogram_nizky_bitrate_rezie_modes_markers.dat' using COL:xticlabels(1) title columnheader")
    pg.pdf('output/graphs/histogram_rezie_nizky_bitrate_modes_markers.pdf')

    # histogram rezie pro vysoky bitrate
    pg.c('set xlabel "ZABEZPEČENÍ"; set ylabel "REŽIE ZABEZPEČENÍ [ % ]"')
    pg.c('unset key; set style data histogram; set style fill solid border; set style histogram clustered')
    pg.c("plot for [COL=2:3] 'output/graphs_data/agreg/histogram_vysoky_bitrate_rezie_modes_markers.dat' using COL:xticlabels(1) title columnheader")
    pg.pdf('output/graphs/histogram_rezie_vysoky_bitrate_modes_markers.pdf')'''

    # Kolik % velikosti souboru zabírají markery v závislosti na bitrate
    pg.c('set xlabel "BITRATE"; set ylabel "REŽIE ZABEZPEČENÍ [ % ]"')
    pg.c('set yrange [0:65]; set xrange [0:2.5]; set key right top')
    pg.c("plot '" + str(graphs_data_bitrate_rezie_sop_eph_agreg_filename) +
         "' title 'SOP + EPH'  with lines lw 3")
    pg.c(
        "replot '" +
        str(graphs_data_bitrate_rezie_vsechny_mody_sop_eph_agreg_filename) +
        "' title 'Líné paralelní zpracování + SEGMARK + SOP + EPH'  with lines lw 3"
    )
    pg.pdf('output/graphs/bitrate_rezie_zabezpeceni_modes_markers.pdf')

    #agreguj_data_nedekomprimovatelnych_souboru( graphs_data_failed_na_poskozeni_bez_ochrany_filename,               graphs_data_failed_na_poskozeni_bez_ochrany_agreg_filename          )
    #agreguj_data_nedekomprimovatelnych_souboru( graphs_data_failed_na_poskozeni_vsechny_mody_sop_eph_filename,      graphs_data_failed_na_poskozeni_vsechny_mody_sop_eph_agreg_filename )

    # Kolik % velikosti souboru zabírají markery v závislosti na bitrate a měnících se PRECINCTS a sop+eph pro layers=12
    pg.c(
        'set key right bottom; set xlabel "POŠKOZENÍ [ % ]"; set ylabel "POČET NEDEKOMPRIMOVATELNÝCH SOUBORŮ [ % ]"'
    )
    #pg.c('set yrange [0.5:1]; set xrange [0:0.1]; set key right')
    pg.c('set yrange [0:100]; set xrange [-0.00005:0.0205]; set key right')
    pg.c("plot '" + str(graphs_data_fails_mode_none_agreg_filename) +
         "' title 'Bez ochrany'  with lines lw 3")
    pg.c("replot '" +
         str(graphs_data_failed_na_poskozeni_sop_eph_agreg_filename) +
         "' title 'SOP + EPH'  with lines lw 3")
    #pg.c("replot '" + str(graphs_data_failed_na_poskozeni_sop_eph_segmark_agreg_filename) + "' title 'SOP, EPH, SEGMARK'  with lines linestyle 5")
    pg.c("replot '" +
         str(graphs_data_fails_mode_lazyparallelsegmark_agreg_filename) +
         "' title 'Líné paralelní zpracování + SEGMARK'  with lines lw 3")
    pg.c(
        "replot '" +
        str(graphs_data_failed_na_poskozeni_vsechny_mody_sop_eph_agreg_filename
            ) +
        "' title 'Líné paralelní zpracování + SEGMARK + SOP + EPH'  with lines lw 3"
    )
    pg.pdf('output/graphs/poskozeni_neuspesne_soubory_modes_markers.pdf')
Exemplo n.º 33
0
def plot_baseline(base, base_min, suffix, det):
    plot_name = '10_baseline'
    if len(base) == 0:
        return
    dummy, fname = tempfile.mkstemp(prefix='tmp_baseline_%03d' % det,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_name, det_feat = detector_name(det)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    gp_set_defaults()
    gp.c('set label "' + det_name + ' ' + det_feat +
         ' - baseline" at graph 0, graph 1.04 noenhanced')
    gp.s([base, base_min], filename=fname)
    gp.c('set auto fix')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c('set ytics nomirror')
    gp.c('set ylabel "Amplitude (V)"')
    gp.c('set xlabel "Time (h)"')
    #gp.c('set yrange [%f:%f]' % (pmin, pmax))
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot "' + fname + '"' + " u (hour($1)):($2) not w l lt 6")
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 34
0
import PyGnuplot as gp
import numpy as np
X = np.arange(42)
Y = np.zeros(42)
# Load file
file1 = open('plots/plot00', 'r')
Lines = file1.readlines()

i = 0
for line in Lines:
    nums = line.split(' ')
    for i in range(len(nums)):
        Y[i] = nums[i]
gp.s([X, Y])
gp.c('set terminal pngcairo size 1100,1000 enhanced')
gp.c('set output "plot1.png"')
gp.c('plot "tmp.dat" u 1:2 w lp')
Exemplo n.º 35
0
def plotSNfit(result, vc, pidx, digi='D1'):
    ''' result : fitting results
        vc, variable carrier
        pidx power index
        digi = 'D1' or 'D2'
        '''
    vc.Tz = result.params['Tz'].value

    if digi == 'D1':
        f = vc.f1
        T = result.params['T1'].value
        G = result.params['G1'].value
        Tn = result.params['Tn1'].value
        data = np.array(vc.cPD1[pidx]) * 1.0

    if digi == 'D2':
        f = vc.f2
        T = result.params['T2'].value
        G = result.params['G2'].value
        Tn = result.params['Tn2'].value
        data = np.array(vc.cPD2[pidx]) * 1.0

    if digi == 'D12':
        f = vc.f1
        T = result.params['T12'].value
        G = result.params['G12'].value
        Tn = result.params['Tn12'].value
        data = np.array(vc.cPD3[pidx]) * 1.0

    if digi == 'D12c':
        f = vc.f1
        T = result.params['T12c'].value
        G = result.params['G12c'].value
        Tn = result.params['Tn12c'].value
        data = np.array(vc.cPD4[pidx]) * 1.0

    factor = f*h*vc.B*G  # factor to photon #
    SNf = fitfunc(G, Tn, T, f, vc)
    Amp = G*vc.B*kB*Tn

    title2 = (digi + ', RF-Drive ' + str(vc.d2.lin[pidx]) + ' G ' + str(np.round(G/1e7, 2)) +
              'e7 = ' + str(np.round(np.log10(G)*10.0, 2)) + 'dB  T ' + str(np.round(Tn, 2)) + 'K')
    dataname = digi + '_' + str(vc.d2.lin[pidx]) + '.dat'
    gp.c('')
    gp.figure()
    # gp.c('clear')
    gp.s([vc.I*1e6, (data)/factor, (SNf)/factor, np.ones_like(data)*Amp/factor],
         filename=vc.resultfolder+dataname)
    gp.c('set title "' + title2 + '"')
    gp.c('set xrange[-19:19]')
    gp.c('set key center top')
    gp.c('plot "' + dataname + '" u 1:2 w l t "Data" ')
    gp.c('replot "' + dataname + '" u 1:3 w l t "Fit" ')
    gp.c('replot "' + dataname + '" u 1:4 w l t "Amplifier Noise" ')
    gp.c('save "' + dataname[:-3] + 'gn"')
    gp.pdf(dataname[:-3]+'pdf')
    print dataname[:-3]+'pdf'
Exemplo n.º 36
0
def plot_pulse_shapes(shapes, suffix, det):
    plot1_name = 'XX_shapes'
    plot2_name = 'XX_normalized_shapes'
    dummy, fname = tempfile.mkstemp(prefix='tmp_shapes_%03d' % det,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_name, det_feat = detector_name(det)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot1_name, suffix)),
                exist_ok=True)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot2_name, suffix)),
                exist_ok=True)
    of = open(fname, 'w')
    for cnt, el in enumerate(shapes):
        for i, v in enumerate(el[0]):
            of.write("%d %f %d %f\n" % (i, v, cnt, el[1]))
        of.write("\n\n")

    gp_set_defaults()
    gp.c('set label "' + det_name + ' ' + det_feat +
         '" at graph 0, graph 1.04 noenhanced')
    gp.c('set auto fix')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c('load "blues.pal"')
    gp.c('set ylabel "Amplitude (V)"')
    gp.c('set xlabel "Time (ms)"')
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot2_name, suffix, plot2_name, suffix, ext))
        gp.c('plot [][] "' + fname + '" u 1:($2 / $4):3 not w l lt palette')
        gp.c('set out')
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot1_name, suffix, plot1_name, suffix, ext))
        gp.c('unset colorbox')
        gp.c('plot [][1:] "' + fname + '" u 1:2:3 not w l lt palette')
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 37
0
def plot_rate(rate, window, suffix, det):
    plot_name = 'XX_rate'
    dummy, fname = tempfile.mkstemp(prefix='tmp_rate_%03d' % det,
                                    suffix='.dat',
                                    dir=cfg.tmpdir,
                                    text=True)
    det_name, det_feat = detector_name(det)
    os.makedirs(os.path.join(cfg.global_odir, det_name,
                             '%s%s' % (plot_name, suffix)),
                exist_ok=True)
    gp_set_defaults()
    gp.c('set label "' + det_name + ' ' + det_feat +
         '" at graph 0, graph 1.04 noenhanced')
    gp.s([rate], filename=fname)
    gp.c('set auto fix')
    gp.c('set offsets graph 0.1, graph 0.1, graph 0.1, graph 0.1')
    gp.c('set ylabel "Rate (Hz)"')
    gp.c('set xlabel "Time (h)"')
    for ext in cfg.cfg['plot']['output_format'].split():
        gp_set_terminal(ext)
        gp.c('set out odir."%s/%s%s/%s%s.%s"' %
             (det_name, plot_name, suffix, plot_name, suffix, ext))
        gp.c('plot [][] "' + fname + '" u ($0 / 3600.):($1/' + str(window) +
             ') not w l lt 6')
        gp.c('set out')
    fn_collector.append(fname)
    os.close(dummy)
Exemplo n.º 38
0
def plot_graphs_modes(agreg_step):
    '''Funkce vykreslí grafy podle dat ve vstupních souborech a uloží je ve formátu PDF do složky output/graphs'''

    #agreguj_data_rezie_modu(agreg_step)
    #priprav_data_pro_sloupcovy_graf_rezie_nizky_bitrate_modes()
    #priprav_data_pro_sloupcovy_graf_rezie_vysoky_bitrate_modes()
    '''# histogram rezie pro nizky bitrate
    pg.c('set xlabel "ZABEZPEČENÍ"; set ylabel "REŽIE ZABEZPEČENÍ [ % ]"')
    pg.c('unset key; set style data histogram; set style fill solid border; set style histogram clustered')
    pg.c("plot for [COL=2:3] 'output/graphs_data/agreg/histogram_nizky_bitrate_rezie_modes.dat' using COL:xticlabels(1) title columnheader")
    pg.pdf('output/graphs/histogram_rezie_nizky_bitrate_modes.pdf')

    # histogram rezie pro vysoky bitrate
    pg.c('set xlabel "ZABEZPEČENÍ"; set ylabel "REŽIE ZABEZPEČENÍ [ % ]"')
    pg.c('unset key; set style data histogram; set style fill solid border; set style histogram clustered')
    pg.c("plot for [COL=2:3] 'output/graphs_data/agreg/histogram_vysoky_bitrate_rezie_modes.dat' using COL:xticlabels(1) title columnheader")
    pg.pdf('output/graphs/histogram_rezie_vysoky_bitrate_modes.pdf')'''
    '''agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_all_filename,             graphs_data_fails_mode_all_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_none_filename,            graphs_data_fails_mode_none_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_bypass_filename,          graphs_data_fails_mode_bypass_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_parallel_filename,        graphs_data_fails_mode_parallel_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_lazyparallel_filename,    graphs_data_fails_mode_lazyparallel_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_ertermsegmark_filename,   graphs_data_fails_mode_ertermsegmark_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_segmark_filename,         graphs_data_fails_mode_segmark_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_bypasssegmark_filename,   graphs_data_fails_mode_bypasssegmark_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_parallelsegmark_filename, graphs_data_fails_mode_parallelsegmark_agreg_filename)
    agreguj_data_nedekomprimovatelnych_souboru(graphs_data_fails_mode_lazyparallelsegmark_filename, graphs_data_fails_mode_lazyparallelsegmark_agreg_filename)'''

    pg.c(
        'set key right bottom; set xlabel "POŠKOZENÍ [ % ]"; set ylabel "POČET NEDEKOMPRIMOVATELNÝCH SOUBORŮ [ % ]"'
    )
    # pg.c('set yrange [0.5:1]; set xrange [0:0.1]; set key right')
    pg.c('set yrange [0:100]; set xrange [-0.00005:0.0205]; set key right')

    pg.c("plot '" + str(graphs_data_fails_mode_none_agreg_filename) +
         "' title 'Žádný mód'  with lines lw 3")
    pg.c("replot '" + str(graphs_data_fails_mode_bypass_agreg_filename) +
         "' title 'Liné zpracování'  with lines lw 3")
    pg.c("replot '" + str(graphs_data_fails_mode_parallel_agreg_filename) +
         "' title 'Paralelní zpracování'  with lines lw 3")
    #pg.c("replot '" + str(graphs_data_fails_mode_lazyparallel_agreg_filename) + "' title 'Líné paralelní zpracování'  with lines linestyle 4")
    pg.c("replot '" +
         str(graphs_data_fails_mode_ertermsegmark_agreg_filename) +
         "' title 'ERTERM + SEGMARK'  with lines lw 3")
    #pg.c("replot '" + str(graphs_data_fails_mode_segmark_agreg_filename) + "' title 'SEGMARK'  with lines linestyle 6")
    #pg.c("replot '" + str(graphs_data_fails_mode_bypasssegmark_agreg_filename) + "' title 'BYPASS, SEGMARK'  with lines linestyle 7")
    #pg.c("replot '" + str(graphs_data_fails_mode_parallelsegmark_agreg_filename) + "' title 'Paralelní zpracování + SEGMARK'  with lines linestyle 8")
    pg.c("replot '" +
         str(graphs_data_fails_mode_lazyparallelsegmark_agreg_filename) +
         "' title 'Líné paralelní zpracování + SEGMARK' with lines lw 3")
    #pg.c("replot '" + str(graphs_data_fails_mode_all_agreg_filename) + "' title 'Všechny módy'  with lines linestyle 12")

    pg.pdf('output/graphs/poskozeni_neuspesne_soubory_modes.pdf')