### In vivo experiments

#### Animals

All experimental procedures were approved by the University of Minnesota Institutional Animal Care and Use Committee and were performed in accordance with guidelines from the US National Institutes of Health. We obtained 10 male and female ferret kits from Marshall Farms and housed them with jills on a 16 h light/8 h dark cycle. No statistical methods were used to predetermine sample sizes, but our sample sizes are similar to those reported in previous publications.

#### Viral injection

Viral injections were performed as previously described^{79} and were consistent with prior work^{11,14}. Briefly, we microinjected a 1:1 ratio of AAV1.hSyn.GCaMP6s.WPRE.SV40 (Addgene) and the somatically targeted AAV1.hSyn.ChrimsonR.mRuby2.ST (University of Minnesota Viral Vector and Cloning Core) into layer 2/3 of the primary visual cortex at P10–15, approximately 10–15 days before imaging experiments. This approach resulted in widespread labeling with both GCaMP and Chrimson. At the cellular level, the populations of GCaMP and Chrimson labeled cells were largely overlapping (Supplementary Fig. S2), although the relative strength of expression of both GCaMP and Chrimson varied within cells, as would be expected from stochastic effects resulting from dual labeling with two AAV viruses. For injection surgery, anesthesia was induced with isoflurane (3.5–4%) and maintained with isoflurane (1–1.5%). Buprenorphine (0.01 mg/kg) and glycopyrrolate (0.01 mg/kg) were administered, as well as 1:1 lidocaine/bupivacaine at the site of incision. Animal temperature was maintained at approximately 37 °C with a water pump heat therapy pad (Adroit Medical HTP-1500, Parkland Scientific). Animals were also mechanically ventilated and both heart rate and end-tidal CO2 were monitored throughout the surgery. Using aseptic surgical technique, skin and muscle overlying visual cortex were retracted. To maximize area of ChrimsonR expression, two small burr holes placed 1.5–2 mm apart were made with a handheld drill (Fordom Electric Co.). Approximately 1 µl of virus contained in a pulled-glass pipette was pressure injected into the cortex at two depths (~200 µm and 400 µm below the surface) at each of the craniotomy sites over 20 min using a Nanoject-III (World Precision Instruments). The craniotomies were filled with 2% agarose and sealed with a thin sterile plastic film to prevent dural adhesion, before suturing the muscle and skin.

#### Cranial window surgery

