<s> from itertools import combinations <EOL> import numpy as np <EOL> import pandas as pd <EOL> from scipy . spatial . distance import pdist <EOL> from scipy . stats import spearmanr <EOL> from skbio . stats . distance import DistanceMatrix <EOL> from skbio . util . _decorator import experimental <EOL> @ experimental ( as_of = "<STR_LIT>" ) <EOL> def bioenv ( distance_matrix , data_frame , columns = None ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( distance_matrix , DistanceMatrix ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> if not isinstance ( data_frame , pd . DataFrame ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> if columns is None : <EOL> columns = data_frame . columns . values . tolist ( ) <EOL> if len ( set ( columns ) ) != len ( columns ) : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if len ( columns ) < <NUM_LIT:1> : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> for column in columns : <EOL> if column not in data_frame : <EOL> raise ValueError ( "<STR_LIT>" % column ) <EOL> vars_df = data_frame . loc [ distance_matrix . ids , columns ] <EOL> if vars_df . isnull ( ) . any ( ) . any ( ) : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> try : <EOL> vars_df = vars_df . astype ( float ) <EOL> except ValueError : <EOL> raise TypeError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> vars_array = _scale ( vars_df ) . values <EOL> dm_flat = distance_matrix . condensed_form ( ) <EOL> num_vars = len ( columns ) <EOL> var_idxs = np . arange ( num_vars ) <EOL> max_rhos = np . empty ( num_vars , dtype = [ ( '<STR_LIT>' , object ) , <EOL> ( '<STR_LIT:size>' , int ) , <EOL> ( '<STR_LIT>' , float ) ] ) <EOL> for subset_size in range ( <NUM_LIT:1> , num_vars + <NUM_LIT:1> ) : <EOL> max_rho = None <EOL> for subset_idxs in combinations ( var_idxs , subset_size ) : <EOL> vars_dm_flat = pdist ( vars_array [ : , subset_idxs ] , <EOL> metric = '<STR_LIT>' ) <EOL> rho = spearmanr ( dm_flat , vars_dm_flat ) [ <NUM_LIT:0> ] <EOL> if max_rho is None or rho > max_rho [ <NUM_LIT:0> ] : <EOL> max_rho = ( rho , subset_idxs ) <EOL> vars_label = '<STR_LIT:U+002CU+0020>' . join ( [ columns [ i ] for i in max_rho [ <NUM_LIT:1> ] ] ) <EOL> max_rhos [ subset_size - <NUM_LIT:1> ] = ( vars_label , subset_size , max_rho [ <NUM_LIT:0> ] ) <EOL> return pd . DataFrame . from_records ( max_rhos , index = '<STR_LIT>' ) <EOL> def _scale ( df ) : <EOL> """<STR_LIT>""" <EOL> df = df . copy ( ) <EOL> df -= df . mean ( ) <EOL> df /= df . std ( ) <EOL> if df . isnull ( ) . any ( ) . any ( ) : <EOL> raise ValueError ( "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> return df </s>
