def coregLoop(pointlist, ages, plateIDs):
    '''
    coregLoop

    This script reconstructs a shapefile of points to their birth time and 
    coregisters each point with another set of points, or a raster file.

    INPUTS:
    pointlist - list of lat/lon
    ages - list of ages corresponding to lat/lon point
    plateIDs - list of plateIDs corresponding to lat/lon point.

    Hardcoded filenames/variables must be changed below:
    input_rotation_filename - Rotation file 
    rasterfile - Time dependent raster files
    f - Time dependent kinemtic csv outputs from 'convergence.py'

    OUTPUTS:
    Coregistered array: List of lat/lons with properties.
    
    METHOD:
    Takes a set of points 
    Rotates the points back to their birth position
    Determines the point's birth position geophysical properties (coregisters)
    '''

    #Set up a list to store the data
    timeSteps = 1  # +- Myrs around point to store. Default 1 which means just the measured point age.
    noVariables = 18  #The number of variables you save
    Nshp = len(pointlist)

    coregData = numpy.zeros((Nshp, timeSteps, noVariables))

    #Create a rotation model to rotate the points back in time
    input_rotation_filename = "Muller_gplates/Global_EarthByte_230-0Ma_GK07_AREPS.rot"

    file_registry = pygplates.FeatureCollectionFileFormatRegistry()
    rotation_feature_collection = file_registry.read(input_rotation_filename)
    rotation_model = pygplates.RotationModel([rotation_feature_collection])

    #Loop over all the samples, coregistering each one.
    for i, currentPoint in enumerate(pointlist):

        lat = currentPoint[1]
        lon = currentPoint[0]
        age = ages[i]
        plateID = int(plateIDs[i])

        print("Deposit:", i, "of", Nshp, "Lat:", lat, "Lon:", lon, "Age:", age,
              "PlateID:", plateID)

        #Loop through each time step in the plate model
        for time in xrange(0, 230, 1):

            #If the point was formed at the current time (or [timeStepsMyr ] prior/after) then we
            #want to find the surrounding plate properties.
            #if  (time > (age-10)) and (time < (age+10)) or (time > (age+20)) and (time < (age+30)):
            if (time > (age - timeSteps)) and (time < (age + timeSteps)):
                t = int(numpy.floor(time - age))
                #print(t,time,age)

                #A raster file, to coregister with, these points have already been rotated
                rasterfile = "Muller_etal_2016_AREPS_Agegrids_v1.11/netCDF_0-230Ma/EarthByte_AREPS_v1.11_Muller_etal_2016_AgeGrid-" + str(
                    time) + ".nc"
                [x, y, z] = gridRead(rasterfile)

                #A vector file to coregister with, these points have already been rotated
                f = numpy.loadtxt("Muller_convergence/subStats_" + str(time) +
                                  ".csv",
                                  delimiter=',')
                lonlat = f[:, 0:2]

                #-------------------#
                #Reconstruct a point to its birth position
                #-------------------#
                latlonPoint = pygplates.LatLonPoint(lat, lon)
                point_to_rotate = pygplates.convert_lat_lon_point_to_point_on_sphere(
                    latlonPoint)

                finite_rotation = rotation_model.get_rotation(time, plateID)
                birthPosition = finite_rotation * point_to_rotate

                latlonBirth = pygplates.convert_point_on_sphere_to_lat_lon_point(
                    birthPosition)
                #allPoints = finite_rotation * pointSet_to_rotate

                latBirth = latlonBirth.get_latitude()
                lonBirth = latlonBirth.get_longitude()

                #-------------------#
                #Set the points for coregistering
                region = 5.0  #degrees

                #-------------------#
                #Coregisterring raster 1
                #-------------------#
                #Find the region in index units
                r = numpy.round(region / (x[1] - x[0]))

                #Find the index unit of lat and lon
                idxLon = (numpy.abs(x - lonBirth)).argmin()
                idxLat = (numpy.abs(y - latBirth)).argmin()

                #Raster 1
                c2 = coregRaster([idxLon, idxLat], z, r)
                #Hack to search further around the age grid if it can't find a match, note index units (not degrees)
                if numpy.isnan(c2):
                    c2 = coregRaster([idxLon, idxLat], z, r + 150.0)
                    print("Trying raster region: ", r + 150.0)

                #-------------------#
                #Coregisterring vector 1
                #-------------------#
                index = coregPoint([lonBirth, latBirth], lonlat, region)
                if index == 'inf':
                    print("trying index region", region + 15)
                    index = coregPoint([lonBirth, latBirth], lonlat,
                                       region + 15.0)

                if numpy.isnan(c2) or index == 'inf':
                    print("Skipping:", i, age, t, time, c2, index, lonBirth,
                          latBirth)

                else:
                    #Vector 1
                    segmentLength = f[index, 3]
                    slabLength = f[index, 9]
                    distSlabEdge = f[index, 15]

                    SPcoregNor = f[index, 4]
                    SPcoregPar = f[index, 12]
                    OPcoregNor = f[index, 5]
                    OPcoregPar = f[index, 13]
                    CONVcoregNor = f[index, 10]
                    CONVcoregPar = f[index, 11]

                    subPolCoreg = f[index, 8]
                    subOblCoreg = f[index, 7]
                    coregData[i, t, :] = [
                        lon, lat, lonBirth, latBirth, age, t, c2,
                        segmentLength, slabLength, distSlabEdge, SPcoregNor,
                        SPcoregPar, OPcoregNor, OPcoregPar, CONVcoregNor,
                        CONVcoregPar, subPolCoreg, subOblCoreg
                    ]

    #Return the filled coregistered array
    return (coregData)
