def computeFractionalAnisotropy(
        farray_e1,
        farray_e2,
        farray_e3,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeFractionalAnisotropy ***")

    n_tuples = farray_e1.GetNumberOfTuples()

    farray_FA   = myVTK.createFloatArray("FA"   , 1, n_tuples)
    farray_FA12 = myVTK.createFloatArray("FA_12", 1, n_tuples)
    farray_FA23 = myVTK.createFloatArray("FA_23", 1, n_tuples)

    for k_tuple in xrange(n_tuples):
        e1 = farray_e1.GetTuple1(k_tuple)
        e2 = farray_e2.GetTuple1(k_tuple)
        e3 = farray_e3.GetTuple1(k_tuple)
        FA   = ((e1-e2)**2+(e1-e3)**2+(e2-e3)**2)**(0.5) / (2*(e1**2+e2**2+e3**2))**(0.5)
        FA12 = ((e1-e2)**2)**(0.5) / (e1**2+e2**2)**(0.5)
        FA23 = ((e2-e3)**2)**(0.5) / (e2**2+e3**2)**(0.5)

        farray_FA.SetTuple1(k_tuple, FA)
        farray_FA12.SetTuple1(k_tuple, FA12)
        farray_FA23.SetTuple1(k_tuple, FA23)

    return (farray_FA,
            farray_FA12,
            farray_FA23)
def readAbaqusFibersFromINP(
        filename,
        verbose=1):

    myVTK.myPrint(verbose, "*** readAbaqusFibersFromINP: " + filename + " ***")

    eF_array = myVTK.createFloatArray('eF', 3)
    eS_array = myVTK.createFloatArray('eS', 3)
    eN_array = myVTK.createFloatArray('eN', 3)

    file = open(filename, 'r')
    file.readline()

    for line in file:
        line = line.split(', ')
        #print line

        eF = [float(item) for item in line[1:4]]
        eS = [float(item) for item in line[4:7]]
        eN = numpy.cross(eF,eS)
        #print "eF =", eF
        #print "eS =", eS
        #print "eN =", eN

        eF_array.InsertNextTuple(eF)
        eS_array.InsertNextTuple(eS)
        eN_array.InsertNextTuple(eN)

    file.close()

    myVTK.myPrint(verbose, "n_tuples = " + str(eF_array.GetNumberOfTuples()))

    return (eF_array,
            eS_array,
            eN_array)
示例#3
0
def readAbaqusFibersFromINP(filename, verbose=0):

    myVTK.myPrint(verbose, "*** readAbaqusFibersFromINP: " + filename + " ***")

    eF_array = myVTK.createFloatArray('eF', 3)
    eS_array = myVTK.createFloatArray('eS', 3)
    eN_array = myVTK.createFloatArray('eN', 3)

    file = open(filename, 'r')
    file.readline()

    for line in file:
        line = line.split(', ')
        #print line

        eF = [float(item) for item in line[1:4]]
        eS = [float(item) for item in line[4:7]]
        eN = numpy.cross(eF, eS)
        #print "eF =", eF
        #print "eS =", eS
        #print "eN =", eN

        eF_array.InsertNextTuple(eF)
        eS_array.InsertNextTuple(eS)
        eN_array.InsertNextTuple(eN)

    file.close()

    myVTK.myPrint(verbose - 1,
                  "n_tuples = " + str(eF_array.GetNumberOfTuples()))

    return (eF_array, eS_array, eN_array)
def computeHelixTransverseSheetAngles(
        farray_eRR,
        farray_eCC,
        farray_eLL,
        farray_eF,
        farray_eS,
        farray_eN,
        use_new_definition=False,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeHelixTransverseSheetAngles ***")

    n_tuples = farray_eRR.GetNumberOfTuples()
    assert (farray_eCC.GetNumberOfTuples() == n_tuples)
    assert (farray_eLL.GetNumberOfTuples() == n_tuples)
    assert (farray_eF.GetNumberOfTuples() == n_tuples)
    assert (farray_eS.GetNumberOfTuples() == n_tuples)
    assert (farray_eN.GetNumberOfTuples() == n_tuples)

    farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_tuples)
    farray_angle_trans = myVTK.createFloatArray("angle_trans", 1, n_tuples)
    farray_angle_sheet = myVTK.createFloatArray("angle_sheet", 1, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    eF = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)

        farray_eF.GetTuple(k_tuple, eF)
        eF -= numpy.dot(eF, eRR) * eRR
        eF /= numpy.linalg.norm(eF)
        angle_helix = math.copysign(1., numpy.dot(eF, eCC)) * math.asin(min(1., max(-1., numpy.dot(eF, eLL)))) * (180./math.pi)
        farray_angle_helix.SetTuple1(k_tuple, angle_helix)

        eF  = numpy.array(farray_eF.GetTuple(k_tuple))
        eF -= numpy.dot(eF, eLL) * eLL
        eF /= numpy.linalg.norm(eF)
        angle_trans = math.copysign(-1., numpy.dot(eF, eCC)) * math.asin(min(1., max(-1., numpy.dot(eF, eRR)))) * (180./math.pi)
        farray_angle_trans.SetTuple1(k_tuple, angle_trans)

        #if (use_new_definition):
            #assert 0, "TODO"
        #else:
            #assert 0, "TODO"

    return (farray_angle_helix,
            farray_angle_trans,
            farray_angle_sheet)
def computeHelixTransverseSheetAngles(farray_eRR,
                                      farray_eCC,
                                      farray_eLL,
                                      farray_eF,
                                      farray_eS,
                                      farray_eN,
                                      use_new_definition=False,
                                      verbose=0):

    myVTK.myPrint(verbose, "*** computeHelixTransverseSheetAngles ***")

    n_tuples = farray_eRR.GetNumberOfTuples()
    assert (farray_eCC.GetNumberOfTuples() == n_tuples)
    assert (farray_eLL.GetNumberOfTuples() == n_tuples)
    assert (farray_eF.GetNumberOfTuples() == n_tuples)
    assert (farray_eS.GetNumberOfTuples() == n_tuples)
    assert (farray_eN.GetNumberOfTuples() == n_tuples)

    farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_tuples)
    farray_angle_trans = myVTK.createFloatArray("angle_trans", 1, n_tuples)
    farray_angle_sheet = myVTK.createFloatArray("angle_sheet", 1, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    eF = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)

        farray_eF.GetTuple(k_tuple, eF)
        eF -= numpy.dot(eF, eRR) * eRR
        eF /= numpy.linalg.norm(eF)
        angle_helix = math.copysign(1., numpy.dot(eF, eCC)) * math.asin(
            min(1., max(-1., numpy.dot(eF, eLL)))) * (180. / math.pi)
        farray_angle_helix.SetTuple1(k_tuple, angle_helix)

        eF = numpy.array(farray_eF.GetTuple(k_tuple))
        eF -= numpy.dot(eF, eLL) * eLL
        eF /= numpy.linalg.norm(eF)
        angle_trans = math.copysign(-1., numpy.dot(eF, eCC)) * math.asin(
            min(1., max(-1., numpy.dot(eF, eRR)))) * (180. / math.pi)
        farray_angle_trans.SetTuple1(k_tuple, angle_trans)

        #if (use_new_definition):
        #assert 0, "TODO"
        #else:
        #assert 0, "TODO"

    return (farray_angle_helix, farray_angle_trans, farray_angle_sheet)
def createArray(
        array_name,
        n_components=1,
        n_tuples=0,
        array_type="float",
        init_to_zero=0,
        verbose=1):

    assert (type(array_type) in [type, str]), "array_type must be a type or a str. Aborting."

    if (type(array_type) is type):
        assert (array_type in [float, int]), "if a type, array_type must be equal to float or int. Aborting."

        if (array_type == float):
            return myVTK.createFloatArray(
                       name=array_name,
                       n_components=n_components,
                       n_tuples=n_tuples,
                       init_to_zero=init_to_zero,
                       verbose=verbose-1)
        elif (array_type == int):
            return myVTK.createIntArray(
                       name=array_name,
                       n_components=n_components,
                       n_tuples=n_tuples,
                       init_to_zero=init_to_zero,
                       verbose=verbose-1)
    elif (type(array_type) is str):
        assert (array_type in ["double", "float", "int", "short"]), "if a str, array_type must be equal to double, float, int or short. Aborting."

        if (array_type == "float") or (array_type == "double"):
            return myVTK.createFloatArray(
                       name=array_name,
                       n_components=n_components,
                       n_tuples=n_tuples,
                       init_to_zero=init_to_zero,
                       verbose=verbose-1)
        elif (array_type == "int"):
            return myVTK.createIntArray(
                       name=array_name,
                       n_components=n_components,
                       n_tuples=n_tuples,
                       init_to_zero=init_to_zero,
                       verbose=verbose-1)
        elif (array_type == "short"):
            return myVTK.createShortArray(
                       name=array_name,
                       n_components=n_components,
                       n_tuples=n_tuples,
                       init_to_zero=init_to_zero,
                       verbose=verbose-1)
