-
Notifications
You must be signed in to change notification settings - Fork 5
Add population-level calculations and stratified statistics #176
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
brandynlucca
merged 20 commits into
brandynlucca-WIP-refactoring
from
brandynlucca-nasc_to_biomass_plus_jolly_hampton
Feb 13, 2024
Merged
Changes from 10 commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
a207806
Added geospatial transformation to config
6ad39ce
Population metrics and stratified stats
7a96ee2
Refactored dataframe 'gather/melt' method
1a9e729
Added docstring to `stretch` function
6fea2da
Added `grouped_merge` method/function
1cdcf4d
Moved `load_configuration` file location
1afeea6
Added INPFC strata to `Survey` methods
67348b5
Amend `test_data_loader`
bd3cccc
Merge branch 'brandynlucca-WIP-refactoring' into brandynlucca-nasc_to…
brandynlucca 14b94f1
Missing import for `group_merge`
8e0080c
Update EchoPro/tests/test_data_loader.py
brandynlucca 22bf7e1
Rename `calculate_bounds` to match operation
9296e87
Renamed `stratum` colname w/ `stratum_num`
46d305c
Refactored funcs in `nasc_to_biomass_conversion`
38c153e
Small edits to new `biology.py` funcs
17da6f6
Missing function imports in `survey.py`
a0aedeb
Added missing import (`numpy`)
895e2ae
Updated `calculate_start_end_coordinates` docs str
brandynlucca dae83c0
Amendments to `stratified_transect_statistics`
1d11497
Merge branch 'brandynlucca-nasc_to_biomass_plus_jolly_hampton' of htt…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import pandas as pd | ||
| import geopy.distance | ||
|
|
||
| def calculate_bounds( group , | ||
| contrast ): | ||
| """ | ||
| Calculates latitude/longitude boundary box | ||
|
|
||
| Parameters | ||
| ---------- | ||
| group: pd.DataFrameGroupBy | ||
| Grouped DataFrame | ||
| contrast: List | ||
| Target contrast for grouping | ||
|
|
||
| Notes | ||
| ----- | ||
| This function calculates the bounding rectangle surrounding the latitude/longitude values | ||
| for each grouped value (e.g. transect) | ||
| """ | ||
|
|
||
| return ( | ||
| group | ||
| .groupby( contrast ) | ||
| .apply( lambda x: pd.Series( { 'minimum_longitude': x['longitude'].min() , | ||
| 'maximum_longitude': x['longitude'].max() , | ||
| 'center_latitude': x[ 'latitude' ].mean() } ) ) | ||
| .reset_index( ) | ||
| ) | ||
|
|
||
| def calculate_transect_distance( dataframe , | ||
| contrast = 'transect_num' ): | ||
| """ | ||
| Calculates spatial features of each transect | ||
|
|
||
| Parameters | ||
| ---------- | ||
| dataframe: pd.DataFrame | ||
| DataFrame | ||
| contrast: List | ||
| Target contrast for grouping | ||
|
|
||
| Notes | ||
| ----- | ||
| This function calculates the bounding rectangle surrounding the latitude/longitude values | ||
| for each transect and stratum, the average spacing between transects, approximate areas | ||
| relative to each transect, and the distance for each transect | ||
| """ | ||
|
|
||
| transect_spacing_area = dataframe.groupby( contrast )[ 'transect_spacing' ].mean().reset_index() | ||
|
|
||
| return ( | ||
| dataframe | ||
| .pipe( lambda df: calculate_bounds( df , [ contrast ] ) ) | ||
| .assign(transect_distance=lambda x: x.apply( lambda row: geopy.distance.distance( | ||
| ( row[ 'center_latitude' ] , row[ 'minimum_longitude' ] ) , | ||
| ( row[ 'center_latitude' ] , row[ 'maximum_longitude' ] ) ).nm , | ||
| axis=1 ) ) | ||
| .merge( transect_spacing_area , on = [ contrast ] ) | ||
| .assign( transect_area = lambda x: x.transect_distance * x.transect_spacing ) | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import numpy as np | ||
| import scipy.stats as st | ||
|
|
||
| def stratified_transect_statistic( transects , | ||
| strata , | ||
| sample_fraction , | ||
| replicates ): | ||
brandynlucca marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| """ | ||
| Calculates stratified mean statistics for a given transect | ||
brandynlucca marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| Parameters | ||
| ---------- | ||
| transects: pd.DataFrame | ||
| DataFrame comprising a variety of spatial metrics for transect data | ||
| strata: pd.DataFrame | ||
| DataFrame comprising summary features of latitude (INPFC) delimited strata | ||
| sample_fraction: np.float64 | ||
| Value representing the proportion of ftransects that are resampled from the | ||
| overall dataset within each strata | ||
| replicates: int | ||
| The number of iterations/realizations used for bootstrapping | ||
|
|
||
| Notes | ||
| ----- | ||
| This function calculates the stratified summary statistics for biomass within | ||
| `EchoPro.survey.stratified_summary()`. | ||
| """ | ||
|
|
||
| ### Convert specific DataFrame columns to arrays for speed | ||
| distance = transects[ 'transect_distance' ].values | ||
| value = transects[ 'B_adult' ].values | ||
brandynlucca marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| num_transects = strata[ 'num_transects' ].values | ||
| total_transect_area = strata.set_index( 'stratum_inpfc' )[ 'total_transect_area' ] | ||
|
|
||
| ### Calculate the number of transects within each stratum based on the | ||
| ### sampling faction defined from the configuration file | ||
| # Number of transects | ||
| num_transects_to_sample = np.round( sample_fraction * num_transects ).astype( int ) | ||
|
|
||
| # Offset term used for later variance calculation | ||
| sample_offset = np.where( num_transects_to_sample == 1 , 0 , 1 ) | ||
|
|
||
| # Calculate effective sample size/degrees of freedom for variance calculation | ||
| sample_dof = num_transects_to_sample * ( num_transects_to_sample - sample_offset ) | ||
|
|
||
| ### Pre-allocate and pre-compute the cumulative sum of numbered transects per strata | ||
| # Transect indices | ||
| cum_num_transects = np.concatenate( ( [ 0 ] , np.cumsum( num_transects ) ) ) | ||
|
|
||
| # Stratified statistics | ||
| mean_arr = np.empty( replicates ) | ||
| variance_arr = np.empty( replicates ) | ||
|
|
||
| ### Iterate across all replicate iterations/realizations | ||
| for i in range( replicates ): | ||
|
|
||
| # Pre-allocate the stratum-specific means and variances | ||
| rho_j = np.empty_like( total_transect_area ) # mean | ||
| var_j = np.empty_like( total_transect_area ) # variance | ||
|
|
||
| # Iterate across all strata | ||
| for j in strata.stratum_inpfc - 1: | ||
|
|
||
| ### Resample (without replacement) based on binned indices | ||
| # Define start and end transects within each stratum | ||
| start , end = cum_num_transects[ j ] , cum_num_transects[ j + 1 ] | ||
|
|
||
| # Resample without replacement | ||
| sel_inds = np.random.choice( np.arange( start , end ) , | ||
| num_transects_to_sample[ j ] , | ||
| replace=False ) | ||
|
|
||
| ### Define stratified weights | ||
| stratified_weights = distance[ sel_inds ] / np.mean( distance[ sel_inds ] ) | ||
|
|
||
| ### Weighted value (e.g. biomass) | ||
| value_distance_density = value[ sel_inds ] / distance[ sel_inds ] | ||
|
|
||
| ### Compute mean and variance | ||
| rho_j[ j ] = np.nansum( value[ sel_inds ] * stratified_weights ) / np.nansum( stratified_weights ) | ||
brandynlucca marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| var_j[ j ] = np.nansum( ( stratified_weights ** 2 * ( value_distance_density - rho_j[ j ] ) ** 2 ) ) / sample_dof[ j ] | ||
|
|
||
| ### Calculate the overall weighted means and variances for later calculations | ||
| # Mean | ||
| mean_arr[ i ] = np.nansum( strata.total_transect_area * rho_j ) | ||
|
|
||
| # Variance | ||
| variance_arr[ i ] = np.sqrt( np.nansum( var_j * strata.total_transect_area ** 2 ) ) | ||
|
|
||
| ### Calculate the summary statistics | ||
| stratified_results = { | ||
| 'biomass': { | ||
| 'mean': { | ||
| 'estimate': np.mean( mean_arr ) , | ||
| 'confidence_interval': confidence_interval( mean_arr ) , | ||
| } , | ||
| 'variance': { | ||
| 'estimate': np.mean( variance_arr ) , | ||
| 'confidence_interval': confidence_interval( variance_arr ) , | ||
| } , | ||
| 'CV': { | ||
| 'estimate': np.mean( variance_arr / mean_arr ) , | ||
| 'confidence_interval': confidence_interval( variance_arr / mean_arr ) , | ||
| } | ||
| } | ||
| } | ||
|
|
||
| ### Carriage return | ||
| return stratified_results | ||
|
|
||
| def confidence_interval( values ): | ||
| """ | ||
| Calculates the 95% confidence interval (Normal) for a given array | ||
|
|
||
| Parameters | ||
| ---------- | ||
| values: np.array | ||
| An array of values | ||
|
|
||
| Notes | ||
| ----- | ||
| This function calculates the 95% confidence interval (assuming a Normal) distribution | ||
| for the bootstrapped stratified samples. This is done as opposed to using the percentile | ||
| method for estimate the intervals. | ||
| """ | ||
| return np.mean( values ) + np.array( [ -1 , 1 ] ) * st.norm.ppf( 0.975 ) * np.std( values ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.