def kinloop(timeFrom,timeTo,data,input_rotation_filename):
    '''
    Determines the absolute and relative velocities of the plates and trench.

    INPUT (with examples):
        
    timeFrom=2 #integer
    timeTo=1 #integer
    data = [[14.7703, 43.5369, 701, 301, 301], [18.8934, 41.5683, 701, 301, 301], 
            [18.6062, 39.7998, 701, 301, 301], [19.4349, 39.3242, 701, 301, 301]]
            #List of points [[Lon, Lat, SPid, TRENCHid, OPid]]
    input_rotation_filename='Shephard_etal_ESR2013_Global_EarthByte_2013.rot' #String
    
    OUTPUT: (array equivalent to 'data' plus Absoulte XYZ and Convergence XYZ 
        velocity components.)

    [14.7703, 43.5369, 701, 301, 301, -13.02077,10.4195,10.45488,-4.86172,
        -4.62026,6.18716]
        
    WARNING: If this function is used stand-alone, without an idea of left
        or right, then it may be backward. Points should be entered CW.

    '''
    #Set the times of interest
    #timeFrom=3 #from xx Ma
    #timeTo=2 # to xx Ma
    
    #Read the SubdctionZoneAttributes data
    kinematicsArray=data

    #Read the rotation file and build a rotation model    
    #input_rotation_filename = "/Users/nbutter/DataMining/CODE/SubductionZoneAttributes/oldTestdata/Global_EarthByte_TPW_CK95G94_PP_20110412.rot"
    file_registry = pygplates.FeatureCollectionFileFormatRegistry()
    rotation_feature_collection = file_registry.read(input_rotation_filename)
    rotation_model = pygplates.RotationModel([rotation_feature_collection])

    #Build the rotations for the times we want    
    fromTimeRotation=rotation_model.get_reconstruction_tree(timeFrom)
    toTimeRotation=rotation_model.get_reconstruction_tree(timeTo)
    
    #Make an array to store our data in
    speedArray=[]
    reversedSub=0 #Initilise this here in case the data does not have headers
    
    #Loop through all the SubdctionZoneAttributes data and find velocities
    for index, point in enumerate(kinematicsArray[:]): 
        #print point[0]
        #See if the point is not a header, or if the next point is not a header
        if isinstance(point[0],str):
            #Also, if it is a header, get the order of the points
            if point[0].find('Reversed') != -1:
                reversedSub=int(point[-1])
                #print reverse
        if len(point) == 5:
            lon = float(point[0])
            lat = float(point[1])
            OPid = int(point[4])
            TRENCHid = int(point[3])
            SPid = int(point[2])

            #Convert point LatLon to XYZ
            pointXYZ, pointXYZcart = latlon2pygplates(lat,lon)
            
            #Get the Euler poles for each of the relevant rotations
            stageTrench = pygplates.ReconstructionTree.get_equivalent_stage_rotation(fromTimeRotation,toTimeRotation,TRENCHid)
            poletTrench,angleTrench = stageTrench.get_euler_pole_and_angle()
            poleTrench = [poletTrench.get_x(), poletTrench.get_y(), poletTrench.get_z()]

            #Absolut velocity is the motion of the SP
            stageSP = pygplates.ReconstructionTree.get_equivalent_stage_rotation(fromTimeRotation,toTimeRotation,SPid)
            poletSP,angleSP = stageSP.get_euler_pole_and_angle()
            #If you want the latitude and longitude, rather than the cartesian:
            #poleSPLatLon = pygplates.convert_point_on_sphere_to_lat_lon_point(poleSP)
            #SPLatLon = [poleSPLatLon.get_latitude(), poleSPLatLon.get_longitude()] 
            poleSP = [poletSP.get_x(), poletSP.get_y(), poletSP.get_z()]

            #Convergence is the relative rotation between the trench and SP
            #if reversedSub==1:
            #convRotation = pygplates.get_relative_stage_rotation(fromTimeRotation,toTimeRotation,TRENCHid,SPid)
            #else:
            convRotation = pygplates.ReconstructionTree.get_relative_stage_rotation(fromTimeRotation,toTimeRotation,SPid,TRENCHid)
            poletCONV,angleCONV = convRotation.get_euler_pole_and_angle()
            poleCONV = [poletCONV.get_x(), poletCONV.get_y(), poletCONV.get_z()]

            #The OP motion
            stageOP = pygplates.ReconstructionTree.get_equivalent_stage_rotation(fromTimeRotation,toTimeRotation,OPid)
            poletOP,angleOP = stageOP.get_euler_pole_and_angle()
            poleOP = [poletOP.get_x(), poletOP.get_y(), poletOP.get_z()]
            
            #Angular velocity (Degrees / Myr) #but need it in radians.. not used
            omegaCONV = numpy.degrees(angleCONV)/(timeFrom-timeTo)
            omegaSP = numpy.degrees(angleSP)/(timeFrom-timeTo) 

            #Velocity vectors at each point in (Earth Radius Units) / Myr
            absoluteV = numpy.cross(poleSP,pointXYZcart) * angleSP/(timeFrom-timeTo) 
            convergenceV = numpy.cross(poleCONV,pointXYZcart) * angleCONV/(timeFrom-timeTo) 
            opV = numpy.cross(poleOP,pointXYZcart) * angleOP/(timeFrom-timeTo)
            trenchV = numpy.cross(poleTrench,pointXYZcart) * angleTrench/(timeFrom-timeTo)            

            #Velocivites vectors in mm/yr (km/Myr)
            Rearth=6371.0 # m 
            vABS = absoluteV * Rearth
            vCONV = convergenceV * Rearth
            vOP = opV * Rearth
            vTrench = trenchV * Rearth

            speedArray.append([lon,lat,SPid,TRENCHid,OPid,\
                round(vABS[0],5),round(vABS[1],5),round(vABS[2],5),\
                round(vCONV[0],5),round(vCONV[1],5),round(vCONV[2],5),\
                round(vOP[0],5),round(vOP[1],5),round(vOP[2],5),\
                round(vTrench[0],5),round(vTrench[1],5),round(vTrench[2],5),\
                int(SPid), int(TRENCHid), int(OPid)])
            #print [lon,lat,SPid,TRENCHid,OPid,round(vABS[0],5),round(vABS[1],5),round(vABS[2],5),round(vCONV[0],5),round(vCONV[1],5),round(vCONV[2],5)]
        #If it is a header, just print it back out.
        else:
            #pass
            speedArray.append(point)

    return(speedArray)
