Exemplo n.º 1
0
def smooth_bump(x, H, ends=0.2, mid=0.2):
    """
    Create a smooth bump of height H with flat bits in the middle and at the
    ends. ends, and mids are fractions of x containing each of the parts
    of the bump::

                  .-------.
                 /         \\
        ........-           -.........
        |  end |   | mid |   |  end  |

    The bumps are half of a sinusoid
    """
    d = x[-1]
    # Determine indices of each of the 5 parts of the bump
    # Every element of x belongs to one and only one

    # start_inds = x <= d*ends
    lbump_inds = l_and(x > d*ends, x <= d/2 - d*mid/2)
    mid_inds = l_and(x <= d/2 + d*mid/2, x > d/2 - d*mid/2)
    rbump_inds = l_and(x <= x[-1] - d*ends, x > d/2 + d*mid/2)
    # end_inds = x >= x[-1] - d*ends

    xL = x[lbump_inds]
    xR = x[rbump_inds]
    bumpL = H/2 + H/2*cos(pi*(xL - xL[-1])/(xL[0] - xL[-1]))
    bumpR = H/2 - H/2*cos(pi*(xR - xR[-1])/(xR[-1] - xR[0]))

    # Construct the output from individual parts
    output = np.zeros(x.shape)
    output[lbump_inds] = bumpL
    output[rbump_inds] = bumpR
    output[mid_inds] = H

    return output
Exemplo n.º 2
0
def diffMolecules(mol1, mol2, sel=None):
    """Check that name, resname, resid, insertion codes match between two molecules.

    Coordinates are not checked.

    Parameters
    ----------
    mol1 : Molecule
        first structure to compare
    mol2 : Molecule
        second structure to compare
    sel: str
        compare only after filtering to this Atom selection string.
        See more `here <http://www.ks.uiuc.edu/Research/vmd/vmd-1.9.2/ug/node89.html>`__

    Returns
    -------
    diff: list
        a list of differences, as human-readable strings (empty if structures are equal).

    Examples
    --------
    >>> m=Molecule("3PTB")
    >>> m2=m.copy()
    >>> m2.set("resname","HIE","resid 91")
    >>> diffMolecules(m,m2,sel="name CA")
    ['CA   HIS    91     vs   CA   HIE    91  ']
    """

    from numpy import logical_and as l_and

    diff = []

    m1 = mol1.copy()
    m1.filter(sel)
    m2 = mol2.copy()
    m2.filter(sel)

    eq_name = np.equal(m1.name, m2.name)
    eq_resid = np.equal(m1.resid, m2.resid)
    eq_resname = np.equal(m1.resname, m2.resname)
    eq_insertion = np.equal(m1.insertion, m2.insertion)

    eq_all = l_and(eq_name, l_and(eq_resid, l_and(eq_resname, eq_insertion)))

    neq = np.logical_not(eq_all).nonzero()
    for i in neq[0]:
        diff.append(
            "{:4s} {:4s} {:4d} {:1s}   vs   {:4s} {:4s} {:4d} {:1s}".format(
                m1.name[i],
                m1.resname[i],
                m1.resid[i],
                m1.insertion[i],
                m2.name[i],
                m2.resname[i],
                m2.resid[i],
                m2.insertion[i],
            ))
    return diff
Exemplo n.º 3
0
def diffMolecules(mol1, mol2, sel=None):
    """Check that name, resname, resid, insertion codes match between two molecules.

    Coordinates are not checked.

    Parameters
    ----------
    mol1 : Molecule
        first structure to compare
    mol2 : Molecule
        second structure to compare
    sel: str
        compare only after filtering to this Atom selection string.
        See more `here <http://www.ks.uiuc.edu/Research/vmd/vmd-1.9.2/ug/node89.html>`__

    Returns
    -------
    diff: list
        a list of differences, as human-readable strings (empty if structures are equal).

    Examples
    --------
    >>> m=Molecule("3PTB")
    >>> m2=m.copy()
    >>> m2.set("resname","HIE","resid 91")
    >>> diffMolecules(m,m2,sel="name CA")
    ['CA   HIS    91     vs   CA   HIE    91  ']
    """

    from numpy import logical_and as l_and

    diff = []

    m1 = mol1.copy()
    m1.filter(sel)
    m2 = mol2.copy()
    m2.filter(sel)

    eq_name = np.equal(m1.name, m2.name)
    eq_resid = np.equal(m1.resid, m2.resid)
    eq_resname = np.equal(m1.resname, m2.resname)
    eq_insertion = np.equal(m1.insertion, m2.insertion)

    eq_all = l_and(eq_name,
                   l_and(eq_resid,
                         l_and(eq_resname, eq_insertion)))

    neq = np.logical_not(eq_all).nonzero()
    for i in neq[0]:
        diff.append("{:4s} {:4s} {:4d} {:1s}   vs   {:4s} {:4s} {:4d} {:1s}".format(
            m1.name[i], m1.resname[i], m1.resid[i], m1.insertion[i],
            m2.name[i], m2.resname[i], m2.resid[i], m2.insertion[i],
        ))
    return diff
