Beispiel #1
0
    def plot_event_heatmap(self, event, board, ax=None):
        if (ax is None):
            fig, ax = plt.subplots()
        #requires that all channels have the
        #same time values
        x = []
        y = []
        z = []
        channels = self.get_chs()
        for j, ch in enumerate(channels):
            wfm = self.get_waveform(event, board, ch)
            if (wfm is None):
                return
            times = wfm.get_times()
            sig = wfm.get_signal()
            if (sig is None):
                continue
            for i, t in enumerate(times):
                voltage = sig[i]
                x.append(t)
                y.append(ch)
                z.append(voltage)

        xbins = times
        ybins = channels
        h = ax.hist2d(x, y, bins=[xbins, ybins], weights=z,
                      cmap=plt.inferno())  #, cmax=20, cmin=-70)
        plt.colorbar(h[3], ax=ax)
Beispiel #2
0
def spect(_data, dbmin=80):
    plt.figure()
    for ii in range(_data.shape[1]):
        plt.subplot(_data.shape[1]*100+10+ii+1)
        f, t, Sxx = scipy.signal.spectrogram(_data[:,ii], fs=fs, axis=0, scaling='spectrum', nperseg=fs//4, noverlap=fs//8, detrend='linear', mode='psd', window='hann')
        Sxx[Sxx==0] = 10**(-20)
        plt.pcolormesh(t, f, 20*np.log10(abs(Sxx)), shading='gouraud', cmap=plt.inferno(),vmax=20*np.log10(abs(Sxx)).max(), vmin=20*np.log10(abs(Sxx)).max()-dbmin)
        plt.ylim((0, fs//8))
        plt.colorbar()
        plt.ylabel('Frequency [Hz]')
        plt.xlabel('Time [sec]')
        plt.tight_layout()
        plt.show()
    def show_3d_results(self):
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')

        result = self.anfis_estimate_labels(self.premises, self.op, self.tsk)

        ax.scatter(self.training_data[0],
                   self.training_data[1],
                   self.training_data[2],
                   c=result.flatten(),
                   cmap=plt.inferno())

        fig.canvas.set_window_title('Results')
        plt.show()
    def show_3d_results_for_x(self, x: list):
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        input = np.array(x)
        fv = input[:self.end_x1].reshape(np.shape(self.premises))
        op = input[self.end_x1:self.end_x2]
        tsk = input[self.end_x2:]
        result = self.anfis_estimate_labels(fv, op, tsk)

        ax.scatter(self.training_data[0],
                   self.training_data[1],
                   self.training_data[2],
                   c=result.flatten(),
                   cmap=plt.inferno())

        fig.canvas.set_window_title('Results')
        plt.show()
Beispiel #5
0
def plot(strings, compact):
    plotData = []
    for i in range(len(compact)):
        amountA = 0
        amountC = 0
        amountG = 0
        amountT = 0
        for string in strings:
            if string[i] == 'A':
                amountA += 1
            elif string[i] == 'C':
                amountC += 1
            elif string[i] == 'G':
                amountG += 1
            elif string[i] == 'T':
                amountT += 1
        total = amountA + amountC + amountG + amountT
        plotData.append([
            amountA / total, amountC / total, amountG / total, amountT / total
        ])

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    x = [x[0] for x in plotData]
    y = [x[1] for x in plotData]
    z = [x[2] for x in plotData]
    c = [x[3] for x in plotData]

    ax.set_xlabel('A')
    ax.set_ylabel('C')
    ax.set_zlabel('G')
    # ax.set_clabel('T')

    img = ax.scatter(x, y, z, c=c, cmap=plt.inferno())
    bar = fig.colorbar(img)
    bar.set_label('T')
    plt.show()
Beispiel #6
0
def main(**kwargs):
    filenameBase = 'resources/output/2018-01-15-215539'
    if 'filename' in kwargs:
        filenameBase = kwargs['filename']
    width = 50
    if 'width' in kwargs:
        width = int(kwargs['width'])
    height = 10
    if 'height' in kwargs:
        height = int(kwargs['height'])
    live = False
    if 'live' in kwargs:
        live = kwargs['live'].lower() in ("yes", "true", "t", "1")
    filename = filenameBase + '.csv'
    temperatureFilename = filenameBase + '-temperature.csv'

    temperatureData, data, xData, avgT, minT, maxT, core2surfaceT, deltaT, timeTotal = [], [], [], [],[], [], [], [], []

    def loadCSV():
        try:
            _tData = loadTemperaturePhaseData()
            _data = genfromtxt(filename, delimiter=',')[:, 2:]
            return _tData, _data
        except IndexError:
            time.sleep(1)
            return loadCSV()

    def loadTemperaturePhaseData():
        with open(temperatureFilename, 'rt') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            try:
                next(reader)
            except:
                time.sleep(1)
                return loadTemperaturePhaseData()
            arr = []
            for row in reader:
                arr.append(
                    TemperaturePhaseData(row[0], row[1], row[2], row[3],
                                         row[4], row[5], row[6], row[7]))
            return arr

    def load():
        _xData, _avgT, _minT, _maxT, _core2surfaceT, _deltaT, _time = [], [], [], [], [], [], []

        _tData, _data = loadCSV()

        for j in range(0, len(_tData)):
            _xData.append(j)
            _avgT.append(_tData[j].average)
            _minT.append(_tData[j].min)
            _maxT.append(_tData[j].max)
            _core2surfaceT.append(_tData[j].core2SurfaceDelta)
            _deltaT.append(_tData[j].iterationDeltaTemp)
            _time.append(_tData[j].timeTotal)
        return _tData, _data, _xData, _avgT, _minT, _maxT, _core2surfaceT, _deltaT, _time

    if not live:
        temperatureData, data, xData, avgT, minT, maxT, core2surfaceT, deltaT, timeTotal = load(
        )

    fig = plt.figure(1, figsize=(16, 9), dpi=100)
    fig.suptitle('Current phase: null\nTime: 00h 00m 00s \nLiveMode: ' +
                 str(live))
    minTemp = fig.add_subplot(521)
    minTLine, = minTemp.plot(minT)
    minTemp.set_title("Minimal temperature")

    maxTemp = fig.add_subplot(522)
    maxTLine, = maxTemp.plot(maxT)
    maxTemp.set_title("Maximal temperature")

    avgTemp = fig.add_subplot(523)
    avgTempLine, = avgTemp.plot(avgT)
    avgTemp.set_title("Average temperature")

    core2surface = fig.add_subplot(524)
    core2surfaceLine, = core2surface.plot(xData, core2surfaceT)
    core2surface.set_title("Difference between surface and core")

    deltaTemp = fig.add_subplot(525)
    deltaTLine, = deltaTemp.plot(xData, deltaT)
    deltaTemp.set_title("Temperature delta since last iteration")
    minTemp.grid(True)
    maxTemp.grid(True)
    deltaTemp.grid(True)
    avgTemp.grid(True)
    core2surface.grid(True)

    if not live:
        xTicks = []
        labels = []
        j = len(temperatureData)
        for i in range(0, j, max(math.ceil(0.1 * j), 2)):
            xTicks.append(i)
            labels.append(timeTotal[i])
        minTemp.set_yticks([min(minT), max(minT) + 1])
        minTemp.set_xticks(xTicks)
        minTemp.set_xticklabels(labels, rotation=20)

        maxTemp.set_yticks([round(min(maxT), 2), round(max(maxT) + 1, 2)])
        maxTemp.set_xticks([0, j])
        maxTemp.set_xticks(xTicks)
        maxTemp.set_xticklabels(labels, rotation=20)

        avgTemp.set_yticks([round(min(avgT), 2), round(max(avgT) + 1, 2)])
        avgTemp.set_xticks([0, j])
        avgTemp.set_xticks(xTicks)
        avgTemp.set_xticklabels(labels, rotation=20)

        core2surface.set_yticks(
            [round(min(core2surfaceT), 2),
             round(max(core2surfaceT) + 1, 2)])
        core2surface.set_xticks([0, j])
        core2surface.set_xticks(xTicks)
        core2surface.set_xticklabels(labels, rotation=20)

        deltaTemp.set_yticks(
            [round(min(deltaT), 2), 0,
             round(max(deltaT) + 1, 2)])
        deltaTemp.set_xticks([0, j])
        deltaTemp.set_xticks(xTicks)
        deltaTemp.set_xticklabels(labels, rotation=20)

    heatDistribution = fig.add_subplot(2, 1, 2)
    heatDistributionImage = plt.imshow(np.zeros((height, width)),
                                       cmap=plt.get_cmap('jet'),
                                       vmin=0,
                                       vmax=1200)
    heatDistribution.set_title('Heat distribution in element',
                               fontsize=14,
                               fontweight='bold')
    heatDistribution.set_xlabel('Element width')
    heatDistribution.set_ylabel('Element height')
    heatDistribution.grid(True)

    plt.colorbar(heatDistributionImage)
    plt.subplots_adjust(top=0.85, wspace=0.25, hspace=1)
    plt.inferno()
    fig.show()

    def updatefig(j):
        # set the data in the axesimage object
        fig.suptitle(
            'Current phase: ' + temperatureData[j].phase + '\nTime: ' +
            temperatureData[j].timeTotal + '\n TempAvg: ' +
            str(round(temperatureData[j].average, 2)) +
            "\N{DEGREE SIGN}C   TempMax:" +
            str(round(temperatureData[j].max, 2)) +
            "\N{DEGREE SIGN}C    TempMin: " +
            str(round(temperatureData[j].min, 2)) +
            "\N{DEGREE SIGN}C\n Diffrence between core and surface: " +
            str(round(temperatureData[j].core2SurfaceDelta, 2)) +
            "\N{DEGREE SIGN}C\nAvgerage delta temperature per minute: " +
            str(round(temperatureData[j].iterationDeltaTemp, 2)) +
            "\N{DEGREE SIGN}C")
        avgTempLine.set_data(xData[:j], avgT[:j])
        minTLine.set_data(xData[:j], minT[:j])
        maxTLine.set_data(xData[:j], maxT[:j])
        core2surfaceLine.set_data(xData[:j], core2surfaceT[:j])
        deltaTLine.set_data(xData[:j], deltaT[:j])
        heatDistributionImage.set_array(np.reshape(data[j], [height, width]))
        # return the artists set

        return [
            avgTempLine, minTLine, maxTLine, core2surfaceLine, deltaTLine,
            heatDistributionImage
        ]

    def liveUpdateFig(j, iter=0):
        if iter > 1000:
            return null
        tempData, d, xD, avgTe, minTe, maxTe, core2surfaceTe, deltaTe, t = load(
        )
        j = min(int(j), len(tempData))

        if len(tempData) == 0 or j >= len(tempData):
            time.sleep(1)
            return liveUpdateFig(j, iter + 1)

        fig.suptitle(
            'Current phase: ' + tempData[j].phase + '\nTime: ' +
            tempData[j].timeTotal + '\n TempAvg: ' +
            str(round(tempData[j].average, 2)) +
            "\N{DEGREE SIGN}C   TempMax:" + str(round(tempData[j].max, 2)) +
            "\N{DEGREE SIGN}C    TempMin: " + str(round(tempData[j].min, 2)) +
            "\N{DEGREE SIGN}C\n Diffrence between core and surface: " +
            str(round(tempData[j].core2SurfaceDelta, 2)) +
            "\N{DEGREE SIGN}C\nAvgerage delta temperature per minute: " +
            str(round(tempData[j].iterationDeltaTemp, 2)) + "\N{DEGREE SIGN}C")

        avgTempLine.set_data(xD[:j], avgTe[:j])
        minTLine.set_data(xD[:j], minTe[:j])
        maxTLine.set_data(xD[:j], maxTe[:j])
        core2surfaceLine.set_data(xD[:j], core2surfaceTe[:j])
        deltaTLine.set_data(xD[:j], deltaTe[:j])
        heatDistributionImage.set_array(np.reshape(d[j], [height, width]))

        xTicks = []
        labels = []
        for i in range(0, j, max(math.ceil(0.1 * j), 2)):
            xTicks.append(i)
            labels.append(t[i])
        minTemp.set_yticks([min(minTe), max(minTe) + 1])
        minTemp.set_xticks(xTicks)
        minTemp.set_xticklabels(labels, rotation=20)

        maxTemp.set_yticks([round(min(maxTe), 2), round(max(maxTe) + 1, 2)])
        maxTemp.set_xticks([0, j])
        maxTemp.set_xticks(xTicks)
        maxTemp.set_xticklabels(labels, rotation=20)

        avgTemp.set_yticks([round(min(avgTe), 2), round(max(avgTe) + 1, 2)])
        avgTemp.set_xticks([0, j])
        avgTemp.set_xticks(xTicks)
        avgTemp.set_xticklabels(labels, rotation=20)

        core2surface.set_yticks(
            [round(min(core2surfaceTe), 2),
             round(max(core2surfaceTe) + 1, 2)])
        core2surface.set_xticks([0, j])
        core2surface.set_xticks(xTicks)
        core2surface.set_xticklabels(labels, rotation=20)

        deltaTemp.set_yticks(
            [round(min(deltaTe), 2), 0,
             round(max(deltaTe) + 1, 2)])
        deltaTemp.set_xticks([0, j])
        deltaTemp.set_xticks(xTicks)
        deltaTemp.set_xticklabels(labels, rotation=20)

        # return the artists set
        return [
            avgTempLine, minTLine, maxTLine, core2surfaceLine, deltaTLine,
            heatDistributionImage
        ]

    if not live:
        plt.rcParams[
            'animation.ffmpeg_path'] = 'C:\\Users\\Wojci\\Documents\\GitHub\\AGH_FEM\\ffmpeg-3.4.1-win64-static\\bin\\ffmpeg.exe'
        Writer = animation.writers['ffmpeg']
        writer = Writer(fps=15,
                        metadata=dict(artist='Wojciech Mazur'),
                        bitrate=1800)
        ani = animation.FuncAnimation(fig,
                                      updatefig,
                                      frames=range(len(data)),
                                      interval=10,
                                      blit=False)
        ani.save(filenameBase + ".mp4", writer=writer)
    else:
        ani = animation.FuncAnimation(fig,
                                      liveUpdateFig,
                                      interval=100,
                                      blit=False)
    plt.show()
Beispiel #7
0
     full_clip = 30 * 1000  # Runs in miliseconds
     rand_start = np.random.randint(0, len(mp3_form) - full_clip)
     mp3_wav = mp3_form[rand_start:(rand_start + full_clip)]
     destin = external_example + '/' + example_name[0][:-4] + '.wav'
     mp3_wav.export(destin, format='wav')
     exit()
 song = external_example + '/' + example_name[1]
 y, sr = librosa.load(song, mono=True)
 sp = librosa.feature.melspectrogram(y=y,
                                     sr=sr,
                                     n_mels=323,
                                     n_fft=4096,
                                     hop_length=2048)
 sp = librosa.power_to_db(sp, ref=np.max)
 sp /= np.mean(sp)
 plt.inferno()
 plt.imshow(sp)
 examp = torch.from_numpy(sp)
 examp = examp.type(torch.FloatTensor)
 examp = examp[None, None, :, :]
 image = Variable(examp)
 list_viz = fake_network(image, len(labels))
 for ind, viz_im in enumerate(list_viz):
     im = viz_im.data.numpy()
     if len(im.shape) > 2:
         im_show = np.transpose(im[0, 2, :, :])
     else:
         im_show = im[0, :]
     plt.figure()
     plt.plot(im_show, 'o')
     plt.title(title[ind])
Beispiel #8
0
def plot_contourPLT(rate_stats,
                    rate,
                    func_select=np.nanmean,
                    height=10,
                    width=15,
                    title_add='',
                    xtitle='s1',
                    ytitle='s2',
                    savefig='',
                    xlim=[],
                    ylim=[],
                    clim=[],
                    levels=6):
    '''
    plot surface contour.
    '''
    bi_select = list(rate_stats.keys())

    fig = []
    d = 0

    props = [(*bi, func_select(rate_stats[bi][rate]['pval']))
             for bi in bi_select]
    props = np.array(props)

    gradient = props[:, 2]

    plt.inferno()
    fig = plt.figure(figsize=(width, height))

    X = props[:, 0]
    Y = props[:, 1]

    dims = [len(set(X)), len(set(Y))]
    dims = tuple(dims)

    X = X.reshape(dims)
    Y = Y.reshape(dims)
    gradient = gradient.reshape(dims)

    if clim:
        ctr_levels = np.linspace(clim[0], clim[1], levels + 1)
        cp = plt.contourf(X, Y, gradient, levels=ctr_levels, cmap=cm.inferno)
    else:
        cp = plt.contourf(X, Y, gradient, levels=levels, cmap=cm.inferno)

    fig.colorbar(cp)
    plt.title('rate: {} '.format(rate) + title_add)
    plt.xlabel(xtitle)
    if xlim:
        plt.xlim(*xlim)
    plt.ylabel(ytitle)
    if ylim:
        plt.ylim(*ylim)
    if savefig:
        os.makedirs(os.path.dirname(savefig), exist_ok=True)
        plt.savefig(savefig)
        plt.close()

    else:
        plt.show()
        plt.close()
Beispiel #9
0
x1 = df.ix[0:, 'x1']
x2 = df.ix[0:, 'x2']
x3 = df.ix[0:, 'x3']
y = df.ix[0:, 'y']

if sys.argv[1:] == ['winter']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.winter())
elif sys.argv[1:] == ['cool']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.cool())
elif sys.argv[1:] == ['viridis']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.viridis())
elif sys.argv[1:] == ['plasma']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.plasma())
elif sys.argv[1:] == ['inferno']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.inferno())
elif sys.argv[1:] == ['jet']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.jet())
elif sys.argv[1:] == ['gist_ncar']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.gist_ncar())
elif sys.argv[1:] == ['rainbow']:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.nipy_spectral())
else:
    p = ax2.scatter(x1, x2, x3, c=y, cmap=plt.nipy_spectral())

fig.colorbar(p)

ax2.set_xlabel('X1')
ax2.set_ylabel('X2')
ax2.set_zlabel('X3')