def coregLoopHistory(pointlist, ts0=0, ts1=230, plateID=201):
    '''
    coregLoopHistory

    This script reconstructs a list of points throughout history and 
    coregisters each point with another set of points, or a raster file.

    INPUTS:
    pointlist - list of lat/lon
    ts0 - time step to rotate points from (probably 0Ma)
    ts1 - time step to rotate points to (probably 230Ma).

    Hardcoded filenames/variables must be changed below:
    input_rotation_filename - Rotation file 
    rasterfile - Time dependent raster files
    f - Time dependent kinemtic csv outputs from 'convergence.py'

    OUTPUTS:
    Coregistered array: List of lat/lons with properties.

    METHOD:
    Takes a set of points 
    Rotates the points back to their birth position
    Determines the point's birth position geophysical properties (coregisters)
    '''

    #Set up an array to store the data
    timeSteps = ts1 - ts0  #The length of time before mineralisation you care about
    noVariables = 18  #The number of variables you save
    Nshp = len(pointlist)
    coregData = numpy.zeros((Nshp, timeSteps, noVariables))

    #Create a rotation model to rotate the points back in time
    input_rotation_filename = "Muller_gplates/Global_EarthByte_230-0Ma_GK07_AREPS.rot"

    file_registry = pygplates.FeatureCollectionFileFormatRegistry()
    rotation_feature_collection = file_registry.read(input_rotation_filename)
    rotation_model = pygplates.RotationModel([rotation_feature_collection])

    #Loop through each time step in the plate model
    for time in xrange(ts0, ts1, 1):

        #A raster file, to coregister with, these points have already been rotated
        rasterfile = "Muller_etal_2016_AREPS_Agegrids_v1.11/netCDF_0-230Ma/EarthByte_AREPS_v1.11_Muller_etal_2016_AgeGrid-" + str(
            time) + ".nc"
        [x, y, z] = gridRead(rasterfile)

        #A vector file to coregister with, these points have already been rotated
        f = numpy.loadtxt("Muller_convergence/subStats_" + str(time) + ".csv",
                          delimiter=',')

        lonlat = f[:, 0:2]

        for i, currentPoint in enumerate(pointlist):

            shapeArray = currentPoint
            age = ts0

            t = time - age
            print(i, age, time, t, plateID)

            #-------------------#
            #Reconstruct a point to its birth position
            #-------------------#
            latlonPoint = pygplates.LatLonPoint(shapeArray[1], shapeArray[0])

            point_to_rotate = pygplates.convert_lat_lon_point_to_point_on_sphere(
                latlonPoint)

            finite_rotation = rotation_model.get_rotation(time, plateID)
            birthPosition = finite_rotation * point_to_rotate

            latlonBirth = pygplates.convert_point_on_sphere_to_lat_lon_point(
                birthPosition)
            #allPoints = finite_rotation * pointSet_to_rotate

            latBirth = latlonBirth.get_latitude()
            lonBirth = latlonBirth.get_longitude()

            #-------------------#
            #Set the points for coregistering
            region = 5.0  #degrees

            #-------------------#
            #Coregisterring raster 1
            #-------------------#
            #Find the region in index units
            r = numpy.round(region / (x[1] - x[0]))

            #Find the index unit of lat and lon
            idxLon = (numpy.abs(x - lonBirth)).argmin()
            idxLat = (numpy.abs(y - latBirth)).argmin()

            #Raster 1
            c2 = coregRaster([idxLon, idxLat], z, r)
            #Hack to search further around the age grid if it can't find a match, \
            #note index units (not degrees)
            if numpy.isnan(c2):
                c2 = coregRaster([idxLon, idxLat], z, r + 150.0)
                print("Trying raster region: ", r + 150.0)

            #-------------------#
            #Coregisterring vector 1
            #-------------------#
            index = coregPoint([lonBirth, latBirth], lonlat, region)
            if index == 'inf':
                print("trying index region", region + 15)
                index = coregPoint([lonBirth, latBirth], lonlat, region + 15.0)

            if numpy.isnan(c2) or index == 'inf':
                #if we have some null data, let's save it anyway, see what happens
                print("Skipping:", i, age, t, time, c2, index, lonBirth,
                      latBirth)

            else:
                #Vector 1
                segmentLength = f[index, 3]
                slabLength = f[index, 9]
                distSlabEdge = f[index, 15]

                SPcoregNor = f[index, 4]
                SPcoregPar = f[index, 12]
                OPcoregNor = f[index, 5]
                OPcoregPar = f[index, 13]
                CONVcoregNor = f[index, 10]
                CONVcoregPar = f[index, 11]

                subPolCoreg = f[index, 8]
                subOblCoreg = f[index, 7]

                coregData[i, t, :] = [
                    shapeArray[0], shapeArray[1], lonBirth, latBirth, age, t,
                    c2, segmentLength, slabLength, distSlabEdge, SPcoregNor,
                    SPcoregPar, OPcoregNor, OPcoregPar, CONVcoregNor,
                    CONVcoregPar, subPolCoreg, subOblCoreg
                ]

    return (coregData)
