Example #1
0
def plot_SpikeSlab(parameterized, fignum=None, ax=None, colors=None, side_by_side=True):
    """
    Plot latent space X in 1D:

        - if fig is given, create input_dim subplots in fig and plot in these
        - if ax is given plot input_dim 1D latent space plots of X into each `axis`
        - if neither fig nor ax is given create a figure with fignum and plot in there

    colors:
        colors of different latent space dimensions input_dim

    """
    if ax is None:
        if side_by_side:
            fig = pb.figure(num=fignum, figsize=(16, min(12, (2 * parameterized.mean.shape[1]))))
        else:
            fig = pb.figure(num=fignum, figsize=(8, min(12, (2 * parameterized.mean.shape[1]))))
    if colors is None:
        from ..Tango import mediumList
        from itertools import cycle
        colors = cycle(mediumList)
        pb.clf()
    else:
        colors = iter(colors)
    plots = []
    means, variances, gamma = parameterized.mean, parameterized.variance, parameterized.binary_prob
    x = np.arange(means.shape[0])
    for i in range(means.shape[1]):
        if side_by_side:
            sub1 = (means.shape[1],2,2*i+1)
            sub2 = (means.shape[1],2,2*i+2)
        else:
            sub1 = (means.shape[1]*2,1,2*i+1)
            sub2 = (means.shape[1]*2,1,2*i+2)

        # mean and variance plot
        a = fig.add_subplot(*sub1)
        a.plot(means, c='k', alpha=.3)
        plots.extend(a.plot(x, means.T[i], c=colors.next(), label=r"$\mathbf{{X_{{{}}}}}$".format(i)))
        a.fill_between(x,
                        means.T[i] - 2 * np.sqrt(variances.T[i]),
                        means.T[i] + 2 * np.sqrt(variances.T[i]),
                        facecolor=plots[-1].get_color(),
                        alpha=.3)
        a.legend(borderaxespad=0.)
        a.set_xlim(x.min(), x.max())
        if i < means.shape[1] - 1:
            a.set_xticklabels('')
        # binary prob plot
        a = fig.add_subplot(*sub2)
        a.bar(x,gamma[:,i],bottom=0.,linewidth=1.,width=1.0,align='center')
        a.set_xlim(x.min(), x.max())
        a.set_ylim([0.,1.])
    pb.draw()
    fig.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95))
    return fig
Example #2
0
def plot_SpikeSlab(parameterized, fignum=None, ax=None, colors=None, side_by_side=True):
    """
    Plot latent space X in 1D:

        - if fig is given, create input_dim subplots in fig and plot in these
        - if ax is given plot input_dim 1D latent space plots of X into each `axis`
        - if neither fig nor ax is given create a figure with fignum and plot in there

    colors:
        colors of different latent space dimensions input_dim

    """
    if ax is None:
        if side_by_side:
            fig = pb.figure(num=fignum, figsize=(16, min(12, (2 * parameterized.mean.shape[1]))))
        else:
            fig = pb.figure(num=fignum, figsize=(8, min(12, (2 * parameterized.mean.shape[1]))))
    if colors is None:
        colors = pb.gca()._get_lines.color_cycle
        pb.clf()
    else:
        colors = iter(colors)
    plots = []
    means, variances, gamma = parameterized.mean, parameterized.variance, parameterized.binary_prob
    x = np.arange(means.shape[0])
    for i in range(means.shape[1]):
        if side_by_side:
            sub1 = (means.shape[1],2,2*i+1)
            sub2 = (means.shape[1],2,2*i+2)
        else:
            sub1 = (means.shape[1]*2,1,2*i+1)
            sub2 = (means.shape[1]*2,1,2*i+2)

        # mean and variance plot
        a = fig.add_subplot(*sub1)
        a.plot(means, c='k', alpha=.3)
        plots.extend(a.plot(x, means.T[i], c=colors.next(), label=r"$\mathbf{{X_{{{}}}}}$".format(i)))
        a.fill_between(x,
                        means.T[i] - 2 * np.sqrt(variances.T[i]),
                        means.T[i] + 2 * np.sqrt(variances.T[i]),
                        facecolor=plots[-1].get_color(),
                        alpha=.3)
        a.legend(borderaxespad=0.)
        a.set_xlim(x.min(), x.max())
        if i < means.shape[1] - 1:
            a.set_xticklabels('')
        # binary prob plot
        a = fig.add_subplot(*sub2)
        a.bar(x,gamma[:,i],bottom=0.,linewidth=0,width=1.0,align='center')
        a.set_xlim(x.min(), x.max())
        a.set_ylim([0.,1.])
    pb.draw()
    fig.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95))
    return fig
