Пример #1
0
def main():

    # Get the path for the mesh to load, either from the program argument if
    # one was given, or a dialog otherwise
    if(len(sys.argv) > 1):
        filename = sys.argv[1]
    else:
        print("ERROR: No file name specified. Proper syntax is 'python testview.py path/to/your/mesh.obj'.")
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer window
    winName = 'meshview -- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)
    meshDisplay.startMainLoop()
Пример #2
0
def main():

    # Get the path for the mesh to load, either from the program argument if
    # one was given, or a dialog otherwise
    if (len(sys.argv) > 1):
        filename = sys.argv[1]
    else:
        print(
            "ERROR: No file name specified. Proper syntax is 'python testview.py path/to/your/mesh.obj'."
        )
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer window
    winName = 'meshview -- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)
    meshDisplay.startMainLoop()
Пример #3
0
def main():

    # Get the path for the mesh to load from the program argument
    if(len(sys.argv) == 3):
        partString = sys.argv[1]
        if partString not in ['part1','part2','part3']:
            print("ERROR part specifier not recognized. Should be one of 'part1', 'part2', or 'part3'")
            exit()
        filename = sys.argv[2]
    else:
        print("ERROR: Incorrect call syntax. Proper syntax is 'python Assignment3.py partN path/to/your/mesh.obj'.")
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer object
    winName = 'DDG Assignment3 ' + partString + '-- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)



    ###################### BEGIN YOUR CODE
    # implement the body of each of these functions

    ############################
    # Part 0: Helper functions #
    ############################
    # Implement a few useful functions that you will want in the remainder of
    # the assignment.

    @property
    @cacheGeometry
    def cotanWeight(self):
        """
        Return the cotangent weight for an edge. Since this gets called on
        an edge, 'self' will be a reference to an edge.

        This will be useful in the problems below.

        Don't forget, everything you implemented for the last homework is now
        available as part of the library (normals, areas, etc). (Moving forward,
        Vertex.normal will mean area-weighted normals, unless otherwise specified)
        """

        return 0.0 # placeholder value


    @property
    @cacheGeometry
    def dualArea(self):
        """
        Return the dual area associated with a vertex. Since this gets called on
        a vertex, 'self' will be a reference to a vertex.

        Recall that the dual area can be defined as 1/3 the area of the surrounding
        faces.
        """

        return 0.0 # placeholder value


    def enumerateVertices(mesh):
        """
        Assign a unique index from 0 to (N-1) to each vertex in the mesh. Should
        return a dictionary containing mappings {vertex ==> index}.

        You will want to use this function in your solutions below.
        """

        return None # placeholder value


    #################################
    # Part 1: Dense Poisson Problem #
    #################################
    # Solve a Poisson problem on the mesh. The primary function here
    # is solvePoissonProblem_dense(), it will get called when you run
    #   python Assignment3.py part1 /path/to/your/mesh.obj
    # and specify density values with the mouse (the press space to solve).
    #
    # Note that this code will be VERY slow on large meshes, because it uses
    # dense matrices.

    def buildLaplaceMatrix_dense(mesh, index):
        """
        Build a Laplace operator for the mesh, with a dense representation

        'index' is a dictionary mapping {vertex ==> index}

        Returns the resulting matrix.
        """

        return None # placeholder value


    def buildMassMatrix_dense(mesh, index):
        """
        Build a mass matrix for the mesh.

        Returns the resulting matrix.
        """

        return None # placeholder value


    def solvePoissonProblem_dense(mesh, densityValues):
        """
        Solve a Poisson problem on the mesh. The results should be stored on the
        vertices in a variable named 'solutionVal'. You will want to make use
        of your buildLaplaceMatrix_dense() function from above.

        densityValues is a dictionary mapping {vertex ==> value} that specifies
        densities. The density is implicitly zero at every vertex not in this
        dictionary.

        When you run this program with 'python Assignment3.py part1 path/to/your/mesh.obj',
        you will get to click on vertices to specify density conditions. See the
        assignment document for more details.
        """

        pass # remove this line once you have implemented the method


    ##################################
    # Part 2: Sparse Poisson Problem #
    ##################################
    # Solve a Poisson problem on the mesh. The primary function here
    # is solvePoissonProblem_sparse(), it will get called when you run
    #   python Assignment3.py part2 /path/to/your/mesh.obj
    # and specify density values with the mouse (the press space to solve).
    #
    # This will be very similar to the previous part. Be sure to see the wiki
    # for notes about the nuances of sparse matrix computation. Now, your code
    # should scale well to larger meshes!

    def buildLaplaceMatrix_sparse(mesh, index):
        """
        Build a laplace operator for the mesh, with a sparse representation.
        This will be nearly identical to the dense method.

        'index' is a dictionary mapping {vertex ==> index}

        Returns the resulting sparse matrix.
        """

        return None # placeholder value

    def buildMassMatrix_sparse(mesh, index):
        """
        Build a sparse mass matrix for the system.

        Returns the resulting sparse matrix.
        """

        return None # placeholder value


    def solvePoissonProblem_sparse(mesh, densityValues):
        """
        Solve a Poisson problem on the mesh, using sparse matrix operations.
        This will be nearly identical to the dense method.
        The results should be stored on the vertices in a variable named 'solutionVal'.

        densityValues is a dictionary mapping {vertex ==> value} that specifies any
        densities. The density is implicitly zero at every vertex not in this dictionary.

        Note: Be sure to look at the notes on the github wiki about sparse matrix
        computation in Python.

        When you run this program with 'python Assignment3.py part2 path/to/your/mesh.obj',
        you will get to click on vertices to specify density conditions. See the
        assignment document for more details.
        """


        pass # remove this line once you have implemented the method


    ###############################
    # Part 3: Mean Curvature Flow #
    ###############################
    # Perform mean curvature flow on the mesh. The primary function here
    # is meanCurvatureFlow(), which will get called when you run
    #   python Assignment3.py part3 /path/to/your/mesh.obj
    # You can adjust the step size with the 'z' and 'x' keys, and press space
    # to perform one step of flow.
    #
    # Of course, you will want to use sparse matrices here, so your code
    # scales well to larger meshes.

    def buildMeanCurvatureFlowOperator(mesh, index, h):
        """
        Construct the (sparse) mean curvature operator matrix for the mesh.
        It might be helpful to use your buildLaplaceMatrix_sparse() and
        buildMassMatrix_sparse() methods from before.

        Returns the resulting matrix.
        """

        return None # placeholder value

    def meanCurvatureFlow(mesh, h):
        """
        Perform mean curvature flow on the mesh. The result of this operation
        is updated positions for the vertices; you should conclude by modifying
        the position variables for the mesh vertices.

        h is the step size for the backwards euler integration.

        When you run this program with 'python Assignment3.py part3 path/to/your/mesh.obj',
        you can press the space bar to perform this operation and z/x to change
        the step size.

        Recall that before you modify the positions of the mesh, you will need
        to set mesh.staticGeometry = False, which disables caching optimizations
        but allows you to modfiy the geometry. After you are done modfiying
        positions, you should set mesh.staticGeometry = True to re-enable these
        optimizations. You should probably have mesh.staticGeometry = True while
        you assemble your operator, or it will be very slow.
        """

        pass # remove this line once you have implemented the method



    ###################### END YOUR CODE

    Edge.cotanWeight = cotanWeight
    Vertex.dualArea = dualArea

    # A pick function for choosing density conditions
    densityValues = dict()
    def pickVertBoundary(vert):
        value = 1.0 if pickVertBoundary.isHigh else -1.0
        print("   Selected vertex at position:" + printVec3(vert.position))
        print("   as a density with value = " + str(value))
        densityValues[vert] = value
        pickVertBoundary.isHigh = not pickVertBoundary.isHigh
    pickVertBoundary.isHigh = True



    # Run in part1 mode
    if partString == 'part1':

        print("\n\n === Executing assignment 2 part 1")
        print("""
        Please click on vertices of the mesh to specify density conditions.
        Alternating clicks will specify high-value (= 1.0) and low-value (= -1.0)
        density conditions. You may select as many density vertices as you want,
        but >= 2 are necessary to yield an interesting solution. When you are done,
        press the space bar to execute your solver and view the results.
        """)

        meshDisplay.pickVertexCallback = pickVertBoundary
        meshDisplay.drawVertices = True

        def executePart1Callback():
            print("\n=== Solving Poisson problem with your dense solver\n")

            # Print and check the density values
            print("Density values:")
            for key in densityValues:
                print("    " + str(key) + " = " + str(densityValues[key]))
            if len(densityValues) < 2:
                print("Aborting solve, not enough density vertices specified")
                return

            # Call the solver
            print("\nSolving problem...")
            t0 = time.time()
            solvePoissonProblem_dense(mesh, densityValues)
            tSolve = time.time() - t0
            print("...solution completed.")
            print("Solution took {:.5f} seconds.".format(tSolve))

            print("Visualizing results...")

            # Error out intelligently if nothing is stored on vert.solutionVal
            for vert in mesh.verts:
                if not hasattr(vert, 'solutionVal'):
                    print("ERROR: At least one vertex does not have the attribute solutionVal defined.")
                    exit()
                if not isinstance(vert.solutionVal, float):
                    print("ERROR: The data stored at vertex.solutionVal is not of type float.")
                    print("   The data has type=" + str(type(vert.solutionVal)))
                    print("   The data looks like vert.solutionVal="+str(vert.solutionVal))
                    exit()

            # Visualize the result
            # meshDisplay.setShapeColorFromScalar("solutionVal", definedOn='vertex', cmapName="seismic", vMinMax=[-1.0,1.0])
            meshDisplay.setShapeColorFromScalar("solutionVal", definedOn='vertex', cmapName="seismic")
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(' ', executePart1Callback, docstring="Solve the Poisson problem and view the results")

        # Start the GUI
        meshDisplay.startMainLoop()




    # Run in part2 mode
    elif partString == 'part2':
        print("\n\n === Executing assignment 2 part 2")
        print("""
        Please click on vertices of the mesh to specify density conditions.
        Alternating clicks will specify high-value (= 1.0) and low-value (= -1.0)
        density conditions. You may select as many density vertices as you want,
        but >= 2 are necessary to yield an interesting solution. When you are done,
        press the space bar to execute your solver and view the results.
        """)

        meshDisplay.pickVertexCallback = pickVertBoundary
        meshDisplay.drawVertices = True

        def executePart2Callback():
            print("\n=== Solving Poisson problem with your sparse solver\n")

            # Print and check the density values
            print("Density values:")
            for key in densityValues:
                print("    " + str(key) + " = " + str(densityValues[key]))
            if len(densityValues) < 2:
                print("Aborting solve, not enough density vertices specified")
                return

            # Call the solver
            print("\nSolving problem...")
            t0 = time.time()
            solvePoissonProblem_sparse(mesh, densityValues)
            tSolve = time.time() - t0
            print("...solution completed.")
            print("Solution took {:.5f} seconds.".format(tSolve))

            print("Visualizing results...")

            # Error out intelligently if nothing is stored on vert.solutionVal
            for vert in mesh.verts:
                if not hasattr(vert, 'solutionVal'):
                    print("ERROR: At least one vertex does not have the attribute solutionVal defined.")
                    exit()
                if not isinstance(vert.solutionVal, float):
                    print("ERROR: The data stored at vertex.solutionVal is not of type float.")
                    print("   The data has type=" + str(type(vert.solutionVal)))
                    print("   The data looks like vert.solutionVal="+str(vert.solutionVal))
                    exit()

            # Visualize the result
            # meshDisplay.setShapeColorFromScalar("solutionVal", definedOn='vertex', cmapName="seismic", vMinMax=[-1.0,1.0])
            meshDisplay.setShapeColorFromScalar("solutionVal", definedOn='vertex', cmapName="seismic")
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(' ', executePart2Callback, docstring="Solve the Poisson problem and view the results")

        # Start the GUI
        meshDisplay.startMainLoop()



    # Run in part3 mode
    elif partString == 'part3':

        print("\n\n === Executing assignment 2 part 3")
        print("""
        Press the space bar to perform one step of mean curvature
        flow smoothing, using your solver. Pressing the 'z' and 'x'
        keys will decrease and increase the step size (h), respectively.
        """)


        stepSize = [0.01]
        def increaseStepsize():
            stepSize[0] += 0.001
            print("Increasing step size. New size h="+str(stepSize[0]))
        def decreaseStepsize():
            stepSize[0] -= 0.001
            print("Decreasing step size. New size h="+str(stepSize[0]))
        meshDisplay.registerKeyCallback('z', decreaseStepsize, docstring="Increase the value of the step size (h) by 0.1")
        meshDisplay.registerKeyCallback('x', increaseStepsize, docstring="Decrease the value of the step size (h) by 0.1")



        def smoothingStep():
            print("\n=== Performing mean curvature smoothing step\n")
            print("  Step size h="+str(stepSize[0]))

            # Call the solver
            print("  Solving problem...")
            t0 = time.time()
            meanCurvatureFlow(mesh, stepSize[0])
            tSolve = time.time() - t0
            print("  ...solution completed.")
            print("  Solution took {:.5f} seconds.".format(tSolve))

            print("Updating display...")
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(' ', smoothingStep, docstring="Perform one step of your mean curvature flow on the mesh")

        # Start the GUI
        meshDisplay.startMainLoop()