Esempio n. 4
0
def coregLoopTimeFirst(recs, shapes, fields, Nshp, shapeType):
    '''
    coregLoop

    This script reconstructs a shapefile of points to their birth time and 
    coregisters each point with another set of points, or a raster file.

    INPUTS:
    Can best be used with the output of readTopologyPlatepolygonFile() 
    which reads a shapefile and returns the 'records', 'shapes', 'fields',
    and 'number of shapes'.

    Hardcoded filenames/variables must be changed below:
        Rotation file - input_rotation_filename
        Time dependent raster files - rasterfile
        Time dependent vector csv outputs from 'convergence.py' - f

    OUTPUTS:
    Coregistered array: List of lat/lons with properties.

    METHOD:
    Takes a set of points (from a shapefile)
    Rotates the points back to their birth position
    Determines the point's birth position geophysical properties (coregisters)
    '''
    #Set up a list to store the data
    if shapeType == 0:
        timeSteps = 230  #The length of time before mineralisation you care about
    else:
        timeSteps = 1

    noVariables = 18  #The number of variables you save

    input_rotation_filename = "Muller_gplates/Global_EarthByte_230-0Ma_GK07_AREPS.rot"
    # input_rotation_filename = "/Users/nbutter/Geodata/PlateModel/Shephard_etal_ESR2013_Global_EarthByte_2013.rot"
    #Create a rotation model to rotate the points back in time
    file_registry = pygplates.FeatureCollectionFileFormatRegistry()
    rotation_feature_collection = file_registry.read(input_rotation_filename)
    rotation_model = pygplates.RotationModel([rotation_feature_collection])

    #Initialise the array to store the data
    coregData = numpy.zeros((Nshp, timeSteps, noVariables))

    #Loop through each time step in the plate model
    for time in xrange(0, 230, 1):

        #A raster file, to coregister with, these points have already been rotated
        rasterfile = "Muller_etal_2016_AREPS_Agegrids_v1.11/netCDF_0-230Ma/EarthByte_AREPS_v1.11_Muller_etal_2016_AgeGrid-" + str(
            time) + ".nc"
        # rasterfile="/Users/nbutter/Geodata/AgeGrid_20111110_Seton_etal_ESR/agegrid_final_mask_"+str(time)+".grd"
        [x, y, z] = gridRead(rasterfile)

        #A vector file to coregister with, these points have already been rotated
        f = readCSV("Muller_convergence/subStats_" + str(time) + ".csv")
        # f = readCSV("/Users/nbutter/Geodata/CONVERGENCE/Shep07/subStats_"+str(time)+".csv")

        lonlat = f[:, 0:2]

        for i, nshpSub in enumerate(xrange(Nshp)):
            #!!! Warning: These are shapefile specific attributes,
            #if you use a different shapefile, you must change these hard codes
            #to the corresponding age and plateID column in the shapefile
            if shapeType == 0:
                shapeArray = numpy.array(shapes[nshpSub])
                age = 0
                plateID = 201
            else:
                shapeArray = numpy.array(shapes[nshpSub].points)
            #Here age is in the last column, and plateID in 7th.

            #1, 2 For porcu/main_edited.shp use 43 for the plateID
            #1, 2 For porcu/main_edited.shp use 9 for the age and 42 for the random age
            #3, 4 For XYBer14_t2_ANDES.shp use 7 for plateID
            #3, 4 For XYBer14_t2_ANDES.shp use 6 for age and -1 for Random
            if shapeType == 1:
                age = round(recs[nshpSub][9])
                plateID = recs[nshpSub][43]
            elif shapeType == 2:
                age = round(recs[nshpSub][42])
                plateID = recs[nshpSub][43]
            elif shapeType == 3:
                age = round(recs[nshpSub][6])
                plateID = recs[nshpSub][7]
            elif shapeType == 4:
                age = round(recs[nshpSub][-1])
                plateID = recs[nshpSub][7]

            t = time - age
            print i, age, time, t, plateID

            #-------------------#
            #Reconstruct a point to its birth position
            #-------------------#
            if shapeType == 0:
                latlonPoint = pygplates.LatLonPoint(shapeArray[1],
                                                    shapeArray[0])
            else:
                latlonPoint = pygplates.LatLonPoint(shapeArray[0][1],
                                                    shapeArray[0][0])

            point_to_rotate = pygplates.convert_lat_lon_point_to_point_on_sphere(
                latlonPoint)

            finite_rotation = rotation_model.get_rotation(time, plateID)
            birthPosition = finite_rotation * point_to_rotate

            latlonBirth = pygplates.convert_point_on_sphere_to_lat_lon_point(
                birthPosition)
            #allPoints = finite_rotation * pointSet_to_rotate

            latBirth = latlonBirth.get_latitude()
            lonBirth = latlonBirth.get_longitude()

            #-------------------#
            #Set the points for coregistering
            region = 5.0  #degrees

            #-------------------#
            #Coregisterring raster 1
            #-------------------#
            #Find the region in index units
            r = numpy.round(region / (x[1] - x[0]))

            #Find the index unit of lat and lon
            idxLon = (numpy.abs(x - lonBirth)).argmin()
            idxLat = (numpy.abs(y - latBirth)).argmin()

            #Raster 1
            c2 = coregRaster([idxLon, idxLat], z, r)
            #Hack to search further around the age grid if it can't find a match, note index units (not degrees)
            # if numpy.isnan(c2):
            #     print "Trying raster region: ", r+100.0
            #     c2=coregRaster([idxLon,idxLat],z,r+100.0)
            if numpy.isnan(c2):
                c2 = coregRaster([idxLon, idxLat], z, r + 150.0)
                print "Trying raster region: ", r + 150.0

            #-------------------#
            #Coregisterring vector 1
            #-------------------#
            index = coregPoint([lonBirth, latBirth], lonlat, region)
            # if index=='inf':
            #                         print "trying index region", region+10
            #                         index=coregPoint([lonBirth,latBirth],lonlat,region+10.0)
            if index == 'inf':
                print "trying index region", region + 15
                index = coregPoint([lonBirth, latBirth], lonlat, region + 15.0)

            if numpy.isnan(c2) or index == 'inf':
                #if we have some null data, let's save it anyway, see what happens
                #allData.append([shapeArray[0][0],shapeArray[0][1],0,0,\
                #    age,age-time,0,0,0,0])
                print "Skipping:", i, age, t, time, c2, index, lonBirth, latBirth

            else:
                #Vector 1
                segmentLength = f[index, 3]
                slabLength = f[index, 9]
                distSlabEdge = f[index, 15]

                SPcoregNor = f[index, 4]
                SPcoregPar = f[index, 12]
                OPcoregNor = f[index, 5]
                OPcoregPar = f[index, 13]
                CONVcoregNor = f[index, 10]
                CONVcoregPar = f[index, 11]

                subPolCoreg = f[index, 8]
                subOblCoreg = f[index, 7]

                #                         0 longitude,
                #                         1 latitude,
                #                         2 convRate(mm/yr),
                #                         3 segmentLength(km),
                #                         4 subPlateVel(mm/yr),
                #                         5 opVelocity(mm/yr),
                #                         6 trenchVel(mm/yr),
                #                         7 subObliquity(degrees),
                #                         8 subPolarity(degrees),
                #                         9 slabDistance(km),
                #                         10 OrthogonalConvergence(mm/yr),
                #                         11 ParallelConvergence(mm/yr),
                #                         12 ParallelSubPlateVel(mm/yr),
                #                         13 ParallelOPvel(mm/yr),
                #                         14 ParallelTrenchVel(mm/yr),
                #                         15 DistanceToSlabEdge(km),
                #                         16 SPid,
                #                         17 TRENCHid,
                #                         18 OPid

                if shapeType == 0:
                    coregData[i,t,:]=[shapeArray[0],shapeArray[1],lonBirth,latBirth,\
                                age,t,c2,\
                                segmentLength,slabLength,distSlabEdge,\
                                SPcoregNor,SPcoregPar,OPcoregNor,OPcoregPar,CONVcoregNor,CONVcoregPar,\
                                subPolCoreg,subOblCoreg]

                else:
                    coregData[i,t,:]=[shapeArray[0][0],shapeArray[0][1],lonBirth,latBirth,\
                                age,t,c2,\
                                segmentLength,slabLength,distSlabEdge,\
                              SPcoregNor,SPcoregPar,OPcoregNor,OPcoregPar,CONVcoregNor,CONVcoregPar,\
                                subPolCoreg,subOblCoreg]

    return (coregData)
frame_change_input_rotation_filename = framework_d.get(
    'frame_change_input_rotation_filename')
frame_change_input_multipoint_filename = framework_d.get(
    'frame_change_input_multipoint_filename')

print now(
), 'frame_change_pygplates: frame_change_input_rotation_filename =', frame_change_input_rotation_filename
print now(
), 'frame_change_pygplates: frame_change_input_multipoint_filename =', frame_change_input_multipoint_filename

# read the rotation data
rotation_model = pygplates.RotationModel(frame_change_input_rotation_filename)

