def load_paleogeography(pg_dir, env_list=None, single_file=False, env_field='ENV'): # default environment_list is the format used for Cao++ 2017 if env_list is None: env_list = ['lm', 'm', 'sm', 'i'] if single_file: print pg_dir features = pygplates.FeatureCollection(pg_dir) pg_features = [] for feature in features: if feature.get_shapefile_attribute(env_field) in env_list: feature.set_shapefile_attribute( 'Layer', feature.get_shapefile_attribute(env_field)) pg_features.append(feature) else: pg_features = [] for env in env_list: try: filename = glob.glob('%s/%s_*.shp' % (pg_dir, env)) print filename features = pygplates.FeatureCollection(filename[0]) for feature in features: feature.set_shapefile_attribute('Layer', env) pg_features.append(feature) except: print 'no features of type %s' % env return pg_features
def get_change_mask_multipoints(pg_features,t1,t2,psl_t1,psl_t2, points,spatial_tree_of_uniform_recon_points, rotation_model,plot=False): 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]) pygplates.FeatureCollection(pg_points_regression).write('./tween_feature_collections/mountain_regression_%0.2fMa_%0.2fMa.gpmlz' % (t1,t2)) pygplates.FeatureCollection(pg_points_transgression).write('./tween_feature_collections/mountain_transgression_%0.2fMa_%0.2fMa.gpmlz' % (t1,t2)) pygplates.FeatureCollection(pg_points_always_land).write('./tween_feature_collections/mountain_stable_%0.2fMa_%0.2fMa.gpmlz' % (t1,t2))
def merge_features(young_time, old_time, time_step, outdir, cleanup=False): # merge the seed points from the 'initial condition' and generated through # the reconstructed mid-ocean ridges through time into a single file # TODO # - why not use gpmlz NO DON'T USE GPML, SERIOUSLY # - filenames should not be hard-coded merge_features = [] for time in np.arange(old_time, young_time - time_step, -time_step): filename = './{:s}/MOR_plus_one_points_{:0.2f}.gmt'.format( outdir, time) print('merging seeds from file {:s}'.format(filename)) features = pygplates.FeatureCollection(filename) for feature in features: merge_features.append(feature) merge_filename = './{:s}/MOR_plus_one_merge_{:0.2f}_{:0.2f}.gmt'.format( outdir, young_time, old_time) print('Attempting to write merged file {:s}'.format(merge_filename)) pygplates.FeatureCollection(merge_features).write(merge_filename) if cleanup: # remove old files that are no longer needed for f in glob.glob("{:s}/MOR_plus_one_points_*.gmt".format(outdir)): os.remove(f) for f in glob.glob( "{:s}/MOR_plus_one_points_*.gmt.gplates.xml".format(outdir)): os.remove(f)
def generate_rotation_feature(rotation_filenames): rotation_features = pygplates.FeatureCollection() for rotation_filename in rotation_filenames: rotation_features.add(pygplates.FeatureCollection(rotation_filename)) return rotation_features
def test_post_files(request): if not request.method == "POST": return HttpResponseBadRequest('expecting post requests!') else: with open('%s/tmp.gpmlz' % settings.MEDIA_ROOT, 'wb+') as destination: for chunk in request.FILES['file1'].chunks(): destination.write(chunk) with open('%s/tmp.rot' % settings.MEDIA_ROOT, 'wb+') as destination: for chunk in request.FILES['file2'].chunks(): destination.write(chunk) filename = 'reconstruct_to_birth_time.gpmlz' rotation_model = pygplates.RotationModel('%s/tmp.rot' % settings.MEDIA_ROOT) features = pygplates.FeatureCollection('%s/tmp.gpmlz' % settings.MEDIA_ROOT) reconstructed_features = reconstruct_to_birth_time( features, rotation_model) tmp = pygplates.FeatureCollection(reconstructed_features) tmp.write('%s/%s' % (settings.MEDIA_ROOT, filename)) f = StringIO( file('%s/%s' % (settings.MEDIA_ROOT, filename), "rb").read()) response = HttpResponse(f, content_type='application/gpmlz') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response
def get_topological_boundaries(request): """ http GET request to retrieve reconstructed topological plate polygons **usage** <http-address-to-gws>/topology/plate_boundaries/time=\ *reconstruction_time*\&model=\ *reconstruction_model* **parameters:** *time* : time for reconstruction [default=0] *model* : name for reconstruction model [defaults to default model from web service settings] **returns:** json containing reconstructed plate boundary features """ time = request.GET.get('time', 0) model = request.GET.get('model', settings.MODEL_DEFAULT) model_dict = get_reconstruction_model_dict(model) features = [] rotation_model = pygplates.RotationModel([ str('%s/%s/%s' % (settings.MODEL_STORE_DIR, model, rot_file)) for rot_file in model_dict['RotationFile'] ]) # need to handle cases where topologies are in one file, and where they are spread across # multiple files topology_features = pygplates.FeatureCollection() if type(model_dict['PlatePolygons']) is list: for file in model_dict['PlatePolygons']: fullfile = str('%s/%s/%s' % (settings.MODEL_STORE_DIR, model, file)) topology_feature = pygplates.FeatureCollection(fullfile) topology_features.add(topology_feature) else: topology_features = pygplates.FeatureCollection( str('%s/%s/%s' % (settings.MODEL_STORE_DIR, model, model_dict['PlatePolygons']))) resolved_polygons = [] shared_boundary_sections = [] pygplates.resolve_topologies(topology_features, rotation_model, resolved_polygons, float(time), shared_boundary_sections) data = wrap_plate_boundaries(shared_boundary_sections, 0.) print('here') ret = json.dumps(pretty_floats(data)) response = HttpResponse(ret, content_type='application/json') #TODO: response['Access-Control-Allow-Origin'] = '*' return response
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 get_deposit_candidates(): polygon_points = get_region_of_interest_polygon().values.flatten() mesh_points = get_mesh_points(polygon_points) #let's find plate id for the mesh points static_polygons = pygplates.FeatureCollection( parameters['static_polygons_file']) rotation_model = pygplates.RotationModel( get_files(parameters['rotation_files'])) mesh_plate_ids = get_plate_id(mesh_points.lon.tolist(), mesh_points.lat.tolist(), static_polygons, rotation_model) mesh_points['plate_id'] = mesh_plate_ids deposit_candidates = [] start_time = parameters["time"]["start"] end_time = parameters["time"]["end"] time_step = parameters["time"]["step"] for t in range(start_time, end_time + 1, time_step): for index, p in mesh_points.iterrows(): deposit_candidates.append([p['lon'], p['lat'], t, p['plate_id']]) deposit_candidates = pd.DataFrame( deposit_candidates, columns=['lon', 'lat', 'age', 'plate_id']) deposit_candidates = deposit_candidates.astype({ "plate_id": int, "age": int }) return deposit_candidates
def rotate_to_common_reference(vgps, reconstruction_model, reference_plate_id=701): ''' Rotate a collection of vgps to a common reference plate ''' if isinstance(vgps, _gpd.GeoDataFrame): rotated_vgps = [] for i,row in vgps.iterrows(): vgp_geometry = pygplates.PointOnSphere(row.PoleLatitude,row.PoleLongitude) feature_rotation = reconstruction_model.rotation_model.get_rotation(row.AverageAge, row.PlateID, anchor_plate_id=reference_plate_id) reconstructed_geometry = feature_rotation * vgp_geometry rotated_vgps.append(reconstructed_geometry.to_lat_lon()) vgps.PoleLatitude = list(zip(*rotated_vgps))[0] vgps.PoleLongitude = list(zip(*rotated_vgps))[1] return vgps elif isinstance(vgps, pygplates.FeatureCollection): rotated_vgps = [] for vgp in vgps: feature_rotation = reconstruction_model.rotation_model.get_rotation(vgp.get(pygplates.PropertyName.gpml_average_age).get_value().get_double(), vgp.get_reconstruction_plate_id(), anchor_plate_id=reference_plate_id) reconstructed_geometry = feature_rotation * vgp.get_geometry() vgp.set_geometry(reconstructed_geometry) vgp.set_reconstructed_plate_id(reference_plate_id) rotated_vgps.append(vgp) return pygplates.FeatureCollection(rotated_vgps)
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 __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 get_velocity_x_y_u_v(time, rotation_model, topology_filenames): delta_time = 5. Xnodes = np.arange(-180, 180, 10) Ynodes = np.arange(-90, 90, 10) Xg, Yg = np.meshgrid(Xnodes, Ynodes) Xg = Xg.flatten() Yg = Yg.flatten() velocity_domain_features = make_GPML_velocity_feature(Xg, Yg) # Load the topological plate polygon features. topology_features = [] for fname in topology_filenames: for f in pygplates.FeatureCollection(fname): topology_features.append(f) # Call the function we created above to get the velocities all_velocities = Get_Plate_Velocities(velocity_domain_features, topology_features, rotation_model, time, delta_time, 'vector_comp') uu = [] vv = [] for vel in all_velocities: if not hasattr(vel, 'get_y'): uu.append(vel[1]) vv.append(vel[0]) else: uu.append(vel.get_y()) vv.append(vel.get_x()) u = np.asarray([uu]).reshape((Ynodes.shape[0], Xnodes.shape[0])) v = np.asarray([vv]).reshape((Ynodes.shape[0], Xnodes.shape[0])) return Xnodes, Ynodes, u, v
def paleolithology(request): anchor_plate_id = request.GET.get('pid', 0) time = request.GET.get('time', 0) model = request.GET.get('model', settings.MODEL_DEFAULT) 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'] ]) paleolithology_datafile = '%s/boucot_paleolithology_combined.shp' % settings.PALEO_STORE_DIR static_polygons_filename = str( '%s/%s/%s' % (settings.MODEL_STORE_DIR, model, model_dict['StaticPolygons'])) #select points based on age before doing plate id assignment - should be quicker?? paleolithology_points = pygplates.FeatureCollection( paleolithology_datafile) valid_points = [] for point in paleolithology_points: if point.get_valid_time()[0] > float( time) and point.get_valid_time()[1] <= float(time): valid_points.append(point) print(valid_points) assigned_features = pygplates.partition_into_plates( static_polygons_filename, rotation_model, valid_points, properties_to_copy=[ pygplates.PartitionProperty.reconstruction_plate_id ], partition_method=pygplates.PartitionMethod.most_overlapping_plate) reconstructed_paleolithology_points = [] pygplates.reconstruct(assigned_features, rotation_model, reconstructed_paleolithology_points, float(time), anchor_plate_id=anchor_plate_id) ret = write_json_reconstructed_point_features( reconstructed_paleolithology_points, attributes=[('LithCode', 'string'), ('Period', 'string')]) #add header for CORS #http://www.html5rocks.com/en/tutorials/cors/ response = HttpResponse(ret, content_type='application/json') #TODO: #The "*" makes the service wide open to anyone. We should implement access control when time comes. response['Access-Control-Allow-Origin'] = '*' return response
def GenerateReconstructedDeltasXYZ(rotation_model, raster_times, raster_filenames, multipoint_feature_collection, output_file_stem, force_plate_frame): for reconstruction_time_index in range(0, len(raster_times[:-1])): reconstruction_time1 = raster_times[reconstruction_time_index] reconstruction_time2 = raster_times[reconstruction_time_index + 1] reconstruction_time_mid = 0.5 * (reconstruction_time1 + reconstruction_time2) print('time: %f Ma' % reconstruction_time_mid) # Exclude any multipoint features that do not exist at either reconstruction time. filtered_multipoint_feature_collection = pygplates.FeatureCollection() have_filtered_multipoints = False for multipoint_feature in multipoint_feature_collection: multipoint_valid_time = multipoint_feature.get_valid_time(None) if not multipoint_valid_time: continue multipoint_begin_time, multipoint_end_time = multipoint_valid_time if reconstruction_time1 > multipoint_begin_time or reconstruction_time1 < multipoint_end_time: continue if reconstruction_time2 > multipoint_begin_time or reconstruction_time2 < multipoint_end_time: continue filtered_multipoint_feature_collection.add(multipoint_feature) have_filtered_multipoints = True if not have_filtered_multipoints: print( 'Skipping mid-time %0.2f since multipoint feature does not exist' % reconstruction_time_mid) continue #InputGridFile1 = GridDir+'gld9NLt-%d.topo_0.5d_corr.0.grd' % reconstruction_time1 InputGridFile1 = raster_filenames[reconstruction_time_index] #InputGridFile2 = GridDir+'gld9NLt-%d.topo_0.5d_corr.0.grd' % reconstruction_time2 InputGridFile2 = raster_filenames[reconstruction_time_index + 1] GenerateReconstructedDeltaXYZ(rotation_model, reconstruction_time1, reconstruction_time2, filtered_multipoint_feature_collection, InputGridFile1, InputGridFile2, force_plate_frame) if force_plate_frame: #cmd = "gmt nearneighbor output -G%sPlateFrameDelta%0.2f.nc -Rd -I0.5d -N1 -S0.75d -V" % ( # output_file_stem, reconstruction_time_mid) cmd = "gmt xyz2grd output -G%sPlateFrameDelta%0.2f.nc -Rd -I1d -V" % ( output_file_stem, reconstruction_time_mid) else: #cmd = "gmt nearneighbor output -G%sReconstructedDelta%0.2f.nc -Rd -I0.5d -N1 -S0.75d -V" % ( # output_file_stem, reconstruction_time_mid) cmd = "gmt xyz2grd output -G%sReconstructedDelta%0.2f.nc -Rd -I1d -V" % ( output_file_stem, reconstruction_time_mid) os.system(cmd)
def gpml_to_dataframe(feature_collection, as_geodataframe=True): ''' function to read in any gplates-compatible feature collection and place it into a pandas dataframe # TODO handle polylines and polygons ''' if os.path.isfile(feature_collection): feature_collection = pygplates.FeatureCollection(feature_collection) elif isinstance(feature_collection, pygplates.FeatureCollection): pass else: raise ValueError( 'Unable to load {:s} as vgp input'.format(feature_collection)) DataFrameTemplate = [ 'Longitude', 'Latitude', 'Name', 'Description', 'MaximumAge', 'MinimumAge', 'PlateID' ] # Get attribute (other than coordinate) names from first feature for feature in feature_collection: for attribute in feature.get_shapefile_attributes(): DataFrameTemplate.append(attribute) break fs = [] for feature in feature_collection: f = [] f.append(feature.get_geometry().to_lat_lon()[1]) f.append(feature.get_geometry().to_lat_lon()[0]) f.append(str(feature.get_name())) f.append(str(feature.get_description())) geom = feature.get_geometry().to_lat_lon() f.append(float(geom[1])) f.append(float(geom[0])) feature_valid_time = feature.get_valid_time() f.append(float(feature_valid_time[0])) f.append(float(feature_valid_time[1])) f.append(int(feature.get_reconstruction_plate_id())) f.append(str(feature.get_feature_type())) f.append(str(feature.get_feature_id())) for attribute in feature.get_shapefile_attributes(): f.append(feature.get_shapefile_attribute(attribute)) fs.append(f) if as_geodataframe: df = _pd.DataFrame(fs, columns=DataFrameTemplate) return _gpd.GeoDataFrame(df, geometry=_gpd.points_from_xy( df.AverageSampleSiteLongitude, df.AverageSampleSiteLatitude), crs=4326) else: return _pd.DataFrame(fs, columns=DataFrameTemplate)
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 get_merged_cob_terrane_raster(COBterrane_file, rotation_model, reconstruction_time, sampling): polygon_features = pygplates.FeatureCollection(COBterrane_file) cobter = force_polygon_geometries(polygon_features) mask = merge_polygons(cobter, rotation_model, time=reconstruction_time, sampling=sampling, return_raster=True) return mask
def gpml2gdf(features): """ Given a gplates feature collection, or a list of features, or a list of reconstructed features, returns a geopandas geodataframe containing the same features """ if isinstance(features, pygplates.FeatureCollection): pass elif isinstance(features, list): if isinstance(features[0], pygplates.Feature): features = pygplates.FeatureCollection(features) elif isinstance(features[0], pygplates.ReconstructedFeatureGeometry): features = _reconstructed_features_to_features(features) features = pygplates.FeatureCollection(features) elif isinstance(features[0], pygplates.ResolvedTopologicalBoundary): features = [ resolved_topology.get_resolved_feature() for resolved_topology in features ] features = pygplates.FeatureCollection(features) else: raise TypeError( 'Unexpected list item of type {:s} for gpml2gdf input'.format( type(features[0]))) else: raise TypeError('Unexpected type {:s} for gpml2gdf input'.format( type(features))) temporary_file = tempfile.NamedTemporaryFile(delete=True, suffix='.geojson') temporary_file.close() features.write(temporary_file.name) gdf = gpd.read_file(temporary_file.name) gdf['NAME'] = gdf['NAME'].astype(str) os.unlink(temporary_file.name) return gdf
def calculate_velocities_over_time(output_filename_prefix, output_filename_extension, rotation_filenames, reconstructable_filenames, threshold_sampling_distance_radians, time_young, time_old, time_increment, velocity_delta_time=1.0, anchor_plate_id=0): if time_increment <= 0: print('The time increment "{0}" is not positive and non-zero.'.format( time_increment), file=sys.stderr) return if time_young > time_old: print('The young time {0} is older (larger) than the old time {1}.'. format(time_young, time_old), file=sys.stderr) return rotation_model = pygplates.RotationModel(rotation_filenames) # Read/parse the reconstructable features once so we're not doing at each time iteration. reconstructable_features = [ pygplates.FeatureCollection(reconstructable_filename) for reconstructable_filename in reconstructable_filenames ] # Iterate over the time range. time = time_young while time <= pygplates.GeoTimeInstant(time_old): print('Time {0}'.format(time)) # Returns a list of tesselated subduction zone points and associated convergence parameters # to write to the output file for the current 'time'. output_data = calculate_velocities( rotation_model, reconstructable_features, threshold_sampling_distance_radians, time, velocity_delta_time, anchor_plate_id) if output_data: output_filename = '{0}_{1:0.2f}.{2}'.format( output_filename_prefix, time, output_filename_extension) write_output_file(output_filename, output_data) # Increment the time further into the past. time += time_increment return 0 # Success
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 __init__(self, rotation_filenames, topology_filenames, geologic_zero, nseeds=1000, nneighbours=3, delta_time=1.): """ A class for importing surface velocities from pygplates. Each time surface velocity points are generated for [nseeds] of equidistantial points at the surface. With these points a cKDTree obect is generated each time, which will be used to interpolate onto required grid points. Interpolation is a weighted average of [nneighbours] closest points, unless the closest points is closer than ~numerical zero. input: rotation_filenames: list of rotation files topology_filenames: list of dynamic polygon files geologic_zero: what is the oldest geologic time available in this model nseeds: number of seed points to generate nneighbours: when interpolating between the seed points and mesh points, how many neighboring points should be used delta_time: how many million years should it take before we read in plate velocities again (is passed on to pygplates for time averaging too) """ # Rotation model(s) self.rotation_model = pygplates.RotationModel(rotation_filenames) if nneighbours < 2: raise ValueError('nneighbours should be at least 2') else: self.nneighbours = nneighbours # Topological plate polygon feature(s). self.topology_features = [] for fname in topology_filenames: for f in pygplates.FeatureCollection(fname): self.topology_features.append(f) # geologic_zero is the same as model_time=0 self.geologic_zero = geologic_zero # time window for velocity interpolations self.delta_time = delta_time # NB: Not sure if we really need to keep seeds at this stage self.seeds = self.__fibonacci_sphere(samples=int(nseeds)) # self.velocity_domain_features = self.__make_GPML_velocity_feature( self.seeds) # last reconstruction time self.reconstruction_time = None # Flag to know when to recalculate surface velocities. self.recalculation_flg = False
def plot_velocities(self, m): delta_time = 5. Xnodes = np.arange(-180, 180, 5) Ynodes = np.arange(-90, 90, 5) Xg, Yg = np.meshgrid(Xnodes, Ynodes) Xg = Xg.flatten() Yg = Yg.flatten() velocity_domain_features = velocity_utils.make_GPML_velocity_feature( Xg, Yg) # Load one or more rotation files into a rotation model. rotation_model = pygplates.RotationModel(rotation_filenames) # Load the topological plate polygon features. topology_features = [] for fname in topology_filenames: for f in pygplates.FeatureCollection(fname): topology_features.append(f) # Call the function we created above to get the velocities all_velocities = velocity_utils.Get_Plate_Velocities( velocity_domain_features, topology_features, rotation_model, self.reconstruction_time, delta_time, 'vector_comp') uu = [] vv = [] for vel in all_velocities: if not hasattr(vel, 'get_y'): uu.append(vel[1]) vv.append(vel[0]) else: uu.append(vel.get_y()) vv.append(vel.get_x()) u = np.asarray([uu]).reshape((Ynodes.shape[0], Xnodes.shape[0])) v = np.asarray([vv]).reshape((Ynodes.shape[0], Xnodes.shape[0])) # compute native x,y coordinates of grid. x, y = m(Xg, Yg) uproj, vproj, xx, yy = m.transform_vector(u, v, Xnodes, Ynodes, 15, 15, returnxy=True, masked=True) # now plot. Q = m.quiver(xx, yy, uproj, vproj, scale=1000, color='grey') # make quiver key. qk = plt.quiverkey(Q, 0.95, 1.05, 50, '50 mm/yr', labelpos='W')
def gdf2gpml(gdf): """ Given a geopandas geodataframe, returns a gplates feature collection """ temporary_file = tempfile.NamedTemporaryFile(delete=True, suffix='.geojson') temporary_file.close() gdf.to_file(temporary_file.name, driver='GeoJSON') feature_collection = pygplates.FeatureCollection(temporary_file.name) os.unlink(temporary_file.name) return feature_collection
def assign_plate_ids(vgps, reconstruction_model): ''' assign plate ids to Virtual Geomagnetic Poles (vgps), which is a special case of plate partitioning where we must use the 'AverageSampleSitePosition' rather than the feature geometry The input type can be a geodataframe or a pygplates FeatureCollection. The output type will match the input ''' plate_partitioner = pygplates.PlatePartitioner(reconstruction_model.static_polygons, reconstruction_model.rotation_model) if isinstance(vgps, _gpd.GeoDataFrame): partition_plate_ids = [] for i,row in vgps.iterrows(): partition_polygon = plate_partitioner.partition_point(pygplates.PointOnSphere(row.geometry.y, row.geometry.x)) partition_plate_ids.append(partition_polygon.get_feature().get_reconstruction_plate_id()) vgps['PlateID'] = partition_plate_ids return vgps elif isinstance(vgps, (pygplates.FeatureCollection, list)): if isinstance(vgps, list): vgps = pygplates.FeatureCollection(vgps) partitioned_vgps = [] for vgp in vgps: partition_polygon = plate_partitioner.partition_point(vgp.get(pygplates.PropertyName.gpml_average_sample_site_position).get_value().get_geometry()) vgp.set_reconstruction_plate_id(partition_polygon.get_feature().get_reconstruction_plate_id()) partitioned_vgps.append(vgp) return pygplates.FeatureCollection(partitioned_vgps) else: raise TypeError('Unexpected type {:} for vgp input'.format(type(vgps)))
def get_merged_cob_terrane_polygons(COBterrane_file, rotation_model, reconstruction_time, sampling, area_threshold=None, return_raster=False): polygon_features = pygplates.FeatureCollection(COBterrane_file) cobter = force_polygon_geometries(polygon_features) cf = merge_polygons(cobter, rotation_model, time=reconstruction_time, sampling=sampling) if area_threshold is not None: sieve_polygons = polygon_area_threshold(cf, area_threshold) return sieve_polygons else: return cf
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_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 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