def _loadData(self):
     """
     Load zinc data file into self._rawDataRegion.
     Rename data groups to exactly match model groups where they differ by case and whitespace only.
     Transfer data points (and converted nodes) into self._region.
     """
     result = self._rawDataRegion.readFile(self._zincDataFileName)
     assert result == RESULT_OK, "Failed to load data file " + str(
         self._zincDataFileName)
     fieldmodule = self._rawDataRegion.getFieldmodule()
     with ChangeManager(fieldmodule):
         # rename data groups to match model
         # future: match with annotation terms
         modelGroupNames = [
             group.getName() for group in getGroupList(self._fieldmodule)
         ]
         writeDiagnostics = self.getDiagnosticLevel() > 0
         for dataGroup in getGroupList(fieldmodule):
             dataGroupName = dataGroup.getName()
             compareName = dataGroupName.strip().casefold()
             for modelGroupName in modelGroupNames:
                 if modelGroupName == dataGroupName:
                     if writeDiagnostics:
                         print("Load data: Data group '" + dataGroupName +
                               "' found in model")
                     break
                 elif modelGroupName.strip().casefold() == compareName:
                     result = dataGroup.setName(modelGroupName)
                     if result == RESULT_OK:
                         if writeDiagnostics:
                             print("Load data: Data group '" +
                                   dataGroupName + "' found in model as '" +
                                   modelGroupName + "'. Renaming to match.")
                     else:
                         print("Error: Load data: Data group '" +
                               dataGroupName + "' found in model as '" +
                               modelGroupName +
                               "'. Renaming to match FAILED.")
                         if fieldmodule.findFieldByName(
                                 modelGroupName).isValid():
                             print(
                                 "    Reason: field of that name already exists."
                             )
                     break
             else:
                 if writeDiagnostics:
                     print("Load data: Data group '" + dataGroupName +
                           "' not found in model")
         # if there are both nodes and datapoints, offset datapoint identifiers to ensure different
         nodes = fieldmodule.findNodesetByFieldDomainType(
             Field.DOMAIN_TYPE_NODES)
         if nodes.getSize() > 0:
             datapoints = fieldmodule.findNodesetByFieldDomainType(
                 Field.DOMAIN_TYPE_DATAPOINTS)
             if datapoints.getSize() > 0:
                 maximumDatapointIdentifier = max(
                     0, getMaximumNodeIdentifier(datapoints))
                 maximumNodeIdentifier = max(
                     0, getMaximumNodeIdentifier(nodes))
                 # this assumes identifiers are in low ranges and can be improved if there is a problem:
                 identifierOffset = 100000
                 while (maximumDatapointIdentifier > identifierOffset) or (
                         maximumNodeIdentifier > identifierOffset):
                     assert identifierOffset < 1000000000, "Invalid node and datapoint identifier ranges"
                     identifierOffset *= 10
                 while True:
                     # logic relies on datapoints being in identifier order
                     datapoint = datapoints.createNodeiterator().next()
                     identifier = datapoint.getIdentifier()
                     if identifier >= identifierOffset:
                         break
                     result = datapoint.setIdentifier(identifier +
                                                      identifierOffset)
                     assert result == RESULT_OK, "Failed to offset datapoint identifier"
             # transfer nodes as datapoints to self._region
             sir = self._rawDataRegion.createStreaminformationRegion()
             srm = sir.createStreamresourceMemory()
             sir.setResourceDomainTypes(srm, Field.DOMAIN_TYPE_NODES)
             self._rawDataRegion.write(sir)
             result, buffer = srm.getBuffer()
             assert result == RESULT_OK, "Failed to write nodes"
             buffer = buffer.replace(bytes("!#nodeset nodes", "utf-8"),
                                     bytes("!#nodeset datapoints", "utf-8"))
             sir = self._region.createStreaminformationRegion()
             srm = sir.createStreamresourceMemoryBuffer(buffer)
             result = self._region.read(sir)
             assert result == RESULT_OK, "Failed to load nodes as datapoints"
     # transfer datapoints to self._region
     sir = self._rawDataRegion.createStreaminformationRegion()
     srm = sir.createStreamresourceMemory()
     sir.setResourceDomainTypes(srm, Field.DOMAIN_TYPE_DATAPOINTS)
     self._rawDataRegion.write(sir)
     result, buffer = srm.getBuffer()
     assert result == RESULT_OK, "Failed to write datapoints"
     sir = self._region.createStreaminformationRegion()
     srm = sir.createStreamresourceMemoryBuffer(buffer)
     result = self._region.read(sir)
     assert result == RESULT_OK, "Failed to load datapoints"
     self._discoverDataCoordinatesField()
     self._discoverMarkerGroup()
    def calculateDataProjections(self, fitterStep: FitterStep):
        """
        Find projections of datapoints' coordinates onto model coordinates,
        by groups i.e. from datapoints group onto matching 2-D or 1-D mesh group.
        Calculate and store projection direction unit vector.
        """
        assert self._dataCoordinatesField and self._modelCoordinatesField
        activeFitterStepConfig = self.getActiveFitterStepConfig(fitterStep)
        with ChangeManager(self._fieldmodule):
            findMeshLocation = None
            datapoints = self._fieldmodule.findNodesetByFieldDomainType(
                Field.DOMAIN_TYPE_DATAPOINTS)
            fieldcache = self._fieldmodule.createFieldcache()
            for d in range(2):
                self._dataProjectionNodesetGroups[d].removeAllNodes()
            groups = getGroupList(self._fieldmodule)
            for group in groups:
                groupName = group.getName()
                dataGroup = group.getFieldNodeGroup(
                    datapoints).getNodesetGroup()
                if not dataGroup.isValid():
                    continue
                for dimension in range(2, 0, -1):
                    meshGroup = group.getFieldElementGroup(
                        self._mesh[dimension - 1]).getMeshGroup()
                    if meshGroup.isValid() and (meshGroup.getSize() > 0):
                        break
                else:
                    if self.getDiagnosticLevel() > 0:
                        if group != self._markerGroup:
                            print("Warning: Cannot project data for group " +
                                  groupName + " as no matching mesh group")
                    continue
                meshLocation = self._dataProjectionLocationFields[dimension -
                                                                  1]
                dataProjectionNodesetGroup = self._dataProjectionNodesetGroups[
                    dimension - 1]
                nodeIter = dataGroup.createNodeiterator()
                node = nodeIter.next()
                fieldcache.setNode(node)
                if not self._dataCoordinatesField.isDefinedAtLocation(
                        fieldcache):
                    if self.getDiagnosticLevel() > 0:
                        print("Warning: Cannot project data for group " +
                              groupName + " as field " +
                              self._dataCoordinatesField.getName() +
                              " is not defined on data")
                    continue
                if not meshLocation.isDefinedAtLocation(fieldcache):
                    # define meshLocation and dataProjectionDirectionField on data Group:
                    nodetemplate = datapoints.createNodetemplate()
                    nodetemplate.defineField(meshLocation)
                    nodetemplate.defineField(
                        self._dataProjectionDirectionField)
                    while node.isValid():
                        result = node.merge(nodetemplate)
                        #print("node",node.getIdentifier(),"result",result)
                        node = nodeIter.next()
                    del nodetemplate
                self.calculateGroupDataProjections(fieldcache, group,
                                                   dataGroup, meshGroup,
                                                   meshLocation,
                                                   activeFitterStepConfig)

            # Store data projection directions
            for dimension in range(1, 3):
                nodesetGroup = self._dataProjectionNodesetGroups[dimension - 1]
                if nodesetGroup.getSize() > 0:
                    fieldassignment = self._dataProjectionDirectionField.createFieldassignment(
                        self._fieldmodule.createFieldNormalise(
                            self._dataProjectionDeltaFields[dimension - 1]))
                    fieldassignment.setNodeset(nodesetGroup)
                    result = fieldassignment.assign()
                    assert result in [ RESULT_OK, RESULT_WARNING_PART_DONE ], \
                        "Error:  Failed to assign data projection directions for dimension " + str(dimension)
                    del fieldassignment

            if self.getDiagnosticLevel() > 0:
                # Warn about unprojected points
                unprojectedDatapoints = self._fieldmodule.createFieldNodeGroup(
                    datapoints).getNodesetGroup()
                unprojectedDatapoints.addNodesConditional(
                    self._fieldmodule.createFieldIsDefined(
                        self._dataCoordinatesField))
                for d in range(2):
                    unprojectedDatapoints.removeNodesConditional(
                        self._dataProjectionNodeGroupFields[d])
                unprojectedCount = unprojectedDatapoints.getSize()
                if unprojectedCount > 0:
                    print(
                        "Warning: " + str(unprojectedCount) +
                        " data points with data coordinates have not been projected"
                    )
                del unprojectedDatapoints

            # remove temporary objects before ChangeManager exits
            del fieldcache