# read the multipoint data
print now(), 'frame_change_pygplates: Reading multipoint data...'
file_registry = pygplates.FeatureCollectionFileFormatRegistry()
multipoint_feature_collection = file_registry.read(
    frame_change_input_multipoint_filename)

print now(), 'frame_change_pygplates: Processing user input:'

# Get the recon time
reconstruction_time = int(sys.argv[1])
print now(
), 'frame_change_pygplates: reconstruction_time = ', reconstruction_time

# Get the input grid
input_grid_file = sys.argv[2]
print now(), 'frame_change_pygplates: input_grid_file = ', input_grid_file

# Get the grid -R
def filterGPML(**kwargs):

    # Start the clock
    start = time.time()

    filterProperties = [
        "inputFile", "outputFile", "filterSequence", "rPlateID", "cPlateID",
        "ageAppearWindow", "ageDisappearWindow", "ageExistsWindow",
        "boundingBox", "featureType", "geometryType", "featureID",
        "featureName", "feature_truncate_age", "inverse", "cascade"
    ]

    # Process supplied arguments and assign values to variables

    # Inverse is set to False by default
    inverse = False

    # Cascade is set to True  by default
    cascade = True

    for parameter, value in kwargs.items():

        if parameter in filterProperties:
            if parameter == filterProperties[0]:
                inputFile = value
            elif parameter == filterProperties[1]:
                outputFile = value
            elif parameter == filterProperties[2]:
                filterSequence = value
            elif parameter == filterProperties[3]:
                rPlateID = value
            elif parameter == filterProperties[4]:
                cPlateID = value
            elif parameter == filterProperties[5]:
                ageAppearWindow = value
            elif parameter == filterProperties[6]:
                ageDisappearWindow = value
            elif parameter == filterProperties[7]:
                ageExistsWindow = value

                if ageExistsWindow[1] > ageExistsWindow[0]:
                    print " "
                    print "ERROR - Age exists window end age older than begin age: " + str(
                        ageExistsWindow[1])

            elif parameter == filterProperties[8]:
                boundingBox = value

                if pgp.LatLonPoint.is_valid_longitude(boundingBox[0]) is False:
                    print " "
                    print "ERROR - Bounding box longitude is not valid: " + str(
                        boundingBox[0])

                if pgp.LatLonPoint.is_valid_longitude(boundingBox[1]) is False:
                    print " "
                    print "ERROR - Bounding box longitude is not valid: " + str(
                        boundingBox[1])

                if pgp.LatLonPoint.is_valid_latitude(boundingBox[2]) is False:
                    print " "
                    print "ERROR - Bounding box latitude is not valid: " + str(
                        boundingBox[2])

                if pgp.LatLonPoint.is_valid_latitude(boundingBox[3]) is False:
                    print " "
                    print "ERROR - Bounding box latitude is not valid: " + str(
                        boundingBox[3])

            elif parameter == filterProperties[9]:
                featureTemp = value
                featureType = []

                if "ALL" in featureTemp:
                    featureType = [
                        "Isochron", "MidOceanRidge",
                        "PassiveContinentalBoundary"
                    ]
                if "ISO" in featureTemp:
                    featureType.append("Isochron")
                if "MOR" in featureTemp:
                    featureType.append("MidOceanRidge")
                if "PCB" in featureTemp:
                    featureType.append("PassiveContinentalBoundary")

            elif parameter == filterProperties[10]:
                geometryType = value

                if "ALL" in geometryType:
                    geometryType = [
                        "PolylineOnSphere", "PolygonOnSphere", "PointOnSphere",
                        "MultiPointOnSphere"
                    ]

            elif parameter == filterProperties[11]:
                featureID = value
            elif parameter == filterProperties[12]:
                featureName = value
            elif parameter == filterProperties[13]:
                feature_truncate_age = value
            elif parameter == filterProperties[14]:
                inverse = value
            elif parameter == filterProperties[15]:
                cascade = value

        else:
            print " "
            print "ERROR - Filter criteria not found: " + str(parameter)
            print " "

    date = datetime.date.today()

    #if inputFile != "none":
    #output = pgp.FeatureCollection()

    featureCollection = pgp.FeatureCollectionFileFormatRegistry()

    print " "
    print "--------------------------------------------"
    print " ### GPMLTools - filterGPML ###"

    # Check for existing output directory and create it if not found
    if not os.path.exists("output"):
        os.makedirs("output")
        print " "
        print "Housekeeping:"
        print "    No output folder found. Folder 'output' created."

    # Check for existing output file with same name and remove if found
    if os.path.isfile("output/output.gpml"):
        os.remove("output/output.gpml")
        print " "
        print "Housekeeping:"
        print "    Previous 'output.gpml' found in destination folder. File removed for new filter sequence."

    try:
        feature = featureCollection.read(inputFile)
        feature1 = featureCollection.read(inputFile)
        print " "
        print "Data handling:"
        print "    Successfully loaded data file:  '" + str(inputFile) + "'"
        print "       - File contains " + str(len(feature)) + " features."

    except pgp.OpenFileForReadingError:
        print " "
        print("    ERROR - File read error in: '" + inputFile +
              "'. Is this a valid GPlates file?")

    except pgp.FileFormatNotSupportedError:
        print " "
        print("    ERROR - File format not supported: '" + inputFile +
              "'. Please check the file name and try again")

    #Filter data

    print " "
    print "Filter sequence:"

    previousFilter = 0

    f1_result = pgp.FeatureCollection()
    f2_result = pgp.FeatureCollection()
    f3_result = pgp.FeatureCollection()
    f4_result = pgp.FeatureCollection()
    f5_result = pgp.FeatureCollection()
    f6_result = pgp.FeatureCollection()
    f7_result = pgp.FeatureCollection()
    f8_result = pgp.FeatureCollection()
    f9_result = pgp.FeatureCollection()
    f10_result = pgp.FeatureCollection()
    f11a_result = pgp.FeatureCollection()
    f11b_result = pgp.FeatureCollection()

    for filter_ in filterSequence:

        if previousFilter == 0:
            data_ = feature
        elif previousFilter == 1:
            data_ = f1_result
        elif previousFilter == 2:
            data_ = f2_result
        elif previousFilter == 3:
            data_ = f3_result
        elif previousFilter == 4:
            data_ = f4_result
        elif previousFilter == 5:
            data_ = f5_result
        elif previousFilter == 6:
            data_ = f6_result
        elif previousFilter == 7:
            data_ = f7_result
        elif previousFilter == 8:
            data_ = f8_result
        elif previousFilter == 9:
            data_ = f9_result
        elif previousFilter == 10:
            data_ = f10_result
        elif previousFilter == 11:
            data_ = f11_result

        # Filter by reconstruction plate ID
        if filter_ == 1:

            for feature in data_:

                if cascade == False:

                    for property in feature:

                        filter_property = property.get_name()

                        if filter_property.get_name(
                        ) == "reconstructionPlateId":
                            selected_filter_property = property.get_value()

                            for property in feature:

                                filter_property = property.get_name()

                                if filter_property.get_name(
                                ) == "conjugatePlateId":
                                    second_filter_property = property.get_value(
                                    )

                                    if inverse == False:

                                        # Isolate criteria match and process
                                        if str(selected_filter_property
                                               ) == str(rPlateID[0]) and str(
                                                   second_filter_property
                                               ) == str(cPlateID[0]):

                                            # Append filtered data to associated Feature Collection
                                            f1_result.add(feature)

                                    elif inverse == True:

                                        if int(str(selected_filter_property)
                                               ) not in rPlateID or int(
                                                   str(second_filter_property)
                                               ) not in cPlateID:

                                            # Append filtered data to associated Feature Collection
                                            f1_result.add(feature)

                elif cascade == True:

                    for property in feature:

                        filter_property = property.get_name()

                        if filter_property.get_name(
                        ) == "reconstructionPlateId":
                            selected_filter_property = property.get_value()

                            if inverse == False:

                                for plateID in rPlateID:

                                    if str(selected_filter_property) == str(
                                            plateID):

                                        # Append filtered data to associated Feature Collection
                                        f1_result.add(feature)

                            elif inverse == True:

                                if int(str(selected_filter_property)
                                       ) not in rPlateID:

                                    # Append filtered data to associated Feature Collection
                                    f1_result.add(feature)

            if cascade == False:
                print "Oooooh, you found the secret command..."
                print " "
                print "    1. Filtering data by reconstruction plate ID: " + str(
                    rPlateID) + " and conjugate plate ID: " + str(cPlateID)
                print "       - Found " + str(len(f1_result)) + " feature(s)."

                cascade = True

            else:

                print " "
                print "    1. Filtering data by reconstruction plate ID(s): " + str(
                    rPlateID)
                print "       - Found " + str(len(f1_result)) + " feature(s)."

            print " "

            previousFilter = 1

        # Filter by conjugate plate ID
        if filter_ == 2:

            for feature in data_:
                for property in feature:

                    filter_property = property.get_name()

                    if filter_property.get_name() == "conjugatePlateId":
                        selected_filter_property = property.get_value()

                        # Isolate criteria match and process
                        if inverse == False:

                            for plateID in cPlateID:

                                if str(selected_filter_property) == str(
                                        plateID):

                                    # Append filtered data to associated Feature Collection
                                    f2_result.add(feature)

                        elif inverse == True:

                            if int(str(
                                    selected_filter_property)) not in cPlateID:

                                # Append filtered data to associated Feature Collection
                                f2_result.add(feature)

            print "    2. Filtering data by conjugate plate ID(s): " + str(
                cPlateID)
            print "       - Found " + str(len(f2_result)) + " feature(s)."
            print " "

            previousFilter = 2

        # Filter by age of appearance
        if filter_ == 3:

            if ageAppearWindow[0] == "DP":
                ageAppearWindow[0] = float("inf")

            for feature in data_:

                begin_time, end_time = feature.get_valid_time()

                if begin_time <= ageAppearWindow[
                        0] and begin_time >= ageAppearWindow[1]:
                    f3_result.add(feature)

            print "    3. Filtering data by age of appearance window: " + str(
                ageAppearWindow[0]) + " - " + str(ageAppearWindow[1]) + " Ma"
            print "       - Found " + str(len(f3_result)) + " feature(s)."
            print " "

            previousFilter = 3

        # Filter by age of disappearance
        if filter_ == 4:

            if ageDisappearWindow[1] == "DF":
                ageDisappearWindow[1] = float("-inf")

            for feature in data_:

                begin_time, end_time = feature.get_valid_time()

                if end_time <= ageDisappearWindow[
                        0] and end_time >= ageDisappearWindow[1]:
                    f4_result.add(feature)

            print "    4. Filtering data by age of disappearance window: " + str(
                ageDisappearWindow[0]) + " - " + str(
                    ageDisappearWindow[1]) + " Ma"
            print "       - Found " + str(len(f4_result)) + " feature(s)."
            print " "

            previousFilter = 4

        # Filter by geographic selection / polygon
        if filter_ == 5:

            for feature in data_:
                for property in feature:

                    filter_property = property.get_name()

                    if filter_property.get_name() == "centerLineOf":
                        selected_filter_property = property.get_value()

                        points = selected_filter_property.get_value(
                        ).get_base_curve().get_polyline().get_points_view()

                        for point in points:
                            point_latlong = pgp.convert_point_on_sphere_to_lat_lon_point(
                                point)

                            if point_latlong.get_longitude() >= float(boundingBox[0]) and point_latlong.get_longitude() <= float(boundingBox[1])\
                                    and point_latlong.get_latitude() >= float(boundingBox[2]) and point_latlong.get_latitude() <= float(boundingBox[3]):

                                # If point is found within bounding box, add feature and break loop (search next feature)
                                f5_result.add(feature)
                                break

            print "    5. Filtering data by geographic bounding box: " + str(
                boundingBox[0]) + "/" + str(boundingBox[1]) + "/" + str(
                    boundingBox[2]) + "/" + str(boundingBox[3])
            print "       - Found " + str(len(f5_result)) + " feature(s)."
            print " "

            previousFilter = 5

        # Filter by age exists window
        if filter_ == 6:

            for feature in data_:

                begin_time, end_time = feature.get_valid_time()

                if begin_time >= ageExistsWindow[
                        0] and end_time <= ageExistsWindow[1]:
                    f6_result.add(feature)
                elif begin_time >= ageExistsWindow[
                        0] and end_time <= ageExistsWindow[
                            0] and end_time >= ageExistsWindow[1]:
                    f6_result.add(feature)
                elif begin_time <= ageExistsWindow[
                        0] and end_time >= ageExistsWindow[1]:
                    f6_result.add(feature)
                elif begin_time <= ageExistsWindow[
                        0] and end_time >= ageExistsWindow[
                            1] and end_time <= ageExistsWindow[1]:
                    f6_result.add(feature)

            print "    6. Filtering data by age of existence window: " + str(
                ageExistsWindow[0]) + " - " + str(ageExistsWindow[1]) + " Ma"
            print "       - Found " + str(len(f6_result)) + " feature(s)."
            print " "

            previousFilter = 6

        # Filter by feature type
        if filter_ == 7:

            iso_count = 0
            mor_count = 0
            pcb_count = 0

            for feature in data_:

                if "Isochron" in featureType:
                    if str(feature.get_feature_type()) == "gpml:Isochron":
                        f7_result.add(feature)
                        iso_count += 1
                if "MidOceanRidge" in featureType:
                    if str(feature.get_feature_type()) == "gpml:MidOceanRidge":
                        f7_result.add(feature)
                        mor_count += 1
                if "PassiveContinentalBoundary" in featureType:
                    if str(feature.get_feature_type()
                           ) == "gpml:PassiveContinentalBoundary":
                        f7_result.add(feature)
                        pcb_count += 1

            print "    7. Filtering data by feature type(s): " + str(
                featureType)

            if "Isochron" in featureType:
                print "       - Found " + str(iso_count) + " Isochron(s)."
            if "MidOceanRidge" in featureType:
                print "       - Found " + str(mor_count) + " MidOceanRidge(s)."
            if "PassiveContinentalBoundary" in featureType:
                print "       - Found " + str(
                    pcb_count) + " PassiveContinentalBoundary(s)."

            print " "

            previousFilter = 7

        # Filter by geometry type
        if filter_ == 8:

            polylineCount = 0
            polygonCount = 0
            pointCount = 0
            multiPointCount = 0

            for feature in data_:

                geometries = feature.get_geometry()

                for geometry in geometryType:

                    if str(geometry) in str(geometries):
                        f8_result.add(feature)

                        if str(geometry) == "PolylineOnSphere":
                            polylineCount += 1
                        if str(geometry) == "PolygonOnSphere":
                            polygonCount += 1
                        if str(geometry) == "PointOnSphere":
                            pointCount += 1
                        if str(geometry) == "MultiPointOnSphere":
                            multiPointCount += 1

            print "    8. Filtering data by feature geometries present: " + str(
                geometryType)

            if "PolylineOnSphere" in geometryType:
                print "       - Found " + str(
                    polylineCount) + " PolylineOnSphere(s)."
            if "PolygonOnSphere" in geometryType:
                print "       - Found " + str(
                    polygonCount) + " PolygonOnSphere(s)."
            if "PointOnSphere" in geometryType:
                print "       - Found " + str(
                    pointCount) + " PointOnSphere(s)."
            if "MultiPointOnSphere" in geometryType:
                print "       - Found " + str(
                    multiPointCount) + " MultiPointOnSphere(s)."

            print " "

            previousFilter = 8

        # Filter by feature ID
        if filter_ == 9:

            for feature in data_:

                for id in featureID:
                    if str(feature.get_feature_id()).lower() == str(
                            id).lower():
                        f9_result.add(feature)

            print "    9. Filtering data by feature ID: " + str(featureID)
            print "       - Found " + str(len(f9_result)) + " feature(s)."
            print " "

            previousFilter = 9

        # Filter by feature name (case insensitive)
        if filter_ == 10:

            for feature in data_:

                feature_name = feature.get_name()

                for names in featureName:

                    if names.lower() in feature_name.lower():
                        f10_result.add(feature)

            print "    10. Filtering data by feature name: " + str(featureName)
            print "       - Found " + str(len(f10_result)) + " feature(s)."
            print " "

            previousFilter = 10

        # Truncate file by age boundary
        if filter_ == 11:

            for feature in data_:

                begin_time, end_time = feature.get_valid_time()

                if begin_time > feature_truncate_age and end_time > feature_truncate_age:

                    f11a_result.add(feature)

                elif begin_time > feature_truncate_age and end_time <= feature_truncate_age:

                    # Special case if SubductionZone - need to incorporate start age
                    if str(feature.get_feature_type()
                           ) == "gpml:SubductionZone":

                        feature.set_valid_time(begin_time,
                                               feature_truncate_age + 0.1)
                        f11a_result.add(feature)

                    else:

                        feature.set_valid_time(begin_time,
                                               feature_truncate_age + 0.1)
                        f11a_result.add(feature)

            # Limitation of pyGPlates: need to loop through copy of feature
            for feature in feature1:

                begin_time, end_time = feature.get_valid_time()

                if begin_time > feature_truncate_age and end_time <= feature_truncate_age:

                    # Special case if SubductionZone - need to incorporate start age
                    if str(feature.get_feature_type()
                           ) == "gpml:SubductionZone":

                        #print feature.get_name()
                        sz_age_array = []

                        for property in feature:

                            # Create array or properties and add 'gpml:subductionZoneAge' if there isn't one already
                            sz_age_array.append(str(property.get_name()))

                        if "gpml:subductionZoneAge" not in sz_age_array:

                            #print feature.get_name()
                            feature.add(
                                pgp.PropertyName.create_gpml(
                                    'subductionZoneAge'),
                                pgp.XsDouble(begin_time))

                        feature.set_valid_time(feature_truncate_age, end_time)

                        f11b_result.add(feature)

                    else:

                        feature.set_valid_time(feature_truncate_age, end_time)
                        f11b_result.add(feature)

                elif begin_time == feature_truncate_age:

                    f11b_result.add(feature)

                elif begin_time <= feature_truncate_age and end_time < feature_truncate_age:

                    f11b_result.add(feature)

            print "    11. File truncated by age boundary: " + str(
                feature_truncate_age) + " Ma"
            print "       - Created " + str(len(
                f11a_result)) + " feature(s) older than truncation boundary."
            print "       - Created " + str(len(
                f11b_result)) + " feature(s) younger than truncation boundary."
            print " "

            previousFilter = 11

    # output new feature collection from filtered data to file

    if previousFilter == 11:

        iso_output1 = eval("f" + str(previousFilter) + "a_result")
        iso_output2 = eval("f" + str(previousFilter) + "b_result")

        if len(iso_output1) != 0:

            outputFeatureCollection1 = pgp.FeatureCollectionFileFormatRegistry(
            )
            outputFeatureCollection1.write(
                iso_output1, "output/>" + str(feature_truncate_age) + "Ma_" +
                str(outputFile))

            print " "
            print "Output file 1:"
            print "    ../output/" + ">" + str(
                feature_truncate_age) + "Ma_" + str(outputFile)
            print " "
            print "Process took " + str(round(time.time() - start,
                                              2)) + " seconds."
            print " "

        if len(iso_output2) != 0:

            outputFeatureCollection2 = pgp.FeatureCollectionFileFormatRegistry(
            )
            outputFeatureCollection2.write(
                iso_output2, "output/<" + str(feature_truncate_age) + "Ma_" +
                str(outputFile))

            print "Output file 2:"
            print "    ../output/" + "<" + str(
                feature_truncate_age) + "Ma_" + str(outputFile)
            print " "
            print "Process took " + str(round(time.time() - start,
                                              2)) + " seconds."
            print "--------------------------------------------"

    else:

        iso_output = eval("f" + str(previousFilter) + "_result")

        outputFeatureCollection = pgp.FeatureCollectionFileFormatRegistry()
        outputFeatureCollection.write(iso_output, outputFile)

        print "Output file:"
        print str(outputFile)
        print " "
        print "Process took " + str(round(time.time() - start,
                                          2)) + " seconds."
        print "--------------------------------------------"