Example #3
0
def plot(parameterized, fignum=None, ax=None, colors=None, figsize=(12, 6)):
    """
    Plot latent space X in 1D:

        - if fig is given, create input_dim subplots in fig and plot in these
        - if ax is given plot input_dim 1D latent space plots of X into each `axis`
        - if neither fig nor ax is given create a figure with fignum and plot in there

    colors:
        colors of different latent space dimensions input_dim

    """
    if ax is None:
        fig = pb.figure(num=fignum, figsize=figsize)
    if colors is None:
        from ..Tango import mediumList
        from itertools import cycle
        colors = cycle(mediumList)
        pb.clf()
    else:
        colors = iter(colors)
    lines = []
    fills = []
    bg_lines = []
    means, variances = parameterized.mean.values, parameterized.variance.values
    x = np.arange(means.shape[0])
    for i in range(means.shape[1]):
        if ax is None:
            a = fig.add_subplot(means.shape[1], 1, i + 1)
        elif isinstance(ax, (tuple, list)):
            a = ax[i]
        else:
            raise ValueError("Need one ax per latent dimension input_dim")
        bg_lines.append(a.plot(means, c='k', alpha=.3))
        lines.extend(
            a.plot(x,
                   means.T[i],
                   c=next(colors),
                   label=r"$\mathbf{{X_{{{}}}}}$".format(i)))
        fills.append(
            a.fill_between(x,
                           means.T[i] - 2 * np.sqrt(variances.T[i]),
                           means.T[i] + 2 * np.sqrt(variances.T[i]),
                           facecolor=lines[-1].get_color(),
                           alpha=.3))
        a.legend(borderaxespad=0.)
        a.set_xlim(x.min(), x.max())
        if i < means.shape[1] - 1:
            a.set_xticklabels('')
    pb.draw()
    a.figure.tight_layout(h_pad=.01)  # , rect=(0, 0, 1, .95))
    return dict(lines=lines, fills=fills, bg_lines=bg_lines)
Example #4
0
def plotIsoStaImpedance(ax, loc, array, flag, par='abs',
                        pSym='s', pColor=None, addLabel='', zorder=1):

    appResFact = 1/(8*np.pi**2*10**(-7))
    treshold = 1.0 # 1 meter
    indUniSta = np.sqrt(np.sum((array[['x','y']].view((float,2))-loc)**2,axis=1)) < treshold
    freq = array['freq'][indUniSta]

    if par == 'abs':
        zPlot = np.abs(array[flag][indUniSta])
    elif par == 'real':
        zPlot = np.real(array[flag][indUniSta])
    elif par == 'imag':
        zPlot = np.imag(array[flag][indUniSta])
    elif par == 'res':
        zPlot = (appResFact/freq)*np.abs(array[flag][indUniSta])**2
    elif par == 'phs':
        zPlot = np.arctan2(array[flag][indUniSta].imag,array[flag][indUniSta].real)*(180/np.pi)

    if not pColor:
        if 'xx' in flag:
            lab = 'XX'
            pColor = 'g'
        elif 'xy' in flag:
            lab = 'XY'
            pColor = 'r'
        elif 'yx' in flag:
            lab = 'YX'
            pColor = 'b'
        elif 'yy' in flag:
            lab = 'YY'
            pColor = 'y'

    ax.plot(freq,zPlot,color=pColor,marker=pSym,label=flag+addLabel,zorder=zorder)