Пример #4
0
def main(inputfile, show=False, StaticGeometry=False):

    # Get the path for the mesh to load, either from the program argument if
    # one was given, or a dialog otherwise
    if (len(sys.argv) > 1):
        filename = sys.argv[1]
    elif inputfile is not None:
        filename = inputfile
    else:
        string1 = "ERROR: No file name specified. "
        string2 = "Proper syntax is 'python Assignment2.py path/to/your/mesh.obj'."
        print(string1 + string2)
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename), staticGeometry=StaticGeometry)

    # Create a viewer object
    winName = 'DDG Assignment2 -- ' + os.path.basename(filename)
    if show:
        meshDisplay = MeshDisplay(windowTitle=winName)
        meshDisplay.setMesh(mesh)

    ###################### BEGIN YOUR CODE
    # implement the body of each of these functions

    #
    #
    #    def buildLaplaceMatrix_dense(mesh, index):
    #        """
    #        Build a Laplace operator for the mesh, with a dense representation
    #
    #        'index' is a dictionary mapping {vertex ==> index}
    #
    #        Returns the resulting matrix.
    #        """
    #        #index_map = mesh.enumerateVertices()
    #        index_map = enumerateVertices(mesh)
    #
    #        return Laplacian

    @property
    @cacheGeometry
    def faceArea(self):
        """
        Compute the area of a face. 
        Though not directly requested, this will be
        useful when computing face-area weighted normals below.
        This method gets called on a face, 
        so 'self' is a reference to the
        face at which we will compute the area.
        """

        v = list(self.adjacentVerts())
        a = 0.5 * norm(
            cross(v[1].position - v[0].position,
                  v[2].position - v[0].position))

        return a

    @property
    @cacheGeometry
    def faceNormal(self):
        """
        Compute normal at a face of the mesh. 
        Unlike at vertices, there is one very
        obvious way to do this, since a face 
        uniquely defines a plane.
        This method gets called on a face, 
        so 'self' is a reference to the
        face at which we will compute the normal.
        """

        v = list(self.adjacentVerts())
        n = normalize(
            cross(v[1].position - v[0].position,
                  v[2].position - v[0].position))

        return n

    @property
    @cacheGeometry
    def vertexNormal_EquallyWeighted(self):
        """
        Compute a vertex normal using the 'equally weighted' method.
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        http://brickisland.net/cs177/?p=217
        Perhaps the simplest way to get vertex normals 
        is to just add up the neighboring face normals:
        """

        normalSum = np.array([0.0, 0.0, 0.0])
        for face in self.adjacentFaces():
            normalSum += face.normal
        n = normalize(normalSum)

        #issue:
        # two different tessellations of the same geometry
        #   can produce very different vertex normals

        return n

    @property
    @cacheGeometry
    def vertexNormal_AreaWeighted(self):
        """
        Compute a vertex normal using 
        the 'face area weights' method.
        
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        The area-weighted normal vector for this vertex"""

        normalSum = np.array([0.0, 0.0, 0.0])
        for face in self.adjacentFaces():
            normalSum += face.normal * face.area
        n = normalize(normalSum)
        #print 'computed vertexNormal_AreaWeighted n = ',n

        return n

    @property
    @cacheGeometry
    def vertexNormal_AngleWeighted(self):
        """
        element type : vertex
        
        Compute a vertex normal using the 
        'Tip-Angle Weights' method.
        
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        A simple way to reduce dependence 
        on the tessellation is to weigh face normals 
        by their corresponding tip angles theta, i.e., 
        the interior angles incident on the vertex of interest:
        """
        normalSum = np.array([0.0, 0.0, 0.0])

        for face in self.adjacentFaces():

            vl = list(face.adjacentVerts())
            vl.remove(self)

            v1 = vl[0].position - self.position
            v2 = vl[1].position - self.position

            # norm ->no need for check:
            #  it doesn not matter what the sign is?
            #area = norm(cross(v1, v2))
            ##if area < 0.0000000001*max((norm(v1),norm(v2))):
            #if area <  0.:
            #    area *= -1.

            alpha = np.arctan2(norm(cross(v1, v2)), dot(v1, v2))
            #print v1
            #print v2
            #print alpha
            #print ''

            normalSum += face.normal * alpha
        n = normalize(normalSum)

        return n

    @property
    @cacheGeometry
    def cotan(self):
        """
        element type : halfedge
        
        Compute the cotangent of 
        the angle OPPOSITE this halfedge. 
        This is not directly required, 
        but will be useful 
        when computing the mean curvature
        normals below.
        
        This method gets called 
        on a halfedge, 
        
        so 'self' is a reference to the
        halfedge at which we will compute the cotangent.
        
        https://math.stackexchange.com/questions/2041099/
            angle-between-vectors-given-cross-and-dot-product
            
        see half edge here:
        Users/lukemcculloch/Documents/Coding/Python/
            DifferentialGeometry/course-master/libddg_userguide.pdf
        """

        if self.isReal:

            # Relevant vectors
            A = -self.next.vector
            B = self.next.next.vector

            # Nifty vector equivalent of cot(theta)
            val = np.dot(A, B) / norm(cross(A, B))
            return val

        else:
            return 0.0

    @property
    @cacheGeometry
    def vertex_Laplace(self):
        """
        element type : vertex
        
        Compute a vertex normal 
        using the 'mean curvature' method.
        
        del del phi = 2NH
        
        -picked up negative sign due to 
           cross products pointing into the page?
        
        -no they are normalized.
        
        -picked up a negative sign due to 
        the cotan(s) being defined 
        for pj, instead of pi.
        
        But how did it change anything?
        
        SwissArmyLaplacian.pdf, page 147
        Applying 'L' to a column bector u
        implements the cotan formula
        
        M = [square diagonal]
        """

        hl = list(self.adjacentHalfEdges())
        pi = self.position
        sumj = 0.
        ot = 1. / 3.
        for hlfedge in hl:
            pj = hlfedge.vertex.position
            ct1 = hlfedge.cotan
            ct2 = hlfedge.twin.cotan
            sumj += (ct1 + ct2) * (pj - pi)
        #laplace = .5*sumj

        return normalize(.5 * sumj)

    @property
    @cacheGeometry
    def vertexNormal_MeanCurvature(self):
        """
        element type : vertex
        
        Compute a vertex normal 
        using the 'mean curvature' method.
        
        Be sure to understand 
        the relationship between 
        this method and the
        area gradient method.
        
        aka, http://brickisland.net/cs177/?p=217:
        (the remarkable fact is that the most 
        straightforward discretization of laplacian 
        leads us right back to the cotan formula! I
        n other words, the vertex normals we get from 
        the mean curvature vector are precisely 
        the same as the ones we get from the area gradient.)
        
        p 60 siggraph2013
        del del phi = 2NH
        
        This method gets called 
        on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        
        http://brickisland.net/cs177/?p=309
        For the dual area of a vertex 
        you can simply use one-third 
        the area of the incident faces
        
        
        hl[0].next.next.next is hl[0]
        >>> True
        
        hl[0].twin.twin is hl[0]
        >>> True
        """

        hl = list(self.adjacentHalfEdges())
        #        lenhl = len(hl)
        #
        #        for hlfedge in self.adjacentHalfEdges:
        #            pass.
        pi = self.position
        sumj = 0.
        ot = 1. / 3.
        for hlfedge in hl:
            pj = hlfedge.vertex.position
            #ct1 = hlfedge.next.cotan
            ct2 = hlfedge.cotan
            #ct2 = hlfedge.twin.next.cotan
            ct1 = hlfedge.twin.cotan
            #dual_area = -ot*hlfedge.face.area #wtf
            sumj += (ct2 + ct1) * (pj - pi)  #/dual_area
        laplace = .5 * sumj
        """
        Picked up a sign because?
        
        
        -picked up negative sign due to 
           cross products pointing into the page?
        
        -no they are normalized.
        
        -picked up a negative sign due to 
           the cotan(s) being defined 
           for pj, instead of pi.
        
        But how did it change anything?
        """
        return normalize(laplace)
        #return normalize(laplace*(.5/self.angleDefect))

    @property
    @cacheGeometry
    def vertexNormal_SphereInscribed(self):
        """
        element type : vertex
        
        Compute a vertex normal 
        using the 'inscribed sphere' method.
        
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        normal at a vertex pi
        can be expressed purely in terms of the 
        edge vectors
            ej = pj-pi
        where pj
            are the immediate neighbors
            of pi
        """

        vl = list(self.adjacentVerts())
        lenvl = len(vl)
        vl.append(vl[0])

        #        Ns = Vector3D(0.0,0.0,0.0)
        #        for i in range(lenvl):
        #            v1 = vl[i].position
        #            v2 = vl[i+1].position
        #            e1 = v1 - self.position
        #            e2 = v2 - self.position
        #            Ns += cross(e1,e2)/((norm(e1)**2)*
        #                                 (norm(e2)**2))

        hl = list(self.adjacentHalfEdges())
        lenhl = len(hl)
        hl.append(hl[0])
        Ns = Vector3D(0.0, 0.0, 0.0)
        for i in range(lenhl):
            e1 = hl[i].vector
            e2 = hl[i + 1].vector
            #Ns += cross(e1,e2)/(sum(abs(e1)**2)*
            #                        sum(abs(e2)**2))
            Ns += cross(e1, e2) / ((norm(e1)**2) * (norm(e2)**2))

        return normalize(-Ns)
        #return Vector3D(0.0,0.0,0.0) # placeholder value

    @property
    @cacheGeometry
    def angleDefect(self):
        """
        angleDefect <=> local Gaussian Curvature
        element type : vertex
        
        Compute the angle defect of a vertex, 
        d(v) (see Assignment 1 Exercise 8).
        
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the angle defect.
        """
        """
        el      = list(self.adjacentEdges())
        evpl    = list(self.adjacentEdgeVertexPairs())
        fl      = list(self.adjacentFaces())
        
        vl      = list(self.adjacentVerts())
        
        https://scicomp.stackexchange.com/questions/27689/
                numerically-stable-way-of-computing-angles-between-vectors
        #"""
        hl = list(self.adjacentHalfEdges())
        lenhl = len(hl)
        hl.append(hl[0])

        alpha = 0.
        for i in range(lenhl):
            v1 = hl[i].vector
            v2 = hl[i + 1].vector
            alpha += np.arctan2(norm(cross(v1, v2)), dot(v1, v2))
        #dv = 2.*np.pi - alpha

        return 2. * np.pi - alpha

    def totalGaussianCurvature():
        """
        Compute the total Gaussian curvature 
        in the mesh, 
        meaning the sum of Gaussian
        curvature at each vertex.
        
        Note that you can access 
        the mesh with the 'mesh' variable.
        """
        tot = 0.
        for vel in mesh.verts:
            tot += vel.angleDefect
        return tot

    def gaussianCurvatureFromGaussBonnet():
        """
        Compute the total Gaussian curvature 
        that the mesh should have, given that the
        Gauss-Bonnet theorem holds 
        (see Assignment 1 Exercise 9).
        
        Note that you can access 
        the mesh with the 'mesh' variable. 
        The mesh includes members like 
        'mesh.verts' and 'mesh.faces', which are
        sets of the vertices (resp. faces) in the mesh.
        """
        V = len(mesh.verts)
        E = len(mesh.edges)
        F = len(mesh.faces)
        EulerChar = V - E + F
        return 2. * np.pi * EulerChar

    ###################### END YOUR CODE

    # Set these newly-defined methods
    # as the methods to use in the classes
    Face.normal = faceNormal
    Face.area = faceArea
    Vertex.normal = vertexNormal_AreaWeighted
    Vertex.vertexNormal_EquallyWeighted = vertexNormal_EquallyWeighted
    Vertex.vertexNormal_AreaWeighted = vertexNormal_AreaWeighted
    Vertex.vertexNormal_AngleWeighted = vertexNormal_AngleWeighted
    Vertex.vertexNormal_MeanCurvature = vertexNormal_MeanCurvature
    #
    Vertex.vertex_Laplace = vertex_Laplace
    #
    Vertex.vertexNormal_SphereInscribed = vertexNormal_SphereInscribed
    Vertex.angleDefect = angleDefect
    HalfEdge.cotan = cotan

    if show:
        ## Functions which will be called
        #    by keypresses to visualize these definitions

        def toggleFaceVectors():
            print("\nToggling vertex vector display")
            if toggleFaceVectors.val:
                toggleFaceVectors.val = False
                meshDisplay.setVectors(None)
            else:
                toggleFaceVectors.val = True
                meshDisplay.setVectors('normal', vectorDefinedAt='face')
            meshDisplay.generateVectorData()

        toggleFaceVectors.val = False  # ridiculous Python scoping hack
        meshDisplay.registerKeyCallback(
            '1',
            toggleFaceVectors,
            docstring="Toggle drawing face normal vectors")

        def toggleVertexVectors():
            print("\nToggling vertex vector display")
            if toggleVertexVectors.val:
                toggleVertexVectors.val = False
                meshDisplay.setVectors(None)
            else:
                toggleVertexVectors.val = True
                meshDisplay.setVectors('normal', vectorDefinedAt='vertex')
            meshDisplay.generateVectorData()

        toggleVertexVectors.val = False  # ridiculous Python scoping hack
        meshDisplay.registerKeyCallback(
            '2',
            toggleVertexVectors,
            docstring="Toggle drawing vertex normal vectors")

        def toggleDefect():
            print("\nToggling angle defect display")
            if toggleDefect.val:
                toggleDefect.val = False
                meshDisplay.setShapeColorToDefault()
            else:
                toggleDefect.val = True
                meshDisplay.setShapeColorFromScalar("angleDefect",
                                                    cmapName="seismic")
                # vMinMax=[-pi/8,pi/8])
            meshDisplay.generateFaceData()

        toggleDefect.val = False
        meshDisplay.registerKeyCallback(
            '3',
            toggleDefect,
            docstring="Toggle drawing angle defect coloring")

        def useEquallyWeightedNormals():
            mesh.staticGeometry = False
            print("\nUsing equally-weighted normals")
            Vertex.normal = vertexNormal_EquallyWeighted
            mesh.staticGeometry = True
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            '4',
            useEquallyWeightedNormals,
            docstring="Use equally-weighted normal computation")

        def useAreaWeightedNormals():
            mesh.staticGeometry = False
            print("\nUsing area-weighted normals")
            Vertex.normal = vertexNormal_AreaWeighted
            mesh.staticGeometry = True
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            '5',
            useAreaWeightedNormals,
            docstring="Use area-weighted normal computation")

        def useAngleWeightedNormals():
            mesh.staticGeometry = False
            print("\nUsing angle-weighted normals")
            Vertex.normal = vertexNormal_AngleWeighted
            mesh.staticGeometry = True
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            '6',
            useAngleWeightedNormals,
            docstring="Use angle-weighted normal computation")

        def useMeanCurvatureNormals():
            mesh.staticGeometry = False
            print("\nUsing mean curvature normals")
            Vertex.normal = vertexNormal_MeanCurvature
            mesh.staticGeometry = True
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            '7',
            useMeanCurvatureNormals,
            docstring="Use mean curvature normal computation")

        def useSphereInscribedNormals():
            mesh.staticGeometry = False
            print("\nUsing sphere-inscribed normals")
            Vertex.normal = vertexNormal_SphereInscribed
            mesh.staticGeometry = True
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            '8',
            useSphereInscribedNormals,
            docstring="Use sphere-inscribed normal computation")

        def computeDiscreteGaussBonnet():
            print("\nComputing total curvature:")
            computed = totalGaussianCurvature()
            predicted = gaussianCurvatureFromGaussBonnet()
            print("   Total computed curvature: " + str(computed))
            print("   Predicted value from Gauss-Bonnet is: " + str(predicted))
            print("   Error is: " + str(abs(computed - predicted)))

        meshDisplay.registerKeyCallback('z',
                                        computeDiscreteGaussBonnet,
                                        docstring="Compute total curvature")

        def deformShape():
            print("\nDeforming shape")
            mesh.staticGeometry = False

            # Get the center and scale of the shape
            center = meshDisplay.dataCenter
            scale = meshDisplay.scaleFactor

            # Rotate according to swirly function
            ax = eu.Vector3(-1.0, .75, 0.5)
            for v in mesh.verts:
                vec = v.position - center
                theta = 0.8 * norm(vec) / scale
                newVec = np.array(eu.Vector3(*vec).rotate_around(ax, theta))
                v.position = center + newVec

            mesh.staticGeometry = True
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            'x',
            deformShape,
            docstring="Apply a swirly deformation to the shape")

        ## Register pick functions that output useful information on click
        def pickVert(vert):
            print("   Position:" + printVec3(vert.position))
            print("   Angle defect: {:.5f}".format(vert.angleDefect))
            print("   Normal (equally weighted): " +
                  printVec3(vert.vertexNormal_EquallyWeighted))
            print("   Normal (area weighted):    " +
                  printVec3(vert.vertexNormal_AreaWeighted))
            print("   Normal (angle weighted):   " +
                  printVec3(vert.vertexNormal_AngleWeighted))
            print("   Normal (sphere-inscribed): " +
                  printVec3(vert.vertexNormal_SphereInscribed))
            print("   Normal (mean curvature):   " +
                  printVec3(vert.vertexNormal_MeanCurvature))

        meshDisplay.pickVertexCallback = pickVert

        def pickFace(face):
            print("   Face area: {:.5f}".format(face.area))
            print("   Normal: " + printVec3(face.normal))
            print("   Vertex positions: ")
            for (i, vert) in enumerate(face.adjacentVerts()):
                print("     v{}: {}".format((i + 1), printVec3(vert.position)))

        meshDisplay.pickFaceCallback = pickFace

    # Start the viewer running
    if show:
        meshDisplay.startMainLoop()

    return mesh
Пример #5
0
def main():

    # Get the path for the mesh to load from the program argument
    if (len(sys.argv) == 3 and sys.argv[1] == 'simple'):
        filename = sys.argv[2]
        simpleTest = True
    elif (len(sys.argv) == 3 and sys.argv[1] == 'fancy'):
        filename = sys.argv[2]
        simpleTest = False
    else:
        print(
            "ERROR: Incorrect call syntax. Proper syntax is 'python Assignment5.py MODE path/to/your/mesh.obj', where MODE is either 'simple' or 'fancy'"
        )
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer object
    winName = 'DDG Assignment5 -- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)

    ###################### BEGIN YOUR CODE

    # DDGSpring216 Assignment 5
    #
    # In this programming assignment you will implement Helmholtz-Hodge decomposition of covectors.
    #
    # The relevant mathematics and algorithm are described in section 8.1 of the course notes.
    # You will also need to implement the core operators in discrete exterior calculus, described mainly in
    # section 3.6 of the course notes.
    #
    # This code can be run with python Assignment5.py MODE /path/to/you/mesh.obj. MODE should be
    # either 'simple' or 'fancy', corresponding to the complexity of the input field omega that is given.
    # It might be easier to debug your algorithm on the simple field first. The assignment code will read in your input
    # mesh, generate a field 'omega' as input, run your algorithm, then display the results.
    # The results can be viewed as streamlines on the surface that flow with the covector field (toggle with 'p'),
    # or, as actual arrows on the faces (toggle with 'l'). The keys '1'-'4' will switch between the input, exact,
    # coexact, and harmonic fields (respectively).
    #
    # A few hints:
    #   - Try performing some basic checks on your operators if things don't seem right. For instance, applying the
    #     exterior derivative twice to anything should always yield zero.
    #   - The streamline visualization is easy to look at, but can be deceiving at times. For instance, streamlines
    #     are not very meaningful where the actual covectors are near 0. Try looking at the actual arrows in that case
    #     ('l').
    #   - Many inputs will not have any harmonic components, especially genus 0 inputs. Don't stress if the harmonic
    #     component of your output is exactly or nearly zero.

    # Implement the body of each of these functions...

    def assignEdgeOrientations(mesh):
        """
        Assign edge orientations to each edge on the mesh.
        
        This method will be called from the assignment code, you do not need to explicitly call it in any of your methods.

        After this method, the following values should be defined:
            - edge.orientedHalfEdge (a reference to one of the halfedges touching that edge)
            - halfedge.orientationSign (1.0 if that halfedge agrees with the orientation of its
                edge, or -1.0 if not). You can use this to make much of your subsequent code cleaner.

        This is a pretty simple method to implement, any choice of orientation is acceptable.
        """

        pass  # remove once you have implemented

    def diagonalInverse(A):
        """
        Returns the inverse of a sparse diagonal matrix. Makes a copy of the matrix.
        
        We will need to invert several diagonal matrices for the algorithm, but scipy does
        not offer a fast method for inverting diagonal matrices, which is a very easy special
        case. As such, this is a useful helper method for you.

        Note that the diagonal inverse is not well-defined if any of the diagonal elements are
        0.0. This needs to be acconuted for when you construct the matrices.
        """

        return None  # placeholder

    @property
    @cacheGeometry
    def circumcentricDualArea(self):
        """
        Compute the area of the circumcentric dual cell for this vertex. Returns a positive scalar.

        This gets called on a vertex, so 'self' will be a reference to the vertex.

        The image on page 78 of the course notes may help you visualize this.
        """

        return 0.0  # placeholder

    Vertex.circumcentricDualArea = circumcentricDualArea

    def buildHodgeStar0Form(mesh, vertexIndex):
        """
        Build a sparse matrix encoding the Hodge operator on 0-forms for this mesh.
        Returns a sparse, diagonal matrix corresponding to vertices.

        The discrete hodge star is a diagonal matrix where each entry is
        the (area of the dual element) / (area of the primal element). You will probably
        want to make use of the Vertex.circumcentricDualArea property you just defined.

        By convention, the area of a vertex is 1.0.
        """

        return None  # placeholder

    def buildHodgeStar1Form(mesh, edgeIndex):
        """
        Build a sparse matrix encoding the Hodge operator on 1-forms for this mesh.
        Returns a sparse, diagonal matrix corresponding to edges.
        
        The discrete hodge star is a diagonal matrix where each entry is
        the (area of the dual element) / (area of the primal element). The solution
        to exercise 26 from the previous homework will be useful here.

        Note that for some geometries, some entries of hodge1 operator may be exactly 0.
        This can create a problem when we go to invert the matrix. To numerically sidestep
        this issue, you probably want to add a small value (like 10^-8) to these diagonal 
        elements to ensure all are nonzero without significantly changing the result.
        """

        return None  # placeholder

    def buildHodgeStar2Form(mesh, faceIndex):
        """
        Build a sparse matrix encoding the Hodge operator on 2-forms for this mesh
        Returns a sparse, diagonal matrix corresponding to faces.

        The discrete hodge star is a diagonal matrix where each entry is
        the (area of the dual element) / (area of the primal element).

        By convention, the area of a vertex is 1.0.
        """

        return None  # placeholder

    def buildExteriorDerivative0Form(mesh, edgeIndex, vertexIndex):
        """
        Build a sparse matrix encoding the exterior derivative on 0-forms.
        Returns a sparse matrix.

        See section 3.6 of the course notes for an explanation of DEC.
        """

        return None  # placeholder

    def buildExteriorDerivative1Form(mesh, faceIndex, edgeIndex):
        """
        Build a sparse matrix encoding the exterior derivative on 1-forms.
        Returns a sparse matrix.
         
        See section 3.6 of the course notes for an explanation of DEC.
        """

        return None  # placeholder

    def decomposeField(mesh):
        """
        Decompose a covector in to exact, coexact, and harmonic components

        The input mesh will have a scalar named 'omega' on its edges (edge.omega)
        representing a discretized 1-form. This method should apply Helmoltz-Hodge 
        decomposition algorithm (as described on page 107-108 of the course notes) 
        to compute the exact, coexact, and harmonic components of omega.

        This method should return its results by storing three new scalars on each edge, 
        as the 3 decomposed components: edge.exactComponent, edge.coexactComponent,
        and edge.harmonicComponent.

        Here are the primary steps you will need to perform for this method:
            
            - Create indexer objects for the vertices, faces, and edges. Note that the mesh
              has handy helper functions pre-defined for each of these: mesh.enumerateEdges() etc.
            
            - Build all of the operators we will need using the methods you implemented above:
              hodge0, hodge1, hodge2, d0, and d1. You should also compute their inverses and
              transposes, as appropriate.

            - Build a vector which represents the input covector (from the edge.omega values)

            - Perform a linear solve for the exact component, as described in the algorithm
            
            - Perform a linear solve for the coexact component, as described in the algorithm

            - Compute the harmonic component as the part which is neither exact nor coexact

            - Store your resulting exact, coexact, and harmonic components on the mesh edges

        This method will be called by the assignment code, you do not need to call it yourself.
        """

        pass  # remove once you have implemented

    ###################### END YOUR CODE

    ### More prep functions
    def generateFieldConstant(mesh):
        print("\n=== Using constant field as arbitrary direction field")
        for vert in mesh.verts:
            vert.vector = vert.projectToTangentSpace(Vector3D(1.4, 0.2, 2.4))

    def generateFieldSimple(mesh):
        for face in mesh.faces:
            face.vector = face.center + Vector3D(
                -face.center[2], face.center[1], face.center[0])
            face.vector = face.projectToTangentSpace(face.vector)

    def gradFromPotential(mesh, potAttr, gradAttr):
        # Simply compute gradient from potential
        for vert in mesh.verts:
            sumVal = Vector3D(0.0, 0.0, 0.0)
            sumWeight = 0.0
            vertVal = getattr(vert, potAttr)
            for he in vert.adjacentHalfEdges():
                sumVal += he.edge.cotanWeight * (getattr(he.vertex, potAttr) -
                                                 vertVal) * he.vector
                sumWeight += he.edge.cotanWeight
            setattr(vert, gradAttr, normalize(sumVal))

    def generateInterestingField(mesh):
        print(
            "\n=== Generating a hopefully-interesting field which has all three types of components\n"
        )

        # Somewhat cheesy hack:
        # We want this function to generate the exact same result on repeated runs of the program to make
        # debugging easier. This means ensuring that calls to random.sample() return the exact same result
        # every time. Normally we could just set a seed for the RNG, and this work work if we were sampling
        # from a list. However, mesh.verts is a set, and Python does not guarantee consistency of iteration
        # order between runs of the program (since the default hash uses the memory address, which certainly
        # changes). Rather than doing something drastic like implementing a custom hash function on the
        # mesh class, we'll just build a separate data structure where vertices are sorted by position,
        # which allows reproducible sampling (as long as positions are distinct).
        sortedVertList = list(mesh.verts)
        sortedVertList.sort(
            key=lambda x: (x.position[0], x.position[1], x.position[2]))
        random.seed(777)

        # Generate curl-free (ish) component
        curlFreePotentialVerts = random.sample(
            sortedVertList, max((2, len(mesh.verts) / 1000)))
        potential = 1.0
        bVals = {}
        for vert in curlFreePotentialVerts:
            bVals[vert] = potential
            potential *= -1
        smoothPotential = solvePoisson(mesh, bVals)
        mesh.applyVertexValue(smoothPotential, "curlFreePotential")
        gradFromPotential(mesh, "curlFreePotential", "curlFreeVecGen")

        # Generate divergence-free (ish) component
        divFreePotentialVerts = random.sample(sortedVertList,
                                              max((2, len(mesh.verts) / 1000)))
        potential = 1.0
        bVals = {}
        for vert in divFreePotentialVerts:
            bVals[vert] = potential
            potential *= -1
        smoothPotential = solvePoisson(mesh, bVals)
        mesh.applyVertexValue(smoothPotential, "divFreePotential")
        gradFromPotential(mesh, "divFreePotential", "divFreeVecGen")
        for vert in mesh.verts:
            normEu = eu.Vector3(*vert.normal)
            vecEu = eu.Vector3(*vert.divFreeVecGen)
            vert.divFreeVecGen = vecEu.rotate_around(
                normEu, pi / 2.0)  # Rotate the field by 90 degrees

        # Combine the components
        for face in mesh.faces:
            face.vector = Vector3D(0.0, 0.0, 0.0)
            for vert in face.adjacentVerts():
                face.vector = 1.0 * vert.curlFreeVecGen + 1.0 * vert.divFreeVecGen

            face.vector = face.projectToTangentSpace(face.vector)

        # clear out leftover attributes to not confuse people
        for vert in mesh.verts:
            del vert.curlFreeVecGen
            del vert.curlFreePotential
            del vert.divFreeVecGen
            del vert.divFreePotential

    # Verify the orientations were defined. Need to do this early, since they are needed for setup
    def checkOrientationDefined(mesh):
        """Verify that edges have oriented halfedges and halfedges have orientation signs"""

        for edge in mesh.edges:
            if not hasattr(edge, 'orientedHalfEdge'):
                print(
                    "ERROR: Edges do not have orientedHalfEdge defined. Cannot proceed"
                )
                exit()
        for he in mesh.halfEdges:
            if not hasattr(he, 'orientationSign'):
                print(
                    "ERROR: halfedges do not have orientationSign defined. Cannot proceed"
                )
                exit()

    # Verify the correct properties are defined after the assignment is run
    def checkResultTypes(mesh):

        for edge in mesh.edges:
            # Check exact
            if not hasattr(edge, 'exactComponent'):
                print(
                    "ERROR: Edges do not have edge.exactComponent defined. Cannot proceed"
                )
                exit()
            if not isinstance(edge.exactComponent, float):
                print(
                    "ERROR: edge.exactComponent is defined, but has the wrong type. Type is "
                    + str(type(edge.exactComponent)) +
                    " when if should be 'float'")
                exit()

            # Check cocoexact
            if not hasattr(edge, 'coexactComponent'):
                print(
                    "ERROR: Edges do not have edge.coexactComponent defined. Cannot proceed"
                )
                exit()
            if not isinstance(edge.coexactComponent, float):
                print(
                    "ERROR: edge.coexactComponent is defined, but has the wrong type. Type is "
                    + str(type(edge.coexactComponent)) +
                    " when if should be 'float'")
                exit()

            # Check harmonic
            if not hasattr(edge, 'harmonicComponent'):
                print(
                    "ERROR: Edges do not have edge.harmonicComponent defined. Cannot proceed"
                )
                exit()
            if not isinstance(edge.harmonicComponent, float):
                print(
                    "ERROR: edge.harmonicComponent is defined, but has the wrong type. Type is "
                    + str(type(edge.harmonicComponent)) +
                    " when if should be 'float'")
                exit()

    # Visualization related
    def covectorToFaceVectorWhitney(mesh, covectorName, vectorName):

        for face in mesh.faces:
            pi = face.anyHalfEdge.vertex.position
            pj = face.anyHalfEdge.next.vertex.position
            pk = face.anyHalfEdge.next.next.vertex.position
            eij = pj - pi
            ejk = pk - pj
            eki = pi - pk
            N = cross(eij, -eki)
            A = 0.5 * norm(N)
            N /= 2 * A
            wi = getattr(face.anyHalfEdge.edge,
                         covectorName) * face.anyHalfEdge.orientationSign
            wj = getattr(face.anyHalfEdge.next.edge,
                         covectorName) * face.anyHalfEdge.next.orientationSign
            wk = getattr(
                face.anyHalfEdge.next.next.edge,
                covectorName) * face.anyHalfEdge.next.next.orientationSign
            # s = (1.0 / (6.0 * A)) * cross(N, wi*(eki-ejk) + wj*(eij-eki) + wk*(ejk-eij))
            s = (1.0 / (6.0 * A)) * cross(
                N,
                wi * (ejk - eij) + wj * (eki - ejk) + wk * (eij - eki))

            setattr(face, vectorName, s)

    def flat(mesh, vectorFieldName, oneFormName):
        """
        Given a vector field defined on faces, compute the corresponding (integrated) 1-form 
        on edges.
        """

        for edge in mesh.edges:

            oe = edge.orientedHalfEdge

            if not oe.isReal:
                val2 = getattr(edge.orientedHalfEdge.twin.face,
                               vectorFieldName)
                meanVal = val2
            elif not oe.twin.isReal:
                val1 = getattr(edge.orientedHalfEdge.face, vectorFieldName)
                meanVal = val1
            else:
                val1 = getattr(edge.orientedHalfEdge.face, vectorFieldName)
                val2 = getattr(edge.orientedHalfEdge.twin.face,
                               vectorFieldName)
                meanVal = 0.5 * (val1 + val2)

            setattr(edge, oneFormName,
                    dot(edge.orientedHalfEdge.vector, meanVal))

    ### Actual main method:

    # get ready
    assignEdgeOrientations(mesh)
    checkOrientationDefined(mesh)

    # Generate a vector field on the surface
    if simpleTest:
        generateFieldSimple(mesh)
    else:
        generateInterestingField(mesh)

    flat(mesh, 'vector', 'omega')

    # Apply the decomposition from this assignment
    print("\n=== Decomposing field in to components")
    decomposeField(mesh)
    print("=== Done decomposing field ===\n\n")

    # Verify everything necessary is defined for the output
    checkResultTypes(mesh)

    # Convert the covectors to face vectors for visualization
    covectorToFaceVectorWhitney(mesh, "exactComponent",
                                "omega_exact_component")
    covectorToFaceVectorWhitney(mesh, "coexactComponent",
                                "omega_coexact_component")
    covectorToFaceVectorWhitney(mesh, "harmonicComponent",
                                "omega_harmonic_component")
    covectorToFaceVectorWhitney(mesh, "omega", "omega_original")

    # Register a vector toggle to switch between the vectors we just defined
    vectorList = [{
        'vectorAttr': 'omega_original',
        'key': '1',
        'colormap': 'Spectral',
        'vectorDefinedAt': 'face'
    }, {
        'vectorAttr': 'omega_exact_component',
        'key': '2',
        'colormap': 'Blues',
        'vectorDefinedAt': 'face'
    }, {
        'vectorAttr': 'omega_coexact_component',
        'key': '3',
        'colormap': 'Reds',
        'vectorDefinedAt': 'face'
    }, {
        'vectorAttr': 'omega_harmonic_component',
        'key': '4',
        'colormap': 'Greens',
        'vectorDefinedAt': 'face'
    }]
    meshDisplay.registerVectorToggleCallbacks(vectorList)

    # Start the GUI
    meshDisplay.startMainLoop()