示例#7
0
def computeSyntheticHelixAngles(
        farray_rr,
        helix_angle_end,
        helix_angle_epi,
        farray_angle_helix=None,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeSyntheticHelixAngles ***")

    n_cells = farray_rr.GetNumberOfTuples()

    if (farray_angle_helix is None):
        farray_angle_helix = myVTK.createFloatArray(
            name="angle_helix",
            n_components=1,
            n_tuples=n_cells)

    for k_cell in xrange(n_cells):
        rr = farray_rr.GetTuple1(k_cell)

        helix_angle_in_degrees = (1.-rr) * helix_angle_end \
                               +     rr  * helix_angle_epi
        farray_angle_helix.SetTuple1(
            k_cell,
            helix_angle_in_degrees)

    return farray_angle_helix
def computeSyntheticHelixAngles(
        farray_rr,
        helix_angle_end,
        helix_angle_epi,
        farray_angle_helix=None,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeSyntheticHelixAngles ***")

    n_cells = farray_rr.GetNumberOfTuples()

    if (farray_angle_helix is None):
        farray_angle_helix = myVTK.createFloatArray(
            name="angle_helix",
            n_components=1,
            n_tuples=n_cells)

    for k_cell in xrange(n_cells):
        rr = farray_rr.GetTuple1(k_cell)

        helix_angle_in_degrees = (1.-rr) * helix_angle_end \
                               +     rr  * helix_angle_epi
        farray_angle_helix.SetTuple1(
            k_cell,
            helix_angle_in_degrees)

    return farray_angle_helix
示例#9
0
def computeHelixAngles(farray_eRR,
                       farray_eCC,
                       farray_eLL,
                       farray_eF,
                       verbose=0):

    myVTK.myPrint(verbose, "*** computeHelixAngles ***")

    n_tuples = farray_eRR.GetNumberOfTuples()
    assert (farray_eCC.GetNumberOfTuples() == n_tuples)
    assert (farray_eLL.GetNumberOfTuples() == n_tuples)
    assert (farray_eF.GetNumberOfTuples() == n_tuples)

    farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    eF = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)
        farray_eF.GetTuple(k_tuple, eF)
        eF -= numpy.dot(eF, eRR) * eRR
        eF /= numpy.linalg.norm(eF)
        helix_angle = math.copysign(1., numpy.dot(eF, eCC)) * math.asin(
            min(1., max(-1., numpy.dot(eF, eLL)))) * (180. / math.pi)
        farray_angle_helix.SetTuple1(k_tuple, helix_angle)

    return farray_angle_helix
def readAbaqusDeformationGradientsFromDAT(
        data_filename,
        verbose=0):

    mypy.my_print(verbose, "*** readAbaqusDeformationGradientsFromDAT: "+data_filename+" ***")

    farray_F = myvtk.createFloatArray("F", 9)

    data_file = open(data_filename, "r")
    context = ""
    k_cell = 0
    for line in data_file:
        if (context == "reading deformation gradients"):
            #print line
            if ("MAXIMUM" in line):
                context = ""
                continue
            if ("OR" in line):
                splitted_line = line.split()
                assert (int(splitted_line[0]) == k_cell+1), "Wrong element number. Aborting."
                F_list = [float(splitted_line[ 3]), float(splitted_line[ 6]), float(splitted_line[7]),
                          float(splitted_line[ 9]), float(splitted_line[ 4]), float(splitted_line[8]),
                          float(splitted_line[10]), float(splitted_line[11]), float(splitted_line[5])]
                farray_F.InsertNextTuple(F_list)
                k_cell += 1

        if (line == "    ELEMENT  PT FOOT-       DG11        DG22        DG33        DG12        DG13        DG23        DG21        DG31        DG32    \n"):
            context = "reading deformation gradients"

    data_file.close()

    mypy.my_print(verbose-1, "n_tuples = "+str(farray_F.GetNumberOfTuples()))

    return farray_F
def readAbaqusStressFromDAT(data_filename, verbose=0):

    mypy.my_print(verbose,
                  "*** readAbaqusStressFromDAT: " + data_filename + " ***")

    s_array = myvtk.createFloatArray("", 6)

    data_file = open(data_filename, 'r')
    context = ""
    k_cell = 0
    for line in data_file:
        if (context == "reading stresses"):
            #print line
            if ("MAXIMUM" in line):
                context = ""
                continue
            if ("OR" in line):
                splitted_line = line.split()
                assert (int(splitted_line[0]) == k_cell +
                        1), "Wrong element number. Aborting."
                s_list = [float(splitted_line[k]) for k in xrange(3, 9)]
                s_array.InsertNextTuple(s_list)
                k_cell += 1

        if (line ==
                "    ELEMENT  PT FOOT-       S11         S22         S33         S12         S13         S23     \n"
            ):
            context = "reading stresses"

    data_file.close()

    mypy.my_print(verbose - 1,
                  "n_tuples = " + str(s_array.GetNumberOfTuples()))

    return s_array
def readAbaqusDeformationGradientsFromDAT(
        data_filename,
        verbose=0):

    myVTK.myPrint(verbose, "*** readAbaqusDeformationGradientsFromDAT: "+data_filename+" ***")

    farray_F = myVTK.createFloatArray("F", 9)

    data_file = open(data_filename, 'r')
    context = ""
    k_cell = 0
    for line in data_file:
        if (context == "reading deformation gradients"):
            #print line
            if ("MAXIMUM" in line):
                context = ""
                continue
            if ("OR" in line):
                splitted_line = line.split()
                assert (int(splitted_line[0]) == k_cell+1), "Wrong element number. Aborting."
                F_list = [float(splitted_line[ 3]), float(splitted_line[ 6]), float(splitted_line[7]),
                          float(splitted_line[ 9]), float(splitted_line[ 4]), float(splitted_line[8]),
                          float(splitted_line[10]), float(splitted_line[11]), float(splitted_line[5])]
                farray_F.InsertNextTuple(F_list)
                k_cell += 1

        if (line == "    ELEMENT  PT FOOT-       DG11        DG22        DG33        DG12        DG13        DG23        DG21        DG31        DG32    \n"):
            context = "reading deformation gradients"

    data_file.close()

    myVTK.myPrint(verbose-1, "n_tuples = "+str(farray_F.GetNumberOfTuples()))

    return farray_F
示例#13
0
def readDynaDeformationGradients(mesh,
                                 hystory_files_basename,
                                 array_name,
                                 verbose=0):

    mypy.my_print(verbose, "*** readDynaDeformationGradients ***")

    n_cells = mesh.GetNumberOfCells()

    history_files_names = [
        hystory_files_basename + ".history#" + str(num)
        for num in range(11, 20)
    ]

    F_list = [[0. for k_component in range(9)] for k_cell in range(n_cells)]

    for k_component in range(9):
        history_file = open(history_files_names[k_component], "r")
        for line in history_file:
            if line.startswith("*") or line.startswith("$"): continue
            line = line.split()
            F_list[int(line[0]) - 1][k_component] = float(line[1])
        history_file.close()

    F_array = myvtk.createFloatArray(array_name, 9, n_cells)

    for k_cell in range(n_cells):
        F_array.SetTuple(k_cell, F_list[k_cell])

    mypy.my_print(verbose - 1,
                  "n_tuples = " + str(F_array.GetNumberOfTuples()))

    mesh.GetCellData().AddArray(F_array)
def readDynaDeformationGradients(
        mesh,
        hystory_files_basename,
        array_name,
        verbose=1):

    myVTK.myPrint(verbose, "*** readDynaDeformationGradients ***")

    n_cells = mesh.GetNumberOfCells()

    history_files_names = [hystory_files_basename + '.history#' + str(num) for num in xrange(11,20)]

    F_list = [[0. for k_component in xrange(9)] for k_cell in xrange(n_cells)]

    for k_component in xrange(9):
        history_file = open(history_files_names[k_component], 'r')
        for line in history_file:
            if line.startswith('*') or line.startswith('$'): continue
            line = line.split()
            F_list[int(line[0])-1][k_component] = float(line[1])
        history_file.close()

    F_array = myVTK.createFloatArray(array_name, 9, n_cells)

    for k_cell in xrange(n_cells):
        F_array.InsertTuple(k_cell, F_list[k_cell])

    myVTK.myPrint(verbose, "n_tuples = " + str(F_array.GetNumberOfTuples()))

    mesh.GetCellData().AddArray(F_array)
def computeHelixAngles(
        farray_eRR,
        farray_eCC,
        farray_eLL,
        farray_eF,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeHelixAngles ***")

    n_tuples = farray_eRR.GetNumberOfTuples()
    assert (farray_eCC.GetNumberOfTuples() == n_tuples)
    assert (farray_eLL.GetNumberOfTuples() == n_tuples)
    assert (farray_eF.GetNumberOfTuples() == n_tuples)

    farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    eF = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)
        farray_eF.GetTuple(k_tuple, eF)
        eF -= numpy.dot(eF, eRR) * eRR
        eF /= numpy.linalg.norm(eF)
        helix_angle = math.copysign(1., numpy.dot(eF, eCC)) * math.asin(min(1., max(-1., numpy.dot(eF, eLL)))) * (180./math.pi)
        farray_angle_helix.SetTuple1(k_tuple, helix_angle)

    return farray_angle_helix
def readAbaqusStressFromDAT(
        data_filename,
        verbose=1):

    myVTK.myPrint(verbose, "*** readAbaqusStressFromDAT: " + data_filename + " ***")

    s_array = myVTK.createFloatArray("", 6)

    data_file = open(data_filename, 'r')
    context = ""
    k_cell = 0
    for line in data_file:
        if (context == "reading stresses"):
            #print line
            if ("MAXIMUM" in line):
                context = ""
                continue
            if ("OR" in line):
                splitted_line = line.split()
                assert (int(splitted_line[0]) == k_cell+1), "Wrong element number. Aborting."
                s_list = [float(splitted_line[k]) for k in xrange(3,9)]
                s_array.InsertNextTuple(s_list)
                k_cell += 1

        if (line == "    ELEMENT  PT FOOT-       S11         S22         S33         S12         S13         S23     \n"):
            context = "reading stresses"

    data_file.close()

    myVTK.myPrint(verbose, "n_tuples = " + str(s_array.GetNumberOfTuples()))

    return s_array
def computeSystolicStrainsFromEndDiastolicAndEndSystolicStates(
        farray_F_dia,
        farray_F_sys,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeSystolicStrainsFromEndDiastolicAndEndSystolicStates ***")

    n_tuples = farray_F_dia.GetNumberOfTuples()
    assert (farray_F_sys.GetNumberOfTuples() == n_tuples)

    farray_E_dia = myVTK.createFloatArray('E_dia', 6, n_tuples)
    farray_E_sys = myVTK.createFloatArray('E_sys', 6, n_tuples)
    farray_F_num = myVTK.createFloatArray('F_num', 6, n_tuples)
    farray_E_num = myVTK.createFloatArray('E_num', 6, n_tuples)

    I = numpy.eye(3)
    E_vec = numpy.empty(6)
    for k_tuple in xrange(n_tuples):
        F_dia = numpy.reshape(farray_F_dia.GetTuple(k_tuple), (3,3), order='C')
        F_sys = numpy.reshape(farray_F_sys.GetTuple(k_tuple), (3,3), order='C')
        #print 'F_dia =', F_dia
        #print 'F_sys =', F_sys

        C = numpy.dot(numpy.transpose(F_dia), F_dia)
        E = (C - I)/2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_E_dia.SetTuple(k_tuple, E_vec)

        C = numpy.dot(numpy.transpose(F_sys), F_sys)
        E = (C - I)/2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_E_sys.SetTuple(k_tuple, E_vec)

        F = numpy.dot(F_sys, numpy.linalg.inv(F_dia))
        farray_F_num.SetTuple(k_tuple, numpy.reshape(F, 9, order='C'))
        #print 'F =', F

        C = numpy.dot(numpy.transpose(F), F)
        E = (C - I)/2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_E_num.SetTuple(k_tuple, E_vec)

    return (farray_E_dia,
            farray_E_sys,
            farray_F_num,
            farray_E_num)
def generateWarpedMesh(
        mesh_folder,
        mesh_basename,
        images,
        structure,
        deformation,
        evolution,
        verbose=0):

    myVTK.myPrint(verbose, "*** generateWarpedMesh ***")

    mesh = myVTK.readUGrid(
        filename=mesh_folder+"/"+mesh_basename+".vtk",
        verbose=verbose-1)
    n_points = mesh.GetNumberOfPoints()
    n_cells = mesh.GetNumberOfCells()

    if os.path.exists(mesh_folder+"/"+mesh_basename+"-WithLocalBasis.vtk"):
        ref_mesh = myVTK.readUGrid(
            filename=mesh_folder+"/"+mesh_basename+"-WithLocalBasis.vtk",
            verbose=verbose-1)
    else:
        ref_mesh = None

    farray_disp = myVTK.createFloatArray(
        name="displacement",
        n_components=3,
        n_tuples=n_points,
        verbose=verbose-1)
    mesh.GetPointData().AddArray(farray_disp)

    mapping = Mapping(images, structure, deformation, evolution)

    X = numpy.empty(3)
    x = numpy.empty(3)
    U = numpy.empty(3)
    if ("zfill" not in images.keys()):
        images["zfill"] = len(str(images["n_frames"]))
    for k_frame in xrange(images["n_frames"]):
        t = images["T"]*float(k_frame)/(images["n_frames"]-1) if (images["n_frames"]>1) else 0.
        mapping.init_t(t)

        for k_point in xrange(n_points):
            mesh.GetPoint(k_point, X)
            mapping.x(X, x)
            U = x - X
            farray_disp.SetTuple(k_point, U)

        myVTK.computeStrainsFromDisplacements(
            mesh=mesh,
            disp_array_name="displacement",
            ref_mesh=ref_mesh,
            verbose=verbose-1)

        myVTK.writeUGrid(
            ugrid=mesh,
            filename=mesh_folder+"/"+mesh_basename+"_"+str(k_frame).zfill(images["zfill"])+".vtk",
            verbose=verbose-1)
示例#19
0
def computeSystolicStrainsFromEndDiastolicAndEndSystolicStates(
        farray_F_dia, farray_F_sys, verbose=0):

    myVTK.myPrint(
        verbose,
        "*** computeSystolicStrainsFromEndDiastolicAndEndSystolicStates ***")

    n_tuples = farray_F_dia.GetNumberOfTuples()
    assert (farray_F_sys.GetNumberOfTuples() == n_tuples)

    farray_E_dia = myVTK.createFloatArray('E_dia', 6, n_tuples)
    farray_E_sys = myVTK.createFloatArray('E_sys', 6, n_tuples)
    farray_F_num = myVTK.createFloatArray('F_num', 6, n_tuples)
    farray_E_num = myVTK.createFloatArray('E_num', 6, n_tuples)

    I = numpy.eye(3)
    E_vec = numpy.empty(6)
    for k_tuple in xrange(n_tuples):
        F_dia = numpy.reshape(farray_F_dia.GetTuple(k_tuple), (3, 3),
                              order='C')
        F_sys = numpy.reshape(farray_F_sys.GetTuple(k_tuple), (3, 3),
                              order='C')
        #print 'F_dia =', F_dia
        #print 'F_sys =', F_sys

        C = numpy.dot(numpy.transpose(F_dia), F_dia)
        E = (C - I) / 2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_E_dia.SetTuple(k_tuple, E_vec)

        C = numpy.dot(numpy.transpose(F_sys), F_sys)
        E = (C - I) / 2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_E_sys.SetTuple(k_tuple, E_vec)

        F = numpy.dot(F_sys, numpy.linalg.inv(F_dia))
        farray_F_num.SetTuple(k_tuple, numpy.reshape(F, 9, order='C'))
        #print 'F =', F

        C = numpy.dot(numpy.transpose(F), F)
        E = (C - I) / 2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_E_num.SetTuple(k_tuple, E_vec)

    return (farray_E_dia, farray_E_sys, farray_F_num, farray_E_num)
def computeCartesianCoordinates(
        points,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeCartesianCoordinates ***")

    n_points = points.GetNumberOfPoints()

    [xmin, xmax, ymin, ymax, zmin, zmax] = points.GetBounds()
    dx = xmax-xmin
    dy = ymax-ymin
    dz = zmax-zmin
    if (verbose >= 2): print "xmin = "+str(xmin)
    if (verbose >= 2): print "xmax = "+str(xmax)
    if (verbose >= 2): print "dx = "+str(dx)
    if (verbose >= 2): print "ymin = "+str(ymin)
    if (verbose >= 2): print "ymax = "+str(ymax)
    if (verbose >= 2): print "dy = "+str(dy)
    if (verbose >= 2): print "zmin = "+str(zmin)
    if (verbose >= 2): print "zmax = "+str(zmax)
    if (verbose >= 2): print "dz = "+str(dz)

    farray_xx = myVTK.createFloatArray("xx", 1, n_points)
    farray_yy = myVTK.createFloatArray("yy", 1, n_points)
    farray_zz = myVTK.createFloatArray("zz", 1, n_points)

    point = numpy.empty(3)
    for k_point in xrange(n_points):
        if (verbose >= 2): print "k_point = "+str(k_point)

        points.GetPoint(k_point, point)
        if (verbose >= 2): print "point = "+str(point)

        xx = (point[0] - xmin) / dx
        yy = (point[1] - ymin) / dy
        zz = (point[2] - zmin) / dz

        farray_xx.SetTuple1(k_point, xx)
        farray_yy.SetTuple1(k_point, yy)
        farray_zz.SetTuple1(k_point, zz)

    return (farray_xx,
            farray_yy,
            farray_zz)
def generateWarpedMesh(mesh_folder,
                       mesh_basename,
                       images,
                       structure,
                       deformation,
                       evolution,
                       verbose=0):

    myVTK.myPrint(verbose, "*** generateWarpedMesh ***")

    mesh = myVTK.readUGrid(filename=mesh_folder + "/" + mesh_basename + ".vtk",
                           verbose=verbose - 1)
    n_points = mesh.GetNumberOfPoints()
    n_cells = mesh.GetNumberOfCells()

    if os.path.exists(mesh_folder + "/" + mesh_basename +
                      "-WithLocalBasis.vtk"):
        ref_mesh = myVTK.readUGrid(filename=mesh_folder + "/" + mesh_basename +
                                   "-WithLocalBasis.vtk",
                                   verbose=verbose - 1)
    else:
        ref_mesh = None

    farray_disp = myVTK.createFloatArray(name="displacement",
                                         n_components=3,
                                         n_tuples=n_points,
                                         verbose=verbose - 1)
    mesh.GetPointData().AddArray(farray_disp)

    mapping = Mapping(images, structure, deformation, evolution)

    X = numpy.empty(3)
    x = numpy.empty(3)
    U = numpy.empty(3)
    if ("zfill" not in images.keys()):
        images["zfill"] = len(str(images["n_frames"]))
    for k_frame in xrange(images["n_frames"]):
        t = images["T"] * float(k_frame) / (images["n_frames"] - 1) if (
            images["n_frames"] > 1) else 0.
        mapping.init_t(t)

        for k_point in xrange(n_points):
            mesh.GetPoint(k_point, X)
            mapping.x(X, x)
            U = x - X
            farray_disp.SetTuple(k_point, U)

        myVTK.computeStrainsFromDisplacements(mesh=mesh,
                                              disp_array_name="displacement",
                                              ref_mesh=ref_mesh,
                                              verbose=verbose - 1)

        myVTK.writeUGrid(ugrid=mesh,
                         filename=mesh_folder + "/" + mesh_basename + "_" +
                         str(k_frame).zfill(images["zfill"]) + ".vtk",
                         verbose=verbose - 1)
def computeCartesianCoordinates(
        points,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeCartesianCoordinates ***")

    n_points = points.GetNumberOfPoints()

    [xmin, xmax, ymin, ymax, zmin, zmax] = points.GetBounds()
    dx = xmax-xmin
    dy = ymax-ymin
    dz = zmax-zmin
    if (verbose >= 2): print "xmin = " + str(xmin)
    if (verbose >= 2): print "xmax = " + str(xmax)
    if (verbose >= 2): print "dx = " + str(dx)
    if (verbose >= 2): print "ymin = " + str(ymin)
    if (verbose >= 2): print "ymax = " + str(ymax)
    if (verbose >= 2): print "dy = " + str(dy)
    if (verbose >= 2): print "zmin = " + str(zmin)
    if (verbose >= 2): print "zmax = " + str(zmax)
    if (verbose >= 2): print "dz = " + str(dz)

    farray_norm_x = myVTK.createFloatArray("norm_x", 1, n_points)
    farray_norm_y = myVTK.createFloatArray("norm_y", 1, n_points)
    farray_norm_z = myVTK.createFloatArray("norm_z", 1, n_points)

    for k_point in xrange(n_points):
        if (verbose >= 2): print "k_point = " + str(k_point)

        point = points.GetPoint(k_point)
        if (verbose >= 2): print "point = " + str(point)

        norm_x = (point[0] - xmin) / dx
        norm_y = (point[1] - ymin) / dy
        norm_z = (point[2] - zmin) / dz

        farray_norm_x.InsertTuple(k_point, [norm_x])
        farray_norm_y.InsertTuple(k_point, [norm_y])
        farray_norm_z.InsertTuple(k_point, [norm_z])

    return (farray_norm_x,
            farray_norm_y,
            farray_norm_z)
示例#23
0
def computeCartesianCoordinates(points, verbose=0):

    myVTK.myPrint(verbose, "*** computeCartesianCoordinates ***")

    n_points = points.GetNumberOfPoints()

    [xmin, xmax, ymin, ymax, zmin, zmax] = points.GetBounds()
    dx = xmax - xmin
    dy = ymax - ymin
    dz = zmax - zmin
    if (verbose >= 2): print "xmin = " + str(xmin)
    if (verbose >= 2): print "xmax = " + str(xmax)
    if (verbose >= 2): print "dx = " + str(dx)
    if (verbose >= 2): print "ymin = " + str(ymin)
    if (verbose >= 2): print "ymax = " + str(ymax)
    if (verbose >= 2): print "dy = " + str(dy)
    if (verbose >= 2): print "zmin = " + str(zmin)
    if (verbose >= 2): print "zmax = " + str(zmax)
    if (verbose >= 2): print "dz = " + str(dz)

    farray_xx = myVTK.createFloatArray("xx", 1, n_points)
    farray_yy = myVTK.createFloatArray("yy", 1, n_points)
    farray_zz = myVTK.createFloatArray("zz", 1, n_points)

    point = numpy.empty(3)
    for k_point in xrange(n_points):
        if (verbose >= 2): print "k_point = " + str(k_point)

        points.GetPoint(k_point, point)
        if (verbose >= 2): print "point = " + str(point)

        xx = (point[0] - xmin) / dx
        yy = (point[1] - ymin) / dy
        zz = (point[2] - zmin) / dz

        farray_xx.SetTuple1(k_point, xx)
        farray_yy.SetTuple1(k_point, yy)
        farray_zz.SetTuple1(k_point, zz)

    return (farray_xx, farray_yy, farray_zz)
def computeSystolicStrains(
        farray_F_dia,
        farray_F_sys,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeSystolicStrains ***")

    n_tuples = farray_F_dia.GetNumberOfTuples()

    farray_E_dia = myVTK.createFloatArray('E_dia', 6, n_tuples)
    farray_E_sys = myVTK.createFloatArray('E_sys', 6, n_tuples)
    farray_F_num = myVTK.createFloatArray('F_num', 6, n_tuples)
    farray_E_num = myVTK.createFloatArray('E_num', 6, n_tuples)

    for k_tuple in xrange(n_tuples):
        F_dia = numpy.reshape(farray_F_dia.GetTuple(k_tuple), (3,3), order='C')
        F_sys = numpy.reshape(farray_F_sys.GetTuple(k_tuple), (3,3), order='C')
        #print 'F_dia =', F_dia
        #print 'F_sys =', F_sys

        C = numpy.dot(numpy.transpose(F_dia), F_dia)
        E = (C - numpy.eye(3))/2
        farray_E_dia.InsertTuple(k_tuple, mat_sym_to_vec_col(E))

        C = numpy.dot(numpy.transpose(F_sys), F_sys)
        E = (C - numpy.eye(3))/2
        farray_E_sys.InsertTuple(k_tuple, mat_sym_to_vec_col(E))

        F = numpy.dot(F_sys, numpy.linalg.inv(F_dia))
        farray_F_num.InsertTuple(k_tuple, numpy.reshape(F, 9, order='C'))
        #print 'F =', F

        C = numpy.dot(numpy.transpose(F), F)
        E = (C - numpy.eye(3))/2
        farray_E_num.InsertTuple(k_tuple, mat_sym_to_vec_col(E))

    return (farray_E_dia,
            farray_E_sys,
            farray_F_num,
            farray_E_num)
def rotateSymmetricMatrix(
        old_array,
        old_array_storage="vec",
        in_vecs=None,
        out_vecs=None,
        verbose=1):

    myVTK.myPrint(verbose, "*** rotateSymmetricMatrix ***")

    n_tuples = old_array.GetNumberOfTuples()
    new_array = myVTK.createFloatArray("", 6, n_tuples)

    for k_tuple in xrange(n_tuples):
        old_matrix = old_array.GetTuple(k_tuple)
        if (old_array_storage == "vec"):
            old_matrix = vec_col_to_mat_sym(old_matrix)
        elif (old_array_storage == "Cmat"):
            old_matrix = numpy.reshape(old_matrix, (3,3), order='C')
        elif (old_array_storage == "Fmat"):
            old_matrix = numpy.reshape(old_matrix, (3,3), order='F')

        if (in_vecs == None):
            in_R = numpy.eye(3)
        else:
            in_R = numpy.transpose(numpy.array([in_vecs[0].GetTuple(k_tuple),
                                                in_vecs[1].GetTuple(k_tuple),
                                                in_vecs[2].GetTuple(k_tuple)]))

        if (out_vecs == None):
            out_R = numpy.eye(3)
        else:
            out_R = numpy.transpose(numpy.array([out_vecs[0].GetTuple(k_tuple),
                                                 out_vecs[1].GetTuple(k_tuple),
                                                 out_vecs[2].GetTuple(k_tuple)]))

        R = numpy.dot(numpy.transpose(in_R), out_R)

        new_matrix = numpy.dot(numpy.dot(numpy.transpose(R), old_matrix), R)

        if (old_array_storage == "vec"):
            new_matrix = mat_sym_to_vec_col(new_matrix)
        elif (old_array_storage == "Cmat"):
            new_matrix = numpy.reshape(new_matrix, 9, order='C')
        elif (old_array_storage == "Fmat"):
            new_matrix = numpy.reshape(new_matrix, 9, order='F')

        new_array.InsertTuple(k_tuple, new_matrix)

    return new_array
def computeFractionalAnisotropy(farray_e1, farray_e2, farray_e3, verbose=0):

    myVTK.myPrint(verbose, "*** computeFractionalAnisotropy ***")

    n_tuples = farray_e1.GetNumberOfTuples()

    farray_FA = myVTK.createFloatArray("FA", 1, n_tuples)
    farray_FA12 = myVTK.createFloatArray("FA_12", 1, n_tuples)
    farray_FA23 = myVTK.createFloatArray("FA_23", 1, n_tuples)

    for k_tuple in xrange(n_tuples):
        e1 = farray_e1.GetTuple1(k_tuple)
        e2 = farray_e2.GetTuple1(k_tuple)
        e3 = farray_e3.GetTuple1(k_tuple)
        FA = ((e1 - e2)**2 + (e1 - e3)**2 +
              (e2 - e3)**2)**(0.5) / (2 * (e1**2 + e2**2 + e3**2))**(0.5)
        FA12 = ((e1 - e2)**2)**(0.5) / (e1**2 + e2**2)**(0.5)
        FA23 = ((e2 - e3)**2)**(0.5) / (e2**2 + e3**2)**(0.5)

        farray_FA.SetTuple1(k_tuple, FA)
        farray_FA12.SetTuple1(k_tuple, FA12)
        farray_FA23.SetTuple1(k_tuple, FA23)

    return (farray_FA, farray_FA12, farray_FA23)
def getMaskedImageUsingMesh(
        image,
        mesh,
        filter_with_field=None,
        verbose=0):

    mypy.my_print(verbose, "*** getMaskedImageUsingMesh ***")

    n_points = image.GetNumberOfPoints()
    farray_scalars_image = image.GetPointData().GetArray("scalars") # note that the field is defined at the points, not the cells

    (cell_locator,
     closest_point,
     generic_cell,
     k_cell,
     subId,
     dist) = myvtk.getCellLocator(
        mesh=mesh,
        verbose=verbose-1)

    if (filter_with_field != None):
        field = mesh.GetCellData().GetArray(filter_with_field[0])
        field_values = filter_with_field[1]

    points = vtk.vtkPoints()

    farray_scalars = myvtk.createFloatArray(
        name="scalars",
        n_components=1)

    point = numpy.empty(3)
    for k_point in range(n_points):
        image.GetPoint(k_point, point)

        k_cell = cell_locator.FindCell(point)
        if (k_cell == -1): continue
        if (filter_with_field != None) and (field.GetTuple1(k_cell) not in field_values): continue

        points.InsertNextPoint(point)
        farray_scalars.InsertNextTuple(farray_scalars_image.GetTuple(k_point))

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.SetPoints(points)
    ugrid.GetPointData().AddArray(farray_scalars)
    myvtk.addVertices(
        ugrid)

    return ugrid
def maskImageWithMesh(
    image,
    mesh,
    filter_with_field=None,
    verbose=0):

    myVTK.myPrint(verbose, "*** maskImageWithMesh ***")

    n_points = image.GetNumberOfPoints()
    farray_scalars_image = image.GetPointData().GetArray("scalars") # note that the field is defined at the points, not the cells

    (cell_locator,
     closest_point,
     generic_cell,
     k_cell,
     subId,
     dist) = myVTK.getCellLocator(
        mesh=mesh,
        verbose=verbose-1)

    if (filter_with_field != None):
        field = mesh.GetCellData().GetArray(filter_with_field[0])
        field_values = filter_with_field[1]

    points = vtk.vtkPoints()

    farray_scalars = myVTK.createFloatArray(
        name="scalars",
        n_components=1)

    point = numpy.empty(3)
    for k_point in xrange(n_points):
        image.GetPoint(k_point, point)

        k_cell = cell_locator.FindCell(point)
        if (k_cell == -1): continue
        if (filter_with_field != None) and (field.GetTuple1(k_cell) not in field_values): continue

        points.InsertNextPoint(point)
        farray_scalars.InsertNextTuple(farray_scalars_image.GetTuple(k_point))

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.SetPoints(points)
    ugrid.GetPointData().AddArray(farray_scalars)
    myVTK.addVertices(
        ugrid)

    return ugrid
示例#29
0
def rotateVectorArray(old_array,
                      in_vecs=None,
                      R=None,
                      out_vecs=None,
                      verbose=0):

    mypy.my_print(verbose, "*** rotateVectorArray ***")

    n_components = old_array.GetNumberOfComponents()
    assert (
        n_components == 3), "Wrong number of components (n_components=" + str(
            n_components) + ", should be 3). Aborting."
    n_tuples = old_array.GetNumberOfTuples()
    new_array = myvtk.createFloatArray(old_array.GetName(), 3, n_tuples)
    new_vector = numpy.empty(3)
    old_vector = numpy.empty(3)

    for k_tuple in range(n_tuples):
        old_array.GetTuple(k_tuple, old_vector)

        if (in_vecs is None):
            in_R = numpy.eye(3)
        else:
            in_R = numpy.transpose(
                numpy.array([
                    in_vecs[0].GetTuple(k_tuple), in_vecs[1].GetTuple(k_tuple),
                    in_vecs[2].GetTuple(k_tuple)
                ]))

        if (R is None):
            R = numpy.eye(3)

        if (out_vecs is None):
            out_R = numpy.eye(3)
        else:
            out_R = numpy.transpose(
                numpy.array([
                    out_vecs[0].GetTuple(k_tuple),
                    out_vecs[1].GetTuple(k_tuple),
                    out_vecs[2].GetTuple(k_tuple)
                ]))

        full_R = numpy.dot(numpy.dot(numpy.transpose(in_R), R), out_R)

        new_vector[:] = numpy.dot(numpy.transpose(full_R), old_vector)
        new_array.SetTuple(k_tuple, new_vector)

    return new_array
def computeSyntheticHelixAngles(farray_rr, helix_angle_end, helix_angle_epi, farray_angle_helix=None, verbose=1):

    myVTK.myPrint(verbose, "*** computeSyntheticHelixAngles ***")

    n_cells = farray_rr.GetNumberOfTuples()

    if farray_angle_helix == None:
        farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_cells)

    for k_cell in xrange(n_cells):
        rr = farray_rr.GetTuple(k_cell)[0]

        helix_angle_in_degrees = (1.0 - rr) * helix_angle_end + rr * helix_angle_epi
        farray_angle_helix.InsertTuple(k_cell, [helix_angle_in_degrees])

    return farray_angle_helix
示例#31
0
def addDeformationGradients(mesh,
                            disp_array_name="Displacement",
                            defo_grad_array_name="DeformationGradient",
                            verbose=0):

    mypy.my_print(verbose, "*** addDeformationGradients ***")

    mypy.my_print(
        min(verbose, 1),
        "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***"
    )
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion()
          == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or
                     (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray(
        "VectorGradient")

    farray_defo_grad = myvtk.createFloatArray(name=defo_grad_array_name,
                                              n_components=9,
                                              n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_defo_grad)
    I = numpy.eye(3)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3, 3), order=ordering)
        F = I + GU
        farray_defo_grad.SetTuple(k_cell, numpy.reshape(F, 9, order='C'))
def addDeformationGradients(
        mesh,
        disp_array_name="Displacement",
        defo_grad_array_name="DeformationGradient",
        verbose=0):

    mypy.my_print(verbose, "*** addDeformationGradients ***")

    mypy.my_print(min(verbose,1), "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***")
    if   (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion() == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray("VectorGradient")

    farray_defo_grad = myvtk.createFloatArray(
        name=defo_grad_array_name,
        n_components=9,
        n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_defo_grad)
    I = numpy.eye(3)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3,3), order=ordering)
        F = I + GU
        farray_defo_grad.SetTuple(k_cell, numpy.reshape(F, 9, order='C'))
def rotateTensors(
        old_tensors,
        R,
        storage="vec",
        verbose=1):

    myVTK.myPrint(verbose, "*** rotateTensors ***")

    assert (storage in ["vec", "Cmat", "Fmat"]), "\"storage\" must be \"vec\", \"Cmat\" or \"Fmat\". Aborting."

    n_tuples = old_tensors.GetNumberOfTuples()
    n_components = old_tensors.GetNumberOfComponents()

    new_tensors = myVTK.createFloatArray("tensors", n_components, n_tuples)

    for k_tuple in xrange(n_tuples):
        old_tensor = old_tensors.GetTuple(k_tuple)
        if (storage == "vec"):
            old_tensor = vec_col_to_mat_sym(old_tensor)
        elif (storage == "Cmat"):
            old_tensor = numpy.reshape(old_tensor, (3,3), order='C')
        elif (storage == "Fmat"):
            old_tensor = numpy.reshape(old_tensor, (3,3), order='F')

        new_tensor = numpy.dot(R, numpy.dot(old_tensor, numpy.transpose(R)))

        if (storage == "vec"):
            new_tensor = mat_sym_to_vec_col(new_tensor)
        elif (storage == "Cmat"):
            new_tensor = numpy.reshape(new_tensor, 9, order='C')
        elif (storage == "Fmat"):
            new_tensor = numpy.reshape(new_tensor, 9, order='F')

        new_tensors.InsertTuple(k_tuple, new_tensor)

    return new_tensors
def computeSyntheticHelixTransverseSheetAngles(
        farray_rr,
        farray_cc,
        farray_ll,
        angles="+/-60",
        sigma=0.,
        farray_angle_helix=None,
        farray_angle_trans=None,
        farray_angle_sheet=None,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeSyntheticHelixTransverseSheetAngles ***")

    if (angles == "+/-60"):
        angles = [[[[+60], [+60]], [[-60], [-60]]],
                  [[[  0], [  0]], [[  0], [  0]]],
                  [[[  0], [  0]], [[  0], [  0]]]]

    n_l = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    d_l = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    n_c = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    d_c = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    for k_angle in xrange(3):
        #print "k_angle = "+str(k_angle)
        for k_r in xrange(2):
            #print "k_r = "+str(k_r)

            n_l[k_angle][k_r] = len(angles[k_angle][k_r])
            assert (n_l[k_angle][k_r] > 1), "Must have more than 1 longitudinal dof. Aborting."
            #print "n_l = "+str(n_l)
            d_l[k_angle][k_r] = 1./(n_l[k_angle][k_r]-1)
            #print "d_l = "+str(d_l)

            n_c[k_angle][k_r] = len(angles[k_angle][k_r][0])
            assert (n_c[k_angle][k_r] > 0), "Must have more than 0 circumferential dof. Aborting."
            #print "n_c = "+str(n_c)
            d_c[k_angle][k_r] = 1./n_c[k_angle][k_r]
            #print "d_c = "+str(d_c)

    n_tuples = farray_rr.GetNumberOfTuples()

    if (farray_angle_helix is None):
        farray_angle_helix = myVTK.createFloatArray(
            "angle_helix",
            1,
            n_tuples)
    if (farray_angle_trans is None):
        farray_angle_trans = myVTK.createFloatArray(
            "angle_trans",
            1,
            n_tuples)
    if (farray_angle_sheet is None):
        farray_angle_sheet = myVTK.createFloatArray(
            "angle_sheet",
            1,
            n_tuples)
    farray_angles = [farray_angle_helix,\
                     farray_angle_trans,\
                     farray_angle_sheet]

    for k_tuple in xrange(n_tuples):
        #print "k_tuple = "+str(k_tuple)

        angles_in_degrees = numpy.empty(3)
        for k_angle in xrange(3):
            #print "k_angle = "+str(k_angle)

                rr = farray_rr.GetTuple1(k_tuple)

                cc = farray_cc.GetTuple1(k_tuple)
                i_c_end = int(cc/d_c[k_angle][0]/1.000001)
                i_c_epi = int(cc/d_c[k_angle][1]/1.000001)
                #print "i_c_end = "+str(i_c_end)
                #print "i_c_epi = "+str(i_c_epi)

                zeta_end = (cc - i_c_end*d_c[k_angle][0])/d_c[k_angle][0]
                zeta_epi = (cc - i_c_epi*d_c[k_angle][1])/d_c[k_angle][1]
                #print "zeta_end = "+str(zeta_end)
                #print "zeta_epi = "+str(zeta_epi)

                ll = farray_ll.GetTuple1(k_tuple)
                i_l_end = int(ll/d_l[k_angle][0]/1.000001)
                i_l_epi = int(ll/d_l[k_angle][1]/1.000001)
                #print "i_l_end = "+str(i_l_end)
                #print "i_l_epi = "+str(i_l_epi)

                eta_end = (ll - i_l_end*d_l[k_angle][0])/d_l[k_angle][0]
                eta_epi = (ll - i_l_epi*d_l[k_angle][1])/d_l[k_angle][1]
                #print "eta_end = "+str(eta_end)
                #print "eta_epi = "+str(eta_epi)

                t_ii_end = angles[k_angle][0][i_l_end  ][ i_c_end   %n_c[k_angle][0]]
                t_ji_end = angles[k_angle][0][i_l_end  ][(i_c_end+1)%n_c[k_angle][0]]
                t_ij_end = angles[k_angle][0][i_l_end+1][ i_c_end   %n_c[k_angle][0]]
                t_jj_end = angles[k_angle][0][i_l_end+1][(i_c_end+1)%n_c[k_angle][0]]
                t_ii_epi = angles[k_angle][1][i_l_epi  ][ i_c_epi   %n_c[k_angle][1]]
                t_ji_epi = angles[k_angle][1][i_l_epi  ][(i_c_epi+1)%n_c[k_angle][1]]
                t_ij_epi = angles[k_angle][1][i_l_epi+1][ i_c_epi   %n_c[k_angle][1]]
                t_jj_epi = angles[k_angle][1][i_l_epi+1][(i_c_epi+1)%n_c[k_angle][1]]
                #print "t_ii_end = "+str(t_ii_end)
                #print "t_ji_end = "+str(t_ji_end)
                #print "t_ij_end = "+str(t_ij_end)
                #print "t_jj_end = "+str(t_jj_end)
                #print "t_ii_epi = "+str(t_ii_epi)
                #print "t_ji_epi = "+str(t_ji_epi)
                #print "t_ij_epi = "+str(t_ij_epi)
                #print "t_jj_epi = "+str(t_jj_epi)

                angle_end = t_ii_end * (1 - zeta_end - eta_end + zeta_end*eta_end) \
                          + t_ji_end * (    zeta_end           - zeta_end*eta_end) \
                          + t_ij_end * (               eta_end - zeta_end*eta_end) \
                          + t_jj_end * (                         zeta_end*eta_end)
                angle_epi = t_ii_epi * (1 - zeta_epi - eta_epi + zeta_epi*eta_epi) \
                          + t_ji_epi * (    zeta_epi           - zeta_epi*eta_epi) \
                          + t_ij_epi * (               eta_epi - zeta_epi*eta_epi) \
                          + t_jj_epi * (                         zeta_epi*eta_epi)

                angles_in_degrees[k_angle] = (1.-rr) * angle_end \
                                           +     rr  * angle_epi
                if (sigma > 0.):
                    angles_in_degrees[k_angle] += random.normalvariate(0., sigma)
                    angles_in_degrees[k_angle]  = (angles_in_degrees[k_angle]+90)%180-90
                farray_angles[k_angle].SetTuple1(
                    k_tuple,
                    angles_in_degrees[k_angle])

    return (farray_angle_helix,
            farray_angle_trans,
            farray_angle_sheet)
示例#35
0
def createArray(name,
                n_components=1,
                n_tuples=0,
                array_type="float",
                init_to_zero=0,
                verbose=0):

    assert (type(array_type)
            in (type, str)), "array_type must be a type or a str. Aborting."

    if (type(array_type) is type):
        assert (array_type in (float, int)), "Wrong array type. Aborting."

        if (array_type == float):
            return myvtk.createFloatArray(name=name,
                                          n_components=n_components,
                                          n_tuples=n_tuples,
                                          init_to_zero=init_to_zero,
                                          verbose=verbose - 1)
        elif (array_type == int):
            return myvtk.createIntArray(name=name,
                                        n_components=n_components,
                                        n_tuples=n_tuples,
                                        init_to_zero=init_to_zero,
                                        verbose=verbose - 1)
    elif (type(array_type) is str):
        assert (array_type
                in ("double", "float", "long", "unsigned long", "int",
                    "unsigned int", "short", "unsigned short", "char",
                    "unsigned char", "int64", "uint64", "int32", "uint32",
                    "int16", "uint16", "int8",
                    "uint8")), "Wrong array type. Aborting."

        if (array_type == "float"):
            return myvtk.createFloatArray(name=name,
                                          n_components=n_components,
                                          n_tuples=n_tuples,
                                          init_to_zero=init_to_zero,
                                          verbose=verbose - 1)
        elif (array_type == "double"):
            return myvtk.createDoubleArray(name=name,
                                           n_components=n_components,
                                           n_tuples=n_tuples,
                                           init_to_zero=init_to_zero,
                                           verbose=verbose - 1)
        elif (array_type in ("long", "int64")):
            return myvtk.createLongArray(name=name,
                                         n_components=n_components,
                                         n_tuples=n_tuples,
                                         init_to_zero=init_to_zero,
                                         verbose=verbose - 1)
        elif (array_type in ("unsigned long", "uint64")):
            return myvtk.createUnsignedLongArray(name=name,
                                                 n_components=n_components,
                                                 n_tuples=n_tuples,
                                                 init_to_zero=init_to_zero,
                                                 verbose=verbose - 1)
        elif (array_type in ("int", "int32")):
            return myvtk.createIntArray(name=name,
                                        n_components=n_components,
                                        n_tuples=n_tuples,
                                        init_to_zero=init_to_zero,
                                        verbose=verbose - 1)
        elif (array_type in ("unsigned int", "uint32")):
            return myvtk.createUnsignedIntArray(name=name,
                                                n_components=n_components,
                                                n_tuples=n_tuples,
                                                init_to_zero=init_to_zero,
                                                verbose=verbose - 1)
        elif (array_type in ("short", "int16")):
            return myvtk.createShortArray(name=name,
                                          n_components=n_components,
                                          n_tuples=n_tuples,
                                          init_to_zero=init_to_zero,
                                          verbose=verbose - 1)
        elif (array_type in ("unsigned short", "uint16")):
            return myvtk.createUnsignedShortArray(name=name,
                                                  n_components=n_components,
                                                  n_tuples=n_tuples,
                                                  init_to_zero=init_to_zero,
                                                  verbose=verbose - 1)
        elif (array_type in ("char", "int8")):
            return myvtk.createCharArray(name=name,
                                         n_components=n_components,
                                         n_tuples=n_tuples,
                                         init_to_zero=init_to_zero,
                                         verbose=verbose - 1)
        elif (array_type in ("unsigned char", "uint8")):
            return myvtk.createUnsignedCharArray(name=name,
                                                 n_components=n_components,
                                                 n_tuples=n_tuples,
                                                 init_to_zero=init_to_zero,
                                                 verbose=verbose - 1)
def computePrincipalDirections(
        field,
        field_storage="vec",
        orient=0,
        farray_eRR=None,
        farray_eCC=None,
        farray_eLL=None,
        verbose=1):

    myVTK.myPrint(verbose, "*** computePrincipalDirections ***")

    assert (field_storage in ["vec", "Cmat", "Fmat"]), "\"field_storage\" must be \"vec\", \"Cmat\" or \"Fmat\". Aborting."

    n_tuples = field.GetNumberOfTuples()

    farray_Lmin = myVTK.createFloatArray('Lmin', 1, n_tuples)
    farray_Lmid = myVTK.createFloatArray('Lmid', 1, n_tuples)
    farray_Lmax = myVTK.createFloatArray('Lmax', 1, n_tuples)

    farray_Vmin = myVTK.createFloatArray('Vmin', 3, n_tuples)
    farray_Vmid = myVTK.createFloatArray('Vmid', 3, n_tuples)
    farray_Vmax = myVTK.createFloatArray('Vmax', 3, n_tuples)

    for k_tuple in xrange(n_tuples):
        #print "k_tuple: " + str(k_tuple)
        matrix = field.GetTuple(k_tuple)
        if (field_storage == "vec"):
            matrix = vec_col_to_mat_sym(matrix)
        elif (field_storage == "Cmat"):
            matrix = numpy.reshape(matrix, (3,3), order='C')
        elif (field_storage == "Fmat"):
            matrix = numpy.reshape(matrix, (3,3), order='F')

        if (numpy.linalg.norm(matrix) > 1e-6):
            #if (verbose): print + 'k_tuple =', k_tuple

            val, vec = numpy.linalg.eig(matrix)
            #if (verbose): print + 'val =', val
            #if (verbose): print + 'vec =', vec
            #if (verbose): print + 'det =', numpy.linalg.det(vec)
            idx = val.argsort()
            val = val[idx]
            vec = vec[:,idx]
            #if (verbose): print + 'val =', val
            #if (verbose): print + 'vec =', vec
            #if (verbose): print + 'det =', numpy.linalg.det(vec)

            matrix_Lmin = [val[0]]
            matrix_Lmid = [val[1]]
            matrix_Lmax = [val[2]]

            matrix_Vmax = vec[:,2]
            matrix_Vmid = vec[:,1]
            if (orient):
                eCC = numpy.array(farray_eCC.GetTuple(k_tuple))
                eLL = numpy.array(farray_eLL.GetTuple(k_tuple))
                matrix_Vmax = math.copysign(1, numpy.dot(matrix_Vmax, eCC)) * matrix_Vmax
                matrix_Vmid = math.copysign(1, numpy.dot(matrix_Vmid, eLL)) * matrix_Vmid
            matrix_Vmin = numpy.cross(matrix_Vmax, matrix_Vmid)
        else:
            matrix_Lmin = [0.]
            matrix_Lmid = [0.]
            matrix_Lmax = [0.]
            matrix_Vmin = [0.]*3
            matrix_Vmid = [0.]*3
            matrix_Vmax = [0.]*3

        farray_Lmin.InsertTuple(k_tuple, matrix_Lmin)
        farray_Lmid.InsertTuple(k_tuple, matrix_Lmid)
        farray_Lmax.InsertTuple(k_tuple, matrix_Lmax)
        farray_Vmin.InsertTuple(k_tuple, matrix_Vmin)
        farray_Vmid.InsertTuple(k_tuple, matrix_Vmid)
        farray_Vmax.InsertTuple(k_tuple, matrix_Vmax)

    return (farray_Lmin,
            farray_Lmid,
            farray_Lmax,
            farray_Vmin,
            farray_Vmid,
            farray_Vmax)
示例#37
0
def computeSyntheticHelixTransverseSheetAngles(farray_rr,
                                               farray_cc,
                                               farray_ll,
                                               angles="+/-60",
                                               sigma=0.,
                                               farray_angle_helix=None,
                                               farray_angle_trans=None,
                                               farray_angle_sheet=None,
                                               verbose=0):

    myVTK.myPrint(verbose,
                  "*** computeSyntheticHelixTransverseSheetAngles ***")

    if (angles == "+/-60"):
        angles = [[[[+60], [+60]], [[-60], [-60]]], [[[0], [0]], [[0], [0]]],
                  [[[0], [0]], [[0], [0]]]]

    n_l = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    d_l = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    n_c = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    d_c = [[0. for k_r in xrange(2)] for k_angle in xrange(3)]
    for k_angle in xrange(3):
        #print "k_angle = "+str(k_angle)
        for k_r in xrange(2):
            #print "k_r = "+str(k_r)

            n_l[k_angle][k_r] = len(angles[k_angle][k_r])
            assert (n_l[k_angle][k_r] >
                    1), "Must have more than 1 longitudinal dof. Aborting."
            #print "n_l = "+str(n_l)
            d_l[k_angle][k_r] = 1. / (n_l[k_angle][k_r] - 1)
            #print "d_l = "+str(d_l)

            n_c[k_angle][k_r] = len(angles[k_angle][k_r][0])
            assert (n_c[k_angle][k_r] >
                    0), "Must have more than 0 circumferential dof. Aborting."
            #print "n_c = "+str(n_c)
            d_c[k_angle][k_r] = 1. / n_c[k_angle][k_r]
            #print "d_c = "+str(d_c)

    n_tuples = farray_rr.GetNumberOfTuples()

    if (farray_angle_helix is None):
        farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_tuples)
    if (farray_angle_trans is None):
        farray_angle_trans = myVTK.createFloatArray("angle_trans", 1, n_tuples)
    if (farray_angle_sheet is None):
        farray_angle_sheet = myVTK.createFloatArray("angle_sheet", 1, n_tuples)
    farray_angles = [farray_angle_helix,\
                     farray_angle_trans,\
                     farray_angle_sheet]

    for k_tuple in xrange(n_tuples):
        #print "k_tuple = "+str(k_tuple)

        angles_in_degrees = numpy.empty(3)
        for k_angle in xrange(3):
            #print "k_angle = "+str(k_angle)

            rr = farray_rr.GetTuple1(k_tuple)

            cc = farray_cc.GetTuple1(k_tuple)
            i_c_end = int(cc / d_c[k_angle][0] / 1.000001)
            i_c_epi = int(cc / d_c[k_angle][1] / 1.000001)
            #print "i_c_end = "+str(i_c_end)
            #print "i_c_epi = "+str(i_c_epi)

            zeta_end = (cc - i_c_end * d_c[k_angle][0]) / d_c[k_angle][0]
            zeta_epi = (cc - i_c_epi * d_c[k_angle][1]) / d_c[k_angle][1]
            #print "zeta_end = "+str(zeta_end)
            #print "zeta_epi = "+str(zeta_epi)

            ll = farray_ll.GetTuple1(k_tuple)
            i_l_end = int(ll / d_l[k_angle][0] / 1.000001)
            i_l_epi = int(ll / d_l[k_angle][1] / 1.000001)
            #print "i_l_end = "+str(i_l_end)
            #print "i_l_epi = "+str(i_l_epi)

            eta_end = (ll - i_l_end * d_l[k_angle][0]) / d_l[k_angle][0]
            eta_epi = (ll - i_l_epi * d_l[k_angle][1]) / d_l[k_angle][1]
            #print "eta_end = "+str(eta_end)
            #print "eta_epi = "+str(eta_epi)

            t_ii_end = angles[k_angle][0][i_l_end][i_c_end % n_c[k_angle][0]]
            t_ji_end = angles[k_angle][0][i_l_end][(i_c_end + 1) %
                                                   n_c[k_angle][0]]
            t_ij_end = angles[k_angle][0][i_l_end + 1][i_c_end %
                                                       n_c[k_angle][0]]
            t_jj_end = angles[k_angle][0][i_l_end + 1][(i_c_end + 1) %
                                                       n_c[k_angle][0]]
            t_ii_epi = angles[k_angle][1][i_l_epi][i_c_epi % n_c[k_angle][1]]
            t_ji_epi = angles[k_angle][1][i_l_epi][(i_c_epi + 1) %
                                                   n_c[k_angle][1]]
            t_ij_epi = angles[k_angle][1][i_l_epi + 1][i_c_epi %
                                                       n_c[k_angle][1]]
            t_jj_epi = angles[k_angle][1][i_l_epi + 1][(i_c_epi + 1) %
                                                       n_c[k_angle][1]]
            #print "t_ii_end = "+str(t_ii_end)
            #print "t_ji_end = "+str(t_ji_end)
            #print "t_ij_end = "+str(t_ij_end)
            #print "t_jj_end = "+str(t_jj_end)
            #print "t_ii_epi = "+str(t_ii_epi)
            #print "t_ji_epi = "+str(t_ji_epi)
            #print "t_ij_epi = "+str(t_ij_epi)
            #print "t_jj_epi = "+str(t_jj_epi)

            angle_end = t_ii_end * (1 - zeta_end - eta_end + zeta_end*eta_end) \
                      + t_ji_end * (    zeta_end           - zeta_end*eta_end) \
                      + t_ij_end * (               eta_end - zeta_end*eta_end) \
                      + t_jj_end * (                         zeta_end*eta_end)
            angle_epi = t_ii_epi * (1 - zeta_epi - eta_epi + zeta_epi*eta_epi) \
                      + t_ji_epi * (    zeta_epi           - zeta_epi*eta_epi) \
                      + t_ij_epi * (               eta_epi - zeta_epi*eta_epi) \
                      + t_jj_epi * (                         zeta_epi*eta_epi)

            angles_in_degrees[k_angle] = (1.-rr) * angle_end \
                                       +     rr  * angle_epi
            if (sigma > 0.):
                angles_in_degrees[k_angle] += random.normalvariate(0., sigma)
                angles_in_degrees[k_angle] = (angles_in_degrees[k_angle] +
                                              90) % 180 - 90
            farray_angles[k_angle].SetTuple1(k_tuple,
                                             angles_in_degrees[k_angle])

    return (farray_angle_helix, farray_angle_trans, farray_angle_sheet)
def generateImages(
        images,
        structure,
        texture,
        noise,
        deformation,
        evolution,
        generate_image_gradient=False,
        verbose=0):

    myVTK.myPrint(verbose, "*** generateImages ***")

    vtk_image = vtk.vtkImageData()

    if   (images["n_dim"] == 1):
        vtk_image.SetExtent([0, images["n_voxels"][0]-1, 0,                       0, 0,                       0])
    elif (images["n_dim"] == 2):
        vtk_image.SetExtent([0, images["n_voxels"][0]-1, 0, images["n_voxels"][1]-1, 0,                       0])
    elif (images["n_dim"] == 3):
        vtk_image.SetExtent([0, images["n_voxels"][0]-1, 0, images["n_voxels"][1]-1, 0, images["n_voxels"][2]-1])
    else:
        assert (0), "n_dim must be \"1\", \"2\" or \"3\". Aborting."

    spacing = numpy.array(images["L"])/numpy.array(images["n_voxels"])
    if   (images["n_dim"] == 1):
        spacing = numpy.array([images["L"][0]/images["n_voxels"][0], 1., 1.])
    elif (images["n_dim"] == 2):
        spacing = numpy.array([images["L"][0]/images["n_voxels"][0], images["L"][1]/images["n_voxels"][1], 1.])
    elif (images["n_dim"] == 2):
        spacing = numpy.array([images["L"][0]/images["n_voxels"][0], images["L"][1]/images["n_voxels"][1], images["L"][2]/images["n_voxels"][2]])
    vtk_image.SetSpacing(spacing)

    origin = numpy.array(vtk_image.GetSpacing())/2
    if   (images["n_dim"] == 1):
        origin[1] = 0.
        origin[2] = 0.
    elif (images["n_dim"] == 2):
        origin[2] = 0.
    vtk_image.SetOrigin(origin)

    n_points = vtk_image.GetNumberOfPoints()
    vtk_image_scalars = myVTK.createFloatArray(
        name="ImageScalars",
        n_components=1,
        n_tuples=n_points,
        verbose=verbose-1)
    vtk_image.GetPointData().SetScalars(vtk_image_scalars)
    if (generate_image_gradient):
        vtk_image_gradient = myVTK.createFloatArray(
            name="ImageScalarsGradient",
            n_components=images["n_dim"],
            n_tuples=n_points,
            verbose=verbose-1)
        vtk_image.GetPointData().SetVectors(vtk_image_gradient)

    if not os.path.exists(images["folder"]):
        os.mkdir(images["folder"])

    x0   = numpy.empty(3)
    x    = numpy.empty(3)
    X    = numpy.empty(3)
    if (generate_image_gradient):
        F    = numpy.empty((3,3))
        Finv = numpy.empty((3,3))
    else:
        F    = None
        Finv = None
    dx   = spacing[0:images["n_dim"]]/images["n_integration"][0:images["n_dim"]]
    global_min = float("+Inf")
    global_max = float("-Inf")
    I = numpy.empty(1)
    i = numpy.empty(1)
    if (generate_image_gradient):
        G = numpy.empty(images["n_dim"])
        g = numpy.empty(images["n_dim"])
    else:
        G = None
        g = None
    image = Image(images, structure, texture, noise)
    mapping = Mapping(images, structure, deformation, evolution)
    if ("zfill" not in images.keys()):
        images["zfill"] = len(str(images["n_frames"]))
    for k_frame in xrange(images["n_frames"]):
        t = images["T"]*float(k_frame)/(images["n_frames"]-1) if (images["n_frames"]>1) else 0.
        print "t = "+str(t)
        mapping.init_t(t)
        for k_point in xrange(n_points):
            vtk_image.GetPoint(k_point, x0)
            #print "x0 = "+str(x0)
            x[:] = x0[:]
            #print "x = "+str(x)
            I[0] = 0.
            #print "I = "+str(I)
            #if (generate_image_gradient): G[:] = 0.
                #print "G = "+str(G)
            if   (images["n_dim"] == 1):
                for k_x in xrange(images["n_integration"][0]):
                    x[0] = x0[0] - dx[0]/2 + (k_x+1./2)*dx[0]/images["n_integration"][0]
                    mapping.X(x, X, Finv)
                    image.I0(X, i, g)
                    I += i
                    #if (generate_image_gradient): G += numpy.dot(g, Finv)
                I /= images["n_integration"][0]
                #if (generate_image_gradient): G /= images["n_integration"][0]
            elif (images["n_dim"] == 2):
                for k_y in xrange(images["n_integration"][1]):
                    x[1] = x0[1] - dx[1]/2 + (k_y+1./2)*dx[1]/images["n_integration"][1]
                    for k_x in xrange(images["n_integration"][0]):
                        x[0] = x0[0] - dx[0]/2 + (k_x+1./2)*dx[0]/images["n_integration"][0]
                        #print "x = "+str(x)
                        mapping.X(x, X, Finv)
                        #print "X = "+str(X)
                        #print "Finv = "+str(Finv)
                        image.I0(X, i, g)
                        #print "i = "+str(i)
                        #print "g = "+str(g)
                        I += i
                        #if (generate_image_gradient): G += numpy.dot(g, Finv)
                I /= images["n_integration"][1]*images["n_integration"][0]
                #if (generate_image_gradient):G /= images["n_integration"][1]*images["n_integration"][0]
            elif (images["n_dim"] == 3):
                for k_z in xrange(images["n_integration"][2]):
                    x[2] = x0[2] - dx[2]/2 + (k_z+1./2)*dx[2]/images["n_integration"][2]
                    for k_y in xrange(images["n_integration"][1]):
                        x[1] = x0[1] - dx[1]/2 + (k_y+1./2)*dx[1]/images["n_integration"][1]
                        for k_x in xrange(images["n_integration"][0]):
                            x[0] = x0[0] - dx[0]/2 + (k_x+1./2)*dx[0]/images["n_integration"][0]
                            mapping.X(x, X, Finv)
                            image.I0(X, i, g)
                            I += i
                            #if (generate_image_gradient): G += numpy.dot(g, Finv)
                I /= images["n_integration"][2]*images["n_integration"][1]*images["n_integration"][0]
                #if (generate_image_gradient): G /= images["n_integration"][2]*images["n_integration"][1]*images["n_integration"][0]
            else:
                assert (0), "n_dim must be \"1\", \"2\" or \"3\". Aborting."
            vtk_image_scalars.SetTuple(k_point, I)
            #if (generate_image_gradient): vtk_image_gradient.SetTuple(k_point, G)
            if (I[0] < global_min): global_min = I[0]
            if (I[0] > global_max): global_max = I[0]
        myVTK.writeImage(
            image=vtk_image,
            filename=images["folder"]+"/"+images["basename"]+"_"+str(k_frame).zfill(images["zfill"])+".vti",
            verbose=verbose-1)

    if (images["data_type"] in ("float")):
        pass
    elif (images["data_type"] in ("unsigned char", "unsigned short", "unsigned int", "unsigned long", "unsigned float", "uint8", "uint16", "uint32", "uint64", "ufloat")):
        #print "global_min = "+str(global_min)
        #print "global_max = "+str(global_max)
        shifter = vtk.vtkImageShiftScale()
        shifter.SetShift(-global_min)
        if   (images["data_type"] in ("unsigned char", "uint8")):
            shifter.SetScale(float(2**8-1)/(global_max-global_min))
            shifter.SetOutputScalarTypeToUnsignedChar()
        elif (images["data_type"] in ("unsigned short", "uint16")):
            shifter.SetScale(float(2**16-1)/(global_max-global_min))
            shifter.SetOutputScalarTypeToUnsignedShort()
        elif (images["data_type"] in ("unsigned int", "uint32")):
            shifter.SetScale(float(2**32-1)/(global_max-global_min))
            shifter.SetOutputScalarTypeToUnsignedInt()
        elif (images["data_type"] in ("unsigned long", "uint64")):
            shifter.SetScale(float(2**64-1)/(global_max-global_min))
            shifter.SetOutputScalarTypeToUnsignedLong()
        elif (images["data_type"] in ("unsigned float", "ufloat")):
            shifter.SetScale(1./(global_max-global_min))
            shifter.SetOutputScalarTypeToFloat()
        for k_frame in xrange(images["n_frames"]):
            vtk_image = myVTK.readImage(
                filename=images["folder"]+"/"+images["basename"]+"_"+str(k_frame).zfill(images["zfill"])+".vti",
                verbose=verbose-1)
            if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
                shifter.SetInputData(vtk_image)
            else:
                shifter.SetInput(vtk_image)
            shifter.Update()
            vtk_image = shifter.GetOutput()
            myVTK.writeImage(
                image=vtk_image,
                filename=images["folder"]+"/"+images["basename"]+"_"+str(k_frame).zfill(images["zfill"])+".vti",
                verbose=verbose-1)
    else:
        assert (0), "Wrong data type. Aborting."
示例#39
0
def computeStrainsFromDisplacements(mesh,
                                    disp_array_name="displacement",
                                    ref_mesh=None,
                                    verbose=0):

    myVTK.myPrint(verbose, "*** computeStrainsFromDisplacements ***")

    myVTK.myPrint(
        min(verbose, 1),
        "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***"
    )
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion()
          == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or
                     (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_points = mesh.GetNumberOfPoints()
    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray(
        "VectorGradient")

    if (ref_mesh is not None):
        farray_strain = myVTK.createFloatArray(name="Strain_CAR",
                                               n_components=6,
                                               n_tuples=n_cells)
    else:
        farray_strain = myVTK.createFloatArray(name="Strain",
                                               n_components=6,
                                               n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_strain)
    I = numpy.eye(3)
    E_vec = numpy.empty(6)
    #e_vec = numpy.empty(6)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3, 3), ordering)
        F = I + GU
        C = numpy.dot(numpy.transpose(F), F)
        E = (C - I) / 2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_strain.SetTuple(k_cell, E_vec)
        #if (add_almansi_strain):
        #Finv = numpy.linalg.inv(F)
        #c = numpy.dot(numpy.transpose(Finv), Finv)
        #e = (I - c)/2
        #mat_sym33_to_vec_col6(e, e_vec)
        #farray_almansi.SetTuple(k_cell, e_vec)

    if (ref_mesh is not None) and (ref_mesh.GetCellData().HasArray("eR")) and (
            ref_mesh.GetCellData().HasArray("eC")) and (
                ref_mesh.GetCellData().HasArray("eL")):
        farray_strain_cyl = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[
                ref_mesh.GetCellData().GetArray("eR"),
                ref_mesh.GetCellData().GetArray("eC"),
                ref_mesh.GetCellData().GetArray("eL")
            ],
            verbose=0)
        farray_strain_cyl.SetName("Strain_CYL")
        mesh.GetCellData().AddArray(farray_strain_cyl)

    if (ref_mesh
            is not None) and (ref_mesh.GetCellData().HasArray("eRR")) and (
                ref_mesh.GetCellData().HasArray("eCC")) and (
                    ref_mesh.GetCellData().HasArray("eLL")):
        farray_strain_pps = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[
                ref_mesh.GetCellData().GetArray("eRR"),
                ref_mesh.GetCellData().GetArray("eCC"),
                ref_mesh.GetCellData().GetArray("eLL")
            ],
            verbose=0)
        farray_strain_pps.SetName("Strain_PPS")
        mesh.GetCellData().AddArray(farray_strain_pps)
def computePseudoProlateSpheroidalCoordinatesAndBasisForLV(
        points,
        farray_c,
        farray_l,
        farray_eL,
        pdata_end,
        pdata_epi,
        iarray_part_id=None,
        verbose=0):

    myVTK.myPrint(
        verbose,
        "*** computePseudoProlateSpheroidalCoordinatesAndBasisForLV ***")

    myVTK.myPrint(verbose - 1, "Computing surface cell normals...")

    pdata_end = myVTK.addPDataNormals(pdata=pdata_end, verbose=verbose - 1)
    pdata_epi = myVTK.addPDataNormals(pdata=pdata_epi, verbose=verbose - 1)

    myVTK.myPrint(verbose - 1, "Initializing surface cell locators...")

    (cell_locator_end, closest_point_end, generic_cell, cellId_end, subId,
     dist_end) = myVTK.getCellLocator(mesh=pdata_end, verbose=verbose - 1)
    (cell_locator_epi, closest_point_epi, generic_cell, cellId_epi, subId,
     dist_epi) = myVTK.getCellLocator(mesh=pdata_epi, verbose=verbose - 1)

    myVTK.myPrint(verbose - 1,
                  "Computing local prolate spheroidal directions...")

    n_points = points.GetNumberOfPoints()

    farray_rr = myVTK.createFloatArray("rr", 1, n_points)
    farray_cc = myVTK.createFloatArray("cc", 1, n_points)
    farray_ll = myVTK.createFloatArray("ll", 1, n_points)

    farray_eRR = myVTK.createFloatArray("eRR", 3, n_points)
    farray_eCC = myVTK.createFloatArray("eCC", 3, n_points)
    farray_eLL = myVTK.createFloatArray("eLL", 3, n_points)

    if (n_points == 0):
        return (farray_rr, farray_cc, farray_ll, farray_eRR, farray_eCC,
                farray_eLL)

    c_lst = [farray_c.GetTuple1(k_point) for k_point in xrange(n_points)]
    c_min = min(c_lst)
    c_max = max(c_lst)

    l_lst = [farray_l.GetTuple1(k_point) for k_point in xrange(n_points)]
    l_min = min(l_lst)
    l_max = max(l_lst)

    pdata_end_normals = pdata_end.GetCellData().GetNormals()
    pdata_epi_normals = pdata_epi.GetCellData().GetNormals()
    pdata_end_normal = numpy.empty(3)
    pdata_epi_normal = numpy.empty(3)

    eL = numpy.empty(3)

    point = numpy.empty(3)
    for k_point in xrange(n_points):
        if (iarray_part_id
                is not None) and (int(iarray_part_id.GetTuple1(k_point)) > 0):
            rr = 0.
            cc = 0.
            ll = 0.
            eRR = numpy.array([1., 0., 0.])
            eCC = numpy.array([0., 1., 0.])
            eLL = numpy.array([0., 0., 1.])

        else:
            points.GetPoint(k_point, point)
            cell_locator_end.FindClosestPoint(point, closest_point_end,
                                              generic_cell, cellId_end, subId,
                                              dist_end)
            cell_locator_epi.FindClosestPoint(point, closest_point_epi,
                                              generic_cell, cellId_epi, subId,
                                              dist_epi)

            rr = dist_end / (dist_end + dist_epi)

            c = farray_c.GetTuple1(k_point)
            cc = (c - c_min) / (c_max - c_min)

            l = farray_l.GetTuple1(k_point)
            ll = (l - l_min) / (l_max - l_min)

            pdata_end_normals.GetTuple(cellId_end, pdata_end_normal)
            pdata_epi_normals.GetTuple(cellId_epi, pdata_epi_normal)
            eRR = (1. - rr) * pdata_end_normal + rr * pdata_epi_normal
            eRR /= numpy.linalg.norm(eRR)

            farray_eL.GetTuple(k_point, eL)
            eCC = numpy.cross(eL, eRR)
            eCC /= numpy.linalg.norm(eCC)

            eLL = numpy.cross(eRR, eCC)

        farray_rr.SetTuple1(k_point, rr)
        farray_cc.SetTuple1(k_point, cc)
        farray_ll.SetTuple1(k_point, ll)
        farray_eRR.SetTuple(k_point, eRR)
        farray_eCC.SetTuple(k_point, eCC)
        farray_eLL.SetTuple(k_point, eLL)

    return (farray_rr, farray_cc, farray_ll, farray_eRR, farray_eCC,
            farray_eLL)
def computePseudoProlateSpheroidalCoordinatesAndBasisForBiV(
        points,
        iarray_regions,
        farray_c,
        farray_l,
        farray_eL,
        pdata_endLV,
        pdata_endRV,
        pdata_epi,
        iarray_part_id=None,
        verbose=0):

    myVTK.myPrint(
        verbose,
        "*** computePseudoProlateSpheroidalCoordinatesAndBasisForBiV ***")

    myVTK.myPrint(verbose - 1, "Computing surface cell normals...")

    pdata_endLV = myVTK.addPDataNormals(pdata=pdata_endLV, verbose=verbose - 1)
    pdata_endRV = myVTK.addPDataNormals(pdata=pdata_endRV, verbose=verbose - 1)
    pdata_epi = myVTK.addPDataNormals(pdata=pdata_epi, verbose=verbose - 1)

    myVTK.myPrint(verbose - 1, "Initializing surface cell locators...")

    (cell_locator_endLV, closest_point_endLV, generic_cell, cellId_endLV,
     subId, dist_endLV) = myVTK.getCellLocator(mesh=pdata_endLV,
                                               verbose=verbose - 1)
    (cell_locator_endRV, closest_point_endRV, generic_cell, cellId_endRV,
     subId, dist_endRV) = myVTK.getCellLocator(mesh=pdata_endRV,
                                               verbose=verbose - 1)
    (cell_locator_epi, closest_point_epi, generic_cell, cellId_epi, subId,
     dist_epi) = myVTK.getCellLocator(mesh=pdata_epi, verbose=verbose - 1)

    myVTK.myPrint(verbose - 1,
                  "Computing local prolate spheroidal directions...")

    n_points = points.GetNumberOfPoints()

    farray_rr = myVTK.createFloatArray("rr", 1, n_points)
    farray_cc = myVTK.createFloatArray("cc", 1, n_points)
    farray_ll = myVTK.createFloatArray("ll", 1, n_points)

    farray_eRR = myVTK.createFloatArray("eRR", 3, n_points)
    farray_eCC = myVTK.createFloatArray("eCC", 3, n_points)
    farray_eLL = myVTK.createFloatArray("eLL", 3, n_points)

    c_lst_FWLV = numpy.array([
        farray_c.GetTuple1(k_point) for k_point in xrange(n_points)
        if (iarray_regions.GetTuple1(k_point) == 0)
    ])
    (c_avg_FWLV,
     c_std_FWLV) = myVTK.computeMeanStddevAngles(angles=c_lst_FWLV,
                                                 angles_in_degrees=False,
                                                 angles_in_pm_pi=False)
    myVTK.myPrint(verbose - 1, "c_avg_FWLV = " + str(c_avg_FWLV))
    c_lst_FWLV = (((c_lst_FWLV - c_avg_FWLV + math.pi) % (2 * math.pi)) -
                  math.pi + c_avg_FWLV)
    c_min_FWLV = min(c_lst_FWLV)
    c_max_FWLV = max(c_lst_FWLV)
    myVTK.myPrint(verbose - 1, "c_min_FWLV = " + str(c_min_FWLV))
    myVTK.myPrint(verbose - 1, "c_max_FWLV = " + str(c_max_FWLV))

    c_lst_S = numpy.array([
        farray_c.GetTuple1(k_point) for k_point in xrange(n_points)
        if (iarray_regions.GetTuple1(k_point) == 1)
    ])
    (c_avg_S, c_std_S) = myVTK.computeMeanStddevAngles(angles=c_lst_S,
                                                       angles_in_degrees=False,
                                                       angles_in_pm_pi=False)
    myVTK.myPrint(verbose - 1, "c_avg_S = " + str(c_avg_S))
    c_lst_S = (((c_lst_S - c_avg_S + math.pi) % (2 * math.pi)) - math.pi +
               c_avg_S)
    c_min_S = min(c_lst_S)
    c_max_S = max(c_lst_S)
    myVTK.myPrint(verbose - 1, "c_min_S = " + str(c_min_S))
    myVTK.myPrint(verbose - 1, "c_max_S = " + str(c_max_S))

    c_lst_FWRV = numpy.array([
        farray_c.GetTuple1(k_point) for k_point in xrange(n_points)
        if (iarray_regions.GetTuple1(k_point) == 2)
    ])
    (c_avg_FWRV,
     c_std_FWRV) = myVTK.computeMeanStddevAngles(angles=c_lst_FWRV,
                                                 angles_in_degrees=False,
                                                 angles_in_pm_pi=False)
    myVTK.myPrint(verbose - 1, "c_avg_FWRV = " + str(c_avg_FWRV))
    c_lst_FWRV = (((c_lst_FWRV - c_avg_FWRV + math.pi) % (2 * math.pi)) -
                  math.pi + c_avg_FWRV)
    c_min_FWRV = min(c_lst_FWRV)
    c_max_FWRV = max(c_lst_FWRV)
    myVTK.myPrint(verbose - 1, "c_min_FWRV = " + str(c_min_FWRV))
    myVTK.myPrint(verbose - 1, "c_max_FWRV = " + str(c_max_FWRV))

    l_lst = [farray_l.GetTuple1(k_point) for k_point in xrange(n_points)]
    l_min = min(l_lst)
    l_max = max(l_lst)

    point = numpy.empty(3)
    for k_point in xrange(n_points):
        if (iarray_part_id
                is not None) and (int(iarray_part_id.GetTuple1(k_point)) > 0):
            rr = 0.
            cc = 0.
            ll = 0.
            eRR = [1., 0., 0.]
            eCC = [0., 1., 0.]
            eLL = [0., 0., 1.]

        else:
            points.GetPoint(k_point, point)
            region_id = iarray_regions.GetTuple1(k_point)

            if (region_id == 0):
                cell_locator_endLV.FindClosestPoint(point, closest_point_endLV,
                                                    generic_cell, cellId_endLV,
                                                    subId, dist_endLV)
                cell_locator_epi.FindClosestPoint(point, closest_point_epi,
                                                  generic_cell, cellId_epi,
                                                  subId, dist_epi)

                rr = dist_endLV / (dist_endLV + dist_epi)

                c = farray_c.GetTuple1(k_point)
                c = (((c - c_avg_FWLV + math.pi) % (2 * math.pi)) - math.pi +
                     c_avg_FWLV)
                cc = (c - c_min_FWLV) / (c_max_FWLV - c_min_FWLV)

                l = farray_l.GetTuple1(k_point)
                ll = (l - l_min) / (l_max - l_min)

                normal_endLV = numpy.reshape(
                    pdata_endLV.GetCellData().GetNormals().GetTuple(
                        cellId_endLV), (3))
                normal_epi = numpy.reshape(
                    pdata_epi.GetCellData().GetNormals().GetTuple(cellId_epi),
                    (3))
                eRR = (1. - rr) * normal_endLV + rr * normal_epi
                eRR /= numpy.linalg.norm(eRR)

                eL = numpy.reshape(farray_eL.GetTuple(k_point), (3))
                eCC = numpy.cross(eL, eRR)
                eCC /= numpy.linalg.norm(eCC)

                eLL = numpy.cross(eRR, eCC)
            elif (region_id == 1):
                cell_locator_endLV.FindClosestPoint(point, closest_point_endLV,
                                                    generic_cell, cellId_endLV,
                                                    subId, dist_endLV)
                cell_locator_endRV.FindClosestPoint(point, closest_point_endRV,
                                                    generic_cell, cellId_endRV,
                                                    subId, dist_endRV)

                rr = dist_endLV / (dist_endLV + dist_endRV)

                c = farray_c.GetTuple1(k_point)
                c = (((c - c_avg_S + math.pi) % (2 * math.pi)) - math.pi +
                     c_avg_S)
                cc = (c - c_min_S) / (c_max_S - c_min_S)

                l = farray_l.GetTuple1(k_point)
                ll = (l - l_min) / (l_max - l_min)

                normal_endLV = numpy.reshape(
                    pdata_endLV.GetCellData().GetNormals().GetTuple(
                        cellId_endLV), (3))
                normal_endRV = numpy.reshape(
                    pdata_endRV.GetCellData().GetNormals().GetTuple(
                        cellId_endRV), (3))
                eRR = (1. - rr) * normal_endLV - rr * normal_endRV
                eRR /= numpy.linalg.norm(eRR)

                eL = numpy.reshape(farray_eL.GetTuple(k_point), (3))
                eCC = numpy.cross(eL, eRR)
                eCC /= numpy.linalg.norm(eCC)

                eLL = numpy.cross(eRR, eCC)
            if (region_id == 2):
                cell_locator_endRV.FindClosestPoint(point, closest_point_endRV,
                                                    generic_cell, cellId_endRV,
                                                    subId, dist_endRV)
                cell_locator_epi.FindClosestPoint(point, closest_point_epi,
                                                  generic_cell, cellId_epi,
                                                  subId, dist_epi)

                rr = dist_endRV / (dist_endRV + dist_epi)

                c = farray_c.GetTuple1(k_point)
                c = (((c - c_avg_FWRV + math.pi) % (2 * math.pi)) - math.pi +
                     c_avg_FWRV)
                cc = (c - c_min_FWRV) / (c_max_FWRV - c_min_FWRV)

                l = farray_l.GetTuple1(k_point)
                ll = (l - l_min) / (l_max - l_min)

                normal_endRV = numpy.reshape(
                    pdata_endRV.GetCellData().GetNormals().GetTuple(
                        cellId_endRV), (3))
                normal_epi = numpy.reshape(
                    pdata_epi.GetCellData().GetNormals().GetTuple(cellId_epi),
                    (3))
                eRR = (1. - rr) * normal_endRV + rr * normal_epi
                eRR /= numpy.linalg.norm(eRR)

                eL = numpy.reshape(farray_eL.GetTuple(k_point), (3))
                eCC = numpy.cross(eL, eRR)
                eCC /= numpy.linalg.norm(eCC)

                eLL = numpy.cross(eRR, eCC)

        farray_rr.SetTuple1(k_point, rr)
        farray_cc.SetTuple1(k_point, cc)
        farray_ll.SetTuple1(k_point, ll)
        farray_eRR.SetTuple(k_point, eRR)
        farray_eCC.SetTuple(k_point, eCC)
        farray_eLL.SetTuple(k_point, eLL)

    return (farray_rr, farray_cc, farray_ll, farray_eRR, farray_eCC,
            farray_eLL)
def computeFiberSheetNormalDirections(
        farray_eRR,
        farray_eCC,
        farray_eLL,
        farray_helix,
        farray_trans,
        farray_sheet,
        angles_in_degrees=True,
        use_new_definition=False,
        shuffle_vectors=False,
        verbose=True):

    myVTK.myPrint(verbose, "*** computeFiberSheetNormalDirections ***")

    n_tuples = farray_helix.GetNumberOfTuples()

    farray_eF = myVTK.createFloatArray("eF", 3, n_tuples)
    farray_eS = myVTK.createFloatArray("eS", 3, n_tuples)
    farray_eN = myVTK.createFloatArray("eN", 3, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)

        if (use_new_definition):
            base = numpy.array([eCC,\
                                eLL,\
                                eRR])

            helix = farray_helix.GetTuple1(k_tuple)
            if (angles_in_degrees): helix *= math.pi/180
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(R_helix, base)

            trans = farray_trans.GetTuple1(k_tuple)
            if (angles_in_degrees): trans *= math.pi/180
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(R_trans, base)

            sheet = farray_sheet.GetTuple1(k_tuple)
            if (angles_in_degrees): sheet *= math.pi/180
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(R_sheet, base)
        else:
            base = numpy.array([+eCC,\
                                +eRR,\
                                -eLL])

            helix = farray_helix.GetTuple1(k_tuple)
            if (angles_in_degrees): helix *= math.pi/180
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(R_helix, base)

            trans = farray_trans.GetTuple1(k_tuple)
            if (angles_in_degrees): trans *= math.pi/180
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(R_trans, base)

            sheet = farray_sheet.GetTuple1(k_tuple)
            if (angles_in_degrees): sheet *= math.pi/180
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(R_sheet, base)

        eF = base[0]
        eS = base[1]
        eN = base[2]

        if (shuffle_vectors):
            eF *= random.choice([-1,+1])
            eS *= random.choice([-1,+1])
            eN = numpy.cross(eF, eS)

        farray_eF.SetTuple(k_tuple, eF)
        farray_eS.SetTuple(k_tuple, eS)
        farray_eN.SetTuple(k_tuple, eN)

    return (farray_eF,
            farray_eS,
            farray_eN)
def readMatLabImage(
        filename,
        field_name,
        field_type,
        spacing=[1.,1.,1.],
        verbose=0):

    mypy.my_print(verbose, "*** readMatLabImage ***")

    assert (os.path.isfile(filename)), "Wrong filename (\""+filename+"\"). Aborting."

    import scipy
    data = scipy.io.loadmat(filename)[field_name]

    n_pixels_x = len(data)
    n_pixels_y = len(data[0])
    n_pixels_z = len(data[0][0])

    n_pixels = n_pixels_x * n_pixels_y * n_pixels_z

    #points = vtk.vtkPoints()
    #points.SetNumberOfPoints(n_pixels)

    #cell_array = vtk.vtkCellArray()
    #cell = vtk.vtkVertex()

    if (field_type == "int"):
        array_data = myvtk.createIntArray(
            name=field_name,
            n_components=1,
            n_tuples=n_pixels)
    elif (field_type == "double"):
        array_data = myvtk.createFloatArray(
            name=field_name,
            n_components=1,
            n_tuples=n_pixels)

    k_pixel = 0
    for k_z in range(n_pixels_z):
        for k_y in range(n_pixels_y):
            for k_x in range(n_pixels_x):
                #points.InsertPoint(k_pixel, [(k_x+0.5)/n_pixels_x,\
                                               #(k_y+0.5)/n_pixels_y,\
                                               #(k_z+0.5)/n_pixels_z])

                #cell.GetPointIds().SetId(0, k_pixel)
                #cell_array.InsertNextCell(cell)

                #array_data.SetTuple1(k_pixel, data[n_pixels_y-1-k_y][n_pixels_x-1-k_x][k_z])
                #array_data.SetTuple1(k_pixel, data[n_pixels_y-1-k_y][k_x][k_z])
                #array_data.SetTuple1(k_pixel, data[k_y][n_pixels_x-1-k_x][k_z])
                array_data.SetTuple1(k_pixel, data[k_y][k_x][k_z])
                #array_data.SetTuple1(k_pixel, data[n_pixels_x-1-k_x][n_pixels_y-1-k_y][k_z])
                #array_data.SetTuple1(k_pixel, data[n_pixels_x-1-k_x][k_y][k_z])
                #array_data.SetTuple1(k_pixel, data[k_x][n_pixels_y-1-k_y][k_z])
                #array_data.SetTuple1(k_pixel, data[k_x][k_y][k_z])

                k_pixel += 1

    #ugrid = vtk.vtkUnstructuredGrid()
    #ugrid.SetPoints(points)
    #ugrid.SetCells(vtk.VTK_VERTEX, cell_array)
    #ugrid.GetCellData().AddArray(array_data)
    #writeXMLUGrid(ugrid, case+".vtu")

    image = vtk.vtkImageData()
    image.SetExtent(0, n_pixels_x-1, 0, n_pixels_y-1, 0, n_pixels_z-1)
    image.SetSpacing(spacing)
    image.GetPointData().AddArray(array_data)

    return image
def computeSyntheticHelixAngles2(farray_rr,
                                 farray_cc,
                                 farray_ll,
                                 angles_end=[[+60.], [+60.]],
                                 angles_epi=[[-60.], [-60.]],
                                 sigma=0.,
                                 farray_angle_helix=None,
                                 verbose=0):

    myVTK.myPrint(verbose, "*** computeSyntheticHelixAngles2 ***")

    n_l = len(angles_end)
    assert (n_l > 1),\
        "n_l must be greater than 1. Aborting."
    assert (len(angles_epi) == n_l),\
        "angles_end and angle_epi must have same length (n_l). Aborting."
    d_l = 1. / (n_l - 1)

    n_c = len(angles_end[0])
    assert (n_c > 0),\
        "n_c must be greater than 0. Aborting."
    for angles in angles_end + angles_epi:
        assert (len(angles) == n_c),\
            "angles lists must have same length (n_c). Aborting."
    d_c = 1. / n_c

    n_tuples = farray_rr.GetNumberOfTuples()
    assert (farray_cc.GetNumberOfTuples() == n_tuples)
    assert (farray_ll.GetNumberOfTuples() == n_tuples)

    if (farray_angle_helix is None):
        farray_angle_helix = myVTK.createFloatArray(name="angle_helix",
                                                    n_components=1,
                                                    n_tuples=n_tuples)
    else:
        assert (farray_angle_helix.GetNumberOfTuples() == n_tuples)

    for k_tuple in xrange(n_tuples):
        #print "k_tuple = "+str(k_tuple)

        cc = farray_cc.GetTuple1(k_tuple)
        i_c = int(cc / d_c / 1.000001)
        #print "i_c = "+str(i_c)

        zeta = (t - i_c * d_c) / d_c
        #print "zeta = "+str(zeta)

        ll = farray_ll.GetTuple1(k_tuple)
        i_l = int(ll / d_l / 1.000001)
        #print "i_l = "+str(i_l)

        eta = (ll - i_l * d_l) / d_l
        #print "eta = "+str(eta)

        t_ii_end = angles_end[i_l][i_c % n_c]
        t_ji_end = angles_end[i_l][(i_c + 1) % n_c]
        t_ij_end = angles_end[i_l + 1][i_c % n_c]
        t_jj_end = angles_end[i_l + 1][(i_c + 1) % n_c]
        t_ii_epi = angles_epi[i_l][i_c % n_c]
        t_ji_epi = angles_epi[i_l][(i_c + 1) % n_c]
        t_ij_epi = angles_epi[i_l + 1][i_c % n_c]
        t_jj_epi = angles_epi[i_l + 1][(i_c + 1) % n_c]
        #print "t_ii_end = "+str(t_ii_end)
        #print "t_ji_end = "+str(t_ji_end)
        #print "t_ij_end = "+str(t_ij_end)
        #print "t_jj_end = "+str(t_jj_end)
        #print "t_ii_epi = "+str(t_ii_epi)
        #print "t_ji_epi = "+str(t_ji_epi)
        #print "t_ij_epi = "+str(t_ij_epi)
        #print "t_jj_epi = "+str(t_jj_epi)

        helix_angle_end = t_ii_end * (1 - zeta - eta + zeta*eta) \
                        + t_ji_end * (zeta - zeta*eta) \
                        + t_ij_end * (eta - zeta*eta) \
                        + t_jj_end * (zeta*eta)
        helix_angle_epi = t_ii_epi * (1 - zeta - eta + zeta*eta) \
                        + t_ji_epi * (zeta - zeta*eta) \
                        + t_ij_epi * (eta - zeta*eta) \
                        + t_jj_epi * (zeta*eta)

        rr = farray_rr.GetTuple1(k_tuple)
        helix_angle_in_degrees = (1.-rr) * helix_angle_end \
                               +     rr  * helix_angle_epi

        if (sigma > 0.):
            helix_angle_in_degrees += random.normalvariate(0., sigma)
            helix_angle_in_degrees = (helix_angle_in_degrees +
                                      90.) % 180. - 90.

        farray_angle_helix.SetTuple1(k_tuple, helix_angle_in_degrees)

    return farray_angle_helix
示例#45
0
def computeFiberSheetNormalDirections(farray_eRR,
                                      farray_eCC,
                                      farray_eLL,
                                      farray_helix,
                                      farray_trans,
                                      farray_sheet,
                                      angles_in_degrees=True,
                                      use_new_definition=False,
                                      shuffle_vectors=False,
                                      verbose=True):

    myVTK.myPrint(verbose, "*** computeFiberSheetNormalDirections ***")

    n_tuples = farray_helix.GetNumberOfTuples()

    farray_eF = myVTK.createFloatArray("eF", 3, n_tuples)
    farray_eS = myVTK.createFloatArray("eS", 3, n_tuples)
    farray_eN = myVTK.createFloatArray("eN", 3, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)

        if (use_new_definition):
            base = numpy.array([eCC,\
                                eLL,\
                                eRR])

            helix = farray_helix.GetTuple1(k_tuple)
            if (angles_in_degrees): helix *= math.pi / 180
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(R_helix, base)

            trans = farray_trans.GetTuple1(k_tuple)
            if (angles_in_degrees): trans *= math.pi / 180
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(R_trans, base)

            sheet = farray_sheet.GetTuple1(k_tuple)
            if (angles_in_degrees): sheet *= math.pi / 180
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(R_sheet, base)
        else:
            base = numpy.array([+eCC,\
                                +eRR,\
                                -eLL])

            helix = farray_helix.GetTuple1(k_tuple)
            if (angles_in_degrees): helix *= math.pi / 180
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(R_helix, base)

            trans = farray_trans.GetTuple1(k_tuple)
            if (angles_in_degrees): trans *= math.pi / 180
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(R_trans, base)

            sheet = farray_sheet.GetTuple1(k_tuple)
            if (angles_in_degrees): sheet *= math.pi / 180
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(R_sheet, base)

        eF = base[0]
        eS = base[1]
        eN = base[2]

        if (shuffle_vectors):
            eF *= random.choice([-1, +1])
            eS *= random.choice([-1, +1])
            eN = numpy.cross(eF, eS)

        farray_eF.SetTuple(k_tuple, eF)
        farray_eS.SetTuple(k_tuple, eS)
        farray_eN.SetTuple(k_tuple, eN)

    return (farray_eF, farray_eS, farray_eN)
def readMatLabImage(
        filename,
        field_name,
        field_type,
        spacing=[1.,1.,1.],
        verbose=1):

    myVTK.myPrint(verbose, "*** readMatLabImage ***")

    assert (os.path.isfile(filename)), "Wrong filename. Aborting."

    data = scipy.io.loadmat(filename)[field_name]

    n_pixels_x = len(data)
    n_pixels_y = len(data[0])
    n_pixels_z = len(data[0][0])

    n_pixels = n_pixels_x * n_pixels_y * n_pixels_z

    #points = vtk.vtkPoints()
    #points.SetNumberOfPoints(n_pixels)

    #cell_array = vtk.vtkCellArray()
    #cell = vtk.vtkVertex()

    if (field_type == "int"):
        array_data = myVTK.createIntArray(field_name, 1, n_pixels)
    elif (field_type == "double"):
        array_data = myVTK.createFloatArray(field_name, 1, n_pixels)

    k_pixel = 0
    for k_z in xrange(n_pixels_z):
        for k_y in xrange(n_pixels_y):
            for k_x in xrange(n_pixels_x):
                #points.InsertPoint(k_pixel, [(k_x+0.5)/n_pixels_x,\
                                               #(k_y+0.5)/n_pixels_y,\
                                               #(k_z+0.5)/n_pixels_z])

                #cell.GetPointIds().SetId(0, k_pixel)
                #cell_array.InsertNextCell(cell)

                #array_data.InsertTuple(k_pixel, [data[n_pixels_y-1-k_y][n_pixels_x-1-k_x][k_z]])
                #array_data.InsertTuple(k_pixel, [data[n_pixels_y-1-k_y][k_x][k_z]])
                #array_data.InsertTuple(k_pixel, [data[k_y][n_pixels_x-1-k_x][k_z]])
                array_data.InsertTuple(k_pixel, [data[k_y][k_x][k_z]])
                #array_data.InsertTuple(k_pixel, [data[n_pixels_x-1-k_x][n_pixels_y-1-k_y][k_z]])
                #array_data.InsertTuple(k_pixel, [data[n_pixels_x-1-k_x][k_y][k_z]])
                #array_data.InsertTuple(k_pixel, [data[k_x][n_pixels_y-1-k_y][k_z]])
                #array_data.InsertTuple(k_pixel, [data[k_x][k_y][k_z]])

                k_pixel += 1

    #ugrid = vtk.vtkUnstructuredGrid()
    #ugrid.SetPoints(points)
    #ugrid.SetCells(vtk.VTK_VERTEX, cell_array)
    #ugrid.GetCellData().AddArray(array_data)
    #writeXMLUGrid(ugrid, case + ".vtu")

    image = vtk.vtkImageData()
    image.SetExtent(0, n_pixels_x-1, 0, n_pixels_y-1, 0, n_pixels_z-1)
    image.SetSpacing(spacing)
    image.GetPointData().AddArray(array_data)

    return image
def computeStrainsFromDisplacements(
        mesh,
        disp_array_name="displacement",
        ref_mesh=None,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeStrainsFromDisplacements ***")

    myVTK.myPrint(min(verbose,1), "*** Warning: at some point the ordering of vector gradient components has changed, and uses C ordering instead of F. ***")
    if   (vtk.vtkVersion.GetVTKMajorVersion() >= 8):
        ordering = "C"
    elif (vtk.vtkVersion.GetVTKMajorVersion() == 7) and ((vtk.vtkVersion.GetVTKMinorVersion() > 0) or (vtk.vtkVersion.GetVTKBuildVersion() > 0)):
        ordering = "C"
    else:
        ordering = "F"

    n_points = mesh.GetNumberOfPoints()
    n_cells = mesh.GetNumberOfCells()

    assert (mesh.GetPointData().HasArray(disp_array_name))
    mesh.GetPointData().SetActiveVectors(disp_array_name)
    cell_derivatives = vtk.vtkCellDerivatives()
    cell_derivatives.SetVectorModeToPassVectors()
    cell_derivatives.SetTensorModeToComputeGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        cell_derivatives.SetInputData(mesh)
    else:
        cell_derivatives.SetInput(mesh)
    cell_derivatives.Update()
    farray_gu = cell_derivatives.GetOutput().GetCellData().GetArray("VectorGradient")

    if (ref_mesh is not None):
        farray_strain = myVTK.createFloatArray(
            name="Strain_CAR",
            n_components=6,
            n_tuples=n_cells)
    else:
        farray_strain = myVTK.createFloatArray(
            name="Strain",
            n_components=6,
            n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_strain)
    I = numpy.eye(3)
    E_vec = numpy.empty(6)
    #e_vec = numpy.empty(6)
    for k_cell in range(n_cells):
        GU = numpy.reshape(farray_gu.GetTuple(k_cell), (3,3), ordering)
        F = I + GU
        C = numpy.dot(numpy.transpose(F), F)
        E = (C - I)/2
        mat_sym33_to_vec_col6(E, E_vec)
        farray_strain.SetTuple(k_cell, E_vec)
        #if (add_almansi_strain):
            #Finv = numpy.linalg.inv(F)
            #c = numpy.dot(numpy.transpose(Finv), Finv)
            #e = (I - c)/2
            #mat_sym33_to_vec_col6(e, e_vec)
            #farray_almansi.SetTuple(k_cell, e_vec)

    if (ref_mesh is not None) and (ref_mesh.GetCellData().HasArray("eR")) and (ref_mesh.GetCellData().HasArray("eC")) and (ref_mesh.GetCellData().HasArray("eL")):
        farray_strain_cyl = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[ref_mesh.GetCellData().GetArray("eR"),
                      ref_mesh.GetCellData().GetArray("eC"),
                      ref_mesh.GetCellData().GetArray("eL")],
            verbose=0)
        farray_strain_cyl.SetName("Strain_CYL")
        mesh.GetCellData().AddArray(farray_strain_cyl)

    if (ref_mesh is not None) and (ref_mesh.GetCellData().HasArray("eRR")) and (ref_mesh.GetCellData().HasArray("eCC")) and (ref_mesh.GetCellData().HasArray("eLL")):
        farray_strain_pps = myVTK.rotateMatrix(
            old_array=mesh.GetCellData().GetArray("Strain_CAR"),
            out_vecs=[ref_mesh.GetCellData().GetArray("eRR"),
                      ref_mesh.GetCellData().GetArray("eCC"),
                      ref_mesh.GetCellData().GetArray("eLL")],
            verbose=0)
        farray_strain_pps.SetName("Strain_PPS")
        mesh.GetCellData().AddArray(farray_strain_pps)
示例#48
0
def rotateMatrix(old_array,
                 old_array_storage="vec",
                 in_vecs=None,
                 R=None,
                 out_vecs=None,
                 verbose=0):

    myVTK.myPrint(verbose, "*** rotateMatrix ***")
    myVTK.myPrint(
        min(verbose, 1),
        "*** Warning: in rotateMatrix, the definition of the global rotation is probably the inverse of the definition in previous rotateTensors function. ***"
    )

    n_components = old_array.GetNumberOfComponents()
    if (old_array_storage == "vec"):
        assert (n_components == 6
                ), "Wrong numpber of components (n_components=" + str(
                    n_components) + "). Aborting."
    elif (old_array_storage == "Cmat"):
        assert (n_components == 9
                ), "Wrong numpber of components (n_components=" + str(
                    n_components) + "). Aborting."
    elif (old_array_storage == "Fmat"):
        assert (n_components == 9
                ), "Wrong numpber of components (n_components=" + str(
                    n_components) + "). Aborting."
    else:
        assert (0), "Wrong storage (old_array_storage=" + str(
            old_array_storage) + "). Aborting."
    n_tuples = old_array.GetNumberOfTuples()
    new_array = myVTK.createFloatArray(old_array.GetName(), n_components,
                                       n_tuples)
    new_vector = numpy.empty(n_components)

    if (old_array_storage == "vec"):
        old_vector = numpy.empty(6)
    elif (old_array_storage == "Cmat"):
        old_vector = numpy.empty(9)
    elif (old_array_storage == "Fmat"):
        old_vector = numpy.empty(9)
    old_matrix = numpy.empty((3, 3))
    new_matrix = numpy.empty((3, 3))
    for k_tuple in xrange(n_tuples):
        old_array.GetTuple(k_tuple, old_vector)
        if (old_array_storage == "vec"):
            vec_col6_to_mat_sym33(old_vector, old_matrix)
        elif (old_array_storage == "Cmat"):
            cvec9_to_mat33(old_vector, old_matrix)
        elif (old_array_storage == "Fmat"):
            fvec9_to_mat33(old_vector, old_matrix)

        if (in_vecs is None):
            in_R = numpy.eye(3)
        else:
            in_R = numpy.transpose(
                numpy.array([
                    in_vecs[0].GetTuple(k_tuple), in_vecs[1].GetTuple(k_tuple),
                    in_vecs[2].GetTuple(k_tuple)
                ]))

        if (out_vecs is None):
            out_R = numpy.eye(3)
        else:
            out_R = numpy.transpose(
                numpy.array([
                    out_vecs[0].GetTuple(k_tuple),
                    out_vecs[1].GetTuple(k_tuple),
                    out_vecs[2].GetTuple(k_tuple)
                ]))

        if (R is None):
            R = numpy.eye(3)

        full_R = numpy.dot(numpy.dot(numpy.transpose(in_R), R), out_R)

        new_matrix[:] = numpy.dot(
            numpy.dot(numpy.transpose(full_R), old_matrix), full_R)

        if (old_array_storage == "vec"):
            mat_sym33_to_vec_col6(new_matrix, new_vector)
        elif (old_array_storage == "Cmat"):
            mat33_to_cvec9(new_matrix, new_vector)
        elif (old_array_storage == "Fmat"):
            mat33_to_fvec9(new_matrix, new_vector)

        new_array.SetTuple(k_tuple, new_vector)

    return new_array
示例#49
0
def computeHelixTransverseSheetAngles2(farray_eRR,
                                       farray_eCC,
                                       farray_eLL,
                                       farray_eF,
                                       farray_eS,
                                       farray_eN,
                                       use_new_definition=False,
                                       ref_vectors_are_material_basis=False,
                                       verbose=0):

    myVTK.myPrint(verbose, "*** computeHelixTransverseSheetAngles2 ***")

    n_tuples = farray_eRR.GetNumberOfTuples()
    assert (farray_eCC.GetNumberOfTuples() == n_tuples)
    assert (farray_eLL.GetNumberOfTuples() == n_tuples)
    assert (farray_eF.GetNumberOfTuples() == n_tuples)
    assert (farray_eS.GetNumberOfTuples() == n_tuples)
    assert (farray_eN.GetNumberOfTuples() == n_tuples)

    farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_tuples)
    farray_angle_trans = myVTK.createFloatArray("angle_trans", 1, n_tuples)
    farray_angle_sheet = myVTK.createFloatArray("angle_sheet", 1, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    eF = numpy.empty(3)
    eS = numpy.empty(3)
    eN = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)
        farray_eF.GetTuple(k_tuple, eF)
        farray_eS.GetTuple(k_tuple, eS)
        farray_eN.GetTuple(k_tuple, eN)

        #print "eRR = "+str(eRR)
        #print "eCC = "+str(eCC)
        #print "eLL = "+str(eLL)
        #print "eF = "+str(eF)
        #print "eS = "+str(eS)
        #print "eN = "+str(eN)

        #print "|eRR| = "+str(numpy.linalg.norm(eRR))
        #print "|eCC| = "+str(numpy.linalg.norm(eCC))
        #print "|eLL| = "+str(numpy.linalg.norm(eLL))

        #print "eRR.eCC = "+str(numpy.dot(eRR, eCC))
        #print "eCC.eLL = "+str(numpy.dot(eCC, eLL))
        #print "eLL.eRR = "+str(numpy.dot(eLL, eRR))

        #print "|eF| = "+str(numpy.linalg.norm(eF))
        #print "|eS| = "+str(numpy.linalg.norm(eS))
        #print "|eN| = "+str(numpy.linalg.norm(eN))

        #print "eF.eS = "+str(numpy.dot(eF, eS))
        #print "eS.eN = "+str(numpy.dot(eS, eN))
        #print "eN.eF = "+str(numpy.dot(eN, eF))

        assert (round(numpy.linalg.norm(eRR),1) == 1.0),\
            "|eRR| = "+str(numpy.linalg.norm(eRR))+" ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eCC),1) == 1.0),\
            "|eCC| = "+str(numpy.linalg.norm(eCC))+" ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eLL),1) == 1.0),\
            "|eLL| = "+str(numpy.linalg.norm(eLL))+" ≠ 1. Aborting."

        assert (round(numpy.dot(eRR,eCC),1) == 0.0),\
            "eRR.eCC = "+str(numpy.dot(eRR,eCC))+" ≠ 0. Aborting."
        assert (round(numpy.dot(eCC,eLL),1) == 0.0),\
            "eCC.eLL = "+str(numpy.dot(eCC,eLL))+" ≠ 0. Aborting."
        assert (round(numpy.dot(eLL,eRR),1) == 0.0),\
            "eLL.eRR = "+str(numpy.dot(eLL,eRR))+" ≠ 0. Aborting."

        assert (round(numpy.linalg.det([eRR, eCC, eLL]),1) == 1.0),\
            "det([eRR, eCC, eLL]) = "+str(numpy.linalg.det([eRR, eCC, eLL]))+" ≠ 1. Aborting."

        assert (round(numpy.linalg.norm(eF),1) == 1.0),\
            "|eF| = "+str(numpy.linalg.norm(eF))+" ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eS),1) == 1.0),\
            "|eS| = "+str(numpy.linalg.norm(eS))+" ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eN),1) == 1.0),\
            "|eN| = "+str(numpy.linalg.norm(eN))+" ≠ 1. Aborting."

        assert (round(numpy.dot(eF,eS),1) == 0.0),\
            "eF.eS = "+str(numpy.dot(eF,eS))+" ≠ 0. Aborting."
        assert (round(numpy.dot(eS,eN),1) == 0.0),\
            "eS.eN = "+str(numpy.dot(eS,eN))+" ≠ 0. Aborting."
        assert (round(numpy.dot(eN,eF),1) == 0.0),\
            "eN.eF = "+str(numpy.dot(eN,eF))+" ≠ 0. Aborting."

        assert (round(numpy.linalg.det([eF, eS, eN]),1) == 1.0),\
            "det([eF, eS, eN]) = "+str(numpy.linalg.det([eF, eS, eN]))+" ≠ 1. Aborting."

        # reference basis
        if (ref_vectors_are_material_basis):
            ref = numpy.array([+eRR, +eCC, +eLL])
        else:
            if (use_new_definition):
                ref = numpy.array([+eCC, +eLL, +eRR])
            else:
                ref = numpy.array([+eCC, +eRR, -eLL])

        # material basis
        if (abs(numpy.dot(eF, ref[0])) > 1e-3):
            eF = math.copysign(1., numpy.dot(eF, ref[0])) * eF
        if (abs(numpy.dot(eS, ref[1])) > 1e-3):
            eS = math.copysign(1., numpy.dot(eS, ref[1])) * eS
        eN = numpy.cross(eF, eS)
        base = numpy.array([eF, eS, eN])

        assert (round(numpy.linalg.det(base),1) == 1.0),\
            "det(base) = "+str(numpy.linalg.det(base))+" ≠ 1. Aborting."

        #print "b0.r0 = "+str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = "+str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = "+str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = "+str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = "+str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = "+str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = "+str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = "+str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = "+str(numpy.dot(base[2], ref[2]))

        if (use_new_definition):
            sheet = math.atan2(numpy.dot(base[1], ref[2]),
                               numpy.dot(base[2], ref[2]))
            #print "sheet = "+str(sheet)+" = "+str(sheet*180/math.pi)
            #sheet = (sheet+math.pi/2)%math.pi - math.pi/2
            #print "sheet = "+str(sheet)+" = "+str(sheet*180/math.pi)
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(numpy.transpose(R_sheet), base)
            #print base
            if (numpy.dot(base[1], ref[1]) < 0):
                R_sheet = numpy.array([[1,  0,  0],\
                                       [0, -1,  0],\
                                       [0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_sheet), base)
        else:
            sheet = math.atan2(-numpy.dot(base[2], ref[1]),
                               numpy.dot(base[1], ref[1]))
            #print "sheet = "+str(sheet)+" = "+str(sheet*180/math.pi)
            #sheet = (sheet+math.pi/2)%math.pi - math.pi/2
            #print "sheet = "+str(sheet)+" = "+str(sheet*180/math.pi)
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(numpy.transpose(R_sheet), base)
            #print base
            if (numpy.dot(base[2], ref[2]) < 0):
                R_sheet = numpy.array([[1,  0,  0],\
                                       [0, -1,  0],\
                                       [0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_sheet), base)

        #print "b0.r0 = "+str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = "+str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = "+str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = "+str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = "+str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = "+str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = "+str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = "+str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = "+str(numpy.dot(base[2], ref[2]))

        if (use_new_definition):
            trans = math.atan2(numpy.dot(base[2], ref[0]),
                               numpy.dot(base[0], ref[0]))
            #print "trans = "+str(trans)+" = "+str(trans*180/math.pi)
            #assert (math.atan2(numpy.dot(base[2], ref[1]), numpy.dot(base[0], ref[1])) == trans),\
            #"atan2(b2 . r1, b0 . r1) = "+str(math.atan2(numpy.dot(base[2], ref[1]), numpy.dot(base[0], ref[1])))+" ≠ trans. Aborting."
            #assert (math.atan2(-numpy.dot(base[0], ref[2]), numpy.dot(base[2], ref[2])) == trans),\
            #"atan2(-b0 . r2, b2 . r2) = "+str(math.atan2(-numpy.dot(base[0], ref[2]), numpy.dot(base[2], ref[2])))+" ≠ trans. Aborting."
            #trans = (trans+math.pi/2)%math.pi - math.pi/2
            #print "trans = "+str(trans)+" = "+str(trans*180/math.pi)
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(numpy.transpose(R_trans), base)
            #print base
            if (numpy.dot(base[2], ref[2]) < 0):
                R_trans = numpy.array([[-1,  0,  0],\
                                       [ 0,  1,  0],\
                                       [ 0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_trans), base)
        else:
            trans = math.atan2(-numpy.dot(base[1], ref[0]),
                               numpy.dot(base[0], ref[0]))
            #print "trans = "+str(trans)+" = "+str(trans*180/math.pi)
            #assert (math.atan2(-numpy.dot(base[1], ref[2]), numpy.dot(base[0], ref[2])) == trans),\
            #"atan2(b1 . r2, b0 . r2) = "+str(math.atan2(numpy.dot(base[1], ref[2]), numpy.dot(base[0], ref[2])))+" ≠ trans. Aborting."
            #assert (-math.atan2(-numpy.dot(base[0], ref[1]), numpy.dot(base[1], ref[1])) == trans),\
            #"atan2(-b0 . r1, b1 . r1) = "+str(math.atan2(-numpy.dot(base[0], ref[1]), numpy.dot(base[1], ref[1])))+" ≠ trans. Aborting."
            #trans = (trans+math.pi/2)%math.pi - math.pi/2
            #print "trans = "+str(trans)+" = "+str(trans*180/math.pi)
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(numpy.transpose(R_trans), base)
            #print base
            if (numpy.dot(base[1], ref[1]) < 0):
                R_trans = numpy.array([[-1,  0,  0],\
                                       [ 0, -1,  0],\
                                       [ 0,  0,  1]])
                base = numpy.dot(numpy.transpose(R_trans), base)

        #print "b0.r0 = "+str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = "+str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = "+str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = "+str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = "+str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = "+str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = "+str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = "+str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = "+str(numpy.dot(base[2], ref[2]))

        if (use_new_definition):
            helix = math.atan2(numpy.dot(base[0], ref[1]),
                               numpy.dot(base[1], ref[1]))
            #print "helix = "+str(helix)+" = "+str(helix*180/math.pi)
            #assert (numpy.isclose(math.atan2(-numpy.dot(base[1], ref[0]), numpy.dot(base[0], ref[0])), helix, atol=1e-3)),\
            #"atan2(-b1 . r0, b0 . r0) = "+str(math.atan2(-numpy.dot(base[1], ref[0]), numpy.dot(base[0], ref[0])))+" ≠ helix. Aborting."
            #helix = (helix+math.pi/2)%math.pi - math.pi/2
            #print "helix = "+str(helix)+" = "+str(helix*180/math.pi)
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(numpy.transpose(R_helix), base)
            #print base
            if (numpy.dot(base[0], ref[0]) < 0):
                R_helix = numpy.array([[-1,  0,  0],\
                                       [ 0, -1,  0],\
                                       [ 0,  0,  1]])
                base = numpy.dot(numpy.transpose(R_helix), base)
        else:
            helix = math.atan2(-numpy.dot(base[0], ref[2]),
                               numpy.dot(base[2], ref[2]))
            #print "helix = "+str(helix)+" = "+str(helix*180/math.pi)
            #assert (numpy.isclose(math.atan2(numpy.dot(base[2], ref[0]), numpy.dot(base[0], ref[0])), helix, atol=1e-3)),\
            #"atan2(-b2 . r0, b0 . r0) = "+str(math.atan2(-numpy.dot(base[2], ref[0]), numpy.dot(base[0], ref[0])))+" ≠ helix. Aborting."
            #helix = (helix+math.pi/2)%math.pi - math.pi/2
            #print "helix = "+str(helix)+" = "+str(helix*180/math.pi)
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(numpy.transpose(R_helix), base)
            #print base
            if (numpy.dot(base[0], ref[0]) < 0):
                R_helix = numpy.array([[-1,  0,  0],\
                                       [ 0,  1,  0],\
                                       [ 0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_helix), base)

        #print "b0.r0 = "+str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = "+str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = "+str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = "+str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = "+str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = "+str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = "+str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = "+str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = "+str(numpy.dot(base[2], ref[2]))

        assert (round(numpy.dot(base[0],ref[0]),1) == 1.0),\
            "b0.r0 = "+str(numpy.dot(base[0],ref[0]))+" ≠ 1. Aborting."
        assert (round(numpy.dot(base[1],ref[1]),1) == 1.0),\
            "b1.r1 = "+str(numpy.dot(base[1],ref[1]))+" ≠ 1. Aborting."
        assert (round(numpy.dot(base[2],ref[2]),1) == 1.0),\
            "b2.r2 = "+str(numpy.dot(base[2],ref[2]))+" ≠ 1. Aborting."

        helix = (helix + math.pi / 2) % math.pi - math.pi / 2
        trans = (trans + math.pi / 2) % math.pi - math.pi / 2
        sheet = (sheet + math.pi / 2) % math.pi - math.pi / 2

        helix *= 180 / math.pi
        trans *= 180 / math.pi
        sheet *= 180 / math.pi

        farray_angle_helix.SetTuple1(k_tuple, helix)
        farray_angle_trans.SetTuple1(k_tuple, trans)
        farray_angle_sheet.SetTuple1(k_tuple, sheet)

    return (farray_angle_helix, farray_angle_trans, farray_angle_sheet)
def computePseudoProlateSpheroidalCoordinatesAndBasisForLV(
        points,
        farray_c,
        farray_l,
        farray_eL,
        pdata_end,
        pdata_epi,
        iarray_part_id=None,
        verbose=1):

    myVTK.myPrint(verbose, "*** computePseudoProlateSpheroidalCoordinatesAndBasisForLV ***")

    myVTK.myPrint(verbose, "Computing surface cell normals...")

    pdata_end = myVTK.addPDataNormals(
        pdata=pdata_end,
        verbose=verbose-1)
    pdata_epi = myVTK.addPDataNormals(
        pdata=pdata_epi,
        verbose=verbose)

    myVTK.myPrint(verbose, "Initializing surface cell locators...")

    (cell_locator_end,
     closest_point_end,
     generic_cell,
     cellId_end,
     subId,
     dist_end) = myVTK.getCellLocator(
         mesh=pdata_end,
         verbose=verbose-1)
    (cell_locator_epi,
     closest_point_epi,
     generic_cell,
     cellId_epi,
     subId,
     dist_epi) = myVTK.getCellLocator(
         mesh=pdata_epi,
         verbose=verbose-1)

    myVTK.myPrint(verbose, "Computing local prolate spheroidal directions...")

    n_points = points.GetNumberOfPoints()

    farray_rr = myVTK.createFloatArray("rr", 1, n_points)
    farray_cc = myVTK.createFloatArray("cc", 1, n_points)
    farray_ll = myVTK.createFloatArray("ll", 1, n_points)

    farray_eRR = myVTK.createFloatArray("eRR", 3, n_points)
    farray_eCC = myVTK.createFloatArray("eCC", 3, n_points)
    farray_eLL = myVTK.createFloatArray("eLL", 3, n_points)

    if (n_points == 0):
        return (farray_rr,
                farray_cc,
                farray_ll,
                farray_eRR,
                farray_eCC,
                farray_eLL)

    c_lst = [farray_c.GetTuple(k_point)[0] for k_point in xrange(n_points)]
    c_min = min(c_lst)
    c_max = max(c_lst)

    l_lst = [farray_l.GetTuple(k_point)[0] for k_point in xrange(n_points)]
    l_min = min(l_lst)
    l_max = max(l_lst)

    for k_point in xrange(n_points):
        if (iarray_part_id is not None) and (int(iarray_part_id.GetTuple(k_point)[0]) > 0):
            rr = 0.
            cc = 0.
            ll = 0.
            eRR = [1.,0.,0.]
            eCC = [0.,1.,0.]
            eLL = [0.,0.,1.]

        else:
            point = numpy.array(points.GetPoint(k_point))
            cell_locator_end.FindClosestPoint(
                point,
                closest_point_end,
                generic_cell,
                cellId_end,
                subId,
                dist_end)
            cell_locator_epi.FindClosestPoint(
                point,
                closest_point_epi,
                generic_cell,
                cellId_epi,
                subId,
                dist_epi)

            rr = dist_end/(dist_end+dist_epi)

            c = farray_c.GetTuple(k_point)[0]
            cc = (c-c_min) / (c_max-c_min)

            l = farray_l.GetTuple(k_point)[0]
            ll = (l-l_min) / (l_max-l_min)

            normal_end = numpy.reshape(pdata_end.GetCellData().GetNormals().GetTuple(cellId_end), (3))
            normal_epi = numpy.reshape(pdata_epi.GetCellData().GetNormals().GetTuple(cellId_epi), (3))
            eRR  = (1.-rr) * normal_end + rr * normal_epi
            eRR /= numpy.linalg.norm(eRR)

            eL = numpy.reshape(farray_eL.GetTuple(k_point), (3))
            eCC  = numpy.cross(eL, eRR)
            eCC /= numpy.linalg.norm(eCC)

            eLL = numpy.cross(eRR, eCC)

        farray_rr.InsertTuple(k_point, [rr])
        farray_cc.InsertTuple(k_point, [cc])
        farray_ll.InsertTuple(k_point, [ll])
        farray_eRR.InsertTuple(k_point, eRR)
        farray_eCC.InsertTuple(k_point, eCC)
        farray_eLL.InsertTuple(k_point, eLL)

    return (farray_rr,
            farray_cc,
            farray_ll,
            farray_eRR,
            farray_eCC,
            farray_eLL)
示例#51
0
def computeFiberDirections(
        farray_eRR,
        farray_eCC,
        farray_eLL,
        farray_angle_helix,
        angles_in_degrees=True,
        use_new_definition=False,
        shuffle_vectors=False,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeFiberDirections ***")

    n_tuples = farray_angle_helix.GetNumberOfTuples()

    farray_eF = myVTK.createFloatArray("eF", 3, n_tuples)
    farray_eS = myVTK.createFloatArray("eS", 3, n_tuples)
    farray_eN = myVTK.createFloatArray("eN", 3, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)

        assert (round(numpy.linalg.norm(eRR),1) == 1.0),\
            "|eRR| = "+str(numpy.linalg.norm(eRR))+"≠ 1. Aborting"
        assert (round(numpy.linalg.norm(eCC),1) == 1.0),\
            "|eCC| = "+str(numpy.linalg.norm(eCC))+"≠ 1. Aborting"
        assert (round(numpy.linalg.norm(eLL),1) == 1.0),\
            "|eLL| = "+str(numpy.linalg.norm(eLL))+"≠ 1. Aborting"

        angle_helix = farray_angle_helix.GetTuple1(k_tuple)
        if (angles_in_degrees): angle_helix = angle_helix*math.pi/180
        eF = math.cos(angle_helix) * eCC + math.sin(angle_helix) * eLL
        #print "eF = "+str(eF)
        if (shuffle_vectors):
            eF *= random.choice([-1,+1])
            #print "eF = "+str(eF)
        if (use_new_definition):
            eN = eRR
            if (shuffle_vectors):
                eN *= random.choice([-1,+1])
                assert (abs(numpy.dot(eN,eRR)) > 0.999)
            eS = numpy.cross(eN, eF)
        else:
            eS = eRR
            if (shuffle_vectors): eS *= random.choice([-1,+1])
            eN = numpy.cross(eF, eS)

        assert (round(numpy.linalg.norm(eF),1) == 1.0),\
            "|eF| = "+str(numpy.linalg.norm(eF))+"≠ 1. Aborting"
        assert (round(numpy.linalg.norm(eS),1) == 1.0),\
            "|eS| = "+str(numpy.linalg.norm(eS))+"≠ 1. Aborting"
        assert (round(numpy.linalg.norm(eN),1) == 1.0),\
            "|eN| = "+str(numpy.linalg.norm(eN))+"≠ 1. Aborting"

        farray_eF.SetTuple(k_tuple, eF)
        farray_eS.SetTuple(k_tuple, eS)
        farray_eN.SetTuple(k_tuple, eN)

    return (farray_eF,
            farray_eS,
            farray_eN)
def computePseudoProlateSpheroidalCoordinatesAndBasisForBiV(
        points,
        iarray_regions,
        farray_c,
        farray_l,
        farray_eL,
        pdata_endLV,
        pdata_endRV,
        pdata_epi,
        iarray_part_id=None,
        verbose=1):

    myVTK.myPrint(verbose, "*** computePseudoProlateSpheroidalCoordinatesAndBasisForBiV ***")

    myVTK.myPrint(verbose, "Computing surface cell normals...")

    pdata_endLV = myVTK.addPDataNormals(
        pdata=pdata_endLV,
        verbose=verbose-1)
    pdata_endRV = myVTK.addPDataNormals(
        pdata=pdata_endRV,
        verbose=verbose-1)
    pdata_epi = myVTK.addPDataNormals(
        pdata=pdata_epi,
        verbose=verbose)

    myVTK.myPrint(verbose, "Initializing surface cell locators...")

    (cell_locator_endLV,
     closest_point_endLV,
     generic_cell,
     cellId_endLV,
     subId,
     dist_endLV) = myVTK.getCellLocator(
         mesh=pdata_endLV,
         verbose=verbose-1)
    (cell_locator_endRV,
    closest_point_endRV,
    generic_cell,
    cellId_endRV,
    subId,
    dist_endRV) = myVTK.getCellLocator(
        mesh=pdata_endRV,
        verbose=verbose-1)
    (cell_locator_epi,
     closest_point_epi,
     generic_cell,
     cellId_epi,
     subId,
     dist_epi) = myVTK.getCellLocator(
         mesh=pdata_epi,
         verbose=verbose-1)

    myVTK.myPrint(verbose, "Computing local prolate spheroidal directions...")

    n_points = points.GetNumberOfPoints()

    farray_rr = myVTK.createFloatArray("rr", 1, n_points)
    farray_cc = myVTK.createFloatArray("cc", 1, n_points)
    farray_ll = myVTK.createFloatArray("ll", 1, n_points)

    farray_eRR = myVTK.createFloatArray("eRR", 3, n_points)
    farray_eCC = myVTK.createFloatArray("eCC", 3, n_points)
    farray_eLL = myVTK.createFloatArray("eLL", 3, n_points)

    c_lst_FWLV = numpy.array([farray_c.GetTuple(k_point)[0] for k_point in xrange(n_points) if (iarray_regions.GetTuple(k_point)[0] == 0)])
    (c_avg_FWLV, c_std_FWLV) = myVTK.computeMeanStddevAngles(
        angles=c_lst_FWLV,
        angles_in_degrees=False,
        angles_in_pm_pi=False)
    myVTK.myPrint(verbose, "c_avg_FWLV = " + str(c_avg_FWLV))
    c_lst_FWLV = (((c_lst_FWLV-c_avg_FWLV+math.pi)%(2*math.pi))-math.pi+c_avg_FWLV)
    c_min_FWLV = min(c_lst_FWLV)
    c_max_FWLV = max(c_lst_FWLV)
    myVTK.myPrint(verbose, "c_min_FWLV = " + str(c_min_FWLV))
    myVTK.myPrint(verbose, "c_max_FWLV = " + str(c_max_FWLV))

    c_lst_S = numpy.array([farray_c.GetTuple(k_point)[0] for k_point in xrange(n_points) if (iarray_regions.GetTuple(k_point)[0] == 1)])
    (c_avg_S, c_std_S) = myVTK.computeMeanStddevAngles(
        angles=c_lst_S,
        angles_in_degrees=False,
        angles_in_pm_pi=False)
    myVTK.myPrint(verbose, "c_avg_S = " + str(c_avg_S))
    c_lst_S = (((c_lst_S-c_avg_S+math.pi)%(2*math.pi))-math.pi+c_avg_S)
    c_min_S = min(c_lst_S)
    c_max_S = max(c_lst_S)
    myVTK.myPrint(verbose, "c_min_S = " + str(c_min_S))
    myVTK.myPrint(verbose, "c_max_S = " + str(c_max_S))

    c_lst_FWRV = numpy.array([farray_c.GetTuple(k_point)[0] for k_point in xrange(n_points) if (iarray_regions.GetTuple(k_point)[0] == 2)])
    (c_avg_FWRV, c_std_FWRV) = myVTK.computeMeanStddevAngles(
        angles=c_lst_FWRV,
        angles_in_degrees=False,
        angles_in_pm_pi=False)
    myVTK.myPrint(verbose, "c_avg_FWRV = " + str(c_avg_FWRV))
    c_lst_FWRV = (((c_lst_FWRV-c_avg_FWRV+math.pi)%(2*math.pi))-math.pi+c_avg_FWRV)
    c_min_FWRV = min(c_lst_FWRV)
    c_max_FWRV = max(c_lst_FWRV)
    myVTK.myPrint(verbose, "c_min_FWRV = " + str(c_min_FWRV))
    myVTK.myPrint(verbose, "c_max_FWRV = " + str(c_max_FWRV))

    l_lst = [farray_l.GetTuple(k_point)[0] for k_point in xrange(n_points)]
    l_min = min(l_lst)
    l_max = max(l_lst)

    for k_point in xrange(n_points):
        if (iarray_part_id is not None) and (int(iarray_part_id.GetTuple(k_point)[0]) > 0):
            rr = 0.
            cc = 0.
            ll = 0.
            eRR = [1.,0.,0.]
            eCC = [0.,1.,0.]
            eLL = [0.,0.,1.]

        else:
            point = numpy.array(points.GetPoint(k_point))
            region_id = iarray_regions.GetTuple(k_point)[0]

            if (region_id == 0):
                cell_locator_endLV.FindClosestPoint(
                    point,
                    closest_point_endLV,
                    generic_cell,
                    cellId_endLV,
                    subId,
                    dist_endLV)
                cell_locator_epi.FindClosestPoint(
                    point,
                    closest_point_epi,
                    generic_cell,
                    cellId_epi,
                    subId,
                    dist_epi)

                rr = dist_endLV/(dist_endLV+dist_epi)

                c = farray_c.GetTuple(k_point)[0]
                c = (((c-c_avg_FWLV+math.pi)%(2*math.pi))-math.pi+c_avg_FWLV)
                cc = (c-c_min_FWLV) / (c_max_FWLV-c_min_FWLV)

                l = farray_l.GetTuple(k_point)[0]
                ll = (l-l_min) / (l_max-l_min)

                normal_endLV = numpy.reshape(pdata_endLV.GetCellData().GetNormals().GetTuple(cellId_endLV), (3))
                normal_epi = numpy.reshape(pdata_epi.GetCellData().GetNormals().GetTuple(cellId_epi), (3))
                eRR  = (1.-rr) * normal_endLV + rr * normal_epi
                eRR /= numpy.linalg.norm(eRR)

                eL = numpy.reshape(farray_eL.GetTuple(k_point), (3))
                eCC  = numpy.cross(eL, eRR)
                eCC /= numpy.linalg.norm(eCC)

                eLL  = numpy.cross(eRR, eCC)
            elif (region_id == 1):
                cell_locator_endLV.FindClosestPoint(
                    point,
                    closest_point_endLV,
                    generic_cell,
                    cellId_endLV,
                    subId,
                    dist_endLV)
                cell_locator_endRV.FindClosestPoint(
                    point,
                    closest_point_endRV,
                    generic_cell,
                    cellId_endRV,
                    subId,
                    dist_endRV)

                rr = dist_endLV/(dist_endLV+dist_endRV)

                c = farray_c.GetTuple(k_point)[0]
                c = (((c-c_avg_S+math.pi)%(2*math.pi))-math.pi+c_avg_S)
                cc = (c-c_min_S) / (c_max_S-c_min_S)

                l = farray_l.GetTuple(k_point)[0]
                ll = (l-l_min) / (l_max-l_min)

                normal_endLV = numpy.reshape(pdata_endLV.GetCellData().GetNormals().GetTuple(cellId_endLV), (3))
                normal_endRV = numpy.reshape(pdata_endRV.GetCellData().GetNormals().GetTuple(cellId_endRV), (3))
                eRR  = (1.-rr) * normal_endLV - rr * normal_endRV
                eRR /= numpy.linalg.norm(eRR)

                eL = numpy.reshape(farray_eL.GetTuple(k_point), (3))
                eCC  = numpy.cross(eL, eRR)
                eCC /= numpy.linalg.norm(eCC)

                eLL = numpy.cross(eRR, eCC)
            if (region_id == 2):
                cell_locator_endRV.FindClosestPoint(
                    point,
                    closest_point_endRV,
                    generic_cell,
                    cellId_endRV,
                    subId,
                    dist_endRV)
                cell_locator_epi.FindClosestPoint(
                    point,
                    closest_point_epi,
                    generic_cell,
                    cellId_epi,
                    subId,
                    dist_epi)

                rr = dist_endRV/(dist_endRV+dist_epi)

                c = farray_c.GetTuple(k_point)[0]
                c = (((c-c_avg_FWRV+math.pi)%(2*math.pi))-math.pi+c_avg_FWRV)
                cc = (c-c_min_FWRV) / (c_max_FWRV-c_min_FWRV)

                l = farray_l.GetTuple(k_point)[0]
                ll = (l-l_min) / (l_max-l_min)

                normal_endRV = numpy.reshape(pdata_endRV.GetCellData().GetNormals().GetTuple(cellId_endRV), (3))
                normal_epi = numpy.reshape(pdata_epi.GetCellData().GetNormals().GetTuple(cellId_epi), (3))
                eRR  = (1.-rr) * normal_endRV + rr * normal_epi
                eRR /= numpy.linalg.norm(eRR)

                eL = numpy.reshape(farray_eL.GetTuple(k_point), (3))
                eCC  = numpy.cross(eL, eRR)
                eCC /= numpy.linalg.norm(eCC)

                eLL = numpy.cross(eRR, eCC)

        farray_rr.InsertTuple(k_point, [rr])
        farray_cc.InsertTuple(k_point, [cc])
        farray_ll.InsertTuple(k_point, [ll])
        farray_eRR.InsertTuple(k_point, eRR)
        farray_eCC.InsertTuple(k_point, eCC)
        farray_eLL.InsertTuple(k_point, eLL)

    return (farray_rr,
            farray_cc,
            farray_ll,
            farray_eRR,
            farray_eCC,
            farray_eLL)
def computeHelixTransverseSheetAngles2(
        farray_eRR,
        farray_eCC,
        farray_eLL,
        farray_eF,
        farray_eS,
        farray_eN,
        use_new_definition=False,
        ref_vectors_are_material_basis=False,
        verbose=1):

    myVTK.myPrint(verbose, "*** computeHelixTransverseSheetAngles2 ***")

    n_tuples = farray_eRR.GetNumberOfTuples()
    assert (farray_eCC.GetNumberOfTuples() == n_tuples)
    assert (farray_eLL.GetNumberOfTuples() == n_tuples)
    assert (farray_eF.GetNumberOfTuples() == n_tuples)
    assert (farray_eS.GetNumberOfTuples() == n_tuples)
    assert (farray_eN.GetNumberOfTuples() == n_tuples)

    farray_angle_helix = myVTK.createFloatArray("angle_helix", 1, n_tuples)
    farray_angle_trans = myVTK.createFloatArray("angle_trans", 1, n_tuples)
    farray_angle_sheet = myVTK.createFloatArray("angle_sheet", 1, n_tuples)

    for k_tuple in xrange(n_tuples):
        #print "k_tuple = " + str(k_tuple)

        eRR = numpy.array(farray_eRR.GetTuple(k_tuple))
        eCC = numpy.array(farray_eCC.GetTuple(k_tuple))
        eLL = numpy.array(farray_eLL.GetTuple(k_tuple))
        eF  = numpy.array(farray_eF.GetTuple(k_tuple))
        eS  = numpy.array(farray_eS.GetTuple(k_tuple))
        eN  = numpy.array(farray_eN.GetTuple(k_tuple))

        #print "eRR = " + str(eRR)
        #print "eCC = " + str(eCC)
        #print "eLL = " + str(eLL)
        #print "eF = " + str(eF)
        #print "eS = " + str(eS)
        #print "eN = " + str(eN)

        #print "|eRR| = " + str(numpy.linalg.norm(eRR))
        #print "|eCC| = " + str(numpy.linalg.norm(eCC))
        #print "|eLL| = " + str(numpy.linalg.norm(eLL))

        #print "eRR.eCC = " + str(numpy.dot(eRR, eCC))
        #print "eCC.eLL = " + str(numpy.dot(eCC, eLL))
        #print "eLL.eRR = " + str(numpy.dot(eLL, eRR))

        #print "|eF| = " + str(numpy.linalg.norm(eF))
        #print "|eS| = " + str(numpy.linalg.norm(eS))
        #print "|eN| = " + str(numpy.linalg.norm(eN))

        #print "eF.eS = " + str(numpy.dot(eF, eS))
        #print "eS.eN = " + str(numpy.dot(eS, eN))
        #print "eN.eF = " + str(numpy.dot(eN, eF))

        assert (round(numpy.linalg.norm(eRR),1) == 1.0),\
            "|eRR| = " + str(numpy.linalg.norm(eRR)) + " ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eCC),1) == 1.0),\
            "|eCC| = " + str(numpy.linalg.norm(eCC)) + " ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eLL),1) == 1.0),\
            "|eLL| = " + str(numpy.linalg.norm(eLL)) + " ≠ 1. Aborting."

        assert (round(numpy.dot(eRR,eCC),1) == 0.0),\
            "eRR.eCC = " + str(numpy.dot(eRR,eCC)) + " ≠ 0. Aborting."
        assert (round(numpy.dot(eCC,eLL),1) == 0.0),\
            "eCC.eLL = " + str(numpy.dot(eCC,eLL)) + " ≠ 0. Aborting."
        assert (round(numpy.dot(eLL,eRR),1) == 0.0),\
            "eLL.eRR = " + str(numpy.dot(eLL,eRR)) + " ≠ 0. Aborting."

        assert (round(numpy.linalg.det([eRR, eCC, eLL]),1) == 1.0),\
            "det([eRR, eCC, eLL]) = " + str(numpy.linalg.det([eRR, eCC, eLL])) + " ≠ 1. Aborting."

        assert (round(numpy.linalg.norm(eF),1) == 1.0),\
            "|eF| = " + str(numpy.linalg.norm(eF)) + " ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eS),1) == 1.0),\
            "|eS| = " + str(numpy.linalg.norm(eS)) + " ≠ 1. Aborting."
        assert (round(numpy.linalg.norm(eN),1) == 1.0),\
            "|eN| = " + str(numpy.linalg.norm(eN)) + " ≠ 1. Aborting."

        assert (round(numpy.dot(eF,eS),1) == 0.0),\
            "eF.eS = " + str(numpy.dot(eF,eS)) + " ≠ 0. Aborting."
        assert (round(numpy.dot(eS,eN),1) == 0.0),\
            "eS.eN = " + str(numpy.dot(eS,eN)) + " ≠ 0. Aborting."
        assert (round(numpy.dot(eN,eF),1) == 0.0),\
            "eN.eF = " + str(numpy.dot(eN,eF)) + " ≠ 0. Aborting."

        assert (round(numpy.linalg.det([eF, eS, eN]),1) == 1.0),\
            "det([eF, eS, eN]) = " + str(numpy.linalg.det([eF, eS, eN])) + " ≠ 1. Aborting."

        # reference basis
        if (ref_vectors_are_material_basis):
            ref = numpy.array([+eRR, +eCC, +eLL])
        else:
            if (use_new_definition):
                ref = numpy.array([+eCC, +eLL, +eRR])
            else:
                ref = numpy.array([+eCC, +eRR, -eLL])

        # material basis
        if (abs(numpy.dot(eF, ref[0])) > 1e-3):
            eF = math.copysign(1., numpy.dot(eF, ref[0])) * eF
        if (abs(numpy.dot(eS, ref[1])) > 1e-3):
            eS = math.copysign(1., numpy.dot(eS, ref[1])) * eS
        eN = numpy.cross(eF, eS)
        base = numpy.array([eF, eS, eN])

        assert (round(numpy.linalg.det(base),1) == 1.0),\
            "det(base) = " + str(numpy.linalg.det(base)) + " ≠ 1. Aborting."

        #print "b0.r0 = " + str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = " + str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = " + str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = " + str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = " + str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = " + str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = " + str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = " + str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = " + str(numpy.dot(base[2], ref[2]))

        if (use_new_definition):
            sheet = math.atan2(numpy.dot(base[1], ref[2]), numpy.dot(base[2], ref[2]))
            #print "sheet = " + str(sheet) + " = " + str(sheet*180/math.pi)
            #sheet = (sheet+math.pi/2)%math.pi - math.pi/2
            #print "sheet = " + str(sheet) + " = " + str(sheet*180/math.pi)
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(numpy.transpose(R_sheet), base)
            #print base
            if (numpy.dot(base[1], ref[1]) < 0):
                R_sheet = numpy.array([[1,  0,  0],\
                                       [0, -1,  0],\
                                       [0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_sheet), base)
        else:
            sheet = math.atan2(-numpy.dot(base[2], ref[1]), numpy.dot(base[1], ref[1]))
            #print "sheet = " + str(sheet) + " = " + str(sheet*180/math.pi)
            #sheet = (sheet+math.pi/2)%math.pi - math.pi/2
            #print "sheet = " + str(sheet) + " = " + str(sheet*180/math.pi)
            C = math.cos(sheet)
            S = math.sin(sheet)
            R_sheet = numpy.array([[1,  0, 0],\
                                   [0,  C, S],\
                                   [0, -S, C]])
            base = numpy.dot(numpy.transpose(R_sheet), base)
            #print base
            if (numpy.dot(base[2], ref[2]) < 0):
                R_sheet = numpy.array([[1,  0,  0],\
                                       [0, -1,  0],\
                                       [0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_sheet), base)

        #print "b0.r0 = " + str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = " + str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = " + str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = " + str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = " + str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = " + str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = " + str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = " + str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = " + str(numpy.dot(base[2], ref[2]))

        if (use_new_definition):
            trans = math.atan2(numpy.dot(base[2], ref[0]), numpy.dot(base[0], ref[0]))
            #print "trans = " + str(trans) + " = " + str(trans*180/math.pi)
            #assert (math.atan2(numpy.dot(base[2], ref[1]), numpy.dot(base[0], ref[1])) == trans),\
                #"atan2(b2 . r1, b0 . r1) = " + str(math.atan2(numpy.dot(base[2], ref[1]), numpy.dot(base[0], ref[1]))) + " ≠ trans. Aborting."
            #assert (math.atan2(-numpy.dot(base[0], ref[2]), numpy.dot(base[2], ref[2])) == trans),\
                #"atan2(-b0 . r2, b2 . r2) = " + str(math.atan2(-numpy.dot(base[0], ref[2]), numpy.dot(base[2], ref[2]))) + " ≠ trans. Aborting."
            #trans = (trans+math.pi/2)%math.pi - math.pi/2
            #print "trans = " + str(trans) + " = " + str(trans*180/math.pi)
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(numpy.transpose(R_trans), base)
            #print base
            if (numpy.dot(base[2], ref[2]) < 0):
                R_trans = numpy.array([[-1,  0,  0],\
                                       [ 0,  1,  0],\
                                       [ 0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_trans), base)
        else:
            trans = math.atan2(-numpy.dot(base[1], ref[0]), numpy.dot(base[0], ref[0]))
            #print "trans = " + str(trans) + " = " + str(trans*180/math.pi)
            #assert (math.atan2(-numpy.dot(base[1], ref[2]), numpy.dot(base[0], ref[2])) == trans),\
                #"atan2(b1 . r2, b0 . r2) = " + str(math.atan2(numpy.dot(base[1], ref[2]), numpy.dot(base[0], ref[2]))) + " ≠ trans. Aborting."
            #assert (-math.atan2(-numpy.dot(base[0], ref[1]), numpy.dot(base[1], ref[1])) == trans),\
                #"atan2(-b0 . r1, b1 . r1) = " + str(math.atan2(-numpy.dot(base[0], ref[1]), numpy.dot(base[1], ref[1]))) + " ≠ trans. Aborting."
            #trans = (trans+math.pi/2)%math.pi - math.pi/2
            #print "trans = " + str(trans) + " = " + str(trans*180/math.pi)
            C = math.cos(trans)
            S = math.sin(trans)
            R_trans = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(numpy.transpose(R_trans), base)
            #print base
            if (numpy.dot(base[1], ref[1]) < 0):
                R_trans = numpy.array([[-1,  0,  0],\
                                       [ 0, -1,  0],\
                                       [ 0,  0,  1]])
                base = numpy.dot(numpy.transpose(R_trans), base)

        #print "b0.r0 = " + str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = " + str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = " + str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = " + str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = " + str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = " + str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = " + str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = " + str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = " + str(numpy.dot(base[2], ref[2]))

        if (use_new_definition):
            helix = math.atan2(numpy.dot(base[0], ref[1]), numpy.dot(base[1], ref[1]))
            #print "helix = " + str(helix) + " = " + str(helix*180/math.pi)
            #assert (numpy.isclose(math.atan2(-numpy.dot(base[1], ref[0]), numpy.dot(base[0], ref[0])), helix, atol=1e-3)),\
                #"atan2(-b1 . r0, b0 . r0) = " + str(math.atan2(-numpy.dot(base[1], ref[0]), numpy.dot(base[0], ref[0]))) + " ≠ helix. Aborting."
            #helix = (helix+math.pi/2)%math.pi - math.pi/2
            #print "helix = " + str(helix) + " = " + str(helix*180/math.pi)
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, S, 0],\
                                   [-S, C, 0],\
                                   [ 0, 0, 1]])
            base = numpy.dot(numpy.transpose(R_helix), base)
            #print base
            if (numpy.dot(base[0], ref[0]) < 0):
                R_helix = numpy.array([[-1,  0,  0],\
                                       [ 0, -1,  0],\
                                       [ 0,  0,  1]])
                base = numpy.dot(numpy.transpose(R_helix), base)
        else:
            helix = math.atan2(-numpy.dot(base[0], ref[2]), numpy.dot(base[2], ref[2]))
            #print "helix = " + str(helix) + " = " + str(helix*180/math.pi)
            #assert (numpy.isclose(math.atan2(numpy.dot(base[2], ref[0]), numpy.dot(base[0], ref[0])), helix, atol=1e-3)),\
                #"atan2(-b2 . r0, b0 . r0) = " + str(math.atan2(-numpy.dot(base[2], ref[0]), numpy.dot(base[0], ref[0]))) + " ≠ helix. Aborting."
            #helix = (helix+math.pi/2)%math.pi - math.pi/2
            #print "helix = " + str(helix) + " = " + str(helix*180/math.pi)
            C = math.cos(helix)
            S = math.sin(helix)
            R_helix = numpy.array([[ C, 0,-S],\
                                   [ 0, 1, 0],\
                                   [ S, 0, C]])
            base = numpy.dot(numpy.transpose(R_helix), base)
            #print base
            if (numpy.dot(base[0], ref[0]) < 0):
                R_helix = numpy.array([[-1,  0,  0],\
                                       [ 0,  1,  0],\
                                       [ 0,  0, -1]])
                base = numpy.dot(numpy.transpose(R_helix), base)

        #print "b0.r0 = " + str(numpy.dot(base[0], ref[0]))
        #print "b0.r1 = " + str(numpy.dot(base[0], ref[1]))
        #print "b0.r2 = " + str(numpy.dot(base[0], ref[2]))
        #print "b1.r0 = " + str(numpy.dot(base[1], ref[0]))
        #print "b1.r1 = " + str(numpy.dot(base[1], ref[1]))
        #print "b1.r2 = " + str(numpy.dot(base[1], ref[2]))
        #print "b2.r0 = " + str(numpy.dot(base[2], ref[0]))
        #print "b2.r1 = " + str(numpy.dot(base[2], ref[1]))
        #print "b2.r2 = " + str(numpy.dot(base[2], ref[2]))

        assert (round(numpy.dot(base[0],ref[0]),1) == 1.0),\
            "b0.r0 = " + str(numpy.dot(base[0],ref[0])) + " ≠ 1. Aborting."
        assert (round(numpy.dot(base[1],ref[1]),1) == 1.0),\
            "b1.r1 = " + str(numpy.dot(base[1],ref[1])) + " ≠ 1. Aborting."
        assert (round(numpy.dot(base[2],ref[2]),1) == 1.0),\
            "b2.r2 = " + str(numpy.dot(base[2],ref[2])) + " ≠ 1. Aborting."

        helix = (helix+math.pi/2)%math.pi - math.pi/2
        trans = (trans+math.pi/2)%math.pi - math.pi/2
        sheet = (sheet+math.pi/2)%math.pi - math.pi/2

        helix *= 180/math.pi
        trans *= 180/math.pi
        sheet *= 180/math.pi

        farray_angle_helix.InsertTuple(k_tuple, [helix])
        farray_angle_trans.InsertTuple(k_tuple, [trans])
        farray_angle_sheet.InsertTuple(k_tuple, [sheet])

    return (farray_angle_helix,
            farray_angle_trans,
            farray_angle_sheet)
def addStrainsFromDeformationGradients(
        mesh,
        defo_grad_array_name="DeformationGradient",
        strain_array_name="Strain",
        mesh_w_local_basis=None,
        verbose=0):

    mypy.my_print(verbose, "*** addStrainsFromDeformationGradients ***")

    assert (mesh.GetCellData().HasArray(defo_grad_array_name))
    farray_f = mesh.GetCellData().GetArray(defo_grad_array_name)

    n_cells = mesh.GetNumberOfCells()
    if (mesh_w_local_basis is not None):
        farray_strain = myvtk.createFloatArray(name=strain_array_name + "_CAR",
                                               n_components=6,
                                               n_tuples=n_cells)
    else:
        farray_strain = myvtk.createFloatArray(name=strain_array_name,
                                               n_components=6,
                                               n_tuples=n_cells)
    mesh.GetCellData().AddArray(farray_strain)
    I = numpy.eye(3)
    E_vec = numpy.empty(6)
    #e_vec = numpy.empty(6)
    for k_cell in range(n_cells):
        F = numpy.reshape(farray_f.GetTuple(k_cell), (3, 3), order="C")
        C = numpy.dot(numpy.transpose(F), F)
        E = (C - I) / 2
        mypy.mat_sym33_to_vec_col6(E, E_vec)
        farray_strain.SetTuple(k_cell, E_vec)
        #if (add_almansi_strain):
        #Finv = numpy.linalg.inv(F)
        #c = numpy.dot(numpy.transpose(Finv), Finv)
        #e = (I - c)/2
        #mypy.mat_sym33_to_vec_col6(e, e_vec)
        #farray_almansi.SetTuple(k_cell, e_vec)

    if (mesh_w_local_basis is not None):
        if  (mesh_w_local_basis.GetCellData().HasArray("eR"))\
        and (mesh_w_local_basis.GetCellData().HasArray("eC"))\
        and (mesh_w_local_basis.GetCellData().HasArray("eL")):
            farray_strain_cyl = myvtk.rotateMatrixArray(
                old_array=mesh.GetCellData().GetArray(strain_array_name +
                                                      "_CAR"),
                out_vecs=[
                    mesh_w_local_basis.GetCellData().GetArray("eR"),
                    mesh_w_local_basis.GetCellData().GetArray("eC"),
                    mesh_w_local_basis.GetCellData().GetArray("eL")
                ],
                verbose=0)
            farray_strain_cyl.SetName(strain_array_name + "_CYL")
            mesh.GetCellData().AddArray(farray_strain_cyl)

        if  (mesh_w_local_basis.GetCellData().HasArray("eRR"))\
        and (mesh_w_local_basis.GetCellData().HasArray("eCC"))\
        and (mesh_w_local_basis.GetCellData().HasArray("eLL")):
            farray_strain_pps = myvtk.rotateMatrixArray(
                old_array=mesh.GetCellData().GetArray(strain_array_name +
                                                      "_CAR"),
                out_vecs=[
                    mesh_w_local_basis.GetCellData().GetArray("eRR"),
                    mesh_w_local_basis.GetCellData().GetArray("eCC"),
                    mesh_w_local_basis.GetCellData().GetArray("eLL")
                ],
                verbose=0)
            farray_strain_pps.SetName(strain_array_name + "_PPS")
            mesh.GetCellData().AddArray(farray_strain_pps)
def computeCylindricalCoordinatesAndBasis(
        points,
        points_AB,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeCylindricalCoordinatesAndBasis ***")

    assert (points_AB.GetNumberOfPoints() >= 2), "points_AB must have at least two points. Aborting."
    point_A = numpy.empty(3)
    point_B = numpy.empty(3)
    points_AB.GetPoint(                              0, point_A)
    points_AB.GetPoint(points_AB.GetNumberOfPoints()-1, point_B)
    eL  = point_B - point_A
    eL /= numpy.linalg.norm(eL)
    if (verbose >= 2): print "eL =", eL

    point_C = point_A+numpy.array([1.,0.,0.])
    #point_C = numpy.empty(3)
    #points.GetPoint(0, point_C)

    AC  = point_C - point_A
    AD  = numpy.cross(eL, AC)
    AD /= numpy.linalg.norm(AD)
    AC  = numpy.cross(AD, eL)

    n_points = points.GetNumberOfPoints()

    farray_r = myVTK.createFloatArray("r", 1, n_points)
    farray_c = myVTK.createFloatArray("c", 1, n_points)
    farray_l = myVTK.createFloatArray("l", 1, n_points)

    farray_eR = myVTK.createFloatArray("eR", 3, n_points)
    farray_eC = myVTK.createFloatArray("eC", 3, n_points)
    farray_eL = myVTK.createFloatArray("eL", 3, n_points)

    point = numpy.empty(3)
    for k_point in xrange(n_points):
        if (verbose >= 2): print "k_point =", k_point

        points.GetPoint(k_point, point)

        if (verbose >= 2): print "point =", point

        eR  = point - point_A
        eC  = numpy.cross(eL, eR)
        eC /= numpy.linalg.norm(eC)
        eR  = numpy.cross(eC, eL)

        farray_eR.SetTuple(k_point, eR)
        farray_eC.SetTuple(k_point, eC)
        farray_eL.SetTuple(k_point, eL)

        r = numpy.dot(point - point_A, eR)
        farray_r.SetTuple1(k_point, r)

        c  = math.atan2(numpy.dot(eR, AD), numpy.dot(eR, AC))
        c += (c<0.)*(2*math.pi)
        farray_c.SetTuple1(k_point, c)

        l = numpy.dot(point - point_A, eL)
        farray_l.SetTuple1(k_point, l)

    return (farray_r,
            farray_c,
            farray_l,
            farray_eR,
            farray_eC,
            farray_eL)
def computePrincipalDirections(
        field,
        field_storage="vec",
        orient=0,
        farray_eRR=None,
        farray_eCC=None,
        farray_eLL=None,
        verbose=0):

    myVTK.myPrint(verbose, "*** computePrincipalDirections ***")

    if   (field_storage == "vec"):
        assert (field.GetNumberOfComponents() == 6), "Wrong numpber of components ("+str(field.GetNumberOfComponents())+"). Aborting."
    elif (field_storage == "Cmat"):
        assert (field.GetNumberOfComponents() == 9), "Wrong numpber of components ("+str(field.GetNumberOfComponents())+"). Aborting."
    elif (field_storage == "Fmat"):
        assert (field.GetNumberOfComponents() == 9), "Wrong numpber of components ("+str(field.GetNumberOfComponents())+"). Aborting."
    else:
        assert (0), "Wrong storage (field_storage="+str(field_storage)+"). Aborting."

    n_tuples = field.GetNumberOfTuples()

    farray_Lmin = myVTK.createFloatArray('Lmin', 1, n_tuples)
    farray_Lmid = myVTK.createFloatArray('Lmid', 1, n_tuples)
    farray_Lmax = myVTK.createFloatArray('Lmax', 1, n_tuples)

    farray_Vmin = myVTK.createFloatArray('Vmin', 3, n_tuples)
    farray_Vmid = myVTK.createFloatArray('Vmid', 3, n_tuples)
    farray_Vmax = myVTK.createFloatArray('Vmax', 3, n_tuples)

    mat = numpy.empty((3,3))
    if (field_storage == "vec"):
        vec = numpy.empty(6)
    elif (field_storage == "Cmat"):
        vec = numpy.empty(9)
    elif (field_storage == "Fmat"):
        vec = numpy.empty(9)
    if (orient):
        eCC = numpy.empty(3)
        eLL = numpy.empty(3)
    for k_tuple in xrange(n_tuples):
        #print "k_tuple: "+str(k_tuple)
        field.GetTuple(k_tuple, vec)
        if (field_storage == "vec"):
            vec_col6_to_mat_sym33(vec, mat)
        elif (field_storage == "Cmat"):
            cvec9_to_mat33(vec, mat)
        elif (field_storage == "Fmat"):
            fvec9_to_mat33(vec, mat)

        if (numpy.linalg.norm(mat) > 1e-6):
            #if (verbose): print + 'k_tuple =', k_tuple

            vals, vecs = numpy.linalg.eig(mat)
            #if (verbose): print + 'vals =', vals
            #if (verbose): print + 'vecs =', vecs
            #if (verbose): print + 'det =', numpy.linalg.det(vecs)
            idx = vals.argsort()
            vals = vals[idx]
            vecs = vecs[:,idx]
            #if (verbose): print + 'vals =', vals
            #if (verbose): print + 'vecs =', vecs
            #if (verbose): print + 'det =', numpy.linalg.det(vecs)

            mat_Lmin = vals[0]
            mat_Lmid = vals[1]
            mat_Lmax = vals[2]

            mat_Vmax = vecs[:,2]
            mat_Vmid = vecs[:,1]
            if (orient):
                farray_eCC.GetTuple(k_tuple, eCC)
                farray_eLL.GetTuple(k_tuple, eLL)
                mat_Vmax = math.copysign(1, numpy.dot(mat_Vmax, eCC)) * mat_Vmax
                mat_Vmid = math.copysign(1, numpy.dot(mat_Vmid, eLL)) * mat_Vmid
            mat_Vmin = numpy.cross(mat_Vmax, mat_Vmid)
        else:
            mat_Lmin = 0.
            mat_Lmid = 0.
            mat_Lmax = 0.
            mat_Vmin = [0.]*3
            mat_Vmid = [0.]*3
            mat_Vmax = [0.]*3

        farray_Lmin.SetTuple1(k_tuple, mat_Lmin)
        farray_Lmid.SetTuple1(k_tuple, mat_Lmid)
        farray_Lmax.SetTuple1(k_tuple, mat_Lmax)
        farray_Vmin.SetTuple(k_tuple, mat_Vmin)
        farray_Vmid.SetTuple(k_tuple, mat_Vmid)
        farray_Vmax.SetTuple(k_tuple, mat_Vmax)

    return (farray_Lmin,
            farray_Lmid,
            farray_Lmax,
            farray_Vmin,
            farray_Vmid,
            farray_Vmax)