On the day of experimental imaging, ferrets were anesthetized with 3–4% isoflurane. Atropine (0.2 mg/kg) was injected subcutaneously. Animals were placed on a feedback-controlled heating pad to maintain an internal temperature of 37–38 °C. Animals were intubated and ventilated, and isoflurane was delivered between 1% and 2% throughout the surgical procedure to maintain a surgical plane of anesthesia. An intraparietal catheter was placed to deliver fluids. EKG, end-tidal CO2, and internal temperature were continuously monitored during the procedure and subsequent imaging session. The scalp was retracted and a custom titanium headplate adhered to the skull using C&B Metabond (Parkell). A 6–7 mm craniotomy was performed at the viral injection site and the dura retracted to reveal the cortex. One 4 mm cover glass (round, #1.5 thickness, Electron Microscopy Sciences) was adhered to the bottom of a custom titanium insert and placed onto the brain to gently compress the underlying cortex and dampen biological motion during imaging. The cranial window was hermetically sealed using a stainless-steel retaining ring (5/16-in. internal retaining ring, McMaster-Carr). Upon completion of the surgical procedure, isoflurane was gradually reduced (0.6–0.9%) and then vecuronium bromide (0.4 mg/kg/h) mixed in an LRS 5% Dextrose solution was delivered IP to reduce motion and prevent spontaneous respiration.

#### Simultaneous optogenetics and calcium imaging mesoscope

To achieve simultaneous widefield calcium imaging and targeted optogenetic stimulation, we built upon previous designs^{80} to construct a custom-built mesoscope (Supplementary Fig. S1, see ref. ^{45}). Epifluorescent calcium imaging was illuminated using a 470 nm LED (Thorlabs M470L5), which was reflected with a long-pass 495 nm dichroic mirror (Chroma T495lpxr, 50 mm) and focused onto the imaging plane using a Nikon objective (B&H Nikon AF NIKKOR 50 mm f/1.4D lens). Emitted light was focused onto the imaging sCMOS camera (Prime BSI Express, Teledyne) using an additional Nikon tube lens (B&H Nikon 105 mm f/2 D-AF DC lens) and an achromat lens (Thorlabs, ACN254-040, f = 40 mm). GCaMP emission was collected using a GFP bandpass filter (Semrock, 525/39).

To maximize the range of laser stimulus power onto the surface of the cortex and minimize the spectral bandwidth of the stimulation light in order to mitigate light artifacts, optogenetic stimulation was driven by a 590 nm continuous wave laser (Coherent MX 590 nm STM; CW). Laser power intensity was modulated using an acousto-optic modulator (Quanta-Tech MTS110-A3-VIS; AOM), which controlled the temporal aspects of the optogenetic stimulation (stimulus onset, duration, frequency, intensity, and waveform). The maximum power density at the imaging plane ranged from 14 to 16 mW/mm^{2}. The first-order diffracted beam from the AOM was coupled to a 400 µm multi-mode fiber (Changchun New Industries (CNI)), passed through a speckle remover (CNI), and into a DMD pattern illuminator (Mightex Polygon1000), which shaped the spatial aspects of the optogenetic stimulus. This patterned light was expanded using tube lens (f = 100 mm) and reflected to the imaging plane with a short-pass 567 nm dichroic mirror (Thorlabs DMSP567L, 50 mm). A photodiode was mounted behind the dichroic to provide precise tracking of stimulus onset times. Light artifacts from optogenetic stimulation were prevented from reaching the camera with a notch filter (594/23, Thorlabs NF594-23) in the collection pathway. Focal distances were adjusted for both the imaging and the stimulation pathways to be parfocal.

#### Widefield epifluorescence and optogenetic stimulation

All imaging of spontaneous activity was done in young animals (P23–29) prior to eye-opening (typically P31 to P35 in ferrets). Widefield epifluorescence imaging was performed with μManager (version 2.0.0-gamma1)^{81}. Images were acquired at 15 Hz with 2 × 2 on camera binning and additional offline 2 × 2 binning to yield 512 × 512 pixels. Prior to optogenetic stimulation, baseline spontaneous activity was captured in 10-min imaging sessions, with the animal sitting in a darkened room facing an LCD monitor displaying a black screen.

Optogenetic stimulation was similarly delivered in the absence of visual stimulation, and the animal’s eyes were shielded from the stimulation laser to prevent indirect stimulation of the retina. Analysis of the opto-evoked events further confirmed this, as we found that visually-evoked events poorly explained the spatial structure of opto-evoked events (Supplementary Fig. S7). For all experiments opto-stimulation was delivered at 10 mW/mm^{2}, except those that investigated the effect of varying the power of the stimulus intensity (Supplementary Fig. S3). Opto-stimuli were presented for 1 s duration with a 5 s interstimulus interval. For uniform full-field optogenetic stimulation, the whole FOV of the DMD illuminator was activated. For patterned stimulation (see below), black and white bitmap images to be projected onto the surface of the cortex were made using Polyscan software (version 1.2.2, Mightex) or Matlab (Mathworks). To map the region of the cortex that was responsive to optogenetic stimulation, we stimulated the cortex with a 4 × 4 grid of approximately 1×1 mm squares moving sequentially over the FOV. We frequently saw a robust response to optogenetic stimulation across the imaging FOV (Supplementary Fig. S12), and animals that failed to show significant responses to optogenetic stimulation in an area >1 mm^{2} were excluded from this study.

#### Spatially structured optogenetic stimuli

We generated artificial structured patterns to project onto the surface of the cortex by bandpass filtering white noise (size 256 ×256 pixels) at varying wavelengths. Bandpass filtering was applied in the frequency domain by a hard cutoff outside the band defined by f_{low} and f_{high}. For simplicity, below we provide these cutoffs in units of pixels in the frequency domain, from which frequencies can be obtained through (f-1)l/256, where l is the resolution of pixel per mm in real space (l = 65 pixels/mm in this case). We binarized these patterns by setting a threshold at the 68th percentile pixel values, producing isolated blobs with a specific wavelength. To test the specificity of opto-evoked activity, for each wavelength we generated three artificial patterns, and then alternated in stimulating with each pattern (3 patterns with 40 trials each, 1 s duration, 5 s interstimulus interval). All tested animals were stimulated with patterns aimed to be smaller than the characteristic wavelength of the network (f_{low} = 40 pixels, f_{high} = 100 pixels; wavelength of approximately 0.5 mm, given) and patterns that approximated the characteristic wavelength of the network (f_{low} = 60 pixels, f_{high} = 100 pixels; wavelength of approximately 0.7 mm). For a subset of experiments, we used narrow bandpass patterns to sample a larger range of wavelengths (5 wavelengths varying f_{low} from 40 to 120 pixels with step size = 20 and setting f_{high} = f_{low} + 4, wavelength approx. 0.48 to 1.10 mm, *n* = 2 animals).

#### Visual stimulation

Visual stimuli were delivered on an LCD screen placed approximately 22 cm in front of the eyes. All animal eyelids were closed, except for animals used for LGN silencing experiments (*n* = 3 animals) whose eyelids were manually opened prior to imaging. Full-field change-in-luminance stimuli were used to evoke ON and OFF responses, with a Michelson contrast of 1. Stimuli were presented using Psychopy software(2020.2.8)^{82} for 5 s ON, 5 s OFF. Individual ON/OFF evoked-events were calculated by averaging evoked responses over the first 2 s following stimulus onset, and ON/OFF maps were calculated by taking the average ON or OFF response across trials, with difference maps showing the difference between ON – OFF responses.

#### LGN silencing

To deliver the GABA(A) agonist muscimol to the LGN, we drilled a craniotomy window (4–11 mm from the midline, 7–11 mm from lambda) prior to imaging. Dura was retracted and exposed cortex was covered and sealed with 2% agarose. To locate and map the LGN, a 5 MΩ electrode (FHC) was driven approximately 7 mm down perpendicularly into the brain using a micromanipulator. An alternating ON/OFF full-field visual stimulus was presented, and successful location of the LGN was identified by multi-unit or single-unit spike responses to change-in-luminance stimulation. The electrode was retracted, and replaced with a pulled glass pipet filled with 100 mM muscimol. Five pulses of 50 nL each were pressure injected into the LGN at 3 depths along the LGN vertical axis (spaced approximately 500 um apart) using a glass-pulled pipet tip. Effective silencing was confirmed by measuring the loss of ON and OFF responses in the visual cortex (Supplementary Fig. S9).

#### Kynurenic acid experiments

To silence propagating synaptic activity within our imaging field of view, we removed the coverslip cannula from the imaging window and bath applied approximately 100 mL of 2 mM kynurenic acid (KYN) to the surface of the cortex. After waiting approximately 5 min for the drug to take effect, we then delivered full-field optogenetic stimulation to the cortex, using the same stimulus parameters as above.

#### Histology and confocal imaging

For a subset of animals, following imaging animals were euthanized and transcardially perfused with 0.9% heparinized saline and 4% paraformaldehyde. The brains were extracted, post-fixed overnight in 4% paraformaldehyde, and stored in 0.1 M phosphate buffer solution. Brains were cut using a vibratome in 50 µm coronal sections, which were then imaged on a confocal microscope (Nikon AX R).

### Data analysis

#### Signal extraction for widefield epifluorescence imaging

Image series were motion corrected using rigid alignment and a region of interest (ROI) was manually drawn around the cortical region of GCaMP expression, excluding major blood vessels. The baseline fluorescence (F_{0}) for each pixel was obtained by applying a rank-order filter to the raw fluorescence trace with a rank 70 samples and a time window of 30 s (451 samples). The rank and time window were chosen such that the baseline faithfully followed the slow trend of the fluorescence activity. The baseline-corrected spontaneous activity was calculated as:

$$\Delta F/F_0=\frac(F-F_0)F_0$$

(1)

#### Event detection and preprocessing

Spontaneous: Detection of spontaneously active events was performed as previously described^{11,14}. Briefly, we first determined active pixels on each frame using a pixelwise threshold set to 5 s.d. above each pixel’s mean value across time. Active pixels not part of a contiguous active region of at least 0.01 mm^{2} were considered ‘inactive’ for the purpose of event detection. Active frames were taken as frames with a spatially extended pattern of activity (>80% of pixels were active). Consecutive active frames were combined into a single event starting with the first high-activity frame and then either ending with the last high-activity frame or, if present, an activity frame defining a local minimum in the fluorescence activity. To assess the spatial pattern of an event, we extracted the maximally active frame for each event, defined as the frame with the highest activity averaged across the ROI.

Opto-evoked: Opto-evoked evoked events were detected by taking the frame at opto-stimulus offset. Modular activity was reliably time-locked to the stimulus, and we made no effort to search for peaks to minimize the potential of our results being contaminated by ongoing spontaneous activity.

To preprocess data, all events were mean activity subtracted and filtered with a Gaussian spatial band-pass filter (σ_{low} = 26 µm and σ_{high} = 195 µm). The mean activity of opto-evoked events was non-modular (Supplementary Fig. S12a), and mean subtraction helped normalize differences in baseline fluorescence between spontaneous and opto-evoked events.

#### Modularity and estimation of event wavelength Λ

To estimate the wavelength and modularity of individual calcium events, we calculated the spatial autocorrelation of the Gaussian highpass filtered image (Fig. 2f, *top*). We then took the radial average of the autocorrelation to get a 1-dimensional autocorrelation function (Fig. 2f, *bottom*). The wavelength *Λ* of the event was calculated as twice the distance to the first minimum from the origin. Modularity is a measure of the regularity of the spatial arrangement of the pattern. It was calculated by finding the absolute difference in correlation amplitude between the first minimum and the subsequent maximum of the 1-dimensional autocorrelation.

#### Modular amplitude

In order to estimate the amplitude of modular peaks, we measured the average spectral power within a band centered around the characteristic wavelength, defined as the average wavelength of spontaneous activity within each animal. We controlled for FOV size across animals and minimized orientation effects by cropping each unfiltered opto-evoked event to a 2 mm diameter circular mask centered within the imaging ROI, and then reduced the DC component of the image by subtracting the mean ∆F/F across the cropped event frame. From this, we computed the Fourier transform of each event, took the squared modulus and the radial average to get the 1D power spectrum. F_{1} is the average power within a spatial frequency band centered on the characteristic frequency, i.e. the interval [2π/(*Λ*−0.06 mm), 2π/(*Λ* + 0.06 mm)].

#### Trial-to-trial variability of opto-evoked events

To determine the trial-to-trial variability in opto-evoked activity, we computed the event-wise Pearson’s correlation between calcium events (Fig. 2i). To visualize clusters of events with similar structure, we performed hierarchical clustering of the correlation matrix (linkage threshold set as half the maximum pairwise distance). Hierarchical clustering was calculated in Python using SciPy’s library (version 1.7.3) of hierarchical clustering functions.

When computing the event correlation matrices for spatially structured opto-evoked activity (Fig. 3d), we did not cluster these events but instead organized the matrix by stimulus pattern ID. The trial-to-trial correlation (Supplementary Fig. S8) was summarized as the mean correlation across all pairs of trials driven by the same stimulus pattern (within pattern), compared to pairs of trials not driven by that specific pattern (across pattern). Controls were estimated by random trial shuffling of the stimulus IDs and taking the average correlation of event number matched trial pairs, then finding the mean across 100 random shuffle simulations.

#### Similarity of opto-evoked activity and optogenetic stimulus pattern

To quantify how similar opto-evoked activity was to its specific stimulus input pattern, we calculated the spatial correlation between each opto-evoked event with each stimulus pattern. The similarity between the i-th event (\(A_i\)) and the j-th stimulus pattern (\(S_j\)) is:

$$\rho _i,j=\, \rmcorr(A_i,\, S_j)$$

(2)

where \({{{{\rmcorr}}}}\) is the Pearson’s correlation over space. Thus, for each event we calculated how similar it was to the specific pattern it was driven with and can compare this to stimulus patterns that it was not driven with (Fig. 3e). For quantifying how similar the mean trial response was to the stimulus input, the same approach was used, except that \(A\) corresponds to the trial averaged pattern. For comparing across animals (Fig. 3f, g) we took the mean across the three stimulus conditions when stimulus ID matched event ID. We estimated a control by trial shuffling the event IDs, to determine how much a given evoked response overlapped with the stimulus pattern by chance (average across 100 random shuffle simulations).

#### Similarity between opto-evoked and spontaneous events

To determine the similarity between individual opto-evoked events and baseline spontaneous calcium events, we computed the event-wise Pearson’s correlation between all events from both datasets. To visualize clusters of events with similar structure (Fig. 6b), we performed hierarchical clustering of the correlation matrix and then segregated the opto-evoked and spontaneous events and sorted by these cluster labels. Since the total number of spontaneous events typically outnumbered the opto-evoked events, for presentation purposes we randomly subsampled an opto-event number matched group of spontaneous events and showed their correlations with opto-evoked activity. Statistical analysis of event correlation distributions included the full correlation matrix of all spontaneous and opto-evoked events.

To estimate the amount of spatial correlation expected by chance, we generated a set of surrogate events by randomly flipping, rotating, and shifting opto-evoked events, thereby maintaining the statistics of the images but disrupting any consistent spatial relationships. Rotation angle drawn from a uniform distribution between 0° and 360° with a step size of 10°, translated shifts were drawn from a uniform distribution between ±450 µm in increments of 26 µm, independently for x and y directions. Reflection occurred with a probability of 0.5, independently at the x and y axes at the center of the ROI. We then computed the surrogate events vs spontaneous event correlation matrix and compared the distributions of correlations for opto-evoked and surrogate control data (Fig. 6c). We used the Kolmogorov–Smirnov test to quantify the similarity of distributions. Individual opto-evoked patterns were considered highly similar to spontaneous events if their correlation was greater than 2 standard deviations over the mean surrogate correlation.

To determine whether the amount of overlap between spatially structured opto-evoked activity significantly deviated from the amount of overlap that could be expected to occur naturally in spontaneous activity, we found each opto-evoked event’s best matching spontaneous pattern. To control for finite sampling size, best matching pairs were found by finding the maximum event-wise Pearson’s correlation between each opto-evoked event and a randomly subsampled, event number matched subset of spontaneous events (*n* = 40). To estimate the null distribution, we did a permutation test finding the average maximum correlation between this same subset of spontaneous events and a separate, equally sized randomly subsampled subset of spontaneous events (*n* simulations = 500), which was used to find the 95% confidence interval.

#### Pixelwise correlation patterns

Correlation patters were calculated using either spontaneous events or opto-evoked events. Correlation patters were calculated as previously described^{11,14}. Briefly, we down sampled each spatially filtered event to 128 × 128 pixels. The resulting events were used to compute the correlation patterns as the pairwise Pearson’s correlation between all locations ** x** within the ROI and the seed point (

**)**

*s*$$C\left(\boldsymbols,\, \boldsymbolx\right)=\frac1N\sum _i=1^N\frac{\left(A_i\left(\boldsymbols\right)-\left\langle A({{{{\boldsymbols}}}})\right\rangle \right)\left(A_i\left(\boldsymbolx\right)-\left\langle A(\boldsymbolx)\right\rangle \right)}{\sigma _{{{{{{\boldsymbols}}}}}}\sigma _\boldsymbolx}$$

(3)

where *A* are the events, the brackets 〈 〉 denote the average over all events and *σ*_{x} denotes the standard deviation of *A* over all *N* events at location ** x**.

#### Comparison of similarity between correlation networks

To compare the similarity between spontaneous and opto-evoked correlation patterns within the same animal, we computed the second-order correlation between patterns. For each seed point, we calculated the Pearson’s correlation between corresponding correlation patterns, while excluding pixels within a 400-μm radius around the seed point to prevent local correlations from inflating the similarity between the two correlation patterns. To obtain an estimate of the upper bound of similarity within spontaneous activity given a finite sampling size, we randomly split spontaneous events into two groups and separately computed correlations and the second-order correlations between the halves (*n* simulations = 100). To determine if the observed networks are more similar than chance, we calculated the similarity between the opto-evoked network and a network calculated from surrogate events (as above).

#### Principal component analysis and dimensionality of calcium events

We estimated the linear dimensionality *d*_{eff} of the subspace spanned by activity patterns by the participation ratio^{83}:

$$d_{{{\rmeff}}}=\frac\left(\sum _i=1^N\gamma _i\right)^2\sum _i=1^N\gamma _i^2$$

(4)

where \(\gamma _i\) are the eigenvalues of the covariance matrix for the *N* pixels within the ROI. As the value of the dimensionality is sensitive to differences in detected event number, to estimate the distribution of the dimensionality for each animal, we calculated the dimensionality of randomly sub-sampled events (*n* = 40 events, matched across animals, 100 simulations) and took the median of the distribution.

To determine the amount of variance spontaneous activity can explain of opto-evoked events, we projected opto-evoked variance onto the principal components of spontaneous activity. The variance of a dataset A (opto-evoked) explained by the i-th principal component \(\boldsymbolp_i,B\) of dataset B (spontaneous) is:

$${{\mathrmvar}}_i,A=\frac{{\boldsymbolp}_i,B^T\,\cdot \,\boldsymbol\Sigma _A\cdot {{{{{{\boldsymbolp}}}}}}_i,B}{{{\rmTr}}({{{{\boldsymbol\Sigma }}}}_A)}$$

(5)

where \({{{{{{\boldsymbol\Sigma }}}}}}_A\) is the covariance matrix of dataset A and \({{{{{{\boldsymbolp}}}}}}_i,B\) is normalized to unit length.

Spontaneous principal component analysis was cross-validated by segregating spontaneous events into two randomly subsampled (without replacement)event matched training groups and test groups. The training group was used to generate the principal component basis set, and the test group was then projected onto the training group components to estimate the corresponding variances \(\gamma _i\). To estimate the null distribution and compute confidence intervals, we performed 100 repetitions of cross-validation. Principal components were computed using the python library Scikit (version 1.0.2)^{84}.

#### Quantification and statistical analysis

Nonparametric tests were used for statistical testing throughout the study. Random subsampling, bootstrapping, and cross validation was used to determine null distributions when indicated. Center and spread values are reported as mean and SEM, unless otherwise noted. Statistical analyses were performed in Python, and significance was defined as *p* < 0.05. Tests for significance were always two-sided, unless otherwise indicated.

### LE/LI network model

To model our spatially structured optogenetic experiments (Fig. 4, Supplementary Figs. S5, S13), we build upon previous work^{11}. We modeled the effects of driving cortical activity with spatially structured input patterns in a rate network with recurrent connections following the scheme of local excitation and lateral inhibition (LE/LI). Pattern formation in such a network typically involves the selective amplification of spatial patterns with a characteristic spatial wavelength Λ. In a nonlinear system such selective amplification may be caused by a linear instability of a uniform solution and the growth of spatial Fourier modes around the characteristic frequency *k* = 2π/*Λ*, sometimes referred to as the supercritical regime (Fig. 1b illustrates this case). However, also in a subcritical regime, below but sufficiently close to this critical point of linear instability and pattern formation, modes around the characteristic frequency are selectively amplified when driven by broad-band input, and these modes decay much slower than those with low or high spatial frequency. For instance, when stimulating such network with spatial white noise, a spatial pattern emerges that is dominated by the characteristic frequency. Since the basic predictions illustrated in Fig. 1 essentially test selective amplification around a characteristic wavelength, they apply to both regimes. For the sake of simplicity, we therefore studied our network model in the subcritical regime, ignoring possible effects due to the saturation of pattern growth (Supplementary Fig. S3). To this end, we used a linear rate network model^{85}:

$$\tau \fracdr(\boldsymbolx,\, t)dt=-r\left(\boldsymbolx,\, t\right)+\mu \sum_yM\left({\boldsymbolx},\, \boldsymboly\right)r\left(\boldsymboly,\, t\right)+I({{{{{\boldsymbolx}}}}})$$

(6)

Here, *r*(** x**,

*t*) is the average firing rate in a local pool of neurons at location

**,**

*x**τ*is the neuronal time constant (set to 1), and

*M*(

**,**

*x***) is the cortical connectivity from location**

*y***to**

*y***. In the most basic form of the model, the cortical connectivity is defined as a difference of Gaussians**

*x*$$M\left({{{{{\boldsymbolx}}}}},\, \boldsymboly\right)=\frac12\pi \sigma _1^2\exp \left(-\frac{{\left|{{{{{\boldsymbolx}}}}}-{{\boldsymboly}}\right|}^2}2\sigma _1^2\right)-\frac12\pi \sigma _2^2\exp \left(-\frac{{\left|{{{{{\boldsymbolx}}}}}-{{{{{\boldsymboly}}}}}\right|}^2}2\sigma _2^2\right)$$

(7)

where *σ*_{1} and *σ*_{2} is controlling the spatial range of the excitatory and inhibitory connections, respectively. The factor \(\mu\) is controlling the overall strength of connections, set such that the maximum eigenvalue of the connectivity matrix is equal to 0.99 (hence the system close to the critical point of pattern formation). The characteristic wavelength *Λ* of the network was directly estimated from the peak of the spectrum of *M* and depends on the connectivity parameters through the expression

$$\varLambda ^2=\frac\pi ^2\sigma _1^2(\kappa ^2-1){{\mathrmln}(\kappa )}$$

(8)

where *κ* = *σ*_{2}/*σ*_{1}. In all our simulations we used a network size = 60 × 60 and set *σ*_{1} = 1.8 and *σ*_{2} = 3.6 (in pixels), resulting in a value of *Λ* = 11.76 pixels. All modeling results shown in the Figures are expressed in units of *Λ*. *I*(** x**) is the input to cortical location

**, assumed to be constant in time (described further below). All solutions were computed at steady-state via direct matrix multiplication.**

*x*Previous work^{11} has shown that networks with isotropic local excitatory and lateral inhibitory connectivity fail to produce activity with long range correlations as large as observed in vivo, but that adding heterogeneity to the connection weights can produce biologically realistic activity patterns, correlation structure and dimensionality. To introduce heterogeneity in our connectivity, we perturbed our network connectivity by multiplying the connectivity kernel *M*(** x**,

**), for any fixed location**

*y***, with the expression:**

*x*$$1+hG({{{{{\boldsymboly}}}}})$$

(9)

where \(h\) is the strength of the perturbation and \(G({{{{{\boldsymboly}}}}})\) is a spatially structured Gaussian random field (computed by bandpass-filtering an uncorrelated Gaussian random field using a difference of Gaussians with *σ*_{low} = 2, *σ*_{high} = 6). Consistent with the network size, *G* was implemented as a 60 × 60 matrix and chosen to be the same for each ** x**. Importantly, the effects of network wavelength transformations of stimulus inputs show a similar bias towards the characteristic wavelength of the network (Fig. 4a–c) as would be expected from a network with homogenous, isotropic connectivity (

*h*= 0, Supplementary Fig. S13), demonstrating that the predictions of the LE/LI mechanism studied here also hold for networks with more realistic, heterogeneous connectivity (

*h*= 0.4).

To simulate the effects of input into the network, to model the in vivo experiments with optogenetic stimulation, the input *I* consisted of a noise component to reflect the impact of various sources of noise in vivo (represented as a dice in Figs. 1, 4, Supplementary Figs. S5 and S13) and a stimulus component:

$$I({{{{{\boldsymbolx}}}}})=\eta N({{{{{\boldsymbolx}}}}})+\omega S({{{{{\boldsymbolx}}}}})$$

(10)

The noise *N*(** x**) was sampled from an uncorrelated Gaussian random field (centered at zero), with its amplitude controlled by the coefficient

*η*. The stimulus or input drive

*S*(

**) was set to 1 for uniform stimulation (Supplementary Figs. S5a–c and S13b). Structured input drive (Fig. 4a–c, Supplementary Figs. S5d–h and S13c–h) was generated analogously to the stimulus patterns used in vivo by applying, in the frequency domain, a narrow bandpass to spatial white noise, and then binarizing the resulting pattern at the 68-percentile threshold. To model the effect of varying wavelengths, we generated structured inputs with incrementally increasing wavelengths (29 bandpass bins, varying**

*x**f*

_{low}from 1 to 8 with step size = 0.25 and setting

*f*

_{high}=

*f*

_{low}+ 2,

*n*= 10 distinct patterns per wavelength). The amplitude of the structured input is defined by \(\omega\). To estimate the effect on wavelength for individual activity patterns and stimulus mean responses (Fig. 4b, c), for each bandpass stimulus pattern we ran 40 simulations varying the input noise while keeping \(S\) constant. We then computed the wavelength of the individual output activity patterns and the wavelength of the mean output activity across simulations. The spatial wavelength of the band-pass used is expressed relative to that computed from Eq. (8). To determine the impact of stimulus versus noise amplitude (Supplementary Fig. S5h), \(\omega\) was varied from 0.05 to 0.6.

### Reporting summary

Further information on research design is available in the Nature Portfolio Reporting Summary linked to this article.

link