-
Notifications
You must be signed in to change notification settings - Fork 1
/
landscape.py
1154 lines (953 loc) · 38.5 KB
/
landscape.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''Single species, one type of patch and matrix - basic module.'''
import numpy as np
from collections import OrderedDict
from itertools import product as iproduct
try:
from matplotlib import pyplot as plt
except ImportError:
pass
## example parameters
#par = OrderedDict([
# ('r', 0.1),
# ('K', 1.),
# ('mu', 0.03),
# ('Dp', 1e-4),
# ('Dm', 1e-3),
# # interface condition (=Dm/Dp)
# #('g', 1.), # no longer required
# # boundary conditions
# ('left', [1., 0., 0.]),
# ('right', [1., 0., 0.]),
# ('top', [1., 0., 0.]),
# ('bottom', [1., 0., 0.])
# ])
# in km
#dx = 0.0286
# 35 pixels -> 1km = 1000m
# 1 pixel -> 0.0286km
# D: 10^-2 km^2/day
# r: 10-50/year ~ 0.1 day^-1
# mu: 1/30 days ~ 0.03 day^-1
## dados novos
# in km
dx = 0.02
# 1 pixel -> 0.02km
# Dm ~ 900 m^2/day ~ 10^-3 km^2/day
# Dp ~ 5 m^2/day ~ 10^-5 km^2/day
# r: 10-50/year ~ 0.1 day^-1
# mu: 1/30 days ~ 0.03 day^-1
def solve_landscape(landscape, par, dx, f_tol=None, force_positive=False, verbose=True):
r"""Find the stationary solution for a given landscape and set of parameters.
Uses a Newton-Krylov solver with LGMRES sparse inverse method to find a
stationary solution (or the solution to the elliptical problem) to the
system of equations in 2 dimensions (x is a 2-d vector):
.. math::
u_t(x) &= D_p \nabla^2 u(x) + ru(1-u(x)/K) = 0 \text{ in a patch} \\
v_t(x) &= D_m \nabla^2 v(x) - \mu v(x) = 0 \text{ in the matrix}
Notes
-----
This function preserves the original interface, but internally it calls the
newer `solve_landscape_ntypes()`.
Parameters
----------
landscape : 2-d array of ints
describe the landscape, with 1 on patches and 0 on matrix
par : dict
parameters (dict keys):
- r : reproductive rate on patches
- K : carrying capacity on patches
- mu : mortality rate in the matrix
- Dp : diffusivity on patches
- Dm : diffusivity in the matrix
- g : habitat discontinuity parameter \gamma. See interface conditions
below (optional, determined from Dp, Dm and alpha if absent)
- alpha : habitat preference, only taken into account if g is not
present. In that case, g is calculated as g = Dm * alpha /
(Dp*(1-alpha)) (optional, ignored if g is given, set to 1/2 if both
are absent)
- left : (a, b, c): external boundary conditions at left border
- right : (a, b, c): external boundary conditions at right border
- top : (a, b, c): external boundary conditions at top border
- bottom : (a, b, c): external boundary conditions at bottom border
dx : float
lenght of each edge
f_tol : float
tolerance for the residue, passed on to the solver routine. Default is
6e-6
force_positive : bool
make sure the solution is always non-negative - in a hacky way. Default
False
verbose : bool
print residue of the solution and its maximum and minimum values
Returns
-------
solution : 2-d array of the same shape of the landscape input
the solution
.. rubric:: Boundary and interface conditions
External boundaries are of the form
.. math:: a \nabla u \cdot \hat{n} + b u + c = 0
and may be different for left, right, top, bottom. The derivative of u is
taken along the normal to the boundary.
The interfaces between patches and matrix are given by
.. math::
u(x) &= \gamma v(x) \\
D_p \nabla u(x) \cdot \hat{n} &= D_m \nabla v(x) \cdot \hat{n}
where u is in a patch and v is the solution in the matrix. Usually the
discontinuity $\gamma$ is a result of different diffusivities and
preference at the border (see Ovaskainen and Cornell 2003). In that case,
given a preference $\alpha$ (between 0 and 1, exclusive) towards the patch,
this parameter should be:
.. math:: \gamma = \frac{D_m}{D_p} \frac{\alpha}{1-\alpha}
This last condition is used in case $\gamma$ is not set. If $\alpha$ isn't
set either, it's assumed $\alpha = 1/2$. These conditions are handled using
an asymetric finite difference scheme for the 2nd derivative:
.. math:: u_{xx}(x) = \frac{4}{3h^2} (u(x-h) - 3 u(x) + 2 u(x+h/2))
At the interface, $u(x+h/2)$ and $v(x+h/2)$ must obey:
.. math::
u(x+h/2) &= \gamma v(x+h/2) \\
D_p (u(x+h/2) - u(x)) &= D_m (v(x+h) - v(x+h/2))
Solving this system, we arrive at the approximation at the interface:
.. math:: u(x+h/2) = \frac{D_m v(x+h)+D_p u(x)}{D_p+D_m / \gamma}
if u(x) is in a patch and v(x+h) is in the matrix, or
.. math:: v(x+h/2) = \frac{D_m v(x)+D_p u(x+h)}{D_p \gamma +D_m}
if v(x) is in the matrix and u(x+h) is in a patch.
References
----------
Ovaskainen, Otso, and Stephen J. Cornell. "Biased movement at a boundary
and conditional occupancy times for diffusion processes." Journal of
Applied Probability 40.3 (2003): 557-580.
"""
p = OrderedDict([
('r', [-par['mu'], par['r']]),
('K', [np.Inf, par['K']]),
('D', [par['Dm'], par['Dp']]),
('left', par['left']),
('right', par['right']),
('top', par['top']),
('bottom', par['bottom'])
])
return solve_landscape_ntypes(landscape, p, dx, f_tol, force_positive,
verbose)
def solve_landscape_ntypes(landscape, par, dx, f_tol=None,
force_positive=False, skip_refine=False, return_residual=False,
verbose=True):
r"""Find the stationary solution for a landscape with many types of habitat.
Uses a Newton-Krylov solver with LGMRES sparse inverse method to find a
stationary solution (or the solution to the elliptical problem) to the
system of equations in 2 dimensions (x is a 2-d vector):
.. math::
\frac{\partial u_i}{\partial t} = D_i \nabla^2 u_i +
r_i u_i\left(1-\frac{u}{K_i}\right) = 0
Parameters
----------
landscape : 2-d array of ints
describe the landscape, with any number of habitat types
par : dict
parameters (dict keys):
- r : growth rates (can be negative)
- K : carrying capacities (cn be np.Inf)
- mu : mortality rate in the matrix
- D : diffusivities
- g : dict of habitat discontinuities $\gamma_{ij}$ - see interface
conditions below. The keys are tuples (i,j) of the habitat
types indices (optional)
- alpha : dict of habitat preferences, only taken into account if g is
not present. In that case, $\gamma_{ij}$ is calculated as
$\gamma_{ij} = D_j \alpha_{ij} / (D_i*(1-\alpha_{ij}))$ (optional)
- left : (a, b, c): external boundary conditions at left border
- right : (a, b, c): external boundary conditions at right border
- top : (a, b, c): external boundary conditions at top border
- bottom : (a, b, c): external boundary conditions at bottom border
dx : float
lenght of each edge
f_tol : float
tolerance for the residue, passed on to the solver routine. Default is
6e-6
force_positive : bool
make sure the solution is always non-negative - in a hacky way. Default
False
skip_refine : bool
do not refine the grid to calculate the residual. This can greatly
improve speed, but will generate errors (even silent wrong results) if
the landscape has contiguous interfaces
return_residual : bool
returns only the residual function, without calculating the solution
verbose : bool
print residue of the solution and its maximum and minimum values
Returns
-------
solution : 2-d array of the same shape of the landscape input
the solution
.. rubric:: Boundary and interface conditions
External boundaries are of the form
.. math:: a \nabla u \cdot \hat{n} + b u + c = 0
and may be different for left, right, top, bottom. The derivative of u is
taken along the normal to the boundary.
The interfaces between patches and matrix are given by
.. math::
u_i(x) &= \gamma_{ij} u_j(x) \\
D_i \nabla u_i(x) \cdot \hat{n} &= D_j \nabla u_j(x) \cdot \hat{n}
Usually the discontinuity $\gamma_{ij}$ is a result of different
diffusivities and preference at the border (see Ovaskainen and Cornell
2003). In that case, given a preference $\alpha_{ij}$ (between 0 and 1,
exclusive) towards $i$, this parameter should be:
.. math:: \gamma_{ij} = \frac{D_j}{D_i} \frac{\alpha_{ij}}{1-\alpha_{ij}}
This last condition is used in case $\gamma$ is not set. If $\alpha$ isn't
set either, it's assumed $\alpha = 1/2$. Notice that $\alpha_{ij} +
\alpha_{ji} = 1$, and so $\gamma_{ij} = \gamma_{ji}^{-1}$. To ensure this
condition, the key (i,j) is always taken with $i>j$.
These conditions are handled using an asymetric finite difference scheme
for the 2nd derivative:
.. math:: u_{xx}(x) = \frac{4}{3h^2} (u(x-h) - 3 u(x) + 2 u(x+h/2))
At the interface, $u(x+h/2)$ and $v(x+h/2)$ must obey:
.. math::
u(x+h/2) &= \gamma v(x+h/2) \\
D_p (u(x+h/2) - u(x)) &= D_m (v(x+h) - v(x+h/2))
Solving this system, we arrive at the approximation at the interface:
.. math:: u(x+h/2) = \frac{D_m v(x+h)+D_p u(x)}{D_p+D_m / \gamma}
if u(x) is in a patch and v(x+h) is in the matrix, or
.. math:: v(x+h/2) = \frac{D_m v(x)+D_p u(x+h)}{D_p \gamma +D_m}
if v(x) is in the matrix and u(x+h) is in a patch.
Example
-------
>>> # simple patch/matrix
>>> from landscape import *
>>> parn = OrderedDict([
('r', [-0.03, 0.1]),
('K', [np.Inf, 1.0]),
('D', [0.001, 0.0001]),
('left', [1.0, 0.0, 0.0]),
('right', [1.0, 0.0, 0.0]),
('top', [1.0, 0.0, 0.0]),
('bottom', [1.0, 0.0, 0.0])
])
>>> l = np.zeros((100,100), dtype=int)
>>> l[40:60, 40:60] = 1
>>> sol = solve_landscape_ntypes(l, parn, dx)
"""
from scipy.optimize import newton_krylov
if not skip_refine:
# refine the grid to avoid contiguous interfaces
landscape = refine_grid(landscape)
dx /= 2
n = np.unique(landscape).astype(int)
p = par.copy()
if 'g' not in p.keys():
p['g'] = {}
if 'alpha' not in p.keys():
p['alpha'] = {}
for i, j in iproduct(n, repeat=2):
if i > j:
p['alpha'][(i,j)] = 0.5
for i, j in iproduct(n, repeat=2):
if i > j:
p['g'][(i,j)] = p['D'][j]/p['D'][i] * \
p['alpha'][(i,j)] / (1-p['alpha'][(i,j)])
# this ensures the consistency of the interface discontinuities
# it ignores the values of g_ij with i < j, replacing it by 1/g_ji
for i, j in iproduct(n, repeat=2):
if i < j:
p['g'][(i,j)] = 1/p['g'][(j,i)]
(al, bl, cl) = p['left']
(ar, br, cr) = p['right']
(at, bt, ct) = p['top']
(ab, bb, cb) = p['bottom']
D = np.zeros_like(landscape, dtype=np.float_)
r = np.zeros_like(landscape, dtype=np.float_)
c = np.zeros_like(landscape, dtype=np.float_)
for i in n:
li = np.where(landscape == i)
D[li] = p['D'][i]
r[li] = p['r'][i]
c[li] = - p['r'][i] / p['K'][i]
Bx, By = find_interfaces_ntypes(landscape)
factor = {}
for i, j in iproduct(n, repeat=2):
if i != j:
factor[(i,j)] = (
# coefficient of term u(x) in u_xx(x)
-2. + 8./3 * p['D'][i]/(p['D'][i]+p['D'][j]/p['g'][(i,j)]),
# coefficient of term u(x+h) in u_xx(x)
-1. + 8./3 * p['D'][j]/(p['D'][i]+p['D'][j]/p['g'][(i,j)])
)
Bxleft = np.zeros_like(landscape, dtype=np.float_)
Bxcenter = np.zeros_like(landscape, dtype=np.float_)
Bxright = np.zeros_like(landscape, dtype=np.float_)
Byleft = np.zeros_like(landscape, dtype=np.float_)
Bycenter = np.zeros_like(landscape, dtype=np.float_)
Byright = np.zeros_like(landscape, dtype=np.float_)
for i,j in factor.keys():
## direction x
# patch type i
Bxcenter[Bx[i,j]] += factor[i,j][0]
Bxleft[shifted_index(Bx[i,j], 0, -1)] += 1./3
Bxright[shifted_index(Bx[i,j], 0, 1)] += factor[i,j][1]
# patch type j
Bxcenter[shifted_index(Bx[i,j], 0, 1)] += factor[j,i][0]
Bxleft[Bx[i,j]] += factor[j,i][1]
Bxright[shifted_index(Bx[i,j], 0, 2)] += 1./3
## direction y
# patch type i
Bycenter[By[i,j]] += factor[i,j][0]
Byleft[shifted_index(By[i,j], 1, -1)] += 1./3
Byright[shifted_index(By[i,j], 1, 1)] += factor[i,j][1]
# patch type j
Bycenter[shifted_index(By[i,j], 1, 1)] += factor[j,i][0]
Byleft[By[i,j]] += factor[j,i][1]
Byright[shifted_index(By[i,j], 1, 2)] += 1./3
def residual(P):
if force_positive:
P = np.abs(P)
d2x = np.zeros_like(P)
d2x[1:-1,:] = P[2:,:] - 2*P[1:-1,:] + P[:-2,:]
# external boundaries
d2x[0,:] = P[1,:] - 2*P[0,:] + (-cl - al/dx * P[0,:])/(bl - al/dx)
d2x[-1,:] = P[-2,:] - 2*P[-1,:] + (-cr + ar/dx * P[-1,:])/(br + ar/dx)
# interface conditions
d2x[1:-1,:] += (
Bxcenter[1:-1,:] * P[1:-1,:] +
Bxleft[:-2,:] * P[:-2,:] +
Bxright[2:,:] * P[2:,:]
)
d2y = np.zeros_like(P)
d2y[:,1:-1] = P[:,2:] - 2*P[:,1:-1] + P[:,:-2]
# external boundaries
d2y[:,0] = P[:,1] - 2*P[:,0] + (-cb - ab/dx * P[:,0])/(bb - ab/dx)
d2y[:,-1] = P[:,-2] - 2*P[:,-1] + (-ct + at/dx * P[:,-1])/(bt + at/dx)
# interface conditions
d2y[:,1:-1] += (
Bycenter[:,1:-1] * P[:,1:-1] +
Byleft[:,:-2] * P[:,:-2] +
Byright[:,2:] * P[:,2:]
)
return D*(d2x + d2y)/dx/dx + r*P + c*P**2
if return_residual:
return residual
# solve
guess = r.copy()
guess[guess>0] = 1/((-c/r)[guess>0])
guess[guess<=0] = 1e-6
sol = newton_krylov(residual, guess, method='lgmres', f_tol=f_tol)
if force_positive:
sol = np.abs(sol)
if verbose:
print('Residual: %e' % abs(residual(sol)).max())
print('max. pop.: %f' % sol.max())
print('min. pop.: %f' % sol.min())
if not skip_refine:
sol = coarse_grid(sol)
return sol
def solve_landscape_ntypes_nspecies(landscape, par, dx, f_tol=None,
force_positive=False, skip_refine=False, return_residual=False,
verbose=True):
'''Find the stationary solution for a given landscape and set of parameters.
Uses a Newton-Krylov solver with LGMRES sparse inverse method to find a
stationary solution (or the solution to the elliptical problem) to the
system of 2n equations in 2 dimensions (x is a 2-d vector):
.. math::
\\frac{\partial u_{ik}}{\partial t} &= D_k \\nabla^2 u_{ik} + r_{ik} u_{ik} (1-\sum_{j=1}^n \\alpha_j u_{jk}) = 0
where i runs over the n species and k over the patch types.
Parameters
----------
landscape : 2-d array of ints
describe the landscape, with any number of habitat types
par : list
the first element is the matrix (or dict with tuple keys) of
competition coefficients, including the inverse of carrying capacities,
and the following elements are dicts with parameters as in the
`solve_landscape_ntypes()` function, except for the carrying capacity.
dx : float
length of each edge
f_tol : float
tolerance for the residue, passed on to the solver routine. Default is
6e-6
force_positive : bool
make sure the solution is always non-negative - in a hacky way. Default
False
skip_refine : bool
do not refine the grid to calculate the residual. This can greatly
improve speed, but will generate errors (even silent wrong results) if
the landscape has contiguous interfaces
return_residual : bool
returns only the residual function, without calculating the solution
verbose : bool
print residue of the solution and its maximum and minimum values
Returns
-------
solution : 2-d array of the same shape of the landscape input containing
the solution
Boundary and interface conditions
---------------------------------
External boundaries are of the form
.. math::
a \\nabla u \cdot \hat{n} + b u + c = 0
and may be different for left, right, top, bottom. The derivative of u is
taken along the normal to the boundary.
The interfaces between patches and matrix are given by
.. math::
u(x) &= \gamma v(x) \\\\
D_p \\nabla u(x) \cdot \hat{n} &= D_m \\nabla v(x) \cdot \hat{n}
where u is a patch and v is the solution in the matrix.
Example
-------
>>> from landscape import *
>>> lA = loadtxt('landA.txt')
>>> par = [
[
[[0, 0],
[0.1, 0.1]],
[[0.1, 0],
[0.1, 0.1]]
],
{'r': [-0.03, 0.1],
'D': [0.001, 0.0001],
'left': [1.0, 0.0, 0.0],
'right': [1.0, 0.0, 0.0],
'top': [1.0, 0.0, 0.0],
'bottom': [1.0, 0.0, 0.0]},
{'r': [0.05, 0.05],
'D': [0.001, 0.001],
'left': [1.0, 0.0, 0.0],
'right': [1.0, 0.0, 0.0],
'top': [1.0, 0.0, 0.0],
'bottom': [1.0, 0.0, 0.0]}
]
>>> sol = solve_landscape_ntypes_nspecies(lA, par, dx)
'''
from scipy.optimize import newton_krylov
if not skip_refine:
# refine the grid to avoid contiguous interfaces
landscape = refine_grid(landscape)
dx /= 2
N = len(par) - 1
n = np.unique(landscape).astype(int)
resi = [ solve_landscape_ntypes(landscape, dict(p,
K=np.Inf*np.ones(len(n))), dx, skip_refine=True, return_residual=True)
for p in par[1:] ]
sec_term = np.zeros((N, N, landscape.shape[0], landscape.shape[1]))
for i,j in iproduct(range(N), range(N)):
for k in n:
lk = np.where(landscape == k)
sec_term[i,j][lk] = par[0][k][i][j]
def residual(P):
if force_positive:
P = np.abs(P)
res = np.zeros_like(P)
# loops are for lazy people
for i, Pi in enumerate(P):
res[i,:,:] = resi[i](Pi) - Pi * (sec_term[i,:,:] * P).sum(axis=0)
return res
if return_residual:
return residual
# build guess based on where growth is positive
guess = np.zeros((N, landscape.shape[0], landscape.shape[1]))
for i in range(N):
for k in n:
lk = np.where(landscape == k)
rik = par[i+1]['r'][k]
if rik <= 0:
guess[i,:,:][lk] = 1e-6
else:
guess[i,:,:][lk] = rik / par[0][k][i][i]
# solve
sol = newton_krylov(residual, guess, method='lgmres', f_tol=f_tol)
if force_positive:
sol = np.abs(sol)
if verbose:
print('Residuals:', *[ '%e' % i for i in
np.abs(residual(sol)).max(axis=(1,2)) ])
print('max. pops.:', *[ '%f' % i for i in sol.max(axis=(1,2)) ])
print('min. pops.:', *[ '%f' % i for i in sol.min(axis=(1,2)) ])
if not skip_refine:
sol = coarse_grid(sol)
return sol
def solve_landscape_nspecies(landscape, par, dx, f_tol=None,
force_positive=False, skip_refine=False, verbose=True):
'''Find the stationary solution for a given landscape and set of parameters.
Uses a Newton-Krylov solver with LGMRES sparse inverse method to find a
stationary solution (or the solution to the elliptical problem) to the
system of 2n equations in 2 dimensions (x is a 2-d vector):
.. math::
\\frac{\partial u_i}{\partial t} &= D_p \\nabla^2 u_i + r_i u_i (1-\sum_{j=1}^n \\alpha_j u_j) = 0 \\text{ in a patch} \\\\
\\frac{\partial v_i}{\partial t} &= D_m \\nabla^2 v_i - \mu_i v_i = 0 \\text{ in the matrix}
Notes
-----
This function preserves the original interface, but internally it calls the
newer `solve_landscape_ntypes_nspecies()`.
Parameters
----------
landscape : a 2-d array (of ints) describing the landscape, with 1 on
patches and 0 on matrix
par : a ordered dict containing parameters in the following order:
r: list of reproductive rates on patches
alpha: matrix of interaction parameters on patches (diagonals are minus the inverse of carrying capacity)
mu: list of mortality rates in the matrix
Dp: list of diffusivities on patches
Dm: list of diffusivities in the matrix
g: habitat preference parameter \gamma, usually less than one. See interface conditions below
left: (a, b, c): external boundary conditions at left border
right: (a, b, c): external boundary conditions at right border
top: (a, b, c): external boundary conditions at top border
bottom: (a, b, c): external boundary conditions at bottom border
dx : float
length of each edge
f_tol : float
tolerance for the residue, passed on to the solver routine. Default is
6e-6
force_positive : bool
make sure the solution is always non-negative - in a hacky way. Default
False
skip_refine : bool
do not refine the grid to calculate the residual. This can greatly
improve speed, but will generate errors (even silent wrong results) if
the landscape has contiguous interfaces
verbose : bool
print residue of the solution and its maximum and minimum values
Returns
-------
solution : 2-d array of the same shape of the landscape input containing
the solution
Boundary and interface conditions
---------------------------------
External boundaries are of the form
.. math::
a \\nabla u \cdot \hat{n} + b u + c = 0
and may be different for left, right, top, bottom. The derivative of u is
taken along the normal to the boundary.
The interfaces between patches and matrix are given by
.. math::
u(x) &= \gamma v(x) \\\\
D_p \\nabla u(x) \cdot \hat{n} &= D_m \\nabla v(x) \cdot \hat{n}
where u is a patch and v is the solution in the matrix. These conditions
are handled using an assymetric finite difference scheme for the 2nd
derivative:
.. math::
u_xx(x) = (4/3/h**2) (u(x-h) - 3 u(x) + 2 u(x+h/2))
with the approximations at the interface:
.. math::
u(x+h/2) = (Dm*v(x+h)+Dp*u(x))/(Dp+Dm*g)
if u(x) is in a patch and v(x+h) is in the matrix, or
.. math::
v(x+h/2) = g*(Dm*v(x)+Dp*u(x+h))/(Dp+Dm*g)
if v(x) is in the matrix and u(x+h) is in a patch.
Example
-------
>>> from landscape import *
>>> parn = OrderedDict([
('rp', [0.1, 0.05]),
('rm', [-0.03, 0.05]),
('alphap', [[0.1, 0], [0.1, 0.1]]),
('alpham', [[0., 0.], [0.1, 0.1]]),
('Dp', [1e-4, 1e-3]),
('Dm', [1e-3, 1e-3]),
# interface condition can be omitted!
#('g', [.1, 1.]),
# boundary conditions
('left', [1., 0., 0.]),
('right', [1., 0., 0.]),
('top', [1., 0., 0.]),
('bottom', [1., 0., 0.])
])
>>> lA = loadtxt('landA.txt')
>>> sol = solve_landscape_nspecies(lA, parn, dx)
'''
p0 = [ par['alpham'], par['alphap'] ]
p1 = dict(
r = [par['rm'][0], par['rp'][0]],
D = [par['Dm'][0], par['Dp'][0]],
**{ k: par[k] for k in ['left', 'right', 'top', 'bottom'] }
)
p2 = dict(
r = [par['rm'][1], par['rp'][1]],
D = [par['Dm'][1], par['Dp'][1]],
**{ k: par[k] for k in ['left', 'right', 'top', 'bottom'] }
)
newpar = [p0, p1, p2]
return solve_landscape_ntypes_nspecies(landscape, newpar, dx, f_tol=f_tol,
skip_refine=skip_refine, verbose=verbose)
def find_interfaces(landscape):
'''Helper function that marks where are the internal boundaries.'''
B = 2*landscape - 1
Bx = B[:-1,:]*(- B[1:,:] * B[:-1,:] + 1)//2
Bxpm = (Bx + 1)//2
Bxmp = (-Bx + 1)//2
By = B[:,:-1]*(- B[:,1:] * B[:,:-1] + 1)//2
Bypm = (By + 1)//2
Bymp = (-By + 1)//2
return Bxpm, Bxmp, Bypm, Bymp
def find_interfaces_ntypes(landscape):
'''Determines internal boundaries for landscapes with many habitat types.
Parameters
----------
landscape : 2-d array
Returns
-------
Bx, By : tuple of two dicts
each key is a tuple (i,j) corresponding to the numbers of the habitat
types, and the value corresponds to the indices where a boundary
between them appears, along either the x or y direction
'''
n = np.unique(landscape).astype(int)
A = 2**(landscape.astype(int))
Ax = A[1:,:] - A[:-1,:]
Ay = A[:,1:] - A[:,:-1]
Bx = {}
By = {}
for i, j in iproduct(n, repeat=2):
if i != j:
Bx[(i,j)] = np.where(Ax == 2**j - 2**i)
By[(i,j)] = np.where(Ay == 2**j - 2**i)
return Bx, By
def shifted_index(x, index, shift):
"""Shifts the indices of elements from an array.
Helper function to deal with indices returned by `np.where()`.
Parameters
----------
x : tuple of arrays
index : integer
Position of the shifted array in th tuple
shift : integer
Value by which to shift the array
Returns
-------
out : tuple of shifted arrays (same shape as input)
Notes
-----
This function doesn't affect the original arrays, it makes a copy, modifies
and then returns it. For that reason, it's not very efficient.
"""
import copy
newx = copy.deepcopy(list(x))
newx[index] += shift
return tuple(newx)
def solve_multiple_parameters(variables, values, landscape, par, dx,
f_tol=None, force_positive=False, verbose=True, multiprocess=True):
'''Solve given landscape for several combinations of parameters.
Solves a given landscape with a set of common parameters and for a range of
values for some variables, optionally using multiprocessing to speed it up.
Parameters
----------
variables : list of strings
names of the varied parameters
values : list of lists (or tuples)
each item contains a list of values corresponding to the parameters
given in the `variables` list
landscape : 2-d array
zeroes and ones describing the landscape
par : ordered dict
common values for all the problem parameters. See documentation for
`solve_landscape()`
dx: float
length of each edge
f_tol : float
tolerance for the residue, passed on to the solver routine. Default is
6e-6
verbose : bool
print residue of the solution and its maximum and minimum values.
Notice that the order of appearance of each output is not the same as
the input if multiprocess is True.
multiprocess : bool
determines whether to use multiprocessing to use multiple cores. True
by default, in which case the total number of CPUs minus one are used
Returns
-------
solutions: list of 2-d arrays
solutions of each set of parameters, in the same ordering of the input
values
Example
-------
>>> from landscape import *
>>> lA = image_to_landscape('landA.tif')
>>> D = np.arange(0.01, 0.05, 0.01)
>>> r = np.arange(0.1, 0.5, 0.1)
>>> values = [ (x, y, y) for x, y in iproduct(r, D) ]
>>> sols = solve_multiple_parameters(['r', 'Dp', 'Dm'], values, lA, par, dx)
'''
from functools import partial
# this is not compatible with python 2.6 when using multiprocessing, due to
# bug http://bugs.python.org/issue5228
solve_landscape_wrapper = partial(solve_landscape, landscape, dx=dx,
f_tol=f_tol, verbose=verbose)
works = [ OrderedDict(par, **dict(zip(variables, p))) for p in values ]
if multiprocess:
from multiprocessing import Pool, cpu_count
cpus = cpu_count()
pool = Pool(cpus if cpus == 1 else cpus - 1)
solutions = pool.map(solve_landscape_wrapper, works)
pool.close()
pool.join()
else:
solutions = map(solve_landscape_wrapper, works)
return solutions
def solve_multiple_landscapes(landscapes, par, dx, f_tol=None, verbose=True,
force_positive=True, multiprocess=True):
'''Solve several landscapes.
Solves a set of landscape with a given set of parameters, optionally using
multiprocessing to speed things up.
Parameters
----------
landscape : list of 2-d arrays
zeroes and ones describing the landscape
par : ordered dict
values for all the problem parameters. See documentation for
`solve_landscape()`
dx : float
lenght of each edge
f_tol : float
tolerance for the residue, passed on to the solver routine. Default is
6e-6
verbose : bool
print residue of the solution and its maximum and minimum values.
Notice that the order of appearance of each output is not the same as
the input if multiprocess is True.
multiprocess : bool
whether to use multiprocessing to use multiple cores. True by default,
in which case the total number of CPUs minus one are used
Returns
-------
solutions : list os 2-d arrays
solutions to each landscape, in the same ordering of the input values
Example
-------
>>> from landscape import *
>>> l = [ random_landscape(i*100, 0.8, 100) for i in range(30,70,10) ]
>>> sols = solve_multiple_landscapes(l, par, dx)
'''
from functools import partial
# this is not compatible with python 2.6 when using multiprocessing, due to
# bug http://bugs.python.org/issue5228
solve_landscape_wrapper = partial(solve_landscape, par=par, dx=dx,
f_tol=f_tol, force_positive=force_positive, verbose=verbose)
if multiprocess:
from multiprocessing import Pool, cpu_count
cpus = cpu_count()
pool = Pool(cpus if cpus == 1 else cpus - 1)
solutions = pool.map(solve_landscape_wrapper, landscapes)
pool.close()
pool.join()
else:
solutions = map(solve_landscape_wrapper, landscapes)
return solutions
def refine_grid(landscape, n=2):
'''Increase the resolution of a landscape grid by a factor of n.'''
return np.repeat(np.repeat(landscape, n, axis=1), n, axis=0)
def coarse_grid(landscape):
'''Decrease resolution of a grid by a factor of 2.
Each square of 2 by 2 pixels over the last two axes is replaced by a single
pixel with its average value.
'''
a = (landscape[...,::2,:] + landscape[...,1::2,:]) / 2
return (a[...,:,::2] + a[...,:,1::2]) / 2
def image_to_landscape(image, n=2):
'''Converts an image to a 2d array of integers from 0 to n-1.
Most image formats (including TIFF) requires PIL.
Parameters
----------
image : string
image filename
Returns
-------
landscape : 2-d array
all values are integers from 0 to n-1, where zeroes correspond to
lighter shades in the original image, and darker shades to higher
values, so that each value corresponds to a distinct type of habitat
'''
from matplotlib.image import imread
from scipy.ndimage.measurements import histogram
M = imread(image).sum(axis=2)[::-1,:]
L = np.zeros_like(M)
nbins = max(20, n*4)
freq = histogram(M, M.min(), M.max(), nbins)
bins = np.linspace(M.min(), M.max(), nbins)
peaks = sorted(freq.argsort()[-n:])
delims = [bins[0]] + [ bins[(peaks[i+1] + peaks[i])//2] for i in range(n-1) ] + [bins[-1]+1]
for i in range(n):
L[ (M > delims[i]) & (M < delims[i+1]) ] = i
#M = np.around(M/M.max())
#return 1 - M.astype(np.int16)
return L
def swap_values(landscape, swaps):
'''Substitute values of a landscape
Parameters
----------
landscape : 2-d array
swaps: list of tuples
each item if of the form (original_value, new_value)
Returns
-------
landscape : 2-d array
Example
-------
>>> # rotation of 3 values
>>> newl = swap_values(l, [(0,1), (1,2), (2,0)])
'''
newl = landscape.copy()
for i,j in swaps:
newl[ landscape == i ] = j
return newl
def random_landscape(cover, frag, size, radius=1, norm='taxicab'):
'''Generates random square landscapes with a given cover and fragmentation.
Parameters
----------
cover : integer smaller than size**2, total number of patch elements
frag : float between 0 and 1 (both exclusive), gives the level of
fragmentation, with 0 being a single clump and 1 a totally random
(scattered) landscape
size : integer, lenght of the landscape (total area is size squared)
radius : integer, maximum distance at which an element is considered to be
a neighbour of another
norm : one of 'maximum' or 'taxicab', defines the norm used for measuring
distances between elements of the landscape
Returns
-------
landscape : a square 2-d array of zeroes and ones
References
----------
Lenore Fahrig, Relative Effects of Habitat Loss and Fragmentation on
Population Extinction, The Journal of Wildlife Management, Vol. 61, No. 3
(Jul., 1997), pp. 603-610
'''
from numpy.random import rand, randint
if cover > size**2:
raise ValueError('Cover (=%i) must be smaller than total area (=%i).' %
(cover, size**2))
M = np.zeros((size+2*radius, size+2*radius), dtype=int)
n = 0
if norm.lower() == 'maximum':
while n < cover:
i, j = randint(radius, size+radius, 2)
if M[i, j]:
continue
if radius == 0 or any(M[i-radius:i+radius+1, j-radius:j+radius+1]):
M[i, j] = 1
n += 1
elif rand() < frag:
M[i, j] = 1