Пример #6
0
def main():

    # Get the path for the mesh to load from the program argument
    if(len(sys.argv) == 3 and sys.argv[1] == 'simple'):
        filename = sys.argv[2]
        simpleTest = True
    elif(len(sys.argv) == 3 and sys.argv[1] == 'fancy'):
        filename = sys.argv[2]
        simpleTest = False 
    else:
        print("ERROR: Incorrect call syntax. Proper syntax is 'python Assignment5.py MODE path/to/your/mesh.obj', where MODE is either 'simple' or 'fancy'")
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))


    # Create a viewer object
    winName = 'DDG Assignment5 -- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)


    ###################### BEGIN YOUR CODE
    
    # DDGSpring216 Assignment 5
    # 
    # In this programming assignment you will implement Helmholtz-Hodge decomposition of covectors.
    #
    # The relevant mathematics and algorithm are described in section 8.1 of the course notes.
    # You will also need to implement the core operators in discrete exterior calculus, described mainly in 
    # section 3.6 of the course notes.
    #
    # This code can be run with python Assignment5.py MODE /path/to/you/mesh.obj. MODE should be
    # either 'simple' or 'fancy', corresponding to the complexity of the input field omega that is given.
    # It might be easier to debug your algorithm on the simple field first. The assignment code will read in your input 
    # mesh, generate a field 'omega' as input, run your algorithm, then display the results.
    # The results can be viewed as streamlines on the surface that flow with the covector field (toggle with 'p'),
    # or, as actual arrows on the faces (toggle with 'l'). The keys '1'-'4' will switch between the input, exact,
    # coexact, and harmonic fields (respectively).
    # 
    # A few hints:
    #   - Try performing some basic checks on your operators if things don't seem right. For instance, applying the 
    #     exterior derivative twice to anything should always yield zero.
    #   - The streamline visualization is easy to look at, but can be deceiving at times. For instance, streamlines
    #     are not very meaningful where the actual covectors are near 0. Try looking at the actual arrows in that case
    #     ('l').
    #   - Many inputs will not have any harmonic components, especially genus 0 inputs. Don't stress if the harmonic 
    #     component of your output is exactly or nearly zero.
    
    
    # Implement the body of each of these functions...
   
    def assignEdgeOrientations(mesh):
        """
        Assign edge orientations to each edge on the mesh.
        
        This method will be called from the assignment code, you do not need to explicitly call it in any of your methods.

        After this method, the following values should be defined:
            - edge.orientedHalfEdge (a reference to one of the halfedges touching that edge)
            - halfedge.orientationSign (1.0 if that halfedge agrees with the orientation of its
                edge, or -1.0 if not). You can use this to make much of your subsequent code cleaner.

        This is a pretty simple method to implement, any choice of orientation is acceptable.
        """

        pass # remove once you have implemented

    def diagonalInverse(A):
        """
        Returns the inverse of a sparse diagonal matrix. Makes a copy of the matrix.
        
        We will need to invert several diagonal matrices for the algorithm, but scipy does
        not offer a fast method for inverting diagonal matrices, which is a very easy special
        case. As such, this is a useful helper method for you.

        Note that the diagonal inverse is not well-defined if any of the diagonal elements are
        0.0. This needs to be acconuted for when you construct the matrices.
        """

        return None # placeholder
    

    @property
    @cacheGeometry
    def circumcentricDualArea(self):
        """
        Compute the area of the circumcentric dual cell for this vertex. Returns a positive scalar.

        This gets called on a vertex, so 'self' will be a reference to the vertex.

        The image on page 78 of the course notes may help you visualize this.
        """
        
        return 0.0 # placeholder
    Vertex.circumcentricDualArea = circumcentricDualArea


    def buildHodgeStar0Form(mesh, vertexIndex):
        """
        Build a sparse matrix encoding the Hodge operator on 0-forms for this mesh.
        Returns a sparse, diagonal matrix corresponding to vertices.

        The discrete hodge star is a diagonal matrix where each entry is
        the (area of the dual element) / (area of the primal element). You will probably
        want to make use of the Vertex.circumcentricDualArea property you just defined.

        By convention, the area of a vertex is 1.0.
        """
       
        return None # placeholder

    
    def buildHodgeStar1Form(mesh, edgeIndex):
        """
        Build a sparse matrix encoding the Hodge operator on 1-forms for this mesh.
        Returns a sparse, diagonal matrix corresponding to edges.
        
        The discrete hodge star is a diagonal matrix where each entry is
        the (area of the dual element) / (area of the primal element). The solution
        to exercise 26 from the previous homework will be useful here.

        Note that for some geometries, some entries of hodge1 operator may be exactly 0.
        This can create a problem when we go to invert the matrix. To numerically sidestep
        this issue, you probably want to add a small value (like 10^-8) to these diagonal 
        elements to ensure all are nonzero without significantly changing the result.
        """
        
        return None # placeholder
    
    
    def buildHodgeStar2Form(mesh, faceIndex):
        """
        Build a sparse matrix encoding the Hodge operator on 2-forms for this mesh
        Returns a sparse, diagonal matrix corresponding to faces.

        The discrete hodge star is a diagonal matrix where each entry is
        the (area of the dual element) / (area of the primal element).

        By convention, the area of a vertex is 1.0.
        """
        
        return None # placeholder

    
    def buildExteriorDerivative0Form(mesh, edgeIndex, vertexIndex):
        """
        Build a sparse matrix encoding the exterior derivative on 0-forms.
        Returns a sparse matrix.

        See section 3.6 of the course notes for an explanation of DEC.
        """
        
        return None # placeholder
    
    def buildExteriorDerivative1Form(mesh, faceIndex, edgeIndex):
        """
        Build a sparse matrix encoding the exterior derivative on 1-forms.
        Returns a sparse matrix.
         
        See section 3.6 of the course notes for an explanation of DEC.
        """
        
        return None # placeholder

    def decomposeField(mesh):
        """
        Decompose a covector in to exact, coexact, and harmonic components

        The input mesh will have a scalar named 'omega' on its edges (edge.omega)
        representing a discretized 1-form. This method should apply Helmoltz-Hodge 
        decomposition algorithm (as described on page 107-108 of the course notes) 
        to compute the exact, coexact, and harmonic components of omega.

        This method should return its results by storing three new scalars on each edge, 
        as the 3 decomposed components: edge.exactComponent, edge.coexactComponent,
        and edge.harmonicComponent.

        Here are the primary steps you will need to perform for this method:
            
            - Create indexer objects for the vertices, faces, and edges. Note that the mesh
              has handy helper functions pre-defined for each of these: mesh.enumerateEdges() etc.
            
            - Build all of the operators we will need using the methods you implemented above:
              hodge0, hodge1, hodge2, d0, and d1. You should also compute their inverses and
              transposes, as appropriate.

            - Build a vector which represents the input covector (from the edge.omega values)

            - Perform a linear solve for the exact component, as described in the algorithm
            
            - Perform a linear solve for the coexact component, as described in the algorithm

            - Compute the harmonic component as the part which is neither exact nor coexact

            - Store your resulting exact, coexact, and harmonic components on the mesh edges

        This method will be called by the assignment code, you do not need to call it yourself.
        """

        pass # remove once you have implemented


    ###################### END YOUR CODE


    ### More prep functions
    def generateFieldConstant(mesh):
        print("\n=== Using constant field as arbitrary direction field")
        for vert in mesh.verts:
            vert.vector = vert.projectToTangentSpace(Vector3D(1.4, 0.2, 2.4))

    def generateFieldSimple(mesh):
        for face in mesh.faces:
            face.vector = face.center + Vector3D(-face.center[2], face.center[1], face.center[0])
            face.vector = face.projectToTangentSpace(face.vector)

    def gradFromPotential(mesh, potAttr, gradAttr):
        # Simply compute gradient from potential
        for vert in mesh.verts:
            sumVal = Vector3D(0.0,0.0,0.0)
            sumWeight = 0.0
            vertVal = getattr(vert, potAttr)
            for he in vert.adjacentHalfEdges():
                sumVal += he.edge.cotanWeight * (getattr(he.vertex, potAttr) - vertVal) * he.vector
                sumWeight += he.edge.cotanWeight
            setattr(vert, gradAttr, normalize(sumVal))

    def generateInterestingField(mesh):
        print("\n=== Generating a hopefully-interesting field which has all three types of components\n")


        # Somewhat cheesy hack: 
        # We want this function to generate the exact same result on repeated runs of the program to make
        # debugging easier. This means ensuring that calls to random.sample() return the exact same result
        # every time. Normally we could just set a seed for the RNG, and this work work if we were sampling
        # from a list. However, mesh.verts is a set, and Python does not guarantee consistency of iteration
        # order between runs of the program (since the default hash uses the memory address, which certainly
        # changes). Rather than doing something drastic like implementing a custom hash function on the 
        # mesh class, we'll just build a separate data structure where vertices are sorted by position,
        # which allows reproducible sampling (as long as positions are distinct).
        sortedVertList = list(mesh.verts)
        sortedVertList.sort(key= lambda x : (x.position[0], x.position[1], x.position[2]))
        random.seed(777)


        # Generate curl-free (ish) component
        curlFreePotentialVerts = random.sample(sortedVertList, max((2,len(mesh.verts)/1000)))
        potential = 1.0
        bVals = {}
        for vert in curlFreePotentialVerts:
            bVals[vert] = potential
            potential *= -1
        smoothPotential = solvePoisson(mesh, bVals)
        mesh.applyVertexValue(smoothPotential, "curlFreePotential")
        gradFromPotential(mesh, "curlFreePotential", "curlFreeVecGen")


        # Generate divergence-free (ish) component
        divFreePotentialVerts = random.sample(sortedVertList, max((2,len(mesh.verts)/1000)))
        potential = 1.0
        bVals = {}
        for vert in divFreePotentialVerts:
            bVals[vert] = potential
            potential *= -1
        smoothPotential = solvePoisson(mesh, bVals)
        mesh.applyVertexValue(smoothPotential, "divFreePotential")
        gradFromPotential(mesh, "divFreePotential", "divFreeVecGen")
        for vert in mesh.verts:
            normEu = eu.Vector3(*vert.normal)
            vecEu = eu.Vector3(*vert.divFreeVecGen)
            vert.divFreeVecGen = vecEu.rotate_around(normEu, pi / 2.0) # Rotate the field by 90 degrees


        # Combine the components
        for face in mesh.faces:
            face.vector = Vector3D(0.0, 0.0, 0.0)
            for vert in face.adjacentVerts():
                face.vector = 1.0 * vert.curlFreeVecGen + 1.0 * vert.divFreeVecGen
            
            face.vector = face.projectToTangentSpace(face.vector)

        
        # clear out leftover attributes to not confuse people
        for vert in mesh.verts:
            del vert.curlFreeVecGen
            del vert.curlFreePotential
            del vert.divFreeVecGen
            del vert.divFreePotential


    # Verify the orientations were defined. Need to do this early, since they are needed for setup
    def checkOrientationDefined(mesh):
        """Verify that edges have oriented halfedges and halfedges have orientation signs"""
    
        for edge in mesh.edges:
            if not hasattr(edge, 'orientedHalfEdge'):
                print("ERROR: Edges do not have orientedHalfEdge defined. Cannot proceed")
                exit()
        for he in mesh.halfEdges:
            if not hasattr(he, 'orientationSign'):
                print("ERROR: halfedges do not have orientationSign defined. Cannot proceed")
                exit()


    # Verify the correct properties are defined after the assignment is run
    def checkResultTypes(mesh):
        
        for edge in mesh.edges:
            # Check exact
            if not hasattr(edge, 'exactComponent'):
                print("ERROR: Edges do not have edge.exactComponent defined. Cannot proceed")
                exit()
            if not isinstance(edge.exactComponent, float):
                print("ERROR: edge.exactComponent is defined, but has the wrong type. Type is " + str(type(edge.exactComponent)) + " when if should be 'float'")
                exit()
        
            # Check cocoexact
            if not hasattr(edge, 'coexactComponent'):
                print("ERROR: Edges do not have edge.coexactComponent defined. Cannot proceed")
                exit()
            if not isinstance(edge.coexactComponent, float):
                print("ERROR: edge.coexactComponent is defined, but has the wrong type. Type is " + str(type(edge.coexactComponent)) + " when if should be 'float'")
                exit()

            # Check harmonic 
            if not hasattr(edge, 'harmonicComponent'):
                print("ERROR: Edges do not have edge.harmonicComponent defined. Cannot proceed")
                exit()
            if not isinstance(edge.harmonicComponent, float):
                print("ERROR: edge.harmonicComponent is defined, but has the wrong type. Type is " + str(type(edge.harmonicComponent)) + " when if should be 'float'")
                exit()



    # Visualization related
    def covectorToFaceVectorWhitney(mesh, covectorName, vectorName):

        for face in mesh.faces:
            pi = face.anyHalfEdge.vertex.position
            pj = face.anyHalfEdge.next.vertex.position
            pk = face.anyHalfEdge.next.next.vertex.position
            eij = pj - pi
            ejk = pk - pj
            eki = pi - pk
            N = cross(eij, -eki)
            A = 0.5 * norm(N)
            N /= 2*A
            wi = getattr(face.anyHalfEdge.edge, covectorName) * face.anyHalfEdge.orientationSign
            wj = getattr(face.anyHalfEdge.next.edge, covectorName) * face.anyHalfEdge.next.orientationSign
            wk = getattr(face.anyHalfEdge.next.next.edge, covectorName) * face.anyHalfEdge.next.next.orientationSign
            # s = (1.0 / (6.0 * A)) * cross(N, wi*(eki-ejk) + wj*(eij-eki) + wk*(ejk-eij))
            s = (1.0 / (6.0 * A)) * cross(N, wi*(ejk-eij) + wj*(eki-ejk) + wk*(eij-eki))

            setattr(face, vectorName, s) 

    def flat(mesh, vectorFieldName, oneFormName):
        """
        Given a vector field defined on faces, compute the corresponding (integrated) 1-form 
        on edges.
        """

        for edge in mesh.edges:

            oe = edge.orientedHalfEdge

            if not oe.isReal:
                val2 = getattr(edge.orientedHalfEdge.twin.face, vectorFieldName)
                meanVal = val2
            elif not oe.twin.isReal:
                val1 = getattr(edge.orientedHalfEdge.face, vectorFieldName)
                meanVal = val1
            else:
                val1 = getattr(edge.orientedHalfEdge.face, vectorFieldName)
                val2 = getattr(edge.orientedHalfEdge.twin.face, vectorFieldName)
                meanVal = 0.5 * (val1 + val2)
    
            setattr(edge, oneFormName, dot(edge.orientedHalfEdge.vector, meanVal))


    ### Actual main method:

    # get ready
    assignEdgeOrientations(mesh)
    checkOrientationDefined(mesh)

    # Generate a vector field on the surface
    if simpleTest:
        generateFieldSimple(mesh)
    else:
        generateInterestingField(mesh)
    
    flat(mesh, 'vector', 'omega')

    # Apply the decomposition from this assignment
    print("\n=== Decomposing field in to components")
    decomposeField(mesh) 
    print("=== Done decomposing field ===\n\n")

    # Verify everything necessary is defined for the output
    checkResultTypes(mesh)

    # Convert the covectors to face vectors for visualization
    covectorToFaceVectorWhitney(mesh, "exactComponent", "omega_exact_component")
    covectorToFaceVectorWhitney(mesh, "coexactComponent", "omega_coexact_component")
    covectorToFaceVectorWhitney(mesh, "harmonicComponent", "omega_harmonic_component")
    covectorToFaceVectorWhitney(mesh, "omega", "omega_original")


    # Register a vector toggle to switch between the vectors we just defined
    vectorList = [  {'vectorAttr':'omega_original', 'key':'1', 'colormap':'Spectral', 'vectorDefinedAt':'face'},
                    {'vectorAttr':'omega_exact_component', 'key':'2', 'colormap':'Blues', 'vectorDefinedAt':'face'},
                    {'vectorAttr':'omega_coexact_component', 'key':'3', 'colormap':'Reds', 'vectorDefinedAt':'face'},
                    {'vectorAttr':'omega_harmonic_component', 'key':'4', 'colormap':'Greens', 'vectorDefinedAt':'face'}
                 ]
    meshDisplay.registerVectorToggleCallbacks(vectorList)

    # Start the GUI
    meshDisplay.startMainLoop()