Beispiel #3
0
    def calculateDataProjections(self):
        """
        Find projections of datapoints' coordinates onto model coordinates,
        by groups i.e. from datapoints group onto matching 2-D or 1-D mesh group.
        Calculate and store projection direction unit vector.
        """
        assert self._dataCoordinatesField and self._modelCoordinatesField
        with ChangeManager(self._fieldmodule):
            findMeshLocation = None
            datapoints = self._fieldmodule.findNodesetByFieldDomainType(
                Field.DOMAIN_TYPE_DATAPOINTS)
            fieldcache = self._fieldmodule.createFieldcache()
            for d in range(2):
                self._dataProjectionNodesetGroups[d].removeAllNodes()
            groups = getGroupList(self._fieldmodule)
            for group in groups:
                groupName = group.getName()
                dataGroup = group.getFieldNodeGroup(
                    datapoints).getNodesetGroup()
                if not dataGroup.isValid():
                    continue
                for dimension in range(2, 0, -1):
                    meshGroup = group.getFieldElementGroup(
                        self._mesh[dimension - 1]).getMeshGroup()
                    if meshGroup.isValid() and (meshGroup.getSize() > 0):
                        break
                else:
                    if self.getDiagnosticLevel() > 0:
                        print(
                            "Fit Geometry:  Warning: Cannot project data for group "
                            + groupName + " as no matching mesh group")
                    continue
                meshLocation = self._dataProjectionLocationFields[dimension -
                                                                  1]
                dataProjectionNodesetGroup = self._dataProjectionNodesetGroups[
                    dimension - 1]
                nodeIter = dataGroup.createNodeiterator()
                node = nodeIter.next()
                fieldcache.setNode(node)
                if not self._dataCoordinatesField.isDefinedAtLocation(
                        fieldcache):
                    if self.getDiagnosticLevel() > 0:
                        print(
                            "Fit Geometry:  Warning: Cannot project data for group "
                            + groupName + " as field " +
                            self._dataCoordinatesField.getName() +
                            " is not defined on data")
                    continue
                if not meshLocation.isDefinedAtLocation(fieldcache):
                    # define meshLocation and on data Group:
                    nodetemplate = datapoints.createNodetemplate()
                    nodetemplate.defineField(meshLocation)
                    nodetemplate.defineField(
                        self._dataProjectionDirectionField)
                    while node.isValid():
                        result = node.merge(nodetemplate)
                        #print("node",node.getIdentifier(),"result",result)
                        node = nodeIter.next()
                    del nodetemplate
                    # restart iteration
                    nodeIter = dataGroup.createNodeiterator()
                    node = nodeIter.next()
                findMeshLocation = self._fieldmodule.createFieldFindMeshLocation(
                    self._dataCoordinatesField, self._modelCoordinatesField,
                    meshGroup)
                findMeshLocation.setSearchMode(
                    FieldFindMeshLocation.SEARCH_MODE_NEAREST)
                while node.isValid():
                    fieldcache.setNode(node)
                    element, xi = findMeshLocation.evaluateMeshLocation(
                        fieldcache, dimension)
                    if not element.isValid():
                        print(
                            "Fit Geometry:  Error finding data projection nearest mesh location for group "
                            + groupName + ". Aborting group.")
                        break
                    result = meshLocation.assignMeshLocation(
                        fieldcache, element, xi)
                    #print(result, "node", node.getIdentifier(), "element", element.getIdentifier(), "xi", xi)
                    #if result != RESULT_OK:
                    #    mesh = meshLocation.getMesh()
                    #    print("--> mesh", mesh.isValid(), mesh.getDimension(), findMeshLocation.getMesh().getDimension())
                    #    print("node", node.getIdentifier(), "is defined", meshLocation.isDefinedAtLocation(fieldcache))
                    assert result == RESULT_OK, "Fit Geometry:  Failed to assign data projection mesh location for group " + groupName
                    dataProjectionNodesetGroup.addNode(node)
                    node = nodeIter.next()

            # Store data projection directions
            for dimension in range(1, 3):
                nodesetGroup = self._dataProjectionNodesetGroups[dimension - 1]
                if nodesetGroup.getSize() > 0:
                    fieldassignment = self._dataProjectionDirectionField.createFieldassignment(
                        self._fieldmodule.createFieldNormalise(
                            self._dataProjectionDeltaFields[dimension - 1]))
                    fieldassignment.setNodeset(nodesetGroup)
                    result = fieldassignment.assign()
                    assert result in [ RESULT_OK, RESULT_WARNING_PART_DONE ], \
                        "Fit Geometry:  Failed to assign data projection directions for dimension " + str(dimension)

            if self.getDiagnosticLevel() > 0:
                # Warn about unprojected points
                unprojectedDatapoints = self._fieldmodule.createFieldNodeGroup(
                    datapoints).getNodesetGroup()
                unprojectedDatapoints.addNodesConditional(
                    self._fieldmodule.createFieldIsDefined(
                        self._dataCoordinatesField))
                for d in range(2):
                    unprojectedDatapoints.removeNodesConditional(
                        self._dataProjectionNodeGroupFields[d])
                unprojectedCount = unprojectedDatapoints.getSize()
                if unprojectedCount > 0:
                    print(
                        "Warning: " + str(unprojectedCount) +
                        " data points with data coordinates have not been projected"
                    )
                del unprojectedDatapoints

            # remove temporary objects before ChangeManager exits
            del findMeshLocation
            del fieldcache