def create_gpml_velocity_feature(longitude_array, latitude_array, filename=None, feature_type=None): # function to make a velocity mesh nodes at an arbitrary set of points defined in Lat # Long and Lat are assumed to be 1d arrays. multi_point = pygplates.MultiPointOnSphere( zip(latitude_array, longitude_array)) # Create a feature containing the multipoint feature. # optionally, define as 'MeshNode' type, so that GPlates will recognise it as a velocity layer if feature_type == 'MeshNode': meshnode_feature = pygplates.Feature( pygplates.FeatureType.create_from_qualified_string( 'gpml:MeshNode')) meshnode_feature.set_name('Velocity Mesh Nodes') else: meshnode_feature = pygplates.Feature() meshnode_feature.set_name('Multipoint Feature') meshnode_feature.set_geometry(multi_point) output_feature_collection = pygplates.FeatureCollection(meshnode_feature) if filename is not None: output_feature_collection.write(filename) else: return output_feature_collection
def create_profile_points(PtLons, PtLats, PointSpacing=0.5): polyline_features = [] polyline = pygplates.PolylineOnSphere(zip(PtLats, PtLons)) polyline_feature = pygplates.Feature() polyline_feature.set_geometry(polyline) polyline_features.append(polyline_feature) # Define point spacing in arc-degrees PointSpacing = 0.5 for feature in polyline_features: geometry = feature.get_geometry() arc_distance = np.degrees(geometry.get_arc_length()) tesselated_polyline = geometry.to_tessellated(np.radians(PointSpacing)) GCPts = tesselated_polyline.to_lat_lon_array() # Actually this is wrong - since it will only give 'near to' 15 degrees, not exact label_points = geometry.to_tessellated( np.radians(15)).to_lat_lon_array() arc_distance = np.degrees(geometry.get_arc_length()) ProfilePoints = np.linspace(-arc_distance / 2, arc_distance / 2, GCPts.shape[0]) return GCPts, ProfilePoints, arc_distance
def create_hierarchy_features(chains,reconstructed_polygons,tree_features=None,valid_time=None): #take plate chains and static polygons, and create a set of line features that # join up the centroid points of polygons based on their linkage in the rotation # hierarchy. # If tree_features in given as an existing list of features, the # new features will be appended. Otherwise a new feature is created. # valid time (optional) can be given as a tuple if tree_features is None: tree_features = [] polygon_centroids = get_polygon_centroids(reconstructed_polygons) for chain in chains: # First and last plate IDs in a chain always correspond to a static polygon. # So p0 and p1 should not be None. p0 = polygon_centroids[chain[0]] p1 = polygon_centroids[chain[-1]] feature = pygplates.Feature() simple_line = pygplates.PolylineOnSphere([p0,p1]) feature.set_geometry(simple_line.to_tessellated(np.radians(1))) feature.set_name(str(chain)) if valid_time is not None: feature.set_valid_time(valid_time[0],valid_time[1]) tree_features.append(feature) return tree_features
def reconstruct_vgps(vgp_features, rotation_model, anchor_plate_id=0): reconstructed_vgps = [] for vgp in vgp_features: time = vgp.get( pygplates.PropertyName.gpml_average_age).get_value().get_double() PlateID = vgp.get_reconstruction_plate_id() geometry = vgp.get(pygplates.PropertyName.gpml_pole_position ).get_value().get_geometry() #print time,PlateID,geometry.to_lat_lon() # Get rotation for data point and reconstruct to Birth Time feature_rotation = rotation_model.get_rotation(time, PlateID, anchor_plate_id) reconstructed_geometry = feature_rotation * geometry #print PlateID,reconstructed_geometry.to_lat_lon() new_feature = pygplates.Feature() new_feature.set_geometry(reconstructed_geometry) new_feature.set_reconstruction_plate_id(PlateID) new_feature.set_valid_time(time, -999) new_feature.set(pygplates.PropertyName.gpml_average_age, pygplates.XsDouble(time)) new_feature.set( pygplates.PropertyName.gpml_pole_a95, vgp.get(pygplates.PropertyName.gpml_pole_a95).get_value()) reconstructed_vgps.append(new_feature) return reconstructed_vgps
def create_mesh_node_feature_from_points(points): """Create a GPlates 'gpml:MeshNode' feature from a sequence of points (pygplates.PointOnSphere objects).""" # Create the new multipoint feature. # This type of feature 'MeshNode' will cause GPlates to automatically create a velocity layer upon loading the points. mesh_node_feature = pygplates.Feature( pygplates.FeatureType.create_gpml('MeshNode')) multipoint = pygplates.MultiPointOnSphere(points) mesh_node_feature.add(pygplates.PropertyName.create_gpml('meshPoints'), pygplates.GmlMultiPoint(multipoint)) # Add time period property. mesh_node_feature.add( pygplates.PropertyName.create_gml('validTime'), pygplates.GmlTimePeriod( pygplates.GeoTimeInstant.create_distant_past(), pygplates.GeoTimeInstant.create_distant_future())) # Add reconstruction plate id property (use plate id zero). mesh_node_feature.add( pygplates.PropertyName.create_gpml('reconstructionPlateId'), pygplates.GpmlConstantValue(pygplates.GpmlPlateId(0))) return mesh_node_feature
def get_masked_multipoint(coords, masking_array, plate_partitioner, valid_time=None): # Inputs: # a list of coordinates (typically a regular grid of Lat/Long points), # an array of indices into that list of coordinates, # a set of polygons to use for cookie-cutting # a valid time to assign to the output features # Returns: # a multipoint feature that multipoint_feature = pygplates.Feature() multipoint_feature.set_geometry( pygplates.MultiPointOnSphere( zip( np.array(coords[0])[masking_array], np.array(coords[1])[masking_array]))) (pg_points_masked, dummy) = plate_partitioner.partition_features( multipoint_feature, partition_return=pygplates.PartitionReturn. separate_partitioned_and_unpartitioned) if valid_time is not None: for feature in pg_points_masked: feature.set_valid_time(valid_time[0], valid_time[1]) return pg_points_masked
def __make_GPML_velocity_feature(self, coords): """ function to make a velocity mesh nodes at an arbitrary set of points defined in coords[# of points, 3] = x, y, z""" # Add points to a multipoint geometry multi_point = pygplates.MultiPointOnSphere([ pygplates.PointOnSphere(x=coords[i, 0], y=coords[i, 1], z=coords[i, 2], normalise=True) for i in range(numpy.shape(coords)[0]) ]) # Create a feature containing the multipoint feature, and defined as MeshNode type meshnode_feature = pygplates.Feature( pygplates.FeatureType.create_from_qualified_string( 'gpml:MeshNode')) meshnode_feature.set_geometry(multi_point) meshnode_feature.set_name('Velocity Mesh Nodes from pygplates') output_feature_collection = pygplates.FeatureCollection( meshnode_feature) # NB: at this point, the feature could be written to a file using # output_feature_collection.write('myfilename.gpmlz') # for use within the notebook, the velocity domain feature is returned from the function return output_feature_collection
def paleobathymetry_from_topologies(resolved_topologies, shared_boundary_sections, deep_ocean_features, model='GDH1', half_spreading_rate=50.): # Approximation of paleobathymetry based on distance to MORs # given some resolved topologies, and some point features (typically in the deep ocean), # calculates the distance of each point to the nearest mid-ocean ridge segment that # forms part of the boundary that the point is located within - then, determines # the implied age assuming a constant spreading rate and given age-depth model pX, pY, pZ = find_distance_to_nearest_ridge(resolved_topologies, shared_boundary_sections, deep_ocean_features) age = np.array(pZ) / half_spreading_rate pdepth = age2depth(age, model=model) pdepth_points = [] for (lon, lat, depth) in zip(pX, pY, pdepth): point_feature = pygplates.Feature() point_feature.set_geometry(pygplates.PointOnSphere(lat, lon)) point_feature.set_shapefile_attribute('depth', np.float(depth)) pdepth_points.append(point_feature) return pdepth_points
def create_hierarchy_features(chains, reconstructed_static_polygons, tree_features=None, valid_time=None): #take plate chains and static polygons, and create a set of line features that # join up the centroid points of polygons based on their linkage in the rotation # hierarchy. # If tree_features in given as an existing list of features, the # new features will be appended. Otherwise a new feature is created. # valid time (optional) can be given as a tuple if tree_features is None: tree_features = [] for chain in chains: p0 = GetPolygonCentroid(reconstructed_static_polygons, chain[0]) p1 = GetPolygonCentroid(reconstructed_static_polygons, chain[-1]) if (len(p0) > 0) & (len(p1) > 0): # in theory this if statement not needed now? feature = pygplates.Feature() simple_line = pygplates.PolylineOnSphere([p0, p1]) feature.set_geometry(simple_line.to_tessellated(np.radians(1))) feature.set_name(str(chain)) if valid_time is not None: feature.set_valid_time(valid_time[0], valid_time[1]) tree_features.append(feature) return tree_features
def merge_polygons(polygons,rotation_model, time=0,sampling=1.,area_threshold=None,filename=None, return_raster=False): multipoints = create_gpml_regular_long_lat_mesh(sampling) grid_dims = (int(180/sampling)+1,int(360/sampling)+1) for multipoint in multipoints: for mp in multipoint.get_all_geometries(): points = mp.to_lat_lon_point_list() bi = run_grid_pip(time,points,polygons,rotation_model,grid_dims) if return_raster: return bi else: # To handle edge effects, pad grid before making contour polygons ## --- start pad_hor = np.zeros((1,bi.shape[1])) pad_ver = np.zeros((bi.shape[0]+2,1)) pad1 = np.vstack((pad_hor,bi,pad_hor)) # add row of zeros to top and bottom pad2 = np.hstack((pad_ver,pad1,pad_ver)) # add row of zeros to left and right #pad3 = np.hstack((pad2,pad_ver)) contours = measure.find_contours(pad2, 0.5, fully_connected='low') ## --- end contour_polygons = [] contour_features = [] for n,cp in enumerate(contours): # To handle edge effects again - strip off parts of polygon # due to padding, and adjust from image coordinates to long/lat # --- start cp[:,1] = (cp[:,1]*sampling)-sampling cp[:,0] = (cp[:,0]*sampling)-sampling cp[np.where(cp[:,0]<0.),0] = 0 cp[np.where(cp[:,0]>180.),0] = 180 cp[np.where(cp[:,1]<0.),1] = 0 cp[np.where(cp[:,1]>360.),1] = 360 ## --- end cpf = pygplates.PolygonOnSphere(zip(cp[:,0]-90,cp[:,1]-180)) contour_polygons.append(cpf) feature = pygplates.Feature() feature.set_geometry(cpf) contour_features.append(feature) if filename is not None: pygplates.FeatureCollection(contour_features).write(filename) else: return contour_features
def create_coverage_feature_from_convergence_data(subduction_convergence_data, time): """Create a feature with a coverage geometry containing the calculated convergence and absolute velocity data. Parameters ---------- subduction_convergence_data : list of tuples The subduction convergence data calculated by :func:`subduction_convergence`. Each tuple in the list contains the calculated data for a single sample point on a subduction zone line. time: float The reconstruction time associated with the subduction convergence data. Returns ------- pygplates.Feature The feature with a coverage geometry containing the calculated convergence and absolute velocity data. """ # Convert the list of tuples (one tuple per sample point) into a tuple of lists (one list per data parameter). (all_lon, all_lat, all_convergence_velocity_magnitude_cm_per_yr, all_convergence_obliquity_degrees, all_absolute_velocity_magnitude_cm_per_yr, all_absolute_obliquity_degrees, all_subducting_length_degrees, all_subducting_arc_normal_azimuth_degrees, all_subducting_plate_id, all_overriding_plate_id) = zip(*subduction_convergence_data) # Put all convergence data for the current reconstruction time into a single feature. coverage_feature = pygplates.Feature() # Make it only appear at 'time'. coverage_feature.set_valid_time(time + 0.5, time - 0.5) # Add each data parameter as a separate scalar coverage. coverage_geometry = pygplates.MultiPointOnSphere(zip(all_lat, all_lon)) coverage_scalars = { pygplates.ScalarType.create_gpml('ConvergenceVelocityMagnitude'): all_convergence_velocity_magnitude_cm_per_yr, pygplates.ScalarType.create_gpml('ConvergenceObliquityDegrees'): all_convergence_obliquity_degrees, pygplates.ScalarType.create_gpml('AbsoluteVelocityMagnitude'): all_absolute_velocity_magnitude_cm_per_yr, pygplates.ScalarType.create_gpml('AbsoluteObliquityDegrees'): all_absolute_obliquity_degrees, pygplates.ScalarType.create_gpml('SubductingLengthDegrees'): all_subducting_length_degrees, pygplates.ScalarType.create_gpml('SubductingArcNormalAzimuthDegrees'): all_subducting_arc_normal_azimuth_degrees, pygplates.ScalarType.create_gpml('SubductingPlateId'): all_subducting_plate_id, pygplates.ScalarType.create_gpml('OverridingPlateId'): all_overriding_plate_id, } coverage_feature.set_geometry((coverage_geometry, coverage_scalars)) return coverage_feature
def create_seed_point_feature(plat,plon,plate_id,conjugate_plate_id,time): # Create a gpml point feature given some attributes point = pygplates.PointOnSphere(plat,plon) point_feature = pygplates.Feature() point_feature.set_geometry(point) point_feature.set_valid_time(time,0.) point_feature.set_reconstruction_plate_id(plate_id) point_feature.set_conjugate_plate_id(conjugate_plate_id) point_feature.set_name('Slab Edge | plate %d | rel. plate %d' % (plate_id,conjugate_plate_id)) return point_feature
def test_post(request): if not request.method == "POST": return HttpResponseBadRequest('expecting post requests!') else: #print request.POST json_feature_collection = json.loads(request.body) model = request.GET.get('model', settings.MODEL_DEFAULT) features = [] for json_feature in json_feature_collection['features']: feature = pygplates.Feature() point = json_feature['geometry']['coordinates'] feature.set_geometry(pygplates.PointOnSphere(point[1], point[0])) feature.set_valid_time(json_feature['properties']['age'], 0) features.append(feature) model_dict = get_reconstruction_model_dict(model) rotation_model = pygplates.RotationModel([ str('%s/%s/%s' % (settings.MODEL_STORE_DIR, model, rot_file)) for rot_file in model_dict['RotationFile'] ]) static_polygons_filename = str( '%s/%s/%s' % (settings.MODEL_STORE_DIR, model, model_dict['StaticPolygons'])) # assign plate-ids to points using static polygons assigned_point_features = pygplates.partition_into_plates( static_polygons_filename, rotation_model, features, properties_to_copy=[ pygplates.PartitionProperty.reconstruction_plate_id ]) feature_collection = pygplates.FeatureCollection( assigned_point_features) reconstructed_features = reconstruct_to_birth_time( feature_collection, rotation_model) # prepare the response to be returned ret = '{"coordinates":[' for g in reconstructed_features: ret += '[{0:5.2f},{1:5.2f}],'.format( g.get_geometry().to_lat_lon()[1], g.get_geometry().to_lat_lon()[0]) ret = ret[0:-1] ret += ']}' return HttpResponse(ret, content_type='application/json')
def write_trees_to_file(input_features, rotation_model, filename, reconstruction_time_range, time_step=1, polygon_type='static', root_feature_filename=None): reconstruction_times = np.arange(reconstruction_time_range[0], reconstruction_time_range[1]+time_step, time_step) tree_features = None root_centroid_features = [] for reconstruction_time in reconstruction_times: print 'working on time %0.2f Ma' % reconstruction_time reconstructed_polygons = [] if polygon_type is 'topological': pygplates.resolve_topologies(input_features, rotation_model, reconstructed_polygons, reconstruction_time) else: pygplates.reconstruct(input_features, rotation_model, reconstructed_polygons, reconstruction_time) uniq_plates_from_polygons = get_unique_plate_ids_from_reconstructed_features(reconstructed_polygons) reconstruction_tree = rotation_model.get_reconstruction_tree(reconstruction_time) chains = get_plate_chains(uniq_plates_from_polygons, reconstruction_tree) tree_features = create_hierarchy_features(chains, reconstructed_polygons, tree_features, valid_time=(reconstruction_time+time_step/2., reconstruction_time-time_step/2.)) if root_feature_filename is not None: polygon_centroids = get_polygon_centroids(reconstructed_polygons) root_plates = get_root_static_polygon_plate_ids(reconstruction_tree, uniq_plates_from_polygons) for root_plate in root_plates: p0 = polygon_centroids[root_plate] feature = pygplates.Feature() feature.set_geometry(pygplates.PointOnSphere(p0)) feature.set_name(str(root_plate)) feature.set_valid_time(reconstruction_time+time_step/2., reconstruction_time-time_step/2.) root_centroid_features.append(feature) tree_feature_collection = pygplates.FeatureCollection(tree_features) tree_feature_collection.write(filename) if root_feature_filename is not None: tree_feature_collection = pygplates.FeatureCollection(root_centroid_features) tree_feature_collection.write(root_feature_filename)
def grdcontour2feature(grdfile,clevel,return_polygons=True): # call GMT to get a single contour at the specified value of clevel call_system_command(['gmt', 'grdcontour', grdfile, '-Rd', '-C+%0.8f' % clevel, '-S4', '-Dcontour_%c.txt']) # read in the GMT delimited xyz ascii file, # create a list of lists with polygon coordinates f = open('./contour_C.txt', 'r') polygons = [] contourlist = [] for line in f: if line[0] == '>': if len(contourlist)>0: polygons.append(contourlist) contourlist = [] else: line = line.split() contourlist.append([float(j) for j in line]) #break # create gplates-format features polyline_features = [] for p in polygons: pf = pygplates.PolylineOnSphere(zip(list(zip(*p))[1],list(zip(*p))[0])) polyline_features.append(pf) # use join to handle polylines split across dateline joined_polyline_features = pygplates.PolylineOnSphere.join(polyline_features) if return_polygons: # force polylines to be polygons joined_polygon_features = [] for geom in joined_polyline_features: polygon = pygplates.Feature() polygon.set_geometry(pygplates.PolygonOnSphere(geom)) joined_polygon_features.append(polygon) return joined_polygon_features else: return joined_polyline_features
def make_GPML_velocity_feature(Long,Lat): # Add points to a multipoint geometry multi_point = pygplates.MultiPointOnSphere([(float(lat),float(lon)) for lat, lon in zip(Lat,Long)]) # Create a feature containing the multipoint feature, and defined as MeshNode type meshnode_feature = pygplates.Feature(pygplates.FeatureType.create_from_qualified_string('gpml:MeshNode')) meshnode_feature.set_geometry(multi_point) meshnode_feature.set_name('Velocity Mesh Nodes from pygplates') output_feature_collection = pygplates.FeatureCollection(meshnode_feature) # NB: at this point, the feature could be written to a file using # output_feature_collection.write('myfilename.gpmlz') # for use within the notebook, the velocity domain feature is returned from the function return output_feature_collection
def subduction(request): if not request.method == "POST": return HttpResponseBadRequest('expecting post requests!') else: #print request.POST json_feature_collection = json.loads(request.body) model = request.GET.get('model', settings.MODEL_DEFAULT) features = [] for json_feature in json_feature_collection['features']: feature = pygplates.Feature() point = json_feature['geometry']['coordinates'] feature.set_geometry(pygplates.PointOnSphere(point[1], point[0])) feature.set_valid_time(json_feature['properties']['age'], 0) features.append(feature) model_dict = get_reconstruction_model_dict(model) rotation_model = pygplates.RotationModel([ str('%s/%s/%s' % (settings.MODEL_STORE_DIR, model, rot_file)) for rot_file in model_dict['RotationFile'] ]) static_polygons_filename = str( '%s/%s/%s' % (settings.MODEL_STORE_DIR, model, model_dict['StaticPolygons'])) # assign plate-ids to points using static polygons assigned_point_features = pygplates.partition_into_plates( static_polygons_filename, rotation_model, features, properties_to_copy=[ pygplates.PartitionProperty.reconstruction_plate_id ]) seed_point_features = pygplates.FeatureCollection( assigned_point_features) df_OreDepositBirthTimeStats = subduction_parameters( seed_point_features, rotation_model) html_table = df_OreDepositBirthTimeStats.to_html(index=False) return render(request, 'list_template.html', {'html_table': html_table})
def random_points_feature(N,filename=None): # function to call Marsaglia's method and return # feature collection or save to file points = marsaglias_method(N) #multipoint = pygplates.MultiPointOnSphere((points.T)) multipoint_feature = pygplates.Feature() multipoint_feature.set_geometry(pygplates.MultiPointOnSphere((points.T))) multipoint_feature.set_name('Random Points from Marsaglia''s method') multipoint_feature_collection = pygplates.FeatureCollection(multipoint_feature) if filename is not None: multipoint_feature_collection.write(filename) else: return multipoint_feature_collection
def create_gpml_velocity_feature(longitude_array, latitude_array): # function to make a velocity mesh nodes at an arbitrary set of points defined in Lat # Long and Lat are assumed to be 1d arrays. multi_point = pygplates.MultiPointOnSphere( zip(latitude_array, longitude_array)) # Create a feature containing the multipoint feature. # optionally, define as 'MeshNode' type, so that GPlates will recognise it as a velocity layer meshnode_feature = pygplates.Feature() meshnode_feature.set_name('Multipoint Feature') meshnode_feature.set_geometry(multi_point) output_feature_collection = pygplates.FeatureCollection(meshnode_feature) return output_feature_collection
def create_gpml_crustal_thickness(longitude_array,latitude_array,thickness,filename=None): multi_point = pygplates.MultiPointOnSphere(zip(latitude_array,longitude_array)) scalar_coverages = { pygplates.ScalarType.create_gpml('CrustalThickness'): thickness} ct_feature = pygplates.Feature() ct_feature.set_geometry((multi_point,scalar_coverages)) ct_feature.set_name('Crustal Thickness') output_feature_collection = pygplates.FeatureCollection(ct_feature) if filename is not None: output_feature_collection.write(filename) else: return output_feature_collection
def get_vertical_change_multipoints(pg_features,t1,t2,psl_t1,psl_t2, points,spatial_tree_of_uniform_recon_points, rotation_model,plot=False): # NOT WORKING DUE TO LACK OF SUPPORT FOR SCALAR COVERAGES print 'Working on interpolation from %0.2f Ma to %0.2f Ma .....' % (t1,t2) plate_partitioner = pygplates.PlatePartitioner(pg_features, rotation_model, reconstruction_time=t1) (distance_to_land_t1, distance_to_psl_t1, distance_to_land_t2, distance_to_psl_t2, regression_msk, transgression_msk, always_land_msk) = get_change_masks(t1,points,spatial_tree_of_uniform_recon_points, psl_t1,psl_t2,rotation_model) coords = zip(*[point.to_lat_lon() for point in points]) pg_points_regression = get_masked_multipoint(coords,regression_msk,plate_partitioner, valid_time=[t2,t1+0.01]) pg_points_transgression = get_masked_multipoint(coords,transgression_msk,plate_partitioner, valid_time=[t2,t1+0.01]) pg_points_always_land = get_masked_multipoint(coords,always_land_msk,plate_partitioner, valid_time=[t2,t1]) # make a scalar coverage multi_point = pygplates.MultiPointOnSphere(points) scalar_coverages = { pygplates.ScalarType.create_gpml('distance_to_land_t1'): distance_to_land_t1, pygplates.ScalarType.create_gpml('distance_to_psl_t1'): distance_to_psl_t1, pygplates.ScalarType.create_gpml('distance_to_land_t2'): distance_to_land_t2, pygplates.ScalarType.create_gpml('distance_to_psl_t2'): distance_to_psl_t2} sc_feature = pygplates.Feature() sc_feature.set_geometry((multi_point,scalar_coverages)) sc_feature.set_name('Paleotopography Test Points') (cc_sc_features, dummy) = plate_partitioner.partition_features(sc_feature, partition_return = pygplates.PartitionReturn.separate_partitioned_and_unpartitioned) pygplates.FeatureCollection(cc_sc_features).write('./tween_feature_collections/mountain_scalar_coverages_%0.2fMa_%0.2fMa.gpmlz' % (t1,t2))
def get_plate_id(lons, lats, static_polygons, rotation_model): p_len = len(lons) assert (p_len == len(lats)), 'The lons and lats must have the same length.' point_features = [] for i in range(p_len): point = pygplates.PointOnSphere(float(lats[i]), float(lons[i])) point_feature = pygplates.Feature() point_feature.set_geometry(point) point_feature.set_name(str(i)) point_features.append(point_feature) plate_ids = [np.nan] * p_len # partition features points = pygplates.partition_into_plates(static_polygons, rotation_model, point_features) for p in points: plate_ids[int(p.get_name())] = p.get_reconstruction_plate_id() return plate_ids
def get_isochrons_for_ridge_snapshot(topology_features, rotation_filename, out_dir, ridge_time, time_step, youngest_seed_time=0, ridge_sampling=2.): print("... Writing seed points along a ridge") if not os.path.exists(out_dir): os.makedirs(out_dir) rotation_model = pygplates.RotationModel(rotation_filename) oldest_seed_time = ridge_time all_longitudes = [] all_latitudes = [] all_ages = [] # The first step is to generate points along the ridge resolved_topologies = [] shared_boundary_sections = [] pygplates.resolve_topologies(topology_features, rotation_filename, resolved_topologies, oldest_seed_time, shared_boundary_sections) # Previous points are on the MOR, current are moved by one time step off MOR. curr_points = get_mid_ocean_ridges(shared_boundary_sections, rotation_model, oldest_seed_time, time_step, ridge_sampling) # Write out the ridge point born at 'ridge_time' but their position at 'ridge_time - time_step'. mor_point_features = [] for curr_point in curr_points: feature = pygplates.Feature() feature.set_geometry(curr_point) feature.set_valid_time(ridge_time, -999) # delete - time_step mor_point_features.append(feature) pygplates.FeatureCollection(mor_point_features).write( './{:s}/MOR_plus_one_points_{:0.2f}.gmt'.format(out_dir, ridge_time)) # print( "... Finished writing seed points along the mid ocean ridge for {:0.2f} Ma" .format(ridge_time))
def force_polygon_geometries(input_features): # given any pygplates feature collection, creates an output feature collection # where all geometries are polygons based on the input geometries # intended for use in forcing features that are strictly polylines to close polygons = [] for feature in input_features: for geom in feature.get_all_geometries(): polygon = pygplates.Feature() polygon.set_geometry(pygplates.PolygonOnSphere(geom)) polygon.set_reconstruction_plate_id(feature.get_reconstruction_plate_id()) # some features in COBTerranes had invalid time ranges - these with throw an error if # we try to create a new feature with same times if feature.get_valid_time()[0]>=feature.get_valid_time()[1]: polygon.set_valid_time(feature.get_valid_time()[0],feature.get_valid_time()[1]) polygons.append(polygon) polygon_features = pygplates.FeatureCollection(polygons) return polygon_features
def reconstruct_points(request): points = request.GET.get('points', None) plate_id = request.GET.get('pid', None) time = request.GET.get('time', None) rotation_model = pygplates.RotationModel( MODEL_DEFAULT+"Seton_etal_ESR2012_2012.1.rot") static_polygons_filename = \ MODEL_DEFAULT+"Seton_etal_ESR2012_StaticPolygons_2012.1.gpmlz" point_features = [] if points: ps = points.split(',') if len(ps)%2==0: for lat,lon in zip(ps[1::2], ps[0::2]): point_feature = pygplates.Feature() point_feature.set_geometry(pygplates.PointOnSphere(float(lat),float(lon))) point_features.append(point_feature) #for f in point_features: # f.set_reconstruction_plate_id(int(plate_id)) assigned_point_features = pygplates.partition_into_plates( static_polygons_filename, rotation_model, point_features, properties_to_copy = [ pygplates.PartitionProperty.reconstruction_plate_id, pygplates.PartitionProperty.valid_time_period]) assigned_point_feature_collection = pygplates.FeatureCollection(assigned_point_features) reconstructed_feature_geometries = [] pygplates.reconstruct(assigned_point_feature_collection, rotation_model, reconstructed_feature_geometries, float(time)) ret='{"coordinates":[' for g in reconstructed_feature_geometries: ret+='[{0:5.2f},{1:5.2f}],'.format( g.get_reconstructed_geometry().to_lat_lon()[1], g.get_reconstructed_geometry().to_lat_lon()[0]) ret=ret[0:-1] ret+=']}' return HttpResponse(ret, content_type='application/json')
def make_GPML_velocity_feature(Long,Lat): # function to make a velocity mesh nodes at an arbitrary set of points defined in Lat # Long and Lat are assumed to be 1d arrays. # Add points to a multipoint geometry SeedPoints = zip(Lat,Long) points = [] for j in range(0,len(SeedPoints)): points.append(SeedPoints[j]) multi_point = pygplates.MultiPointOnSphere(points) # Create a feature containing the multipoint feature, and defined as MeshNode type meshnode_feature = pygplates.Feature(pygplates.FeatureType.create_from_qualified_string('gpml:MeshNode')) meshnode_feature.set_geometry(multi_point) meshnode_feature.set_name('Velocity Mesh Nodes from pygplates') output_feature_collection = pygplates.FeatureCollection(meshnode_feature) # NB: at this point, the feature could be written to a file using # output_feature_collection.write('myfilename.gpmlz') # for use within the notebook, the velocity domain feature is returned from the function return output_feature_collection
def reconstruct_coastlines(time): shp_path = settings.MODEL_STORE_DIR+'/'+settings.MODEL_DEFAULT+'/coastlines_low_res/Seton_etal_ESR2012_Coastlines_2012.shp' import shapefile sf = shapefile.Reader(shp_path) features = [] for record in sf.shapeRecords(): if record.shape.shapeType != 5: continue for idx in range(len(record.shape.parts)): start_idx = record.shape.parts[idx] end_idx = len(record.shape.points) if idx < (len(record.shape.parts) -1): end_idx = record.shape.parts[idx+1] polygon_feature = pygplates.Feature() points = record.shape.points[start_idx:end_idx] polygon_feature.set_geometry( pygplates.PolygonOnSphere([(lat,lon) for lon, lat in points])) polygon_feature.set_reconstruction_plate_id(int(record.record[0])) features.append(polygon_feature) break feature_collection = pygplates.FeatureCollection(features) reconstructed_polygons = [] model_dict = get_reconstruction_model_dict(settings.MODEL_DEFAULT) rotation_model = pygplates.RotationModel([str('%s/%s/%s' % (settings.MODEL_STORE_DIR,settings.MODEL_DEFAULT,rot_file)) for rot_file in model_dict['RotationFile']]) pygplates.reconstruct( feature_collection, rotation_model, reconstructed_polygons, float(time)) return reconstructed_polygons
for point_index, polygon_feature in enumerate( polygon_features_containing_points): points_in_polygon = polygon_feature_to_points_mapping.setdefault( polygon_feature, []) points_in_polygon.append(points[point_index]) # Create multi-point features. multi_point_features = [] for polygon_feature, points_in_polygon in polygon_feature_to_points_mapping.iteritems( ): multi_point_feature = pygplates.Feature() multi_point_feature.set_geometry( pygplates.MultiPointOnSphere(points_in_polygon)) # If points contained by any polygon then assign its plate ID, otherwise no plate ID assigned. if polygon_feature is not None: begin_time, end_time = polygon_feature.get_valid_time() multi_point_feature.set_valid_time(begin_time, end_time) multi_point_feature.set_reconstruction_plate_id( polygon_feature.get_reconstruction_plate_id())
def reconstruct_raster_stage(static_polygon_features, rotation_model, time_from, time_to, uniform_recon_points, spatial_tree_of_uniform_recon_points, anchor_plate_id=0): print 'Reconstruct static polygons...' # Reconstruct the multipoint feature. recon_static_polygon_features = [] pygplates.reconstruct(static_polygon_features, rotation_model, recon_static_polygon_features, time_to, anchor_plate_id=anchor_plate_id) # Extract the polygons and plate IDs from the reconstructed static polygons. recon_static_polygons = [] recon_static_polygon_plate_ids = [] for recon_static_polygon_feature in recon_static_polygon_features: recon_plate_id = recon_static_polygon_feature.get_feature( ).get_reconstruction_plate_id() recon_polygon = recon_static_polygon_feature.get_reconstructed_geometry( ) recon_static_polygon_plate_ids.append(recon_plate_id) recon_static_polygons.append(recon_polygon) print 'Find static polygons...' # Find the reconstructed static polygon (plate IDs) containing the uniform (reconstructed) points. # # The order (and length) of 'recon_point_plate_ids' matches the order (and length) of 'uniform_recon_points'. # Points outside all static polygons return a value of None. recon_point_plate_ids = points_in_polygons.find_polygons_using_points_spatial_tree( uniform_recon_points, spatial_tree_of_uniform_recon_points, recon_static_polygons, recon_static_polygon_plate_ids) print 'Group by polygons...' # Group recon points with plate IDs so we can later create one multipoint per plate. recon_points_grouped_by_plate_id = {} for point_index, point_plate_id in enumerate(recon_point_plate_ids): # Reject any points outside all reconstructed static polygons. if point_plate_id is None: continue # Add empty list to dict if first time encountering plate ID. if point_plate_id not in recon_points_grouped_by_plate_id: recon_points_grouped_by_plate_id[point_plate_id] = [] # Add to list of points associated with plate ID. recon_point = uniform_recon_points[point_index] recon_points_grouped_by_plate_id[point_plate_id].append(recon_point) print 'Reverse reconstruct points...' # Reconstructed points. recon_point_lons = [] recon_point_lats = [] # Present day points associated with reconstructed points. point_lons = [] point_lats = [] # Create a multipoint feature for each plate ID and reverse-reconstruct it to get present-day points. # # Iterate over key/value pairs in dictionary. for plate_id, recon_points_in_plate in recon_points_grouped_by_plate_id.iteritems( ): # Reverse reconstructing a multipoint is much faster than individually reverse-reconstructing points. multipoint_feature = pygplates.Feature() multipoint_feature.set_geometry( pygplates.MultiPointOnSphere(recon_points_in_plate)) multipoint_feature.set_reconstruction_plate_id(plate_id) # Reverse reconstruct the multipoint feature. pygplates.reverse_reconstruct(multipoint_feature, rotation_model, time_to, anchor_plate_id=anchor_plate_id) #Forward reconstruct multipoint to multipoint_at_from_time = [] pygplates.reconstruct(multipoint_feature, rotation_model, multipoint_at_from_time, time_from, anchor_plate_id=anchor_plate_id) # Extract reverse-reconstructed geometry. multipoint = multipoint_at_from_time[0].get_reconstructed_geometry() # Collect present day and associated reconstructed points. for point_index, point in enumerate(multipoint): lat, lon = point.to_lat_lon() point_lons.append(lon) point_lats.append(lat) recon_point = recon_points_in_plate[point_index] recon_lat, recon_lon = recon_point.to_lat_lon() recon_point_lons.append(recon_lon) recon_point_lats.append(recon_lat) print 'Sample present-day grid...' # Query present-day grid using present-day points. # # TODO: Note sure what happens in regions where there's no data in grid (need to ignore those points). #data = data_grid.ev(point_lons, point_lats) #data = [1.0] * len(recon_point_lons) #data = sample_grid_using_scipy(point_lons,point_lats,grdfile) return recon_point_lons, recon_point_lats, point_lons, point_lats
subducting_points = [] subducting_sed_thicknesses = [] subducting_sediment_volumes_metres_3_per_year_per_metre = [] convergence_normal_velocities_cms_per_year = [] for ( lon, lat, sed_thickness, subducting_sediment_volume_metres_3_per_year_per_metre, convergence_normal_velocity_cms_per_year) in subducting_lon_lat_thickness_velocity_volume_list: subducting_points.append(pygplates.PointOnSphere(lat, lon)) subducting_sed_thicknesses.append(sed_thickness) subducting_sediment_volumes_metres_3_per_year_per_metre.append(subducting_sediment_volume_metres_3_per_year_per_metre) convergence_normal_velocities_cms_per_year.append(convergence_normal_velocity_cms_per_year) # Create a scalar coverage feature to display sediment thicknesses in GPlates. subducting_thickness_feature = pygplates.Feature() subducting_thickness_feature.set_geometry(( pygplates.MultiPointOnSphere(subducting_points), {pygplates.ScalarType.create_gpml('subducting_sed_thick') : subducting_sed_thicknesses, pygplates.ScalarType.create_gpml('sed_volume_m_3_per_year_per_m') : subducting_sediment_volumes_metres_3_per_year_per_metre, pygplates.ScalarType.create_gpml('conv_normal_vel_cms_year') : convergence_normal_velocities_cms_per_year})) # Only want to display this feature at 'time' Ma. subducting_thickness_feature.set_valid_time(time + 0.5, time - 0.5) subducting_thickness_features.append(subducting_thickness_feature) pygplates.FeatureCollection(subducting_thickness_features).write('subducting_thicknesses.gpmlz') sys.exit(0)