Пример #7
0
def main():

    # Get the path for the mesh to load, either from the program argument if
    # one was given, or a dialog otherwise
    if(len(sys.argv) > 1):
        filename = sys.argv[1]
    else:
        print("ERROR: No file name specified. Proper syntax is 'python Assignment2.py path/to/your/mesh.obj'.")
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer object
    winName = 'DDG Assignment2 -- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName, width=400, height=300)
    meshDisplay.setMesh(mesh)

    ###################### BEGIN YOUR CODE
    # implement the body of each of these functions

    @property
    @cacheGeometry
    def faceArea(self):
        """
        Compute the area of a face. Though not directly requested, this will be
        useful when computing face-area weighted normals below.
        This method gets called on a face, so 'self' is a reference to the
        face at which we will compute the area.
        """
        v = list(self.adjacentVerts())
        a = 0.5 * norm(cross(v[1].position - v[0].position, v[2].position - v[0].position))

        return a

    def faceArea2(self):
        """
        use area vector to compute the polygon area
        """
        sum_areavector = [0.0, 0.0, 0.0]

        verts = list(self.adjacentVerts())
        LEN = len(verts)
        for (i, v) in enumerate(verts):
            sum_areavector += 0.5 * cross(verts[i].position, verts[(i+1)%LEN].position)

        return norm(sum_areavector)

    @property
    @cacheGeometry
    def faceNormal(self):
        """
        Compute normal at a face of the mesh. Unlike at vertices, there is one very
        obvious way to do this, since a face uniquely defines a plane.
        This method gets called on a face, so 'self' is a reference to the
        face at which we will compute the normal.
        """
        v = list(self.adjacentVerts())
        n = normalize(cross(v[1].position - v[0].position, v[2].position - v[0].position))

        return n


    @property
    @cacheGeometry
    def vertexNormal_EquallyWeighted(self):
        """
        Compute a vertex normal using the 'equally weighted' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """
        normalSum = np.array([0.0,0.0,0.0])
        for face in self.adjacentFaces():
            normalSum += face.normal * 1.0
        n = normalize(normalSum)

        return n

    @property
    @cacheGeometry
    def vertexNormal_AreaWeighted(self):
        """
        Compute a vertex normal using the 'face area weights' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """
        normalSum = np.array([0.0,0.0,0.0])
        for face in self.adjacentFaces():
            normalSum += face.normal * face.area
        n = normalize(normalSum)

        return n

    @property
    @cacheGeometry
    def vertexNormal_AngleWeighted(self):
        """
        Compute a vertex normal using the 'tip angle weights' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """
        normalSum = np.array([0.0,0.0,0.0])

        for face in self.adjacentFaces():

            v = list(face.adjacentVerts())

            v0 = v1 = v2 = Vertex()

            if v[0].id == self.id:
               v0 = v[0]; v1 = v[1]; v2 = v[2];
            if v[1].id == self.id:
               v0 = v[1]; v1 = v[2]; v2 = v[0];
            if v[2].id == self.id:
               v0 = v[2]; v1 = v[0]; v2 = v[1];

            a = v1.position - v0.position
            b = v2.position - v0.position

            theta = acos(np.dot((a/norm(a)),(b/norm(b))))

            normalSum += face.normal * theta

        n = normalize(normalSum)
        return n


    #@property
    #@cacheGeometry
    def cotan(self):
        """
        Compute the cotangent of the angle opposite a halfedge. This is not
        directly required, but will be useful when computing the mean curvature
        normals below.
        This method gets called on a halfedge, so 'self' is a reference to the
        halfedge at which we will compute the cotangent.
        """
        if self.next.next.next is not self:
            raise ValueError("ERROR: halfedge.cotan() is only well-defined on a triangle")

        if self.isReal:

            # Relevant vectors
            v0 =  self.next.next.vector
            v1 = -self.next.vector

            # Nifty vector equivalent of cot(theta)
            val = np.dot(v0, v1) / norm(cross(v0, v1))
            return val

        else:
            return 0.0 # placeholder value


    @property
    @cacheGeometry
    def vertexNormal_MeanCurvature(self):
        """
        Compute a vertex normal using the 'mean curvature' method.
        Be sure to understand the relationship between this method and the
        area gradient method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """
        # the vertex normals we get from the mean curvature vector are precisely 
        # the same as the ones we get from the area gradient
        # areaGrad(p_i) = 0.5 * SUM((cot a_j + cot b_j)(p_i - p_j))
        sum_normal = [0.0, 0.0, 0.0]

        halfedges = list(self.adjacentHalfEdges_CounterClockwise())
        for he in halfedges:
            sum_normal += (cotan(he.twin) + cotan(he)) * (-he.vector) # (p_i - p_j) = -he.vector

        n = normalize(0.5 * sum_normal)
        return n

    @property
    @cacheGeometry
    def vertexNormal_SphereInscribed(self):
        """
        Compute a vertex normal using the 'inscribed sphere' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """
        # Ns = 1/c * SUM(e(j) x e(j+1) / (|e(j)|^2 * |e(j+1)|^2))
        sum_normal = [0.0, 0.0, 0.0]

        halfedges = list(self.adjacentHalfEdges_CounterClockwise())
        LEN = len(halfedges)

        for j in range(0, LEN-1): # [0, LEN-1)
            normj  = norm(halfedges[j].vector)
            normj1 = norm(halfedges[j+1].vector)

            sum_normal += cross(halfedges[j].vector, halfedges[j+1].vector) / (normj*normj * normj1*normj1)

        n = normalize(sum_normal)
        return n # But it seems that I should use -n to return the correct normal value



    @property
    @cacheGeometry
    def angleDefect(self):
        """
        Compute the angle defect of a vertex, d(v) (see Assignment 1 Exercise 8).
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the angle defect.
        """
        sum_theta = 0.0
        # acos(np.dot((a/norm(a)),(b/norm(b))))
        for face in self.adjacentFaces():
            
            v = list(face.adjacentVerts())

            v0 = v1 = v2 = Vertex()

            if v[0].id == self.id:
               v0 = v[0]; v1 = v[1]; v2 = v[2];
            if v[1].id == self.id:
               v0 = v[1]; v1 = v[2]; v2 = v[0];
            if v[2].id == self.id:
               v0 = v[2]; v1 = v[0]; v2 = v[1];

            a = v1.position - v0.position
            b = v2.position - v0.position

            theta = acos(np.dot((a/norm(a)),(b/norm(b))))

            sum_theta += theta
	
        return 2.0 * pi - sum_theta


    def totalGaussianCurvature():
        """
        Compute the total Gaussian curvature in the mesh, meaning the sum of Gaussian
        curvature at each vertex.
        Note that you can access the mesh with the 'mesh' variable.
        """
        sum_ = 0.0
        for v in mesh.verts:
            sum_ += v.angleDefect
        return sum_


    def gaussianCurvatureFromGaussBonnet():
        """
        Compute the total Gaussian curvature that the mesh should have, given that the
        Gauss-Bonnet theorem holds (see Assignment 1 Exercise 9).
        Note that you can access the mesh with the 'mesh' variable. The
        mesh includes members like 'mesh.verts' and 'mesh.faces', which are
        sets of the vertices (resp. faces) in the mesh.
        """
        X = len(mesh.verts) - len(mesh.edges) + len(mesh.faces)
        return 2.0 * pi * X


    ###################### END YOUR CODE


    # Set these newly-defined methods as the methods to use in the classes
    Face.normal = faceNormal
    Face.area = faceArea
    Vertex.normal = vertexNormal_AreaWeighted
    Vertex.vertexNormal_EquallyWeighted = vertexNormal_EquallyWeighted
    Vertex.vertexNormal_AreaWeighted = vertexNormal_AreaWeighted
    Vertex.vertexNormal_AngleWeighted = vertexNormal_AngleWeighted
    Vertex.vertexNormal_MeanCurvature = vertexNormal_MeanCurvature
    Vertex.vertexNormal_SphereInscribed = vertexNormal_SphereInscribed
    Vertex.angleDefect = angleDefect
    HalfEdge.cotan = cotan


    ## Functions which will be called by keypresses to visualize these definitions

    def toggleFaceVectors():
        print("\nToggling vertex vector display")
        if toggleFaceVectors.val:
            toggleFaceVectors.val = False
            meshDisplay.setVectors(None)
        else:
            toggleFaceVectors.val = True
            meshDisplay.setVectors('normal', vectorDefinedAt='face')
        meshDisplay.generateVectorData()
    toggleFaceVectors.val = False # ridiculous Python scoping hack
    meshDisplay.registerKeyCallback('1', toggleFaceVectors, docstring="Toggle drawing face normal vectors")


    def toggleVertexVectors():
        print("\nToggling vertex vector display")
        if toggleVertexVectors.val:
            toggleVertexVectors.val = False
            meshDisplay.setVectors(None)
        else:
            toggleVertexVectors.val = True
            meshDisplay.setVectors('normal', vectorDefinedAt='vertex')
        meshDisplay.generateVectorData()
    toggleVertexVectors.val = False # ridiculous Python scoping hack
    meshDisplay.registerKeyCallback('2', toggleVertexVectors, docstring="Toggle drawing vertex normal vectors")


    def toggleDefect():
        print("\nToggling angle defect display")
        if toggleDefect.val:
            toggleDefect.val = False
            meshDisplay.setShapeColorToDefault()
        else:
            toggleDefect.val = True
            meshDisplay.setShapeColorFromScalar("angleDefect", cmapName="seismic",vMinMax=[-pi/8,pi/8])
        meshDisplay.generateFaceData()
    toggleDefect.val = False
    meshDisplay.registerKeyCallback('3', toggleDefect, docstring="Toggle drawing angle defect coloring")


    def useEquallyWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing equally-weighted normals")
        Vertex.normal = vertexNormal_EquallyWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()
    meshDisplay.registerKeyCallback('4', useEquallyWeightedNormals, docstring="Use equally-weighted normal computation")

    def useAreaWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing area-weighted normals")
        Vertex.normal = vertexNormal_AreaWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()
    meshDisplay.registerKeyCallback('5', useAreaWeightedNormals, docstring="Use area-weighted normal computation")

    def useAngleWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing angle-weighted normals")
        Vertex.normal = vertexNormal_AngleWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()
    meshDisplay.registerKeyCallback('6', useAngleWeightedNormals, docstring="Use angle-weighted normal computation")

    def useMeanCurvatureNormals():
        mesh.staticGeometry = False
        print("\nUsing mean curvature normals")
        Vertex.normal = vertexNormal_MeanCurvature
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()
    meshDisplay.registerKeyCallback('7', useMeanCurvatureNormals, docstring="Use mean curvature normal computation")

    def useSphereInscribedNormals():
        mesh.staticGeometry = False
        print("\nUsing sphere-inscribed normals")
        Vertex.normal = vertexNormal_SphereInscribed
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()
    meshDisplay.registerKeyCallback('8', useSphereInscribedNormals, docstring="Use sphere-inscribed normal computation")

    def computeDiscreteGaussBonnet():
        print("\nComputing total curvature:")
        computed = totalGaussianCurvature()
        predicted = gaussianCurvatureFromGaussBonnet()
        print("   Total computed curvature: " + str(computed))
        print("   Predicted value from Gauss-Bonnet is: " + str(predicted))
        print("   Error is: " + str(abs(computed - predicted)))
    meshDisplay.registerKeyCallback('z', computeDiscreteGaussBonnet, docstring="Compute total curvature")

    def deformShape():
        print("\nDeforming shape")
        mesh.staticGeometry = False

        # Get the center and scale of the shape
        center = meshDisplay.dataCenter
        scale = meshDisplay.scaleFactor

        # Rotate according to swirly function
        ax = eu.Vector3(-1.0,.75,0.5)
        for v in mesh.verts:
            vec = v.position - center
            theta = 0.8 * norm(vec) / scale
            newVec = np.array(eu.Vector3(*vec).rotate_around(ax, theta))
            v.position = center + newVec


        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback('x', deformShape, docstring="Apply a swirly deformation to the shape")



    ## Register pick functions that output useful information on click
    def pickVert(vert):
        print("   Position:" + printVec3(vert.position))
        print("   Angle defect: {:.5f}".format(vert.angleDefect))
        print("   Normal (equally weighted): " + printVec3(vert.vertexNormal_EquallyWeighted))
        print("   Normal (area weighted):    " + printVec3(vert.vertexNormal_AreaWeighted))
        print("   Normal (angle weighted):   " + printVec3(vert.vertexNormal_AngleWeighted))
        print("   Normal (sphere-inscribed): " + printVec3(vert.vertexNormal_SphereInscribed))
        print("   Normal (mean curvature):   " + printVec3(vert.vertexNormal_MeanCurvature))
    meshDisplay.pickVertexCallback = pickVert

    def pickFace(face):
        print("   Face area : {:.5f}".format(face.area))
        print("   Face area2: {:.5f}".format(faceArea2(face)))
        print("   Normal: " + printVec3(face.normal))
        print("   Vertex positions: ")
        for (i, vert) in enumerate(face.adjacentVerts()):
            print("     v{}: {}".format((i+1),printVec3(vert.position)))
    meshDisplay.pickFaceCallback = pickFace


    # Start the viewer running
    meshDisplay.startMainLoop()