Esempio n. 7
0
import sys

# Read files and reconstruction time from bash script
ReconTime = int(sys.argv[1])
RotFile = str(sys.argv[2])
RidgeFile = str(sys.argv[3])
IsochronFile = str(sys.argv[4])
IsoCOBFile = str(sys.argv[5])
# Date = str(sys.argv[6])

print("     Current reconstruction time is", ReconTime, "Ma")

# This section gets the features that have not been subducted at the desired time

# -- For the isochron file
featureCollection_iso = pgp.FeatureCollectionFileFormatRegistry()
features_iso = featureCollection_iso.read(IsochronFile)
IsochronFile_subset = pgp.FeatureCollection()

for feature in features_iso:
    if feature.get_valid_time()[1] <= ReconTime:
        IsochronFile_subset.add(feature)

# -- For the ridge file
featureCollection_ri = pgp.FeatureCollectionFileFormatRegistry()
features_ri = featureCollection_ri.read(RidgeFile)
RidgeFile_subset = pgp.FeatureCollection()

for feature in features_ri:
    if feature.get_valid_time()[1] <= ReconTime:
        RidgeFile_subset.add(feature)
def coregLoop(sampleData, agegrid, kinfolder, input_rotation_filename):
    '''
    coregLoop

    This script reconstructs a shapefile of points to their birth time and 
    coregisters each point with another set of points, or a raster file.

    METHOD:
    Takes a set of points 
    Rotates the points back to their birth position
    Determines the point's birth position geophysical properties (coregisters)
    '''
    #Set up a list to store the data

    timeSteps = 1
    noVariables = 18  #The number of variables you save
    Nshp = len(sampleData)

    #Initialise the array to store the data
    coregData = numpy.zeros((Nshp, timeSteps, noVariables))

    #Create a rotation model to rotate the points back in time
    file_registry = pygplates.FeatureCollectionFileFormatRegistry()
    rotation_feature_collection = file_registry.read(input_rotation_filename)
    rotation_model = pygplates.RotationModel([rotation_feature_collection])

    #Loop over all the sample, coregistering each one.
    for i, nshpSub in enumerate(sampleData):

        lat = nshpSub[0]
        lon = nshpSub[1]
        age = int(nshpSub[2])
        plateID = int(nshpSub[3])

        print("Deposit:", i, "of", Nshp, "Lat:", lat, "Lon:", lon, "Age:", age,
              "PlateID:", plateID)

        #Loop through each time step in the plate model
        for time in xrange(0, 230, 1):

            #If the point was formed at the current time (or 10Myr prior) then we
            #want to find the surrounding plate properties.
            #if  (time > (age-10)) and (time < (age+10)) or (time > (age+20)) and (time < (age+30)):
            if (time > (age - 1)) and (time < (age + timeSteps)):
                t = time - age
                # print t, time

                #A raster file, to coregister with, these points have already been rotated
                rasterfile = agegrid + str(time) + ".nc"
                [x, y, z] = gridRead(rasterfile)

                #A vector file to coregister with, these points have already been rotated

                f = numpy.loadtxt(kinfolder + "subStats_" + str(time) + ".csv",
                                  delimiter=',')
                lonlat = f[:, 0:2]

                #-------------------#
                #Reconstruct a point to its birth position
                #-------------------#
                latlonPoint = pygplates.LatLonPoint(lat, lon)
                point_to_rotate = pygplates.convert_lat_lon_point_to_point_on_sphere(
                    latlonPoint)

                finite_rotation = rotation_model.get_rotation(time, plateID)
                birthPosition = finite_rotation * point_to_rotate

                latlonBirth = pygplates.convert_point_on_sphere_to_lat_lon_point(
                    birthPosition)
                #allPoints = finite_rotation * pointSet_to_rotate

                latBirth = latlonBirth.get_latitude()
                lonBirth = latlonBirth.get_longitude()

                #-------------------#
                #Set the points for coregistering
                region = 5.0  #degrees

                #-------------------#
                #Coregisterring raster 1
                #-------------------#
                #Find the region in index units
                r = numpy.round(region / (x[1] - x[0]))

                #Find the index unit of lat and lon
                idxLon = (numpy.abs(x - lonBirth)).argmin()
                idxLat = (numpy.abs(y - latBirth)).argmin()

                #Raster 1
                c2 = coregRaster([idxLon, idxLat], z, r)
                #Hack to search further around the age grid if it can't find a match, note index units (not degrees)
                if numpy.isnan(c2):
                    c2 = coregRaster([idxLon, idxLat], z, r + 150.0)
                    print("Trying raster region: ", r + 150.0)

                #-------------------#
                #Coregisterring vector 1
                #-------------------#
                index = coregPoint([lonBirth, latBirth], lonlat, region)
                if index == 'inf':
                    print("trying index region", region + 15)
                    index = coregPoint([lonBirth, latBirth], lonlat,
                                       region + 15.0)

                if numpy.isnan(c2) or index == 'inf':
                    print("Skipping:", nshpSub, age, t, time, c2, index,
                          lonBirth, latBirth)

                else:
                    #Vector 1
                    segmentLength = f[index, 3]
                    slabLength = f[index, 9]
                    distSlabEdge = f[index, 15]

                    SPcoregNor = f[index, 4]
                    SPcoregPar = f[index, 12]
                    OPcoregNor = f[index, 5]
                    OPcoregPar = f[index, 13]
                    CONVcoregNor = f[index, 10]
                    CONVcoregPar = f[index, 11]

                    subPolCoreg = f[index, 8]
                    subOblCoreg = f[index, 7]

                    coregData[i, t, :] = [
                        lon, lat, lonBirth, latBirth, age, t, c2,
                        segmentLength, slabLength, distSlabEdge, SPcoregNor,
                        SPcoregPar, OPcoregNor, OPcoregPar, CONVcoregNor,
                        CONVcoregPar, subPolCoreg, subOblCoreg
                    ]

    #Return the filled coregistered array
    return (coregData)