def test_extinction(rerun=0,measure=0,nsys=10,show=0): #Comparison between competitive, trophic, disordered path=Path('test_extinction') try: if not os.listdir(path): rerun=1 except: rerun =1 if rerun: #If not already run before kwargs={} prm=deepcopy(dft_prm) loop(path=path,axes=axes,check_key=0,print_msg=1,tmax=500000,tsample=10000., #keep='all', parameters=prm,dynamics=dft_dyn, **kwargs ) if rerun or measure: rebuild_filelist(path) make_measures(path,use_measures=['usual','effective','abundance', 'matrix', 'removal', 'testcavity', measure_cavity, ]) if not show: return axes=['n_shape'] measures=open_measures(path) measures=measures[measures['avgN']!=0] show_hist(measures=measures,axes=axes, values=['n_abundance'] ) from cavity import cavity_distri xs=np.linspace(0,0.5,100) sigma,mu,gamma=[measures['n_couplings_'+z].mean() for z in ('sigma', 'mu','gamma') ] dist=cavity_distri(S=2000,sigma=sigma,sigma_k=0,mu=mu,gamma=gamma) plot(xs,[dist(x) for x in xs],hold=1,linewidth=2 ) plt.xlabel(r'Abundance $n_i$') plot_main(measures=measures,axes=axes) plot_cavity(measures=measures, axes=axes,)
def intersection(rerun=1, measure=0, nsys=100, show=0): #Comparison between competitive trophic path = Path('interp_intersection') #(model_resource_generalists, {'vars':('R','X'), 'S':6, 'R':np.logspace(.8,.81,5), 'X':np.linspace(.9909,.991,5), 'sigma_rho':.25 } ), #(model_trophic_satur, {'vars':('m0','e'),'sigma_k':0.05,'S':2000, 'm0':np.linspace(12.1,12.2,6),'e':np.linspace(0.01,.03,11),'s0':2, } ), kwargs = {} prm = deepcopy(dft_prm) kwargs['r_shape'] = (6, ) kwargs['n_shape'] = (6, ) kwargs['r_std'] = 0.25 cmean = prm['consumption']['mean'] prm['consumption']['save'] = False prm['r']['save'] = False X = 0.991 kwargs['consumption_std'] = np.sqrt(cmean**2 * (1 / X - 1)) axes = [('sys', range(nsys))] if rerun: loop( path=path, axes=axes, check_key=0, print_msg=1, converge=1, tmax=500000, tsample=15000., #keep='all', parameters=prm, dynamics=dft_dyn, **kwargs) if rerun or measure: rebuild_filelist(path) make_measures(path, use_measures=[ 'usual', 'effective', 'abundance', measure_cavity, ], update_prev=0) measures = open_measures(path) kwargs = {} show_hist(measures=measures, axes=['n_shape'], values=['n_abundance'], log='y', bins=30) from cavity import cavity_distri xs = np.linspace(0, 0.5, 100) sigma, mu, gamma = [ measures['n_couplings_' + z].mean() for z in ('sigma', 'mu', 'gamma') ] dist = cavity_distri(S=2000, sigma=sigma, sigma_k=0, mu=mu, gamma=gamma) plot(xs, [dist(x) for x in xs], hold=1, linewidth=2) plt.xlabel(r'Abundance $n_i$') plt.show()
def gamma_role(rerun=0, measure=0, nsys=10, show=0): #Comparison between competitive, trophic, disordered path = Path('interp_gamma_cavity') try: if not os.listdir(path): rerun = 1 except: rerun = 1 if rerun: #If not already run before kwargs = {} prm = deepcopy(dft_prm) prm['fluxes'] = { 'type': 'matrix', 'variables': [('n', 'com'), ('n', 'com')], 'role': 'fluxes', 'save': False, 'mean': 50. / 1600., 'std': 0, 'sign': 1, } prm['commtroph'] = { 'type': 'matrix', 'variables': [('n', 'com'), ('n', 'com')], 'role': 'interactions', 'structure': 'trophic', 'requires': ['fluxes'], #'efficiency':0.724, 'efficiency': 0.6, 'ordered': 0, 'dynamics': None, } prm['community'].update({ #'distribution':'exponential' }) #specs=[ ((16,),None,'nlv'),((5625,),'nlv',None) ][1:] specs = [((300, ), None, 'nlv'), ((400, ), None, 'nlv'), ((600, ), None, 'nlv'), ((1600, ), 'nlv', None)] #[:-1] axes = [(('n_shape', 'commtroph_dynamics', 'community_dynamics'), specs), ('sys', range(10))] loop( path=path, axes=axes, check_key=0, print_msg=1, tmax=500000, tsample=10000., #keep='all', parameters=prm, dynamics=dft_dyn, **kwargs) if rerun or measure: rebuild_filelist(path) make_measures(path, use_measures=[ 'usual', 'effective', 'abundance', 'matrix', measure_cavity, 'testcavity' ]) #,'trophic','assembly_corr'] ) if not show: return axes = ['n_shape'] measures = open_measures(path) measures = measures[measures['avgN'] != 0] show_hist(measures=measures, axes=axes, values=['n_abundance']) from cavity import cavity_distri xs = np.linspace(0, 0.5, 100) sigma, mu, gamma = [ measures['n_couplings_' + z].mean() for z in ('sigma', 'mu', 'gamma') ] dist = cavity_distri(S=2000, sigma=sigma, sigma_k=0, mu=mu, gamma=gamma) plot(xs, [dist(x) for x in xs], hold=1, linewidth=2) plt.xlabel(r'Abundance $n_i$') plot_main(measures=measures, axes=axes) plot_cavity( measures=measures, axes=axes, ) if 0: plot_data( measures=measures, axes=axes, #split_by=['community_symmetry'], values=[('press', { 'style': 'plot', 'linewidth': 2 }), ('n_matrix_press', { 'style': 'scatter' })], hold=1) plt.ylabel(r'Response to press$') plt.xlabel(r'Pool size $S$') #show_data(measures=measures,axes=axes, values= ['n_%alive','phi','avgN','stdN','n_biomass','n_biomass_std','n_interactions_mu' ,'n_interactions_sigma']) if 0: compare = { 'phi': 'n_%alive', 'avgN': 'n_biomass', 'stdN': 'n_biomass_std', 'press': 'n_matrix_press', } for trait in ('phi', 'avgN', 'stdN', 'press'): plot_data(measures=measures, axes=axes, hold=1, newfig=1, title=trait, values=[(trait, { 'style': 'plot', 'log': 'x' }), (compare[trait], { 'style': 'scatter' })]) plt.show()
def intersection(path=Path('interp_intersection'), rerun=0, nsys=10, measure=0, show=0, hold=0): #Comparison between competitive, trophic if 0: compare_prms_models([ (model_trophic_satur, { 'vars': ('m0', 'e'), 'm0': np.linspace(20, 20.1, 10), 'e': np.linspace(0, 0.001, 10)[1:-1], 'S': 100, 's0': 0., 'sigma_k': .3 }), ], mode='scatter') try: if not os.listdir(path): rerun = 1 except: rerun = 1 if rerun: #If not already run before kwargs = {} prm = deepcopy(dft_prm) #(model_trophic_satur, {'vars':('m0','e'),'m0':np.linspace(20,20.1,10),'e':np.linspace(0,0.001,10)[1:-1], #'S':100,'s0':1.,'sigma_k':.3 } ), prm['fluxes'] = { 'type': 'matrix', 'structure': 'random', #'distribution':'exponential', 'variables': [('n', 'com'), ('n', 'com')], 'role': 'fluxes', 'save': False, 'sign': 1, 'mean': 20. / 100., 'std': 1. / 100, } prm['commtroph'] = { 'type': 'matrix', 'variables': [('n', 'com'), ('n', 'com')], 'role': 'interactions', 'structure': 'trophic', 'requires': ['fluxes'], 'efficiency': 0., 'ordered': 0, 'dynamics': None, 'diagonal': 0, 'mean': 1, } prm['community'].update({ 'mean': 10., 'std': 1., 'symmetry': -1., 'diagonal': 0, }) prm['growth']['std'] = 0 prm['n']['shape'] = (100, ) specs = [(None, 'nlv'), ('nlv', None)] axes = [(('commtroph_dynamics', 'community_dynamics'), specs[1:]), ('sys', range(nsys))] loop(path=path, axes=axes, check_key=0, print_msg=1, tmax=500000, tsample=10000., converge=1, parameters=prm, dynamics=dft_dyn, **kwargs) if rerun or measure: rebuild_filelist(path) make_measures( path, use_measures=[ 'usual', 'effective', 'abundance', #'matrix', measure_cavity, #'testcavity' ]) #,'trophic','assembly_corr'] ) if not show: return axes = ['commtroph_dynamics'] dico = { 'commtroph_dynamics': 'community', 0: 'competition', 1: 'predation', 'n_abundance': 'Species abundance' } measures = open_measures(path) measures['commtroph_dynamics'][measures['commtroph_dynamics'].isnull()] = 0 measures['commtroph_dynamics'][measures['commtroph_dynamics'] == 'nlv'] = 1 hists = show_hist(measures=measures, axes=axes, values=['n_abundance'], dictionary=dico, log='', bins=30) from cavity import cavity_distri xs = np.linspace(0, np.max([np.max(z) for z in measures['n_abundance']]), 100) sigma, mu, gamma = [ measures['n_couplings_' + z].mean() for z in ('sigma', 'mu', 'gamma') ] #sigma,mu,gamma=1,10,-1 dist = cavity_distri(S=2000, sigma=sigma, sigma_k=measures['n_capacity_std'].mean(), mu=mu, gamma=gamma) plot(xs, [dist(x) for x in xs], hold=1, linewidth=2, log='') #plt.xlabel(r'Abundance $n_i$') # print np.sum(hists['n_abundance'][1][1:])*1./np.sum(hists['n_abundance'][1]),np.sum([dist(x) for x in xs[:-1]]*(xs[1:]-xs[:-1]) ) # plt.bar(0,np.sum(hists['n_abundance'][1][1])*(1-np.sum([dist(x) for x in xs[:-1]]*(xs[1:]-xs[:-1]) )), width=0.01 ) #plot_main(measures=measures,axes=axes) #plot_cavity(measures=measures, axes=axes,) if not hold: plt.show()
def ordering(path=Path('ordering'), mode='dft', struct='all', rerun=0, measure=0, nsys=3, sysmin=0, show=0, funcresp=False, **kw): if struct == 'all': struct = [ 'triangular', 'nested', 'bipartite', 'scalefree', 'assortativity', 'clustering', 'connectivity' ] if hasattr(struct, '__iter__'): for st in struct: ordering(path=path, mode=mode, struct=st, rerun=rerun, measure=0, nsys=nsys, sysmin=sysmin, show=0, funcresp=funcresp) ordering(path=path, mode=mode, struct=None, rerun=0, measure=measure, nsys=nsys, sysmin=sysmin, show=show, funcresp=funcresp) return if mode != 'dft': path = Path(path.strip() + '_{}'.format(mode)) try: if not os.listdir(str(path)): rerun = 1 except OSError as e: print e rerun = 1 kwargs = {} prm = deepcopy(dft_prm) prm['growth']['std'] = 0.25 prm['n']['shape'] = (120, ) prm['community']['stdrel'] = .3 prm['community']['diagonal'] = 0 prm['community']['structure'] = 'random' prm['edges'] = { 'type': 'matrix', 'variables': [('n', 'com'), ('n', 'com')], 'mode': 'network', 'connectivity': .2, 'role': 'edges', 'save': False, 'structure': 'random', } if funcresp: prm['threshold'] = { 'type': 'matrix', 'variables': ['n'], 'dynamics': 'nlv', 'role': 'threshold', 'mean': 5., 'std': 0., 'sign': 1, } dyn = { 'nlv': { 'type': 'simplefr', 'variables': [ ('n', 'com'), ], }, } else: dyn = deepcopy(dft_dyn) if mode == 'competition': prm['community']['mean'] = -0.04 prm['community']['symmetry'] = .9 prm['growth']['sign'] = 1 elif mode == 'predation': prm['final'] = prm.pop('community') prm['community'] = { 'type': 'matrix', 'variables': [('n', 'com'), ('n', 'com')], 'role': 'fluxes', 'mean': 0.05, 'stdrel': .3, 'save': False, } prm['final']['requires'] = ['community'] prm['final']['efficiency'] = 0.2 prm['final']['structure'] = 'trophic' prm['final']['ordered'] = 0 prm['final'].pop('symmetry', None) prm['growth']['sign'] = 0 elif mode == 'mutualism': if not funcresp: prm['community']['rowmax'] = 0.5 else: prm['community']['mean'] = 0.05 prm['community']['symmetry'] = 0.3 prm['growth']['sign'] = 0 #prm['growth']['std']=0.25 prm['community']['requires'] = ['edges'] prm['community']['edgefrom'] = 'edges' order = np.linspace(0, 1, 11) axes = [] if struct == 'nested': prm['edges']['structure'] = 'nested' #prm['community']['connectivity']=.6 axes = [ ('edges_nestedness', order), ] elif struct == 'triangular': prm['edges']['structure'] = 'triangular' #prm['community']['connectivity']=.6 axes = [ ('edges_triangular', order[6:]), ] elif struct == 'bipartite': prm['edges']['structure'] = 'multipartite' axes = [ ('edges_partition', order), ] elif struct == 'scalefree': prm['edges']['structure'] = 'barabasi' axes = [ ('edges_order', order), ] prm['edges']['connectivity'] = prm['edges']['connectivity'] / 3. prm['community']['mean'] = prm['community']['mean'] * 3. elif struct == 'assortativity': axes = [ ('edges_assortativity', np.linspace(-1, 1, 2 * len(order))), ] elif struct == 'clustering': axes = [ ('edges_clustering', np.linspace(-1, 1, 2 * len(order))), ] elif struct == 'connectivity': axes = [ ('edges_connectivity', np.linspace(0.05, 1, len(order))), ] elif not struct is None: raise Exception('Unknown structure: {}'.format(struct)) axes += [('sys', range(sysmin, nsys + sysmin))] if not struct is None: axes[0] = (axes[0][0], 'community_order'), zip(axes[0][1], np.abs(axes[0][1])) kwargs['community_label'] = struct if rerun: loop(path=path, axes=axes, check_key=0, print_msg=1, tmax=500000, ftol=0.0002, tsample=10000., parameters=prm, dynamics=dyn, converge=1, **kwargs) if rerun or measure: rebuild_filelist(path) make_measures( path, use_measures=[ 'usual', 'effective', ifelse(funcresp, measure_funcresp, 'usual'), ifelse(funcresp, measure_funcresp_cavity, measure_cavity), #'matrix', #'degree', #measure_ordered, #measure_ordered_cavity, # measure_groups,measure_groups_cavity, measure_cavity_compare, #'abundance', ], # read_filter=ifelse( struct is None,None,('community_label','==',struct)), death=10**-10) if not show: return axes = ['community_order'] split_by = ['community_label'] measures = open_measures(path) dico = { 'community_edgemean': r'$s$', 'n_shape': r'$S$', 'community_nestedness': 'nestedness', 'community_partition': 'partition', 'edges_structure': 'network', 'community_structure': 'structure', 'cavity_compare': 'Distance to reference', 'community_order': 'Ordering', 'multipartite': 'bipartite', 'random': 'scale-free' } plot_modelprm(measures=measures, axes=axes, split_by=split_by, dictionary=dico) #plt.show() plot_main(measures=measures, axes=axes, split_by=split_by, dictionary=dico, aggregator='mean', log='') plot_data(measures=measures, axes=axes, split_by=split_by, hold=1, values=[('n_couplings_n_std', { 'style': 'plot' }), ('n_couplings_n_mean', { 'style': 'plot', 'color': 'r' })]) plot_data(measures=measures, axes=axes, split_by=split_by, hold=1, values=['n_connectivity']) if 0: plot_data(measures=measures, axes=axes, split_by=split_by, hold=1, values=['n_degree_std']) plot_data( measures=measures, axes=axes, split_by=split_by, hold=1, values=[('n_biomass_tot', { 'style': 'scatter' }), ('totN', { 'style': 'plot' })], dictionary=dico, title='{}: Total biomass'.format(mode.capitalize()), ) plot_data( measures=measures, axes=axes, split_by=split_by, hold=1, values=['cavity_compare'], dictionary=dico, title=mode.capitalize(), ) plt.ylim(ymin=0, ymax=.5) if 0: #ABUNDANCE HIST if struct != 'all': measures = measures[measures['community_structure'] == struct] show_hist(measures=measures[measures['community_order'] == 1], axes=axes, values=['n_abundance'], dictionary=dico, log='y') sigma, mu, gamma = [ measures['n_couplings_' + z].mean() for z in ('sigma', 'mu', 'gamma') ] zeta = measures['n_capacity_std'].mean() from cavity import cavity_distri print sigma, mu, gamma dist = cavity_distri(S=measures['n_shape'][0][0], sigma=sigma, sigma_k=zeta, mu=mu, gamma=gamma) xs = np.linspace(0, np.max([np.max(z) for z in measures['n_abundance']]), 100) plot(xs, [dist(x) for x in xs], hold=1, linewidth=2, log='y') if not hold: plt.show()