def main(inputfile, show=False, StaticGeometry=False, partString='part1'):

    # Get the path for the mesh to load from the program argument
    if (len(sys.argv) == 3):
        partString = sys.argv[1]
        if partString not in ['part1', 'part2', 'part3']:
            print(
                "ERROR part specifier not recognized. Should be one of 'part1', 'part2', or 'part3'"
            )
            exit()
        filename = sys.argv[2]
    elif inputfile is not None:
        filename = inputfile
    else:
        print(
            "ERROR: Incorrect call syntax. Proper syntax is 'python Assignment3.py partN path/to/your/mesh.obj'."
        )
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename), staticGeometry=StaticGeometry)

    # Create a viewer object
    winName = 'DDG Assignment3 ' + partString + '-- ' + os.path.basename(
        filename)

    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)

    ###################### BEGIN YOUR CODE
    # implement the body of each of these functions

    ############################
    # assignment 2 code:
    ############################

    @property
    @cacheGeometry
    def faceArea(self):
        """
        Compute the area of a face. 
        Though not directly requested, this will be
        useful when computing face-area weighted normals below.
        This method gets called on a face, 
        so 'self' is a reference to the
        face at which we will compute the area.
        """

        v = list(self.adjacentVerts())
        a = 0.5 * norm(
            cross(v[1].position - v[0].position,
                  v[2].position - v[0].position))

        return a

    @property
    @cacheGeometry
    def vertexNormal_EquallyWeighted(self):
        """
        Compute a vertex normal using the 'equally weighted' method.
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        http://brickisland.net/cs177/?p=217
        Perhaps the simplest way to get vertex normals 
        is to just add up the neighboring face normals:
        """

        normalSum = np.array([0.0, 0.0, 0.0])
        for face in self.adjacentFaces():
            normalSum += face.normal
        n = normalize(normalSum)

        #issue:
        # two different tessellations of the same geometry
        #   can produce very different vertex normals

        return n

    @property
    @cacheGeometry
    def vertexNormal_AreaWeighted(self):
        """
        Compute a vertex normal using 
        the 'face area weights' method.
        
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        The area-weighted normal vector for this vertex"""

        normalSum = np.array([0.0, 0.0, 0.0])
        for face in self.adjacentFaces():
            normalSum += face.normal * face.area
        n = normalize(normalSum)
        #print 'computed vertexNormal_AreaWeighted n = ',n

        return n

    @property
    @cacheGeometry
    def vertexNormal_AngleWeighted(self):
        """
        element type : vertex
        
        Compute a vertex normal using the 
        'Tip-Angle Weights' method.
        
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the normal.
        
        A simple way to reduce dependence 
        on the tessellation is to weigh face normals 
        by their corresponding tip angles theta, i.e., 
        the interior angles incident on the vertex of interest:
        """
        normalSum = np.array([0.0, 0.0, 0.0])

        for face in self.adjacentFaces():

            vl = list(face.adjacentVerts())
            vl.remove(self)

            v1 = vl[0].position - self.position
            v2 = vl[1].position - self.position

            # norm ->no need for check:
            #  it doesn not matter what the sign is?
            #area = norm(cross(v1, v2))
            ##if area < 0.0000000001*max((norm(v1),norm(v2))):
            #if area <  0.:
            #    area *= -1.

            alpha = np.arctan2(norm(cross(v1, v2)), dot(v1, v2))
            #print v1
            #print v2
            #print alpha
            #print ''

            normalSum += face.normal * alpha
        n = normalize(normalSum)

        return n

    @property
    @cacheGeometry
    def faceNormal(self):
        """
        Compute normal at a face of the mesh. 
        Unlike at vertices, there is one very
        obvious way to do this, since a face 
        uniquely defines a plane.
        This method gets called on a face, 
        so 'self' is a reference to the
        face at which we will compute the normal.
        """

        v = list(self.adjacentVerts())
        n = normalize(
            cross(v[1].position - v[0].position,
                  v[2].position - v[0].position))

        return n

    @property
    @cacheGeometry
    def cotan(self):
        """
        element type : halfedge
        
        Compute the cotangent of 
        the angle OPPOSITE this halfedge. 
        This is not directly required, 
        but will be useful 
        when computing the mean curvature
        normals below.
        
        This method gets called 
        on a halfedge, 
        
        so 'self' is a reference to the
        halfedge at which we will compute the cotangent.
        
        https://math.stackexchange.com/questions/2041099/
            angle-between-vectors-given-cross-and-dot-product
            
        see half edge here:
        Users/lukemcculloch/Documents/Coding/Python/
            DifferentialGeometry/course-master/libddg_userguide.pdf
        """
        # Validate that this is on a triangle
        if self.next.next.next is not self:
            raise ValueError(
                "ERROR: halfedge.cotan() is only well-defined on a triangle")

        if self.isReal:

            # Relevant vectors
            A = -self.next.vector
            B = self.next.next.vector

            # Nifty vector equivalent of cot(theta)
            val = np.dot(A, B) / norm(cross(A, B))
            return val

        else:
            return 0.0

    @property
    @cacheGeometry
    def angleDefect(self):
        """
        angleDefect <=> local Gaussian Curvature
        element type : vertex
        
        Compute the angle defect of a vertex, 
        d(v) (see Assignment 1 Exercise 8).
        
        This method gets called on a vertex, 
        so 'self' is a reference to the
        vertex at which we will compute the angle defect.
        """
        """
        el      = list(self.adjacentEdges())
        evpl    = list(self.adjacentEdgeVertexPairs())
        fl      = list(self.adjacentFaces())
        
        vl      = list(self.adjacentVerts())
        
        https://scicomp.stackexchange.com/questions/27689/
                numerically-stable-way-of-computing-angles-between-vectors
        #"""
        hl = list(self.adjacentHalfEdges())
        lenhl = len(hl)
        hl.append(hl[0])

        alpha = 0.
        for i in range(lenhl):
            v1 = hl[i].vector
            v2 = hl[i + 1].vector
            alpha += np.arctan2(norm(cross(v1, v2)), dot(v1, v2))
        #dv = 2.*np.pi - alpha

        return 2. * np.pi - alpha

    def totalGaussianCurvature():
        """
        Compute the total Gaussian curvature 
        in the mesh, 
        meaning the sum of Gaussian
        curvature at each vertex.
        
        Note that you can access 
        the mesh with the 'mesh' variable.
        """
        tot = 0.
        for vel in mesh.verts:
            tot += vel.angleDefect
        return tot

    def gaussianCurvatureFromGaussBonnet():
        """
        Compute the total Gaussian curvature 
        that the mesh should have, given that the
        Gauss-Bonnet theorem holds 
        (see Assignment 1 Exercise 9).
        
        Note that you can access 
        the mesh with the 'mesh' variable. 
        The mesh includes members like 
        'mesh.verts' and 'mesh.faces', which are
        sets of the vertices (resp. faces) in the mesh.
        """
        V = len(mesh.verts)
        E = len(mesh.edges)
        F = len(mesh.faces)
        EulerChar = V - E + F
        return 2. * np.pi * EulerChar

    ############################
    # Part 0: Helper functions #
    ############################
    # Implement a few useful functions that you will want in the remainder of
    # the assignment.

    @property
    @cacheGeometry
    def cotanWeight(self):
        """
        Return the cotangent weight for an edge. Since this gets called on
        an edge, 'self' will be a reference to an edge.

        This will be useful in the problems below.

        Don't forget, everything you implemented for the last homework is now
        available as part of the library (normals, areas, etc). (Moving forward,
        Vertex.normal will mean area-weighted normals, unless otherwise specified)
        """
        val = 0.0
        if self.anyHalfEdge.isReal:
            val += self.anyHalfEdge.cotan
        if self.anyHalfEdge.twin.isReal:
            val += self.anyHalfEdge.twin.cotan
        val *= 0.5
        return val

    @property
    @cacheGeometry
    def vertex_Laplace(self):
        """
        element type : vertex
        
        Compute a vertex normal 
        using the 'mean curvature' method.
        
        del del phi = 2NH
        
        -picked up negative sign due to 
           cross products pointing into the page?
        
        -no they are normalized.
        
        -picked up a negative sign due to 
        the cotan(s) being defined 
        for pj, instead of pi.
        
        But how did it change anything?
        """

        hl = list(self.adjacentHalfEdges())
        pi = self.position
        sumj = 0.
        ot = 1. / 3.
        for hlfedge in hl:
            pj = hlfedge.vertex.position
            ct1 = hlfedge.cotan
            ct2 = hlfedge.twin.cotan
            sumj += (ct1 + ct2) * (pj - pi)
        #laplace = .5*sumj

        return normalize(-.5 * sumj)

    ##
    ##*******************************************************
    ##
    @property
    @cacheGeometry
    def dualArea(self):
        """
        Return the dual area associated with a vertex. 
        Since this gets called on
        a vertex, 'self' will be a 
        reference to a vertex.

        Recall that the dual area can be 
        defined as 1/3 the area of the surrounding
        faces.
        
        http://brickisland.net/DDGFall2017/
        'the barycentric dual area associated 
        with a vertex i is equal to one-third the area
        of all triangles ijk touching i.'
        """
        fl = list(self.adjacentFaces())
        area_star = 0.
        for ff in fl:
            area_star += ff.area / 3.

        return area_star

    def enumerateVertices(mesh):
        """
        Assign a unique index from 0 to (N-1) to each vertex in the mesh. Should
        return a dictionary containing mappings {vertex ==> index}.

        You will want to use this function in your solutions below.
        """
        #        index_map = {}
        #        index = 0
        #        for vv in mesh.verts:
        #            index_map[vv] = index
        #            index += 1
        return mesh.enumerateVertices

    @property
    @cacheGeometry
    def adjacency(self):
        index_map = enumerateVertices(self)
        nrows = ncols = len(mesh.verts)
        adjacency = np.zeros((nrows, ncols), int)
        for vv in mesh.verts:
            ith = index_map[vv]
            avlist = list(vv.adjacentVerts())
            for av in avlist:
                jth = index_map[av]
                adjacency[ith, jth] = 1
        return adjacency

    #################################
    # Part 1: Dense Poisson Problem #
    #################################
    # Solve a Poisson problem on the mesh. The primary function here
    # is solvePoissonProblem_dense(), it will get called when you run
    #   python Assignment3.py part1 /path/to/your/mesh.obj
    # and specify density values with the mouse (the press space to solve).
    #
    # Note that this code will be VERY slow on large meshes, because it uses
    # dense matrices.

    def buildLaplaceMatrix_dense(mesh, index_map=None):
        """
        Build a Laplace operator for the mesh, with a dense representation

        'index' is a dictionary mapping {vertex ==> index}
        TLM renamed to index_map

        Returns the resulting matrix.
        """
        if index_map is None:
            # index_map = mesh.enumerateVertices()
            index_map = enumerateVertices(mesh)

        nrows = ncols = len(mesh.verts)
        adjacency = np.zeros((nrows, ncols), int)
        for vv in mesh.verts:
            ith = index_map[vv]
            avlist = list(vv.adjacentVerts())
            for av in avlist:
                jth = index_map[av]
                adjacency[ith, jth] = 1

        Laplacian = np.zeros((nrows, ncols), float)
        for vi in mesh.verts:
            ith = index_map[vi]
            ll = list(vi.adjacentEdgeVertexPairs())
            for edge, vj in ll:
                jth = index_map[vj]
                #                Laplacian[ith,jth] = np.dot(vj.normal,
                #                                             edge.cotanWeight*(vj.position -
                #                                                       vi.position)
                #                                             )
                if ith == jth:
                    pass  #Laplacian[ith,jth] = edge.cotanWeight
                else:
                    Laplacian[ith, jth] = edge.cotanWeight

            Laplacian[ith, ith] = -sum(Laplacian[ith])

        return Laplacian

    def buildMassMatrix_dense(mesh, index):
        """
        Build a mass matrix for the mesh.

        Returns the resulting matrix.
        """
        nrows = ncols = len(mesh.verts)

        #MassMatrix = np.zeros((nrows),float)
        MassMatrix = np.zeros((nrows, ncols), float)
        for i, vert in enumerate(mesh.verts):
            #MassMatrix[i,i] = 1./vert.dualArea
            MassMatrix[i, i] = vert.dualArea

        return MassMatrix

    def solvePoissonProblem_dense(mesh, densityValues):
        """
        Solve a Poisson problem on the mesh. The results should be stored on the
        vertices in a variable named 'solutionVal'. You will want to make use
        of your buildLaplaceMatrix_dense() function from above.

        densityValues is a dictionary mapping {vertex ==> value} that specifies
        densities. The density is implicitly zero at every vertex not in this
        dictionary.

        When you run this program with 'python Assignment3.py part1 path/to/your/mesh.obj',
        you will get to click on vertices to specify density conditions. See the
        assignment document for more details.
        """
        index_map = enumerateVertices(mesh)
        L = buildLaplaceMatrix_dense(mesh, index_map)

        M = buildMassMatrix_dense(mesh, index_map)  #M <= 2D
        rho = np.zeros((len(mesh.verts)), float)

        for key in densityValues:
            #index_val = index_map[key]
            print 'key dual area = ', key.dualArea
            rho[index_map[key]] = densityValues[key]  #*key.dualArea

        #
        # SwissArmyLaplacian,
        #   page 179 Cu = Mf is better conditioned
        sol_vec = np.linalg.solve(L, np.dot(M, rho))

        #sparse attempts:
        #sol_vec = linsolve.spsolve(L, rho)
        #sol_vec = dsolve.spsolve(L, rho, use_umfpack=False)
        #sol_vec = dsolve.spsolve(L, rho, use_umfpack=True)

        for vert in mesh.verts:
            key = index_map[vert]
            #print 'TLM sol_vec = ',sol_vec[key]
            vert.solutionVal = sol_vec[key]
            if rho[key]:
                vert.densityVal = rho[key]
            else:
                vert.densityVal = 0.

        return

    ##################################
    # Part 2: Sparse Poisson Problem #
    ##################################
    # Solve a Poisson problem on the mesh. The primary function here
    # is solvePoissonProblem_sparse(), it will get called when you run
    #   python Assignment3.py part2 /path/to/your/mesh.obj
    # and specify density values with the mouse (the press space to solve).
    #
    # This will be very similar to the previous part. Be sure to see the wiki
    # for notes about the nuances of sparse matrix computation. Now, your code
    # should scale well to larger meshes!

    def buildLaplaceMatrix_sparse(mesh, index_map=None):
        """
        Build a laplace operator for the mesh, with a sparse representation.
        This will be nearly identical to the dense method.

        'index' is a dictionary mapping {vertex ==> index}

        Returns the resulting sparse matrix.
        """
        if index_map is None:
            # index_map = mesh.enumerateVertices()
            index_map = enumerateVertices(mesh)

        nrows = ncols = len(mesh.verts)
        adjacency = np.zeros((nrows, ncols), int)
        for vv in mesh.verts:
            ith = index_map[vv]
            avlist = list(vv.adjacentVerts())
            for av in avlist:
                jth = index_map[av]
                adjacency[ith, jth] = 1

        Laplacian = np.zeros((nrows, ncols), float)
        for vi in mesh.verts:
            ith = index_map[vi]
            ll = list(vi.adjacentEdgeVertexPairs())
            for edge, vj in ll:
                jth = index_map[vj]
                #                Laplacian[ith,jth] = np.dot(vj.normal,
                #                                             edge.cotanWeight*(vj.position -
                #                                                       vi.position)
                #                                             )
                if ith == jth:
                    pass  #Laplacian[ith,jth] = edge.cotanWeight
                else:
                    Laplacian[ith, jth] = edge.cotanWeight

            Laplacian[ith, ith] = -sum(Laplacian[ith])

        return csr_matrix(Laplacian)

    def buildMassMatrix_sparse(mesh, index):
        """
        Build a sparse mass matrix for the system.

        Returns the resulting sparse matrix.
        """
        nrows = ncols = len(mesh.verts)

        MassMatrix = np.zeros((nrows), float)
        #for i,vert in enumerate(mesh.verts):
        #    MassMatrix[i] = vert.dualArea

        return MassMatrix

    def solvePoissonProblem_sparse(mesh, densityValues):
        """
        Solve a Poisson problem on the mesh, using sparse matrix operations.
        This will be nearly identical to the dense method.
        The results should be stored on the vertices in a variable named 'solutionVal'.

        densityValues is a dictionary mapping {vertex ==> value} that specifies any
        densities. The density is implicitly zero at every vertex not in this dictionary.

        Note: Be sure to look at the notes on the github wiki about sparse matrix
        computation in Python.

        When you run this program with 'python Assignment3.py part2 path/to/your/mesh.obj',
        you will get to click on vertices to specify density conditions. See the
        assignment document for more details.
        """

        index_map = enumerateVertices(mesh)
        L = buildLaplaceMatrix_sparse(mesh, index_map)

        M = buildMassMatrix_dense(mesh, index_map)  #M <= 2D
        rho = np.zeros((len(mesh.verts)), float)

        for key in densityValues:
            #index_val = index_map[key]
            print 'key dual area = ', key.dualArea
            rho[index_map[key]] = densityValues[key]  #*key.dualArea

        # convert to sparse matrix (CSR method)
        #Lsparse = csr_matrix(L)
        #iL = np.linalg.inv(L)
        #sol_vec = np.dot(iL,rho)

        #sol_vec = np.linalg.solve(L, rho)
        #sol_vec = linsolve.spsolve(L, rho)

        #sol_vec = linsolve.spsolve(L, np.dot(M,rho) )
        #sol_vec = dsolve.spsolve(L, rho, use_umfpack=False)
        sol_vec = dsolve.spsolve(L, np.dot(M, rho), use_umfpack=True)

        for vert in mesh.verts:
            key = index_map[vert]
            #print 'TLM sol_vec = ',sol_vec[key]
            vert.solutionVal = sol_vec[key]
            if rho[key]:
                vert.densityVal = rho[key]
            else:
                vert.densityVal = 0.

        return

    ###############################
    # Part 3: Mean Curvature Flow #
    ###############################
    # Perform mean curvature flow on the mesh. The primary function here
    # is meanCurvatureFlow(), which will get called when you run
    #   python Assignment3.py part3 /path/to/your/mesh.obj
    # You can adjust the step size with the 'z' and 'x' keys, and press space
    # to perform one step of flow.
    #
    # Of course, you will want to use sparse matrices here, so your code
    # scales well to larger meshes.

    def buildMeanCurvatureFlowOperator(mesh, index=None, h=None):
        """
        Construct the (sparse) mean curvature operator matrix for the mesh.
        It might be helpful to use your buildLaplaceMatrix_sparse() and
        buildMassMatrix_sparse() methods from before.

        Returns the resulting matrix.
        """
        nrows = ncols = len(mesh.verts)

        ##MassMatrix = np.zeros((nrows),float)
        #MassMatrix = np.zeros((nrows,ncols),float)
        #for i,vert in enumerate(mesh.verts):
        #    MassMatrix[i] = 1./vert.dualArea
        #    #MassMatrix[i,i] = 1./vert.dualArea

        Laplacian = np.zeros((nrows, ncols), float)
        for vi in mesh.verts:
            ith = index[vi]
            ll = list(vi.adjacentEdgeVertexPairs())
            for edge, vj in ll:
                jth = index[vj]
                #                Laplacian[ith,jth] = np.dot(vj.normal,
                #                                             edge.cotanWeight*(vj.position -
                #                                                       vi.position)
                #                                             )
                if ith == jth:
                    pass  #Laplacian[ith,jth] = edge.cotanWeight
                else:
                    Laplacian[ith, jth] = edge.cotanWeight

            Laplacian[ith, ith] = -sum(Laplacian[ith])

        return csr_matrix(Laplacian)

    def meanCurvatureFlow_use_numpy_solve(mesh, h):
        """
        Perform mean curvature flow on the mesh. The result of this operation
        is updated positions for the vertices; you should conclude by modifying
        the position variables for the mesh vertices.

        h is the step size for the backwards euler integration.

        When you run this program with 'python Assignment3.py part3 path/to/your/mesh.obj',
        you can press the space bar to perform this operation and z/x to change
        the step size.

        Recall that before you modify the positions of the mesh, you will need
        to set mesh.staticGeometry = False, which disables caching optimizations
        but allows you to modfiy the geometry. After you are done modfiying
        positions, you should set mesh.staticGeometry = True to re-enable these
        optimizations. You should probably have mesh.staticGeometry = True while
        you assemble your operator, or it will be very slow.
        """
        # index_map = mesh.enumerateVertices()
        index_map = enumerateVertices(mesh)
        nrows = ncols = len(mesh.verts)

        Id = np.identity(nrows, float)
        M = buildMassMatrix_dense(mesh, index_map)  #M <= 2D

        MCF = buildMeanCurvatureFlowOperator(mesh, index=index_map, h=h)

        #
        # SwissArmyLaplacian,
        #   page 181 (I-hC)u = u is not symmetric
        #            (M-hC)u = Mu is better conditioned
        #----------------------------------------------
        Mi = np.linalg.inv(M)

        L = np.matmul(Mi, MCF)
        #UpdateOperator = np.linalg.inv(Id-h*L)
        #----------------------------------------------
        #UpdateOperator = np.linalg.inv(M-h*MCF)

        LHS = M - h * MCF
        UpdateOperator = np.linalg.inv(LHS)
        #UpdateOperator = np.matmul(UpdateOperator,M)

        vertices = np.zeros((nrows, 3), float)
        for i, vert in enumerate(mesh.verts):
            vertices[i] = vert.position
        LHS = Id - h * L

        UpdateOperator = np.linalg.solve(LHS, vertices)
        vertices = UpdateOperator
        for i, vert in enumerate(mesh.verts):
            #key = index_map[vert]
            vert.position = vertices[i]


#
#        vertices = np.dot(UpdateOperator,vertices)
#        for i,vert in enumerate(mesh.verts):
#            key = index_map[vert]
#            vert.position = vertices[i]

        return

    def meanCurvatureFlow(mesh, h):
        """
        Perform mean curvature flow on the mesh. The result of this operation
        is updated positions for the vertices; you should conclude by modifying
        the position variables for the mesh vertices.

        h is the step size for the backwards euler integration.

        When you run this program with 'python Assignment3.py part3 path/to/your/mesh.obj',
        you can press the space bar to perform this operation and z/x to change
        the step size.

        Recall that before you modify the positions of the mesh, you will need
        to set mesh.staticGeometry = False, which disables caching optimizations
        but allows you to modfiy the geometry. After you are done modfiying
        positions, you should set mesh.staticGeometry = True to re-enable these
        optimizations. You should probably have mesh.staticGeometry = True while
        you assemble your operator, or it will be very slow.
        """
        # index_map = mesh.enumerateVertices()
        index_map = enumerateVertices(mesh)
        nrows = ncols = len(mesh.verts)

        #Id = np.identity(nrows,float)
        M = buildMassMatrix_dense(mesh, index_map)  #M <= 2D
        Msp = csr_matrix(M)

        #pure cotan operator:
        MCF = buildMeanCurvatureFlowOperator(mesh, index=index_map, h=h)

        #
        # SwissArmyLaplacian,
        #   page 181 (I-hC)u = u is not symmetric
        #            (M-hC)u = Mu is better conditioned
        #----------------------------------------------
        #Mi = np.linalg.inv(M)
        #L = np.matmul(Mi,MCF)
        #UpdateOperator = np.linalg.inv(Id-h*L)
        #----------------------------------------------
        #LHS = M-h*MCF

        LHS = Msp - MCF.multiply(h)

        #UpdateOperator = np.linalg.inv(LHS)
        #UpdateOperator = np.matmul(UpdateOperator,M)

        UpdateOperator = dsolve.spsolve(LHS, M, use_umfpack=True)

        vertices = np.zeros((nrows, 3), float)
        for i, vert in enumerate(mesh.verts):
            vertices[i] = vert.position

        #https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.cho_solve.html
        #UpdateOperator = scipy.linalg.cho_solve(
        #        scipy.linalg.cho_factor(LHS),
        #          np.dot(M,vertices))

        #P, L, U = scipy.linalg.lu(LHS)

        # for non symmetric, numpy solve, style:
        #        LHS = Id-h*L
        #        UpdateOperator = np.linalg.solve(LHS, vertices)
        #        vertices = UpdateOperator
        #        for i,vert in enumerate(mesh.verts):
        #            #key = index_map[vert]
        #            vert.position = vertices[i]

        #
        vertices = np.dot(UpdateOperator, vertices)
        for i, vert in enumerate(mesh.verts):
            #key = index_map[vert]
            vert.position = vertices[i]

        return

    ###################### END YOUR CODE
    # from assignment 2:
    Face.normal = faceNormal
    Face.area = faceArea
    Vertex.normal = vertexNormal_AreaWeighted
    Vertex.vertexNormal_EquallyWeighted = vertexNormal_EquallyWeighted
    Vertex.vertexNormal_AreaWeighted = vertexNormal_AreaWeighted
    Vertex.vertexNormal_AngleWeighted = vertexNormal_AngleWeighted
    ##
    Vertex.vertex_Laplace = vertex_Laplace
    #
    #Vertex.vertexNormal_SphereInscribed = vertexNormal_SphereInscribed
    Vertex.angleDefect = angleDefect
    HalfEdge.cotan = cotan

    def toggleDefect():
        print("\nToggling angle defect display")
        if toggleDefect.val:
            toggleDefect.val = False
            meshDisplay.setShapeColorToDefault()
        else:
            toggleDefect.val = True
            meshDisplay.setShapeColorFromScalar("angleDefect",
                                                cmapName="seismic")
            #,vMinMax=[-pi/8,pi/8])
        meshDisplay.generateFaceData()

    toggleDefect.val = False
    meshDisplay.registerKeyCallback(
        '3', toggleDefect, docstring="Toggle drawing angle defect coloring")

    def computeDiscreteGaussBonnet():
        print("\nComputing total curvature:")
        computed = totalGaussianCurvature()
        predicted = gaussianCurvatureFromGaussBonnet()
        print("   Total computed curvature: " + str(computed))
        print("   Predicted value from Gauss-Bonnet is: " + str(predicted))
        print("   Error is: " + str(abs(computed - predicted)))

    meshDisplay.registerKeyCallback('z',
                                    computeDiscreteGaussBonnet,
                                    docstring="Compute total curvature")

    ###################### Assignment 3 stuff
    Edge.cotanWeight = cotanWeight
    Vertex.dualArea = dualArea

    # A pick function for choosing density conditions
    densityValues = dict()

    def pickVertBoundary(vert):
        """
        See MeshDisplay callbacks,
        pickVertexCallback
        for how this works!
        
        self.pickVertexCallback <== pickVertBoundary(vert)
        self.pickVertexCallback(pickObject = your_vertex)
        """
        value = 1.0 if pickVertBoundary.isHigh else -1.0
        print("   Selected vertex at position:" + printVec3(vert.position))
        print("   as a density with value = " + str(value))
        densityValues[vert] = value
        print 'densityValues = ', densityValues
        pickVertBoundary.isHigh = not pickVertBoundary.isHigh

    pickVertBoundary.isHigh = True

    # Run in part1 mode
    if partString == 'part1':

        print("\n\n === Executing assignment 2 part 1")
        print("""
        Please click on vertices of the mesh to specify density conditions.
        Alternating clicks will specify high-value (= 1.0) and low-value (= -1.0)
        density conditions. You may select as many density vertices as you want,
        but >= 2 are necessary to yield an interesting solution. When you are done,
        press the space bar to execute your solver and view the results.
        """)

        meshDisplay.pickVertexCallback = pickVertBoundary
        meshDisplay.drawVertices = True

        def executePart1Callback():
            print("\n=== Solving Poisson problem with your dense solver\n")

            # Print and check the density values
            print("Density values:")
            for key in densityValues:
                print("    " + str(key) + " = " + str(densityValues[key]))
            #if len(densityValues) < 2:
            #    print("Aborting solve, not enough density vertices specified")
            #    return

            # Call the solver
            print("\nSolving problem...")
            t0 = time.time()
            solvePoissonProblem_dense(mesh, densityValues)
            tSolve = time.time() - t0
            print("...solution completed.")
            print("Solution took {:.5f} seconds.".format(tSolve))

            print("Visualizing results...")

            # Error out intelligently if nothing is stored on vert.solutionVal
            for vert in mesh.verts:
                if not hasattr(vert, 'solutionVal'):
                    print(
                        "ERROR: At least one vertex does not have the attribute solutionVal defined."
                    )
                    exit()
                if not isinstance(vert.solutionVal, float):
                    print(
                        "ERROR: The data stored at vertex.solutionVal is not of type float."
                    )
                    print("   The data has type=" +
                          str(type(vert.solutionVal)))
                    print("   The data looks like vert.solutionVal=" +
                          str(vert.solutionVal))
                    exit()

            # Visualize the result
            #            meshDisplay.setShapeColorFromScalar("solutionVal",
            #                                                definedOn='vertex',
            #                                                cmapName="seismic",
            #                                                vMinMax=[-10.0,10.0])
            meshDisplay.setShapeColorFromScalar("solutionVal",
                                                definedOn='vertex',
                                                cmapName="seismic")
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            ' ',
            executePart1Callback,
            docstring="Solve the Poisson problem and view the results")

        def showdensity():
            # Visualize the result
            #            meshDisplay.setShapeColorFromScalar("densityVal",
            #                                                definedOn='vertex',
            #                                                cmapName="seismic",
            #                                                vMinMax=[-1.0,1.0])
            meshDisplay.setShapeColorFromScalar("densityVal",
                                                definedOn='vertex',
                                                cmapName="seismic")
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            'b',
            showdensity,
            docstring="Show the density map for the Poisson Problem")

        # Start the GUI
        if show:
            meshDisplay.startMainLoop()

    # Run in part2 mode
    elif partString == 'part2':
        print("\n\n === Executing assignment 2 part 2")
        print("""
        Please click on vertices of the mesh to specify density conditions.
        Alternating clicks will specify high-value (= 1.0) and low-value (= -1.0)
        density conditions. You may select as many density vertices as you want,
        but >= 2 are necessary to yield an interesting solution. When you are done,
        press the space bar to execute your solver and view the results.
        """)

        meshDisplay.pickVertexCallback = pickVertBoundary
        meshDisplay.drawVertices = True

        def executePart2Callback():
            print("\n=== Solving Poisson problem with your sparse solver\n")

            # Print and check the density values
            print("Density values:")
            for key in densityValues:
                print("    " + str(key) + " = " + str(densityValues[key]))
            #if len(densityValues) < 2:
            #    print("Aborting solve, not enough density vertices specified")
            #    return

            # Call the solver
            print("\nSolving problem...")
            t0 = time.time()
            solvePoissonProblem_sparse(mesh, densityValues)
            tSolve = time.time() - t0
            print("...solution completed.")
            print("Solution took {:.5f} seconds.".format(tSolve))

            print("Visualizing results...")

            # Error out intelligently if nothing is stored on vert.solutionVal
            for vert in mesh.verts:
                if not hasattr(vert, 'solutionVal'):
                    print(
                        "ERROR: At least one vertex does not have the attribute solutionVal defined."
                    )
                    exit()
                if not isinstance(vert.solutionVal, float):
                    print(
                        "ERROR: The data stored at vertex.solutionVal is not of type float."
                    )
                    print("   The data has type=" +
                          str(type(vert.solutionVal)))
                    print("   The data looks like vert.solutionVal=" +
                          str(vert.solutionVal))
                    exit()

            # Visualize the result
            # meshDisplay.setShapeColorFromScalar("solutionVal", definedOn='vertex', cmapName="seismic", vMinMax=[-1.0,1.0])
            meshDisplay.setShapeColorFromScalar("solutionVal",
                                                definedOn='vertex',
                                                cmapName="seismic")
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            ' ',
            executePart2Callback,
            docstring="Solve the Poisson problem and view the results")

        # Start the GUI
        if show:
            meshDisplay.startMainLoop()

    # Run in part3 mode
    elif partString == 'part3':

        print("\n\n === Executing assignment 2 part 3")
        print("""
        Press the space bar to perform one step of mean curvature
        flow smoothing, using your solver. Pressing the 'z' and 'x'
        keys will decrease and increase the step size (h), respectively.
        """)

        stepSize = [0.01]

        def increaseStepsize():
            stepSize[0] += 0.001
            print("Increasing step size. New size h=" + str(stepSize[0]))

        def decreaseStepsize():
            stepSize[0] -= 0.001
            print("Decreasing step size. New size h=" + str(stepSize[0]))

        meshDisplay.registerKeyCallback(
            'z',
            decreaseStepsize,
            docstring="Increase the value of the step size (h) by 0.1")
        meshDisplay.registerKeyCallback(
            'x',
            increaseStepsize,
            docstring="Decrease the value of the step size (h) by 0.1")

        def smoothingStep():
            print("\n=== Performing mean curvature smoothing step\n")
            print("  Step size h=" + str(stepSize[0]))

            # Call the solver
            print("  Solving problem...")
            t0 = time.time()
            meanCurvatureFlow(mesh, stepSize[0])
            tSolve = time.time() - t0
            print("  ...solution completed.")
            print("  Solution took {:.5f} seconds.".format(tSolve))

            print("Updating display...")
            meshDisplay.generateAllMeshValues()

        meshDisplay.registerKeyCallback(
            ' ',
            smoothingStep,
            docstring="Perform one step of your mean curvature flow on the mesh"
        )

        # Start the GUI
        if show:
            meshDisplay.startMainLoop()
    return mesh, meshDisplay