Example #5
0
def plot(parameterized, fignum=None, ax=None, colors=None, figsize=(12, 6)):
    """
    Plot latent space X in 1D:

        - if fig is given, create input_dim subplots in fig and plot in these
        - if ax is given plot input_dim 1D latent space plots of X into each `axis`
        - if neither fig nor ax is given create a figure with fignum and plot in there

    colors:
        colors of different latent space dimensions input_dim

    """
    if ax is None:
        fig = pb.figure(num=fignum, figsize=figsize)
    if colors is None:
        colors = pb.gca()._get_lines.color_cycle
        pb.clf()
    else:
        colors = iter(colors)
    lines = []
    fills = []
    bg_lines = []
    means, variances = parameterized.mean.values, parameterized.variance.values
    x = np.arange(means.shape[0])
    for i in range(means.shape[1]):
        if ax is None:
            a = fig.add_subplot(means.shape[1], 1, i + 1)
        elif isinstance(ax, (tuple, list)):
            a = ax[i]
        else:
            raise ValueError("Need one ax per latent dimension input_dim")
        bg_lines.append(a.plot(means, c='k', alpha=.3))
        lines.extend(a.plot(x, means.T[i], c=colors.next(), label=r"$\mathbf{{X_{{{}}}}}$".format(i)))
        fills.append(a.fill_between(x,
                        means.T[i] - 2 * np.sqrt(variances.T[i]),
                        means.T[i] + 2 * np.sqrt(variances.T[i]),
                        facecolor=lines[-1].get_color(),
                        alpha=.3))
        a.legend(borderaxespad=0.)
        a.set_xlim(x.min(), x.max())
        if i < means.shape[1] - 1:
            a.set_xticklabels('')
    pb.draw()
    a.figure.tight_layout(h_pad=.01) # , rect=(0, 0, 1, .95))
    return dict(lines=lines, fills=fills, bg_lines=bg_lines)
def fitting_variables_calculating_parameters(dict_of_data):
    x = dict_of_data.get(x)
    dx = dict_of_data.get(dx)
    y = dict_of_data.get(y)
    dy = dict_of_data.get(dy)
    N = len(x)
    x_roof, x_square_roof, x_roof_square, y_roof, xy_roof, xy_square_roof, dy_square_roof, dy_power_minus2 = 0, 0, 0, 0, 0, 0, 0, 0

    #now to assign the data to the variables
    for k in range(0, N):
        x_roof = x_roof + (x[k] / (dy[k]**2))
        y_roof = y_roof + (y[k] / (dy[k]**2))
        xy_roof = xy_roof + ((x[k] * y[k]) / (dy[k]**2))
        x_square_roof += ((x[k]**2) / (dy[k]**2))
        dy_square_roof += 1
        dy_power_minus2 += (dy[k]**(-2))
    x_roof = x_roof / dy_power_minus2
    y_roof = y_roof / dy_power_minus2
    xy_roof = xy_roof / dy_power_minus2
    x_roof_square = x_roof**2
    x_square_roof = x_square_roof / dy_power_minus2
    dy_square_roof = dy_square_roof / dy_power_minus2

    #now we calculate the fitting parameters
    A = (xy_roof - (x_roof * y_roof)) / (x_square_roof - x_roof_square)
    dA = numpy.sqrt((dy_square_roof) / (N * (x_square_roof - x_roof_square)))
    B = y_roof - (A * x_roof)
    dB = numpy.sqrt((dy_square_roof * x_square_roof) /
                    (N * (x_square_roof - x_roof_square)))

    #chi square calculation
    chi_square = 0
    for i in range(0, N):
        chi_square += ((y[i] - (A * x[i] + B)) / dy[i])**2
    chi_square_red = chi_square / (N - 2)

    #print and return the parameters calculated:
    print('a =', A, '+-', dA)
    print('b =', B, '+-', dB)
    print('chi2 =', chi_square)
    print('chi2_reduced =', chi_square_red)
    return A, B
