Multistability and regime shifts in microbial communities explained by competition for essential nutrients

Microbial communities routinely have several possible species compositions or community states observed for the same environmental parameters. Changes in these parameters can trigger abrupt and persistent transitions (regime shifts) between such community states. Yet little is known about the main determinants and mechanisms of multistability in microbial communities. Here, we introduce and study a consumer-resource model in which microbes compete for two types of essential nutrients each represented by multiple different metabolites. We adapt game-theoretical methods of the stable matching problem to identify all possible species compositions of such microbial communities. We then classify them by their resilience against three types of perturbations: fluctuations in nutrient supply, invasions by new species, and small changes of abundances of existing ones. We observe multistability and explore an intricate network of regime shifts between stable states in our model. Our results suggest that multistability requires microbial species to have different stoichiometries of essential nutrients. We also find that a balanced nutrient supply promotes multistability and species diversity, yet make individual community states less stable.


Introduction
Recent metagenomics studies revealed that microbial communities living in similar environments are often composed of rather different sets of species (Zhou et al., 2007;Lahti et al., 2014;Lozupone et al., 2012;Zhou et al., 2013;Pagaling et al., 2017;Gonze et al., 2017). It remains unclear to what extent such alternative species compositions are deterministic as opposed to being an unpredictable outcome of communities' stochastic assembly. Furthermore, changes in environmental parameters may trigger abrupt and persistent transitions between alternative species compositions (Shade et al., 2012;Rocha et al., 2018;Scheffer and Carpenter, 2003). Such transitions, known as ecosystem regime shifts, significantly alter the function of a microbial community and are difficult to reverse. Understanding the mechanisms and principal determinants of alternative species compositions and regime shifts is practically important. Thus, they have been extensively studied over the past several decades (Sutherland, 1974;Holling, 1973;May, 1977;Tilman et al., 1997;Schrö der et al., 2005;Fukami and Nakajima, 2011;Bush et al., 2017).
Growth of microbial species is affected by many factors, with availability of nutrients being among the most important ones. Thus, the supply of nutrients and competition for them plays a crucial role in determining the species composition of a microbial community. The majority of modeling approaches explicitly taking nutrients into account are based on the classic MacArthur consumerresource model and its variants (MacArthur and Levins, 1964;MacArthur, 1970;Huisman and Weissing, 1999;Tikhonov and Monasson, 2017;Posfai et al., 2017;Goldford et al., 2018;Goyal et al., 2018;Butler and O'Dwyer, 2018). This model assumes that every species co-utilizes several substitutable nutrients of a single type (e.g. carbon sources). However, nutrients required for growth of a species exist in the form of several essential (non-substitutable) types including sources of C, N, P, Fe, etc. Real ecosystems driven by competition for multiple essential nutrients have been extensively experimentally studied (see recent papers; Fanin et al., 2015;Browning et al., 2017;Camenzind et al., 2018 and references therein). The theoretical foundation for all existing consumer-resource models capturing this type of growth has been laid in Tilman (1982), where a model with two essential resources has been introduced and studied. Future studies extended Tilman's approach to three and more essential resources, where it has been shown to sometimes result in oscillations and chaos (Huisman and Weissing, 1999;Huisman and Weissing, 2001;Shoresh et al., 2008). However, all the previously studied models accounted for just a single metabolite per each essential nutrient.
Here, we introduce and study a new consumer-resource model of a microbial community supplied with multiple metabolites of two essential types (e.g. C and N or N and P). This ecosystem is populated by microbes selected from a fixed pool of species. We show that our model has a very large number of possible steady states classified by their distinct species compositions. Using game-theoretical methods adapted from the well-known stable marriage (or stable matching) problem (Gale and Shapley, 1962;Gusfield and Irving, 1989), we predict all these states based only on the ranked lists of competitive abilities of individual species for each of the nutrients. We further classify these states by their dynamic stability, and whether they could be invaded by other species in our pool. We then focus our attention on a set of steady states that are both dynamically stable and resilient with respect to species invasion.
For each state, we identify its feasibility range of all possible environmental parameters (nutrient supply rates) for which all of state's species are able to survive. We further demonstrate that for a given set of nutrient supply rates, more than one state could be simultaneously feasible, thereby allowing for multistability. While the overall number of stable states in our model is exponentially eLife digest In nature, different species of bacteria and fungi often live together in stable microbial communities. Exactly which species are present in the group and in which proportion may vary between communities. Changes in the environment, and in particular in the availability of nutrients, can trigger abrupt, extensive, and long-lasting changes in the composition of a community: these events are known as regime shifts. For instance, when bodies of water receive large quantities of phosphorus and nitrogen, certain algae can start to multiply uncontrollably and take over other species. A given community can have different stable species compositions, but it was unclear exactly how variations in nutrients can influence regime shifts.
To examine this problem, Dubinkina, Fridman, Pandey and Maslov harnessed mathematical techniques used in game theory and economics and modeled all the possible stable compositions of a community. They could then predict which environmental conditions -in this case, the amount of specific nutrients -were necessary for each stable composition to exist. These models also showed which conditions could trigger a regime shift. Finally, how resilient the communities were to different types of perturbations -for instance, an invasion by new species or changes in nutrient supply -was examined.
The results show that if competing species require different quantities of the same nutrients, then the community can have several possible stable compositions and it is more likely to go through regime shifts. In addition, a small number of keystone species were identified which can drive regime shifts by preventing other microbes from invading the community. Ultimately, these results suggest ways to control microbial communities in our environment, for example by manipulating nutrient supplies or introducing certain species at the right time. More work is needed however to verify the predictions of the model in real communities of microbes. large, only very few of them can be realized for a given set of environmental conditions defined by nutrient supply rates. The principal component analysis of predicted microbial abundances in our model shows a separation between the alternative stable states reminiscent of real-life microbial ecosystems. We further explore an intricate network of regime shifts between the alternative stable states in our model triggered by changes in nutrient supply. Our results suggest that multistability requires microbial species to have different stoichiometries of two essential resources. We also find that well-balanced nutrient supply rates matching the average species' stoichiometry promote multistability and species diversity yet make individual community states less structurally and dynamically stable. These and other insights from our consumer-resource model may help to understand the existing data and provide guidance for future experimental studies of alternative stable states and regime shifts in microbial communities.

Results
Microbial community growing on two types of essential nutrients represented by multiple metabolites Our consumer-resource model describes a microbial ecosystem colonized by microbes selected from a pool of S species. Growth of each of these species could be limited by two types of essential resources, to which we refer to as 'carbon' and 'nitrogen'. In principle, these could be any pair of resources essential for life: C, N, P, Fe, etc. A generalization of this model to more than two types of essential resources (e.g. C, N and P) is straightforward. Carbon and nitrogen resources exist in the environment in the form of K distinct metabolites containing carbon , and M other metabolites containing nitrogen. For simplicity, we ignore the possibility of the same metabolite providing both types. We further assume that each of the S species in the pool is a specialist, capable of utilizing only a single pair of nutrients, that is one metabolite containing carbon and one metabolite containing nitrogen.
We assume that for given environmental concentrations of all nutrients, a growth rate of a species a is limited by a single essential resource via Liebig's law of the minimum (de Baar, 1994): g a ðc; nÞ ¼ minðl ðcÞ a c; l ðnÞ a nÞ : Here, c and n are the environmental concentrations of the unique carbon and nitrogen resources consumed by this species. The coefficients l ðcÞ a and l ðnÞ a are defined as species-specific growth rates per unit of concentration of each of two resources. They quantify the competitive abilities of the species a for its carbon and nitrogen resources, respectively. Indeed, according to the competitive exclusion principle, if two species are limited by the same resource, the one with the larger value of l wins the competition. Note that according to Liebig's law, if the carbon source is in short supply so that l ðcÞ a c<l ðnÞ a n, it sets the value for this species growth rate. We refer to this situation as c-source limiting the growth of the species a. Conversely, when l ðcÞ a c>l ðnÞ a n, the n-source is limiting the growth of this species. Thus, each species always has exactly one growth-limiting resource and one non-limiting resource.
In our model, microbes grow in a well-mixed chemostat-like environment subject to a constant dilution rate d (see Figure 1A for an illustration). The dynamics of the population density, B a , of a microbial species a is then governed by: where c i and n j are the specific pair of nutrients defining the growth rate g a of this species according to the Liebig's law (Equation 1). These nutrients are externally supplied at fixed rates f j to a chemostat with a dilution rate d. Red and blue square nodes represent these nutrients inside the chemostat with steady state concentrations c 1 , c 2 (for carbon) and n 1 , n 2 (for nitrogen). They are consumed by three microbial species labeled by the pair of carbon (the first index) and nitrogen (the second index) nutrients this species consumes. Shaded ovals connect every species to its unique growth-limiting nutrient. The fourth species B 2;1 is not present in this steady state. (b) All seven uninvadable states in our realization of 2C Â 2N Â 4S model (see Supplementary files 1,2 for the specific parameters). depicted using the same schematic representation as in (a). Panels (c-e) schematically illustrate three possible types of perturbations of a community state, corresponding to three different types of its stability. (c) Changes of nutrient supply rates, that may result in extinction of some of the species. Green shaded area schematically depicts the region of nutrient supply rates where a given state is feasible, red arrows represent the perturbations of nutrient supply rates. (d) Introduction of species currently absent from the system, that is invasion, that may change the set of surviving species. (e) Small fluctuations in abundances of existing species, that may disturb the dynamic equilibrium of the system and potentially drive it to another state. (f) Table that shows which stability criteria are satisfied for 34 possible states in our realization of 2C Â 2N Â 4S model. Note that these types of stability are in general unrelated to each other. The online version of this article includes the following figure supplement(s) for figure 1: Here, Y ðcÞ a and Y ðnÞ a are the growth yields of the species a on its c-and n-resources respectively. Yields quantify the concentration of microbial cells generated per unit of concentration of each of these two consumed resources. The yield ratio Y ðnÞ a =Y ðcÞ a determines the unique C:N stoichiometry of each species.
A steady state of the microbial ecosystem can be found by setting the right hand sides of Equations 2-3 to zero and solving them for environmental concentrations of all nutrients c i , and n j , and abundances B a of all species. We choose to label all possible steady states by the list of species present in the state and by the growth-limiting nutrient (cor n) for each of these species. Thus, two identical sets of species, where at least one species is growth limited by a different nutrient are treated as two distinct states of our model. Conversely, our definition of a steady state does not take into account species' abundances. Examples of such states in a system with two carbon, two nitrogen nutrients and four species (one species for every pair of carbon and nitrogen nutrients) with specific values of species' competitive abilities l ðcÞ  Figure 1B. For the sake of brevity we refer to this model as 2C Â 2N Â 4S.
Because each of the S species in the pool could be absent from a given state, or, if present, could be limited by either its c-or its n-resource, the theoretical maximum of the number of distinct states is 3 S (equal to 81 in our 2C Â 2N Â 4S example). However, the actual number of possible steady states is considerably smaller (equal to 34 in this case). Indeed, possible steady states in our model are constrained by a variant of the competitive exclusion principle (Gause, 1932) (see Materials and methods for details). One of the universal consequences of this principle is that the number of species present in a steady state of any consumer-resource model cannot exceed K + M À the total number of nutrients.
We greatly simplified the task of finding all steady states in our model by the discovery of the exact correspondence between our system and a variant of the celebrated stable matching (or stable marriage) problem in game theory and economics (Gale and Shapley, 1962;Gusfield and Irving, 1989). The matching in our model connect pairs of C and N resources via microbial species using both of them. Unlike in the traditional stable marriage model, a given resource can be involved in more than one matching but cannot be limiting for more than one microbe. Thus, the competitive exclusion principle provides a number of constraints on the set of possible matchings and their stability, which are described in detail in Materials and methods and Appendix 3.

Three criteria for stability of microbial communities
Each of the steady states identified in the previous chapter can be realized only for a certain range of nutrient supply rates. These ranges can be calculated using the steady state solutions of Equations 2, 3, governing the dynamics of microbial populations and nutrient concentrations, respectively (see Materials and methods). Among all formal mathematical solutions of these equations we select those, where populations of all species and all nutrient concentrations are non-negative. This imposes constraints on nutrient supply rates, thereby determining their feasible range for a given steady state (shown in green in Figure 1C). The volume of such feasible range has been previously used to quantify the so-called structural stability of a steady state (Rohr et al., 2014;Grilli et al., 2017;Butler and O'Dwyer, 2018). States with larger feasible volumes generally tend to be more resilient with respect to fluctuations in nutrient supply.
Stability of a steady state could be also disturbed by a successful invasion of a new species (see Figure 1D). We can test the resilience of a given state in our model with respect to such invasions. A state is called uninvadable if none of the other species from our pool can survive in the environment shaped by the existing species. Figure 1B shows all seven states that are uninvadable in our variant of the 2C Â 2N Â 4S model. Whether or not a given state is uninvadable is determined by the specific choice of parameters l ðcÞ a , l ðnÞ a . For example, for parameters listed in the Supplementary file 1 the state in which B 12 is limited by carbon c 1 , and B 22 -by carbon c 2 could be invaded by the species B 11 . Indeed, l ðcÞ of B 11 is larger than that of B 12 , and the nitrogen concentration n 1 is not limited by any species. Hence, this state is not shown in Figure 1B. However, the same state may turn out to be uninvadable for a different combination of parameters. The one-to-one correspondence between our model and a variant of the stable matching problem (Gale and Shapley, 1962) allows us to identify all uninvadable steady states for a given choice of l ðcÞ a , l ðnÞ a describing species competitiveness for resources (see Materials and methods and Appendix 3 ).
Note that, in the regime of our model, where the supply of all nutrients is high, that is f ðc;nÞ ) d 2 =l ðc;nÞ a , invadability of individual states does not depend on supply rates. Indeed, in this regime the outcome of an attempted invasion is fully determined by the competition between species, which in turn depends only on the rank-order of competitive abilities l of the invading species relative to the species currently present in the ecosystem (see Materials and methods for details).
In addition to structural and invasion types of stability described above, there is also a notion of dynamic stability of a steady state actively discussed in the ecosystems literature (see e.g. May, 1972;Allesina and Tang, 2012;Butler and O'Dwyer, 2018). Dynamic stability can be tested by exposing a steady state to small perturbations in populations of all species present in this state (see Figure 1E). The state is declared dynamically stable if after any such disturbance the system ultimately returns to its initial configuration (see Materials and methods for details of the testing procedure used in our study).
We classify all the steady states in our model according to these three types of stability. The example of this classification for our realization of 2C Â 2N Â 4S model is summarized in Figure 1F. Note, that in general, one type of stability does not imply another. Out of 34 possible steady states realized for different ranges of nutrient supply rates there are only seven uninvadable ones. In the 2C Â 2N Â 4S model only one of the states (labelled seven in Figure 1B) turned out to be dynamically unstable, while for the remaining 33 states small perturbations of microbial abundances present in the state do not trigger a change of the state. Unlike two other types of stability, the structural stability has a continuous range. It could be quantified by the fraction of all possible combinations of nutrient supply rates for which a given state is feasible (referred to as state's normalized feasible range). We estimated the normalized feasible ranges of all states in the 2C Â 2N Â 4S model using a Monte Carlo procedure described in Materials and methods. The results are reflected in the second column of Figure 1F, where a structurally stable state is defined as that whose normalized feasible range exceeds 0.1 (an arbitrary threshold). In general we find that normalized feasible ranges of uninvadable states in our model have a broad log-normal distribution (see Figure 1-figure supplement 1 for details).
It is natural to focus our attention on steady states that are simultaneously uninvadable and dynamically stable. Indeed, such states correspond to natural endpoints of the microbial community assembly process. They would persist for as long as the nutrient supply rates do not change outside of their structural stability range. Therefore, they represent the states of microbial ecosystems that are likely to be experimentally observed. From now on, we concentrate our study almost exclusively on those states and refer to them simply as stable states.

Regime shifts between alternative stable states
The feasible ranges of nutrient supply of different stable states may or may not overlap with each other (see Figure 2A-B for a schematic illustration of two different scenarios). Whenever feasible ranges of two or more states overlap (see Figure 2B) -multistability ensues. Note that the states in the overlapping region of their feasibility ranges constitute true alternative stable states defined and studied in the ecosystems literature (Sutherland, 1974;Holling, 1973;May, 1977;Fukami and Nakajima, 2011;Bush et al., 2017). The existence of alternative stable states goes hand-in-hand with regime shifts manifesting themselves as large discontinuous and hysteretic changes of species abundances (Scheffer and Carpenter, 2003).
Every pair of states with overlapping feasibility ranges in our model corresponds to a possible regime shift between these states as illustrated in Figure 2D (note abrupt changes in the population B 11 at the boundary of the overlapping region). In general, a discontinuous regime shift happens in our model when one of the species (B 12 in this example) changes its growth-limiting nutrient thereby making the state invadable. It is then promptly invaded by the species present in the new state (B 11 and B 22 in our example) which may lead to immediate changes in populations of multiple species. Conversely, when feasible ranges of a pair of states do not overlap with each other but share a boundary (Figure 2A), the transition between these states is smooth and non-hysteretic ( Figure 2C). It manifests itself in continuous changes in abundances of all microbial species at the boundary between states. Such continuous transitions happen in our model when the growth rate of one of Figure 2. Regime shifts between alternative stable states. (a) Shaded green areas schematically depict the feasible ranges of nutrient supply rates for several stable states in our model (#2-#4 in Figure 1B). The feasible range of the state #4 does not overlap with that of any other state. Feasible ranges of states #2 and #3 also do not overlap but share a common boundary. Panel (b) depicts the opposite scenario of overlapping feasible ranges of another pair of stable states (#1 and #2 in Figure 1B). In the overlapping region (dark green), they form a pair of alternative stable states. (c) A smooth Figure 2 continued on next page the species (B 21 in this example) falls below the dilution rate d. This species then slowly disappears from the ecosystem thereby changing its state. When this boundary is crossed in the opposite direction, the same species (B 21 ) gradually appears in the ecosystem.
As expected for regime shifts, dynamically unstable states always accompany multistable regions in our model (Scheffer and Carpenter, 2003) (see below for a detailed discussion of the interplay between multistability and dynamically unstable states). We observed that dynamically unstable state #7 in our 2C Â 2N Â 4S is feasible in the overlapping region between states #1 and #2 in Figure 2B. The population B 11 in this state is shown as dashed line in Figure 2D.
We identified all possible regime shifts in the 2C Â 2N Â 4S model by systematically looking for overlaps between the feasible ranges of nutrient supply of all six uninvadable dynamically stable states. These regime shifts can be represented as a network in which nodes correspond to community's stable states and edges connect states with partially overlapping feasible ranges (see thick red edges in Figure 2E). One can see that regime shifts are possible only for of nine pairs of uninvadable states. We performed additional simulations (see Materials and mthods) looking for shared boundaries (continuous transitions) between uninvadable states and identified additional four pairs of states bordering each other (thin blue edges in Figure 2E). The pairs of states #5 -#6 and #3 -#4 do not directly transition to each other either continuously or discontinuously. This indicates that their feasible ranges are too far apart from each other, so that they do not have any overlaps or common boundaries.
Combining the information in Figure 1B and Figure 2E one can find that all states connected by a discontinuous regime shift in our 2C Â 2N Â 4S model have two distinct sets of keystone species: B 11 -B 22 in one state and B 12 -B 21 in another. This is because all regime shifts are driven by the same bistable switch in which these pairs of species compete and mutually exclude each other. The dynamically unstable state #7 is formed by the union of all four keystone species and, when perturbed, collapses into a state with either one or another keystone set. Conversely, states connected by a continuous transition share the same pair of keystone species. One of the 'satellite' species, that is species distinct from the keystone, gradually goes extinct when the boundary between these states is crossed. When the nutrient supply is changed in the opposite direction this species gradually invades the system. Figure 2F shows a much larger network of 8633 regime shifts between 893 uninvadable dynamically stable states in the 6C Â 6N Â 36S realization of our model. In this model the microbial community is supplied with six carbon and six nitrogen nutrients and colonized from a pool of 36 microbial species (one for each pair of C and N nutrients) (see Supplementary files 3, 4, 5, 6 for the values of l's and yields). For simplicity, we did not show the remaining 165 uninvadable stable states that have no possible regimes shifts to any other states. The size of a node is proportional to its degree (i.e. the total number of other states it overlaps with) ranging between 1 and 164 with average around 20 (the degree distribution is shown in Figure 2-figure supplement 1).
The network modularity analysis (see Materials and methods for details) revealed seven network modules indicating that pairs of states that could possibly undergo a regime shift are clustered together in the multi-dimensional space of nutrient supply rates. This modular structure suggests the transition between two states at the boundary. The population B 11 of the microbial species (1,1) is plotted as a function of changing nutrient supply rate f ðcÞ (same as the x-axis in panel (a)). Vertical gray line corresponds to the boundary between states #3 and #2. (d) A regime shift between two states. B 11 is plotted as a function of nutrient supply f ðcÞ as it sweeps through the overlapping region (gray area) in panel (b). Note abrupt changes of B 11 at the boundaries of the overlapping region and its hysteretic behavior as expected for regime shifts. Dashed line corresponds to B 11 in a dynamically unstable state (#7 in Figure 1B). (e) The network of possible regime shifts between pairs of stable states in the 2C Â 2N Â 4S model. Each red edge represents a possible regime shift between two states it connects (overlap of their feasible ranges as in panel (d)). Each blue edge corresponds to a smooth transition between two states while changing the fluxes (as in panel (c)). Nodes correspond to six uninvadable and dynamically stable states (state labels are the same as in Figure 1b). Sizes of nodes reflect relative magnitudes of feasible ranges of states they represent. (f) Network of 8633 possible regime shifts between pairs of 893 uninvadable dynamically stable states in the 6C Â 6N Â 36S model. The size of each node reflects its degree (i.e. the total number of other stable states that a given state can shift into). The color of each node corresponds to its network modularity class calculated as described in Materials and methods. The online version of this article includes the following figure supplement(s) for figure 2: existence of distinct sets of keystone species driving regime shifts within each module. However, the complexity of the 6C Â 6N Â 36S model does not allow a straightforward identification of these drivers (paired sets of keystone species and dynamically unstable states).

Patterns of multistability
In a general case, the number of stable states that are simultaneously feasible for a given set of nutrient supply rates can be more than two. Furthermore, as the number of nutrients increases, the multistability with more than two stable states becomes progressively more common. In Figure 3A, we quantify the frequency of multistability with V stable states occur in our 6C Â 6N Â 36S model across all possible nutrient supply rates (see Materials and methods for details of how this was estimated). V À 1 approximately follows a Poisson distribution (dashed line in Figure 3A) with l ¼ 0:063. Note that for some supply rates up to five stable states can be simultaneously feasible. However, the probability to encounter such cases is exponentially small.
We further explored the factors that determine whether multistability is possible in resource-limited microbial communities. Like in a simple special case of regime shift between two microbial species studied in Tilman (1982), multistability in our model is only possible if individual microbial species have different C:N stoichiometry. This stoichiometry is given by the ratio of species' nitrogen and carbon yields. Our numerical simulations and mathematical arguments show that when all species have exactly the same stoichiometry Y ðnÞ a =Y ðcÞ a , there is no multistability or dynamical instability in of supply of two essential nutrients. The peak of the distribution is close to the balanced supply (f ðcÞ : f ðnÞ ' 1 : 1). (c) The PCA plot of relative microbial abundances in the vicinity of the environment, where V ¼ 5 stable states coexist. Supply rates were randomly sampled within ±10% from the initial environment. Each point shows the first (x-axis) and the second (y-axis) principal components of microbial abundances in every uninvadable state feasible for this combination of supply rates. Colored circles label the original five stable states, black circles -several other stable states, which became feasible for nearby supply rates, and grey crosses -dynamically unstable states feasible in this region of nutrient supply rates. The online version of this article includes the following figure supplement(s) for figure 3: our model (see Appendix 5 ) . That is to say, in this case for every set of nutrient supply rates the community has a unique uninvadable state, and all these states are dynamically stable. A complementary question is whether multistable states are more common around particular ratios of carbon and nitrogen supply rates. Figure 3B shows this to be the case: the likelihood of multistability has a sharp peak around the well-balanced C:N nutrient supply rates. In this region multiple stable states are present for roughly 15% of nutrient supply rate combinations. Note that the average C:N stoichiometry of species in our model is assumed to be 1:1. In case of an arbitrary C:N stoichiometry, by redefining the units of nutrient concentrations and supply rates one can transform any ecosystem to have 1:1 nutrient ratio. Hence, in general, we predict that the highest chance to observe multistability will be when the ratio of nutrient supply rates is close to the average C:N stoichiometry of species in the community.
To illustrate how multistable states manifest themselves in a commonly performed Principal Component Analysis (PCA) of species' relative abundances, we picked the environment with V ¼ 5 simultaneously feasible stable states in our 6C Â 6N Â 36S model. In natural environments, nutrient supply usually fluctuates both in time and space. To simulate this we sampled a ±10% range of nutrient supply rates around this chosen environment (see Materials and methods) and calculated species' relative abundances in each of the uninvadable states feasible for a given nutrient supply. To better understand the relationship between dynamically stable and unstable states we included the latter in our analysis. Figure 3C shows the first vs the second principal components of relative microbial abundances sampled in this fluctuating environment. (two more examples calculated for different multistable neighborhoods are shown in Figure 3-figure supplement 1A-B). One can see five distinct clusters, each corresponding to a single dynamically stable uninvadable state. Interestingly, in the PCA plot these states are separated by V À 1 ¼ 4 dynamically unstable ones. Furthermore, all states are aligned along a quasi-1D manifold with an alternating order of stable and unstable states. It is tempting to conjecture that some variant of our model may explain similar arrangements of clusters of microbial abundances, commonly seen in PCA plots of real ecosystems. If this is the case, the gaps between neighboring clusters would correspond to dynamically unstable states of the ecosystem, which may be experimentally observable as long transients in community composition.

Patterns of diversity and structural stability of states
Above we demonstrated that multistable states are much more common for balanced nutrient supply rates, that is to say, when the average ratio of carbon and nitrogen supply rates matches the average C:N stoichiometry of species in the community (see Figure 3B). Interestingly, a balanced supply of nutrients also promotes species diversity. In Figure 4A, we plot the average number of species in a stable state, referred to as species richness, as a function of the average balance between carbon and nitrogen supplies for 6C Â 6N Â 36S model. The species richness is the largest (around 10.5) for balanced nutrient supply rates, while dropping down to the absolute minimal value of six in two extreme cases of very large imbalance of supply rates, where the nutrient supplied in excess becomes irrelevant in competition. In this case, only six species that are teh top competitors for carbon metabolites (if nitrogen supply is plentiful) or, respectively nitrogen metabolites (if carbon is large) survive, while the rest of less competitive species are never present in uninvadable states. The number of distinct community states also has a sharp peak at balanced nutrient supply (see 3orders of magnitude difference in Figure 4-figure supplement 1).
For balanced nutrient supply rates the relationship between species' competitiveness and its prevalence in the community is much less pronounced than for imbalanced ones. It is shown in Figure 4B, where we plot the prevalence of the species as a function of its average competitiveness. Here, the average competitiveness rank of a species is defined as the mean of its ranks of competitive abilities (l parameters of the model) for its carbon and nitrogen resources. The rank 1 being assigned to the most competitive species for a given resource (the species with the largest value of l), while the rank 6 -to the least competitive species for this resource. Species prevalence is given by the fraction of all environments where it can survive. Note that all 36 species in our pool are present in some of the environments.
In general, more competitive species tend to survive in a larger subset of environments (see the dashed curve in Figure 4B). For example, in our pool there is one species which happens to be the most competitive for both its carbon and nitrogen sources. This species is present in all of the states in every environment. However, we also find that some of the least competitive species (those at the right end of the x-axis in Figure 4B) survive in a broad range of environments. For example, one species with average competitiveness rank of 5.5 corresponding to the last and next to last rank for its two resources still has relatively high prevalence of around 20%. This illustrates complex ways in which relative competitiveness of all species in the pool shapes their prevalence in a broad range of environments.
We also explore the relationship between species richness of a state (i.e. its total number of surviving species) and its other properties. Figure 4C shows an exponential increase of the number of uninvadable states as a function of species richness. In our 6C Â 6N Â 36S model all uninvadable states with less than 10 species are dynamically stable (solid line in Figure 4C), while those with 10 or more species can be both stable or unstable (dashed line in Figure 4C). Overall, the fraction of stable states to dynamically unstable ones decreases with species richness. In other words, the  Figure 4A). probability for a state to be dynamically unstable increases with the number of species. In this aspect, our model behaves similar to the gLV model in Robert May's study (May, 1972).
In Figure 4D, we show a negative correlation between the species richness of a stable state and its feasible range of nutrient supplies. Thus in our model the number of species in an ecosystem has detrimental effect on the structural stability of the community quantifying its robustness to fluctuating nutrient supply (Rohr et al., 2014). The empirically observed exponential decay of state's feasible range with its number of species is well described by a two-fold decrease per each species added (see Serván et al., 2018 andGrilli et al., 2017 for related results in the gLV model). Note that the observed decrease in feasible range with species richness goes hand-in-hand with an increase in the overall number of states. Thus, in well-balanced environments a large number of states are carving all possible combinations of nutrient supply into many small and overlapping ranges.
Overall, the results of our model with a large number of nutrients suggest the following picture. In nutrient-balanced environments, we expect to observe a high diversity of species in the existing communities. These species can form a very large number of possible combinations (uninvadable states). Each of these states could be realized only for a narrow range of nutrient supply rates indicating their low structural stability. Moreover, in such environments we predict common appearance of multistability between some of these states.

Discussion
The inspiration for our model was the common appearance of alternative stable states in ecosystems in general, and microbial communities in particular (Sutherland, 1974;Tilman et al., 1997;Schrö der et al., 2005;Fukami and Nakajima, 2011;Bush et al., 2017;Pagaling et al., 2017;Gonze et al., 2017). For example, eutrophication of shallow lakes caused by algal competition for N and P is one of the best studied examples of alternative stable states and regime shifts (Scheffer and Jeppesen, 2007). To the best of our knowledge our model is the first consumerresource model capable of multistability between several states, each characterized by a high diversity of species. We extend Tilman's scenario (Tilman, 1982) in which the growth of two species is limited by a pair of essential resources to the case of multiple nutrients of each type. This allows us to assemble complex communities with large number of co-existing species and provides additional insights into patterns of multistability in such communities.

Multistability requires diverse species stoichiometry
We find that multistability in our model requires a mix of species with different nutrient stoichiometries. In this aspect it is similar to both the Tilman model (Tilman, 1982), and the MacArthur model (MacArthur and Levins, 1964;MacArthur, 1970;Chesson, 1990). Common variants of the MacArthur model assume identical biomass yields of different species growing on a given nutrient (Tikhonov and Monasson, 2017;Posfai et al., 2017;Goldford et al., 2018;Goyal et al., 2018;Butler and O'Dwyer, 2018). In this case, the absence of multistability is guaranteed by a convex Lyapunov function (MacArthur, 1970) guiding any dynamical trajectory of the system to its unique minimum. However, a MacArthur model with different nutrient yields of different species is capable of multistability. For some growth functions gðC; NÞ multistability is possible even in a community of species with identical nutrient yields/stoichiometries. For example, the growth function gðC; NÞ ¼ l Á C Á N has been numerically studied in the context of autocatalytic polymer growth and shown to be capable of multistability (Tkachenko and Maslov, 2018). This model had 1:1 stoichiometry: a ligation always eliminates one left end and one right end of two polymer chains and generates one autocatalytic polymer segment. Another type of growth function with two essential resources has been shown to have bistable solutions even for identical species stoichiometries (see Figure 5C in Marsland et al., 2019b). The Minimum Environmental Perturbation Principle introduced in this study may provide additional insights on the necessary conditions for multistability in consumer resource models.
Given that multistability in our model is impossible in communities of species with identical stoichiometries, it is reasonable to expect that the larger is the variation of C:N ratio of individual microbes, the higher is the likelihood to observe multistability. We investigated this question in the 2C Â 2N Â 4S model and summarized the results in Figure 5. It shows that the likelihood of finding nutrient supply rates with multistability systematically decreases with standard deviation of the logarithm of species stoichiometry. We also found that about half of the combinations of species stoichiometries yielded no multistable states at all. Multistability in our model is caused by a complex interplay between species' competitiveness abilities l and their C:N stoichiometries Y ðnÞ Y ðcÞ . Appendix 4 explains why multistability is impossible for half of yield combinations for which the enumerator in Equation S11 exceeds its denominator.
Nutrient stoichiometry of phytoplankton species in marine ecosystems has been known to be relatively universal with C:N:P ' 106:16:1 known as Redfield ratio (Redfield, 1958). Thus species-to-species variability of C:N ratio for phytoplankton is rather small with logarithmic standard deviation estimated to be around 0.05 based on data from Finkel et al. (2016). In this limit, the multistability in our model is rather unlikely (observed in~3% of nutrient supply combinations, see green arrow in Figure 5). The likelihood of multistability is also low (~1%) for the mammalian gut microbiome, where variability of the logarithm of C:N ratio in different 'keystone' gut species studied in Reese et al. (2018) is around 0.03. The chances of multistability increase in terrestrial ecosystems such as soil, where significant deviations from the Redfield ratio have been reported (Cleveland and Liptzin, 2007). For example, using the data for the microbial species from grassland leaf litter community reported in Mouginot et al. (2014), with log(C:N) variability of 0.12 we predict the likelihood of multistability to be around 10%. . Standard deviations of yields (x-axis) and the fraction of nutrient supply rates with multistability (y-axis) were logarithmically binned into 50 bins along each axis. The color scale represents log10 of the normalized count in each bin. The counts were normalized to add up to 100% in each column (same bin of the x-axis) to approximate the probability distribution of multistability fraction for given standard deviation of species stoichiometry. The bottom row (0) corresponds to 2069 yields combinations where no multistability was observed for any nutrient supply combinations in our Monte-Carlo simulations of 10 6 flux points. The red arrow on the x-axis corresponds to the approximate yield variation for mammalian gut microbes from Reese et al. (2018). The red arrow on y-axis highlights the predicted likelihood of multistability in our model for a microbial community with the same yield variation in our model. Light green arrows show an estimation of these numbers for phytoplankton species from Finkel et al. (2016). Dark green arrows correspond to the soil microbes studied in Mouginot et al. (2014).

Multistability requires balanced nutrient supply matching the average species stoichiometry
Another important factor favoring multistability in our model is the balanced supply of two essential nutrients (see Figure 3B). It occurs when the average ratio of supply rates of two essential nutrients matches the average C:N stoichiometry of community's species (see Figure 3B). When nutrient supplies are balanced, microbial community multistability is relatively common. Furthermore, for balanced nutrients the community can be in one of many different states, characterized by different combinations of limiting nutrients. These states tend to have high species diversity ( Figure 4A) -a trend consistent with lake ecosystems in Interlandi and Kilham (2001) -and relatively small range of feasible supply rates ( Figure 4D). Hence, regime shifts can be easily triggered by changes in nutrient supply. The balanced region is characterized by a complex relationship between species competitiveness and survival, so that even relatively poor competitors could occasionally have high prevalence (species in the upper right corner of Figure 4B).
In the opposite limit, the supply of nutrients of one type (say nitrogen) greatly exceeds that of another type (say carbon). For such imbalanced supply, the community has a unique uninvadable state, where every carbon nutrient supports the growth of the single most competitive species. Nitrogen nutrients are not limiting the growth of any species and thus have no impact on species survival and community diversity. As a consequence, the average diversity of microbial communities in such nutrient-imbalanced environments is low (about one half of that for balanced supply conditions). This is in agreement with many experimental studies showing that addition of high quantities of one essential nutrient (e.g. as nitrogen fertilizer) tends to decrease species diversity. This has been reported in numerous experimental studies cited in the chapter 'Resource richness and species diversity' of Tilman (1982) as well as in recent experiments in microbial communities (Mello et al., 2016).
Multistability and the total number of states are affected by tradeoffs Species in our model are characterized by their competitiveness abilities l ðcÞ , l ðnÞ and nutrient yields Y ðcÞ and Y ðnÞ . As we showed above, the rank order of the former fully defines the total number of stable states and their invadability. On the other hand, multistability highly depends on combination of species' nutrient yields. While in the current version of our model we did not assume any specific correlations between these parameters, imposing such correlations due to various biologically motivated tradeoffs may affect multistability and the total number of states of the ecosystem.
One possibility is a negative correlation between the competitive abilities of a given species for different nutrients. Such tradeoff may exist due to a limited amount of internal resources (such as the overall number of transporters) this species can allocate for consumption of all nutrients. This type of tradeoff was shown to result in an increased species diversity in well-balanced environments, but does not lead to multistability Tikhonov, 2016). Similar negative (positive) correlations to increase (decrease) the number of stable states in a very different consumer-resource model based on the stable marriage problem (Goyal et al., 2018). We expect these results to also apply to our model with tradeoff between l ðcÞ a and l ðnÞ a . Negative correlations between species' competitive abilities for carbon and nitrogen are expected to increase the total number of stable states in our model, while positive correlations -to decrease it.
Another possibility is a negative correlation between species' competitive ability and its yield for the same nutrient. It is known as a 'growth-yield tradeoff', which states that microbial species with faster growth on a given nutrient tend to use it less efficiently (have a smaller yield) (Pfeiffer et al., 2001;Beardmore et al., 2011;Novak et al., 2006). Growth-yield tradeoff is expected to increase the likelihood of multistability in our model. It could be demonstrated already in the model of Tilman (1982) with two species competing for two essential resources. If the species with the higher growth rate on, say, carbon source has a smaller yield on this resource than the other species -bistability always ensues. Note that, while growth-yield tradeoff is known to be common among microorganisms, the macroscopic (e.g. plant) ecosystems, which are the main focus of Tilman (1982), have the opposite correlation in which species' yield Y is proportional to its competitive ability l. This type of tradeoff leads to a relative scarcity of multistability in macroscopic ecosystems.
Conversely, multistability is expected to be more common in microbial ecosystems due to the growth-yield tradeoff.
Interplay between diversity and stability in ecosystems with multiple essential nutrients Ever since Robert May's provocative question 'Will a large complex system be stable?' (May, 1972) the focus of many theoretical ecology studies has been on investigating the interplay between dynamic stability and species diversity in real and model ecosystems (Ives and Carpenter, 2007). May's prediction that ecosystems with large number of species tend to be dynamically unstable needs to be reconciled with the fact that we are surrounded by complex and diverse ecosystems that are apparently stable. Thus, it is important to understand the factors affecting stability of ecosystems in general and microbial ecosystems in particular .
Here, we explored the interplay between diversity and stability in a particular type of microbial ecosystems with multiple essential nutrients. We discussed three criteria for stability of microbial communities shaped by the competition for nutrients: (i) how stable is the species composition of a community to fluctuations in nutrient supply rates; (ii) the extent of community's resilience to species invasions; and (iii) its dynamical stability to small stochastic changes in abundances of existing species. Naturally-occurring microbial communities may or may not be stable according to either one of these three criteria (Ives and Carpenter, 2007). The degree of importance of each single criterion is determined by multiple factors such as how constant are nutrient supply rates in time and space and how frequently new microbial species migrate to the ecosystem.
Our model provides the following insights into how these three criteria are connected to each other. First, as evident from Figure 1F, the three types of stability are largely independent from each other. Second, communities growing on a well balanced mix of nutrients tend to have high species diversity (see peak in Figure 4A). The similar effect was demonstrated in other consumer resource models Tikhonov and Monasson, 2017;Taillefumier et al., 2017;Marsland et al., 2019a). However, each of the community states in this regime tends to have a low structural stability with respect to nutrient fluctuations. In environments with highly variable nutrient supplies the community will frequently shift between these states. That is to say, some of the species will repeatedly go locally extinct and the vacated niches will be repopulated by others. Furthermore, many of the steady states in this regime are dynamically unstable giving rise to multistability and regime shifts. In this sense our model follows the general trend reported in May (1972). Conversely, microbial communities growing on an imbalanced mix of essential nutrients have relatively low diversity ( Figure 4A) but are characterized by a high degree of structural and dynamic stability (see Figure 4D and Figure 4C respectively). We expect these trends to apply to a broad variety of consumer-resource models.
The existence of dynamically unstable states always goes hand in hand with multistability (Scheffer and Carpenter, 2003) (see the dashed line in Figure 2D for an illustration of this effect in our model). Interestingly, in our model we always find V À 1 dynamically unstable states coexisting with V dynamically stable ones for the same environmental parameters (see Figure 3C Figure 3C are positioned along some one-dimensional curve in PCA coordinates. This arrangement hints at the possibility of a non-convex one-dimensional Lyapunov function whose V minima (corresponding to stable states) are always separated by V À 1 maxima (unstable stable states) as dictated by the Morse theory (Milnor, 1963). This should be contrasted with convex multidimensional Lyapunov functions used in MacArthur (1970), Case and Casten (1979) and Chesson (1990).

Extensions of the model
Our model can be extended to accommodate several additional properties of real-life microbial ecosystems. First, one could include generalist species capable of using more than one nutrient of each type. The growth rate of such species is given by: ai c i ; X j used by a l ðnÞ aj n j ! Here, the sum over i (respectively j) is carried out over all carbon (nitrogen, respectively) sources that this species is capable of converting to its biomass. One may also consider the possibility of diauxic shifts between substitutable nutrient sources. In this case, each generalist species is following a predetermined preference list of nutrients and uses its carbon and nitrogen resources one-at-a-time, as modelled in Goyal et al. (2018). Since at any state each of the species is using a 'specialist strategy', that is to say, it is growing on a single carbon and a single nitrogen source, we expect that many of the results of the current study would be extendable to this model. Interestingly, the stable marriage problem can be used to predict the stable states of microbial communities with diauxic shifts between substitutable resources (Goyal et al., 2018) and those in communities growing on a mix of two essential nutrients as in this study. It must be pointed out that these models use rather different variants of the stable marriage model.
It is straightforward to generalize our model to Monod's growth equation and to take into account non-zero death rate (or maintenance cost) of individual species (see Appendix 1).
One can extend our model to include cross-feeding between the species. In this case some of the nutrients are generated as metabolic byproducts by the species in the community. These byproducts should be counted among nutrient sources and thus would allow the number of species to exceed the number of externally supplied resources.
Above we assumed a fixed size of the species pool. This constraint could be modified in favor of an expanding pool composed of a constantly growing number of species. These new species correspond to either migrants from outside of the community or mutants of the species within the community. This variant of the model would allow one to explore the interplay between ecosystem's maturity (quantified by the number of species in the pool) and its properties such as multistability and propensity to regime shifts.

Control of microbial ecosystems exhibiting multistability and regime shifts
In many practical situations we would like to be able to control microbial communities in a predictable and robust manner. That is to say, we would like to be able to reliably steer the community into one of its stable states and to maintain it there for as long as necessary. Alternative stable states and regimes shifts greatly complicate the task of manipulation and control of microbial ecosystems. Indeed, multistability means that the environmental parameters alone do not fully define the state of the community. In order to get it to a desired state, one needs to carefully select the trajectory along which one changes the environmental parameters (nutrient supply rates). Changing these parameters could lead to disappearance (local extinction) of some microbial species and open the ecosystem for colonization by others thereby changing its state. However, not all the states could be directly converted to each other in one step due to them being restricted to vastly different environments. Thus, densely interconnected networks of regime shifts shown in Figure 2E-F can be viewed as maps guiding the selection of the optimal environmental trajectory leading to the desired stable species composition.
These maps also suggest that microbial ecosystems described by our model might have a relatively small number of key drivers of regime shifts roughly corresponding to network modules (see Figure 2F). Regime shifts in each of the modules are driven by the competition between two mutually exclusive sets of keystone species. In addition to these keystone species, states also include 'satellite' species that do not generally affect the bistable switch. The exploration of different manipulation strategies of microbial ecosystems and the role of keystone and peripheral species in regime shifts is the subject of our future research (Maslov et al., unpublished).

Identification of all states and classification of them as invadable or uninvadable
The competitive exclusion principle states that, in general, two species competing for the same growth-limiting nutrient cannot coexist with each other. Accounting for non-limiting nutrients present in our model, the competitive exclusion principle can be reformulated as the following two rules: . Rule 1: In a given steady state each nutrient (either carbon or nitrogen) limits the growth of no more than one species.
. Rule 2: Any number of species can use a given nutrient in a non growth-limiting fashion. However, each of such species needs to be able to survive at the steady state concentration of this nutrient set by the growth-limited species. That means that for every nutrient each of the non growth-limited species b needs to be more competitive than the grow-limited species a for the same resource: l ðcÞ a <l ðcÞ b (or l ðnÞ a <l ðnÞ b in case of a nitrogen nutrient).
Note that in any state of our model every species has a unique nutrient limiting its growth. By the virtue of the Rule 1, if a nutrient is limiting the growth of any species at all, such species is also unique. Hence, in a given state the relationship between surviving species and their growth-limiting nutrients (marked as shaded ovals in Figure 1A) is an example of a matching on a graph of resource utilization. Rule two imposes additional limitations on this matching. As we show in the Appendix 2 , uninvadable states correspond to stable matchings in a variant of the celebrated stable marriage problem (Gale and Shapley, 1962;Gusfield and Irving, 1989).
Just like in the MacArthur model (MacArthur and Levins, 1964) or any other consumer-resource model for that matter, the number of species present in a steady state of the community cannot exceed the total number of nutrients they consume. Any community constructed using Rules 1 and 2 represents a steady state of the ecosystem feasible for a certain range of nutrient supply rates. This state can be either invadable or uninvadable, and either dynamically stable or not.
For simplicity in our simulations we use equal numbers of C and N resources (L carbons and L nitrogens), with one unique species capable of utilization of every pair of resources (L 2 species in total). One must reiterate that our theory is not restricted to the specific values of K, M, and S. We first selected the values of l ðcÞ ði;jÞ and l ðnÞ ði;jÞ from a uniform random distribution between 10 and 100. Note that in the regime of high nutrient supply (f ðc;nÞ >> d 2 l ðc;nÞ ) all steady states of the community can be identified and tested for invadability using only the relative rank order of species' competitiveness for nutrients. For this we used the following exhaustive search algorithm: Step 1 -Select the subset of species whose growth is limited by C (C-limited species). For every carbon nutrient there are L ways to choose a species using this nutrient. There is also an additional possibility that this nutrient is not limiting the growth of any species. Thus, the total number of possibilities is L þ 1 for each of L carbon nutrients. There are ðL þ 1Þ L ways to choose the set of C-limited species and our algorithm will exhaustively investigate each of these potential steady states one-byone.
Step 2 -Given the set of C-limited species selected in Step 1, we now select the set of N-limited species. We first eliminate from our search any species that doesn't have enough carbon to grow.
That is to say, we go over all carbon nutrients one-by-one and eliminate all species whose l ðcÞ is smaller than that of the C-limited species (if any) for this carbon nutrient. Among the remaining species we go over the nitrogen nutrients one-by-one and look for all possible ways to add a species limited by a given nitrogen source n j that satisfy the Rule 2. More specifically, we identify all species that use n j and can grow on their carbon sources (those are the only species that remained after the elimination procedure described above). We then compare l ðnÞ s of these species to l ðnÞ s of all C-limited species using n j . To satisfy the Rule 2 for each n j we can add at most one N-limited species and its l ðnÞ has to be smaller than l ðnÞ s of all C-limited species using n j . Let M j be the number of such species (M j ¼ 0 if there are no such species for a given n j ). The total number of possible steady states of our model for a given combination of C-limited species selected in Step 1 is given by Q L j¼1 ðM j þ 1Þ. Here the þ1 factor in M j þ 1 takes into account an additional possibility to not add any N-limited species for n j .
The unique way to construct an uninvadable state by following this algorithm is to go over all nitrogen sources one-by-one and for each of them add the N-limited species with the largest l ðnÞ among all species using this resource, whose growth is allowed by carbon constraints. If for every n j this species is allowed by the Rule 2, that is to say, if its l ðnÞ is smaller than l ðnÞ of all C-limited species using n j , we successfully constructed a unique uninvadable state for a given set of C-limited species. Indeed, all possible invading species that are allowed to grow by their carbon nutrients will be blocked by their nitrogen nutrients. If, however, for any of n j , the species with the largest l ðnÞ is not allowed by the Rule 2, that is to say, if its l ðnÞ is larger than l ðnÞ of at least one of the C-limited species, this species would make a successful invader of any state we construct. In this case, there is no uninvadable state for the set of C-limited species selected during the Step 1.
We used the above procedure to identify all possible steady states and to classify them as invadable and uninvadable for different numbers of resources used in our 2C Â 2N Â 4S and 6C Â 6N Â 36S examples. Note that, while this method is computationally feasible for a relatively small number of nutrients (we were able to successfully use it for up to 9 nutrients of each type), for larger systems one should rely on computationally more efficient algorithms based on the stable marriage problem (Gale and Shapley, 1962;Gusfield and Irving, 1989) as described in the Appendix 3.
Monte-Carlo sampling of nutrient supply rates to identify feasible ranges of states Given the parameters defining all species (i.e., the set of their ls and Ys) and the chemostat dilution constant d, each state p is feasible within a finite region in the nutrient supply space (a K þ M dimen- j g), where all microbial populations and nutrient concentrations are nonnegative and the limiting nutrients of every surviving species do not change. It is easy to show that in a steady state our system satisfies mass conservation laws for each of the nutrients: To simplify the process of calculating the feasible volumes of all states we worked in the limit of high nutrient supply where f =d, that is to say, its concentration before any microbial species were added to the chemostat. In this case one can ignore the terms c i and n j in Equation 4 for all nutrient limiting growth of some species and leave only the ones that are not limiting the growth of any species. It is convenient to introduce the K + M À dimensional vectorX p of microbial abundances and non-limiting nutrient concentrations in a given state p. For example, for the uninvadable state #5 in the 2C Â 2N Â 4S model we have:X 5 ¼ fB ð1;1Þ ; B ð1;2Þ ; B ð2;2Þ ; n 2 g.
The mass conservation laws (Equation 4) can be used to obtain the feasible volumes of all states and can be represented in a compact matrix form for each state p: where f is the vector of K þ M nutrient supply rates andR p is a matrix composed of inverse yields Using Equation 5, it is easy to check if a given state is feasible at a particular nutrient supply ratẽ f by multiplyingR p À1 (the inverse of the matrixR p ) withf. If all of the elements of the resulting vec-torX p are positive, then the state p is feasible atf. If the matrixR p is not invertible that is detðR p Þ ¼ 0, the state is feasible only on a low-dimensional subset of nutrient supply rates. This is not possible for a general choice of yields Y and is not considered in our study.
The parameters l and Y for 2C Â 2N Â 4S and 6C Â 6N Â 36S realizations of the model were drawn from the uniform random distributions and are listed in Supplementary files 1,2 and 3,4,5,6. For l's the distribution ranges between 10 and 100. For Y's it is between 0.1 and 1.
In our numerical simulations, for each model realization, we sampled 10 6 random nutrient supply rate combinationsf. Supply rates of each individual nutrient were independently selected from a uniform distribution on the [10, 1000] interval. We refer to this procedure as Monte Carlo sampling. The lower bound ensures that the system is always in the limit of high nutrient supply since max ð d 2 la Þ ¼ 0:1 ( 10:. Then we checked the feasibility of each of the 33 possible steady states (both invadable and uninvadable) in the 2C Â 2N Â 4S model and each of the 1211 uninvadable steady states in the 6C Â 6N Â 36S model. That is to say, for every set of nutrient supply ratesf and for every state p we checked whether all elements ofX p are positive. The feasible range of nutrient supply rates of each state was estimated as the fraction of nutrient supply rate combinations (out of 1 million vectorsf sampled by our Monte Carlo algorithm) where this state was found to be feasible.

The network of regime shifts from overlaps of feasible ranges
Two stable states are said to be capable of a regime shift if their feasibility ranges overlap with each other, that is if there exists at least one nutrient supply rate combination at which both these states are feasible. We used the data obtained by the Monte-Carlo sampling to look for such cases and to construct networks shown in Figure 2E, Figure 2F.
We performed additional simulations to look for boundaries between uninvadable states in our realization of the 2C Â 2N Â 4S model. In order to do that, for each state we generated a large ensemble of random vectors of bacterial abundances of surviving species and concentrations of all not-limiting nutrients. The population of one of the species (also randomly selected) was set to be a small negative number (À0.01). This represents continuous gradual extinction of this species upon crossing of the boundary, The populations of state's other surviving species and the concentrations of its non-limiting nutrients were drawn from the uniform distribution between (0,1]. Using Equation 5, we calculated the nutrient supply rates f corresponding to this case. For these nutrient supply rates lying just across the feasibility boundary of the originally selected state, we checked the feasibility of other five uninvadable dynamically stable states. If any of these states ended up being feasible, we assumed that this state shares a boundary with the originally selected one. Using these procedure we found four bordering pairs of states shown as red edges in Figure 2E. We used Gephi 0.9.2 software package to visualize the network in Figure 2F and to perform its modularity analysis. Seven densely interconnected clusters shown with different colors in Figure 2F were identified using Gephi's built-in module-detection algorithm (Blondel et al., 2008) with the resolution parameter set to 1.5.

Dynamic stability of states
We checked the dynamic stability of every 33 possible steady state (both invadable and uninvadable) (for the 2C Â 2N Â 4S model) and each of the 1211 uninvadable states (for the 6C Â 6N Â 36S model) using the following two algorithms:

Small perturbation analysis
For 2C Â 2N Â 4S example and each of the 33 states we selected many supply rate combination where this state is feasible. For each of these supply rates we generated the populations in our ecosystem to be equal to their steady state values. We then subjected them to small perturbations of of all nutrient concentrations and of all microbial populations of species present in the state. If after some transient period all populations and concentrations returned to their steady state values -the state was declared to be dynamically stable. If they drifted to these in some other steady state -the original state was declared to be dynamically unstable. Based on our numerical simulations the dynamical stability of the state was independent of the nutrient supply rates at which this numerical experiment has been performed. We choose to perturb only the populations of the species present in the state because an invadable state, by definition, would always be dynamically unstable against an addition of a very small population of at least one invading species from the species pool. This instability should not render it dynamically unstable. The numerical integration of the system dynamics following a perturbation was done in C programming language using the CVODE solver library of the SUNDIALS package (Hindmarsh et al., 2005).

Inference of state's dynamic stability from the pattern of its overlaps with other states
The number of uninvadable states (1211) in our 6C Â 6N Â 36S model was too large to be directly tested for dynamic stability as we did for the 2C Â 2N Â 4S model. Their dynamic stability was instead inferred from our Monte-Carlo simulations listing all feasible uninvadable states for every sampled nutrient supply rate combination. We first identified 1022 uninvadable states, which were the unique feasible state for at least one nutrient supply point. All such states should be dynamically stable, since for every nutrient supply rate there should be at least one uninvadable dynamically stable state representing the end point of system's dynamics. The remaining 173 uninvadable states, which were feasible for at least one of 1 million sampled nutrient supply rates were labelled as potentially dynamically unstable. Note that in our Monte-Carlo analysis we only sampled a finite (albeit large) number of nutrient supply rate combinations. Thus it is entirely possible that we missed some crucial supply rate combinations for which one of these states was the only uninvadable state. Any such point would have rendered this state as dynamically stable. Such false assignments might lead to a violation of the basic empirical rule in our model stating that V uninvadable stable states are always accompanied by V À 1 uninvadable dynamically unstable states (V=ðV À 1Þ rule) for some sampled nutrient supply rates. In our Monte Carlo simulations of the 6C Â 6N Â 36S model the V=ðV À 1Þ rule was violated for only 370 nutrient supply rates combinations out of 1,000,000 sampled points. We believe that these violations were caused by an incorrect identification of dynamically unstable states mentioned above. To iteratively refine the lists of stable and unstable states, we went over all potentially unstable states one-by-one and checked whether reclassifying the state involved in the largest number of violations as stable would reduce the overall number of violations. If it did, we reclassified this state as stable and recalculated the number of violations for all remaining points. By the end of this iterative procedure we were able to completely eliminate violations by reassigning 36 potentially unstable states as dynamically stable. This left us with 1022 + 36 = 1058 dynamically stable and 173 À 36 = 137 dynamically unstable uninvadable states in the 6C Â 6N Â 36S model. The remaining 1211 À 1058 À 137 = 16 uninvadable states were not feasible for any of 1,000,000 sampled nutrient supply rates. Hence their dynamic stability remains unidentified. Both 36 reassigned states and 16 undetected states are expected to have very small ranges of feasible nutrient supply rates.

Multistability as a function of variation in stoichiometric ratios of different species
To investigate how multistability in our model depends on variation in stoichiometric ratios of different species, we simulated 4000 variants of the 2C Â 2N Â 4S model. In these variants, we kept the same choice of species competitiveness (quantified by their l's) but reassigned their yields Y. To cover a broad range of standard deviations of N:C stoichiometry of different species (their Y ðcÞ a =Y ðnÞ a ) we randomly sampled yield combinations from gradually expanding intervals. First we simulated 1000 model variants, where yields of four species were independently drawn from uniform distribution Uð0:45; 0:55Þ. These simulations were followed by 1000 model variants, where yields of four species were drawn from Uð0:3; 0:7Þ, 1000 model variants with yields from Uð0:1; 0:9Þ and, finally, 1000 model variants with yields from Uð0:01; 1:0Þ. In each variant of the model with a particular set of yields of four species, we calculated the fraction of multistable points among 10 5 nutrient supply rate combinations as described in the section 5.2 Monte-Carlo sampling of nutrient supply rates to identify feasible ranges of states of Materials and methods. The results are shown in Figure 5.

GitHub repository of the code used in our project
The PCA analysis, plots and statistical tests were implemented using R version 3.4.4. Other simulations were carried out in C (using compiler gcc version 5.4.0) and Python 3.5.2. Matlab analysis was done using MATLAB and Statistics Toolbox Release 2018a, The MathWorks, Inc, Natick, Massachusetts, United States. The code for both our simulations and statistical analysis can be downloaded from: https://github.com/ssm57/CandN (Dubinkina and Maslov, 2019; copy archived at https:// github.com/elifesciences-publications/CandN).

Additional information
Funding No external funding was received for this work.

Data availability
All data generated or analysed during this study are included in the manuscript and supporting files. The code for both our simulations and statistical analysis can be downloaded from: https://github. com/ssm57/CandN (copy archived at https://github.com/elifesciences-publications/CandN). Zhou X, Brown CJ, Abdo Z, Davis CC, Hansmann MA, Joyce P, Foster JA, Forney LJ. 2007. Differences in the composition of vaginal microbial communities found in healthy caucasian and black women.

General form of growth laws
It is straightforward to generalize our model to allow a more general functional form for growth laws than Liebig's law, minðl ðcÞ a c i ; l ðnÞ a n j Þ. Microbial growth on two essential substrates is thought to normally follow Monod's equation for the rate-limiting nutrient: g ðmÞ a minðc i =ðK ðcÞ a þ c i Þ; n j =ðK ðnÞ a þ n j ÞÞ (See Kovárová-Kovar and Egli, 1998 for a discussion of limitations of Monod's law). For low concentrations of the rate-limiting nutrient, say carbon source, the Monod's law simplifies to the linear growth law used throughout this study: In another variant of growth laws, two essential nutrients at low concentrations jointly affect the growth rate of the microbe: g ðmÞ a c i Á n j =½ðK ðcÞ a þ c i Þ Á ðK ðnÞ a þ n j Þ (see Bader, 1978 for a discussion of these and other forms of double-substrate growth law). For simplicity of mathematical calculation we limited this study to Liebig's law. However, many of the essential results we obtained (e. g. possible multistability in a system where species have different yields) hold for any growth laws listed above. In fact, the low concentration version of the previous growth law, where g ðmÞ a c i Á n j has been studied by one of us in the context of autocatalytic growth of heteropolymers (Tkachenko and Maslov, 2018). Instead of exponentially replicating microbial species Tkachenko and Maslov (2018) considers pairs of mutually catalytic (and thus exponentially growing) complementary '2-mers' (a specific sequence of two consecutive monomers anywhere within a polymer chain). This minor difference complicates the math, while leaving the basic properties unchanged. Just like in our system, where up to 2L species (out of L 2 candidates) may simultaneously survive in the steady state of an ecosystem grown on of L carbon and L nitrogen sources, the polymer systems have no more than 2Z 2-mer 'species' (out of Z 2 candidates) surviving in the steady state with polymers having Z possible monomers on their right ends and Z possible monomers on their left ends. Many (but not all) results of this paper are largely consistent with the present study. Note that for polymers the yields of all 'species' are equal to 1, that is to say, one new 2-mer is formed upon ligation of one left end of a polymer with one right of another polymer chain. Yet, the model in Tkachenko and Maslov (2018) is capable of (at least) bistability. At present, it is not clear if this is due to autocatalytic cycles having length two or this property would survive in a simpler version of the model in which instead of the Equation (1) of Tkachenko and Maslov (2018) one has _ d ij ¼ d ij ðl ij l i r j À dÞ and the overall fluxes of left and right ends are independent from each other (instead of both being equal to c i ¼ f i =d as in Tkachenko and Maslov, 2018).
Another variant of the model is where each species a has its own unique 'death' or 'maintenance' rate d a , playing the role of the same dilution rate d. The steady states of this model (but not the dynamics leading to these states) can be calculated by dividing both sides of Equations 2 by d a . This is equivalent by redefining the competitiveness parameters tol a ¼ l a =d a and setting the chemostat dilution rate tod ¼ 1. All of our results in the high-flux regime f ) d 2 =l would remain unchanged.
From (Equation 5-Equation 6) one can see that when all species have the same C:N stoichiometry, the maximal number of microbialspecies in a state is equal to the number of nutrients minus 1. Indeed, one can show that a state p with S surv ¼ K þ M has detðR p Þ ¼ 0, which means that the feasible volume of any such state is zero. These states are only possible on a lower-dimensional manifold in the ðK þ MÞ-dimensional space of supply rates (these results have been already discussed by Tilman in his special case; Tilman, 1982).
Multistability is also possible in a variant of the MacArthur model (MacArthur and Levins, 1964;MacArthur, 1970;Chesson, 1990) in which different species have different yields on individual carbon sources (Maslov, unpublished). A convex Lyapunov function (MacArthur, 1970) precluding multistability does not exist in this case.

Constraints on steady states from microbial and nutrient dynamics
A steady state of equations describing the microbial dynamics (Equation 2) is realized when either B a ¼ 0 (the species was absent from the system from the start or subsequently went extinct) or when its growth rate g a is exactly equal to the chemostat dilution rate d. This imposes constraints on steady state nutrient concentrations with the number of constraints equal to the number of microbial species present with non-zero concentrations. Since, in general, the number of constraints cannot be larger than the number of constrained variables, no more than K þ M of species could be simultaneously present in a steady state of the ecosystem. For Liebig's growth law used in this study, each resource can have no more than one species for which this resource limits its growth, that is to say, which sets the value of the minimum in minðl ðcÞ a c i ; l ðnÞ a n j Þ The steady state concentrations of these resources are given by c ðÃÞ i ¼ d=l ðcÞ a (if the growth is limited by the carbon source) and n ðÃÞ j ¼ d=l ðnÞ a (if the growth is limited by the nitrogen source). Here a is the species whose growth is rate-limited by the resource in question. In a general case, no more than one species can be limited by the same resource (carbon in our example), since the species with the largest l ðcÞ would outcompete other species with smaller values of l ðcÞ by making the steady state concentration c ðÃÞ i so low that other species can no longer grow on it. Note however, that multiple species b could consume the same resource as the rate-limiting species a, as long as their growth is not limited by the resource. Each of these species must then be limited by their other nutrient (a nitrogen source in our example). However, their survival requires that carbon concentration set by species a is sufficient for their growth. Thereby, any species growing on a resource in a non-limited fashion must have l . Exclusion Rule 1: Each nutrient (either carbon or nitrogen source) can limit the growth of no more than one species a. From this it follows that the number of species co-existing in any given steady state cannot be larger than K þ M, the total number of nutrients.
. Exclusion Rule 2: Each nutrient (e.g. specific carbon source) can be used by any number of species in a non-rate-limiting fashion (that is to say, where it does not constrain species growth in Liebig's law). However, any such species b has to have l ðcÞ b >l ðcÞ a , where l ðcÞ a is the competitive ability of the species whose growth is limited by this nutrient. In case of a nitrogen nutrient, the constraint becomes l , where a are the species rate-limited by each resource. In the absence of such species, the concentration of a resource is given by anything left after it being consumed by surviving species in a non-rate-limiting manner. One can show that in this case, the resource (e.g. carbon) concentration has to be larger than d=l ðcÞ b , where l ðcÞ b is the smallest affinity among microbes utilizing this resource.
One convenient approximation greatly simplifying working with Equation S2 is the 'highflux limit' in which f where aðiÞ is the (unique) species limited by the nutrient i. If the nutrient is not limiting for any os the species in the steady state, aðiÞ is the species using the nutrient in a non-limited fashion, which has the smallest value of l. This last rule comes from the observation that in order for a non-limiting resource not to become limiting for a species b currently using it in a non-limiting fashion, its concentration cannot fall below d=l ðxÞ b . Thus, when checking the feasibility of a given state, the concentration of a non-limiting resource can be written as d=l ðxÞ b þ a positive number, or (more conveniently) the influx of this resource can be offset as described in Equation S3 2.
Condition 2. Hospital h prefers applicant a to at least one of its assigned applicants.
If such a pair ða; hÞ exists, it is called 'a blocking pair' or 'a pair that blocks the matching'. A stable matching by definition has no blocking pairs. Gale and Shapley proved that for any set of applicant/hospital rankings and hospital vacancies there is at least one stable matching (Gale and Shapley, 1962). Generally the number of stable matching is larger than one. For example, for stable marriages and random rankings the average number of stable matchings is given by L=e log L (Gusfield and Irving, 1989). To the best of our knowledge, the dependence of this number on the distribution of hospital vacancies has not been investigated. The fact that the actual number of uninvadable states is rather close to its lower bound indicates that, at least for L 9, the number of stable matchings averaged over all possible in-degree allocations is rather close to 1.
Gale and Shapely not only proved the existence of at least one stable matching, but also proposed a constructive algorithm on how to find it. Listed below are the main steps in this algorithm optimized for for applicants. Each applicant first submits his/her application to the hospital ranking 1 in his/her preference lists. Each hospital considers all applications it received so far and accepts all of the applicants if their number is less or equal than hospital's announced number of vacancies, L i . If the number of applicants exceeds L i , the hospital gives a conditional admission to the best-ranking L i applicants according to hospital's own preference list. Each applicant not admitted to their top hospital goes a step down on his/her preference list and applies to the second-best hospital. The latter admits this applicant if (1) this hospital has not yet filled all of its vacancies or (2) all vacancies are filled, but among the conditionally admitted applicants there is at least one who ranks lower (according to hospital's list) than the new applicant. Such lower-ranked applicants are declined admission and replaced with better ones. They subsequently lower their expectations and apply to the next hospital on their list. After a number of iterations all applicants are admitted and all vacancies are filled so that this process stops. As Gale and Shapley (1962) proved, the resulting matching is stable. Furthermore, the theorem states that in this matching every applicant gets admitted to the best hospital among all stable matchings, while every hospital gets the worst set of residents among all stable matchings. Later research described in Gusfield and Irving (1989) describe more complex constructive algorithms allowing one to efficiently find all of the stable matchings starting with the applicant-optimal one.
Well developed mathematical apparatus of stable matching problem provides an invaluable help in the task of identifying all uninvadable states in microbial ecosystems. Indeed, without its assistance this task would require exponentially long time. To connect the problem of finding all uninvadable states to that of finding all stable matchings between hospitals and residents, we start with the following three observations:

1.
In any uninvadable steady state, either all carbon sources or all nitrogen sources (or both) are occupied. Indeed, if in a steady state a carbon source c i and a nitrogen source n j are notlimiting to any microbes, then microbe B ij can always grow and thereby invade this state. Thus uninvadable states can be counted separately: one first counts the states where all nitrogen sources are occupied, and then counts those in which all carbon sources are occupied. Double counting happens when both carbon and all nitrogen sources are occupied. We will keep the possibility of double counting in mind and return to this problem later.

2.
For a pool of species, where for every pair of resources there is exactly one microbe using each (carbon, nitrogen) pair, one can think of each of L carbon (alternatively, nitrogen) sources as if it had a list of 'preferences' ranking all nitrogen (correspondingly carbon) sources. Indeed, the ranking of competitive abilities l ðcÞ ik of different microbes using the same carbon source c i but different nitrogen sources n k can be viewed as the ranking of nitrogen sources k by the carbon source i. Conversely, the ranking of l ðnÞ mj with the same n j but variable c m can be thought of as ranking of carbon sources c m by the nitrogen source n j .

3.
Consider a steady state in which all nitrogen sources are occupied. In our network representation it corresponds to every nitrogen source sending an outgoing link to some carbon source. Let L i be the number of microbes using the carbon source i in a non-limiting fashion (the in-degree of these outgoing links ending on c i , see Appendix 3- figure 1C). Then, obviously, L ¼ P L i (note that some of the terms in this sum might be equal to zero).
One can prove that if the state is uninvadable, then the matching given by all edges going from nitrogen sources to carbon sources must be stable in the Gale-Shapley sense. To prove this, let's think of nitrogen sources as 'applicants' and carbon sources as 'hospitals' with their numbers of 'vacancies' given by L i . Indeed, any unstable matching has at least one blocking pair ðn j ; c i Þ such that: . Condition 1. The nitrogen source ('applicant') n j 'prefers' the carbon source ('hospital') c i to its currently assigned carbon source (the one used by the current microbe B kj limited n j ).
This means that l ðnÞ ij >l ðnÞ kj . Thus the microbe B ij can grow on its nitrogen source (provided that it can also grow on its carbon source).
. Condition 2. The carbon source ('hospital') c i 'prefers' the nitrogen source ('applicant') n j to at least one of L i of its currently assigned carbon sources (the set of microbes using c i in a non-rate-limiting fashion). Thereby l ðcÞ ij must be larger than the smallest l ðcÞ among these microbes. According to the Exclusion Rule 2, this smallest l ðcÞ is still larger than l ðcÞ of the microbe limited by c i (if it exists). Thus the microbe B ij can also grow on its carbon source.
This proves that the microbe B ij corresponding to any blocking pair can grow on both its carbon and its nitrogen sources, and thereby can successfully invade the steady state. This finishes the proof that any uninvadable state has to be a stable matching in the Gale-Shapley sense.
Appendix 3-figure 1. Network representation of a state in Stable Marriage analogy. (a) Schematic representation of state #5 in the 2C Â 2N Â 4S model (the same state is shown in Figure 1A in Main text). Here each species represented as an arrow connecting two resources it is utilizing for growth, with the color and direction of arrow representing growth-limitation of a species (red corresponds to C-limited species, blue N-limited one). (b)-(c) Schematic representation of two-step construction of state #991 in the 6C Â 6N Â 36S model. (b) We first assign all species that are growth-limited by N (blue links outgoing from N sources). The numbers above C sources indicate number of vacancies for a given resource. (c) Then for a given set of N-limited species we populate the remaining C-limited ones that are allowed by the Condition 2 (red links outgoing from C sources).
However, this does not prove that any stable matching corresponds to exactly one uninvadable state. To prove this we first notice that, up to this point, our candidate uninvadable state contained only the nitrogen-limited species (See Appendix 3- figure 1B) . We will now supplement it with carbon-limited species in such a way that (1) added species do not violate the exclusion rule 2; (2) added species render the state completely uninvadable. Let is introduce a new notation (applicable to our case in which all nitrogen sources are occupied). Let l ðcÞ min ðiÞ denote the smallest l ðcÞ among all species using c i in a non-rate-limiting fashion. The Gale-Shapley theorem only guarantees the protection of our state from invasion by a species ði; jÞ with l ðcÞ ij larger than l ðcÞ min ðiÞ (see the Condition 2 above). To ensure that our state is uninvadable by the rest of the species, one needs to add some carbon-limited species to this state. In order to do this in a systematic way, for each c i we compile the list of all species using this carbon source with l ðcÞ <l ðcÞ min ðiÞ. Each of these species is a potential invader. Some species could be crossed off from the list of potential invaders because they cannot grow on their nitrogen source. These species have l ðnÞ below that of the (unique) species limited by their nitrogen source. Among the species that remained on the list of invaders after this procedure, we select that with the largest l ðcÞ and add it to our steady state as a C ! N directed edge, that is to say, as a carbon-limited species. This will prevent all other potential invaders on our list, since they have smaller l ðcÞ and thus, following the addition of our top carbon-limited species, they would no longer be able to grow based on their carbon source. We will go over all c i and add such carbon-limited species if they are needed. The only scenario when such species is not needed if our list of potential invaders would turn up to be empty. In this case we will leave this carbon source unoccupied. See Appendix 3- figure 1C for the illustration of an uninvadabe state constructed by the above procedure in 6C Â 6N Â 36S model. Since for each carbon source the above algorithm selects the carbon-limited species (or selects to add no such species) in a unique fashion, there is a single uninvadable state for every stable matching in the Gale-Shapley sense. We are now in a position to predict and enumerate all uninvadable states in our model.

Lower bound on the number of uninvadable states
To count the number of partitions ðL 1 ; L 2 ; :::; L L Þ such that P L i ¼ L, one can use a well known combinatorial method. According to this method, one introduces L À 1 identical 'separators' (marked with |) which are placed between L identical objects (marked Á) separating them into L (possibly empty) partitions. For example, for L ¼ 4 a partition 0; 1; 0; 3 would be denoted as j Á jj Á ÁÁ. The combinatorial number of all possible arrangements of separators and objects is obviously 2LÀ1 L À Á . For every such partition the Gale-Shapley theorem guarantees at least one stable matching (that is, at least one uninvadable steady state). The lower bound on the number of uninvadable steady states has to be doubled to account for reversal of roles of carbons and nitrogens. There is a small possibility that we double counted one partition ð1; 1; :::; 1Þ. Indeed, the unique uninvadable stable state corresponding to this partition could in principle be counted both when we start from nitrogen sources and when we start from carbon sources. While such uninvadable steady states can and do occur, if only under rather special circumstances described below, they cannot be obtained by the classical Gale and Shapley resident(nitrogen)-proposing algorithm. Indeed, at the last step of the nitrogenproposing algorithm all carbon sources except just one carbon sources have all their vacancies already filled. Since the algorithm makes all nitrogen sources to go down their preference lists, at this point none of the carbon source whose outgoing arrow has already been accepted would prefer the last nitrogen with a vacancy to the one they have sent an arrow to. Thus, in terms of our adaptation of the Gale-Shapley algorithm to identify all uninvadable states, the last carbon to receive the incoming link from the last nitrogen does not need to be occupied (send a link from C to N) to prevent an invasion, as there is no one willing to invade it because of nitrogen preferences. Thus, in the uninvadable state identified by the Gale and Shapley nitrogen-proposing algorithm, this carbon source would have an incoming arrow but no outgoing arrow. Such states would not be double counted and would not affect our lower bound on the total number of uninvadable states in the model. A partition in which each carbon and each nitrogen source have exactly one vacancy could have more than two (possibly identical) stable states found by the Gale and Shapley nitrogen-proposing and carbon-proposing algorithms could lead to double counting. Hence, in general one may need to merge a handful of identical states independently found starting from carbon and nitrogen sides.
Then we have N UIS ! 2 2LÀ1 More generally, the number of carbon sources, K, is not equal to the number of nitrogen sources, M. The resource type with a larger number will always have at least one resource left without input. Thus here one never needs to correct for double counting. Using the same reasoning as for K ¼ M ¼ L, the lower bound on the number of resources in this case is given by KþMÀ1 Here, the first term counts the uninvadable steady states in which all nitrogen sources are occupied and the partition divides M edges sent by nitrogen sources among K carbon sources, which requires K À 1'dividers'. The second term counts the number of uninvadable steady states in which all carbon sources are occupied. Denoting the fraction of carbon resources among all resources as p ¼ K=ðK þ MÞ and using the Stirling approximation one gets exp ðK þ MÞðÀp log p À ð1 À pÞ logð1 À pÞ ½ ffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffiffi ffi 2pðK þ MÞpð1 À pÞ p : In the case of multiple microbial species using the same pairs of resources, our version of the Gale-Shapley resident-oriented algorithm must be further updated. Let M be the number of nitrogen sources, and K -the number of carbon sources in the ecosystem, S the number of species in our pool, each requiring a pair of resources to grow. As now there may be more than one microbe that uses a given pair of resources c i and n j , we introduce the notation B ðrÞ ij for the rth microbe using the same pair of sources c i and n j . On average, each nitrogen (carbon) source has S=K (S=M) microbes, which are capable of using it. As in the traditional Gale-Shapley algorithm, each nitrogen (carbon) source ranks all microbes capable of using it by their l ðnÞ (l ðcÞ ).
The way to identify all uninvadable stable states in this case is determined by a variant of the stable marriage problem (or rather the hospital/resident problem) in which every man (and every woman) may have more than one way to propose marriage to the same woman (man). In our model, this corresponds to more than one microbe (a type of marriage) capable of growing on the same pair of carbon (corresponding to, say, men) and nitrogen (corresponding to women) sources. You may think of it as if each participant has several different ways to propose to the person of the opposite sex (send flowers, take to a restaurant, etc). Each of these proposals is ranked by both parties independent of other ways. As far as we know, this variant has not been considered in the literature yet. However, all of the results of the usual stable marriage (or hospital-resident) problem remain unchanged.
One can easily see that our lower bound (Equation S5) on the number of uninvadable states (equal to the number of stable marriages in all partitions) remains unchanged. Indeed, it is given by the number of partitions and hence depends only on K and M and not on S. However, for S ) K Á M one expects to have many more stable marriages for each partition. Thus the lower bound we have established is likely to severely underestimate the actual number of UIS in the ecosystem.