Пример #9
0
def main():

    # Get the path for the mesh to load, either from the program argument if
    # one was given, or a dialog otherwise
    if (len(sys.argv) > 1):
        filename = sys.argv[1]
    else:
        print(
            "ERROR: No file name specified. Proper syntax is 'python Assignment2.py path/to/your/mesh.obj'."
        )
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer object
    winName = 'DDG Assignment2 -- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)

    ###################### BEGIN YOUR CODE
    # implement the body of each of these functions

    @property
    @cacheGeometry
    def faceArea(self):
        """
        Compute the area of a face. Though not directly requested, this will be
        useful when computing face-area weighted normals below.
        This method gets called on a face, so 'self' is a reference to the
        face at which we will compute the area.
        """

        return 0.0  # placeholder value

    @property
    @cacheGeometry
    def faceNormal(self):
        """
        Compute normal at a face of the mesh. Unlike at vertices, there is one very
        obvious way to do this, since a face uniquely defines a plane.
        This method gets called on a face, so 'self' is a reference to the
        face at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_EquallyWeighted(self):
        """
        Compute a vertex normal using the 'equally weighted' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_AreaWeighted(self):
        """
        Compute a vertex normal using the 'face area weights' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_AngleWeighted(self):
        """
        Compute a vertex normal using the 'tip angle weights' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def cotan(self):
        """
        Compute the cotangent of the angle opposite a halfedge. This is not
        directly required, but will be useful when computing the mean curvature
        normals below.
        This method gets called on a halfedge, so 'self' is a reference to the
        halfedge at which we will compute the cotangent.
        """

        return 0.0  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_MeanCurvature(self):
        """
        Compute a vertex normal using the 'mean curvature' method.
        Be sure to understand the relationship between this method and the
        area gradient method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_SphereInscribed(self):
        """
        Compute a vertex normal using the 'inscribed sphere' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def angleDefect(self):
        """
        Compute the angle defect of a vertex, d(v) (see Assignment 1 Exercise 8).
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the angle defect.
        """

        return 0.0  # placeholder value

    def totalGaussianCurvature():
        """
        Compute the total Gaussian curvature in the mesh, meaning the sum of Gaussian
        curvature at each vertex.
        Note that you can access the mesh with the 'mesh' variable.
        """

        return 0.0  # placeholder value

    def gaussianCurvatureFromGaussBonnet():
        """
        Compute the total Gaussian curvature that the mesh should have, given that the
        Gauss-Bonnet theorem holds (see Assignment 1 Exercise 9).
        Note that you can access the mesh with the 'mesh' variable. The
        mesh includes members like 'mesh.verts' and 'mesh.faces', which are
        sets of the vertices (resp. faces) in the mesh.
        """

        return 0.0  # placeholder value

    ###################### END YOUR CODE

    # Set these newly-defined methods as the methods to use in the classes
    Face.normal = faceNormal
    Face.area = faceArea
    Vertex.normal = vertexNormal_AreaWeighted
    Vertex.vertexNormal_EquallyWeighted = vertexNormal_EquallyWeighted
    Vertex.vertexNormal_AreaWeighted = vertexNormal_AreaWeighted
    Vertex.vertexNormal_AngleWeighted = vertexNormal_AngleWeighted
    Vertex.vertexNormal_MeanCurvature = vertexNormal_MeanCurvature
    Vertex.vertexNormal_SphereInscribed = vertexNormal_SphereInscribed
    Vertex.angleDefect = angleDefect
    HalfEdge.cotan = cotan

    ## Functions which will be called by keypresses to visualize these definitions

    def toggleFaceVectors():
        print("\nToggling vertex vector display")
        if toggleFaceVectors.val:
            toggleFaceVectors.val = False
            meshDisplay.setVectors(None)
        else:
            toggleFaceVectors.val = True
            meshDisplay.setVectors('normal', vectorDefinedAt='face')
        meshDisplay.generateVectorData()

    toggleFaceVectors.val = False  # ridiculous Python scoping hack
    meshDisplay.registerKeyCallback(
        '1', toggleFaceVectors, docstring="Toggle drawing face normal vectors")

    def toggleVertexVectors():
        print("\nToggling vertex vector display")
        if toggleVertexVectors.val:
            toggleVertexVectors.val = False
            meshDisplay.setVectors(None)
        else:
            toggleVertexVectors.val = True
            meshDisplay.setVectors('normal', vectorDefinedAt='vertex')
        meshDisplay.generateVectorData()

    toggleVertexVectors.val = False  # ridiculous Python scoping hack
    meshDisplay.registerKeyCallback(
        '2',
        toggleVertexVectors,
        docstring="Toggle drawing vertex normal vectors")

    def toggleDefect():
        print("\nToggling angle defect display")
        if toggleDefect.val:
            toggleDefect.val = False
            meshDisplay.setShapeColorToDefault()
        else:
            toggleDefect.val = True
            meshDisplay.setShapeColorFromScalar("angleDefect",
                                                cmapName="seismic",
                                                vMinMax=[-pi / 8, pi / 8])
        meshDisplay.generateFaceData()

    toggleDefect.val = False
    meshDisplay.registerKeyCallback(
        '3', toggleDefect, docstring="Toggle drawing angle defect coloring")

    def useEquallyWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing equally-weighted normals")
        Vertex.normal = vertexNormal_EquallyWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback(
        '4',
        useEquallyWeightedNormals,
        docstring="Use equally-weighted normal computation")

    def useAreaWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing area-weighted normals")
        Vertex.normal = vertexNormal_AreaWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback(
        '5',
        useAreaWeightedNormals,
        docstring="Use area-weighted normal computation")

    def useAngleWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing angle-weighted normals")
        Vertex.normal = vertexNormal_AngleWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback(
        '6',
        useAngleWeightedNormals,
        docstring="Use angle-weighted normal computation")

    def useMeanCurvatureNormals():
        mesh.staticGeometry = False
        print("\nUsing mean curvature normals")
        Vertex.normal = vertexNormal_MeanCurvature
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback(
        '7',
        useMeanCurvatureNormals,
        docstring="Use mean curvature normal computation")

    def useSphereInscribedNormals():
        mesh.staticGeometry = False
        print("\nUsing sphere-inscribed normals")
        Vertex.normal = vertexNormal_SphereInscribed
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback(
        '8',
        useSphereInscribedNormals,
        docstring="Use sphere-inscribed normal computation")

    def computeDiscreteGaussBonnet():
        print("\nComputing total curvature:")
        computed = totalGaussianCurvature()
        predicted = gaussianCurvatureFromGaussBonnet()
        print("   Total computed curvature: " + str(computed))
        print("   Predicted value from Gauss-Bonnet is: " + str(predicted))
        print("   Error is: " + str(abs(computed - predicted)))

    meshDisplay.registerKeyCallback('z',
                                    computeDiscreteGaussBonnet,
                                    docstring="Compute total curvature")

    def deformShape():
        print("\nDeforming shape")
        mesh.staticGeometry = False

        # Get the center and scale of the shape
        center = meshDisplay.dataCenter
        scale = meshDisplay.scaleFactor

        # Rotate according to swirly function
        ax = eu.Vector3(-1.0, .75, 0.5)
        for v in mesh.verts:
            vec = v.position - center
            theta = 0.8 * norm(vec) / scale
            newVec = np.array(eu.Vector3(*vec).rotate_around(ax, theta))
            v.position = center + newVec

        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback(
        'x', deformShape, docstring="Apply a swirly deformation to the shape")

    ## Register pick functions that output useful information on click
    def pickVert(vert):
        print("   Position:" + printVec3(vert.position))
        print("   Angle defect: {:.5f}".format(vert.angleDefect))
        print("   Normal (equally weighted): " +
              printVec3(vert.vertexNormal_EquallyWeighted))
        print("   Normal (area weighted):    " +
              printVec3(vert.vertexNormal_AreaWeighted))
        print("   Normal (angle weighted):   " +
              printVec3(vert.vertexNormal_AngleWeighted))
        print("   Normal (sphere-inscribed): " +
              printVec3(vert.vertexNormal_SphereInscribed))
        print("   Normal (mean curvature):   " +
              printVec3(vert.vertexNormal_MeanCurvature))

    meshDisplay.pickVertexCallback = pickVert

    def pickFace(face):
        print("   Face area: {:.5f}".format(face.area))
        print("   Normal: " + printVec3(face.normal))
        print("   Vertex positions: ")
        for (i, vert) in enumerate(face.adjacentVerts()):
            print("     v{}: {}".format((i + 1), printVec3(vert.position)))

    meshDisplay.pickFaceCallback = pickFace

    # Start the viewer running
    meshDisplay.startMainLoop()
Пример #10
0
def main():

    # Get the path for the mesh to load, either from the program argument if
    # one was given, or a dialog otherwise
    if len(sys.argv) > 1:
        filename = sys.argv[1]
    else:
        print("ERROR: No file name specified. Proper syntax is 'python Assignment2.py path/to/your/mesh.obj'.")
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer object
    winName = "DDG Assignment2 -- " + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)

    ###################### BEGIN YOUR CODE
    # implement the body of each of these functions

    @property
    @cacheGeometry
    def faceArea(self):
        """
        Compute the area of a face. Though not directly requested, this will be
        useful when computing face-area weighted normals below.
        This method gets called on a face, so 'self' is a reference to the
        face at which we will compute the area.
        """

        return 0.0  # placeholder value

    @property
    @cacheGeometry
    def faceNormal(self):
        """
        Compute normal at a face of the mesh. Unlike at vertices, there is one very
        obvious way to do this, since a face uniquely defines a plane.
        This method gets called on a face, so 'self' is a reference to the
        face at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_EquallyWeighted(self):
        """
        Compute a vertex normal using the 'equally weighted' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_AreaWeighted(self):
        """
        Compute a vertex normal using the 'face area weights' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_AngleWeighted(self):
        """
        Compute a vertex normal using the 'tip angle weights' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def cotan(self):
        """
        Compute the cotangent of the angle opposite a halfedge. This is not
        directly required, but will be useful when computing the mean curvature
        normals below.
        This method gets called on a halfedge, so 'self' is a reference to the
        halfedge at which we will compute the cotangent.
        """

        return 0.0  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_MeanCurvature(self):
        """
        Compute a vertex normal using the 'mean curvature' method.
        Be sure to understand the relationship between this method and the
        area gradient method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def vertexNormal_SphereInscribed(self):
        """
        Compute a vertex normal using the 'inscribed sphere' method.
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the normal.
        """

        return Vector3D(0.0, 0.0, 0.0)  # placeholder value

    @property
    @cacheGeometry
    def angleDefect(self):
        """
        Compute the angle defect of a vertex, d(v) (see Assignment 1 Exercise 8).
        This method gets called on a vertex, so 'self' is a reference to the
        vertex at which we will compute the angle defect.
        """

        return 0.0  # placeholder value

    def totalGaussianCurvature():
        """
        Compute the total Gaussian curvature in the mesh, meaning the sum of Gaussian
        curvature at each vertex.
        Note that you can access the mesh with the 'mesh' variable.
        """

        return 0.0  # placeholder value

    def gaussianCurvatureFromGaussBonnet():
        """
        Compute the total Gaussian curvature that the mesh should have, given that the
        Gauss-Bonnet theorem holds (see Assignment 1 Exercise 9).
        Note that you can access the mesh with the 'mesh' variable. The
        mesh includes members like 'mesh.verts' and 'mesh.faces', which are
        sets of the vertices (resp. faces) in the mesh.
        """

        return 0.0  # placeholder value

    ###################### END YOUR CODE

    # Set these newly-defined methods as the methods to use in the classes
    Face.normal = faceNormal
    Face.area = faceArea
    Vertex.normal = vertexNormal_AreaWeighted
    Vertex.vertexNormal_EquallyWeighted = vertexNormal_EquallyWeighted
    Vertex.vertexNormal_AreaWeighted = vertexNormal_AreaWeighted
    Vertex.vertexNormal_AngleWeighted = vertexNormal_AngleWeighted
    Vertex.vertexNormal_MeanCurvature = vertexNormal_MeanCurvature
    Vertex.vertexNormal_SphereInscribed = vertexNormal_SphereInscribed
    Vertex.angleDefect = angleDefect
    HalfEdge.cotan = cotan

    ## Functions which will be called by keypresses to visualize these definitions

    def toggleFaceVectors():
        print("\nToggling vertex vector display")
        if toggleFaceVectors.val:
            toggleFaceVectors.val = False
            meshDisplay.setVectors(None)
        else:
            toggleFaceVectors.val = True
            meshDisplay.setVectors("normal", vectorDefinedAt="face")
        meshDisplay.generateVectorData()

    toggleFaceVectors.val = False  # ridiculous Python scoping hack
    meshDisplay.registerKeyCallback("1", toggleFaceVectors, docstring="Toggle drawing face normal vectors")

    def toggleVertexVectors():
        print("\nToggling vertex vector display")
        if toggleVertexVectors.val:
            toggleVertexVectors.val = False
            meshDisplay.setVectors(None)
        else:
            toggleVertexVectors.val = True
            meshDisplay.setVectors("normal", vectorDefinedAt="vertex")
        meshDisplay.generateVectorData()

    toggleVertexVectors.val = False  # ridiculous Python scoping hack
    meshDisplay.registerKeyCallback("2", toggleVertexVectors, docstring="Toggle drawing vertex normal vectors")

    def toggleDefect():
        print("\nToggling angle defect display")
        if toggleDefect.val:
            toggleDefect.val = False
            meshDisplay.setShapeColorToDefault()
        else:
            toggleDefect.val = True
            meshDisplay.setShapeColorFromScalar("angleDefect", cmapName="seismic", vMinMax=[-pi / 8, pi / 8])
        meshDisplay.generateFaceData()

    toggleDefect.val = False
    meshDisplay.registerKeyCallback("3", toggleDefect, docstring="Toggle drawing angle defect coloring")

    def useEquallyWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing equally-weighted normals")
        Vertex.normal = vertexNormal_EquallyWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback("4", useEquallyWeightedNormals, docstring="Use equally-weighted normal computation")

    def useAreaWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing area-weighted normals")
        Vertex.normal = vertexNormal_AreaWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback("5", useAreaWeightedNormals, docstring="Use area-weighted normal computation")

    def useAngleWeightedNormals():
        mesh.staticGeometry = False
        print("\nUsing angle-weighted normals")
        Vertex.normal = vertexNormal_AngleWeighted
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback("6", useAngleWeightedNormals, docstring="Use angle-weighted normal computation")

    def useMeanCurvatureNormals():
        mesh.staticGeometry = False
        print("\nUsing mean curvature normals")
        Vertex.normal = vertexNormal_MeanCurvature
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback("7", useMeanCurvatureNormals, docstring="Use mean curvature normal computation")

    def useSphereInscribedNormals():
        mesh.staticGeometry = False
        print("\nUsing sphere-inscribed normals")
        Vertex.normal = vertexNormal_SphereInscribed
        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback("8", useSphereInscribedNormals, docstring="Use sphere-inscribed normal computation")

    def computeDiscreteGaussBonnet():
        print("\nComputing total curvature:")
        computed = totalGaussianCurvature()
        predicted = gaussianCurvatureFromGaussBonnet()
        print("   Total computed curvature: " + str(computed))
        print("   Predicted value from Gauss-Bonnet is: " + str(predicted))
        print("   Error is: " + str(abs(computed - predicted)))

    meshDisplay.registerKeyCallback("z", computeDiscreteGaussBonnet, docstring="Compute total curvature")

    def deformShape():
        print("\nDeforming shape")
        mesh.staticGeometry = False

        # Get the center and scale of the shape
        center = meshDisplay.dataCenter
        scale = meshDisplay.scaleFactor

        # Rotate according to swirly function
        ax = eu.Vector3(-1.0, 0.75, 0.5)
        for v in mesh.verts:
            vec = v.position - center
            theta = 0.8 * norm(vec) / scale
            newVec = np.array(eu.Vector3(*vec).rotate_around(ax, theta))
            v.position = center + newVec

        mesh.staticGeometry = True
        meshDisplay.generateAllMeshValues()

    meshDisplay.registerKeyCallback("x", deformShape, docstring="Apply a swirly deformation to the shape")

    ## Register pick functions that output useful information on click
    def pickVert(vert):
        print("   Position:" + printVec3(vert.position))
        print("   Angle defect: {:.5f}".format(vert.angleDefect))
        print("   Normal (equally weighted): " + printVec3(vert.vertexNormal_EquallyWeighted))
        print("   Normal (area weighted):    " + printVec3(vert.vertexNormal_AreaWeighted))
        print("   Normal (angle weighted):   " + printVec3(vert.vertexNormal_AngleWeighted))
        print("   Normal (sphere-inscribed): " + printVec3(vert.vertexNormal_SphereInscribed))
        print("   Normal (mean curvature):   " + printVec3(vert.vertexNormal_MeanCurvature))

    meshDisplay.pickVertexCallback = pickVert

    def pickFace(face):
        print("   Face area: {:.5f}".format(face.area))
        print("   Normal: " + printVec3(face.normal))
        print("   Vertex positions: ")
        for (i, vert) in enumerate(face.adjacentVerts()):
            print("     v{}: {}".format((i + 1), printVec3(vert.position)))

    meshDisplay.pickFaceCallback = pickFace

    # Start the viewer running
    meshDisplay.startMainLoop()
def main(inputfile,
         show=False,
         StaticGeometry=False,
         partString='part1',
         is_simple=True):

    # Get the path for the mesh to load from the program argument
    if (len(sys.argv) == 3 and sys.argv[1] == 'simple'):
        filename = sys.argv[2]
        simpleTest = True
    elif (len(sys.argv) == 3 and sys.argv[1] == 'fancy'):
        filename = sys.argv[2]
        simpleTest = False
    elif inputfile is not None:
        filename = inputfile
        simpleTest = is_simple
    else:
        print(
            "ERROR: Incorrect call syntax. Proper syntax is 'python Assignment5.py MODE path/to/your/mesh.obj', where MODE is either 'simple' or 'fancy'"
        )
        exit()

    # Read in the mesh
    mesh = HalfEdgeMesh(readMesh(filename))

    # Create a viewer object
    winName = 'DDG Assignment5 -- ' + os.path.basename(filename)
    meshDisplay = MeshDisplay(windowTitle=winName)
    meshDisplay.setMesh(mesh)

    ###################### BEGIN YOUR CODE

    # DDGSpring216 Assignment 5
    #
    # In this programming assignment you will implement Helmholtz-Hodge decomposition of covectors.
    #
    # The relevant mathematics and algorithm are described in section 8.1 of the course notes.
    # You will also need to implement the core operators in discrete exterior calculus, described mainly in
    # section 3.6 of the course notes.
    #
    # This code can be run with python Assignment5.py MODE /path/to/you/mesh.obj. MODE should be
    # either 'simple' or 'fancy', corresponding to the complexity of the input field omega that is given.
    # It might be easier to debug your algorithm on the simple field first. The assignment code will read in your input
    # mesh, generate a field 'omega' as input, run your algorithm, then display the results.
    # The results can be viewed as streamlines on the surface that flow with the covector field (toggle with 'p'),
    # or, as actual arrows on the faces (toggle with 'l'). The keys '1'-'4' will switch between the input, exact,
    # coexact, and harmonic fields (respectively).
    #
    # A few hints:
    #   - Try performing some basic checks on your operators if things don't seem right. For instance, applying the
    #     exterior derivative twice to anything should always yield zero.
    #   - The streamline visualization is easy to look at, but can be deceiving at times. For instance, streamlines
    #     are not very meaningful where the actual covectors are near 0. Try looking at the actual arrows in that case
    #     ('l').
    #   - Many inputs will not have any harmonic components, especially genus 0 inputs. Don't stress if the harmonic
    #     component of your output is exactly or nearly zero.

    # Implement the body of each of these functions...

    #    def assignEdgeOrientations(mesh):
    #        """
    #        Assign edge orientations to each edge on the mesh.
    #
    #        This method will be called from the assignment code, you do not need to explicitly call it in any of your methods.
    #
    #        After this method, the following values should be defined:
    #            - edge.orientedHalfEdge (a reference to one of the halfedges touching that edge)
    #            - halfedge.orientationSign (1.0 if that halfedge agrees with the orientation of its
    #                edge, or -1.0 if not). You can use this to make much of your subsequent code cleaner.
    #
    #        This is a pretty simple method to implement, any choice of orientation is acceptable.
    #        """
    #        for edge in mesh.edges:
    #            edge.orientedHalfEdge = edge.anyHalfEdge
    #            edge.anyHalfEdge.orientationSign = -1.0
    #            edge.anyHalfEdge.twin.orientationSign = 1.0
    #        return

    def diagonalInverse(A):
        """
        Returns the inverse of a sparse diagonal matrix. Makes a copy of the matrix.
        
        We will need to invert several diagonal matrices for the algorithm, but scipy does
        not offer a fast method for inverting diagonal matrices, which is a very easy special
        case. As such, this is a useful helper method for you.

        Note that the diagonal inverse is not well-defined if any of the diagonal elements are
        0.0. This needs to be acconuted for when you construct the matrices.
        """
        ncol, nrow = np.shape(A)
        assert (
            ncol == nrow
        ), 'ERROR: Diagonal inverse only make sense for a symmetric matrix'

        #B = 1./np.diag(A)

        for i in range(ncol):
            A[i, i] = 1. / A[i, i]  #B[i]

        return A