Example #7
0
def plotIsoStaImpedance(ax,
                        loc,
                        array,
                        flag,
                        par="abs",
                        pSym="s",
                        pColor=None,
                        addLabel="",
                        zorder=1):

    appResFact = 1 / (8 * np.pi**2 * 10**(-7))
    treshold = 1.0  # 1 meter
    indUniSta = (np.sqrt(
        np.sum((array[["x", "y"]].copy().view(
            (float, 2)) - loc)**2, axis=1)) < treshold)
    freq = array["freq"][indUniSta]

    if par == "abs":
        zPlot = np.abs(array[flag][indUniSta])
    elif par == "real":
        zPlot = np.real(array[flag][indUniSta])
    elif par == "imag":
        zPlot = np.imag(array[flag][indUniSta])
    elif par == "res":
        zPlot = (appResFact / freq) * np.abs(array[flag][indUniSta])**2
    elif par == "phs":
        zPlot = np.arctan2(array[flag][indUniSta].imag,
                           array[flag][indUniSta].real) * (180 / np.pi)

    if not pColor:
        if "xx" in flag:
            lab = "XX"
            pColor = "g"
        elif "xy" in flag:
            lab = "XY"
            pColor = "r"
        elif "yx" in flag:
            lab = "YX"
            pColor = "b"
        elif "yy" in flag:
            lab = "YY"
            pColor = "y"

    ax.plot(freq,
            zPlot,
            color=pColor,
            marker=pSym,
            label=flag + addLabel,
            zorder=zorder)
Example #8
0
def plotIsoStaImpedance(ax,
                        loc,
                        array,
                        flag,
                        par='abs',
                        pSym='s',
                        pColor=None,
                        addLabel='',
                        zorder=1):

    appResFact = 1 / (8 * np.pi**2 * 10**(-7))
    treshold = 1.0  # 1 meter
    indUniSta = np.sqrt(
        np.sum((array[['x', 'y']].view(
            (float, 2)) - loc)**2, axis=1)) < treshold
    freq = array['freq'][indUniSta]

    if par == 'abs':
        zPlot = np.abs(array[flag][indUniSta])
    elif par == 'real':
        zPlot = np.real(array[flag][indUniSta])
    elif par == 'imag':
        zPlot = np.imag(array[flag][indUniSta])
    elif par == 'res':
        zPlot = (appResFact / freq) * np.abs(array[flag][indUniSta])**2
    elif par == 'phs':
        zPlot = np.arctan2(array[flag][indUniSta].imag,
                           array[flag][indUniSta].real) * (180 / np.pi)

    if not pColor:
        if 'xx' in flag:
            lab = 'XX'
            pColor = 'g'
        elif 'xy' in flag:
            lab = 'XY'
            pColor = 'r'
        elif 'yx' in flag:
            lab = 'YX'
            pColor = 'b'
        elif 'yy' in flag:
            lab = 'YY'
            pColor = 'y'

    ax.plot(freq,
            zPlot,
            color=pColor,
            marker=pSym,
            label=flag + addLabel,
            zorder=zorder)