Exemplo n.º 4
0
def calculate_metrics(preds, targets, patient):
    """

    Parameters
    ----------
    preds:
        torch tensor of size 1*C*Z*Y*X
    targets:
        torch tensor of same shape
    patient :
        The patient ID
    """
    pp = pprint.PrettyPrinter(indent=4)
    assert preds.shape == targets.shape, "Preds and targets do not have the same size"

    labels = ["ET", "TC", "WT"]

    metrics_list = []

    for i, label in enumerate(labels):
        metrics = dict(
            patient_id=patient,
            label=label,
        )

        if np.sum(targets[i]) == 0:
            print(f"{label} not present for {patient}")
            sens = np.nan
            dice = 1 if np.sum(preds[i]) == 0 else 0
            tn = np.sum(l_and(l_not(preds[i]), l_not(targets[i])))
            fp = np.sum(l_and(preds[i], l_not(targets[i])))
            spec = tn / (tn + fp)
            haussdorf_dist = np.nan

        else:
            preds_coords = np.argwhere(preds[i])
            targets_coords = np.argwhere(targets[i])
            haussdorf_dist = directed_hausdorff(preds_coords,
                                                targets_coords)[0]

            tp = np.sum(l_and(preds[i], targets[i]))
            tn = np.sum(l_and(l_not(preds[i]), l_not(targets[i])))
            fp = np.sum(l_and(preds[i], l_not(targets[i])))
            fn = np.sum(l_and(l_not(preds[i]), targets[i]))

            sens = tp / (tp + fn)
            spec = tn / (tn + fp)

            dice = 2 * tp / (2 * tp + fp + fn)

        metrics[HAUSSDORF] = haussdorf_dist
        metrics[DICE] = dice
        metrics[SENS] = sens
        metrics[SPEC] = spec
        pp.pprint(metrics)
        metrics_list.append(metrics)

    return metrics_list
Exemplo n.º 5
0
if True:
    ps = tools.calculate_probability(xyzc[:,0:3], final_img, pixel_size=0.2)
    print(ps.shape)
    sio.savemat("results.mat", {"predictions": ps})

results = sio.loadmat("results.mat")
predictions = (255.0 - results["predictions"]) / 255.0

y_true = np.where(xyzc[:,3] == 16, True, False)
y_pred = np.where(predictions > 0.5, True, False).reshape(y_true.shape)
turret_points = np.nonzero(y_pred)[0]
turret_xyz = xyzc[turret_points, 0:3]

hits = y_pred == y_true
print("Accuracy: %f" % (np.count_nonzero(hits) / len(y_true)))
print("False Negative Rate: %f" % (np.sum(l_and(y_true, l_not(y_pred))) / np.sum(y_true)))
print("False Positive Rate: %f" % (np.sum(l_and(l_not(y_true), y_pred)) / np.sum(y_true)))
#plot_confusion_matrix(y_true, y_pred, ["No turret", "Turret"])
imageio.imwrite("%s/predicted_threshold.png" % path, (final_img > 0.5).astype(float))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(turret_xyz[:,0], turret_xyz[:,1], turret_xyz[:,2])
# ax.set_xlabel('X Label')
# ax.set_ylabel('Y Label')
# ax.set_zlabel('Z Label')
plt.show()


sio.savemat("points.mat", {"predictions": predictions,
                              "xyz": xyzic[:, [0,1,2]],