#    @property
#    @cacheGeometry
#    def circumcentricArea(self):
#        """
#        Compute the area of the circumcentric dual cell for this vertex.
#        Returns a positive scalar.
#
#        This gets called on a vertex, so 'self' will be a reference to the vertex.
#
#        The image on page 78 of the course notes may help you visualize this.
#        (TLM:  not sure what this references any more)
#
#
#        TLM note for those like me who miss the obvious:
#            You are not computing the circumcenter!
#            Go straight to the area!
#
#        real source, slide 62:
#            http://brickisland.net/DDGFall2017/wp-content/uploads/2017/09/
#                                CMU_DDG_Fall2017_06_DiscreteExteriorCalculus.pdf
#        """
#        # vl      = list(self.adjacentVerts())
#        # fl      = list(self.adjacentFaces())
#        DualArea = 0.
#        for face in self.adjacentFaces():
#            #v1 = face.anyHalfEdge.vertex.position
#            #v2 = face.anyHalfEdge.next.vertex.position
#            #v3 = face.anyHalfEdge.next.next.vertex.position
#            l1 = norm(face.anyHalfEdge.vector)              #||v1-v3||
#            l2 = norm(face.anyHalfEdge.next.vector)         #||v2-v1||
#            l3 = norm(face.anyHalfEdge.next.next.vector)    #||v3-v2||
#
#            s = .5*(l1+l2+l3)
#            DualArea +=  np.sqrt(s*(s-l1)*(s-l2)*(s-l3))
#
#
#        return DualArea
#    Vertex.circumcentricArea = circumcentricArea

#    @property
#    @cacheGeometry
#    def circumcentricDualArea(self):
#        """
#        Compute the area of the circumcentric dual cell for this vertex.
#        Returns a positive scalar.
#
#        This gets called on a vertex, so 'self' will be a reference to the vertex.
#
#        The image on page 78 of the course notes may help you visualize this.
#        (TLM:  not sure what this references any more)
#
#
#        TLM note for those like me who miss the obvious:
#            You are not computing the circumcenter!
#            Go straight to the area!
#
#        real source, slide 62:
#            http://brickisland.net/DDGFall2017/wp-content/uploads/2017/09/
#                                CMU_DDG_Fall2017_06_DiscreteExteriorCalculus.pdf
#        """
#        DualArea = 0.
#        for hedge in self.adjacentHalfEdges():
#            cak = hedge.cotan
#            lik = norm(hedge.vector)
#            caj = hedge.next.next.cotan
#            lij = norm(hedge.next.next.vector)
#
#            DualArea +=  (lij**2 *cak) + (lik**2 * caj)
#
#
#        return DualArea/8.
#    Vertex.circumcentricDualArea = circumcentricDualArea

#    def buildHodgeStar0Form(mesh, vertexIndex):
#        """
#        Build a sparse matrix encoding the Hodge operator on 0-forms for this mesh.
#        Returns a sparse, diagonal matrix corresponding to vertices.
#
#        The discrete hodge star is a diagonal matrix where each entry is
#        the (area of the dual element) / (area of the primal element). You will probably
#        want to make use of the Vertex.circumcentricDualArea property you just defined.
#
#        TLM as seen in notes:
#        By convention, the area of a vertex is 1.0.
#        """
#        nrows = ncols = len(mesh.verts)
#        vertex_area = 1.0
#
#        Hodge0Form = np.zeros((nrows,ncols),float)
#        for i,vert in enumerate(mesh.verts):
#            vi = vertexIndex[vert]
#            Hodge0Form[vi,vi] = vert.circumcentricDualArea #/primal vertex_area
#            #Hodge0Form[vi,vi] = vert.barycentricDualArea #/primal vertex_area
#        return Hodge0Form
#
#
#    def buildHodgeStar1Form(mesh, edgeIndex):
#        """
#        Build a sparse matrix encoding the Hodge operator on 1-forms for this mesh.
#        Returns a sparse, diagonal matrix corresponding to edges.
#
#        The discrete hodge star is a diagonal matrix where each entry is
#        the (area of the dual element) / (area of the primal element). The solution
#        to exercise 26 from the previous homework will be useful here.
#
#        TLM: cotan formula again.  see ddg notes page 89
#        see also source slide 56 (did you mean slide 62?):
#            http://brickisland.net/DDGFall2017/wp-content/uploads/2017/09/
#                                CMU_DDG_Fall2017_06_DiscreteExteriorCalculus.pdf
#
#        Note that for some geometries, some entries of hodge1 operator may be exactly 0.
#        This can create a problem when we go to invert the matrix. To numerically sidestep
#        this issue, you probably want to add a small value (like 10^-8) to these diagonal
#        elements to ensure all are nonzero without significantly changing the result.
#        """
#        nrows = ncols = len(mesh.edges)
#        Hodge1Form = np.zeros((nrows,ncols),float)
#
#        for i,edge in enumerate(mesh.edges):
#            ei = edgeIndex[edge]
#            w = (( edge.anyHalfEdge.cotan + edge.anyHalfEdge.twin.cotan ) *.5) + 1.e-8
#            #Hodge1Form[ei,ei] = edge.cotanWeight + 1.e-8
#            Hodge1Form[ei,ei] = w
#        return Hodge1Form
#
#
#    def buildHodgeStar2Form(mesh, faceIndex):
#        """
#        Build a sparse matrix encoding the Hodge operator on 2-forms for this mesh
#        Returns a sparse, diagonal matrix corresponding to faces.
#
#        The discrete hodge star is a diagonal matrix where each entry is
#        the (area of the dual element) / (area of the primal element).
#
#
#        TLM hint hint!, vertex is => (dual) vertex:
#        By convention, the area of a vertex is 1.0.
#
#
#        TLM: see also source slide 57:
#            http://brickisland.net/DDGFall2017/wp-content/uploads/2017/09/
#                                CMU_DDG_Fall2017_06_DiscreteExteriorCalculus.pdf
#        """
#        nrows = ncols = len(mesh.faces)
#        Hodge2Form = np.zeros((nrows,ncols),float)
#
#        for i,face in enumerate(mesh.faces):
#            fi = faceIndex[face]
#            Hodge2Form[fi,fi] = 1./face.area
#            #Hodge2Form[fi,fi] = 1./face.AreaToDualVertexCicumcentric #circumcentric
#        return Hodge2Form
#
#
#    def buildExteriorDerivative0Form(mesh, edgeIndex, vertexIndex):
#        """
#        Build a sparse matrix encoding the exterior derivative on 0-forms.
#        Returns a sparse matrix.
#
#        See section 3.6 of the course notes for an explanation of DEC.
#
#        0form -> 1form
#
#        In [2]: ed
#        Out[2]: <Edge #0>
#
#        In [3]: ed.anyHalfEdge
#        Out[3]: <HalfEdge #11661>
#
#        In [4]: ed.anyHalfEdge.vertex
#        Out[4]: <Vertex #0>
#
#        In [5]: ed.anyHalfEdge.vertex.position
#        Out[5]: array([1.25, 0.  , 0.  ])
#
#        In [6]: ed.anyHalfEdge.twin.vertex.position
#        Out[6]: array([ 1.246147,  0.      , -0.098074])
#
#        In [7]: ed.anyHalfEdge.vertex.position - ed.anyHalfEdge.twin.vertex.position
#        Out[7]: array([0.003853, 0.      , 0.098074])
#
#        In [8]: ed.anyHalfEdge.vector
#        Out[8]: array([0.003853, 0.      , 0.098074])
#
#        ## so ed.anyHalfEdge.vector runs
#            from anyHalfEdge.twin.vertex
#            to   anyHalfEdge.vertex
#
#        In [9]: ed.anyHalfEdge.twin.vector
#        Out[9]: array([-0.003853,  0.      , -0.098074])
#        """
#        vert_edge_incidence = np.zeros((mesh.nedges,mesh.nverts),float)
#        #        for vertex in mesh.verts:
#        #            vj = vertexIndex[vertex]
#        #            for edge in vertex.adjacentEdges():
#        #                ei = edgeIndex[edge]
#        #
#        #                value = edge.orientedHalfEdge.orientationSign
#        #                if vertex is edge.anyHalfEdge.vertex:
#        #                    # then we are at edge.anyHalfEdge.vertex,
#        #                    # i.e., the end of this half edge's vector. (not the start of the vector)
#        #                    value = -value
#        #
#        #                vert_edge_incidence[ei,vj] = value
#
#
#        for edge in mesh.edges:
#            ei = edgeIndex[edge]
#
#            vh1 = edge.orientedHalfEdge.vertex
#            vh2 = edge.orientedHalfEdge.twin.vertex
#
#            ci = vertexIndex[vh1]
#            cj = vertexIndex[vh2]
#
#            #value = edge.orientedHalfEdge.orientationSign
#
#            vert_edge_incidence[ei,ci] =  1. #-value
#            vert_edge_incidence[ei,cj] = -1. #value
#        return csr_matrix( vert_edge_incidence )
#        #return vert_edge_incidence
#
#
#    def buildExteriorDerivative1FormOLD(mesh, faceIndex, edgeIndex):
#        """
#        Build a sparse matrix encoding the exterior derivative on 1-forms.
#        Returns a sparse matrix.
#
#        See section 3.6 of the course notes for an explanation of DEC.
#        """
#        edge_face_incidence = np.zeros((mesh.nfaces,mesh.nedges),float)
#        for face in mesh.faces:
#            fi = faceIndex[face]
#            v = list(face.adjacentVerts()) #0,1,2
#            #tv = []
#            for edge in face.adjacentEdges():
#                ej = edgeIndex[edge]
#                value = edge.orientedHalfEdge.orientationSign
#
#                #anyHalfEdge vector goes from
#                #  anyHalfEdge.twin.vertex to anyHalfEdge.vertex
#                edge_start = edge.anyHalfEdge.twin.vertex
#                edge_end = edge.anyHalfEdge.vertex
#                if edge_start is v[0]:
#                    if edge_end is v[1]:
#                        value = value
#                    else:
#                        value = -value
#                elif edge_start is v[1]:
#                    if edge_end is v[2]:
#                        value = value
#                    else:
#                        value = -value
#                else:
#                    assert(edge_start is v[2])
#                    if edge_end is v[0]:
#                        value = value
#                    else:
#                        value = -value
#
##                tv.append([edge,value])
#                edge_face_incidence[fi,ej] = value
#        return edge_face_incidence
#    def buildExteriorDerivative1Form(mesh, faceIndex, edgeIndex):
#        """
#        Build a sparse matrix encoding the exterior derivative on 1-forms.
#        Returns a sparse matrix.
#
#        See section 3.6 of the course notes for an explanation of DEC.
#        """
#        edge_face_incidence = np.zeros((mesh.nfaces,mesh.nedges),float)
#        for face in mesh.faces:
#            fi = faceIndex[face]
#            #v = list(face.adjacentVerts()) #0,1,2
#            #tv = []
#            for he in face.adjacentHalfEdges():
#                ej = edgeIndex[he.edge]
#                #value = he.orientationSign
#                #tv.append([edge,value])
#                if he is he.edge.orientedHalfEdge:
#                    edge_face_incidence[fi,ej] =  1. #value
#                else:
#                    edge_face_incidence[fi,ej] = -1. #-value
#
#        #return edge_face_incidence
#        return csr_matrix( edge_face_incidence )