Example #9
0
    def cannyEdgeDetectorFilter(self, img, sigma=1, t_low=0.01, t_high=0.2):

        im = img.convert('L')
        img = np.array(im, dtype=float)

        # 1) Convolve gaussian kernel with gradient
        # gaussian kernel
        halfSize = 3 * sigma
        maskSize = 2 * halfSize + 1
        mat = np.ones((maskSize, maskSize)) / (float)(2 * np.pi * (sigma**2))
        xyRange = np.arange(-halfSize, halfSize + 1)
        xx, yy = np.meshgrid(xyRange, xyRange)
        x2y2 = (xx**2 + yy**2)
        exp_part = np.exp(-(x2y2 / (2.0 * (sigma**2))))
        gSig = mat * exp_part

        gx, gy = self.drogEdgeDetectorFilter(gSig, ret_grad=True, pillow=False)

        # 2) Magnitude and Angles
        # apply kernels for Ix & Iy
        Ix = cv2.filter2D(img, -1, gx)
        Iy = cv2.filter2D(img, -1, gy)

        # compute magnitude
        mag = np.sqrt(Ix**2 + Iy**2)

        # normalize magnitude image
        normMag = my_Normalize(mag)

        # compute orientation of gradient
        orient = np.arctan2(Iy, Ix)

        # round elements of orient
        orientRows = orient.shape[0]
        orientCols = orient.shape[1]

        # 3) Non maximum suppression
        for i in range(0, orientRows):
            for j in range(0, orientCols):
                if normMag[i, j] > t_low:
                    # case 0
                    if (orient[i, j] > (-np.pi / 8) and orient[i, j] <=
                        (np.pi / 8)):
                        orient[i, j] = 0
                    elif (orient[i, j] > (7 * np.pi / 8)
                          and orient[i, j] <= np.pi):
                        orient[i, j] = 0
                    elif (orient[i, j] >= -np.pi and orient[i, j] <
                          (-7 * np.pi / 8)):
                        orient[i, j] = 0
                    # case 1
                    elif (orient[i, j] > (np.pi / 8) and orient[i, j] <=
                          (3 * np.pi / 8)):
                        orient[i, j] = 3
                    elif (orient[i, j] >= (-7 * np.pi / 8) and orient[i, j] <
                          (-5 * np.pi / 8)):
                        orient[i, j] = 3
                    # case 2
                    elif (orient[i, j] > (3 * np.pi / 8) and orient[i, j] <=
                          (5 * np.pi / 8)):
                        orient[i, j] = 2
                    elif (orient[i, j] >= (-5 * np.pi / 4) and orient[i, j] <
                          (-3 * np.pi / 8)):
                        orient[i, j] = 2
                    # case 3
                    elif (orient[i, j] > (5 * np.pi / 8) and orient[i, j] <=
                          (7 * np.pi / 8)):
                        orient[i, j] = 1
                    elif (orient[i, j] >= (-3 * np.pi / 8) and orient[i, j] <
                          (-np.pi / 8)):
                        orient[i, j] = 1

        mag = normMag
        mag_thin = np.zeros(mag.shape)
        for i in range(mag.shape[0] - 1):
            for j in range(mag.shape[1] - 1):
                if mag[i][j] < t_low:
                    continue
                if orient[i][j] == 0:
                    if mag[i][j] > mag[i][j - 1] and mag[i][j] >= mag[i][j +
                                                                         1]:
                        mag_thin[i][j] = mag[i][j]
                if orient[i][j] == 1:
                    if mag[i][j] > mag[i - 1][j + 1] and mag[i][j] >= mag[
                            i + 1][j - 1]:
                        mag_thin[i][j] = mag[i][j]
                if orient[i][j] == 2:
                    if mag[i][j] > mag[i - 1][j] and mag[i][j] >= mag[i +
                                                                      1][j]:
                        mag_thin[i][j] = mag[i][j]
                if orient[i][j] == 3:
                    if mag[i][j] > mag[i - 1][j - 1] and mag[i][j] >= mag[
                            i + 1][j + 1]:
                        mag_thin[i][j] = mag[i][j]

        # 4) Thresholding and edge linking

        result_binary = np.zeros(mag_thin.shape)

        tHigh = t_high
        tLow = t_low
        # forward scan
        for i in range(0, mag_thin.shape[0] - 1):  # rows
            for j in range(0, mag_thin.shape[1] - 1):  # columns
                if mag_thin[i][j] >= tHigh:
                    if mag_thin[i][j + 1] >= tLow:  # right
                        mag_thin[i][j + 1] = tHigh
                    if mag_thin[i + 1][j + 1] >= tLow:  # bottom right
                        mag_thin[i + 1][j + 1] = tHigh
                    if mag_thin[i + 1][j] >= tLow:  # bottom
                        mag_thin[i + 1][j] = tHigh
                    if mag_thin[i + 1][j - 1] >= tLow:  # bottom left
                        mag_thin[i + 1][j - 1] = tHigh

        # backwards scan
        for i in range(mag_thin.shape[0] - 2, 0, -1):  # rows
            for j in range(mag_thin.shape[1] - 2, 0, -1):  # columns
                if mag_thin[i][j] >= tHigh:
                    if mag_thin[i][j - 1] > tLow:  # left
                        mag_thin[i][j - 1] = tHigh
                    if mag_thin[i - 1][j - 1]:  # top left
                        mag_thin[i - 1][j - 1] = tHigh
                    if mag_thin[i - 1][j] > tLow:  # top
                        mag_thin[i - 1][j] = tHigh
                    if mag_thin[i - 1][j + 1] > tLow:  # top right
                        mag_thin[i - 1][j + 1] = tHigh

        # fill in result_binary
        for i in range(0, mag_thin.shape[0] - 1):  # rows
            for j in range(0, mag_thin.shape[1] - 1):  # columns
                if mag_thin[i][j] >= tHigh:
                    result_binary[i][j] = 255  # set to 255 for >= tHigh

        img = Image.fromarray(result_binary)
        return img