#    def decomposeField(mesh):
#        """
#        Decompose a covector in to exact, coexact, and harmonic components
#
#        The input mesh will have a scalar named 'omega' on its edges (edge.omega)
#        representing a discretized 1-form. This method should apply Helmoltz-Hodge
#        decomposition algorithm (as described on page 107-108 of the course notes)
#        to compute the exact, coexact, and harmonic components of omega.
#
#        This method should return its results by storing three new scalars on each edge,
#        as the 3 decomposed components: edge.exactComponent, edge.coexactComponent,
#        and edge.harmonicComponent.
#
#        Here are the primary steps you will need to perform for this method:
#
#            - Create indexer objects for the vertices, faces, and edges. Note that the mesh
#              has handy helper functions pre-defined
#              for each of these: mesh.enumerateEdges() etc.
#
#            - Build all of the operators we will need using
#              the methods you implemented above:
#                  hodge0, hodge1, hodge2, d0, and d1.
#              You should also compute their inverses and
#                  transposes, as appropriate.
#
#            - Build a vector which represents the input covector (from the edge.omega values)
#
#            - Perform a linear solve for the exact component, as described in the algorithm
#
#            - Perform a linear solve for the coexact component, as described in the algorithm
#
#            - Compute the harmonic component as the part which is neither exact nor coexact
#
#            - Store your resulting exact, coexact, and harmonic components on the mesh edges
#
#        This method will be called by the assignment code, you do not need to call it yourself.
#        """
#
#        """1)Create indexer objects for the vertices, faces, and edges. Note that the mesh
#              has handy helper functions pre-defined for each of these: mesh.enumerateEdges() etc. """
#
#        t0master = time.time()
#        edgeIndex   = mesh.enumerateEdges
#        vertexIndex = mesh.enumerateVertices
#        faceIndex   = mesh.enumerateFaces
#
#        """2)Build all of the operators we will need using the methods you implemented above:
#              hodge0, hodge1, hodge2, d0, and d1. You should also compute their inverses and
#              transposes, as appropriate."""
#        hodge0  = mesh.buildHodgeStar0Form(vertexIndex)
#        ihodge0 = diagonalInverse(hodge0)
#        hodge1  = mesh.buildHodgeStar1Form( edgeIndex)
#        #hodge2  = buildHodgeStar2Form(mesh, faceIndex)
#        ihodge1 = diagonalInverse(hodge1)
#        #ihodge2 = diagonalInverse(hodge2)
#        d0  = mesh.buildExteriorDerivative0Form(
#                                           edgeIndex=edgeIndex,
#                                           vertexIndex=vertexIndex)
#        d0T = d0.T
#        d1  = mesh.buildExteriorDerivative1Form(
#                                           faceIndex=faceIndex,
#                                           edgeIndex=edgeIndex)
#        d1T = d1.T
#
#
#        print 'shape d0 = ',np.shape(d0)
#        print 'shape d1 = ',np.shape(d1)
#        #print 'shape hodge0 = ',np.shape(hodge0)
#        print 'shape hodge1 = ',np.shape(hodge1)
#        #print 'shape hodge2 = ',np.shape(hodge2)
#
#
#
#        omega = np.zeros((mesh.nedges),float)
#        for edge in mesh.edges:
#            i = edgeIndex[edge]
#            omega[i] = edge.omega
#
#        #solve system 1 for d alpha
#        # page 117-118-119
#        # scipy.linalg.cholesky
#        print 'system 1, alpha'
#        print 'build LHS...'
#        #LHS = np.matmul(d0T,
#        #             np.matmul(hodge1,d0))
#        t0 = time.time()
#        LHS = np.dot(ihodge0,
#                     d0T.dot(hodge1))
#        ss = np.shape(LHS)[0]
#        LHS = csr_matrix(LHS)
#        LHS = LHS.dot(d0)
#        LHS = LHS + (1.e-8 * csr_matrix(np.identity(ss,float)))
#        #llt = scipy.linalg.cholesky(LHS,lower=True)
#        tSolve = time.time() - t0
#        print("...sparse alpha LHS completed.")
#        print("alpha LHS build took {:.5f} seconds.".format(tSolve))
#        print 'build RHS...'
#        #RHS = np.matmul(d0T,
#        #             np.matmul(hodge1,omega))
#        RHS = np.dot(ihodge0,
#                     d0T.dot(hodge1.dot(omega))
#                     )
#        print 'type RHS = ',type(RHS)
#        print 'solve'
#        #alpha = np.linalg.solve(LHS,RHS)
#        alpha = dsolve.spsolve(LHS, RHS ,
#                               use_umfpack=True)
#        #alpha = scipy.sparse.linalg.cg(llt,RHS)
#        #alpha = dsolve.spsolve(csr_matrix(llt), RHS ,
#        #                       use_umfpack=True)
#
#        print 'solve complete, alpha complete'
#
#
#
#
#        #solve system 2 for delta Beta
#        # page 117-118-119
#        # scipy.linalg.lu
#        print 'system 2, Beta'
#        print 'build LHS...'
#        #LHS = np.matmul(d1,
#        #             np.matmul(ihodge1,d1T))
#        t0 = time.time()
#        LHS = d1.dot(ihodge1)
#
#        #ss = np.shape(LHS)[0]
#
#        LHS = csr_matrix(LHS)
#        LHS = LHS.dot(d1T)
#
#        #LHS = csr_matrix(LHS)
#        LHS = LHS #+ 1.e-8 * csr_matrix(np.identity(ss,float))
#
#        tSolve = time.time() - t0
#        print("...sparse Beta LHS build completed.")
#        print("Beta LHS build took {:.5f} seconds.".format(tSolve))
#        print 'build RHS...'
#        #RHS = np.matmul(d1,omega)
#        RHS = d1.dot(omega)
#        print 'solve'
#        #Beta = np.linalg.solve(LHS,RHS)
#        Beta = dsolve.spsolve(LHS, RHS ,
#                               use_umfpack=True)
#        #        print 'solve complete, transform'
#        #        Beta = np.dot(ihodge2,Beta)
#        #        print 'transform complete, Beta complete'
#        #
#        # store exact, coexact, harmonic components on the mesh edges.
#        print 'decomposition field to mesh'
#
#
#        print 'Now push alpha and Beta into 1 forms'
#        # now push alpha to a 1 form using d:
#        alpha = d0.dot(alpha)
#        """  Say we start with a primal 2-form on a primal face.
#        Applying the star operator takes us to a dual 0-form on a dual vertex.
#        Taking the differential getsus to a dual 1-form on a dual edge.
#        And finally, another star operator
#        brings us to a primal 1-formon a primal edge."""
#        #now pull back to a 1 form using the codifferential *d*
#        # *d* Beta => *d0*
#        #Beta = np.dot(hodge0,
#        #              np.dot(d0,
#        #              np.dot(hodge2,Beta)))
#        # the easy way:
#        Beta = d1T.dot(Beta)
#        print 'solve complete, transform'
#        Beta = np.dot(ihodge1,Beta)
#        print 'transform complete, Beta complete'
#
#        #Beta = np.zeros_like(alpha)
#        for edge in mesh.edges:
#            i = edgeIndex[edge]
#            edge.exactComponent    = alpha[i]
#            edge.coexactComponent  = Beta [i]
#            edge.harmonicComponent = omega[i] - (alpha[i] + Beta[i])
#            #edge.harmonicComponent = omega[i] - (Beta[i])
#        print 'decomposition complete'
#
#        tSolve = time.time() - t0master
#        print("...Decomposition completed.")
#        print("Total Time {:.5f} seconds.".format(tSolve))

    def enumerateVertices(mesh):
        """
        Assign a unique index from 0 to (N-1) to each vertex in the mesh. Should
        return a dictionary containing mappings {vertex ==> index}.

        You will want to use this function in your solutions below.
        """
        #        index_map = {}
        #        index = 0
        #        for vv in mesh.verts:
        #            index_map[vv] = index
        #            index += 1
        return mesh.enumerateVertices

    @property
    @cacheGeometry
    def adjacency(self):
        index_map = enumerateVertices(self)
        nrows = ncols = len(mesh.verts)
        adjacency = np.zeros((nrows, ncols), int)
        for vv in mesh.verts:
            ith = index_map[vv]
            avlist = list(vv.adjacentVerts())
            for av in avlist:
                jth = index_map[av]
                adjacency[ith, jth] = 1
        return adjacency

    #################################
    # Part 1: Dense Poisson Problem #
    #################################
    # Solve a Poisson problem on the mesh. The primary function here
    # is solvePoissonProblem_dense(), it will get called when you run
    #   python Assignment3.py part1 /path/to/your/mesh.obj
    # and specify density values with the mouse (the press space to solve).
    #
    # Note that this code will be VERY slow on large meshes, because it uses
    # dense matrices.

    def buildLaplaceMatrix_sparse(mesh, index_map=None):
        """
        Build a Laplace operator for the mesh, with a dense representation

        'index' is a dictionary mapping {vertex ==> index}
        TLM renamed to index_map

        Returns the resulting matrix.
        """
        if index_map is None:
            index_map = mesh.enumerateVertices()

        nrows = ncols = len(mesh.verts)
        #        adjacency = np.zeros((nrows,ncols),int)
        #        for vv in mesh.verts:
        #            ith = index_map[vv]
        #            avlist = list(vv.adjacentVerts())
        #            for av in avlist:
        #                jth = index_map[av]
        #                adjacency[ith,jth] = 1

        Laplacian = np.zeros((nrows, ncols), float)
        for vi in mesh.verts:
            ith = index_map[vi]
            ll = list(vi.adjacentEdgeVertexPairs())
            for edge, vj in ll:
                jth = index_map[vj]
                #                Laplacian[ith,jth] = np.dot(vj.normal,
                #                                             edge.cotanWeight*(vj.position -
                #                                                       vi.position)
                #                                             )
                w1 = edge.anyHalfEdge.cotan
                w2 = edge.anyHalfEdge.twin.cotan
                W = .5 * (w1 + w2)
                #W = edge.cotanWeight
                if ith == jth:
                    pass
                else:
                    Laplacian[ith, jth] = W

            Laplacian[ith, ith] = -(sum(Laplacian[ith]))  #+ 1.e-8)

        return csr_matrix(Laplacian)

    def buildMassMatrix_dense(mesh, index):
        """
        Build a mass matrix for the mesh.

        Returns the resulting matrix.
        """
        nrows = ncols = len(mesh.verts)

        #MassMatrix = np.zeros((nrows),float)
        MassMatrix = np.zeros((nrows, ncols), float)
        for vert in mesh.verts:
            i = index[vert]
            #MassMatrix[i,i] = 1./vert.dualArea
            MassMatrix[i, i] = vert.barycentricDualArea
            #MassMatrix[i,i] = vert.circumcentricDualArea

        return MassMatrix

    def solvePoisson(mesh, densityValues):
        """
        Solve a Poisson problem on the mesh. The results should be stored on the
        vertices in a variable named 'solutionVal'. You will want to make use
        of your buildLaplaceMatrix_dense() function from above.

        densityValues is a dictionary mapping {vertex ==> value} that specifies
        densities. The density is implicitly zero at every vertex not in this
        dictionary.

        When you run this program with 'python Assignment3.py part1 path/to/your/mesh.obj',
        you will get to click on vertices to specify density conditions. See the
        assignment document for more details.
        """
        index_map = mesh.enumerateVertices
        L = buildLaplaceMatrix_sparse(mesh, index_map)
        M = buildMassMatrix_dense(mesh, index_map)  #M <= 2D
        totalArea = mesh.totalArea

        rho = np.zeros((len(mesh.verts), 1), float)
        for key in densityValues:
            #index_val = index_map[key]
            print 'key dual area = ', key.barycentricDualArea
            rho[index_map[key]] = densityValues[key]  #*key.dualArea

        nRows, nCols = np.shape(M)
        totalRho = sum(M.dot(rho))
        #rhoBar = np.ones((nRows,1),float)*(totalRho/totalArea)
        rhoBar = totalRho / totalArea
        rhs = M.dot(rhoBar - rho)
        #rhs = np.matmul(M,(rho-rhoBar) )
        #rhs = np.dot(M,rho)
        #
        # SwissArmyLaplacian,
        #   page 179 Cu = Mf is better conditioned
        # assert(Cu == L) ??
        #sol_vec = np.linalg.solve(L, np.dot(M,rho) )

        #sparse:
        #sol_vec = dsolve.spsolve(L, np.dot(M,rho) , use_umfpack=True)
        # standard:
        #sol_vec = dsolve.spsolve(L, rhs , use_umfpack=True)

        #sparse Cholesky solve:
        llt = skchol.cholesky_AAt(L)  #factor
        sol_vec = llt(rhs)

        #eigen:
        #sol_vec = np.zeros((nRows),float)
        #scipy.sparse.linalg.lobpcg(L,sol_vec,rhs) #@eigensolver

        #sol_vec = dsolve.spsolve(L, rho , use_umfpack=True)
        vert_sol = {}
        for vert in mesh.verts:
            key = index_map[vert]
            #print 'TLM sol_vec = ',sol_vec[key]
            vert.solutionVal = sol_vec[key]
            vert_sol[vert] = sol_vec[key]
            if rho[key]:
                vert.densityVal = rho[key]
            else:
                vert.densityVal = 0.

        return vert_sol

    ###################### END YOUR CODE

    ### More prep functions
    def generateFieldConstant(mesh):
        print("\n=== Using constant field as arbitrary direction field")
        for vert in mesh.verts:
            vert.vector = vert.projectToTangentSpace(Vector3D(1.4, 0.2, 2.4))

    def generateFieldSimple(mesh):
        for face in mesh.faces:
            face.vector = face.center + Vector3D(
                -face.center[2], face.center[1], face.center[0])
            face.vector = face.projectToTangentSpace(face.vector)

    def gradFromPotential(mesh, potAttr, gradAttr):
        # Simply compute gradient from potential
        for vert in mesh.verts:
            sumVal = Vector3D(0.0, 0.0, 0.0)
            sumWeight = 0.0
            vertVal = getattr(vert, potAttr)
            for he in vert.adjacentHalfEdges():
                sumVal += he.edge.cotanWeight * (getattr(he.vertex, potAttr) -
                                                 vertVal) * he.vector
                sumWeight += he.edge.cotanWeight
            setattr(vert, gradAttr, normalize(sumVal))

    def generateInterestingField(mesh, divscale=1., curlscale=1.):
        print(
            "\n=== Generating a hopefully-interesting field which has all three types of components\n"
        )

        # Somewhat cheesy hack:
        # We want this function to generate the exact same result on repeated runs of the program to make
        # debugging easier. This means ensuring that calls to random.sample() return the exact same result
        # every time. Normally we could just set a seed for the RNG, and this work work if we were sampling
        # from a list. However, mesh.verts is a set, and Python does not guarantee consistency of iteration
        # order between runs of the program (since the default hash uses the memory address, which certainly
        # changes). Rather than doing something drastic like implementing a custom hash function on the
        # mesh class, we'll just build a separate data structure where vertices are sorted by position,
        # which allows reproducible sampling (as long as positions are distinct).
        sortedVertList = list(mesh.verts)
        sortedVertList.sort(
            key=lambda x: (x.position[0], x.position[1], x.position[2]))
        random.seed(100)

        # Generate curl-free (ish) component
        curlFreePotentialVerts = random.sample(
            sortedVertList, max((2, len(mesh.verts) / 1000)))
        potential = divscale
        bVals = {}
        for vert in curlFreePotentialVerts:
            bVals[vert] = potential
            potential *= -1.
        smoothPotential = solvePoisson(mesh, bVals)
        mesh.applyVertexValue(smoothPotential, "curlFreePotential")
        gradFromPotential(mesh, "curlFreePotential", "curlFreeVecGen")

        # Generate divergence-free (ish) component
        divFreePotentialVerts = random.sample(sortedVertList,
                                              max((2, len(mesh.verts) / 1000)))
        potential = curlscale
        bVals = {}
        for vert in divFreePotentialVerts:
            bVals[vert] = potential
            potential *= -1.
        smoothPotential = solvePoisson(mesh, bVals)
        mesh.applyVertexValue(smoothPotential, "divFreePotential")
        gradFromPotential(mesh, "divFreePotential", "divFreeVecGen")
        for vert in mesh.verts:
            normEu = eu.Vector3(*vert.normal)
            vecEu = eu.Vector3(*vert.divFreeVecGen)
            vert.divFreeVecGen = vecEu.rotate_around(
                normEu, pi / 2.0)  # Rotate the field by 90 degrees

        # Combine the components
        for face in mesh.faces:
            face.vector = Vector3D(0.0, 0.0, 0.0)
            for vert in face.adjacentVerts():
                face.vector = 1.0 * vert.curlFreeVecGen + 1.0 * vert.divFreeVecGen

            face.vector = face.projectToTangentSpace(face.vector)

        # clear out leftover attributes to not confuse people
        for vert in mesh.verts:
            del vert.curlFreeVecGen
            del vert.curlFreePotential
            del vert.divFreeVecGen
            del vert.divFreePotential

    # Verify the orientations were defined. Need to do this early, since they are needed for setup
    def checkOrientationDefined(mesh):
        """Verify that edges have oriented halfedges and halfedges have orientation signs"""

        for edge in mesh.edges:
            if not hasattr(edge, 'orientedHalfEdge'):
                print(
                    "ERROR: Edges do not have orientedHalfEdge defined. Cannot proceed"
                )
                exit()
        for he in mesh.halfEdges:
            if not hasattr(he, 'orientationSign'):
                print(
                    "ERROR: halfedges do not have orientationSign defined. Cannot proceed"
                )
                exit()

    # Verify the correct properties are defined after the assignment is run
    def checkResultTypes(mesh):

        for edge in mesh.edges:
            # Check exact
            if not hasattr(edge, 'exactComponent'):
                print(
                    "ERROR: Edges do not have edge.exactComponent defined. Cannot proceed"
                )
                exit()
            if not isinstance(edge.exactComponent, float):
                print(
                    "ERROR: edge.exactComponent is defined, but has the wrong type. Type is "
                    + str(type(edge.exactComponent)) +
                    " when if should be 'float'")
                exit()

            # Check cocoexact
            if not hasattr(edge, 'coexactComponent'):
                print(
                    "ERROR: Edges do not have edge.coexactComponent defined. Cannot proceed"
                )
                exit()
            if not isinstance(edge.coexactComponent, float):
                print(
                    "ERROR: edge.coexactComponent is defined, but has the wrong type. Type is "
                    + str(type(edge.coexactComponent)) +
                    " when if should be 'float'")
                exit()

            # Check harmonic
            if not hasattr(edge, 'harmonicComponent'):
                print(
                    "ERROR: Edges do not have edge.harmonicComponent defined. Cannot proceed"
                )
                exit()
            if not isinstance(edge.harmonicComponent, float):
                print(
                    "ERROR: edge.harmonicComponent is defined, but has the wrong type. Type is "
                    + str(type(edge.harmonicComponent)) +
                    " when if should be 'float'")
                exit()

    # Visualization related
    def covectorToFaceVectorWhitney(mesh, covectorName, vectorName):
        """lookout wedge below! (tlm)
        
        this code is okay because it is able to show the initial 
        vector field correctly.
        """
        for face in mesh.faces:
            pi = face.anyHalfEdge.vertex.position
            pj = face.anyHalfEdge.next.vertex.position
            pk = face.anyHalfEdge.next.next.vertex.position
            eij = pj - pi
            ejk = pk - pj
            eki = pi - pk
            N = cross(eij, -eki)
            A = 0.5 * norm(N)
            N /= 2 * A
            wi = getattr(face.anyHalfEdge.edge,
                         covectorName) * face.anyHalfEdge.orientationSign
            wj = getattr(face.anyHalfEdge.next.edge,
                         covectorName) * face.anyHalfEdge.next.orientationSign
            wk = getattr(
                face.anyHalfEdge.next.next.edge,
                covectorName) * face.anyHalfEdge.next.next.orientationSign
            #s = (1.0 / (6.0 * A)) * cross(N, wi*(eki-ejk) + wj*(eij-eki) + wk*(ejk-eij))
            s = (1.0 / (6.0 * A)) * cross(
                N,
                wi * (ejk - eij) + wj * (eki - ejk) + wk * (eij - eki))

            setattr(face, vectorName, s)
        return

    # Visualization related
    def covectorToFaceVectorWhitneyJS(mesh, covectorName, vectorName):
        """lookout wedge below! (tlm)
        """
        edgeIndex = mesh.enumerateEdges
        for face in mesh.faces:
            h = face.anyHalfEdge

            pi = h.vertex.position
            pj = h.next.vertex.position
            pk = h.next.next.vertex.position
            eij = pj - pi
            ejk = pk - pj
            eki = pi - pk

            #cij =
            #if h.edge.anyHalfEdge is not h:
            #   cij *= -1.

            wij = getattr(face.anyHalfEdge.edge,
                          covectorName)  #* face.anyHalfEdge.orientationSign
            wjk = getattr(
                face.anyHalfEdge.next.edge,
                covectorName)  #* face.anyHalfEdge.next.orientationSign
            wki = getattr(
                face.anyHalfEdge.next.next.edge,
                covectorName)  #* face.anyHalfEdge.next.next.orientationSign
            if h.edge.anyHalfEdge is not h:
                wij *= -1
            if h.next.edge.anyHalfEdge is not h:
                wjk *= -1
            if h.next.next.edge.anyHalfEdge is not h:
                wki *= -1

            #N = cross(eij, -eki)
            #A = 0.5 * norm(N)
            #N /= 2*A
            A = face.area
            N = face.normal
            #
            a = (eki - ejk) * wij
            b = (eij - eki) * wjk
            c = (ejk - eij) * wki

            #pystyle
            #a=wij*(ejk-eij)
            #b=wjk*(eki-ejk)
            #c=wki*(eij-eki)

            #s = (1.0 / (6.0 * A)) * cross(N, wij*(eki-ejk) + wjk*(eij-eki) + wki*(ejk-eij))
            #s = (1.0 / (6.0 * A)) * cross(N, wij*(ejk-eij) + wjk*(eki-ejk) + wki*(eij-eki))
            s = cross(N, (a + b + c)) * (1. / (6. * A))
            setattr(face, vectorName, s)

    def flat(mesh, vectorFieldName, oneFormName):
        """
        Given a vector field defined on faces, compute the corresponding (integrated) 1-form 
        on edges.
        """

        for edge in mesh.edges:

            oe = edge.orientedHalfEdge

            if not oe.isReal:
                val2 = getattr(edge.orientedHalfEdge.twin.face,
                               vectorFieldName)
                meanVal = val2
            elif not oe.twin.isReal:
                val1 = getattr(edge.orientedHalfEdge.face, vectorFieldName)
                meanVal = val1
            else:
                val1 = getattr(edge.orientedHalfEdge.face, vectorFieldName)
                val2 = getattr(edge.orientedHalfEdge.twin.face,
                               vectorFieldName)
                meanVal = 0.5 * (val1 + val2)

            setattr(edge, oneFormName,
                    dot(edge.orientedHalfEdge.vector, meanVal))

    ### Actual main method:

    # get ready
    mesh.assignEdgeOrientations()
    checkOrientationDefined(mesh)

    # Generate a vector field on the surface
    if simpleTest:
        generateFieldSimple(mesh)
        #generateFieldConstant(mesh)
    else:
        generateInterestingField(mesh, divscale=1., curlscale=1.)

    flat(mesh, 'vector', 'omega')

    # Apply the decomposition from this assignment
    print("\n=== Decomposing field in to components")
    #decomposeField(mesh)
    #hd = HodgeDecomposition(mesh)
    mesh.HodgeDecomposition()
    mesh.hodgeDecomposition.decomposeField()
    print("=== Done decomposing field ===\n\n")

    # Verify everything necessary is dfined for the output
    checkResultTypes(mesh)
    #
    # Convert the covectors to face vectors for visualization
    covectorToFaceVectorWhitney(mesh, "exactComponent",
                                "omega_exact_component")
    covectorToFaceVectorWhitney(mesh, "coexactComponent",
                                "omega_coexact_component")
    covectorToFaceVectorWhitney(mesh, "harmonicComponent",
                                "omega_harmonic_component")
    covectorToFaceVectorWhitney(mesh, "omega", "omega_original")
    #
    #
    # Register a vector toggle to switch between the vectors we just defined
    vectorList = [{
        'vectorAttr': 'omega_original',
        'key': '1',
        'colormap': 'Spectral',
        'vectorDefinedAt': 'face'
    }, {
        'vectorAttr': 'omega_exact_component',
        'key': '2',
        'colormap': 'Blues',
        'vectorDefinedAt': 'face'
    }, {
        'vectorAttr': 'omega_coexact_component',
        'key': '3',
        'colormap': 'Reds',
        'vectorDefinedAt': 'face'
    }, {
        'vectorAttr': 'omega_harmonic_component',
        'key': '4',
        'colormap': 'Greens',
        'vectorDefinedAt': 'face'
    }]
    meshDisplay.registerVectorToggleCallbacks(vectorList)

    print 'Computing Tree Cotree decomposition'
    mesh.TreeCotree()
    print 'Computing Tree Cotree generators'
    mesh.TreeCotree_compute_generators()
    print 'Plot Tree Cotree generators'
    mesh.setup_TreeCotree_plot()
    #    meshDisplay.registerVectorToggleCallbacks(
    #                    [{'vectorAttr':'g1',
    #                      'key':'5',
    #                      'colormap':'Oranges',
    #                     'vectorDefinedAt':'face'},
    #                    {'vectorAttr':'g2',
    #                      'key':'6',
    #                      'colormap':'Oranges',
    #                     'vectorDefinedAt':'face'}])

    # Start the GUI
    if show:
        meshDisplay.startMainLoop()

    return mesh, meshDisplay