From 0c37b6fc717a9978760704bd1ae58382eca155bd Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 4 Apr 2019 15:38:09 -0600 Subject: [PATCH 001/167] (issue #256) moved RandSeed() calls to right before runGrid() This ensures that the RNGs are seeded regardless of gridded or non-gridded mode. --- ST_main.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/ST_main.c b/ST_main.c index 2758636b..77988d4b 100644 --- a/ST_main.c +++ b/ST_main.c @@ -163,6 +163,13 @@ int main(int argc, char **argv) { printf("STEPWAT init_args() executed successfully \n"); + RandSeed(Globals.randseed, &environs_rng); + RandSeed(Globals.randseed, &mortality_rng); + RandSeed(Globals.randseed, &resgroups_rng); + RandSeed(Globals.randseed, &species_rng); + RandSeed(Globals.randseed, &grid_rng); + RandSeed(Globals.randseed, &markov_rng); + if (UseGrid == TRUE) { runGrid(); return 0; @@ -200,12 +207,6 @@ int main(int argc, char **argv) { parm_Initialize(iter); Plot_Initialize(); - RandSeed(Globals.randseed, &environs_rng); - RandSeed(Globals.randseed, &mortality_rng); - RandSeed(Globals.randseed, &resgroups_rng); - RandSeed(Globals.randseed, &species_rng); - RandSeed(Globals.randseed, &grid_rng); - RandSeed(Globals.randseed, &markov_rng); Globals.currIter = iter; From 7d89416eeb2a097909c1bf62b2ca7c315d98831f Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 4 Apr 2019 15:42:07 -0600 Subject: [PATCH 002/167] (issue #251) removed unneeded call to free_all_sxw_memory See the issue for more details --- ST_grid.c | 1 - 1 file changed, 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index 732d6b5c..edf3d8af 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2341,7 +2341,6 @@ static void _init_soil_layers(int cell, int isSpinup) init_site_info(); //in SW_Site.c, called to initialize layer data... - free_all_sxw_memory(); _init_SXW_inputs(FALSE, grid_Soils[i].rootsFile); //we call this so that SXW can set the correct sizes/values up for the memory dynamically allocated in sxw.c if (!isSpinup) From 9f215fbc34d5ce6415d0f55d2f2b8c7aaac045d3 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Sat, 6 Apr 2019 18:55:26 -0400 Subject: [PATCH 003/167] (Issue #254) Remove xgrow and veg_prod_type --- .../Grid_Inputs/grid_disturbances.csv | 290 +++++++++--------- 1 file changed, 145 insertions(+), 145 deletions(-) diff --git a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv index 88f584aa..dd4364a2 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv @@ -1,145 +1,145 @@ -cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfrq,extirp,killfreq_startyr,xgrow,veg_prod_type,grazing_frq,grazingfrq_startyr -0,0,0,0,3,0,0,0,0,2,3,4 -1,0,0,0,3,0,0,0,0,4,3,4 -2,0,0,0,3,0,0,0,0,4,3,4 -3,0,0,0,3,0,0,0,0,4,3,4 -4,0,0,0,3,0,0,0,0,4,3,4 -5,0,0,0,3,0,0,0,0,3,3,4 -6,0,0,0,3,0,0,0,0,3,3,4 -7,0,0,0,3,0,0,0,0,3,3,4 -8,0,0,0,3,0,0,0,0,2,3,4 -9,0,0,0,3,0,0,0,0,2,3,4 -10,0,0,0,3,0,0,0,0,2,3,4 -11,0,0,0,3,0,0,0,0,2,3,4 -12,0,0,0,3,0,0,0,0,2,3,4 -13,0,0,0,3,0,0,0,0,2,3,4 -14,0,0,0,3,0,0,0,0,2,3,4 -15,0,0,0,3,0,0,0,0,2,3,4 -16,0,0,0,3,0,0,0,0,2,3,4 -17,0,0,0,0,0,0,0,0,2,0,0 -18,0,0,0,0,0,0,0,0,2,0,0 -19,0,0,0,0,0,0,0,0,2,0,0 -20,0,0,0,0,0,0,0,0,2,0,0 -21,0,0,0,0,0,0,0,0,2,0,0 -22,0,0,0,0,0,0,0,0,2,0,0 -23,0,0,0,0,0,0,0,0,2,0,0 -24,0,0,0,0,0,0,0,0,2,0,0 -25,0,0,0,0,0,0,0,0,2,0,0 -26,0,0,0,0,0,0,0,0,2,0,0 -27,0,0,0,0,0,0,0,0,2,0,0 -28,0,0,0,0,0,0,0,0,2,0,0 -29,0,0,0,0,0,0,0,0,2,0,0 -30,0,0,0,0,0,0,0,0,2,0,0 -31,0,0,0,0,0,0,0,0,2,0,0 -32,0,0,0,0,0,0,0,0,2,0,0 -33,0,0,0,0,0,0,0,0,2,0,0 -34,0,0,0,0,0,0,0,0,2,0,0 -35,0,0,0,0,0,0,0,0,2,0,0 -36,0,0,0,0,0,0,0,0,2,0,0 -37,0,0,0,0,0,0,0,0,2,0,0 -38,0,0,0,0,0,0,0,0,2,0,0 -39,0,0,0,0,0,0,0,0,2,0,0 -40,0,0,0,0,0,0,0,0,2,0,0 -41,0,0,0,0,0,0,0,0,2,0,0 -42,0,0,0,0,0,0,0,0,2,0,0 -43,0,0,0,0,0,0,0,0,2,0,0 -44,0,0,0,0,0,0,0,0,2,0,0 -45,0,0,0,0,0,0,0,0,2,0,0 -46,0,0,0,0,0,0,0,0,2,0,0 -47,0,0,0,0,0,0,0,0,2,0,0 -48,0,0,0,0,0,0,0,0,2,0,0 -49,0,0,0,0,0,0,0,0,2,0,0 -50,0,0,0,0,0,0,0,0,2,0,0 -51,0,0,0,0,0,0,0,0,2,0,0 -52,0,0,0,0,0,0,0,0,2,0,0 -53,0,0,0,0,0,0,0,0,2,0,0 -54,0,0,0,0,0,0,0,0,2,0,0 -55,0,0,0,0,0,0,0,0,2,0,0 -56,0,0,0,0,0,0,0,0,2,0,0 -57,0,0,0,0,0,0,0,0,2,0,0 -58,0,0,0,0,0,0,0,0,2,0,0 -59,0,0,0,0,0,0,0,0,2,0,0 -60,0,0,0,0,0,0,0,0,2,0,0 -61,0,0,0,0,0,0,0,0,2,0,0 -62,0,0,0,0,0,0,0,0,2,0,0 -63,0,0,0,0,0,0,0,0,2,0,0 -64,0,0,0,0,0,0,0,0,2,0,0 -65,0,0,0,0,0,0,0,0,2,0,0 -66,0,0,0,0,0,0,0,0,2,0,0 -67,0,0,0,0,0,0,0,0,2,0,0 -68,0,0,0,0,0,0,0,0,2,0,0 -69,0,0,0,0,0,0,0,0,2,0,0 -70,0,0,0,0,0,0,0,0,2,0,0 -71,0,0,0,0,0,0,0,0,2,0,0 -72,0,0,0,0,0,0,0,0,2,0,0 -73,0,0,0,0,0,0,0,0,2,0,0 -74,0,0,0,0,0,0,0,0,2,0,0 -75,0,0,0,0,0,0,0,0,2,0,0 -76,0,0,0,0,0,0,0,0,2,0,0 -77,0,0,0,0,0,0,0,0,2,0,0 -78,0,0,0,0,0,0,0,0,2,0,0 -79,0,0,0,0,0,0,0,0,2,0,0 -80,0,0,0,0,0,0,0,0,2,0,0 -81,0,0,0,0,0,0,0,0,2,0,0 -82,0,0,0,0,0,0,0,0,2,0,0 -83,0,0,0,0,0,0,0,0,2,0,0 -84,0,0,0,0,0,0,0,0,2,0,0 -85,0,0,0,0,0,0,0,0,2,0,0 -86,0,0,0,0,0,0,0,0,2,0,0 -87,0,0,0,0,0,0,0,0,2,0,0 -88,0,0,0,0,0,0,0,0,2,0,0 -89,0,0,0,0,0,0,0,0,2,0,0 -90,0,0,0,0,0,0,0,0,2,0,0 -91,0,0,0,0,0,0,0,0,2,0,0 -92,0,0,0,0,0,0,0,0,2,0,0 -93,0,0,0,0,0,0,0,0,2,0,0 -94,0,0,0,0,0,0,0,0,2,0,0 -95,0,0,0,0,0,0,0,0,2,0,0 -96,0,0,0,0,0,0,0,0,2,0,0 -97,0,0,0,0,0,0,0,0,2,0,0 -98,0,0,0,0,0,0,0,0,2,0,0 -99,0,0,0,0,0,0,0,0,2,0,0 -100,0,0,0,0,0,0,0,0,2,0,0 -101,0,0,0,0,0,0,0,0,2,0,0 -102,0,0,0,0,0,0,0,0,2,0,0 -103,0,0,0,0,0,0,0,0,2,0,0 -104,0,0,0,0,0,0,0,0,2,0,0 -105,0,0,0,0,0,0,0,0,2,0,0 -106,0,0,0,0,0,0,0,0,2,0,0 -107,0,0,0,0,0,0,0,0,2,0,0 -108,0,0,0,0,0,0,0,0,2,0,0 -109,0,0,0,0,0,0,0,0,2,0,0 -110,0,0,0,0,0,0,0,0,2,0,0 -111,0,0,0,0,0,0,0,0,2,0,0 -112,0,0,0,0,0,0,0,0,2,0,0 -113,0,0,0,0,0,0,0,0,2,0,0 -114,0,0,0,0,0,0,0,0,2,0,0 -115,0,0,0,0,0,0,0,0,2,0,0 -116,0,0,0,0,0,0,0,0,2,0,0 -117,0,0,0,0,0,0,0,0,2,0,0 -118,0,0,0,0,0,0,0,0,2,0,0 -119,0,0,0,0,0,0,0,0,2,0,0 -120,0,0,0,0,0,0,0,0,2,0,0 -121,0,0,0,0,0,0,0,0,2,0,0 -122,0,0,0,0,0,0,0,0,2,0,0 -123,0,0,0,0,0,0,0,0,2,0,0 -124,0,0,0,0,0,0,0,0,2,0,0 -125,0,0,0,0,0,0,0,0,2,0,0 -126,0,0,0,0,0,0,0,0,2,0,0 -127,0,0,0,0,0,0,0,0,2,0,0 -128,0,0,0,0,0,0,0,0,2,0,0 -129,0,0,0,0,0,0,0,0,2,0,0 -130,0,0,0,0,0,0,0,0,2,0,0 -131,0,0,0,0,0,0,0,0,2,0,0 -132,0,0,0,0,0,0,0,0,2,0,0 -133,0,0,0,0,0,0,0,0,2,0,0 -134,0,0,0,0,0,0,0,0,2,0,0 -135,0,0,0,0,0,0,0,0,2,0,0 -136,0,0,0,0,0,0,0,0,2,0,0 -137,0,0,0,0,0,0,0,0,2,0,0 -138,0,0,0,0,0,0,0,0,2,0,0 -139,0,0,0,0,0,0,0,0,2,0,0 -140,0,0,0,0,0,0,0,0,2,0,0 -141,0,0,0,0,0,0,0,0,2,0,0 -142,0,0,0,0,0,0,0,0,2,0,0 -143,0,0,0,0,0,0,0,0,2,0,0 +cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfrq,extirp,killfreq_startyr,grazing_frq,grazingfrq_startyr +0,0,0,0,3,0,0,0,3,4 +1,0,0,0,3,0,0,0,3,4 +2,0,0,0,3,0,0,0,3,4 +3,0,0,0,3,0,0,0,3,4 +4,0,0,0,3,0,0,0,3,4 +5,0,0,0,3,0,0,0,3,4 +6,0,0,0,3,0,0,0,3,4 +7,0,0,0,3,0,0,0,3,4 +8,0,0,0,3,0,0,0,3,4 +9,0,0,0,3,0,0,0,3,4 +10,0,0,0,3,0,0,0,3,4 +11,0,0,0,3,0,0,0,3,4 +12,0,0,0,3,0,0,0,3,4 +13,0,0,0,3,0,0,0,3,4 +14,0,0,0,3,0,0,0,3,4 +15,0,0,0,3,0,0,0,3,4 +16,0,0,0,3,0,0,0,3,4 +17,0,0,0,0,0,0,0,0,0 +18,0,0,0,0,0,0,0,0,0 +19,0,0,0,0,0,0,0,0,0 +20,0,0,0,0,0,0,0,0,0 +21,0,0,0,0,0,0,0,0,0 +22,0,0,0,0,0,0,0,0,0 +23,0,0,0,0,0,0,0,0,0 +24,0,0,0,0,0,0,0,0,0 +25,0,0,0,0,0,0,0,0,0 +26,0,0,0,0,0,0,0,0,0 +27,0,0,0,0,0,0,0,0,0 +28,0,0,0,0,0,0,0,0,0 +29,0,0,0,0,0,0,0,0,0 +30,0,0,0,0,0,0,0,0,0 +31,0,0,0,0,0,0,0,0,0 +32,0,0,0,0,0,0,0,0,0 +33,0,0,0,0,0,0,0,0,0 +34,0,0,0,0,0,0,0,0,0 +35,0,0,0,0,0,0,0,0,0 +36,0,0,0,0,0,0,0,0,0 +37,0,0,0,0,0,0,0,0,0 +38,0,0,0,0,0,0,0,0,0 +39,0,0,0,0,0,0,0,0,0 +40,0,0,0,0,0,0,0,0,0 +41,0,0,0,0,0,0,0,0,0 +42,0,0,0,0,0,0,0,0,0 +43,0,0,0,0,0,0,0,0,0 +44,0,0,0,0,0,0,0,0,0 +45,0,0,0,0,0,0,0,0,0 +46,0,0,0,0,0,0,0,0,0 +47,0,0,0,0,0,0,0,0,0 +48,0,0,0,0,0,0,0,0,0 +49,0,0,0,0,0,0,0,0,0 +50,0,0,0,0,0,0,0,0,0 +51,0,0,0,0,0,0,0,0,0 +52,0,0,0,0,0,0,0,0,0 +53,0,0,0,0,0,0,0,0,0 +54,0,0,0,0,0,0,0,0,0 +55,0,0,0,0,0,0,0,0,0 +56,0,0,0,0,0,0,0,0,0 +57,0,0,0,0,0,0,0,0,0 +58,0,0,0,0,0,0,0,0,0 +59,0,0,0,0,0,0,0,0,0 +60,0,0,0,0,0,0,0,0,0 +61,0,0,0,0,0,0,0,0,0 +62,0,0,0,0,0,0,0,0,0 +63,0,0,0,0,0,0,0,0,0 +64,0,0,0,0,0,0,0,0,0 +65,0,0,0,0,0,0,0,0,0 +66,0,0,0,0,0,0,0,0,0 +67,0,0,0,0,0,0,0,0,0 +68,0,0,0,0,0,0,0,0,0 +69,0,0,0,0,0,0,0,0,0 +70,0,0,0,0,0,0,0,0,0 +71,0,0,0,0,0,0,0,0,0 +72,0,0,0,0,0,0,0,0,0 +73,0,0,0,0,0,0,0,0,0 +74,0,0,0,0,0,0,0,0,0 +75,0,0,0,0,0,0,0,0,0 +76,0,0,0,0,0,0,0,0,0 +77,0,0,0,0,0,0,0,0,0 +78,0,0,0,0,0,0,0,0,0 +79,0,0,0,0,0,0,0,0,0 +80,0,0,0,0,0,0,0,0,0 +81,0,0,0,0,0,0,0,0,0 +82,0,0,0,0,0,0,0,0,0 +83,0,0,0,0,0,0,0,0,0 +84,0,0,0,0,0,0,0,0,0 +85,0,0,0,0,0,0,0,0,0 +86,0,0,0,0,0,0,0,0,0 +87,0,0,0,0,0,0,0,0,0 +88,0,0,0,0,0,0,0,0,0 +89,0,0,0,0,0,0,0,0,0 +90,0,0,0,0,0,0,0,0,0 +91,0,0,0,0,0,0,0,0,0 +92,0,0,0,0,0,0,0,0,0 +93,0,0,0,0,0,0,0,0,0 +94,0,0,0,0,0,0,0,0,0 +95,0,0,0,0,0,0,0,0,0 +96,0,0,0,0,0,0,0,0,0 +97,0,0,0,0,0,0,0,0,0 +98,0,0,0,0,0,0,0,0,0 +99,0,0,0,0,0,0,0,0,0 +100,0,0,0,0,0,0,0,0,0 +101,0,0,0,0,0,0,0,0,0 +102,0,0,0,0,0,0,0,0,0 +103,0,0,0,0,0,0,0,0,0 +104,0,0,0,0,0,0,0,0,0 +105,0,0,0,0,0,0,0,0,0 +106,0,0,0,0,0,0,0,0,0 +107,0,0,0,0,0,0,0,0,0 +108,0,0,0,0,0,0,0,0,0 +109,0,0,0,0,0,0,0,0,0 +110,0,0,0,0,0,0,0,0,0 +111,0,0,0,0,0,0,0,0,0 +112,0,0,0,0,0,0,0,0,0 +113,0,0,0,0,0,0,0,0,0 +114,0,0,0,0,0,0,0,0,0 +115,0,0,0,0,0,0,0,0,0 +116,0,0,0,0,0,0,0,0,0 +117,0,0,0,0,0,0,0,0,0 +118,0,0,0,0,0,0,0,0,0 +119,0,0,0,0,0,0,0,0,0 +120,0,0,0,0,0,0,0,0,0 +121,0,0,0,0,0,0,0,0,0 +122,0,0,0,0,0,0,0,0,0 +123,0,0,0,0,0,0,0,0,0 +124,0,0,0,0,0,0,0,0,0 +125,0,0,0,0,0,0,0,0,0 +126,0,0,0,0,0,0,0,0,0 +127,0,0,0,0,0,0,0,0,0 +128,0,0,0,0,0,0,0,0,0 +129,0,0,0,0,0,0,0,0,0 +130,0,0,0,0,0,0,0,0,0 +131,0,0,0,0,0,0,0,0,0 +132,0,0,0,0,0,0,0,0,0 +133,0,0,0,0,0,0,0,0,0 +134,0,0,0,0,0,0,0,0,0 +135,0,0,0,0,0,0,0,0,0 +136,0,0,0,0,0,0,0,0,0 +137,0,0,0,0,0,0,0,0,0 +138,0,0,0,0,0,0,0,0,0 +139,0,0,0,0,0,0,0,0,0 +140,0,0,0,0,0,0,0,0,0 +141,0,0,0,0,0,0,0,0,0 +142,0,0,0,0,0,0,0,0,0 +143,0,0,0,0,0,0,0,0,0 From ed2bc2514c4defd17b488f8450fcac2dba0165b2 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sun, 7 Apr 2019 17:27:30 -0600 Subject: [PATCH 004/167] Prototyped CellType struct, created ST_stats.h In ST_grid.c: I added the CellType struct with a few variables that I know need to be plot-specific. This struct is never instantiated in the code, it is only there to discuss and augment. In ST_stats.h: created ST_stats.h and moved all struct definitions from ST_stats.c to the new file. This way, we can instantiate accumulators in other files like ST_grid.c. In ST_stats.c: Moved all struct definitions out of this file. This file now includes ST_stats.h and uses the struct definitions from it. --- ST_grid.c | 21 +++++++++++++++++++++ ST_stats.c | 37 ++++--------------------------------- ST_stats.h | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 33 deletions(-) create mode 100644 ST_stats.h diff --git a/ST_grid.c b/ST_grid.c index edf3d8af..92fcb3aa 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -77,6 +77,7 @@ #include "filefuncs.h" #include "myMemory.h" #include "ST_globals.h" +#include "ST_stats.h" #include "rands.h" #include "sxw_funcs.h" @@ -140,6 +141,26 @@ struct _grid_init_species_st int *species_seed_avail; }typedef Grid_Init_Species_St; +/* Struct to hold all plot-specific parameters */ +struct grid_cell_st +{ + GroupType myGroup; + SpeciesType mySpecies; + SucculentType mySucculent; + EnvType myEnvironment; + PlotType myPlot; + ModelType myGlobals; + Bool useSeedDispersal; + Bool duringSpinup; + + /* ---------------- accumulators -------------------- */ + StatType _Dist, _Ppt, _Temp, + *_Grp, *_Gsize, *_Gpr, *_Gmort, *_Gestab, + *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; + FireStatsType *_Gwf; + /* -------------- end accumulators ------------------ */ +} typedef CellType; + /************ Module Variable Declarations ***************/ /***********************************************************/ diff --git a/ST_stats.c b/ST_stats.c index 0b0537a0..39cc2efd 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -26,6 +26,7 @@ #include "myMemory.h" #include "sw_src/SW_Site.h" #include "ST_structs.h" +#include "ST_stats.h" #include "sxw.h" extern SXW_t SXW; extern SW_SITE SW_Site; @@ -63,48 +64,18 @@ /************************ Local Structure Defs *************/ /***********************************************************/ -struct accumulators_st { - double ave, sum_dif_sqr, sd; - unsigned long nobs; -}; - -struct stat_st { - char *name; /* array of ptrs to names in RGroup & Species */ - struct accumulators_st *s; -} _Dist, _Ppt, _Temp, +StatType _Dist, _Ppt, _Temp, *_Grp, *_Gsize, *_Gpr, *_Gmort, *_Gestab, *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; -typedef struct { - struct accumulators_st *dist, *temp, *ppt, **grp1, **gsize, **gpr2, **gwf2, **gpf2, - **gmort, **gestab, **spp, **indv, **smort, **sestab, **sreceived; -} accumulators_grid_st; - accumulators_grid_st *grid_Stat; -struct fire_st { - int *wildfire; - int **prescribedFire; -} *_Gwf; - - -// Local Structure for holding sum values of all the grid cells - -struct accumulators_grid_cell_st { - double sum, sum_std; - unsigned long nobs; -}; +FireStatsType *_Gwf; -struct stat_grid_cell_st { - char *name; /* array of ptrs to names in RGroup & Species */ - struct accumulators_grid_cell_st *s; /* array of holding all the years values */ -} _Dist_grid_cell, _Ppt_grid_cell, _Temp_grid_cell, +GridStatsType _Dist_grid_cell, _Ppt_grid_cell, _Temp_grid_cell, *_Grp_grid_cell, *_Gsize_grid_cell, *_Gpr_grid_cell,*_Gwf_grid_cell,*_Gpf_grid_cell, *_Gmort_grid_cell, *_Gestab_grid_cell, *_Spp_grid_cell, *_Indv_grid_cell, *_Smort_grid_cell, *_Sestab_grid_cell, *_Sreceived_grid_cell; - - - /*************** Local Function Declarations ***************/ /***********************************************************/ static void _init( void); diff --git a/ST_stats.h b/ST_stats.h new file mode 100644 index 00000000..4e19174a --- /dev/null +++ b/ST_stats.h @@ -0,0 +1,49 @@ +/* Chandler Haukap- This file defines all structs used in ST_stats.c. + * It was created to allow the gridded code to instanciate accumulators + * without including ST_stats.c. + * + * To read the documentation related to creating this struct see issues + * #259 and #266 on GitHub */ + +#ifndef STATS_STRUCT_DEF +#define STATS_STRUCT_DEF + + +/* Basic struct that holds average, sum of differences squared, standard deviation + * and number of entries. This is enough information to calculate running values without + * storing raw data. If you would like to create a new accumulator do not use this + * struct. Instead, use StatType.*/ +struct accumulators_st { + double ave, sum_dif_sqr, sd; + unsigned long nobs; +}; + +/* Accumulator along with the RGroup or Species name. */ +struct stat_st { + char *name; /* array of ptrs to names in RGroup & Species */ + struct accumulators_st *s; +} typedef StatType; + +typedef struct { + struct accumulators_st *dist, *temp, *ppt, **grp1, **gsize, **gpr2, **gwf2, **gpf2, + **gmort, **gestab, **spp, **indv, **smort, **sestab, **sreceived; +} accumulators_grid_st; + +/* Struct for wildfire and prescribed fire stats. */ +struct fire_st { + int *wildfire; + int **prescribedFire; +} typedef FireStatsType; + +// Structure for holding sum values of all the grid cells +struct accumulators_grid_cell_st { + double sum, sum_std; + unsigned long nobs; +}; + +struct stat_grid_cell_st { + char *name; /* array of ptrs to names in RGroup & Species */ + struct accumulators_grid_cell_st *s; /* array of holding all the years values */ +} typedef GridStatsType; + +#endif \ No newline at end of file From 97a6d4c8e54981575bfd8016a8fa604f8cbd1f7c Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 10 Apr 2019 14:11:53 -0600 Subject: [PATCH 005/167] Moved randseed to former location, added randseed calls to ST_grid.c Issue #256. Moving the randseed calls to before RunGrid() was resulting in different behavior with the same seed. To remedy this I have moved calls to randseed back to their former location, and added separate randseed calls in ST_grid.c in the equivalent location right after Plot_Initialize(). --- ST_grid.c | 14 ++++++++++++++ ST_main.c | 14 +++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 92fcb3aa..5d166a85 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -191,6 +191,12 @@ extern SW_SITE SW_Site; extern SW_VEGPROD SW_VegProd; extern SW_WEATHER SW_Weather; extern pcg32_random_t grid_rng; //this file's unique random number generator +extern pcg32_random_t environs_rng; +extern pcg32_random_t mortality_rng; +extern pcg32_random_t resgroups_rng; +extern pcg32_random_t species_rng; +extern pcg32_random_t grid_rng; +extern pcg32_random_t markov_rng; //This is Rgroup structure pointer that will read rgroup disturbance value, will be used in // grid disturbance @@ -455,6 +461,14 @@ void runGrid(void) parm_Initialize(iter); Plot_Initialize(); + + RandSeed(Globals.randseed, &environs_rng); + RandSeed(Globals.randseed, &mortality_rng); + RandSeed(Globals.randseed, &resgroups_rng); + RandSeed(Globals.randseed, &species_rng); + RandSeed(Globals.randseed, &grid_rng); + RandSeed(Globals.randseed, &markov_rng); + if (iter > 1) _free_grid_globals(); //frees the memory from when we called _load_grid_globals() last time... (doesn't need to be called on the first iteration because the memory hasn't been allocated yet) diff --git a/ST_main.c b/ST_main.c index 77988d4b..c0b73d97 100644 --- a/ST_main.c +++ b/ST_main.c @@ -163,13 +163,6 @@ int main(int argc, char **argv) { printf("STEPWAT init_args() executed successfully \n"); - RandSeed(Globals.randseed, &environs_rng); - RandSeed(Globals.randseed, &mortality_rng); - RandSeed(Globals.randseed, &resgroups_rng); - RandSeed(Globals.randseed, &species_rng); - RandSeed(Globals.randseed, &grid_rng); - RandSeed(Globals.randseed, &markov_rng); - if (UseGrid == TRUE) { runGrid(); return 0; @@ -208,6 +201,13 @@ int main(int argc, char **argv) { Plot_Initialize(); + RandSeed(Globals.randseed, &environs_rng); + RandSeed(Globals.randseed, &mortality_rng); + RandSeed(Globals.randseed, &resgroups_rng); + RandSeed(Globals.randseed, &species_rng); + RandSeed(Globals.randseed, &grid_rng); + RandSeed(Globals.randseed, &markov_rng); + Globals.currIter = iter; if (storeAllIterations) { From 9690c04a41b2453265757a634a1f3d63186fc53d Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 11 Apr 2019 10:29:30 -0600 Subject: [PATCH 006/167] Compress sxw.c variables into struct. I added a new struct to sxw.h that contains all of the local variables from sxw.c This way we can instantiate these variables in each grid cell when using gridded mode. I named this struct TempType for now until we agree on a new name. The implementation of this struct in sxw.c is called SXWTemp. I am commiting these changes so that I can move on to other issues, and will change the names once we come up with something descriptive. I also added two local variables to the transp_window struct: added_transp and lastYear. These were free floating variables that need to be cell specific. --- ST_grid.c | 3 +- sxw.c | 158 +++++++++++++++++++------------------------------ sxw.h | 50 ++++++++++++---- sxw_resource.c | 80 ++++++++----------------- sxw_soilwat.c | 40 ++++++------- sxw_sql.c | 16 +++-- 6 files changed, 151 insertions(+), 196 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 5d166a85..97219d25 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -191,11 +191,12 @@ extern SW_SITE SW_Site; extern SW_VEGPROD SW_VegProd; extern SW_WEATHER SW_Weather; extern pcg32_random_t grid_rng; //this file's unique random number generator + +/* We need to seed these RNGs when using the gridded mode but do not use them in this file. */ extern pcg32_random_t environs_rng; extern pcg32_random_t mortality_rng; extern pcg32_random_t resgroups_rng; extern pcg32_random_t species_rng; -extern pcg32_random_t grid_rng; extern pcg32_random_t markov_rng; //This is Rgroup structure pointer that will read rgroup disturbance value, will be used in diff --git a/sxw.c b/sxw.c index 871bb857..075ca126 100644 --- a/sxw.c +++ b/sxw.c @@ -82,56 +82,22 @@ extern SW_MARKOV SW_Markov; extern Bool prepare_IterationSummary; extern Bool storeAllIterations; - - /*************** Module/Local Variable Declarations ***************/ /***********************************************************/ /* these are initialized and maybe populated here but are used * in sxw_resource.c so they aren't declared static. */ -/* ----- 3d arrays ------- */ -RealD * _rootsXphen, /* relative roots X phen in each lyr,grp,pd */ - * _roots_active, /* "active" in terms of size and phenology */ - * _roots_active_rel; - - -/* ----- 2D arrays ------- */ -/* malloc'ed here for consistency but only used */ -/* in sxw_resource.c and sxw_soilwat.c */ - - /* rgroup by layer, ie, group-level values */ -RealD * _roots_max, /* read from root distr. file */ - * _roots_active_sum, /* used in sxw_resource */ - - /* rgroup by period */ - * _phen; /* phenology read from file */ - -/* simple vectors hold the resource information for each group */ -/* curr/equ gives the available/required ratio */ -RealF _resource_cur[MAX_RGROUPS], /* current resource availability for each STEPPE functional type */ - _resource_pr[MAX_RGROUPS]; /* resource convertable to PR */ - // Window of transpiration used by _transp_contribution_by_group() in sxw_resource.c // "Window" refers to the number of years over which transpiration data is averaged. transp_t transp_window; - -// Amount of additional transpiration added for the current year -RealF added_transp; - pcg32_random_t resource_rng; //rng for swx_resource.c functions. +TempType SXWTemp; #ifdef SXW_BYMAXSIZE /* addition to meet changes specified at the top of the file */ RealF _Grp_BMass[MAX_RGROUPS]; #endif -/* and one vector for the production constants */ -RealD _prod_litter[MAX_MONTHS]; -RealD * _prod_bmass; -RealD * _prod_pctlive; - -RealF _bvt; /* ratio of biomass/m2 / transp/m2 */ - /* These are only used here so they are static. */ // static char inbuf[FILENAME_MAX]; /* reusable input buffer */ static char _swOutDefName[FILENAME_MAX]; @@ -411,7 +377,7 @@ This function is no longer utilized, SXW_GetResource has replaced it _resource_pr is no longer used as a parameter. We remain the code for the time being KAP 7/20/2016 */ - RealF pr = ZRO(_resource_pr[rg]) ? 0.0 : 1. / _resource_pr[rg]; + RealF pr = ZRO(SXWTemp._resource_pr[rg]) ? 0.0 : 1. / SXWTemp._resource_pr[rg]; return pr; //return pr > 10 ? 10 : pr; } @@ -421,7 +387,7 @@ RealF SXW_GetTranspiration( GrpIndex rg) { /* see _sxw_update_resource() for _resource_cur[] */ //printf("SXW_GetTranspiration _resource_cur[%d] = %.5f \n", rg, _resource_cur[rg]); - return _resource_cur[rg]; + return SXWTemp._resource_cur[rg]; } void SXW_PrintDebug(Bool cleanup) { @@ -444,16 +410,16 @@ void SXW_PrintDebug(Bool cleanup) { insertInfo(); insertSXWPhen(); insertSXWProd(); - insertRootsXphen(_rootsXphen); + insertRootsXphen(SXWTemp._rootsXphen); } insertInputVars(); insertInputProd(); insertInputSoils(); - insertOutputVars(_resource_cur, added_transp); - insertRgroupInfo(_resource_cur); + insertOutputVars(SXWTemp._resource_cur, transp_window.added_transp); + insertRgroupInfo(SXWTemp._resource_cur); insertOutputProd(&SW_VegProd); - insertRootsSum(_roots_active_sum); - insertRootsRelative(_roots_active_rel); + insertRootsSum(SXWTemp._roots_active_sum); + insertRootsRelative(SXWTemp._roots_active_rel); insertTranspiration(); insertSWCBulk(); } @@ -507,7 +473,7 @@ static void _read_roots_max(void) { cnt++; lyr = 0; while ((p = strtok(NULL, " \t"))) { - _roots_max[Ilg(lyr, g)] = atof(p); + SXWTemp._roots_max[Ilg(lyr, g)] = atof(p); lyr++; } if (lyr != SXW.NTrLyrs) { @@ -552,7 +518,7 @@ static void _read_phen(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - _phen[Igp(g,m)] = atof(p); + SXWTemp._phen[Igp(g,m)] = atof(p); m++; } @@ -590,7 +556,7 @@ static void _read_bvt(void) { CloseFile(&fp); - _bvt = bmass / transp; + SXWTemp._bvt = bmass / transp; } @@ -608,7 +574,7 @@ static void _read_prod(void) { fp = OpenFile(MyFileName, "r"); while (GetALine(fp, inbuf)) { - x = sscanf(inbuf, "%lf", &_prod_litter[mon]); + x = sscanf(inbuf, "%lf", &SXWTemp._prod_litter[mon]); if (x < 1) { LogError(logfp, LOGFATAL, "%s: invalid record for litter %d.", MyFileName, mon + 1); @@ -643,7 +609,7 @@ static void _read_prod(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - _prod_bmass[Igp(g, mon)] = atof(p); + SXWTemp._prod_bmass[Igp(g, mon)] = atof(p); mon++; } cnt++; @@ -678,7 +644,7 @@ static void _read_prod(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - _prod_pctlive[Igp(g, mon)] = atof(p); + SXWTemp._prod_pctlive[Igp(g, mon)] = atof(p); mon++; } cnt++; @@ -750,16 +716,16 @@ static void _make_roots_arrays(void) { char *fstr = "_make_roots_array()"; size = SXW.NGrps * SXW.NTrLyrs; - _roots_max = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._roots_max = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); size = SXW.NGrps * SXW.NPds * SXW.NTrLyrs; - _rootsXphen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - _roots_active = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - _roots_active_rel = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._rootsXphen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._roots_active = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._roots_active_rel = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); //4 - Grass,Frob,Tree,Shrub size = NVEGTYPES * SXW.NPds * SXW.NTrLyrs; - _roots_active_sum = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._roots_active_sum = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } static void _make_phen_arrays(void) { @@ -768,7 +734,7 @@ static void _make_phen_arrays(void) { char *fstr = "_make_phen_arrays()"; size = SXW.NGrps * MAX_MONTHS; - _phen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._phen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } @@ -777,8 +743,8 @@ static void _make_prod_arrays(void) { char *fstr = "_make_phen_arrays()"; size = SXW.NGrps * MAX_MONTHS; - _prod_bmass = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - _prod_pctlive = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._prod_bmass = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWTemp._prod_pctlive = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } static void _make_transp_arrays(void) { @@ -928,7 +894,7 @@ void _print_debuginfo(void) { //ForEachTranspLayer(t) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", _rootsXphen[Iglp(r, t, p)]); + fprintf(f, "\t%.4f", SXWTemp._rootsXphen[Iglp(r, t, p)]); fprintf(f, "\n"); } } @@ -944,18 +910,18 @@ void _print_debuginfo(void) { } fprintf(f, "\n================== %d =============================\n", SW_Model.year); - fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env.ppt, Env.temp, SXW.aet, sum, added_transp, sum + added_transp); + fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env.ppt, Env.temp, SXW.aet, sum, transp_window.added_transp, sum + transp_window.added_transp); fprintf(f, "Group \tRelsize\tPR\tResource_cur\tResource_cur\n"); fprintf(f, "----- \t-------\t-----\t-no scaling-\t-with scaling-\n"); ForEachGroup(r) { sum1 += RGroup[r]->relsize; sum2 += RGroup[r]->pr; - sum3 += _resource_cur[r]; - fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, RGroup[r]->relsize, RGroup[r]->pr, _resource_cur[r]/_bvt, _resource_cur[r]); + sum3 += SXWTemp._resource_cur[r]; + fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, RGroup[r]->relsize, RGroup[r]->pr, SXWTemp._resource_cur[r]/SXWTemp._bvt, SXWTemp._resource_cur[r]); } fprintf(f, "----- \t-------\t-----\t-----\t\t-----\n"); - fprintf(f, "%s\t\t%.4f\t%.4f\t%.4f\t\t%.4f\n", "Total", sum1, sum2, sum3/_bvt, sum3); + fprintf(f, "%s\t\t%.4f\t%.4f\t%.4f\t\t%.4f\n", "Total", sum1, sum2, sum3/SXWTemp._bvt, sum3); fprintf(f, "\n------ Production Values Daily Summed Across Types Monthly Averaged -------\n"); fprintf(f, "Month\tBMass\tPctLive\tLAIlive\tVegCov\tTotAGB\n"); @@ -1020,7 +986,7 @@ void _print_debuginfo(void) { for (l = 0; l < SXW.NTrLyrs; l++) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", _roots_active_sum[Itlp(t, l, p)]); + fprintf(f, "\t%.4f", SXWTemp._roots_active_sum[Itlp(t, l, p)]); fprintf(f, "\n"); } } @@ -1039,7 +1005,7 @@ void _print_debuginfo(void) { //ForEachTranspLayer(t) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", _roots_active_rel[Iglp(r, t, p)]); + fprintf(f, "\t%.4f", SXWTemp._roots_active_rel[Iglp(r, t, p)]); fprintf(f, "\n"); } } @@ -1147,48 +1113,48 @@ void free_all_sxw_memory( void ) { /***********************************************************/ void free_sxw_memory( void ) { - Mem_Free(_roots_max); - Mem_Free(_rootsXphen); - Mem_Free(_roots_active); - Mem_Free(_roots_active_rel); - Mem_Free(_roots_active_sum); - Mem_Free(_phen); - Mem_Free(_prod_bmass); - Mem_Free(_prod_pctlive); + Mem_Free(SXWTemp._roots_max); + Mem_Free(SXWTemp._rootsXphen); + Mem_Free(SXWTemp._roots_active); + Mem_Free(SXWTemp._roots_active_rel); + Mem_Free(SXWTemp._roots_active_sum); + Mem_Free(SXWTemp._phen); + Mem_Free(SXWTemp._prod_bmass); + Mem_Free(SXWTemp._prod_pctlive); } /***********************************************************/ void load_sxw_memory( RealD* grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ) { //load memory from the grid free_sxw_memory(); - _roots_max = Mem_Calloc(SXW.NGrps * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - _rootsXphen = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - _roots_active = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - _roots_active_rel = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - _roots_active_sum = Mem_Calloc(4 * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - _phen = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - _prod_bmass = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - _prod_pctlive = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - - memcpy(_roots_max, grid_roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); - memcpy(_rootsXphen, grid_rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(_roots_active, grid_roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(_roots_active_rel, grid_roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(_roots_active_sum, grid_roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(_phen, grid_phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(_prod_bmass, grid_prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(_prod_pctlive, grid_prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + SXWTemp._roots_max = Mem_Calloc(SXW.NGrps * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWTemp._rootsXphen = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWTemp._roots_active = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWTemp._roots_active_rel = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWTemp._roots_active_sum = Mem_Calloc(4 * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWTemp._phen = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + SXWTemp._prod_bmass = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + SXWTemp._prod_pctlive = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + + memcpy(SXWTemp._roots_max, grid_roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWTemp._rootsXphen, grid_rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWTemp._roots_active, grid_roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWTemp._roots_active_rel, grid_roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWTemp._roots_active_sum, grid_roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWTemp._phen, grid_phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(SXWTemp._prod_bmass, grid_prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(SXWTemp._prod_pctlive, grid_prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); } /***********************************************************/ void save_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ) { //save memory to the grid - memcpy(grid_roots_max, _roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_rootsXphen, _rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active, _roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active_rel, _roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active_sum, _roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_phen, _phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(grid_prod_bmass, _prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(grid_prod_pctlive, _prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_roots_max, SXWTemp._roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_rootsXphen, SXWTemp._rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active, SXWTemp._roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active_rel, SXWTemp._roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active_sum, SXWTemp._roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_phen, SXWTemp._phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_prod_bmass, SXWTemp._prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_prod_pctlive, SXWTemp._prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); } diff --git a/sxw.h b/sxw.h index 8dd4e0be..cb169958 100644 --- a/sxw.h +++ b/sxw.h @@ -24,7 +24,9 @@ // A base of 4.4 C as described in Sims et al. 1978 Journal of Ecology // Additional testing required here and GROWING_BASE_TEMP should eventually be moved to env.in #define GROWING_BASE_TEMP 4.4 // base-temperature in degree Celsius - +#define SXW_NFILES 5 +// The number of transpiration values retained by transp_data +#define MAX_WINDOW 100 #include "generic.h" #include "SW_Times.h" @@ -70,10 +72,7 @@ struct stepwat_st { // ------ DEBUG stuff: char *debugfile; /* added in ST_Main(), read to get debug instructions */ -}; - -// The number of transpiration values retained by transp_data -#define MAX_WINDOW 100 +} typedef SXW_t; // transp_data stores three arrays: ratios, transp, and sum of squares. These arrays form // a moving window that stores "size" years worth of previous transpiration data. @@ -115,16 +114,46 @@ struct transp_data { //SoS_array[] stores the sum of squares values (xi - mean)^2 for the previous (size) iterations. RealF SoS_array[MAX_WINDOW]; //(xi - mean)^2 -}; -typedef struct transp_data transp_t; + // Amount of additional transpiration added for the current year + RealF added_transp; -#define SXW_NFILES 5 + // _transp_contribution_by_group() has different behavior for production years and setup years. + // this variable keeps track of what year last year was, to make sure that the year actually + // incremented. If it did NOT, then this is a setup year. + int lastYear; + +} typedef transp_t; -typedef struct stepwat_st SXW_t; +struct temp_SXW_st{ + /* ----- 3d arrays ------- */ + RealD * _rootsXphen, /* relative roots X phen in each lyr,grp,pd */ + * _roots_active, /* "active" in terms of size and phenology */ + * _roots_active_rel; -#define ForEachTrPeriod(i) for((i)=0; (i)< SXW.NPds; (i)++) + /* ----- 2D arrays ------- */ + /* rgroup by layer, ie, group-level values */ + RealD * _roots_max, /* read from root distr. file */ + * _roots_active_sum, /* used in sxw_resource */ + /* rgroup by period */ + * _phen; /* phenology read from file */ + + /* simple vectors hold the resource information for each group */ + /* curr/equ gives the available/required ratio */ + RealF _resource_cur[MAX_RGROUPS], /* current resource availability for each STEPPE functional type */ + _resource_pr[MAX_RGROUPS]; /* resource convertable to PR */ + + /* one vector for the production constants */ + RealD _prod_litter[MAX_MONTHS]; + RealD * _prod_bmass; + RealD * _prod_pctlive; + + RealF _bvt; /* ratio of biomass/m2 / transp/m2 */ + +} typedef TempType; + +#define ForEachTrPeriod(i) for((i)=0; (i)< SXW.NPds; (i)++) /* convert 3-d index to actual array index for group/layer/phenology 3d table */ @@ -135,7 +164,6 @@ typedef struct stepwat_st SXW_t; */ #define Itlp(t,l,p) (((t)*SXW.NTrLyrs*SXW.NPds) + ((l)*SXW.NPds) + (p)) - // veg type, layer, timeperiod #define Ivlp(v,l,p) (((v)*NVEGTYPES * SXW.NTrLyrs * SXW.NPds) + ((l)*SXW.NTrLyrs * SXW.NPds) + ((p)*SXW.NPds)) diff --git a/sxw_resource.c b/sxw_resource.c index be9719b1..417a8bd2 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -47,34 +47,7 @@ //extern SW_SOILWAT SW_Soilwat; //extern SW_VEGPROD SW_VegProd; - -/*************** Local Variable Declarations ***************/ -/***********************************************************/ -/* malloc'ed and maybe read in sxw.c but used here */ -/* ----- 3d arrays ------- */ -extern - RealD * _rootsXphen, /* relative roots X phen by layer & group */ - * _roots_active, /*relative to the total roots_phen_lyr_group */ - * _roots_active_rel; - - -/* ----- 2D arrays ------- */ - -extern - /* rgroup by layer */ - RealD * _roots_max, /* root distribution with depth for STEPPE functional groups, read from input */ - * _roots_active_sum, /* active roots in each month and soil layer for STEPPE functional groups in the current year */ - - /* rgroup by period */ - * _phen; /* phenological activity for each month for STEPPE functional groups, read from input */ - -extern - RealF _resource_pr[MAX_RGROUPS], /* resource convertable to pr */ - _resource_cur[MAX_RGROUPS]; /* resources currently available by group*/ - RealF added_transp; /* transpiration added for the current year */ - -extern - RealF _bvt; +extern TempType SXWTemp; /* ------ Running Averages ------ */ extern @@ -83,11 +56,6 @@ extern extern pcg32_random_t resource_rng; -// _transp_contribution_by_group() has different behavior for production years and setup years. -// this variable keeps track of what year last year was, to make sure that the year actually -// incremented. If it did NOT, then this is a setup year. -int lastYear; - //void _print_debuginfo(void); /*************** Local Function Declarations ***************/ @@ -110,14 +78,14 @@ void _sxw_root_phen(void) { TimeInt p; for (y = 0; y < (Globals.grpCount * SXW.NPds * SXW.NTrLyrs); y++) - _rootsXphen[y] = 0; + SXWTemp._rootsXphen[y] = 0; ForEachGroup(g) { int nLyrs = getNTranspLayers(RGroup[g]->veg_prod_type); for (y = 0; y < nLyrs; y++) { ForEachTrPeriod(p) { - _rootsXphen[Iglp(g, y, p)] = _roots_max[Ilg(y, g)] * _phen[Igp(g, p)]; + SXWTemp._rootsXphen[Iglp(g, y, p)] = SXWTemp._roots_max[Ilg(y, g)] * SXWTemp._phen[Igp(g, p)]; } } } @@ -163,14 +131,14 @@ void _sxw_update_resource(void) { _sxw_update_root_tables(sizes); /* Assign transpiration (resource availability) to each STEPPE functional group */ - _transp_contribution_by_group(_resource_cur); + _transp_contribution_by_group(SXWTemp._resource_cur); /* Scale transpiration resources by a constant, bvt, to convert resources * (cm) to biomass that can be supported by those resources (g/cm) */ ForEachGroup(g) { //printf("for groupName= %smresource_cur prior to multiplication: %f\n",RGroup[g]->name, _resource_cur[g]); - _resource_cur[g] = _resource_cur[g] * _bvt; + SXWTemp._resource_cur[g] = SXWTemp._resource_cur[g] * SXWTemp._bvt; //printf("for groupName= %s, resource_cur post multiplication: %f\n\n",Rgroup[g]->name, _resource_cur[g]); } /* _print_debuginfo(); */ @@ -189,7 +157,7 @@ void _sxw_update_root_tables( RealF sizes[] ) { int t,nLyrs; /* Set some things to zero where 4 refers to Tree, Shrub, Grass, Forb */ - Mem_Set(_roots_active_sum, 0, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + Mem_Set(SXWTemp._roots_active_sum, 0, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); /* Calculate the active roots in each month and soil layer for each STEPPE * functional group based on the functional group biomass this year */ @@ -200,9 +168,9 @@ void _sxw_update_root_tables( RealF sizes[] ) { for (l = 0; l < nLyrs; l++) { ForEachTrPeriod(p) { - x = _rootsXphen[Iglp(g, l, p)] * sizes[g]; - _roots_active[Iglp(g, l, p)] = x; - _roots_active_sum[Itlp(t, l, p)] += x; + x = SXWTemp._rootsXphen[Iglp(g, l, p)] * sizes[g]; + SXWTemp._roots_active[Iglp(g, l, p)] = x; + SXWTemp._roots_active_sum[Itlp(t, l, p)] += x; } } } @@ -216,11 +184,11 @@ void _sxw_update_root_tables( RealF sizes[] ) { for (l = 0; l < nLyrs; l++) { ForEachTrPeriod(p) { - _roots_active_rel[Iglp(g, l, p)] = - ZRO(_roots_active_sum[Itlp(t,l,p)]) ? + SXWTemp._roots_active_rel[Iglp(g, l, p)] = + ZRO(SXWTemp._roots_active_sum[Itlp(t,l,p)]) ? 0. : - _roots_active[Iglp(g, l, p)] - / _roots_active_sum[Itlp(t,l, p)]; + SXWTemp._roots_active[Iglp(g, l, p)] + / SXWTemp._roots_active_sum[Itlp(t,l, p)]; } } } @@ -244,14 +212,14 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { RealD *transp; RealF sumUsedByGroup = 0., sumTranspTotal = 0., TranspRemaining = 0.; RealF transp_ratio; - added_transp = 0; + transp_window.added_transp = 0; RealF transp_ratio_sd; // year 0 is a set up year. No need to calculate transpiration. // if there are multiple iterations the last year will run twice; // once for data and once for tear down. The second "last year" is // equivalent to year 0. - if(Globals.currYear == 0 || Globals.currYear == lastYear) { + if(Globals.currYear == 0 || Globals.currYear == transp_window.lastYear) { transp_window.average = 0; transp_window.ratio_average = 0; transp_window.sum_of_sqrs = 0; @@ -293,7 +261,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { ForEachTrPeriod(p) { int nLyrs = getNTranspLayers(RGroup[g]->veg_prod_type); for (l = 0; l < nLyrs; l++) { - use_by_group[g] += (RealF) (_roots_active_rel[Iglp(g, l, p)] * transp[Ilp(l, p)]); + use_by_group[g] += (RealF) (SXWTemp._roots_active_rel[Iglp(g, l, p)] * transp[Ilp(l, p)]); } } //printf("for groupName= %s, use_by_group[g] in transp= %f \n",RGroup[g]->name,use_by_group[g] ); @@ -370,25 +338,25 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { RealF max = transp_window.ratio_average + transp_ratio_sd; // This transpiration will be added - added_transp = (1 - transp_ratio / RandUniFloatRange(min, max, &resource_rng)) * transp_window.average; - if(added_transp < 0){ + transp_window.added_transp = (1 - transp_ratio / RandUniFloatRange(min, max, &resource_rng)) * transp_window.average; + if(transp_window.added_transp < 0){ LogError(logfp, LOGNOTE, "sxw_resource: Added transpiration less than 0.\n"); } //printf("Year %d:\tTranspiration to add: %f\n",Globals.currYear,add_transp); //printf("TranspRemaining: %f\tTranspRemaining+add_transp: %f\n",TranspRemaining,add_transp+TranspRemaining); /* -------------------- Recalculate the window including added_transp in the current year -------------------- */ - RealF added_transp_ratio = added_transp / SXW.ppt; + RealF added_transp_ratio = transp_window.added_transp / SXW.ppt; //add added_transp to the average. This is technically part of the current year, so no need to subtract anything. - transp_window.average += added_transp/transp_window.size; + transp_window.average += transp_window.added_transp/transp_window.size; //add added_transp ratio to the ratio average. This is technically part of the current year, so no need to subtract anything. transp_window.ratio_average += (added_transp_ratio)/transp_window.size; //put the new transpiration in the window. Note: oldest_index has not been incremented, so it points to what was just added - transp_window.transp[transp_window.oldest_index] += added_transp; + transp_window.transp[transp_window.oldest_index] += transp_window.added_transp; //put the new ratio in the window. Note: oldest_index has not been incremented, so it points to what was just added transp_window.ratios[transp_window.oldest_index] += added_transp_ratio; // calculate the new sum of squares value - RealF totalTranspRatio = (sumTranspTotal + added_transp)/SXW.ppt; + RealF totalTranspRatio = (sumTranspTotal + transp_window.added_transp)/SXW.ppt; RealF ssqr = (totalTranspRatio - transp_window.ratio_average) * (totalTranspRatio - transp_window.ratio_average); // Subtract the sum of squares calculated above, which was stored in the array. Replace it with what was just calculated. transp_window.sum_of_sqrs += ssqr - transp_window.SoS_array[transp_window.oldest_index]; @@ -400,7 +368,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { /* Adds the additional transpiration to the remaining transpiration * so it can be distributed proportionally to the functional groups. */ - TranspRemaining += added_transp; + TranspRemaining += transp_window.added_transp; } //oldest_index++ accounting for the array bounds @@ -419,5 +387,5 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { } //remember the last year. When setting up for a new iteration the same year will appear twice, and we want to skip it the second time - lastYear = Globals.currYear; + transp_window.lastYear = Globals.currYear; } diff --git a/sxw_soilwat.c b/sxw_soilwat.c index 91d6ba40..a638fae1 100644 --- a/sxw_soilwat.c +++ b/sxw_soilwat.c @@ -60,13 +60,7 @@ extern SW_SITE SW_Site; extern SW_MODEL SW_Model; extern SW_VEGPROD SW_VegProd; - -/*********** Local/Module Variable Declarations ************/ -/***********************************************************/ -extern RealD *_roots_max; -extern RealD _prod_litter[MAX_MONTHS]; -extern RealD * _prod_bmass; -extern RealD * _prod_pctlive; +extern TempType SXWTemp; #ifdef SXW_BYMAXSIZE extern RealF _Grp_BMass[]; /* added 2/28/03 */ @@ -139,7 +133,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 1) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_TREES] += (RealF) _roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_TREES] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_TREES] += y->transp_coeff[SW_TREES]; } @@ -149,7 +143,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 2) { if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_SHRUB] += (RealF) _roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_SHRUB] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; /*printf("* lyr=%d, group=%s(%d), type=%d, tl=%d, rootmax=%f, relsize1=%f, relsize2=%f, trco=%f\n", t, RGroup[g]->name, g, RGroup[g]->veg_prod_type, getNTranspLayers(RGroup[g]->veg_prod_type), @@ -165,7 +159,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 3) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_GRASS] += (RealF) _roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_GRASS] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_GRASS] += y->transp_coeff[SW_GRASS]; } @@ -175,7 +169,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 4) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_FORBS] += (RealF) _roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_FORBS] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_FORBS] += y->transp_coeff[SW_FORBS]; } @@ -262,24 +256,24 @@ static void _update_productivity(void) { ForEachGroup(g) { if (1 == RGroup[g]->veg_prod_type) { //tree - v->veg[SW_TREES].pct_live[m] += _prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_TREES].biomass[m] += _prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_TREES].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_TREES].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; } else if (2 == RGroup[g]->veg_prod_type) { //shrub - v->veg[SW_SHRUB].pct_live[m] += _prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_SHRUB].biomass[m] += _prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_SHRUB].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_SHRUB].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; } else if (3 == RGroup[g]->veg_prod_type) { //grass - v->veg[SW_GRASS].pct_live[m] += _prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_GRASS].biomass[m] += _prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_GRASS].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_GRASS].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; } else if (4 == RGroup[g]->veg_prod_type) { //forb - v->veg[SW_FORBS].pct_live[m] += _prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_FORBS].biomass[m] += _prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_FORBS].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_FORBS].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; } } - v->veg[SW_TREES].litter[m] = (vegTypeBiomass[0] * _prod_litter[m]); - v->veg[SW_SHRUB].litter[m] = (vegTypeBiomass[1] * _prod_litter[m]); - v->veg[SW_GRASS].litter[m] = (vegTypeBiomass[2] * _prod_litter[m]); - v->veg[SW_FORBS].litter[m] = (vegTypeBiomass[3] * _prod_litter[m]); + v->veg[SW_TREES].litter[m] = (vegTypeBiomass[0] * SXWTemp._prod_litter[m]); + v->veg[SW_SHRUB].litter[m] = (vegTypeBiomass[1] * SXWTemp._prod_litter[m]); + v->veg[SW_GRASS].litter[m] = (vegTypeBiomass[2] * SXWTemp._prod_litter[m]); + v->veg[SW_FORBS].litter[m] = (vegTypeBiomass[3] * SXWTemp._prod_litter[m]); } } diff --git a/sxw_sql.c b/sxw_sql.c index eabaf143..913643dd 100644 --- a/sxw_sql.c +++ b/sxw_sql.c @@ -18,11 +18,7 @@ extern SW_MODEL SW_Model; extern SXW_t SXW; extern SW_SITE SW_Site; extern SW_VEGPROD SW_VegProd; -extern RealD *_phen; -extern RealD _prod_litter[MAX_MONTHS]; -extern RealD * _prod_bmass; -extern RealD * _prod_pctlive; -extern RealF _bvt; +extern TempType SXWTemp; static sqlite3 *db; static char sql[1024]; @@ -123,7 +119,7 @@ void insertSXWPhen(void) { { for(m=0;m<12;m++) { sql[0] = 0; - sprintf(sql, "INSERT INTO sxwphen (RGroupID, Month, GrowthPCT) VALUES (%d, %d, %f);", g+1, m+1,_phen[Igp(g,m)]); + sprintf(sql, "INSERT INTO sxwphen (RGroupID, Month, GrowthPCT) VALUES (%d, %d, %f);", g+1, m+1,SXWTemp._phen[Igp(g,m)]); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); } @@ -142,7 +138,8 @@ void insertSXWProd(void) { { for(m=0;m<12;m++) { sql[0] = 0; - sprintf(sql, "INSERT INTO sxwprod (RGroupID, Month, BMASS, LITTER, PCTLIVE) VALUES (%d, %d, %f, %f, %f);", g+1, m+1, _prod_bmass[Igp(g,m)], _prod_litter[m], _prod_pctlive[Igp(g,m)]); + sprintf(sql, "INSERT INTO sxwprod (RGroupID, Month, BMASS, LITTER, PCTLIVE) VALUES (%d, %d, %f, %f, %f);", + g+1, m+1, SXWTemp._prod_bmass[Igp(g,m)], SXWTemp._prod_litter[m], SXWTemp._prod_pctlive[Igp(g,m)]); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); } @@ -156,7 +153,8 @@ void insertInfo() { sql[0] = 0; beginTransaction(); - sprintf(sql, "INSERT INTO info (StartYear, Years, Iterations, RGroups, TranspirationLayers, SoilLayers, PlotSize, BVT) VALUES (%d, %d, %d, %d, %d, %d, %f, %f);", SW_Model.startyr, Globals.runModelYears, Globals.runModelIterations, Globals.grpCount, SXW.NTrLyrs, SXW.NSoLyrs, Globals.plotsize, _bvt); + sprintf(sql, "INSERT INTO info (StartYear, Years, Iterations, RGroups, TranspirationLayers, SoilLayers, PlotSize, BVT) VALUES (%d, %d, %d, %d, %d, %d, %f, %f);", + SW_Model.startyr, Globals.runModelYears, Globals.runModelIterations, Globals.grpCount, SXW.NTrLyrs, SXW.NSoLyrs, Globals.plotsize, SXWTemp._bvt); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); endTransaction(); @@ -384,7 +382,7 @@ void insertRgroupInfo(RealF * _resource_cur) { beginTransaction(); ForEachGroup(r) { - insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),RGroup[r]->relsize, RGroup[r]->pr, _resource_cur[r]/_bvt, _resource_cur[r]); + insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),RGroup[r]->relsize, RGroup[r]->pr, _resource_cur[r]/SXWTemp._bvt, _resource_cur[r]); } endTransaction(); } From c8e793e95a1dd481d0bc590ff0a9e4f954ce8a80 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 11 Apr 2019 15:37:44 -0600 Subject: [PATCH 007/167] Issue #259 Added SXW variables to CellType struct transp_window, SXW, and SXWTemp now have equivalents in the CellType struct. Additionally I added some documentation to the struct. --- ST_grid.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index 97219d25..34bdceed 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -144,13 +144,22 @@ struct _grid_init_species_st /* Struct to hold all plot-specific parameters */ struct grid_cell_st { + /* RGroup coresponding to this cell */ GroupType myGroup; + /* Species corresponding to this cell */ SpeciesType mySpecies; + /* Succulents corresponding to this cell */ SucculentType mySucculent; + /* This cell's environment. We expect each cell to + * have slightly different weather each year */ EnvType myEnvironment; + /* Cell's plot data */ PlotType myPlot; + /* Global variables corresponding to this cell */ ModelType myGlobals; + /* If TRUE this cell should use seed dispersal */ Bool useSeedDispersal; + /* TRUE if this cell is in spinup mode */ Bool duringSpinup; /* ---------------- accumulators -------------------- */ @@ -159,6 +168,12 @@ struct grid_cell_st *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; FireStatsType *_Gwf; /* -------------- end accumulators ------------------ */ + + /* -------------------- SXW ------------------------- */ + transp_t myTranspWindow; + SXW_t mySXW; + TempType mySXWTemp; + /* ------------------ End SXW ----------------------- */ } typedef CellType; /************ Module Variable Declarations ***************/ From a13702f3e082171be62dc1b5cb26836e49da49d8 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 11 Apr 2019 15:41:41 -0600 Subject: [PATCH 008/167] Issue #253 removed readme.txt from testing.sagebrush.master folder --- testing.sagebrush.master/readme.txt | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 testing.sagebrush.master/readme.txt diff --git a/testing.sagebrush.master/readme.txt b/testing.sagebrush.master/readme.txt deleted file mode 100644 index 529ba7ec..00000000 --- a/testing.sagebrush.master/readme.txt +++ /dev/null @@ -1,3 +0,0 @@ -#By Kyle Palmquist, 06/01/2015 -#This folder contains all of the default input parameters for the sagebrush steppe in Montana (based on Trace Martyn’s data). -#The weather data and site parameters are for Lewistown, MT. \ No newline at end of file From f0ca09024e6c7f6f2cb54a9a4ec35f7dbcf599bf Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 12 Apr 2019 13:21:51 -0600 Subject: [PATCH 009/167] Changed name of new sxw struct (issue #267) TempType -> SXW_resourceType SXWTemp -> SXWResources Temp was used to denote temporary names. These new names are permanent, barring us coming up with a more descriptive name. --- ST_grid.c | 2 +- sxw.c | 122 ++++++++++++++++++++++++------------------------- sxw.h | 2 +- sxw_resource.c | 28 ++++++------ sxw_soilwat.c | 34 +++++++------- sxw_sql.c | 10 ++-- 6 files changed, 99 insertions(+), 99 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 34bdceed..55ee96d7 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -172,7 +172,7 @@ struct grid_cell_st /* -------------------- SXW ------------------------- */ transp_t myTranspWindow; SXW_t mySXW; - TempType mySXWTemp; + SXW_resourceType mySXWResources; /* ------------------ End SXW ----------------------- */ } typedef CellType; diff --git a/sxw.c b/sxw.c index 075ca126..7cc38901 100644 --- a/sxw.c +++ b/sxw.c @@ -91,7 +91,7 @@ extern Bool storeAllIterations; // "Window" refers to the number of years over which transpiration data is averaged. transp_t transp_window; pcg32_random_t resource_rng; //rng for swx_resource.c functions. -TempType SXWTemp; +SXW_resourceType SXWResources; #ifdef SXW_BYMAXSIZE /* addition to meet changes specified at the top of the file */ @@ -377,7 +377,7 @@ This function is no longer utilized, SXW_GetResource has replaced it _resource_pr is no longer used as a parameter. We remain the code for the time being KAP 7/20/2016 */ - RealF pr = ZRO(SXWTemp._resource_pr[rg]) ? 0.0 : 1. / SXWTemp._resource_pr[rg]; + RealF pr = ZRO(SXWResources._resource_pr[rg]) ? 0.0 : 1. / SXWResources._resource_pr[rg]; return pr; //return pr > 10 ? 10 : pr; } @@ -387,7 +387,7 @@ RealF SXW_GetTranspiration( GrpIndex rg) { /* see _sxw_update_resource() for _resource_cur[] */ //printf("SXW_GetTranspiration _resource_cur[%d] = %.5f \n", rg, _resource_cur[rg]); - return SXWTemp._resource_cur[rg]; + return SXWResources._resource_cur[rg]; } void SXW_PrintDebug(Bool cleanup) { @@ -410,16 +410,16 @@ void SXW_PrintDebug(Bool cleanup) { insertInfo(); insertSXWPhen(); insertSXWProd(); - insertRootsXphen(SXWTemp._rootsXphen); + insertRootsXphen(SXWResources._rootsXphen); } insertInputVars(); insertInputProd(); insertInputSoils(); - insertOutputVars(SXWTemp._resource_cur, transp_window.added_transp); - insertRgroupInfo(SXWTemp._resource_cur); + insertOutputVars(SXWResources._resource_cur, transp_window.added_transp); + insertRgroupInfo(SXWResources._resource_cur); insertOutputProd(&SW_VegProd); - insertRootsSum(SXWTemp._roots_active_sum); - insertRootsRelative(SXWTemp._roots_active_rel); + insertRootsSum(SXWResources._roots_active_sum); + insertRootsRelative(SXWResources._roots_active_rel); insertTranspiration(); insertSWCBulk(); } @@ -473,7 +473,7 @@ static void _read_roots_max(void) { cnt++; lyr = 0; while ((p = strtok(NULL, " \t"))) { - SXWTemp._roots_max[Ilg(lyr, g)] = atof(p); + SXWResources._roots_max[Ilg(lyr, g)] = atof(p); lyr++; } if (lyr != SXW.NTrLyrs) { @@ -518,7 +518,7 @@ static void _read_phen(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - SXWTemp._phen[Igp(g,m)] = atof(p); + SXWResources._phen[Igp(g,m)] = atof(p); m++; } @@ -556,7 +556,7 @@ static void _read_bvt(void) { CloseFile(&fp); - SXWTemp._bvt = bmass / transp; + SXWResources._bvt = bmass / transp; } @@ -574,7 +574,7 @@ static void _read_prod(void) { fp = OpenFile(MyFileName, "r"); while (GetALine(fp, inbuf)) { - x = sscanf(inbuf, "%lf", &SXWTemp._prod_litter[mon]); + x = sscanf(inbuf, "%lf", &SXWResources._prod_litter[mon]); if (x < 1) { LogError(logfp, LOGFATAL, "%s: invalid record for litter %d.", MyFileName, mon + 1); @@ -609,7 +609,7 @@ static void _read_prod(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - SXWTemp._prod_bmass[Igp(g, mon)] = atof(p); + SXWResources._prod_bmass[Igp(g, mon)] = atof(p); mon++; } cnt++; @@ -644,7 +644,7 @@ static void _read_prod(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - SXWTemp._prod_pctlive[Igp(g, mon)] = atof(p); + SXWResources._prod_pctlive[Igp(g, mon)] = atof(p); mon++; } cnt++; @@ -716,16 +716,16 @@ static void _make_roots_arrays(void) { char *fstr = "_make_roots_array()"; size = SXW.NGrps * SXW.NTrLyrs; - SXWTemp._roots_max = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._roots_max = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); size = SXW.NGrps * SXW.NPds * SXW.NTrLyrs; - SXWTemp._rootsXphen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - SXWTemp._roots_active = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - SXWTemp._roots_active_rel = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._rootsXphen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._roots_active = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._roots_active_rel = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); //4 - Grass,Frob,Tree,Shrub size = NVEGTYPES * SXW.NPds * SXW.NTrLyrs; - SXWTemp._roots_active_sum = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._roots_active_sum = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } static void _make_phen_arrays(void) { @@ -734,7 +734,7 @@ static void _make_phen_arrays(void) { char *fstr = "_make_phen_arrays()"; size = SXW.NGrps * MAX_MONTHS; - SXWTemp._phen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._phen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } @@ -743,8 +743,8 @@ static void _make_prod_arrays(void) { char *fstr = "_make_phen_arrays()"; size = SXW.NGrps * MAX_MONTHS; - SXWTemp._prod_bmass = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - SXWTemp._prod_pctlive = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._prod_bmass = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources._prod_pctlive = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } static void _make_transp_arrays(void) { @@ -894,7 +894,7 @@ void _print_debuginfo(void) { //ForEachTranspLayer(t) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", SXWTemp._rootsXphen[Iglp(r, t, p)]); + fprintf(f, "\t%.4f", SXWResources._rootsXphen[Iglp(r, t, p)]); fprintf(f, "\n"); } } @@ -917,11 +917,11 @@ void _print_debuginfo(void) { ForEachGroup(r) { sum1 += RGroup[r]->relsize; sum2 += RGroup[r]->pr; - sum3 += SXWTemp._resource_cur[r]; - fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, RGroup[r]->relsize, RGroup[r]->pr, SXWTemp._resource_cur[r]/SXWTemp._bvt, SXWTemp._resource_cur[r]); + sum3 += SXWResources._resource_cur[r]; + fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, RGroup[r]->relsize, RGroup[r]->pr, SXWResources._resource_cur[r]/SXWResources._bvt, SXWResources._resource_cur[r]); } fprintf(f, "----- \t-------\t-----\t-----\t\t-----\n"); - fprintf(f, "%s\t\t%.4f\t%.4f\t%.4f\t\t%.4f\n", "Total", sum1, sum2, sum3/SXWTemp._bvt, sum3); + fprintf(f, "%s\t\t%.4f\t%.4f\t%.4f\t\t%.4f\n", "Total", sum1, sum2, sum3/SXWResources._bvt, sum3); fprintf(f, "\n------ Production Values Daily Summed Across Types Monthly Averaged -------\n"); fprintf(f, "Month\tBMass\tPctLive\tLAIlive\tVegCov\tTotAGB\n"); @@ -986,7 +986,7 @@ void _print_debuginfo(void) { for (l = 0; l < SXW.NTrLyrs; l++) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", SXWTemp._roots_active_sum[Itlp(t, l, p)]); + fprintf(f, "\t%.4f", SXWResources._roots_active_sum[Itlp(t, l, p)]); fprintf(f, "\n"); } } @@ -1005,7 +1005,7 @@ void _print_debuginfo(void) { //ForEachTranspLayer(t) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", SXWTemp._roots_active_rel[Iglp(r, t, p)]); + fprintf(f, "\t%.4f", SXWResources._roots_active_rel[Iglp(r, t, p)]); fprintf(f, "\n"); } } @@ -1113,48 +1113,48 @@ void free_all_sxw_memory( void ) { /***********************************************************/ void free_sxw_memory( void ) { - Mem_Free(SXWTemp._roots_max); - Mem_Free(SXWTemp._rootsXphen); - Mem_Free(SXWTemp._roots_active); - Mem_Free(SXWTemp._roots_active_rel); - Mem_Free(SXWTemp._roots_active_sum); - Mem_Free(SXWTemp._phen); - Mem_Free(SXWTemp._prod_bmass); - Mem_Free(SXWTemp._prod_pctlive); + Mem_Free(SXWResources._roots_max); + Mem_Free(SXWResources._rootsXphen); + Mem_Free(SXWResources._roots_active); + Mem_Free(SXWResources._roots_active_rel); + Mem_Free(SXWResources._roots_active_sum); + Mem_Free(SXWResources._phen); + Mem_Free(SXWResources._prod_bmass); + Mem_Free(SXWResources._prod_pctlive); } /***********************************************************/ void load_sxw_memory( RealD* grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ) { //load memory from the grid free_sxw_memory(); - SXWTemp._roots_max = Mem_Calloc(SXW.NGrps * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWTemp._rootsXphen = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWTemp._roots_active = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWTemp._roots_active_rel = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWTemp._roots_active_sum = Mem_Calloc(4 * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWTemp._phen = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - SXWTemp._prod_bmass = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - SXWTemp._prod_pctlive = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - - memcpy(SXWTemp._roots_max, grid_roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWTemp._rootsXphen, grid_rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWTemp._roots_active, grid_roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWTemp._roots_active_rel, grid_roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWTemp._roots_active_sum, grid_roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWTemp._phen, grid_phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(SXWTemp._prod_bmass, grid_prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(SXWTemp._prod_pctlive, grid_prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + SXWResources._roots_max = Mem_Calloc(SXW.NGrps * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources._rootsXphen = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources._roots_active = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources._roots_active_rel = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources._roots_active_sum = Mem_Calloc(4 * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources._phen = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + SXWResources._prod_bmass = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + SXWResources._prod_pctlive = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + + memcpy(SXWResources._roots_max, grid_roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWResources._rootsXphen, grid_rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWResources._roots_active, grid_roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWResources._roots_active_rel, grid_roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWResources._roots_active_sum, grid_roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(SXWResources._phen, grid_phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(SXWResources._prod_bmass, grid_prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(SXWResources._prod_pctlive, grid_prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); } /***********************************************************/ void save_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ) { //save memory to the grid - memcpy(grid_roots_max, SXWTemp._roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_rootsXphen, SXWTemp._rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active, SXWTemp._roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active_rel, SXWTemp._roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active_sum, SXWTemp._roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_phen, SXWTemp._phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(grid_prod_bmass, SXWTemp._prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(grid_prod_pctlive, SXWTemp._prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_roots_max, SXWResources._roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_rootsXphen, SXWResources._rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active, SXWResources._roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active_rel, SXWResources._roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active_sum, SXWResources._roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + memcpy(grid_phen, SXWResources._phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_prod_bmass, SXWResources._prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_prod_pctlive, SXWResources._prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); } diff --git a/sxw.h b/sxw.h index cb169958..f4a69c93 100644 --- a/sxw.h +++ b/sxw.h @@ -151,7 +151,7 @@ struct temp_SXW_st{ RealF _bvt; /* ratio of biomass/m2 / transp/m2 */ -} typedef TempType; +} typedef SXW_resourceType; #define ForEachTrPeriod(i) for((i)=0; (i)< SXW.NPds; (i)++) diff --git a/sxw_resource.c b/sxw_resource.c index 417a8bd2..4f92e4f9 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -47,7 +47,7 @@ //extern SW_SOILWAT SW_Soilwat; //extern SW_VEGPROD SW_VegProd; -extern TempType SXWTemp; +extern SXW_resourceType SXWResources; /* ------ Running Averages ------ */ extern @@ -78,14 +78,14 @@ void _sxw_root_phen(void) { TimeInt p; for (y = 0; y < (Globals.grpCount * SXW.NPds * SXW.NTrLyrs); y++) - SXWTemp._rootsXphen[y] = 0; + SXWResources._rootsXphen[y] = 0; ForEachGroup(g) { int nLyrs = getNTranspLayers(RGroup[g]->veg_prod_type); for (y = 0; y < nLyrs; y++) { ForEachTrPeriod(p) { - SXWTemp._rootsXphen[Iglp(g, y, p)] = SXWTemp._roots_max[Ilg(y, g)] * SXWTemp._phen[Igp(g, p)]; + SXWResources._rootsXphen[Iglp(g, y, p)] = SXWResources._roots_max[Ilg(y, g)] * SXWResources._phen[Igp(g, p)]; } } } @@ -131,14 +131,14 @@ void _sxw_update_resource(void) { _sxw_update_root_tables(sizes); /* Assign transpiration (resource availability) to each STEPPE functional group */ - _transp_contribution_by_group(SXWTemp._resource_cur); + _transp_contribution_by_group(SXWResources._resource_cur); /* Scale transpiration resources by a constant, bvt, to convert resources * (cm) to biomass that can be supported by those resources (g/cm) */ ForEachGroup(g) { //printf("for groupName= %smresource_cur prior to multiplication: %f\n",RGroup[g]->name, _resource_cur[g]); - SXWTemp._resource_cur[g] = SXWTemp._resource_cur[g] * SXWTemp._bvt; + SXWResources._resource_cur[g] = SXWResources._resource_cur[g] * SXWResources._bvt; //printf("for groupName= %s, resource_cur post multiplication: %f\n\n",Rgroup[g]->name, _resource_cur[g]); } /* _print_debuginfo(); */ @@ -157,7 +157,7 @@ void _sxw_update_root_tables( RealF sizes[] ) { int t,nLyrs; /* Set some things to zero where 4 refers to Tree, Shrub, Grass, Forb */ - Mem_Set(SXWTemp._roots_active_sum, 0, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + Mem_Set(SXWResources._roots_active_sum, 0, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); /* Calculate the active roots in each month and soil layer for each STEPPE * functional group based on the functional group biomass this year */ @@ -168,9 +168,9 @@ void _sxw_update_root_tables( RealF sizes[] ) { for (l = 0; l < nLyrs; l++) { ForEachTrPeriod(p) { - x = SXWTemp._rootsXphen[Iglp(g, l, p)] * sizes[g]; - SXWTemp._roots_active[Iglp(g, l, p)] = x; - SXWTemp._roots_active_sum[Itlp(t, l, p)] += x; + x = SXWResources._rootsXphen[Iglp(g, l, p)] * sizes[g]; + SXWResources._roots_active[Iglp(g, l, p)] = x; + SXWResources._roots_active_sum[Itlp(t, l, p)] += x; } } } @@ -184,11 +184,11 @@ void _sxw_update_root_tables( RealF sizes[] ) { for (l = 0; l < nLyrs; l++) { ForEachTrPeriod(p) { - SXWTemp._roots_active_rel[Iglp(g, l, p)] = - ZRO(SXWTemp._roots_active_sum[Itlp(t,l,p)]) ? + SXWResources._roots_active_rel[Iglp(g, l, p)] = + ZRO(SXWResources._roots_active_sum[Itlp(t,l,p)]) ? 0. : - SXWTemp._roots_active[Iglp(g, l, p)] - / SXWTemp._roots_active_sum[Itlp(t,l, p)]; + SXWResources._roots_active[Iglp(g, l, p)] + / SXWResources._roots_active_sum[Itlp(t,l, p)]; } } } @@ -261,7 +261,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { ForEachTrPeriod(p) { int nLyrs = getNTranspLayers(RGroup[g]->veg_prod_type); for (l = 0; l < nLyrs; l++) { - use_by_group[g] += (RealF) (SXWTemp._roots_active_rel[Iglp(g, l, p)] * transp[Ilp(l, p)]); + use_by_group[g] += (RealF) (SXWResources._roots_active_rel[Iglp(g, l, p)] * transp[Ilp(l, p)]); } } //printf("for groupName= %s, use_by_group[g] in transp= %f \n",RGroup[g]->name,use_by_group[g] ); diff --git a/sxw_soilwat.c b/sxw_soilwat.c index a638fae1..981d7ba6 100644 --- a/sxw_soilwat.c +++ b/sxw_soilwat.c @@ -60,7 +60,7 @@ extern SW_SITE SW_Site; extern SW_MODEL SW_Model; extern SW_VEGPROD SW_VegProd; -extern TempType SXWTemp; +extern SXW_resourceType SXWResources; #ifdef SXW_BYMAXSIZE extern RealF _Grp_BMass[]; /* added 2/28/03 */ @@ -133,7 +133,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 1) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_TREES] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_TREES] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_TREES] += y->transp_coeff[SW_TREES]; } @@ -143,7 +143,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 2) { if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_SHRUB] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_SHRUB] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; /*printf("* lyr=%d, group=%s(%d), type=%d, tl=%d, rootmax=%f, relsize1=%f, relsize2=%f, trco=%f\n", t, RGroup[g]->name, g, RGroup[g]->veg_prod_type, getNTranspLayers(RGroup[g]->veg_prod_type), @@ -159,7 +159,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 3) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_GRASS] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_GRASS] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_GRASS] += y->transp_coeff[SW_GRASS]; } @@ -169,7 +169,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 4) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_FORBS] += (RealF) SXWTemp._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_FORBS] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_FORBS] += y->transp_coeff[SW_FORBS]; } @@ -256,24 +256,24 @@ static void _update_productivity(void) { ForEachGroup(g) { if (1 == RGroup[g]->veg_prod_type) { //tree - v->veg[SW_TREES].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_TREES].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_TREES].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_TREES].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; } else if (2 == RGroup[g]->veg_prod_type) { //shrub - v->veg[SW_SHRUB].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_SHRUB].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_SHRUB].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_SHRUB].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; } else if (3 == RGroup[g]->veg_prod_type) { //grass - v->veg[SW_GRASS].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_GRASS].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_GRASS].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_GRASS].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; } else if (4 == RGroup[g]->veg_prod_type) { //forb - v->veg[SW_FORBS].pct_live[m] += SXWTemp._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_FORBS].biomass[m] += SXWTemp._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_FORBS].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_FORBS].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; } } - v->veg[SW_TREES].litter[m] = (vegTypeBiomass[0] * SXWTemp._prod_litter[m]); - v->veg[SW_SHRUB].litter[m] = (vegTypeBiomass[1] * SXWTemp._prod_litter[m]); - v->veg[SW_GRASS].litter[m] = (vegTypeBiomass[2] * SXWTemp._prod_litter[m]); - v->veg[SW_FORBS].litter[m] = (vegTypeBiomass[3] * SXWTemp._prod_litter[m]); + v->veg[SW_TREES].litter[m] = (vegTypeBiomass[0] * SXWResources._prod_litter[m]); + v->veg[SW_SHRUB].litter[m] = (vegTypeBiomass[1] * SXWResources._prod_litter[m]); + v->veg[SW_GRASS].litter[m] = (vegTypeBiomass[2] * SXWResources._prod_litter[m]); + v->veg[SW_FORBS].litter[m] = (vegTypeBiomass[3] * SXWResources._prod_litter[m]); } } diff --git a/sxw_sql.c b/sxw_sql.c index 913643dd..6173fd00 100644 --- a/sxw_sql.c +++ b/sxw_sql.c @@ -18,7 +18,7 @@ extern SW_MODEL SW_Model; extern SXW_t SXW; extern SW_SITE SW_Site; extern SW_VEGPROD SW_VegProd; -extern TempType SXWTemp; +extern SXW_resourceType SXWResources; static sqlite3 *db; static char sql[1024]; @@ -119,7 +119,7 @@ void insertSXWPhen(void) { { for(m=0;m<12;m++) { sql[0] = 0; - sprintf(sql, "INSERT INTO sxwphen (RGroupID, Month, GrowthPCT) VALUES (%d, %d, %f);", g+1, m+1,SXWTemp._phen[Igp(g,m)]); + sprintf(sql, "INSERT INTO sxwphen (RGroupID, Month, GrowthPCT) VALUES (%d, %d, %f);", g+1, m+1,SXWResources._phen[Igp(g,m)]); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); } @@ -139,7 +139,7 @@ void insertSXWProd(void) { for(m=0;m<12;m++) { sql[0] = 0; sprintf(sql, "INSERT INTO sxwprod (RGroupID, Month, BMASS, LITTER, PCTLIVE) VALUES (%d, %d, %f, %f, %f);", - g+1, m+1, SXWTemp._prod_bmass[Igp(g,m)], SXWTemp._prod_litter[m], SXWTemp._prod_pctlive[Igp(g,m)]); + g+1, m+1, SXWResources._prod_bmass[Igp(g,m)], SXWResources._prod_litter[m], SXWResources._prod_pctlive[Igp(g,m)]); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); } @@ -154,7 +154,7 @@ void insertInfo() { beginTransaction(); sprintf(sql, "INSERT INTO info (StartYear, Years, Iterations, RGroups, TranspirationLayers, SoilLayers, PlotSize, BVT) VALUES (%d, %d, %d, %d, %d, %d, %f, %f);", - SW_Model.startyr, Globals.runModelYears, Globals.runModelIterations, Globals.grpCount, SXW.NTrLyrs, SXW.NSoLyrs, Globals.plotsize, SXWTemp._bvt); + SW_Model.startyr, Globals.runModelYears, Globals.runModelIterations, Globals.grpCount, SXW.NTrLyrs, SXW.NSoLyrs, Globals.plotsize, SXWResources._bvt); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); endTransaction(); @@ -382,7 +382,7 @@ void insertRgroupInfo(RealF * _resource_cur) { beginTransaction(); ForEachGroup(r) { - insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),RGroup[r]->relsize, RGroup[r]->pr, _resource_cur[r]/SXWTemp._bvt, _resource_cur[r]); + insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),RGroup[r]->relsize, RGroup[r]->pr, _resource_cur[r]/SXWResources._bvt, _resource_cur[r]); } endTransaction(); } From 59702c7ab5b925f33b2ba06c070ac4a7d32deddb Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sun, 14 Apr 2019 17:13:18 -0600 Subject: [PATCH 010/167] (issue #271) changed global variables to pointers Globals, Plot, Env, and Succulent and now pointers. They are allocated in a new function called allocate_Globals() I also removed the function _globals_init from ST_params.c because it serves no purpose anymore. All memory allocation is handled in the new function. --- ST_defines.h | 4 +- ST_environs.c | 116 +++++++++++++++++----------------- ST_globals.h | 8 +-- ST_grid.c | 162 +++++++++++++++++++++++------------------------ ST_indivs.c | 4 +- ST_main.c | 50 +++++++++------ ST_mortality.c | 52 ++++++++-------- ST_output.c | 50 +++++++-------- ST_params.c | 141 +++++++++++++++++++---------------------- ST_resgroups.c | 26 ++++---- ST_species.c | 12 ++-- ST_sql.c | 14 ++--- ST_stats.c | 166 ++++++++++++++++++++++++------------------------- sxw.c | 18 +++--- sxw_environs.c | 6 +- sxw_resource.c | 30 ++++----- sxw_soilwat.c | 4 +- sxw_sql.c | 24 +++---- 18 files changed, 441 insertions(+), 446 deletions(-) diff --git a/ST_defines.h b/ST_defines.h index a579ee66..a830cea6 100644 --- a/ST_defines.h +++ b/ST_defines.h @@ -116,12 +116,12 @@ typedef enum {F_First, F_Log, F_Model, F_Env, F_Plot, F_RGroup, F_Species, * preferably as GrpIndex, but note that it gets changed, so it * can only be an lvalue. */ /* void ForEachGroup(GrpIndex) */ -#define ForEachGroup(c) for((c)=0; (c)< Globals.grpCount; (c)++) +#define ForEachGroup(c) for((c)=0; (c)< Globals->grpCount; (c)++) /* Generate an SppIndex to access Species[] to loop over each * defined species, irrespective of group. */ /* void ForEachSpecies(SppIndex) */ -#define ForEachSpecies(s) for((s)=0; (s)< Globals.sppCount; (s)++) +#define ForEachSpecies(s) for((s)=0; (s)< Globals->sppCount; (s)++) /* Same for individuals within a species. Traverses a species' * linked list of IndivType objects. i is a pointer to diff --git a/ST_environs.c b/ST_environs.c index 24c3fbfc..edca8bb4 100644 --- a/ST_environs.c +++ b/ST_environs.c @@ -65,7 +65,7 @@ static void _make_ppt( void) { /*======================================================*/ /* If not running SOILWAT,take a random number from normal distribution with*/ /* mean, stddev that is between min & max from */ -/* the Globals.ppt structure.*/ +/* the Globals->ppt structure.*/ /* Also set the growing season precip. */ /* HISTORY */ @@ -74,7 +74,7 @@ static void _make_ppt( void) { * The ppt and gsppt are set in _sxw_set_environs() * but we still pass through this code to set the * Dry/Wet/Normal state. - * KAP 1/26/2017 The above note by CB is not correct. Env.ppt + * KAP 1/26/2017 The above note by CB is not correct. Env->ppt * is set in _sxw_set_environs, but gsppt is not, it is * set below. When using SOILWAT or not, the gsspt, ppt.dry, * and ppt.wet is currently fixed each year and read from env.in @@ -93,27 +93,27 @@ static void _make_ppt( void) { // Run with SOILWAT2: we have monthly PPT and temperature to calculate // growing season precipitation as sum of monthly precipitation of those // months when mean air temperature exceeds a threshold `GROWING_BASE_TEMP` - Env.gsppt = 0; // gsppt is defined as IntS and units are millimeters + Env->gsppt = 0; // gsppt is defined as IntS and units are millimeters for (i = 0; i < MAX_MONTHS; i++) { - Env.gsppt += GE(SXW.temp_monthly[i], GROWING_BASE_TEMP) ? + Env->gsppt += GE(SXW.temp_monthly[i], GROWING_BASE_TEMP) ? (IntS) (SXW.ppt_monthly[i] * 10. + 0.5) : 0; } - if (Env.gsppt <= 0) + if (Env->gsppt <= 0) { LogError(logfp, LOGWARN, "Zero growing season precipitation in "\ - "year = %d of iteration = %d", Globals.currYear, Globals.currIter); - Env.gsppt = 0; + "year = %d of iteration = %d", Globals->currYear, Globals->currIter); + Env->gsppt = 0; } - if ( Env.ppt <= Globals.ppt.dry ) - Env.wet_dry = Ppt_Dry; - else if (Env.ppt >= Globals.ppt.wet) - Env.wet_dry = Ppt_Wet; + if ( Env->ppt <= Globals->ppt.dry ) + Env->wet_dry = Ppt_Dry; + else if (Env->ppt >= Globals->ppt.wet) + Env->wet_dry = Ppt_Wet; else - Env.wet_dry = Ppt_Norm; + Env->wet_dry = Ppt_Norm; } /**************************************************************/ @@ -127,12 +127,12 @@ static void _set_ppt_reduction( void) { /*------------------------------------------------------*/ /* EQN 10*/ - Succulent.reduction = fabs(Succulent.growth[Slope] - * Env.gsppt - + Succulent.growth[Intcpt]); + Succulent->reduction = fabs(Succulent->growth[Slope] + * Env->gsppt + + Succulent->growth[Intcpt]); /* EQN 16*/ - Succulent.prob_death = (Succulent.mort[Slope] * Env.gsppt - + Succulent.mort[Intcpt]) / 100.0; + Succulent->prob_death = (Succulent->mort[Slope] * Env->gsppt + + Succulent->mort[Intcpt]) / 100.0; } /**************************************************************/ @@ -158,20 +158,20 @@ static void _set_temp_reduction( void) { RealF tp[4]; /* parms for temp growth modifier eqn.*/ for ( i=CoolSeason; i <= WarmSeason; i ++ ){ - tp[1] = Globals.tempparm[i][0]; - tp[2] = Globals.tempparm[i][1]; - tp[3] = Globals.tempparm[i][2]; - tp[0] = Env.temp + tp[1]; - Env.temp_reduction[i] = tp[2]*tp[0] + tp[3] * (tp[0]*tp[0]); - Env.temp_reduction[i] = max(0., Env.temp_reduction[i]); + tp[1] = Globals->tempparm[i][0]; + tp[2] = Globals->tempparm[i][1]; + tp[3] = Globals->tempparm[i][2]; + tp[0] = Env->temp + tp[1]; + Env->temp_reduction[i] = tp[2]*tp[0] + tp[3] * (tp[0]*tp[0]); + Env->temp_reduction[i] = max(0., Env->temp_reduction[i]); } - if (Env.temp < 9.5 ) { - Env.temp_reduction[CoolSeason] = .9; - Env.temp_reduction[WarmSeason] = .6; + if (Env->temp < 9.5 ) { + Env->temp_reduction[CoolSeason] = .9; + Env->temp_reduction[WarmSeason] = .6; } else { - Env.temp_reduction[CoolSeason] = .6; - Env.temp_reduction[WarmSeason] = .9; + Env->temp_reduction[CoolSeason] = .6; + Env->temp_reduction[WarmSeason] = .9; } } @@ -191,73 +191,73 @@ static void _make_disturbance( void) { /*------------------------------------------------------*/ /* Can't have simultaneous disturbances*/ - if (Plot.disturbance != NoDisturb) { - switch( Plot.disturbance) { + if (Plot->disturbance != NoDisturb) { + switch( Plot->disturbance) { case FecalPat: - if (Plot.pat_removed) { - Plot.disturbed = 0; - Plot.pat_removed = FALSE; - Plot.disturbance = NoDisturb; + if (Plot->pat_removed) { + Plot->disturbed = 0; + Plot->pat_removed = FALSE; + Plot->disturbance = NoDisturb; } else { - pc = Globals.pat.recol[Slope] * Plot.disturbed - + Globals.pat.recol[Intcpt]; + pc = Globals->pat.recol[Slope] * Plot->disturbed + + Globals->pat.recol[Intcpt]; if (RandUni(&environs_rng) <= pc) { - Plot.pat_removed = TRUE; + Plot->pat_removed = TRUE; /* slight effects for one year*/ - Plot.disturbed = 1; + Plot->disturbed = 1; } else { - Plot.pat_removed = FALSE; - Plot.disturbed++; + Plot->pat_removed = FALSE; + Plot->disturbed++; } } break; case NoDisturb: // Does nothing but prevent a compiler warning case LastDisturb: default: - Plot.disturbed = (Plot.disturbed) ? Plot.disturbed -1 : 0; + Plot->disturbed = (Plot->disturbed) ? Plot->disturbed -1 : 0; } - if (Plot.disturbed == 0) - Plot.disturbance = NoDisturb; + if (Plot->disturbed == 0) + Plot->disturbance = NoDisturb; } /* if the disturbance was expired above, */ /* we can generate a new one immediately */ - if (Plot.disturbance == NoDisturb) { + if (Plot->disturbance == NoDisturb) { /* pick some type of disturbance (other than none)*/ event = (DisturbEvent) RandUniIntRange(1, LastDisturb -1, &environs_rng); /* make sure this is off unless needed */ - Plot.pat_removed = FALSE; + Plot->pat_removed = FALSE; switch( event) { case FecalPat: - if (!Globals.pat.use) {event=NoDisturb; break;} - event = (RandUni(&environs_rng) <= Globals.pat.occur) + if (!Globals->pat.use) {event=NoDisturb; break;} + event = (RandUni(&environs_rng) <= Globals->pat.occur) ? event : NoDisturb; if (event == NoDisturb) break; - Plot.pat_removed = (RandUni(&environs_rng) <= Globals.pat.removal) + Plot->pat_removed = (RandUni(&environs_rng) <= Globals->pat.removal) ? TRUE : FALSE; - Plot.disturbed = 0; + Plot->disturbed = 0; break; case AntMound: - if (!Globals.mound.use) {event=NoDisturb; break;} - event = (RandUni(&environs_rng) <= Globals.mound.occur) + if (!Globals->mound.use) {event=NoDisturb; break;} + event = (RandUni(&environs_rng) <= Globals->mound.occur) ? event :NoDisturb; if (event == NoDisturb) break; - Plot.disturbed = RandUniIntRange(Globals.mound.minyr, - Globals.mound.maxyr, + Plot->disturbed = RandUniIntRange(Globals->mound.minyr, + Globals->mound.maxyr, &environs_rng); break; case Burrow: - if (!Globals.burrow.use) {event=NoDisturb; break;} - event = (RandUni(&environs_rng) <= Globals.burrow.occur) + if (!Globals->burrow.use) {event=NoDisturb; break;} + event = (RandUni(&environs_rng) <= Globals->burrow.occur) ? event :NoDisturb; if (event == NoDisturb) break; - Plot.disturbed = (Globals.burrow.minyr > 0) - ? RandUniIntRange(1, Globals.burrow.minyr, &environs_rng) + Plot->disturbed = (Globals->burrow.minyr > 0) + ? RandUniIntRange(1, Globals->burrow.minyr, &environs_rng) : 0; break; case NoDisturb: @@ -267,7 +267,7 @@ static void _make_disturbance( void) { default: break; } - Plot.disturbance = event; + Plot->disturbance = event; } diff --git a/ST_globals.h b/ST_globals.h index 3a862e88..fa6c5c7e 100644 --- a/ST_globals.h +++ b/ST_globals.h @@ -21,10 +21,10 @@ extern SpeciesType *Species[MAX_SPECIES]; extern GroupType *RGroup [MAX_RGROUPS]; -extern SucculentType Succulent; -extern EnvType Env; -extern PlotType Plot; -extern ModelType Globals; +extern SucculentType *Succulent; +extern EnvType *Env; +extern PlotType *Plot; +extern ModelType *Globals; extern BmassFlagsType BmassFlags; extern MortFlagsType MortFlags; diff --git a/ST_grid.c b/ST_grid.c index 55ee96d7..e76f912b 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -216,7 +216,7 @@ extern pcg32_random_t markov_rng; //This is Rgroup structure pointer that will read rgroup disturbance value, will be used in // grid disturbance -//extern GroupType *RGroup [MAX_RGROUPS]; // don't need to extern here, because this is done in ST_globals.h +//extern GroupType *RGroup [MAX_RGROUPS]; // don't need to extern here, because this is done in ST_Globals->h // these are grids to store the SOILWAT variables... also dynamically allocated/freed SW_SOILWAT *grid_SW_Soilwat, *spinup_SW_Soilwat; @@ -455,8 +455,8 @@ void runGrid(void) if (UseProgressBar) { prog_Incr = (((double) 1) - / ((double) ((Globals.runModelYears * grid_Cells) - * Globals.runModelIterations))); //gets how much progress we'll make in one year towards our goal of iter*years*cells + / ((double) ((Globals->runModelYears * grid_Cells) + * Globals->runModelIterations))); //gets how much progress we'll make in one year towards our goal of iter*years*cells prog_Time = clock(); //used for timing sprintf(prog_Prefix, "simulations: "); } @@ -464,7 +464,7 @@ void runGrid(void) char aString[2048]; sprintf(aString, "%s/%s", grid_directories[0], SW_Weather.name_prefix); - for (iter = 1; iter <= Globals.runModelIterations; iter++) + for (iter = 1; iter <= Globals->runModelIterations; iter++) { //for each iteration /* @@ -478,20 +478,20 @@ void runGrid(void) Plot_Initialize(); - RandSeed(Globals.randseed, &environs_rng); - RandSeed(Globals.randseed, &mortality_rng); - RandSeed(Globals.randseed, &resgroups_rng); - RandSeed(Globals.randseed, &species_rng); - RandSeed(Globals.randseed, &grid_rng); - RandSeed(Globals.randseed, &markov_rng); + RandSeed(Globals->randseed, &environs_rng); + RandSeed(Globals->randseed, &mortality_rng); + RandSeed(Globals->randseed, &resgroups_rng); + RandSeed(Globals->randseed, &species_rng); + RandSeed(Globals->randseed, &grid_rng); + RandSeed(Globals->randseed, &markov_rng); if (iter > 1) _free_grid_globals(); //frees the memory from when we called _load_grid_globals() last time... (doesn't need to be called on the first iteration because the memory hasn't been allocated yet) - Globals.currIter = iter; + Globals->currIter = iter; _load_grid_globals(); //allocates/initializes grid variables (specifically the ones that are going to change every iter) - for (year = 1; year <= Globals.runModelYears; year++) + for (year = 1; year <= Globals->runModelYears; year++) { //for each year for (i = 1; i <= grid_Rows; i++) for (j = 1; j <= grid_Cols; j++) @@ -512,7 +512,7 @@ void runGrid(void) _load_spinup_cell(spinup_cell); // loads the spinup cell into the global variables } - Globals.currYear = year; + Globals->currYear = year; if (year > 1 && UseSeedDispersal) _set_sd_lyppt(i, j); @@ -564,10 +564,10 @@ void runGrid(void) for (i = 1; i <= grid_Rows; i++) for (j = 1; j <= grid_Cols; j++) { - _load_cell(i, j, Globals.runModelYears, TRUE); + _load_cell(i, j, Globals->runModelYears, TRUE); stat_Collect_GMort(); stat_Collect_SMort(); - _save_cell(i, j, Globals.runModelYears, TRUE); + _save_cell(i, j, Globals->runModelYears, TRUE); } //reset soilwat to initial condition ChDir(grid_directories[0]); @@ -597,7 +597,7 @@ void runGrid(void) int cell = j + ((i - 1) * grid_Cols) - 1; _load_cell(i, j, 1, TRUE); - for (year = 2; year <= Globals.runModelYears; year++) // _load_cell gets the first years accumulators loaded, so we start at 2... + for (year = 2; year <= Globals->runModelYears; year++) // _load_cell gets the first years accumulators loaded, so we start at 2... stat_Load_Accumulators(cell, year); char fileMort[1024], fileBMass[1024], fileReceivedProb[1024]; @@ -672,10 +672,10 @@ static void _run_spinup(void) Plot_Initialize(); - Globals.currIter = iter; + Globals->currIter = iter; //_load_grid_globals(); //allocates/initializes grid variables (specifically the ones that are going to change every iter) - for (year = 1; year <= Globals.runModelYears; year++) + for (year = 1; year <= Globals->runModelYears; year++) { //for each year for (spinup_Cell = 0; spinup_Cell < nSoilTypes; spinup_Cell++) { // for each different soil type @@ -685,7 +685,7 @@ static void _run_spinup(void) //int i = ((cell + 1 - j) / grid_Cols) + 1; // this is the row of the first cell of this soiltype _load_spinup_cell(spinup_Cell); - Globals.currYear = year; + Globals->currYear = year; // _do_grid_disturbances(i, j); @@ -788,7 +788,7 @@ static void _init_grid_inputs(void) LogError(logfp, LOGFATAL, "Number of cells in grid exceeds MAX_CELLS defined in ST_defines.h"); - Globals.nCells = (grid_Cols * grid_Rows); + Globals->nCells = (grid_Cols * grid_Rows); GetALine(f, buf); i = sscanf(buf, "%d", &UseDisturbances); @@ -987,7 +987,7 @@ static void _init_grid_globals(void) "_init_grid_globals()"); for (i = 0; i < grid_Cells; i++) grid_initSpecies[i].species_seed_avail = Mem_Calloc( - Globals.sppCount, sizeof(int), "_init_grid_globals()"); + Globals->sppCount, sizeof(int), "_init_grid_globals()"); } //if(sd_Option2a || sd_Option2b) { @@ -1092,10 +1092,10 @@ static void _load_grid_globals(void) } } - grid_Succulent[i] = Succulent; - grid_Env[i] = Env; - grid_Plot[i] = Plot; - grid_Globals[i] = Globals; + grid_Succulent[i] = *Succulent; + grid_Env[i] = *Env; + grid_Plot[i] = *Plot; + grid_Globals[i] = *Globals; if (UseDisturbances) { @@ -1205,10 +1205,10 @@ static void _load_spinup_globals(void) } } - spinup_Succulent[i] = Succulent; - spinup_Env[i] = Env; - spinup_Plot[i] = Plot; - spinup_Globals[i] = Globals; + spinup_Succulent[i] = *Succulent; + spinup_Env[i] = *Env; + spinup_Plot[i] = *Plot; + spinup_Globals[i] = *Globals; if (UseDisturbances) { @@ -1553,10 +1553,10 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) grid_RGroup[c][cell].max_age * sizeof(IntUS)); } - Succulent = grid_Succulent[cell]; - Env = grid_Env[cell]; - Plot = grid_Plot[cell]; - Globals = grid_Globals[cell]; + *Succulent = grid_Succulent[cell]; + *Env = grid_Env[cell]; + *Plot = grid_Plot[cell]; + *Globals = grid_Globals[cell]; Mem_Free(SXW.f_roots); Mem_Free(SXW.f_phen); @@ -1672,10 +1672,10 @@ static void _load_spinup_cell(int cell) spinup_RGroup[c][cell].max_age * sizeof(IntUS)); } - Succulent = spinup_Succulent[cell]; - Env = spinup_Env[cell]; - Plot = spinup_Plot[cell]; - Globals = spinup_Globals[cell]; + *Succulent = spinup_Succulent[cell]; + *Env = spinup_Env[cell]; + *Plot = spinup_Plot[cell]; + *Globals = spinup_Globals[cell]; Mem_Free(SXW.f_roots); Mem_Free(SXW.f_phen); @@ -1795,10 +1795,10 @@ static void _save_cell(int row, int col, int year, Bool useAccumulators) RGroup[c]->max_age * sizeof(IntUS)); } - grid_Succulent[cell] = Succulent; - grid_Env[cell] = Env; - grid_Plot[cell] = Plot; - grid_Globals[cell] = Globals; + grid_Succulent[cell] = *Succulent; + grid_Env[cell] = *Env; + grid_Plot[cell] = *Plot; + grid_Globals[cell] = *Globals; Mem_Free(grid_SXW[cell].f_roots); Mem_Free(grid_SXW[cell].f_phen); @@ -1911,10 +1911,10 @@ static void _save_spinup_cell(int cell) RGroup[c]->max_age * sizeof(IntUS)); } - spinup_Succulent[cell] = Succulent; - spinup_Env[cell] = Env; - spinup_Plot[cell] = Plot; - spinup_Globals[cell] = Globals; + spinup_Succulent[cell] = *Succulent; + spinup_Env[cell] = *Env; + spinup_Plot[cell] = *Plot; + spinup_Globals[cell] = *Globals; Mem_Free(spinup_SXW[cell].f_roots); Mem_Free(spinup_SXW[cell].f_phen); @@ -2571,7 +2571,7 @@ static void _read_seed_dispersal_in(void) MAXD = ((H * VW) / VT) / 100.0; // divide by 100.0 because we want it in meters, not centimeters sd_Rate = -(log(0.05) / MAXD); //sd_Rate is the seed dispersal rate... 0.05 = exp(-RATE*MAXD) => RATE = -(ln(0.05)/MAXD) See Coffin et al. 1993 - plotLength = sqrt(Globals.plotsize); + plotLength = sqrt(Globals->plotsize); MAXDP = (int) ceil(MAXD / plotLength); //MAXD in terms of plots... rounds up to the nearest integer maxCells = (int) pow((MAXDP * 2) + 1.0, 2.0); //gets the maximum number of cells that a grid cell can possibly disperse seeds to... it ends up being more then the maximum actually... if (grid_Cells < maxCells) @@ -2635,7 +2635,7 @@ static void _do_seed_dispersal(void) int i, j, germ, sgerm, year; SppIndex s; - if (Globals.currYear == 1 && !sd_Option1a && !sd_Option1b) + if (Globals->currYear == 1 && !sd_Option1a && !sd_Option1b) { //since we have no previous data to go off of, use the current years... for (i = 0; i < grid_Cells; i++) ForEachSpecies(s) @@ -2663,17 +2663,17 @@ static void _do_seed_dispersal(void) randomN = RandUni(&grid_rng); germ = LE(randomN, Species[s]->seedling_estab_prob); - year = Globals.currYear - 1; + year = Globals->currYear - 1; for (i = 0; i < grid_Cells; i++) { - if (sd_Option1a && Globals.currYear <= sd_NYearsSeedsAvailable) + if (sd_Option1a && Globals->currYear <= sd_NYearsSeedsAvailable) { grid_SD[s][i].seeds_present = 1; } else if (sd_Option1b - && Globals.currYear <= sd_NYearsSeedsAvailable + && Globals->currYear <= sd_NYearsSeedsAvailable && grid_initSpecies[i].species_seed_avail[s]) { grid_SD[s][i].seeds_present = 1; @@ -2692,9 +2692,9 @@ static void _do_seed_dispersal(void) /*&& (year != grid_Disturb[i].kill_yr)*/) { //commented above one condition as it was causing a bug there, next year of killing year will make - //allow_growth flag to false as year = Globals.currYear - 1 , so for example if killing year= 6 and Globals.currYear=7 then here + //allow_growth flag to false as year = Globals->currYear - 1 , so for example if killing year= 6 and Globals->currYear=7 then here // year variable will be 7-1 =6 that is equal to killing year 6, so this condition (year != grid_Disturb[i].kill_yr) - //will fail and allow_growth will not become TRUE, then when Globals.currYear=8 this allow_growth= FALSE will carry forward and there will no call + //will fail and allow_growth will not become TRUE, then when Globals->currYear=8 this allow_growth= FALSE will carry forward and there will no call // to other functions like Species_Update_Newsize() so new size will not be updated and last year size will carry forward so in final output year 7 and year 8 will // have same output that is not correct. grid_Species[s][i].allow_growth = TRUE; @@ -2704,8 +2704,8 @@ static void _do_seed_dispersal(void) else if (sgerm || GT(biomass, 0.0)) grid_Species[s][i].allow_growth = TRUE; grid_Species[s][i].sd_sgerm = sgerm; //based upon whether we have received/produced seeds that germinated - //if(grid_Species[s][i].allow_growth == TRUE && i == 52 && s == 0 && Globals.currIter == 1) - // printf("%s allow_growth:%d year:%d sgerm:%d iter:%d\n", grid_Species[s][i].name, grid_Species[s][i].allow_growth, year, sgerm, Globals.currIter); + //if(grid_Species[s][i].allow_growth == TRUE && i == 52 && s == 0 && Globals->currIter == 1) + // printf("%s allow_growth:%d year:%d sgerm:%d iter:%d\n", grid_Species[s][i].name, grid_Species[s][i].allow_growth, year, sgerm, Globals->currIter); } } @@ -2827,7 +2827,7 @@ static void _kill_groups_and_species(void) GrpIndex rg; ForEachGroup(rg) { - if (Globals.currYear < RGroup[rg]->startyr) + if (Globals->currYear < RGroup[rg]->startyr) { /* don't start trying to kill until RGroup[rg]->startyr year as nothing grow till now */ continue; @@ -2861,34 +2861,34 @@ static int _do_grid_disturbances(int row, int col) if(UseDisturbances) { int cell = col + ((row - 1) * grid_Cols) - 1; -// printf( "inside _do_grid_disturbances Globals.currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", -// Globals.currYear, cell, grid_Disturb[cell].kill_yr); - if ((Globals.currYear >=grid_Disturb[cell].killfreq_startyr) && GT((float)grid_Disturb[cell].killfrq, 0.)) +// printf( "inside _do_grid_disturbances Globals->currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", +// Globals->currYear, cell, grid_Disturb[cell].kill_yr); + if ((Globals->currYear >=grid_Disturb[cell].killfreq_startyr) && GT((float)grid_Disturb[cell].killfrq, 0.)) { if (LT((float)grid_Disturb[cell].killfrq, 1.0)) { if (RandUni(&grid_rng) <= grid_Disturb[cell].killfrq) { - grid_Disturb[cell].kill_yr = Globals.currYear; + grid_Disturb[cell].kill_yr = Globals->currYear; } } - else if (((Globals.currYear - grid_Disturb[cell].killfreq_startyr) % (IntU) grid_Disturb[cell].killfrq) == 0) + else if (((Globals->currYear - grid_Disturb[cell].killfreq_startyr) % (IntU) grid_Disturb[cell].killfrq) == 0) { - grid_Disturb[cell].kill_yr = Globals.currYear; + grid_Disturb[cell].kill_yr = Globals->currYear; } } - if (Globals.currYear == grid_Disturb[cell].extirp) + if (Globals->currYear == grid_Disturb[cell].extirp) { _do_groups_and_species_extirpate(); return 1; } - else if (Globals.currYear == grid_Disturb[cell].kill_yr) + else if (Globals->currYear == grid_Disturb[cell].kill_yr) { -// printf( "current year matched with cell kill_year so calling _kill_groups_and_species() Globals.currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", -// Globals.currYear, cell, grid_Disturb[cell].kill_yr); +// printf( "current year matched with cell kill_year so calling _kill_groups_and_species() Globals->currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", +// Globals->currYear, cell, grid_Disturb[cell].kill_yr); _kill_groups_and_species(); return 1; } @@ -2910,32 +2910,32 @@ static void _do_grid_proportion_Recovery(int row, int col) if (UseDisturbances) { int cell = col + ((row - 1) * grid_Cols) - 1; -// printf( "inside _do_grid_proportion_Recovery Globals.currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", -// Globals.currYear, cell, grid_Disturb[cell].kill_yr); - if ((Globals.currYear >= grid_Disturb[cell].killfreq_startyr) && GT((float)grid_Disturb[cell].killfrq, 0.)) +// printf( "inside _do_grid_proportion_Recovery Globals->currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", +// Globals->currYear, cell, grid_Disturb[cell].kill_yr); + if ((Globals->currYear >= grid_Disturb[cell].killfreq_startyr) && GT((float)grid_Disturb[cell].killfrq, 0.)) { if (LT((float)grid_Disturb[cell].killfrq, 1.0)) { if (RandUni(&grid_rng) <= grid_Disturb[cell].killfrq) { - grid_Disturb[cell].kill_yr = Globals.currYear; + grid_Disturb[cell].kill_yr = Globals->currYear; } } - else if (((Globals.currYear - grid_Disturb[cell].killfreq_startyr) % (IntU) grid_Disturb[cell].killfrq) == 0) + else if (((Globals->currYear - grid_Disturb[cell].killfreq_startyr) % (IntU) grid_Disturb[cell].killfrq) == 0) { - grid_Disturb[cell].kill_yr = Globals.currYear; + grid_Disturb[cell].kill_yr = Globals->currYear; } } //rgroup proportion recovery - if (Globals.currYear == grid_Disturb[cell].kill_yr) + if (Globals->currYear == grid_Disturb[cell].kill_yr) { GrpIndex rg; ForEachGroup(rg) { - if (Globals.currYear < RGroup[rg]->startyr) + if (Globals->currYear < RGroup[rg]->startyr) { /* don't start trying to grow until RGroup[rg]->startyr year */ continue; @@ -2983,30 +2983,30 @@ static void _do_grid_grazing_EndOfYear(int row, int col) IntU grazingyr = 0; int cell = col + ((row - 1) * grid_Cols) - 1; - if ((Globals.currYear >=grid_Disturb[cell].grazingfreq_startyr) && grid_Disturb[cell].grazing_frq > 0.) + if ((Globals->currYear >=grid_Disturb[cell].grazingfreq_startyr) && grid_Disturb[cell].grazing_frq > 0.) { if (grid_Disturb[cell].grazing_frq < 1.0) { if (RandUni(&grid_rng) <= grid_Disturb[cell].grazing_frq) { - grazingyr = Globals.currYear; + grazingyr = Globals->currYear; } } - else if (((Globals.currYear - grid_Disturb[cell].grazingfreq_startyr) % (IntU) grid_Disturb[cell].grazing_frq) == 0) + else if (((Globals->currYear - grid_Disturb[cell].grazingfreq_startyr) % (IntU) grid_Disturb[cell].grazing_frq) == 0) { - grazingyr = Globals.currYear; + grazingyr = Globals->currYear; } } //rgroup proportion grazing - if (Globals.currYear == grazingyr) + if (Globals->currYear == grazingyr) { GrpIndex rg; ForEachGroup(rg) { - if (Globals.currYear < RGroup[rg]->startyr) + if (Globals->currYear < RGroup[rg]->startyr) { /* don't start trying to grow or do grazing until RGroup[rg]->startyr year */ continue; @@ -3022,7 +3022,7 @@ static void _do_grid_grazing_EndOfYear(int row, int col) } else { - // printf( "year = %d, calling Species_Proportion_Grazing() with rgroup name= %s , RGroup[%d]->proportion_grazing =%f for Species[%d]->name= %s \n", Globals.currYear,RGroup[rg]->name, rg,RGroup[rg]->proportion_grazing, i, Species[RGroup[rg]->est_spp[i]]->name); + // printf( "year = %d, calling Species_Proportion_Grazing() with rgroup name= %s , RGroup[%d]->proportion_grazing =%f for Species[%d]->name= %s \n", Globals->currYear,RGroup[rg]->name, rg,RGroup[rg]->proportion_grazing, i, Species[RGroup[rg]->est_spp[i]]->name); Species_Proportion_Grazing(RGroup[rg]->est_spp[i], RGroup[rg]->proportion_grazing); } @@ -3068,7 +3068,7 @@ static void _read_init_species(void) if (do_copy == 1 && copy_cell > -1 && copy_cell < grid_Cells && cell != 0 && copy_cell < cell) { //copy this cells values from a previous cell's - for (j = 0; j < Globals.sppCount; j++) + for (j = 0; j < Globals->sppCount; j++) grid_initSpecies[i].species_seed_avail[j] = grid_initSpecies[copy_cell].species_seed_avail[j]; grid_initSpecies[i].use_SpinUp = diff --git a/ST_indivs.c b/ST_indivs.c index 7d519fae..c92f9f99 100644 --- a/ST_indivs.c +++ b/ST_indivs.c @@ -223,7 +223,7 @@ void indiv_proportion_Kill(IndivType *ndv, int killType, RealF proportKilled) LogError(logfp, LOGWARN, "%s dies older than max_age (%d > %d). Iter=%d, Year=%d\n", Species[ndv->myspecies]->name, ndv->age, Species[ndv->myspecies]->max_age, - Globals.currIter, Globals.currYear); + Globals->currIter, Globals->currYear); } //if (!UseGrid) @@ -353,7 +353,7 @@ void indiv_Kill_Complete( IndivType *ndv, int killType) { LogError(logfp, LOGWARN, "%s dies older than max_age (%d > %d). Iter=%d, Year=%d\n", Species[ndv->myspecies]->name, ndv->age, Species[ndv->myspecies]->max_age, - Globals.currIter, Globals.currYear); + Globals->currIter, Globals->currYear); } // if(!UseGrid) // insertIndivKill(ndv->id,killType); diff --git a/ST_main.c b/ST_main.c index c0b73d97..33ae46b6 100644 --- a/ST_main.c +++ b/ST_main.c @@ -86,6 +86,7 @@ SW_FILE_STATUS SW_File_Status; /*************** Local Function Declarations ***************/ /***********************************************************/ void Plot_Initialize( void); +void allocate_Globals(void); static void usage(void) { char *s ="STEPPE plant community dynamics (SGS-LTER Jan-04).\n" @@ -120,10 +121,10 @@ FILE *logfp, /* used everywhere by LogError */ int logged; /* indicator that err file was written to */ SpeciesType *Species[MAX_SPECIES]; GroupType *RGroup [MAX_RGROUPS]; -SucculentType Succulent; -EnvType Env; -PlotType Plot; -ModelType Globals; +SucculentType *Succulent; +EnvType *Env; +PlotType *Plot; +ModelType *Globals; BmassFlagsType BmassFlags; MortFlagsType MortFlags; @@ -159,6 +160,7 @@ int main(int argc, char **argv) { storeAllIterations = FALSE; // dont want to store all soilwat output iterations unless -i flag STdebug_requested = FALSE; + allocate_Globals(); init_args(argc, argv); // read input arguments and intialize proper flags printf("STEPWAT init_args() executed successfully \n"); @@ -184,12 +186,12 @@ int main(int argc, char **argv) { ST_connect("Output/stdebug"); } - incr = (IntS) ((float) Globals.runModelIterations / 10); + incr = (IntS) ((float) Globals->runModelIterations / 10); if (incr == 0) incr = 1; /* --- Begin a new iteration ------ */ - for (iter = 1; iter <= Globals.runModelIterations; iter++) { + for (iter = 1; iter <= Globals->runModelIterations; iter++) { if (progfp == stderr) { if (iter % incr == 0) fprintf(progfp, "."); @@ -201,29 +203,29 @@ int main(int argc, char **argv) { Plot_Initialize(); - RandSeed(Globals.randseed, &environs_rng); - RandSeed(Globals.randseed, &mortality_rng); - RandSeed(Globals.randseed, &resgroups_rng); - RandSeed(Globals.randseed, &species_rng); - RandSeed(Globals.randseed, &grid_rng); - RandSeed(Globals.randseed, &markov_rng); + RandSeed(Globals->randseed, &environs_rng); + RandSeed(Globals->randseed, &mortality_rng); + RandSeed(Globals->randseed, &resgroups_rng); + RandSeed(Globals->randseed, &species_rng); + RandSeed(Globals->randseed, &grid_rng); + RandSeed(Globals->randseed, &markov_rng); - Globals.currIter = iter; + Globals->currIter = iter; if (storeAllIterations) { - SW_OUT_create_iteration_files(Globals.currIter); + SW_OUT_create_iteration_files(Globals->currIter); } if (prepare_IterationSummary) { - print_IterationSummary = (Bool) (Globals.currIter == Globals.runModelIterations); + print_IterationSummary = (Bool) (Globals->currIter == Globals->runModelIterations); } /* ------ Begin running the model ------ */ - for (year = 1; year <= Globals.runModelYears; year++) { + for (year = 1; year <= Globals->runModelYears; year++) { //printf("------------------------Repetition/year = %d / %d\n", iter, year); - Globals.currYear = year; + Globals->currYear = year; rgroup_Establish(); @@ -287,7 +289,7 @@ int main(int argc, char **argv) { // dont need to restart if last iteration finished // this keeps it from re-writing the output folder and overwriting output files - if (Globals.currIter != Globals.runModelIterations) + if (Globals->currIter != Globals->runModelIterations) { // don't reset in last iteration because we need to close files // before clearing/de-allocated SOILWAT2-memory @@ -402,6 +404,14 @@ void Plot_Initialize(void) { SXW_InitPlot(); } +/* Allocates memory for any global variables defined as pointers */ +void allocate_Globals(void){ + Env = (EnvType*) Mem_Calloc(1, sizeof(EnvType), "allocate_Globals: Env"); + Succulent = (SucculentType*) Mem_Calloc(1, sizeof(SucculentType), "allocate_Globals: Succulent"); + Globals = (ModelType*) Mem_Calloc(1, sizeof(ModelType), "allocate_Globals: Globals"); + Plot = (PlotType*) Mem_Calloc(1, sizeof(PlotType), "allocate_Globals: Plot"); +} + /**************************************************************/ static void init_args(int argc, char **argv) { @@ -610,7 +620,7 @@ void check_sizes(const char *chkpt) { if (LT(diff, fabs(spsize - Species[sp]->relsize))) { LogError(stdout, LOGWARN, "%s (%d:%d): SP: \"%s\" size error: " "SP=%.7f, ndv=%.7f", - chkpt, Globals.currIter, Globals.currYear, + chkpt, Globals->currIter, Globals->currYear, Species[sp]->name, Species[sp]->relsize, spsize); } } @@ -618,7 +628,7 @@ void check_sizes(const char *chkpt) { if (LT(diff, fabs(rgsize - RGroup[rg]->relsize))) { LogError(stdout, LOGWARN, "%s (%d:%d): RG \"%s\" size error: " "RG=%.7f, ndv=%.7f", - chkpt, Globals.currIter, Globals.currYear, + chkpt, Globals->currIter, Globals->currYear, RGroup[rg]->name, RGroup[rg]->relsize, rgsize); } } diff --git a/ST_mortality.c b/ST_mortality.c index be0a1e9c..3ba62baa 100644 --- a/ST_mortality.c +++ b/ST_mortality.c @@ -168,14 +168,14 @@ void mort_Main( Bool *killed) { } /* Now implement succulent mortality if this year is "wet" year */ if (g->succulent - && Env.wet_dry == Ppt_Wet - && RandUni(&mortality_rng) <= Succulent.prob_death ) + && Env->wet_dry == Ppt_Wet + && RandUni(&mortality_rng) <= Succulent->prob_death ) _succulents( sp ); /* Finally, implement mortality due to fecal pats, ant mounds, or animal burrows * (disturbances originally conceptualized for the shortgrass steppe that result in * plant mortality */ - switch (Plot.disturbance) { + switch (Plot->disturbance) { case FecalPat: _pat( sp); break; @@ -219,7 +219,7 @@ void mort_EndOfYear(void) { /* Check species index number from the beginning to all the species in * species.in , if the species name == checkname then get the biomass and stop the loop*/ - for (i = 0; i < Globals.sppCount; i++) { /* if species name = checkname = brte then get the biomass of brte(cheatgrass)*/ + for (i = 0; i < Globals->sppCount; i++) { /* if species name = checkname = brte then get the biomass of brte(cheatgrass)*/ if (strcmp(cheatgrass_name, Species[i]->name) == 0) { biomass_cheatgrass = Species_GetBiomass(i); /* calculate biomass of cheatgrass*/ g = RGroup[Species[i]->res_grp]; @@ -241,7 +241,7 @@ void mort_EndOfYear(void) { // in this for loop "g" refers to the RGroup of cheatgrass. RGroup[rg] refers // to the current iteration's RGroup. ForEachGroup(rg) { - if (Globals.currYear < RGroup[rg]->startyr) { + if (Globals->currYear < RGroup[rg]->startyr) { continue; } @@ -271,27 +271,27 @@ void mort_EndOfYear(void) { // If a wildfire occurs this year if (random_number <= fire_possibility) { - RGroup[rg]->killyr = Globals.currYear; + RGroup[rg]->killyr = Globals->currYear; /* Increase the number of wildfires that have occurred across all iterations in this year by 1 */ RGroup[rg]->wildfire = 1; } /* ------------------------- END WILDFIRE BASED ON CHEATGRASS BIOMASS ------------------------- */ - } else if(Globals.currYear >= RGroup[rg]->killfreq_startyr) { // Otherwise simulate prescribed fire + } else if(Globals->currYear >= RGroup[rg]->killfreq_startyr) { // Otherwise simulate prescribed fire if(RGroup[rg]->killfreq < 1){ /* --------------------- STOCHASTIC PRESCRIBED FIRE -------------------- */ if(random_number <= RGroup[rg]->killfreq) { - RGroup[rg]->killyr = Globals.currYear; + RGroup[rg]->killyr = Globals->currYear; /* Increase the number of prescribed fires that have occurred across all iterations in this year by 1 */ RGroup[rg]->prescribedfire = 1; } /* ------------------- END STOCHASTIC PRESCRIBED FIRE ----------------- */ - } else if (((Globals.currYear - RGroup[rg]->killfreq_startyr) % (IntU) RGroup[rg]->killfreq) == 0) { + } else if (((Globals->currYear - RGroup[rg]->killfreq_startyr) % (IntU) RGroup[rg]->killfreq) == 0) { /* ------------------------ PRESCRIBED FIRE AT A FIXED RETURN INTERVAL ----------------------- */ - RGroup[rg]->killyr = Globals.currYear; + RGroup[rg]->killyr = Globals->currYear; /* Calculate the prescribed fire counts */ RGroup[rg]->prescribedfire = 1; /* ------------------------ END PRESCRIBED FIRE AT A FIXED RETURN INTERVAL ------------------- */ @@ -299,18 +299,18 @@ void mort_EndOfYear(void) { } /* Kill all individuals of the functional group and don't let them re-establish */ - if (Globals.currYear == RGroup[rg]->extirp) { + if (Globals->currYear == RGroup[rg]->extirp) { rgroup_Extirpate(rg); /* If the current year is a kill year, implement mortality */ - } else if (Globals.currYear == RGroup[rg]->killyr) { + } else if (Globals->currYear == RGroup[rg]->killyr) { RGroup_Kill(rg); } /* If the current year is a fire year, then remove extra_growth here instead of in _kill_extra_growth called in ST_main.c. Otherwise, biomass will be non-zero in a fire year with complete killing */ - if (Globals.currYear == RGroup[rg]->killyr) { + if (Globals->currYear == RGroup[rg]->killyr) { if (!RGroup[rg]->use_extra_res){ continue; } @@ -348,33 +348,33 @@ void grazing_EndOfYear( void){ IntU grazingyr =0; g = RGroup[rg]; - //printf("inside grazing_EndOfYear() year=%d, rgroupName=%s, grazingfreq_startyr=%d, grazingfreq=%d, proportionGrazing=%f startYear=%d \n",Globals.currYear,g->name,g->grazingfreq_startyr,g->grazingfrq,g->proportion_grazing, RGroup[rg]->startyr); + //printf("inside grazing_EndOfYear() year=%d, rgroupName=%s, grazingfreq_startyr=%d, grazingfreq=%d, proportionGrazing=%f startYear=%d \n",Globals->currYear,g->name,g->grazingfreq_startyr,g->grazingfrq,g->proportion_grazing, RGroup[rg]->startyr); - if (Globals.currYear < RGroup[rg]->startyr) + if (Globals->currYear < RGroup[rg]->startyr) { /* Grazing cannot occur for an RGroup[rg] until the year that RGroup[rg] is turned on */ continue; } - if ((Globals.currYear >=g->grazingfreq_startyr) && (g->grazingfrq > 0)) + if ((Globals->currYear >=g->grazingfreq_startyr) && (g->grazingfrq > 0)) { if (g->grazingfrq < 1.0) { if (RandUni(&mortality_rng) <= g->grazingfrq) { - grazingyr = Globals.currYear; + grazingyr = Globals->currYear; } } - else if (((Globals.currYear - g->grazingfreq_startyr) % (IntU) g->grazingfrq) == 0) + else if (((Globals->currYear - g->grazingfreq_startyr) % (IntU) g->grazingfrq) == 0) { - grazingyr = Globals.currYear; + grazingyr = Globals->currYear; } } //Implement grazing if this year is a year where grazing should occur - if (Globals.currYear == grazingyr) + if (Globals->currYear == grazingyr) { //printf( "currYear is equal to grazingYear so will iterate all the Species for doing grazing, RGroup[g]->est_count =%d \n",RGroup[rg]->est_count); Int i; @@ -384,7 +384,7 @@ void grazing_EndOfYear( void){ { continue; } - //printf( "year=%d calling Species_Proportion_Grazing() rgroupName=%s, est_count =%d,grazingfreq_startyr=%d, grazingfreq=%d, proportionGrazing=%f \n",Globals.currYear,g->name,RGroup[rg]->est_count,g->grazingfreq_startyr,g->grazingfrq,g->proportion_grazing); + //printf( "year=%d calling Species_Proportion_Grazing() rgroupName=%s, est_count =%d,grazingfreq_startyr=%d, grazingfreq=%d, proportionGrazing=%f \n",Globals->currYear,g->name,RGroup[rg]->est_count,g->grazingfreq_startyr,g->grazingfrq,g->proportion_grazing); /* Remove plant biomass to implement grazing using the proportion_grazing specified in inputs */ Species_Proportion_Grazing(RGroup[rg]->est_spp[i],RGroup[rg]->proportion_grazing ); @@ -408,14 +408,14 @@ void proportion_Recovery(void) { ForEachGroup(rg) { - if (Globals.currYear < RGroup[rg]->startyr) { + if (Globals->currYear < RGroup[rg]->startyr) { /* Recovery of biomass after fire cannot occur for an RGroup[rg] until the year * that RGroup[rg] is turned on */ continue; } // Implement recovery of biomass after fire that represents re-sprouting - if (Globals.currYear == RGroup[rg]->killyr) { + if (Globals->currYear == RGroup[rg]->killyr) { Int i; //printf("'before proportion_recovery': Group = %s, relsize = %f, est_count = %d\n", @@ -457,7 +457,7 @@ static void _pat( const SppIndex sp) { /* ---------------------------------------------*/ /* Generate kill list, depending on sensitivity */ /* ---------------------------------------------*/ - if ( Plot.pat_removed) { + if ( Plot->pat_removed) { /* get list of seedlings and annuals*/ ForEachIndiv(p, Species[sp]) { if ( p->age == 1 || Species[sp]->disturbclass == VerySensitive) @@ -562,7 +562,7 @@ static void _succulents( const SppIndex sp) { IndivType *p, *kills[MAX_INDIVS_PER_SPP]; - RealF killamt = Succulent.reduction; + RealF killamt = Succulent->reduction; int i, k=0; ForEachIndiv (p, Species[sp]) { @@ -894,7 +894,7 @@ void _kill_extra_growth(void) { /* Check that extragrowth <= s->relsize, otherwise relsize will become * negative. If not, then reset to s->relsize. If the current year * is a fire year, return, as killing of extragrowth has already occurred in Mort_EndofYear */ - if (!ZERO(Species[sp]->extragrowth) && Globals.currYear != RGroup[rg]->killyr) { + if (!ZERO(Species[sp]->extragrowth) && Globals->currYear != RGroup[rg]->killyr) { Species[sp]->extragrowth = LE(Species[sp]->extragrowth, Species[sp]->relsize) ? Species[sp]->extragrowth : Species[sp]->relsize; // Sets relsize to 0 then sums up all the the individuals' relsizes and adds them back. diff --git a/ST_output.c b/ST_output.c index 9c8476a0..48bc8fe2 100644 --- a/ST_output.c +++ b/ST_output.c @@ -52,7 +52,7 @@ void output_Bmass_Yearly( Int year ) { if (!BmassFlags.yearly) return; - if(Globals.currYear == 1) // At year one we need a header. + if(Globals->currYear == 1) // At year one we need a header. { /* --------- Begin setting up header ------- */ @@ -92,18 +92,18 @@ void output_Bmass_Yearly( Int year ) { } } sprintf(filename, "%s%0*d.csv", Parm_name(F_BMassPre), - Globals.bmass.suffixwidth, - Globals.currIter); - Globals.bmass.fp_year = OpenFile(filename, "a"); + Globals->bmass.suffixwidth, + Globals->currIter); + Globals->bmass.fp_year = OpenFile(filename, "a"); /* Write data line to already opened file */ for (i=0; i< fc-1; i++) { - fprintf(Globals.bmass.fp_year,"%s%c", fields[i], BmassFlags.sep); + fprintf(Globals->bmass.fp_year,"%s%c", fields[i], BmassFlags.sep); } - if (i) fprintf(Globals.bmass.fp_year,"%s\n", fields[i]); - fflush(Globals.bmass.fp_year); - CloseFile(&Globals.bmass.fp_year); + if (i) fprintf(Globals->bmass.fp_year,"%s\n", fields[i]); + fflush(Globals->bmass.fp_year); + CloseFile(&Globals->bmass.fp_year); fc = 0; //reset fc for first line of data. } @@ -114,7 +114,7 @@ void output_Bmass_Yearly( Int year ) { } if (BmassFlags.dist) { - switch (Plot.disturbance) { + switch (Plot->disturbance) { case NoDisturb: strcpy(s, "None"); break; case FecalPat: strcpy(s, "Pat"); break; case AntMound: strcpy(s, "Mound"); break; @@ -125,10 +125,10 @@ void output_Bmass_Yearly( Int year ) { } if (BmassFlags.ppt) - sprintf(fields[fc++], "%d", Env.ppt); + sprintf(fields[fc++], "%d", Env->ppt); if (BmassFlags.pclass) { - switch (Env.wet_dry) { + switch (Env->wet_dry) { case Ppt_Norm: strcpy(s, "Normal"); break; case Ppt_Wet: strcpy(s, "Wet"); break; case Ppt_Dry: strcpy(s, "Dry"); break; @@ -138,7 +138,7 @@ void output_Bmass_Yearly( Int year ) { } if (BmassFlags.tmp) - sprintf(fields[fc++], "%0.1f", Env.temp); + sprintf(fields[fc++], "%0.1f", Env->temp); if (BmassFlags.grpb) { ForEachGroup(rg) { @@ -162,18 +162,18 @@ void output_Bmass_Yearly( Int year ) { } } sprintf(filename, "%s%0*d.csv", Parm_name(F_BMassPre), - Globals.bmass.suffixwidth, - Globals.currIter); - Globals.bmass.fp_year = OpenFile(filename, "a"); + Globals->bmass.suffixwidth, + Globals->currIter); + Globals->bmass.fp_year = OpenFile(filename, "a"); /* Write data line to already opened file */ for (i=0; i< fc-1; i++) { - fprintf(Globals.bmass.fp_year,"%s%c", fields[i], BmassFlags.sep); + fprintf(Globals->bmass.fp_year,"%s%c", fields[i], BmassFlags.sep); } - if (i) fprintf(Globals.bmass.fp_year,"%s\n", fields[i]); - fflush(Globals.bmass.fp_year); - CloseFile(&Globals.bmass.fp_year); + if (i) fprintf(Globals->bmass.fp_year,"%s\n", fields[i]); + fflush(Globals->bmass.fp_year); + CloseFile(&Globals->bmass.fp_year); } @@ -184,9 +184,9 @@ void output_Mort_Yearly( void ) { IntS age, rg, sp; char filename[FILENAME_MAX]; - sprintf(filename, "%s%0*d.csv", Parm_name(F_MortPre), Globals.mort.suffixwidth, Globals.currIter); - Globals.mort.fp_year = OpenFile(filename, "a"); - FILE *f = Globals.mort.fp_year; + sprintf(filename, "%s%0*d.csv", Parm_name(F_MortPre), Globals->mort.suffixwidth, Globals->currIter); + Globals->mort.fp_year = OpenFile(filename, "a"); + FILE *f = Globals->mort.fp_year; if (!MortFlags.yearly) return; @@ -197,7 +197,7 @@ void output_Mort_Yearly( void ) { fprintf(f, "(Estabs)"); if (MortFlags.group) { ForEachGroup(rg) - fprintf(Globals.mort.fp_year, "%c%d", MortFlags.sep, RGroup[rg]->estabs); + fprintf(Globals->mort.fp_year, "%c%d", MortFlags.sep, RGroup[rg]->estabs); } if (MortFlags.species) { ForEachSpecies(sp) @@ -207,7 +207,7 @@ void output_Mort_Yearly( void ) { /* now print the kill data */ - for (age = 0; age < Globals.Max_Age; age++) { + for (age = 0; age < Globals->Max_Age; age++) { fprintf(f, "%d", age + 1); if (MortFlags.group) { ForEachGroup(rg) @@ -234,5 +234,5 @@ void output_Mort_Yearly( void ) { fprintf(f, "\n"); } - CloseFile(&Globals.mort.fp_year); + CloseFile(&Globals->mort.fp_year); } diff --git a/ST_params.c b/ST_params.c index 12c70e05..79659a3b 100644 --- a/ST_params.c +++ b/ST_params.c @@ -49,7 +49,6 @@ SppIndex species_New(void); /*********** Locally Used Function Declarations ************/ /***********************************************************/ -static void _globals_init( void); static void _env_init( void); static void _plot_init( void); static void _setNameLen(char *dest, char *src, Int len); @@ -96,40 +95,40 @@ void parm_Initialize( Int iter) { if (beenhere) { // if (BmassFlags.yearly) { // sprintf(filename, "%s%0*d.csv", Parm_name(F_BMassPre), -// Globals.bmass.suffixwidth, +// Globals->bmass.suffixwidth, // iter); // printf("parm_Initialize: %s\n",filename, filename); -// if (Globals.bmass.fp_year != NULL) { +// if (Globals->bmass.fp_year != NULL) { // LogError(logfp, LOGFATAL, "Programmer error: " -// "Globals.bmass.fp_year not null" +// "Globals->bmass.fp_year not null" // " in parm_Initialize()"); // } -// Globals.bmass.fp_year = OpenFile(filename, "w");//moved to output function -// fprintf(Globals.bmass.fp_year, "%s", Globals.bmass.header_line); -// fflush(Globals.bmass.fp_year); -// CloseFile(&Globals.bmass.fp_year); +// Globals->bmass.fp_year = OpenFile(filename, "w");//moved to output function +// fprintf(Globals->bmass.fp_year, "%s", Globals->bmass.header_line); +// fflush(Globals->bmass.fp_year); +// CloseFile(&Globals->bmass.fp_year); // } // // if (MortFlags.yearly) { // sprintf(filename, "%s%0*d.csv", Parm_name(F_MortPre), -// Globals.mort.suffixwidth, +// Globals->mort.suffixwidth, // iter); -// if (Globals.mort.fp_year != NULL) { +// if (Globals->mort.fp_year != NULL) { // LogError(logfp, LOGFATAL, "Programmer error: " -// "Globals.mort.fp_year not null" +// "Globals->mort.fp_year not null" // " in parm_Initialize()"); // } -// Globals.mort.fp_year = OpenFile(filename, "w"); -// fprintf(Globals.mort.fp_year, "%s", Globals.mort.header_line); -// fflush(Globals.mort.fp_year); -// CloseFile(&Globals.mort.fp_year); +// Globals->mort.fp_year = OpenFile(filename, "w"); +// fprintf(Globals->mort.fp_year, "%s", Globals->mort.header_line); +// fflush(Globals->mort.fp_year); +// CloseFile(&Globals->mort.fp_year); // } } else { - _globals_init(); _files_init(); _model_init(); _env_init(); + _plot_init(); _bmassflags_init(); _mortflags_init(); @@ -172,19 +171,6 @@ void parm_SetName( char *s, int which) { if (_files[which]) Mem_Free( _files[which]); _files[which] = Str_Dup(s); -} - - -/**************************************************************/ -static void _globals_init( void) { -/*======================================================*/ -/* this memset() goes against the mymemory model, but I'm not - * sure of the best approach to take for static vars */ - memset ( &Globals, 0, sizeof(struct globals_st)); - /*Globals.outf = NULL; */ - - - } /**************************************************************/ @@ -225,34 +211,33 @@ static void _files_init( void ) { /**************************************************************/ static void _model_init( void) { /*======================================================*/ - FILE *f; - int seed; + int seed, years; char tmp[80]; MyFileName = Parm_name(F_Model); f = OpenFile(MyFileName, "r"); - /* ----------------------------------------------------*/ /* scan for the first line*/ if (!GetALine(f, inbuf)) { LogError(logfp, LOGFATAL, "%s: No data found!\n", MyFileName); } else { - sscanf( inbuf, "%s %hu %d", + sscanf( inbuf, "%s %d %d", tmp, - &Globals.runModelYears, + &years, &seed); - Globals.Max_Age = Globals.runModelYears; - Globals.runModelIterations = atoi(tmp); - if (Globals.runModelIterations < 1 || - Globals.runModelYears < 1 ) { + Globals->runModelYears = years; + Globals->Max_Age = Globals->runModelYears; + Globals->runModelIterations = atoi(tmp); + if (Globals->runModelIterations < 1 || + Globals->runModelYears < 1 ) { LogError(logfp, LOGFATAL,"Invalid parameters for RunModelIterations " "or RunModelYears (%s)", MyFileName); } - Globals.bmass.suffixwidth = Globals.mort.suffixwidth = strlen(tmp); - Globals.randseed = (IntL) ((seed) ? -abs(seed) : 0); + Globals->bmass.suffixwidth = Globals->mort.suffixwidth = strlen(tmp); + Globals->randseed = (IntL) ((seed) ? -abs(seed) : 0); } CloseFile(&f); @@ -280,46 +265,46 @@ static void _env_init( void) { switch(++index) { case 1: x=sscanf( inbuf, "%f %f %hu %hu %hu %hu %f %hu", - &Globals.ppt.avg, &Globals.ppt.std, - &Globals.ppt.min, &Globals.ppt.max, - &Globals.ppt.dry, &Globals.ppt.wet, - &Globals.gsppt_prop, &Globals.transp_window); + &Globals->ppt.avg, &Globals->ppt.std, + &Globals->ppt.min, &Globals->ppt.max, + &Globals->ppt.dry, &Globals->ppt.wet, + &Globals->gsppt_prop, &Globals->transp_window); nitems = 8; break; case 2: x=sscanf( inbuf, "%f %f %f %f", - &Globals.temp.avg, &Globals.temp.std, - &Globals.temp.min, &Globals.temp.max); + &Globals->temp.avg, &Globals->temp.std, + &Globals->temp.min, &Globals->temp.max); nitems = 4; break; case 3: x=sscanf( inbuf, "%d %f %f %f %f ", &use[0], - &Globals.pat.occur, &Globals.pat.removal, - &Globals.pat.recol[Slope], - &Globals.pat.recol[Intcpt]); + &Globals->pat.occur, &Globals->pat.removal, + &Globals->pat.recol[Slope], + &Globals->pat.recol[Intcpt]); nitems = 4; break; case 4: x=sscanf( inbuf, "%d %f %hu %hu", &use[1], - &Globals.mound.occur, - &Globals.mound.minyr, - &Globals.mound.maxyr); + &Globals->mound.occur, + &Globals->mound.minyr, + &Globals->mound.maxyr); nitems = 3; break; case 5: x=sscanf( inbuf, "%d %f %hu", &use[2], - &Globals.burrow.occur, - &Globals.burrow.minyr); + &Globals->burrow.occur, + &Globals->burrow.minyr); nitems = 2; break; case 6: x=sscanf( inbuf, "%f %f %f %f %f %f", - &Globals.tempparm[CoolSeason][0], - &Globals.tempparm[CoolSeason][1], - &Globals.tempparm[CoolSeason][2], - &Globals.tempparm[WarmSeason][0], - &Globals.tempparm[WarmSeason][1], - &Globals.tempparm[WarmSeason][2]); + &Globals->tempparm[CoolSeason][0], + &Globals->tempparm[CoolSeason][1], + &Globals->tempparm[CoolSeason][2], + &Globals->tempparm[WarmSeason][0], + &Globals->tempparm[WarmSeason][1], + &Globals->tempparm[WarmSeason][2]); nitems = 6; break; } @@ -330,9 +315,9 @@ static void _env_init( void) { } /* end while*/ - Globals.pat.use = itob(use[0]); - Globals.mound.use = itob(use[1]); - Globals.burrow.use = itob(use[2]); + Globals->pat.use = itob(use[0]); + Globals->mound.use = itob(use[1]); + Globals->burrow.use = itob(use[2]); CloseFile(&f); } @@ -354,7 +339,7 @@ static void _plot_init( void) { LogError(logfp, LOGFATAL, "%s: No data found!\n", MyFileName); } - x = sscanf( inbuf, " %f", &Globals.plotsize); + x = sscanf( inbuf, " %f", &Globals->plotsize); if (x < nitems) { LogError(logfp, LOGFATAL, "%s: Incorrect number of fields", MyFileName); @@ -380,7 +365,7 @@ static void _check_species( void) { */ IntS i, cnt, maxage, minage, /* placeholders */ - runyrs = Globals.runModelYears; /* shorthand */ + runyrs = Globals->runModelYears; /* shorthand */ SppIndex sp; GrpIndex rg; Bool tripped = FALSE; @@ -464,7 +449,7 @@ static void _check_species( void) { RGroup[rg]->max_age = (Species[sp]->max_age) ? max(Species[sp]->max_age, RGroup[rg]->max_age) - : Globals.Max_Age; + : Globals->Max_Age; } RGroup[rg]->kills = (IntUS *) Mem_Calloc(GrpMaxAge(rg), sizeof(IntUS), @@ -627,7 +612,7 @@ static void _bmassflags_init( void) { /**************************************************************/ ///*======================================================*/ -///* Writes to Globals.header */ +///* Writes to Globals->header */ /* static void _bmasshdr_init( void) { char fields[MAX_OUTFIELDS][MAX_FIELDLEN+1]; @@ -675,10 +660,10 @@ static void _bmasshdr_init( void) { // Put header line in global variable for (i=0; i< fc-1; i++) { sprintf(inbuf,"%s%c", fields[i], BmassFlags.sep); - strcat(Globals.bmass.header_line, inbuf); + strcat(Globals->bmass.header_line, inbuf); } sprintf(inbuf,"%s\n", fields[i]); - strcat(Globals.bmass.header_line, inbuf); + strcat(Globals->bmass.header_line, inbuf); } */ @@ -790,7 +775,7 @@ static void _mortflags_init( void) { /**************************************************************/ /*======================================================*/ -/* Writes to Globals.header */ +/* Writes to Globals->header */ /* static void _morthdr_create( void) { @@ -814,10 +799,10 @@ static void _morthdr_create( void) { // Put header line in global variable for (i=0; i< fc-1; i++) { sprintf(inbuf,"%s%c", fields[i], MortFlags.sep); - strcat(Globals.mort.header_line, inbuf); + strcat(Globals->mort.header_line, inbuf); } sprintf(inbuf,"%s\n", fields[i]); - strcat(Globals.mort.header_line, inbuf); + strcat(Globals->mort.header_line, inbuf); } */ @@ -968,7 +953,7 @@ static void _rgroup_add1( char name[], RealF space, RealF density, RGroup[rg]->max_stretch = (IntS) stretch; RGroup[rg]->max_spp_estab = (IntS) estab; RGroup[rg]->max_density = density; - RGroup[rg]->max_per_sqm = density / Globals.plotsize; + RGroup[rg]->max_per_sqm = density / Globals->plotsize; RGroup[rg]->use_mort = itob(mort); RGroup[rg]->slowrate = slow; RGroup[rg]->min_res_req = space; @@ -1067,10 +1052,10 @@ static void _rgroup_addsucculent( char name[], MyFileName, name2); } RGroup[rg]->succulent = TRUE; - Succulent.growth[Slope] = wslope; - Succulent.growth[Intcpt] = wint; - Succulent.mort[Slope] = dslope; - Succulent.mort[Intcpt] = dint; + Succulent->growth[Slope] = wslope; + Succulent->growth[Intcpt] = wint; + Succulent->mort[Slope] = dslope; + Succulent->mort[Intcpt] = dint; } /**************************************************************/ @@ -1168,7 +1153,7 @@ static void _species_init( void) { Species[sp]->received_prob = 0; Species[sp]->cohort_surv = cohort; Species[sp]->var = var; - Species[sp]->pseed = pseed / Globals.plotsize; + Species[sp]->pseed = pseed / Globals->plotsize; /* Species[sp]->ann_mort_prob = (age > 0) ? -log(cohort)/age : 0.0; diff --git a/ST_resgroups.c b/ST_resgroups.c index 34bb1d7e..41a979cd 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -201,13 +201,13 @@ static void _add_annual_seedprod(SppIndex sp, RealF lastyear_relsize) { * that can establish. Otherwise, this year's seed production is a function * of the number of seeds produced per unit biomass multiplied by species biomass * (maximum species biomass * last year's species relative size). */ - if (Globals.currYear == 1) { + if (Globals->currYear == 1) { s->seedprod[0] = RandUniIntRange(1, s->max_seed_estab, &resgroups_rng); //printf("Species name=%s ,currYear =1 so new calculated value s->seedprod[%u]= %hu , s->max_seed_estab =%hu\n", s->name, i, s->seedprod[i], s->max_seed_estab); } else { s->seedprod[0] = (IntU) (s->pseed * s->mature_biomass * lastyear_relsize); - //printf("Species name=%s ,currYear=%hu so new calculated value s->seedprod[%u]= %hu , s->max_seed_estab =%hu, lastyear_relsize=%.5f\n", s->name, Globals.currYear, i, s->seedprod[i], s->max_seed_estab, lastyear_relsize); + //printf("Species name=%s ,currYear=%hu so new calculated value s->seedprod[%u]= %hu , s->max_seed_estab =%hu, lastyear_relsize=%.5f\n", s->name, Globals->currYear, i, s->seedprod[i], s->max_seed_estab, lastyear_relsize); } } @@ -445,7 +445,7 @@ void rgroup_Grow(void) { continue; /* Succulents can't grow if it is a wet year, so skip */ - if (g->succulent && Env.wet_dry == Ppt_Wet) + if (g->succulent && Env->wet_dry == Ppt_Wet) continue; /* Increment size of each individual in response to normal resources */ @@ -458,7 +458,7 @@ void rgroup_Grow(void) { /* Modify growth rate by temperature calculated in Env_Generate() */ if (s->tempclass != NoSeason) - tgmod = Env.temp_reduction[s->tempclass]; + tgmod = Env->temp_reduction[s->tempclass]; /* Now increase size of the individual plants of current species */ ForEachIndiv(ndv, s) { @@ -611,7 +611,7 @@ void rgroup_Establish(void) { GroupType *g; /* Cannot establish if plot is still in disturbed state*/ - if (Plot.disturbed > 0) { + if (Plot->disturbed > 0) { ForEachGroup(rg) RGroup[rg]->regen_ok = FALSE; return; /* skip regen for all */ @@ -625,7 +625,7 @@ void rgroup_Establish(void) { g->regen_ok = TRUE; /* default */ - if (Globals.currYear < RGroup[rg]->startyr) { + if (Globals->currYear < RGroup[rg]->startyr) { g->regen_ok = FALSE; } else ///if ( g->max_age == 1 ) { @@ -634,7 +634,7 @@ void rgroup_Establish(void) { /// if ( LT(g->killfreq, 1.0) ) { /// if (RandUni(&resgroups_rng) <= g->killfreq) /// g->regen_ok = FALSE; - /// } else if ( (Globals.currYear - g->startyr) % (IntU)g->killfreq == 0) { + /// } else if ( (Globals->currYear - g->startyr) % (IntU)g->killfreq == 0) { /// g->regen_ok = FALSE; /// } /// } @@ -652,7 +652,7 @@ void rgroup_Establish(void) { /* Establishment for species that belong to annual functional groups*/ if (Species[sp]->max_age == 1) { - //printf("Globals.currYear = %hu, call to _add_annuals sp=%d Species[sp]->lastyear_relsize : %.5f \n", Globals.currYear, sp, Species[sp]->lastyear_relsize); + //printf("Globals->currYear = %hu, call to _add_annuals sp=%d Species[sp]->lastyear_relsize : %.5f \n", Globals->currYear, sp, Species[sp]->lastyear_relsize); num_est = _add_annuals(rg, sp, Species[sp]->lastyear_relsize); // printf("g->seedbank annuals=%d \n",g->seedbank); } @@ -664,7 +664,7 @@ void rgroup_Establish(void) { if (num_est) { /* printf("%d %d %d %d\n", - Globals.currIter, Globals.currYear, sp, num_est); */ + Globals->currIter, Globals->currYear, sp, num_est); */ Species_Add_Indiv(sp, num_est); species_Update_Estabs(sp, num_est); @@ -707,8 +707,8 @@ void rgroup_IncrAges(void) LogError(logfp, LOGWARN, "%s grown older than max_age (%d > %d). Iter=%d, Year=%d\n", Species[ndv->myspecies]->name, ndv->age, - Species[ndv->myspecies]->max_age, Globals.currIter, - Globals.currYear); + Species[ndv->myspecies]->max_age, Globals->currIter, + Globals->currYear); } } } @@ -889,9 +889,9 @@ GrpIndex RGroup_New(void) /* Chris Bennett @ LTER-CSU 6/15/2000 */ /*------------------------------------------------------*/ - GrpIndex i = (GrpIndex) Globals.grpCount; + GrpIndex i = (GrpIndex) Globals->grpCount; - if (++Globals.grpCount > MAX_RGROUPS) + if (++Globals->grpCount > MAX_RGROUPS) { LogError(logfp, LOGFATAL, "Too many groups specified (>%d)!\n" "You must adjust MAX_RGROUPS and recompile!", diff --git a/ST_species.c b/ST_species.c index 78f935d0..89360ecd 100644 --- a/ST_species.c +++ b/ST_species.c @@ -277,7 +277,7 @@ void Species_Update_Newsize(SppIndex sp, RealF newsize) LogError(logfp, LOGWARN, "Species_Update_Newsize: %s relsize < 0.0 (=%.6f)" " year=%d, iter=%d", Species[sp]->name, - Species[sp]->relsize, Globals.currYear, Globals.currIter); + Species[sp]->relsize, Globals->currYear, Globals->currIter); //printf("Species relsize <0: name=%s, Species[sp]->relsize=%.5f \n ",Species[sp]->name, Species[sp]->relsize); } if (GT(Species[sp]->relsize, 100.)) @@ -285,7 +285,7 @@ void Species_Update_Newsize(SppIndex sp, RealF newsize) LogError(logfp, LOGNOTE, "Species_Update_Newsize: %s relsize very large (=%.1f)" " year=%d, iter=%d", Species[sp]->name, - Species[sp]->relsize, Globals.currYear, Globals.currIter); + Species[sp]->relsize, Globals->currYear, Globals->currIter); } // printf("Inside Species_Update_Newsize() spIndex=%d, name =%s,Species[sp]->relsize=%.5f, newsize=%.5f \n ",sp, Species[sp]->name,Species[sp]->relsize, newsize); @@ -331,9 +331,9 @@ SppIndex species_New(void) /* Chris Bennett @ LTER-CSU 6/15/2000 */ /*------------------------------------------------------*/ - SppIndex i = (SppIndex) Globals.sppCount; + SppIndex i = (SppIndex) Globals->sppCount; - if (++Globals.sppCount > MAX_SPECIES) + if (++Globals->sppCount > MAX_SPECIES) { LogError(logfp, LOGFATAL, "Too many species specified (>%d)!\n" "You must adjust MAX_SPECIES and recompile!\n", @@ -582,10 +582,10 @@ void save_annual_species_relsize() { ForEachSpecies(sp) { if (Species[sp]->max_age == 1) { - //printf("Globals.currYear = %d, sp=%d , Species[sp]->relsize=%.5f ,old value lastyear_relsize : %.5f \n", Globals.currYear, sp, Species[sp]->relsize, Species[sp]->lastyear_relsize); + //printf("Globals->currYear = %d, sp=%d , Species[sp]->relsize=%.5f ,old value lastyear_relsize : %.5f \n", Globals->currYear, sp, Species[sp]->relsize, Species[sp]->lastyear_relsize); Species[sp]->lastyear_relsize = Species[sp]->relsize; //Species[sp]->lastyear_relsize = 2; - //printf("Globals.currYear = %d, sp=%d new updated value lastyear_relsize : %.5f \n", Globals.currYear, sp, Species[sp]->lastyear_relsize); + //printf("Globals->currYear = %d, sp=%d new updated value lastyear_relsize : %.5f \n", Globals->currYear, sp, Species[sp]->lastyear_relsize); } } } diff --git a/ST_sql.c b/ST_sql.c index fdc474e8..30d0124f 100644 --- a/ST_sql.c +++ b/ST_sql.c @@ -109,7 +109,7 @@ static void finalizeStatements() { } void insertIndivKill(int IndivID, int KillTypeID) { - sqlite3_bind_int(stmt_IndivKill, 1, Globals.currYear); + sqlite3_bind_int(stmt_IndivKill, 1, Globals->currYear); sqlite3_bind_int(stmt_IndivKill, 2, KillTypeID); sqlite3_bind_int(stmt_IndivKill, 3, IndivID); @@ -142,7 +142,7 @@ static void insertIndivYearInfoRow(int Year, int IndivID, int MortalityTypeID, i void insertIndivYearInfo(IndivType *ind) { //Take off of age because this happens after rgroup_IncrAges remove if you put before. - insertIndivYearInfoRow(Globals.currYear, ind->id, ind->killedby, (ind->age - 1), ind->mm_extra_res, ind->slow_yrs, ind->yrs_neg_pr, ind->killed, ind->relsize, ind->grp_res_prop, ind->res_required, ind->res_avail, ind->res_extra, ind->pr, ind->growthrate, ind->prob_veggrow); + insertIndivYearInfoRow(Globals->currYear, ind->id, ind->killedby, (ind->age - 1), ind->mm_extra_res, ind->slow_yrs, ind->yrs_neg_pr, ind->killed, ind->relsize, ind->grp_res_prop, ind->res_required, ind->res_avail, ind->res_extra, ind->pr, ind->growthrate, ind->prob_veggrow); } static void insertIndivRow(int IndivID, int Iteration, int CreatedYear, int SpeciesID, int RGroupID) { @@ -157,7 +157,7 @@ static void insertIndivRow(int IndivID, int Iteration, int CreatedYear, int Spec } void insertIndiv(IndivType *ind) { - insertIndivRow(ind->id, Globals.currIter, Globals.currYear, ind->myspecies+1, Species[ind->myspecies]->res_grp+1); + insertIndivRow(ind->id, Globals->currIter, Globals->currYear, ind->myspecies+1, Species[ind->myspecies]->res_grp+1); } static void insertSpeciesYearInfoRow(int Year, int Iteration, int SpeciesID, int EstabCount, int Estabs, float RelSize, float ExtraGrowth, float ReceivedProb, int AllowGrowth, int sdSGerm) { @@ -179,7 +179,7 @@ static void insertSpeciesYearInfoRow(int Year, int Iteration, int SpeciesID, int void insertSpecieYearInfo(SppIndex s) { SpeciesType *sp = Species[s]; - insertSpeciesYearInfoRow(Globals.currYear, Globals.currIter, s+1, sp->est_count, sp->estabs, sp->relsize, sp->extragrowth, sp->received_prob, sp->allow_growth, sp->sd_sgerm); + insertSpeciesYearInfoRow(Globals->currYear, Globals->currIter, s+1, sp->est_count, sp->estabs, sp->relsize, sp->extragrowth, sp->received_prob, sp->allow_growth, sp->sd_sgerm); } static void insertRGroupYearInfoRow(int Year, int Iteration, int RGroupID, int Estabs, int KillYr, int YrsNegPR, float mmExtraRes, float ResRequired, float ResAvail, float ResExtra, float PR, float RelSize, int EstSppCount, int Extirpated, int RegenOk) { @@ -206,7 +206,7 @@ static void insertRGroupYearInfoRow(int Year, int Iteration, int RGroupID, int E void insertRGroupYearInfo(GrpIndex g) { GroupType *rg = RGroup[g]; - insertRGroupYearInfoRow(Globals.currYear, Globals.currIter, g+1, rg->estabs, rg->killyr, rg->yrs_neg_pr, rg->mm_extra_res, rg->res_required, rg->res_avail, rg->res_extra, rg->pr, rg->relsize, rg->est_count, rg->extirpated, rg->regen_ok); + insertRGroupYearInfoRow(Globals->currYear, Globals->currIter, g+1, rg->estabs, rg->killyr, rg->yrs_neg_pr, rg->mm_extra_res, rg->res_required, rg->res_avail, rg->res_extra, rg->pr, rg->relsize, rg->est_count, rg->extirpated, rg->regen_ok); } static void insertRgroups(void) { @@ -267,8 +267,8 @@ static void insertInfo(void) { beginTransaction(); sprintf(sql, "INSERT INTO info (Years, Iterations, Seed, RGroups, Species, PlotSize) VALUES (%d, %d, %d, %d, %d, %f);", - Globals.runModelYears, Globals.runModelIterations, (int) Globals.randseed, - Globals.grpCount, Globals.sppCount, Globals.plotsize); + Globals->runModelYears, Globals->runModelIterations, (int) Globals->randseed, + Globals->grpCount, Globals->sppCount, Globals->plotsize); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); endTransaction(); diff --git a/ST_stats.c b/ST_stats.c index 39cc2efd..5d38eaf2 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -135,14 +135,14 @@ void stat_Collect( Int year ) { } year--; - if (BmassFlags.dist && Plot.disturbed) + if (BmassFlags.dist && Plot->disturbed) _Dist.s[year].nobs++; if (BmassFlags.ppt) - _collect_add( &_Ppt.s[year], Env.ppt); + _collect_add( &_Ppt.s[year], Env->ppt); if (BmassFlags.tmp) - _collect_add( &_Temp.s[year], Env.temp); + _collect_add( &_Temp.s[year], Env->temp); if (BmassFlags.grpb) { if (BmassFlags.wildfire) { @@ -204,77 +204,77 @@ static void _init( void) { if (BmassFlags.dist) _Dist_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Dist)"); if (BmassFlags.ppt) _Ppt_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(PPT)"); if (BmassFlags.tmp) _Temp_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Temp)"); if (BmassFlags.grpb) { _Grp_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals.grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Grp)"); + Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Grp)"); ForEachGroup(rg) _Grp_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Grp[rg].s)"); + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Grp[rg].s)"); if (BmassFlags.size) { _Gsize_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals.grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(GSize)"); + Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(GSize)"); ForEachGroup(rg) _Gsize_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(GSize[rg].s)"); + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(GSize[rg].s)"); } if (BmassFlags.pr) { _Gpr_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals.grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpr)"); + Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpr)"); ForEachGroup(rg) _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpr[rg].s)"); + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpr[rg].s)"); } if (BmassFlags.wildfire) { _Gpr_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals.grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gwf)"); + Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gwf)"); ForEachGroup(rg) _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gwf[rg].s)"); + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gwf[rg].s)"); } if (BmassFlags.prescribedfire) { _Gpr_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals.grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpf)"); + Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpf)"); ForEachGroup(rg) _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpf[rg].s)"); + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpf[rg].s)"); } } if (BmassFlags.sppb) { _Spp_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals.sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Spp)"); + Mem_Calloc( Globals->sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Spp)"); ForEachSpecies(sp) _Spp_grid_cell[sp].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Spp[sp].s)"); + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Spp[sp].s)"); if (BmassFlags.indv) { _Indv_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals.sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Indv)"); + Mem_Calloc( Globals->sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Indv)"); ForEachSpecies(sp) _Indv_grid_cell[sp].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Indv[sp].s)"); + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Indv[sp].s)"); } } @@ -282,49 +282,49 @@ static void _init( void) { if (BmassFlags.dist) _Dist.s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Dist)"); if (BmassFlags.ppt) _Ppt.s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(PPT)"); if (BmassFlags.tmp) _Temp.s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Temp)"); if (BmassFlags.grpb) { _Grp = (struct stat_st *) - Mem_Calloc( Globals.grpCount, + Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), "_stat_init(Grp)"); ForEachGroup(rg) _Grp[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Grp[rg].s)"); if (BmassFlags.size) { _Gsize = (struct stat_st *) - Mem_Calloc( Globals.grpCount, + Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), "_stat_init(GSize)"); ForEachGroup(rg) _Gsize[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(GSize[rg].s)"); } if (BmassFlags.pr) { _Gpr = (struct stat_st *) - Mem_Calloc( Globals.grpCount, + Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), "_stat_init(Gpr)"); ForEachGroup(rg) _Gpr[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Gpr[rg].s)"); } @@ -337,7 +337,7 @@ static void _init( void) { _Gwf->wildfire = (int *) Mem_Calloc( 1, - sizeof(int) * Globals.runModelYears, + sizeof(int) * Globals->runModelYears, "_stat_init(Gwf->wildfire)"); _Gwf->prescribedFire = (int **) @@ -347,8 +347,8 @@ static void _init( void) { ForEachGroup(rg){ _Gwf->prescribedFire[rg] = (int *) - Mem_Calloc( Globals.runModelYears, - sizeof(int) * Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, + sizeof(int) * Globals->runModelYears, "_stat_init(Gwf->prescribedFire)"); } } @@ -357,7 +357,7 @@ static void _init( void) { if (MortFlags.group) { _Gestab = (struct stat_st *) - Mem_Calloc( Globals.grpCount, + Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), "_stat_init(Gestab)"); ForEachGroup(rg) @@ -366,7 +366,7 @@ static void _init( void) { "_stat_init(Gestab[rg].s)"); _Gmort = (struct stat_st *) - Mem_Calloc( Globals.grpCount, + Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), "_stat_init(Gmort)"); ForEachGroup(rg) @@ -378,30 +378,30 @@ static void _init( void) { if (BmassFlags.sppb) { _Spp = (struct stat_st *) - Mem_Calloc( Globals.sppCount, + Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "_stat_init(Spp)"); ForEachSpecies(sp) _Spp[sp].s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Spp[sp].s)"); if (BmassFlags.indv) { _Indv = (struct stat_st *) - Mem_Calloc( Globals.sppCount, + Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "_stat_init(Indv)"); ForEachSpecies(sp) _Indv[sp].s = (struct accumulators_st *) - Mem_Calloc( Globals.runModelYears, + Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Indv[sp].s)"); } } if (MortFlags.species) { _Sestab = (struct stat_st *) - Mem_Calloc( Globals.sppCount, + Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "_stat_init(Sestab)"); ForEachSpecies(sp) @@ -410,7 +410,7 @@ static void _init( void) { "_stat_init(Sestab[sp].s)"); _Smort = (struct stat_st *) - Mem_Calloc( Globals.sppCount, + Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "_stat_init(Smort)"); ForEachSpecies(sp) @@ -421,9 +421,9 @@ static void _init( void) { } if (UseSeedDispersal && UseGrid) { - _Sreceived = Mem_Calloc( Globals.sppCount, sizeof(struct stat_st), "_stat_init(Sreceived)"); + _Sreceived = Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "_stat_init(Sreceived)"); ForEachSpecies(sp) { - _Sreceived[sp].s = (struct accumulators_st *)Mem_Calloc( Globals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Sreceived[sp].s)"); + _Sreceived[sp].s = (struct accumulators_st *)Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Sreceived[sp].s)"); _Sreceived[sp].name = &Species[sp]->name[0]; } } @@ -450,24 +450,24 @@ static void _init( void) { /***********************************************************/ void stat_Init_Accumulators( void ) { //allocates memory for all of the grid accumulators - grid_Stat = Mem_Calloc(Globals.nCells, sizeof(accumulators_grid_st), "stat_Init_Accumulators()"); + grid_Stat = Mem_Calloc(Globals->nCells, sizeof(accumulators_grid_st), "stat_Init_Accumulators()"); int i, j; - for( i = 0; i < Globals.nCells; i++) { - if (BmassFlags.dist) grid_Stat[i].dist = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.ppt) grid_Stat[i].ppt = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.tmp) grid_Stat[i].temp = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + for( i = 0; i < Globals->nCells; i++) { + if (BmassFlags.dist) grid_Stat[i].dist = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.ppt) grid_Stat[i].ppt = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.tmp) grid_Stat[i].temp = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); if (BmassFlags.grpb) { - grid_Stat[i].grp1 = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); // gave grp and gpr numbers attached to them so I wouldn't mix them up lol... bad (confusing) variable names on part of the original creator. - if (BmassFlags.size) grid_Stat[i].gsize = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.pr) grid_Stat[i].gpr2 = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if (BmassFlags.wildfire) grid_Stat[i].gwf2 = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if (BmassFlags.prescribedfire) grid_Stat[i].gpf2 = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].grp1 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); // gave grp and gpr numbers attached to them so I wouldn't mix them up lol... bad (confusing) variable names on part of the original creator. + if (BmassFlags.size) grid_Stat[i].gsize = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.pr) grid_Stat[i].gpr2 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + if (BmassFlags.wildfire) grid_Stat[i].gwf2 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + if (BmassFlags.prescribedfire) grid_Stat[i].gpf2 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); } if (MortFlags.group) { - grid_Stat[i].gmort = Mem_Calloc(Globals.grpCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - grid_Stat[i].gestab = Mem_Calloc(Globals.grpCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].gmort = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].gestab = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); GrpIndex gp; ForEachGroup(gp) { grid_Stat[i].gmort[gp] = Mem_Calloc(GrpMaxAge(gp), sizeof(struct accumulators_st), "stat_Init_Accumulators()"); @@ -475,12 +475,12 @@ void stat_Init_Accumulators( void ) { } } if(BmassFlags.sppb) { - grid_Stat[i].spp = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if(BmassFlags.indv) grid_Stat[i].indv = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].spp = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + if(BmassFlags.indv) grid_Stat[i].indv = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); } if (MortFlags.species) { - grid_Stat[i].smort = Mem_Calloc(Globals.sppCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - grid_Stat[i].sestab = Mem_Calloc(Globals.sppCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].smort = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].sestab = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); SppIndex sp; ForEachSpecies(sp) { grid_Stat[i].smort[sp] = Mem_Calloc(SppMaxAge(sp), sizeof(struct accumulators_st), "stat_Init_Accumulators()"); @@ -489,23 +489,23 @@ void stat_Init_Accumulators( void ) { } if(UseSeedDispersal && UseGrid) - grid_Stat[i].sreceived = Mem_Calloc(Globals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].sreceived = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - for( j = 0; j < Globals.runModelYears; j++) { + for( j = 0; j < Globals->runModelYears; j++) { if (BmassFlags.grpb) { - grid_Stat[i].grp1[j] = Mem_Calloc(Globals.grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.size) grid_Stat[i].gsize[j] = Mem_Calloc(Globals.grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.pr) grid_Stat[i].gpr2[j] = Mem_Calloc(Globals.grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.wildfire) grid_Stat[i].gwf2[j] = Mem_Calloc(Globals.grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.prescribedfire) grid_Stat[i].gpf2[j] = Mem_Calloc(Globals.grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + grid_Stat[i].grp1[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.size) grid_Stat[i].gsize[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.pr) grid_Stat[i].gpr2[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.wildfire) grid_Stat[i].gwf2[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.prescribedfire) grid_Stat[i].gpf2[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); } if(BmassFlags.sppb) { - grid_Stat[i].spp[j] = Mem_Calloc(Globals.sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if(BmassFlags.indv) grid_Stat[i].indv[j] = Mem_Calloc(Globals.sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + grid_Stat[i].spp[j] = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if(BmassFlags.indv) grid_Stat[i].indv[j] = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); } if(UseSeedDispersal && UseGrid) - grid_Stat[i].sreceived[j] = Mem_Calloc(Globals.sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + grid_Stat[i].sreceived[j] = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); } } } @@ -639,8 +639,8 @@ void stat_Free_Accumulators( void ) { //frees all the memory allocated in stat_init_Accumulators() int i, j; - for( i = 0; i < Globals.nCells; i++) { - for( j = 0; j < Globals.runModelYears; j++) { + for( i = 0; i < Globals->nCells; i++) { + for( j = 0; j < Globals->runModelYears; j++) { if(BmassFlags.grpb) { Mem_Free(grid_Stat[i].grp1[j]); if (BmassFlags.size) Mem_Free(grid_Stat[i].gsize[j]); @@ -807,7 +807,7 @@ void stat_Collect_SMort ( void ) { /***********************************************************/ void stat_Output_YrMorts( void ) { - FILE *f = Globals.mort.fp_year; + FILE *f = Globals->mort.fp_year; IntS age; GrpIndex rg; SppIndex sp; @@ -838,7 +838,7 @@ void stat_Output_YrMorts( void ) { fprintf(f,"\n"); /* print one line of kill frequencies per age */ - for(age=0; age < Globals.Max_Age; age++) { + for(age=0; age < Globals->Max_Age; age++) { fprintf(f,"%d", age+1); if (MortFlags.group) { ForEachGroup(rg){ @@ -898,7 +898,7 @@ void stat_Output_AllMorts( void) { fprintf(f,"\n"); /* print one line of kill frequencies per age */ - for(age=0; age < Globals.Max_Age; age++) { + for(age=0; age < Globals->Max_Age; age++) { fprintf(f,"%d", age+1); if (MortFlags.group) { ForEachGroup(rg) @@ -940,7 +940,7 @@ void stat_Output_AllBmassAvg() { fprintf(f, "%s", buf); } - for( yr=1; yr<= Globals.runModelYears; yr++) { + for( yr=1; yr<= Globals->runModelYears; yr++) { *buf = '\0'; if (BmassFlags.yr) sprintf(buf, "%d%c", yr, sep); @@ -1065,7 +1065,7 @@ void stat_Output_AllCellAvgBmass(const char * filename) fprintf(f, "%s", buf); } - for (yr = 1; yr <= Globals.runModelYears; yr++) + for (yr = 1; yr <= Globals->runModelYears; yr++) { *buf = '\0'; @@ -1180,7 +1180,7 @@ void stat_Output_AllBmass(void) { fprintf(f, "%s", buf); } - for( yr=1; yr<= Globals.runModelYears; yr++) { + for( yr=1; yr<= Globals->runModelYears; yr++) { *buf = '\0'; if (BmassFlags.yr) sprintf(buf, "%d%c", yr, sep); @@ -1246,7 +1246,7 @@ void stat_Output_AllBmass(void) { if (BmassFlags.sppb) { - for ((sp) = 0; (sp) < Globals.sppCount - 1; (sp)++) + for ((sp) = 0; (sp) < Globals->sppCount - 1; (sp)++) { sprintf(tbuf, "%f%c", _get_avg(&_Spp[sp].s[yr - 1]), sep); strcat(buf, tbuf); @@ -1300,7 +1300,7 @@ void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool make fprintf(f,"\n"); } - for( yr=1; yr<= Globals.runModelYears; yr++) { + for( yr=1; yr<= Globals->runModelYears; yr++) { *buf = '\0'; sprintf(buf, "%d%c", yr, sep); @@ -1340,15 +1340,15 @@ static void copyStruct(RealF val,RealF std_val,struct accumulators_grid_cell_st static RealF _get_gridcell_avg(struct accumulators_grid_cell_st *p) { - if (Globals.nCells == 0) + if (Globals->nCells == 0) return 0.0; - RealF avg = (RealF) (p->sum / (double) Globals.nCells); + RealF avg = (RealF) (p->sum / (double) Globals->nCells); return avg; } static int _get_gridcell_sum(struct accumulators_grid_cell_st *p) { - if (Globals.nCells == 0) + if (Globals->nCells == 0) return 0; int sum = (RealF) (p->sum); return sum; @@ -1358,9 +1358,9 @@ static int _get_gridcell_sum(struct accumulators_grid_cell_st *p) /***********************************************************/ static RealF _get_gridcell_std(struct accumulators_grid_cell_st *p) { - if (Globals.nCells == 0) + if (Globals->nCells == 0) return 0.0; - RealF avg = (RealF) (p->sum_std / (double) Globals.nCells); + RealF avg = (RealF) (p->sum_std / (double) Globals->nCells); return avg; } diff --git a/sxw.c b/sxw.c index 7cc38901..857201b2 100644 --- a/sxw.c +++ b/sxw.c @@ -149,7 +149,7 @@ void SXW_Init( Bool init_SW, char *f_roots ) { */ char roots[MAX_FILENAMESIZE] = { '\0' }; -RandSeed(Globals.randseed, &resource_rng); +RandSeed(Globals->randseed, &resource_rng); #ifdef SXW_BYMAXSIZE GrpIndex rg; SppIndex sp; @@ -166,7 +166,7 @@ RandSeed(Globals.randseed, &resource_rng); _sxwfiles[3] = &SXW.f_prod; _sxwfiles[4] = &SXW.f_watin; - SXW.NGrps = Globals.grpCount; + SXW.NGrps = Globals->grpCount; _read_files(); if(f_roots != NULL) { @@ -200,8 +200,8 @@ RandSeed(Globals.randseed, &resource_rng); SXW.NSoLyrs = SW_Site.n_layers; printf("Number of layers: %d\n", SW_Site.n_layers); - printf("Number of iterations: %d\n", Globals.runModelIterations); - printf("Number of years: %d\n", Globals.runModelYears); + printf("Number of iterations: %d\n", Globals->runModelIterations); + printf("Number of years: %d\n", Globals->runModelYears); _make_arrays(); @@ -483,7 +483,7 @@ static void _read_roots_max(void) { } } - if (cnt < Globals.grpCount) { + if (cnt < Globals->grpCount) { LogError(logfp, LOGFATAL, "%s: Not enough valid groups found.", MyFileName); } @@ -524,7 +524,7 @@ static void _read_phen(void) { } - if (cnt < Globals.grpCount) { + if (cnt < Globals->grpCount) { LogError(logfp, LOGFATAL, "%s: Not enough valid groups found.", MyFileName); } @@ -617,7 +617,7 @@ static void _read_prod(void) { break; } - if (cnt < Globals.grpCount) { + if (cnt < Globals->grpCount) { LogError(logfp, LOGFATAL, "%s: Not enough valid groups found.", MyFileName); } @@ -652,7 +652,7 @@ static void _read_prod(void) { break; } - if (cnt < Globals.grpCount) { + if (cnt < Globals->grpCount) { LogError(logfp, LOGFATAL, "%s: Not enough valid groups found.", MyFileName); } @@ -910,7 +910,7 @@ void _print_debuginfo(void) { } fprintf(f, "\n================== %d =============================\n", SW_Model.year); - fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env.ppt, Env.temp, SXW.aet, sum, transp_window.added_transp, sum + transp_window.added_transp); + fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env->ppt, Env->temp, SXW.aet, sum, transp_window.added_transp, sum + transp_window.added_transp); fprintf(f, "Group \tRelsize\tPR\tResource_cur\tResource_cur\n"); fprintf(f, "----- \t-------\t-----\t-no scaling-\t-with scaling-\n"); diff --git a/sxw_environs.c b/sxw_environs.c index afa3713f..479c8e34 100644 --- a/sxw_environs.c +++ b/sxw_environs.c @@ -37,7 +37,7 @@ extern SW_MODEL SW_Model; extern SW_SOILWAT SW_Soilwat; extern SW_WEATHER SW_Weather; -extern EnvType Env; +extern EnvType *Env; /*************** Local Variable Declarations ***************/ /***********************************************************/ @@ -55,8 +55,8 @@ void _sxw_set_environs(void) { * need to convert ppt from cm to mm */ //Integer conversion always does floor so .5 is added - Env.ppt = (IntS) (SXW.ppt * 10 + .5); - Env.temp = SXW.temp; + Env->ppt = (IntS) (SXW.ppt * 10 + .5); + Env->temp = SXW.temp; } diff --git a/sxw_resource.c b/sxw_resource.c index 4f92e4f9..ecab8867 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -77,7 +77,7 @@ void _sxw_root_phen(void) { GrpIndex g; TimeInt p; - for (y = 0; y < (Globals.grpCount * SXW.NPds * SXW.NTrLyrs); y++) + for (y = 0; y < (Globals->grpCount * SXW.NPds * SXW.NTrLyrs); y++) SXWResources._rootsXphen[y] = 0; ForEachGroup(g) @@ -219,15 +219,15 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { // if there are multiple iterations the last year will run twice; // once for data and once for tear down. The second "last year" is // equivalent to year 0. - if(Globals.currYear == 0 || Globals.currYear == transp_window.lastYear) { + if(Globals->currYear == 0 || Globals->currYear == transp_window.lastYear) { transp_window.average = 0; transp_window.ratio_average = 0; transp_window.sum_of_sqrs = 0; - if(Globals.transp_window > MAX_WINDOW){ - LogError(logfp, LOGNOTE, "sxw_resource: Transp_window specified in inputs is greater than maximum window.\nInput: %d\nMaximum: %d\nSetting window to %d.\n",Globals.transp_window, MAX_WINDOW,MAX_WINDOW); - Globals.transp_window = MAX_WINDOW; + if(Globals->transp_window > MAX_WINDOW){ + LogError(logfp, LOGNOTE, "sxw_resource: Transp_window specified in inputs is greater than maximum window.\nInput: %d\nMaximum: %d\nSetting window to %d.\n",Globals->transp_window, MAX_WINDOW,MAX_WINDOW); + Globals->transp_window = MAX_WINDOW; } - transp_window.size = Globals.transp_window; + transp_window.size = Globals->transp_window; transp_window.oldest_index = 0; return; //no point calculating anything since SOILWAT hasn't run } @@ -287,18 +287,18 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { // Determines if the current year transpiration/ppt is greater than 1 standard deviations away // from the mean. If TRUE, add additional transpiration. - if(transp_window.size >= Globals.currYear) //we need to do a running average + if(transp_window.size >= Globals->currYear) //we need to do a running average { // add transpiration to the window transp_window.transp[transp_window.oldest_index] = sumTranspTotal; //update the average - transp_window.average = get_running_mean(Globals.currYear,transp_window.average, sumTranspTotal); + transp_window.average = get_running_mean(Globals->currYear,transp_window.average, sumTranspTotal); //add the ratio value to the window transp_window.ratios[transp_window.oldest_index] = transp_ratio; //save the last mean. we will need it to calculate the sum of squares RealF last_ratio = transp_window.ratio_average; //calculate the running mean - transp_window.ratio_average = get_running_mean(Globals.currYear,transp_window.ratio_average,transp_ratio); + transp_window.ratio_average = get_running_mean(Globals->currYear,transp_window.ratio_average,transp_ratio); //calculate the running sum of squares RealF ssqr = get_running_sqr(last_ratio, transp_window.ratio_average, transp_ratio); //add the calculated sum of squares to the running total @@ -306,7 +306,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { //add the calculated sum of squares to the array transp_window.SoS_array[transp_window.oldest_index] = ssqr; //calculate the standard deviation - transp_ratio_sd = final_running_sd(Globals.currYear, transp_window.sum_of_sqrs); + transp_ratio_sd = final_running_sd(Globals->currYear, transp_window.sum_of_sqrs); } else { //we need to do a moving window //add the new value, subtract the old value from the average; @@ -327,12 +327,12 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { transp_ratio_sd = final_running_sd(transp_window.size, transp_window.sum_of_sqrs); } - //printf("Year %d: ratio = %f, mean = %f, sos = %f sd = %f\n",Globals.currYear, + //printf("Year %d: ratio = %f, mean = %f, sos = %f sd = %f\n",Globals->currYear, // transp_ratio,transp_window.ratio_average, transp_window.sum_of_sqrs, transp_ratio_sd); // If this year's transpiration is notably low (1 sd below the mean), add additional transpired water if (transp_ratio < (transp_window.ratio_average - 1 * transp_ratio_sd)) { - //printf("Year %d below 1 sd: ratio = %f, average = %f, sd = %f\n", Globals.currYear,transp_ratio, + //printf("Year %d below 1 sd: ratio = %f, average = %f, sd = %f\n", Globals->currYear,transp_ratio, //transp_window.ratio_average, transp_ratio_sd); RealF min = transp_window.ratio_average - transp_ratio_sd; RealF max = transp_window.ratio_average + transp_ratio_sd; @@ -342,7 +342,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { if(transp_window.added_transp < 0){ LogError(logfp, LOGNOTE, "sxw_resource: Added transpiration less than 0.\n"); } - //printf("Year %d:\tTranspiration to add: %f\n",Globals.currYear,add_transp); + //printf("Year %d:\tTranspiration to add: %f\n",Globals->currYear,add_transp); //printf("TranspRemaining: %f\tTranspRemaining+add_transp: %f\n",TranspRemaining,add_transp+TranspRemaining); /* -------------------- Recalculate the window including added_transp in the current year -------------------- */ @@ -363,7 +363,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { // replace the sum of squares with what we just calculated transp_window.SoS_array[transp_window.oldest_index] = ssqr; - //printf("Year %d: ratio = %f, mean = %f, sos = %f\n",Globals.currYear, + //printf("Year %d: ratio = %f, mean = %f, sos = %f\n",Globals->currYear, //transp_ratio+added_transp_ratio,transp_window.ratio_average, transp_window.sum_of_sqrs); /* Adds the additional transpiration to the remaining transpiration @@ -387,5 +387,5 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { } //remember the last year. When setting up for a new iteration the same year will appear twice, and we want to skip it the second time - transp_window.lastYear = Globals.currYear; + transp_window.lastYear = Globals->currYear; } diff --git a/sxw_soilwat.c b/sxw_soilwat.c index 981d7ba6..79c19555 100644 --- a/sxw_soilwat.c +++ b/sxw_soilwat.c @@ -100,7 +100,7 @@ void _sxw_sw_setup (RealF sizes[]) { void _sxw_sw_run(void) { /*======================================================*/ - SW_Model.year = SW_Model.startyr + Globals.currYear-1; + SW_Model.year = SW_Model.startyr + Globals->currYear-1; SW_CTL_run_current_year(); } @@ -223,7 +223,7 @@ static void _update_productivity(void) { /* get total biomass for the plot in sq.m */ ForEachGroup(g) { RGroup[g]->rgroupFractionOfVegTypeBiomass = 0.0; - bmassg[g] = Biomass(g) / Globals.plotsize; + bmassg[g] = Biomass(g) / Globals->plotsize; totbmass += bmassg[g]; if (1 == RGroup[g]->veg_prod_type) { //tree vegTypeBiomass[0] += bmassg[g]; diff --git a/sxw_sql.c b/sxw_sql.c index 6173fd00..0112abcf 100644 --- a/sxw_sql.c +++ b/sxw_sql.c @@ -154,7 +154,7 @@ void insertInfo() { beginTransaction(); sprintf(sql, "INSERT INTO info (StartYear, Years, Iterations, RGroups, TranspirationLayers, SoilLayers, PlotSize, BVT) VALUES (%d, %d, %d, %d, %d, %d, %f, %f);", - SW_Model.startyr, Globals.runModelYears, Globals.runModelIterations, Globals.grpCount, SXW.NTrLyrs, SXW.NSoLyrs, Globals.plotsize, SXWResources._bvt); + SW_Model.startyr, Globals->runModelYears, Globals->runModelIterations, Globals->grpCount, SXW.NTrLyrs, SXW.NSoLyrs, Globals->plotsize, SXWResources._bvt); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); endTransaction(); @@ -215,7 +215,7 @@ static void insertSXWinputVarsRow(int year, int iter, double fracGrass, double f void insertInputVars() { int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; SW_VEGPROD *v = &SW_VegProd; beginTransaction(); @@ -248,7 +248,7 @@ static void insertSXWinputProdRow(int year, int iter, int VegProdType, int Month void insertInputProd() { int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; int p; SW_VEGPROD *v = &SW_VegProd; @@ -286,7 +286,7 @@ static void insertSXWinputSoilsRow(int year, int iter, int Layer, double Tree_tr void insertInputSoils() { int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; int l; SW_SITE *s = &SW_Site; @@ -326,7 +326,7 @@ static void insertSXWoutputVarsRow(int year, int iter, int MAP_mm, double MAT_C, void insertOutputVars(RealF * _resource_cur, RealF added_transp) { int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; int p; int t; int r; @@ -348,7 +348,7 @@ void insertOutputVars(RealF * _resource_cur, RealF added_transp) { sum3 += _resource_cur[r]; } beginTransaction(); - insertSXWoutputVarsRow(Year, Iteration, Env.ppt, Env.temp, SXW.aet, sum, added_transp, sum+added_transp, sum1,sum2,sum3); + insertSXWoutputVarsRow(Year, Iteration, Env->ppt, Env->temp, SXW.aet, sum, added_transp, sum+added_transp, sum1,sum2,sum3); endTransaction(); } @@ -377,7 +377,7 @@ static void insertSXWoutputRgroupRow(int year, int iter, int RGroupID, double Bi void insertRgroupInfo(RealF * _resource_cur) { int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; int r; beginTransaction(); @@ -400,7 +400,7 @@ static void insertSXWoutputProdRow(int year, int iter, int Month, double BMass, void insertOutputProd(SW_VEGPROD *v) { int p; int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; beginTransaction(); int doy = 1; @@ -491,7 +491,7 @@ void insertRootsSum(RealD * _roots_active_sum) { int i; double m[12]; int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; beginTransaction(); for(i=1; i<=4; i++) { @@ -545,7 +545,7 @@ void insertRootsRelative(RealD * _roots_active_rel) { int nLyrs; double m[12]; int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; beginTransaction(); ForEachGroup(g) @@ -599,7 +599,7 @@ void insertTranspiration() { int p; double m[12]; int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; beginTransaction(); //Total - 0 @@ -681,7 +681,7 @@ void insertSWCBulk() { int p; double m[12]; int Year = SW_Model.year; - int Iteration = Globals.currIter; + int Iteration = Globals->currIter; beginTransaction(); for (l = 0; l < SXW.NSoLyrs; l++) { From 6429ee2f327b060c22d9b47d6422168e3f90357a Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 15 Apr 2019 12:30:50 -0600 Subject: [PATCH 011/167] Issue #271 added dealloc_Globals() function to be called at the end of the program --- ST_main.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ST_main.c b/ST_main.c index 33ae46b6..a340e1a8 100644 --- a/ST_main.c +++ b/ST_main.c @@ -87,6 +87,7 @@ SW_FILE_STATUS SW_File_Status; /***********************************************************/ void Plot_Initialize( void); void allocate_Globals(void); +void deallocate_Globals(void); static void usage(void) { char *s ="STEPPE plant community dynamics (SGS-LTER Jan-04).\n" @@ -317,6 +318,8 @@ int main(int argc, char **argv) { SW_CTL_clear_model(TRUE); // de-allocate all memory free_all_sxw_memory(); + deallocate_Globals(); + printf("\nend program\n"); fprintf(progfp, "\n"); @@ -412,6 +415,12 @@ void allocate_Globals(void){ Plot = (PlotType*) Mem_Calloc(1, sizeof(PlotType), "allocate_Globals: Plot"); } +void deallocate_Globals(void){ + Mem_Free(Env); + Mem_Free(Succulent); + Mem_Free(Globals); + Mem_Free(Plot); +} /**************************************************************/ static void init_args(int argc, char **argv) { From 5384d06cb06b26ee94be3496a363c06688205921 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 17 Apr 2019 10:26:30 -0600 Subject: [PATCH 012/167] issue #271 move SOILWAT head to my branch --- sw_src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sw_src b/sw_src index 7f9e519f..28f5cfad 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit 7f9e519fdaa3fa9cad91ffdd75ebb3498c223c94 +Subproject commit 28f5cfad846e4eb6bbb8ef51daf1cf59b801c47c From daac9e6d9589cade367dcb7070e35d3d471787ac Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 18 Apr 2019 14:52:30 -0600 Subject: [PATCH 013/167] Created allocate_gridCells and load_cell functions (issue #272 and #273) allocate_gridCells allocates memory for the 2d gridCells array. load_cell moves the Global variables to point to gridCells[row][col]'s fields. I still need to figure out how to load the SXW variables and Stats variables since they aren't globals. Neither of these functions are implemented yet. --- ST_grid.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index e76f912b..4970db89 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -196,6 +196,8 @@ EnvType *grid_Env, *spinup_Env; PlotType *grid_Plot, *spinup_Plot; ModelType *grid_Globals, *spinup_Globals; +CellType** gridCells; + // these two variables are for storing SXW variables... also dynamically allocated/freed SXW_t *grid_SXW, *spinup_SXW; Grid_SXW_St *grid_SXW_ptrs, *spinup_SXW_ptrs; @@ -311,6 +313,7 @@ static void _init_SXW_inputs(Bool init_SW, char *f_roots); static void _init_stepwat_inputs(void); static void _init_grid_globals(void); static void _init_spinup_globals(void); +static void allocate_gridCells(int rows, int cols); static void _load_grid_globals(void); static void _load_spinup_globals(void); static void _free_grid_memory(void); @@ -318,6 +321,7 @@ static void _free_spinup_memory(void); static void _free_grid_globals(void); static void _free_spinup_globals(void); static void _load_cell(int row, int col, int year, Bool useAccumulators); +static void load_cell(int row, int col); static void _load_spinup_cell(int cell); static void _save_cell(int row, int col, int year, Bool useAccumulators); static void _save_spinup_cell(int cell); @@ -442,6 +446,7 @@ void runGrid(void) Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; _init_grid_inputs();// reads the grid inputs in & initializes the global grid variables + allocate_gridCells(grid_Rows, grid_Cols); if (sd_Option2a || sd_Option2b) _run_spinup(); // does the initial spinup @@ -850,6 +855,15 @@ static void _init_stepwat_inputs(void) ChDir(".."); // goes back to the folder that we were in } +/* Allocates memory for the grid cells. This only needs to be called once. */ +static void allocate_gridCells(int rows, int cols){ + int i; + gridCells = (CellType**) Mem_Calloc(rows, sizeof(CellType*), "allocate_gridCells: rows"); + for(i = 0; i < rows; ++i){ + gridCells[i] = (CellType*) Mem_Calloc(cols, sizeof(CellType), "allocate_gridCells: columns"); + } +} + /***********************************************************/ static IndivType* _create_empty_indv(void) { @@ -1625,6 +1639,34 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) grid_SXW_ptrs[cell].prod_pctlive); } +/* load gridCells[row][col] into the globals variables */ +static void load_cell(int row, int col){ + /* These are commented out until the clean_code_lowpriority + * branch is merged into this branch + RGroup = &gridCells[row][col].myGroup; + Species = &gridCells[row][col].mySpecies; + */ + + /* Succulents corresponding to this cell */ + Succulent = &gridCells[row][col].mySucculent; + + /* This cell's environment. We expect each cell to + * have slightly different weather each year */ + Env = &gridCells[row][col].myEnvironment; + + /* Cell's plot data */ + Plot = &gridCells[row][col].myPlot; + + /* Global variables corresponding to this cell */ + Globals = &gridCells[row][col].myGlobals; + + /* If TRUE this cell should use seed dispersal */ + UseSeedDispersal = gridCells[row][col].useSeedDispersal; + + /* TRUE if this cell is in spinup mode */ + DuringSpinup = gridCells[row][col].duringSpinup; +} + /***********************************************************/ static void _load_spinup_cell(int cell) { From f8f507e62487c18eba7b027da687cb9e6cbfa0b0 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 18 Apr 2019 17:04:00 -0600 Subject: [PATCH 014/167] Changed _Ppt, _Dist, _Temp to pointers (issue #275) These variables are now pointers that are dynamically allocated at run time. This changes nothing in non-gridded mode, but will make gridded mode capable of shallow copying it's data. --- ST_stats.c | 75 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 30 deletions(-) diff --git a/ST_stats.c b/ST_stats.c index 5d38eaf2..3bc321ef 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -64,7 +64,7 @@ /************************ Local Structure Defs *************/ /***********************************************************/ -StatType _Dist, _Ppt, _Temp, +StatType *_Dist, *_Ppt, *_Temp, *_Grp, *_Gsize, *_Gpr, *_Gmort, *_Gestab, *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; @@ -136,13 +136,13 @@ void stat_Collect( Int year ) { year--; if (BmassFlags.dist && Plot->disturbed) - _Dist.s[year].nobs++; + _Dist->s[year].nobs++; if (BmassFlags.ppt) - _collect_add( &_Ppt.s[year], Env->ppt); + _collect_add( &_Ppt->s[year], Env->ppt); if (BmassFlags.tmp) - _collect_add( &_Temp.s[year], Env->temp); + _collect_add( &_Temp->s[year], Env->temp); if (BmassFlags.grpb) { if (BmassFlags.wildfire) { @@ -280,21 +280,27 @@ static void _init( void) { } - if (BmassFlags.dist) - _Dist.s = (struct accumulators_st *) + if (BmassFlags.dist) { + _Dist = (StatType*) Mem_Calloc(1, sizeof(StatType), "_stat_init(Dist)"); + _Dist->s = (struct accumulators_st *) Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Dist)"); - if (BmassFlags.ppt) - _Ppt.s = (struct accumulators_st *) + } + if (BmassFlags.ppt) { + _Ppt = (StatType*) Mem_Calloc(1, sizeof(StatType), "_stat_init(PPT"); + _Ppt->s = (struct accumulators_st *) Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(PPT)"); - if (BmassFlags.tmp) - _Temp.s = (struct accumulators_st *) + } + if (BmassFlags.tmp) { + _Temp = (StatType*) Mem_Calloc(1, sizeof(StatType), "_stat_init(Temp)"); + _Temp->s = (struct accumulators_st *) Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Temp)"); + } if (BmassFlags.grpb) { _Grp = (struct stat_st *) Mem_Calloc( Globals->grpCount, @@ -544,9 +550,9 @@ void stat_Load_Accumulators(int cell, int year) { } } - if (BmassFlags.tmp) _copy_over(&_Temp.s[yr], &grid_Stat[cell].temp[yr]); - if (BmassFlags.ppt) _copy_over(&_Ppt.s[yr], &grid_Stat[cell].ppt[yr]); - if (BmassFlags.dist) _copy_over(&_Dist.s[yr], &grid_Stat[cell].dist[yr]); + if (BmassFlags.tmp) _copy_over(&_Temp->s[yr], &grid_Stat[cell].temp[yr]); + if (BmassFlags.ppt) _copy_over(&_Ppt->s[yr], &grid_Stat[cell].ppt[yr]); + if (BmassFlags.dist) _copy_over(&_Dist->s[yr], &grid_Stat[cell].dist[yr]); if(BmassFlags.grpb) { GrpIndex c; @@ -605,9 +611,9 @@ void stat_Save_Accumulators(int cell, int year) { } } - if (BmassFlags.tmp) _copy_over(&grid_Stat[cell].temp[yr], &_Temp.s[yr]); - if (BmassFlags.ppt) _copy_over(&grid_Stat[cell].ppt[yr], &_Ppt.s[yr]); - if (BmassFlags.dist) _copy_over(&grid_Stat[cell].dist[yr], &_Dist.s[yr]); + if (BmassFlags.tmp) _copy_over(&grid_Stat[cell].temp[yr], &_Temp->s[yr]); + if (BmassFlags.ppt) _copy_over(&grid_Stat[cell].ppt[yr], &_Ppt->s[yr]); + if (BmassFlags.dist) _copy_over(&grid_Stat[cell].dist[yr], &_Dist->s[yr]); if(BmassFlags.grpb) { GrpIndex c; @@ -720,9 +726,18 @@ void stat_free_mem( void ) { Mem_Free(_Gwf->prescribedFire); } - if (BmassFlags.dist) Mem_Free(_Dist.s); - if (BmassFlags.ppt) Mem_Free(_Ppt.s); - if (BmassFlags.tmp) Mem_Free(_Temp.s); + if (BmassFlags.dist) { + Mem_Free(_Dist->s); + Mem_Free(_Dist); + } + if (BmassFlags.ppt) { + Mem_Free(_Ppt->s); + Mem_Free(_Ppt); + } + if (BmassFlags.tmp) { + Mem_Free(_Temp->s); + Mem_Free(_Temp); + } if(BmassFlags.grpb) { Mem_Free(_Grp); @@ -946,15 +961,15 @@ void stat_Output_AllBmassAvg() { sprintf(buf, "%d%c", yr, sep); if (BmassFlags.dist) { - sprintf(tbuf, "%ld%c", _Dist.s[yr-1].nobs, sep); - _Dist_grid_cell.s[yr-1].nobs = _Dist.s[yr-1].nobs; + sprintf(tbuf, "%ld%c", _Dist->s[yr-1].nobs, sep); + _Dist_grid_cell.s[yr-1].nobs = _Dist->s[yr-1].nobs; strcat(buf, tbuf); } if (BmassFlags.ppt) { - RealF avg = _get_avg(&_Ppt.s[yr - 1]); - RealF std = _get_std(&_Ppt.s[yr - 1]); + RealF avg = _get_avg(&_Ppt->s[yr - 1]); + RealF std = _get_std(&_Ppt->s[yr - 1]); sprintf(tbuf, "%f%c%f%c", avg, sep, std, sep); copyStruct(avg, std, &_Ppt_grid_cell.s[yr - 1]); strcat(buf, tbuf); @@ -968,8 +983,8 @@ void stat_Output_AllBmassAvg() { if (BmassFlags.tmp) { - RealF avg = _get_avg(&_Temp.s[yr - 1]); - RealF std = _get_std(&_Temp.s[yr - 1]); + RealF avg = _get_avg(&_Temp->s[yr - 1]); + RealF std = _get_std(&_Temp->s[yr - 1]); sprintf(tbuf, "%f%c%f%c", avg, sep, std, sep); copyStruct(avg,std, &_Temp_grid_cell.s[yr - 1]); strcat(buf, tbuf); @@ -1186,15 +1201,15 @@ void stat_Output_AllBmass(void) { sprintf(buf, "%d%c", yr, sep); if (BmassFlags.dist) { - sprintf(tbuf, "%ld%c", _Dist.s[yr-1].nobs, + sprintf(tbuf, "%ld%c", _Dist->s[yr-1].nobs, sep); strcat(buf, tbuf); } if (BmassFlags.ppt) { sprintf(tbuf, "%f%c%f%c", - _get_avg(&_Ppt.s[yr-1]), sep, - _get_std(&_Ppt.s[yr-1]), sep); + _get_avg(&_Ppt->s[yr-1]), sep, + _get_std(&_Ppt->s[yr-1]), sep); strcat( buf, tbuf); } @@ -1205,8 +1220,8 @@ void stat_Output_AllBmass(void) { if (BmassFlags.tmp) { sprintf(tbuf, "%f%c%f%c", - _get_avg(&_Temp.s[yr-1]), sep, - _get_std(&_Temp.s[yr-1]), sep); + _get_avg(&_Temp->s[yr-1]), sep, + _get_std(&_Temp->s[yr-1]), sep); strcat( buf, tbuf); } From 382f7beede91017dc538700a487094c20c724404 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sun, 21 Apr 2019 18:18:12 -0600 Subject: [PATCH 015/167] (issue #274) created stat_Copy_Accumulators function This new function allows us to shallow copy accumulators even though accumulators aren't global variables. To achieve this the new function takes pointers to the location of the accumulators that we want to copy. --- ST_stats.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/ST_stats.c b/ST_stats.c index 3bc321ef..9b715c41 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -62,6 +62,10 @@ void stat_Free_Accumulators( void ); void stat_Init_Accumulators( void ); + void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, + StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, + StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); + /************************ Local Structure Defs *************/ /***********************************************************/ StatType *_Dist, *_Ppt, *_Temp, @@ -700,6 +704,30 @@ void stat_Free_Accumulators( void ) { stat_free_mem(); } +/* Shallow copies StatType and FireStatsType pointers to the local pointers. + This is intended to be used with gridded mode to load in a given cell */ +void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, + StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, + StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime){ + + /* Move the local pointers to the location of the given pointers */ + _Dist = newDist; + _Ppt = newPpt; + _Temp = newTemp; + _Grp = newGrp; + _Gsize = newGsize; + _Gpr = newGpr; + _Gmort = newGmort; + _Gestab = newGestab; + _Spp = newSpp; + _Indv = newIndv; + _Smort = newSmort; + _Sestab = newSestab; + _Sreceived = newSrecieved; + _Gwf = newGwf; + firsttime = firstTime; +} + /***********************************************************/ void stat_free_mem( void ) { //frees memory allocated in this module From d6b2a138cb4047660f86e532a833f9c711ed28d0 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 23 Apr 2019 15:24:16 -0600 Subject: [PATCH 016/167] (issue #278) Made transp_window a pointer To accomplish this I created a new function in sxw.c called _allocate_memory which should be called once per iteration. This not only changes tranps_window to a pointer, but also the arrays inside on transp_window. This ensures that we can easily reassign memory. --- sxw.c | 27 ++++++++++++-- sxw.h | 6 ++-- sxw_resource.c | 95 ++++++++++++++++++++++++-------------------------- 3 files changed, 72 insertions(+), 56 deletions(-) diff --git a/sxw.c b/sxw.c index 857201b2..1984b850 100644 --- a/sxw.c +++ b/sxw.c @@ -89,7 +89,7 @@ extern Bool storeAllIterations; */ // Window of transpiration used by _transp_contribution_by_group() in sxw_resource.c // "Window" refers to the number of years over which transpiration data is averaged. -transp_t transp_window; +transp_t* transp_window; pcg32_random_t resource_rng; //rng for swx_resource.c functions. SXW_resourceType SXWResources; @@ -110,6 +110,7 @@ static TimeInt _debugyrs[100], _debugyrs_cnt; /*************** Local Function Declarations ***************/ /***********************************************************/ +static void _allocate_memory(void); static void _read_files( void ); static void _read_roots_max(void); static void _read_phen(void); @@ -151,6 +152,9 @@ void SXW_Init( Bool init_SW, char *f_roots ) { RandSeed(Globals->randseed, &resource_rng); +/* Allocate memory for all local pointers */ +_allocate_memory(); + #ifdef SXW_BYMAXSIZE GrpIndex rg; SppIndex sp; /* Sum each group's maximum biomass */ @@ -415,7 +419,7 @@ void SXW_PrintDebug(Bool cleanup) { insertInputVars(); insertInputProd(); insertInputSoils(); - insertOutputVars(SXWResources._resource_cur, transp_window.added_transp); + insertOutputVars(SXWResources._resource_cur, transp_window->added_transp); insertRgroupInfo(SXWResources._resource_cur); insertOutputProd(&SW_VegProd); insertRootsSum(SXWResources._roots_active_sum); @@ -425,6 +429,23 @@ void SXW_PrintDebug(Bool cleanup) { } } +/* Allocate memory for sxw local variables. This should only be called once per simulation. */ +static void _allocate_memory(void){ + transp_window = (transp_t*) Mem_Calloc(1, sizeof(transp_t), "_allocate_memory: transp_window"); + + /* Set the size of our transpiration window. */ + if(Globals->transp_window > MAX_WINDOW){ + LogError(logfp, LOGWARN, "Requested transp_window (%d) > %d. Setting transp_window to %d.", + Globals->transp_window, MAX_WINDOW, MAX_WINDOW); + transp_window->size = MAX_WINDOW; + } else { + transp_window->size = Globals->transp_window; + } + + transp_window->ratios = (RealF*) Mem_Calloc(transp_window->size, sizeof(RealF), "_allocate_memory: transp_window->ratios"); + transp_window->transp = (RealF*) Mem_Calloc(transp_window->size, sizeof(RealF), "_allocate_memory: transp_window->transp"); + transp_window->SoS_array = (RealF*) Mem_Calloc(transp_window->size, sizeof(RealF), "_allocate_memory: transp_window->SoS_array"); +} static void _read_files( void ) { /*======================================================*/ @@ -910,7 +931,7 @@ void _print_debuginfo(void) { } fprintf(f, "\n================== %d =============================\n", SW_Model.year); - fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env->ppt, Env->temp, SXW.aet, sum, transp_window.added_transp, sum + transp_window.added_transp); + fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env->ppt, Env->temp, SXW.aet, sum, transp_window->added_transp, sum + transp_window->added_transp); fprintf(f, "Group \tRelsize\tPR\tResource_cur\tResource_cur\n"); fprintf(f, "----- \t-------\t-----\t-no scaling-\t-with scaling-\n"); diff --git a/sxw.h b/sxw.h index f4a69c93..1c424f61 100644 --- a/sxw.h +++ b/sxw.h @@ -106,14 +106,14 @@ struct transp_data { // ratios[] stores (transpiration/precipitation) values. It is used to keep track of // what value needs to be removed from the moving average. - RealF ratios[MAX_WINDOW]; // transp/ppt + RealF* ratios; // transp/ppt // transp[] stores transpiration values. It is used to keep track of what value needs to be // removed from the moving ratio_average. - RealF transp[MAX_WINDOW]; // transp + RealF* transp; // transp //SoS_array[] stores the sum of squares values (xi - mean)^2 for the previous (size) iterations. - RealF SoS_array[MAX_WINDOW]; //(xi - mean)^2 + RealF* SoS_array; //(xi - mean)^2 // Amount of additional transpiration added for the current year RealF added_transp; diff --git a/sxw_resource.c b/sxw_resource.c index ecab8867..e261d720 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -51,7 +51,7 @@ extern SXW_resourceType SXWResources; /* ------ Running Averages ------ */ extern - transp_t transp_window; + transp_t* transp_window; extern pcg32_random_t resource_rng; @@ -212,23 +212,18 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { RealD *transp; RealF sumUsedByGroup = 0., sumTranspTotal = 0., TranspRemaining = 0.; RealF transp_ratio; - transp_window.added_transp = 0; + transp_window->added_transp = 0; RealF transp_ratio_sd; // year 0 is a set up year. No need to calculate transpiration. // if there are multiple iterations the last year will run twice; // once for data and once for tear down. The second "last year" is // equivalent to year 0. - if(Globals->currYear == 0 || Globals->currYear == transp_window.lastYear) { - transp_window.average = 0; - transp_window.ratio_average = 0; - transp_window.sum_of_sqrs = 0; - if(Globals->transp_window > MAX_WINDOW){ - LogError(logfp, LOGNOTE, "sxw_resource: Transp_window specified in inputs is greater than maximum window.\nInput: %d\nMaximum: %d\nSetting window to %d.\n",Globals->transp_window, MAX_WINDOW,MAX_WINDOW); - Globals->transp_window = MAX_WINDOW; - } - transp_window.size = Globals->transp_window; - transp_window.oldest_index = 0; + if(Globals->currYear == 0 || Globals->currYear == transp_window->lastYear) { + transp_window->average = 0; + transp_window->ratio_average = 0; + transp_window->sum_of_sqrs = 0; + transp_window->oldest_index = 0; return; //no point calculating anything since SOILWAT hasn't run } @@ -287,92 +282,92 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { // Determines if the current year transpiration/ppt is greater than 1 standard deviations away // from the mean. If TRUE, add additional transpiration. - if(transp_window.size >= Globals->currYear) //we need to do a running average + if(transp_window->size >= Globals->currYear) //we need to do a running average { // add transpiration to the window - transp_window.transp[transp_window.oldest_index] = sumTranspTotal; + transp_window->transp[transp_window->oldest_index] = sumTranspTotal; //update the average - transp_window.average = get_running_mean(Globals->currYear,transp_window.average, sumTranspTotal); + transp_window->average = get_running_mean(Globals->currYear,transp_window->average, sumTranspTotal); //add the ratio value to the window - transp_window.ratios[transp_window.oldest_index] = transp_ratio; + transp_window->ratios[transp_window->oldest_index] = transp_ratio; //save the last mean. we will need it to calculate the sum of squares - RealF last_ratio = transp_window.ratio_average; + RealF last_ratio = transp_window->ratio_average; //calculate the running mean - transp_window.ratio_average = get_running_mean(Globals->currYear,transp_window.ratio_average,transp_ratio); + transp_window->ratio_average = get_running_mean(Globals->currYear,transp_window->ratio_average,transp_ratio); //calculate the running sum of squares - RealF ssqr = get_running_sqr(last_ratio, transp_window.ratio_average, transp_ratio); + RealF ssqr = get_running_sqr(last_ratio, transp_window->ratio_average, transp_ratio); //add the calculated sum of squares to the running total - transp_window.sum_of_sqrs += ssqr; + transp_window->sum_of_sqrs += ssqr; //add the calculated sum of squares to the array - transp_window.SoS_array[transp_window.oldest_index] = ssqr; + transp_window->SoS_array[transp_window->oldest_index] = ssqr; //calculate the standard deviation - transp_ratio_sd = final_running_sd(Globals->currYear, transp_window.sum_of_sqrs); + transp_ratio_sd = final_running_sd(Globals->currYear, transp_window->sum_of_sqrs); } else { //we need to do a moving window //add the new value, subtract the old value from the average; - transp_window.average += (sumTranspTotal - transp_window.transp[transp_window.oldest_index])/transp_window.size; + transp_window->average += (sumTranspTotal - transp_window->transp[transp_window->oldest_index])/transp_window->size; //add the new value, subtract the old value from the ratio average; - transp_window.ratio_average += (transp_ratio - transp_window.ratios[transp_window.oldest_index])/transp_window.size; + transp_window->ratio_average += (transp_ratio - transp_window->ratios[transp_window->oldest_index])/transp_window->size; //put the new transpiration in the window - transp_window.transp[transp_window.oldest_index] = sumTranspTotal; + transp_window->transp[transp_window->oldest_index] = sumTranspTotal; //put the new ratio in the window - transp_window.ratios[transp_window.oldest_index] = transp_ratio; + transp_window->ratios[transp_window->oldest_index] = transp_ratio; // calculate the new sum of squares value - RealF ssqr = (transp_ratio - transp_window.ratio_average) * (transp_ratio - transp_window.ratio_average); + RealF ssqr = (transp_ratio - transp_window->ratio_average) * (transp_ratio - transp_window->ratio_average); // add the new sum of squares, subtract the old. - transp_window.sum_of_sqrs += ssqr - transp_window.SoS_array[transp_window.oldest_index]; + transp_window->sum_of_sqrs += ssqr - transp_window->SoS_array[transp_window->oldest_index]; // update the sum of squares window. - transp_window.SoS_array[transp_window.oldest_index] = ssqr; + transp_window->SoS_array[transp_window->oldest_index] = ssqr; //calculate the standard deviation - transp_ratio_sd = final_running_sd(transp_window.size, transp_window.sum_of_sqrs); + transp_ratio_sd = final_running_sd(transp_window->size, transp_window->sum_of_sqrs); } //printf("Year %d: ratio = %f, mean = %f, sos = %f sd = %f\n",Globals->currYear, - // transp_ratio,transp_window.ratio_average, transp_window.sum_of_sqrs, transp_ratio_sd); + // transp_ratio,transp_window->ratio_average, transp_window->sum_of_sqrs, transp_ratio_sd); // If this year's transpiration is notably low (1 sd below the mean), add additional transpired water - if (transp_ratio < (transp_window.ratio_average - 1 * transp_ratio_sd)) { + if (transp_ratio < (transp_window->ratio_average - 1 * transp_ratio_sd)) { //printf("Year %d below 1 sd: ratio = %f, average = %f, sd = %f\n", Globals->currYear,transp_ratio, - //transp_window.ratio_average, transp_ratio_sd); - RealF min = transp_window.ratio_average - transp_ratio_sd; - RealF max = transp_window.ratio_average + transp_ratio_sd; + //transp_window->ratio_average, transp_ratio_sd); + RealF min = transp_window->ratio_average - transp_ratio_sd; + RealF max = transp_window->ratio_average + transp_ratio_sd; // This transpiration will be added - transp_window.added_transp = (1 - transp_ratio / RandUniFloatRange(min, max, &resource_rng)) * transp_window.average; - if(transp_window.added_transp < 0){ + transp_window->added_transp = (1 - transp_ratio / RandUniFloatRange(min, max, &resource_rng)) * transp_window->average; + if(transp_window->added_transp < 0){ LogError(logfp, LOGNOTE, "sxw_resource: Added transpiration less than 0.\n"); } //printf("Year %d:\tTranspiration to add: %f\n",Globals->currYear,add_transp); //printf("TranspRemaining: %f\tTranspRemaining+add_transp: %f\n",TranspRemaining,add_transp+TranspRemaining); /* -------------------- Recalculate the window including added_transp in the current year -------------------- */ - RealF added_transp_ratio = transp_window.added_transp / SXW.ppt; + RealF added_transp_ratio = transp_window->added_transp / SXW.ppt; //add added_transp to the average. This is technically part of the current year, so no need to subtract anything. - transp_window.average += transp_window.added_transp/transp_window.size; + transp_window->average += transp_window->added_transp/transp_window->size; //add added_transp ratio to the ratio average. This is technically part of the current year, so no need to subtract anything. - transp_window.ratio_average += (added_transp_ratio)/transp_window.size; + transp_window->ratio_average += (added_transp_ratio)/transp_window->size; //put the new transpiration in the window. Note: oldest_index has not been incremented, so it points to what was just added - transp_window.transp[transp_window.oldest_index] += transp_window.added_transp; + transp_window->transp[transp_window->oldest_index] += transp_window->added_transp; //put the new ratio in the window. Note: oldest_index has not been incremented, so it points to what was just added - transp_window.ratios[transp_window.oldest_index] += added_transp_ratio; + transp_window->ratios[transp_window->oldest_index] += added_transp_ratio; // calculate the new sum of squares value - RealF totalTranspRatio = (sumTranspTotal + transp_window.added_transp)/SXW.ppt; - RealF ssqr = (totalTranspRatio - transp_window.ratio_average) * (totalTranspRatio - transp_window.ratio_average); + RealF totalTranspRatio = (sumTranspTotal + transp_window->added_transp)/SXW.ppt; + RealF ssqr = (totalTranspRatio - transp_window->ratio_average) * (totalTranspRatio - transp_window->ratio_average); // Subtract the sum of squares calculated above, which was stored in the array. Replace it with what was just calculated. - transp_window.sum_of_sqrs += ssqr - transp_window.SoS_array[transp_window.oldest_index]; + transp_window->sum_of_sqrs += ssqr - transp_window->SoS_array[transp_window->oldest_index]; // replace the sum of squares with what we just calculated - transp_window.SoS_array[transp_window.oldest_index] = ssqr; + transp_window->SoS_array[transp_window->oldest_index] = ssqr; //printf("Year %d: ratio = %f, mean = %f, sos = %f\n",Globals->currYear, - //transp_ratio+added_transp_ratio,transp_window.ratio_average, transp_window.sum_of_sqrs); + //transp_ratio+added_transp_ratio,transp_window->ratio_average, transp_window->sum_of_sqrs); /* Adds the additional transpiration to the remaining transpiration * so it can be distributed proportionally to the functional groups. */ - TranspRemaining += transp_window.added_transp; + TranspRemaining += transp_window->added_transp; } //oldest_index++ accounting for the array bounds - transp_window.oldest_index = (transp_window.oldest_index + 1) % transp_window.size; + transp_window->oldest_index = (transp_window->oldest_index + 1) % transp_window->size; /* ------------ End testing to see if additional transpiration is necessary ---------- */ @@ -387,5 +382,5 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { } //remember the last year. When setting up for a new iteration the same year will appear twice, and we want to skip it the second time - transp_window.lastYear = Globals->currYear; + transp_window->lastYear = Globals->currYear; } From 5dc004d756c5fcd9c7290a8bb0cb8295f93c7ca0 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 23 Apr 2019 15:30:29 -0600 Subject: [PATCH 017/167] (issue #279) added .vscode to the gitignore Not really a gridded code issue but it has been annoying me. --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index e569e0aa..27665af0 100644 --- a/.gitignore +++ b/.gitignore @@ -74,3 +74,7 @@ nbproject/private/Default.properties nbproject/private/launcher.properties nbproject/private/private.xml nbproject/project.xml + +# VScode project files +###################### +.vscode From c3b8aa96ec020d4e70b1584ac4e01c551f847f02 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 23 Apr 2019 15:47:04 -0600 Subject: [PATCH 018/167] (issue #728) added deallocation function to sxw.c This function will deallocate any dynamically allocated pointers in sxw.c. --- ST_grid.c | 2 ++ sxw.c | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index 4970db89..2a1603ea 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -298,6 +298,7 @@ void save_sxw_memory(RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive); +void _deallocate_memory(void); //void SXW_init( Bool init_SW ); @@ -643,6 +644,7 @@ void runGrid(void) printf("\routputting files took approximately %.2f seconds\n", ((double) (clock() - prog_Time) / CLOCKS_PER_SEC)); _free_grid_memory(); // free our allocated memory since we do not need it anymore + _deallocate_memory(); // sxw memory. /*if(UseProgressBar)*/printf("!\n"); } diff --git a/sxw.c b/sxw.c index 1984b850..bcbd4461 100644 --- a/sxw.c +++ b/sxw.c @@ -133,6 +133,7 @@ static void SXW_Reinit(void); void load_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ); void save_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ); void free_sxw_memory( void ); +void _deallocate_memory(void); /****************** Begin Function Code ********************/ /***********************************************************/ @@ -447,6 +448,15 @@ static void _allocate_memory(void){ transp_window->SoS_array = (RealF*) Mem_Calloc(transp_window->size, sizeof(RealF), "_allocate_memory: transp_window->SoS_array"); } +/* Deallocate any sxw local pointers. When running the non-gridded mode + * there is no need to call this since we only have one transp_window variable */ +void _deallocate_memory(void){ + Mem_Free(transp_window->ratios); + Mem_Free(transp_window->transp); + Mem_Free(transp_window->SoS_array); + Mem_Free(transp_window); +} + static void _read_files( void ) { /*======================================================*/ /* read list of input files. */ From 3955a3b8c10d0ec0c3861ffb58f95f01a0b5152b Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 23 Apr 2019 16:47:01 -0600 Subject: [PATCH 019/167] (issue #280) changed SXW and SXWResources to pointers Both variables are now allocated in _allocate_memory in sxw.c. In ST main there was one line in init_args that referenced SXW before we could possibly allocate the memory for SXW. To remedy this I moved the line to SXW_Init. --- ST_environs.c | 6 +- ST_grid.c | 270 ++++++++++++++++++++++++------------------------- ST_main.c | 7 +- sxw.c | 269 ++++++++++++++++++++++++------------------------ sxw.h | 14 +-- sxw_environs.c | 6 +- sxw_resource.c | 50 ++++----- sxw_soilwat.c | 38 +++---- sxw_sql.c | 46 ++++----- sxw_tester.c | 18 ++-- sxw_vars.h | 2 +- 11 files changed, 366 insertions(+), 360 deletions(-) diff --git a/ST_environs.c b/ST_environs.c index edca8bb4..e6b394d4 100644 --- a/ST_environs.c +++ b/ST_environs.c @@ -23,7 +23,7 @@ #include "sxw_funcs.h" #include "sw_src/filefuncs.h" #include "sw_src/Times.h" -extern SXW_t SXW; +extern SXW_t* SXW; /*********** Locally Used Function Declarations ************/ /***********************************************************/ @@ -97,8 +97,8 @@ static void _make_ppt( void) { for (i = 0; i < MAX_MONTHS; i++) { - Env->gsppt += GE(SXW.temp_monthly[i], GROWING_BASE_TEMP) ? - (IntS) (SXW.ppt_monthly[i] * 10. + 0.5) : 0; + Env->gsppt += GE(SXW->temp_monthly[i], GROWING_BASE_TEMP) ? + (IntS) (SXW->ppt_monthly[i] * 10. + 0.5) : 0; } if (Env->gsppt <= 0) diff --git a/ST_grid.c b/ST_grid.c index 2a1603ea..ed25b8ef 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -130,7 +130,7 @@ struct _grid_sd_struct }typedef Grid_SD_St; struct _grid_sxw_st -{ //holds pointers dynamically allocated by SXW.c +{ //holds pointers dynamically allocated by SXW->c RealD *roots_max, *rootsXphen, *roots_active, *roots_active_rel, *roots_active_sum, *phen, *prod_bmass, *prod_pctlive; }typedef Grid_SXW_St; @@ -1122,31 +1122,31 @@ static void _load_grid_globals(void) if (UseSoils) _init_soil_layers(i, 0); - grid_SXW[i] = SXW; + grid_SXW[i] = *SXW; - grid_SXW[i].f_roots = Str_Dup(SXW.f_roots); - grid_SXW[i].f_phen = Str_Dup(SXW.f_phen); - grid_SXW[i].f_bvt = Str_Dup(SXW.f_bvt); - grid_SXW[i].f_prod = Str_Dup(SXW.f_prod); - grid_SXW[i].f_watin = Str_Dup(SXW.f_watin); + grid_SXW[i].f_roots = Str_Dup(SXW->f_roots); + grid_SXW[i].f_phen = Str_Dup(SXW->f_phen); + grid_SXW[i].f_bvt = Str_Dup(SXW->f_bvt); + grid_SXW[i].f_prod = Str_Dup(SXW->f_prod); + grid_SXW[i].f_watin = Str_Dup(SXW->f_watin); - grid_SXW[i].transpTotal = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + grid_SXW[i].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_init_grid_globals()"); ForEachVegType(k) { - grid_SXW[i].transpVeg[k] = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + grid_SXW[i].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_init_grid_globals()"); } - grid_SXW[i].swc = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealF), + grid_SXW[i].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), "_init_grid_globals()"); - memcpy(grid_SXW[i].transpTotal, SXW.transpTotal, - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(grid_SXW[i].transpTotal, SXW->transpTotal, + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); ForEachVegType(k) { - memcpy(grid_SXW[i].transpVeg[k], SXW.transpVeg[k], - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(grid_SXW[i].transpVeg[k], SXW->transpVeg[k], + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); } - memcpy(grid_SXW[i].swc, SXW.swc, - SXW.NPds * SXW.NSoLyrs * sizeof(RealF)); + memcpy(grid_SXW[i].swc, SXW->swc, + SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); grid_SW_Soilwat[i] = SW_Soilwat; grid_SW_Site[i] = SW_Site; @@ -1235,31 +1235,31 @@ static void _load_spinup_globals(void) if (UseSoils) //TODO: DM should i be cell value after lookup from soilTypes_Array _init_soil_layers(i, 1); - spinup_SXW[i] = SXW; + spinup_SXW[i] = *SXW; - spinup_SXW[i].f_roots = Str_Dup(SXW.f_roots); - spinup_SXW[i].f_phen = Str_Dup(SXW.f_phen); - spinup_SXW[i].f_bvt = Str_Dup(SXW.f_bvt); - spinup_SXW[i].f_prod = Str_Dup(SXW.f_prod); - spinup_SXW[i].f_watin = Str_Dup(SXW.f_watin); + spinup_SXW[i].f_roots = Str_Dup(SXW->f_roots); + spinup_SXW[i].f_phen = Str_Dup(SXW->f_phen); + spinup_SXW[i].f_bvt = Str_Dup(SXW->f_bvt); + spinup_SXW[i].f_prod = Str_Dup(SXW->f_prod); + spinup_SXW[i].f_watin = Str_Dup(SXW->f_watin); - spinup_SXW[i].transpTotal = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + spinup_SXW[i].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_init_spinup_globals()"); ForEachVegType(k) { - spinup_SXW[i].transpVeg[k] = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + spinup_SXW[i].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_init_grid_globals()"); } - spinup_SXW[i].swc = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + spinup_SXW[i].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), "_init_grid_globals()"); - memcpy(spinup_SXW[i].transpTotal, SXW.transpTotal, - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(spinup_SXW[i].transpTotal, SXW->transpTotal, + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); ForEachVegType(k) { - memcpy(spinup_SXW[i].transpVeg[k], SXW.transpVeg[k], - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(spinup_SXW[i].transpVeg[k], SXW->transpVeg[k], + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); } - memcpy(spinup_SXW[i].swc, SXW.swc, - SXW.NPds * SXW.NSoLyrs * sizeof(RealF)); + memcpy(spinup_SXW[i].swc, SXW->swc, + SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); spinup_SW_Soilwat[i] = SW_Soilwat; spinup_SW_Site[i] = SW_Site; @@ -1574,49 +1574,49 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) *Plot = grid_Plot[cell]; *Globals = grid_Globals[cell]; - Mem_Free(SXW.f_roots); - Mem_Free(SXW.f_phen); - Mem_Free(SXW.f_bvt); - Mem_Free(SXW.f_prod); - Mem_Free(SXW.f_watin); - Mem_Free(SXW.transpTotal); + Mem_Free(SXW->f_roots); + Mem_Free(SXW->f_phen); + Mem_Free(SXW->f_bvt); + Mem_Free(SXW->f_prod); + Mem_Free(SXW->f_watin); + Mem_Free(SXW->transpTotal); ForEachVegType(k) { - Mem_Free(SXW.transpVeg[k]); + Mem_Free(SXW->transpVeg[k]); } - if (SXW.swc != NULL) - Mem_Free(SXW.swc); + if (SXW->swc != NULL) + Mem_Free(SXW->swc); for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) Mem_Free(SW_Site.lyr[j]); Mem_Free(SW_Site.lyr); - SXW = grid_SXW[cell]; + *SXW = grid_SXW[cell]; SW_Site = grid_SW_Site[cell]; SW_Soilwat = grid_SW_Soilwat[cell]; SW_VegProd = grid_SW_VegProd[cell]; - SXW.transpTotal = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealD), - "_load_cell(SXW.transp)"); + SXW->transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), + "_load_cell(SXW->transp)"); ForEachVegType(k) { - SXW.transpVeg[k] = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealD), - "_load_cell(SXW.transp)"); - } - SXW.swc = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealF), - "_load_cell(SXW.swc)"); - - SXW.f_roots = Str_Dup(grid_SXW[cell].f_roots); - SXW.f_phen = Str_Dup(grid_SXW[cell].f_phen); - SXW.f_bvt = Str_Dup(grid_SXW[cell].f_bvt); - SXW.f_prod = Str_Dup(grid_SXW[cell].f_prod); - SXW.f_watin = Str_Dup(grid_SXW[cell].f_watin); - memcpy(SXW.transpTotal, grid_SXW[cell].transpTotal, - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + SXW->transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), + "_load_cell(SXW->transp)"); + } + SXW->swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), + "_load_cell(SXW->swc)"); + + SXW->f_roots = Str_Dup(grid_SXW[cell].f_roots); + SXW->f_phen = Str_Dup(grid_SXW[cell].f_phen); + SXW->f_bvt = Str_Dup(grid_SXW[cell].f_bvt); + SXW->f_prod = Str_Dup(grid_SXW[cell].f_prod); + SXW->f_watin = Str_Dup(grid_SXW[cell].f_watin); + memcpy(SXW->transpTotal, grid_SXW[cell].transpTotal, + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); ForEachVegType(k) { - memcpy(SXW.transpVeg[k], grid_SXW[cell].transpVeg[k], - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(SXW->transpVeg[k], grid_SXW[cell].transpVeg[k], + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); } - memcpy(SXW.swc, grid_SXW[cell].swc, - SXW.NPds * SXW.NSoLyrs * sizeof(RealF)); + memcpy(SXW->swc, grid_SXW[cell].swc, + SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); SW_Site.lyr = Mem_Calloc( grid_SW_Site[cell].n_layers + grid_SW_Site[cell].deepdrain, @@ -1721,48 +1721,48 @@ static void _load_spinup_cell(int cell) *Plot = spinup_Plot[cell]; *Globals = spinup_Globals[cell]; - Mem_Free(SXW.f_roots); - Mem_Free(SXW.f_phen); - Mem_Free(SXW.f_bvt); - Mem_Free(SXW.f_prod); - Mem_Free(SXW.f_watin); - Mem_Free(SXW.transpTotal); + Mem_Free(SXW->f_roots); + Mem_Free(SXW->f_phen); + Mem_Free(SXW->f_bvt); + Mem_Free(SXW->f_prod); + Mem_Free(SXW->f_watin); + Mem_Free(SXW->transpTotal); ForEachVegType(k) { - Mem_Free(SXW.transpVeg[k]); + Mem_Free(SXW->transpVeg[k]); } - if (SXW.swc != NULL) - Mem_Free(SXW.swc); + if (SXW->swc != NULL) + Mem_Free(SXW->swc); for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) Mem_Free(SW_Site.lyr[j]); Mem_Free(SW_Site.lyr); - SXW = spinup_SXW[cell]; + *SXW = spinup_SXW[cell]; SW_Site = spinup_SW_Site[cell]; SW_Soilwat = spinup_SW_Soilwat[cell]; SW_VegProd = spinup_SW_VegProd[cell]; - SXW.transpTotal = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealD), - "_load_spinup_cell(SXW.transpTotal)"); + SXW->transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), + "_load_spinup_cell(SXW->transpTotal)"); ForEachVegType(k) { - SXW.transpVeg[k] = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealD), - "_load_spinup_cell(SXW.transpVeg)"); - } - SXW.swc = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealF), - "_load_spinup_cell(SXW.swc)"); - - SXW.f_roots = Str_Dup(spinup_SXW[cell].f_roots); - SXW.f_phen = Str_Dup(spinup_SXW[cell].f_phen); - SXW.f_bvt = Str_Dup(spinup_SXW[cell].f_bvt); - SXW.f_prod = Str_Dup(spinup_SXW[cell].f_prod); - SXW.f_watin = Str_Dup(spinup_SXW[cell].f_watin); - memcpy(SXW.transpTotal, spinup_SXW[cell].transpTotal, - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + SXW->transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), + "_load_spinup_cell(SXW->transpVeg)"); + } + SXW->swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), + "_load_spinup_cell(SXW->swc)"); + + SXW->f_roots = Str_Dup(spinup_SXW[cell].f_roots); + SXW->f_phen = Str_Dup(spinup_SXW[cell].f_phen); + SXW->f_bvt = Str_Dup(spinup_SXW[cell].f_bvt); + SXW->f_prod = Str_Dup(spinup_SXW[cell].f_prod); + SXW->f_watin = Str_Dup(spinup_SXW[cell].f_watin); + memcpy(SXW->transpTotal, spinup_SXW[cell].transpTotal, + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); ForEachVegType(k) { - memcpy(SXW.transpVeg[k], spinup_SXW[cell].transpVeg[k], - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(SXW->transpVeg[k], spinup_SXW[cell].transpVeg[k], + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); } - memcpy(SXW.swc, spinup_SXW[cell].swc, - SXW.NPds * SXW.NSoLyrs * sizeof(RealF)); + memcpy(SXW->swc, spinup_SXW[cell].swc, + SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); SW_Site.lyr = Mem_Calloc( spinup_SW_Site[cell].n_layers + spinup_SW_Site[cell].deepdrain, @@ -1860,33 +1860,33 @@ static void _save_cell(int row, int col, int year, Bool useAccumulators) Mem_Free(grid_SW_Site[cell].lyr[j]); Mem_Free(grid_SW_Site[cell].lyr); - grid_SXW[cell] = SXW; + grid_SXW[cell] = *SXW; grid_SW_Site[cell] = SW_Site; grid_SW_Soilwat[cell] = SW_Soilwat; grid_SW_VegProd[cell] = SW_VegProd; - grid_SXW[cell].transpTotal = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + grid_SXW[cell].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); ForEachVegType(k) { - grid_SXW[cell].transpVeg[k] = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + grid_SXW[cell].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); } - grid_SXW[cell].swc = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealF), + grid_SXW[cell].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), "_save_cell(grid_SXW[cell].swc)"); - grid_SXW[cell].f_roots = Str_Dup(SXW.f_roots); - grid_SXW[cell].f_phen = Str_Dup(SXW.f_phen); - grid_SXW[cell].f_bvt = Str_Dup(SXW.f_bvt); - grid_SXW[cell].f_prod = Str_Dup(SXW.f_prod); - grid_SXW[cell].f_watin = Str_Dup(SXW.f_watin); - memcpy(grid_SXW[cell].transpTotal, SXW.transpTotal, - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + grid_SXW[cell].f_roots = Str_Dup(SXW->f_roots); + grid_SXW[cell].f_phen = Str_Dup(SXW->f_phen); + grid_SXW[cell].f_bvt = Str_Dup(SXW->f_bvt); + grid_SXW[cell].f_prod = Str_Dup(SXW->f_prod); + grid_SXW[cell].f_watin = Str_Dup(SXW->f_watin); + memcpy(grid_SXW[cell].transpTotal, SXW->transpTotal, + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); ForEachVegType(k) { - memcpy(grid_SXW[cell].transpVeg[k], SXW.transpVeg[k], - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(grid_SXW[cell].transpVeg[k], SXW->transpVeg[k], + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); } - memcpy(grid_SXW[cell].swc, SXW.swc, - SXW.NPds * SXW.NSoLyrs * sizeof(RealF)); + memcpy(grid_SXW[cell].swc, SXW->swc, + SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); grid_SW_Site[cell].lyr = Mem_Calloc( SW_Site.n_layers + SW_Site.deepdrain, sizeof(SW_LAYER_INFO *), @@ -1977,33 +1977,33 @@ static void _save_spinup_cell(int cell) Mem_Free(spinup_SW_Site[cell].lyr[j]); Mem_Free(spinup_SW_Site[cell].lyr); - spinup_SXW[cell] = SXW; + spinup_SXW[cell] = *SXW; spinup_SW_Site[cell] = SW_Site; spinup_SW_Soilwat[cell] = SW_Soilwat; spinup_SW_VegProd[cell] = SW_VegProd; - spinup_SXW[cell].transpTotal = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + spinup_SXW[cell].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); ForEachVegType(k) { - spinup_SXW[cell].transpVeg[k] = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, + spinup_SXW[cell].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); } - spinup_SXW[cell].swc = Mem_Calloc(SXW.NPds * SXW.NSoLyrs, sizeof(RealF), + spinup_SXW[cell].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), "_save_cell(grid_SXW[cell].swc)"); - spinup_SXW[cell].f_roots = Str_Dup(SXW.f_roots); - spinup_SXW[cell].f_phen = Str_Dup(SXW.f_phen); - spinup_SXW[cell].f_bvt = Str_Dup(SXW.f_bvt); - spinup_SXW[cell].f_prod = Str_Dup(SXW.f_prod); - spinup_SXW[cell].f_watin = Str_Dup(SXW.f_watin); - memcpy(spinup_SXW[cell].transpTotal, SXW.transpTotal, - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + spinup_SXW[cell].f_roots = Str_Dup(SXW->f_roots); + spinup_SXW[cell].f_phen = Str_Dup(SXW->f_phen); + spinup_SXW[cell].f_bvt = Str_Dup(SXW->f_bvt); + spinup_SXW[cell].f_prod = Str_Dup(SXW->f_prod); + spinup_SXW[cell].f_watin = Str_Dup(SXW->f_watin); + memcpy(spinup_SXW[cell].transpTotal, SXW->transpTotal, + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); ForEachVegType(k) { - memcpy(spinup_SXW[cell].transpVeg[k], SXW.transpVeg[k], - SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + memcpy(spinup_SXW[cell].transpVeg[k], SXW->transpVeg[k], + SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); } - memcpy(spinup_SXW[cell].swc, SXW.swc, - SXW.NPds * SXW.NSoLyrs * sizeof(RealF)); + memcpy(spinup_SXW[cell].swc, SXW->swc, + SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); spinup_SW_Site[cell].lyr = Mem_Calloc( SW_Site.n_layers + SW_Site.deepdrain, sizeof(SW_LAYER_INFO *), @@ -2441,25 +2441,25 @@ static void _init_soil_layers(int cell, int isSpinup) if (!isSpinup) { - grid_SXW_ptrs[i].roots_max = Mem_Calloc(SXW.NGrps * SXW.NTrLyrs, + grid_SXW_ptrs[i].roots_max = Mem_Calloc(SXW->NGrps * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); grid_SXW_ptrs[i].rootsXphen = Mem_Calloc( - SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); grid_SXW_ptrs[i].roots_active = Mem_Calloc( - SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); grid_SXW_ptrs[i].roots_active_rel = Mem_Calloc( - SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); grid_SXW_ptrs[i].roots_active_sum = Mem_Calloc( - 4 * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + 4 * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); - grid_SXW_ptrs[i].phen = Mem_Calloc(SXW.NGrps * MAX_MONTHS, + grid_SXW_ptrs[i].phen = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "_init_soil_layers()"); - grid_SXW_ptrs[i].prod_bmass = Mem_Calloc(SXW.NGrps * MAX_MONTHS, + grid_SXW_ptrs[i].prod_bmass = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "_init_soil_layers()"); - grid_SXW_ptrs[i].prod_pctlive = Mem_Calloc(SXW.NGrps * MAX_MONTHS, + grid_SXW_ptrs[i].prod_pctlive = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "_init_soil_layers()"); save_sxw_memory(grid_SXW_ptrs[i].roots_max, grid_SXW_ptrs[i].rootsXphen, @@ -2471,25 +2471,25 @@ static void _init_soil_layers(int cell, int isSpinup) else { - spinup_SXW_ptrs[i].roots_max = Mem_Calloc(SXW.NGrps * SXW.NTrLyrs, + spinup_SXW_ptrs[i].roots_max = Mem_Calloc(SXW->NGrps * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); spinup_SXW_ptrs[i].rootsXphen = Mem_Calloc( - SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); spinup_SXW_ptrs[i].roots_active = Mem_Calloc( - SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); spinup_SXW_ptrs[i].roots_active_rel = Mem_Calloc( - SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); spinup_SXW_ptrs[i].roots_active_sum = Mem_Calloc( - 4 * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), + 4 * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "_init_soil_layers()"); - spinup_SXW_ptrs[i].phen = Mem_Calloc(SXW.NGrps * MAX_MONTHS, + spinup_SXW_ptrs[i].phen = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "_init_soil_layers()"); - spinup_SXW_ptrs[i].prod_bmass = Mem_Calloc(SXW.NGrps * MAX_MONTHS, + spinup_SXW_ptrs[i].prod_bmass = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "_init_soil_layers()"); - spinup_SXW_ptrs[i].prod_pctlive = Mem_Calloc(SXW.NGrps * MAX_MONTHS, + spinup_SXW_ptrs[i].prod_pctlive = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "_init_soil_layers()"); save_sxw_memory(spinup_SXW_ptrs[i].roots_max, diff --git a/ST_main.c b/ST_main.c index a340e1a8..510613d0 100644 --- a/ST_main.c +++ b/ST_main.c @@ -33,7 +33,7 @@ #include "sw_src/SW_Output_outtext.h" #include "sw_src/SW_Output_outarray.h" #include "sw_src/rands.h" -extern SXW_t SXW; +extern SXW_t* SXW; extern Bool prepare_IterationSummary; // defined in `SOILWAT2/SW_Output.c` extern Bool print_IterationSummary; // defined in `SOILWAT2/SW_Output_outtext.c` @@ -234,7 +234,7 @@ int main(int argc, char **argv) { rgroup_PartResources(); - if (!isnull(SXW.debugfile) ) SXW_PrintDebug(0); + if (!isnull(SXW->debugfile) ) SXW_PrintDebug(0); rgroup_Grow(); @@ -309,7 +309,7 @@ int main(int argc, char **argv) { ST_disconnect(); } - if (!isnull(SXW.debugfile)){ + if (!isnull(SXW->debugfile)){ printf("entering debugfile\n"); SXW_PrintDebug(1); } @@ -461,7 +461,6 @@ static void init_args(int argc, char **argv) { /* Defaults */ parm_SetFirstName( DFLT_FIRSTFILE); QuietMode = EchoInits = UseSeedDispersal = FALSE; - SXW.debugfile = NULL; progfp = stderr; diff --git a/sxw.c b/sxw.c index bcbd4461..09b5122f 100644 --- a/sxw.c +++ b/sxw.c @@ -69,7 +69,7 @@ /*************** Global Variable Declarations ***************/ /***********************************************************/ -SXW_t SXW; +SXW_t* SXW; extern SW_SITE SW_Site; extern SW_MODEL SW_Model; @@ -91,7 +91,7 @@ extern Bool storeAllIterations; // "Window" refers to the number of years over which transpiration data is averaged. transp_t* transp_window; pcg32_random_t resource_rng; //rng for swx_resource.c functions. -SXW_resourceType SXWResources; +SXW_resourceType* SXWResources; #ifdef SXW_BYMAXSIZE /* addition to meet changes specified at the top of the file */ @@ -165,13 +165,14 @@ _allocate_memory(); /* end code 2/14/03 */ #endif - _sxwfiles[0] = &SXW.f_roots; - _sxwfiles[1] = &SXW.f_phen; - _sxwfiles[2] = &SXW.f_bvt; - _sxwfiles[3] = &SXW.f_prod; - _sxwfiles[4] = &SXW.f_watin; + _sxwfiles[0] = &SXW->f_roots; + _sxwfiles[1] = &SXW->f_phen; + _sxwfiles[2] = &SXW->f_bvt; + _sxwfiles[3] = &SXW->f_prod; + _sxwfiles[4] = &SXW->f_watin; - SXW.NGrps = Globals->grpCount; + SXW->debugfile = NULL; + SXW->NGrps = Globals->grpCount; _read_files(); if(f_roots != NULL) { @@ -179,13 +180,13 @@ _allocate_memory(); strcpy(roots, DirName(*_sxwfiles[0])); strcat(roots, f_roots); Mem_Free(*_sxwfiles[0]); - _sxwfiles[0] = &SXW.f_roots; + _sxwfiles[0] = &SXW->f_roots; *_sxwfiles[0] = Str_Dup(roots); } - SXW.NPds = MAX_MONTHS; + SXW->NPds = MAX_MONTHS; _read_watin(); - if (SXW.debugfile) + if (SXW->debugfile) _read_debugfile(); @@ -194,15 +195,15 @@ _allocate_memory(); SXW_Reinit(); } - SXW.NTrLyrs = SW_Site.n_transp_lyrs[0]; - if(SW_Site.n_transp_lyrs[1] > SXW.NTrLyrs) - SXW.NTrLyrs = SW_Site.n_transp_lyrs[1]; - if(SW_Site.n_transp_lyrs[3] > SXW.NTrLyrs) - SXW.NTrLyrs = SW_Site.n_transp_lyrs[3]; - if(SW_Site.n_transp_lyrs[2] > SXW.NTrLyrs) - SXW.NTrLyrs = SW_Site.n_transp_lyrs[2]; + SXW->NTrLyrs = SW_Site.n_transp_lyrs[0]; + if(SW_Site.n_transp_lyrs[1] > SXW->NTrLyrs) + SXW->NTrLyrs = SW_Site.n_transp_lyrs[1]; + if(SW_Site.n_transp_lyrs[3] > SXW->NTrLyrs) + SXW->NTrLyrs = SW_Site.n_transp_lyrs[3]; + if(SW_Site.n_transp_lyrs[2] > SXW->NTrLyrs) + SXW->NTrLyrs = SW_Site.n_transp_lyrs[2]; - SXW.NSoLyrs = SW_Site.n_layers; + SXW->NSoLyrs = SW_Site.n_layers; printf("Number of layers: %d\n", SW_Site.n_layers); printf("Number of iterations: %d\n", Globals->runModelIterations); @@ -230,7 +231,7 @@ _allocate_memory(); static void SXW_Reinit(void) { char *temp; - temp = strdup(SXW.f_watin); + temp = strdup(SXW->f_watin); SW_CTL_init_model(temp); SW_CTL_obtain_inputs(); SW_OUT_set_SXWrequests(); @@ -304,7 +305,7 @@ void SXW_Run_SOILWAT (void) { #endif // Initialize `SXW` values for current year's run: - SXW.aet = 0.; /* used to be in sw_setup() but it needs clearing each run */ + SXW->aet = 0.; /* used to be in sw_setup() but it needs clearing each run */ //SXW_SW_Setup_Echo(); _sxw_sw_run(); @@ -365,10 +366,10 @@ void SXW_SW_Setup_Echo(void) { } // adding values to sxw structure for use in ST_stats.c - /*SXW.grass_cover = SW_VegProd.grass.conv_stcr; - SXW.shrub_cover = SW_VegProd.shrub.conv_stcr; - SXW.tree_cover = SW_VegProd.tree.conv_stcr; - SXW.forbs_cover = SW_VegProd.forb.conv_stcr;*/ + /*SXW->grass_cover = SW_VegProd.grass.conv_stcr; + SXW->shrub_cover = SW_VegProd.shrub.conv_stcr; + SXW->tree_cover = SW_VegProd.tree.conv_stcr; + SXW->forbs_cover = SW_VegProd.forb.conv_stcr;*/ fprintf(f, "\n"); @@ -382,7 +383,7 @@ This function is no longer utilized, SXW_GetResource has replaced it _resource_pr is no longer used as a parameter. We remain the code for the time being KAP 7/20/2016 */ - RealF pr = ZRO(SXWResources._resource_pr[rg]) ? 0.0 : 1. / SXWResources._resource_pr[rg]; + RealF pr = ZRO(SXWResources->_resource_pr[rg]) ? 0.0 : 1. / SXWResources->_resource_pr[rg]; return pr; //return pr > 10 ? 10 : pr; } @@ -392,7 +393,7 @@ RealF SXW_GetTranspiration( GrpIndex rg) { /* see _sxw_update_resource() for _resource_cur[] */ //printf("SXW_GetTranspiration _resource_cur[%d] = %.5f \n", rg, _resource_cur[rg]); - return SXWResources._resource_cur[rg]; + return SXWResources->_resource_cur[rg]; } void SXW_PrintDebug(Bool cleanup) { @@ -415,16 +416,16 @@ void SXW_PrintDebug(Bool cleanup) { insertInfo(); insertSXWPhen(); insertSXWProd(); - insertRootsXphen(SXWResources._rootsXphen); + insertRootsXphen(SXWResources->_rootsXphen); } insertInputVars(); insertInputProd(); insertInputSoils(); - insertOutputVars(SXWResources._resource_cur, transp_window->added_transp); - insertRgroupInfo(SXWResources._resource_cur); + insertOutputVars(SXWResources->_resource_cur, transp_window->added_transp); + insertRgroupInfo(SXWResources->_resource_cur); insertOutputProd(&SW_VegProd); - insertRootsSum(SXWResources._roots_active_sum); - insertRootsRelative(SXWResources._roots_active_rel); + insertRootsSum(SXWResources->_roots_active_sum); + insertRootsRelative(SXWResources->_roots_active_rel); insertTranspiration(); insertSWCBulk(); } @@ -446,6 +447,9 @@ static void _allocate_memory(void){ transp_window->ratios = (RealF*) Mem_Calloc(transp_window->size, sizeof(RealF), "_allocate_memory: transp_window->ratios"); transp_window->transp = (RealF*) Mem_Calloc(transp_window->size, sizeof(RealF), "_allocate_memory: transp_window->transp"); transp_window->SoS_array = (RealF*) Mem_Calloc(transp_window->size, sizeof(RealF), "_allocate_memory: transp_window->SoS_array"); + + SXW = (SXW_t*) Mem_Calloc(1, sizeof(SXW_t), "_allocate_memory: SXW"); + SXWResources = (SXW_resourceType*) Mem_Calloc(1, sizeof(SXW_resourceType), "_allocate_memory: SXWResources"); } /* Deallocate any sxw local pointers. When running the non-gridded mode @@ -455,6 +459,9 @@ void _deallocate_memory(void){ Mem_Free(transp_window->transp); Mem_Free(transp_window->SoS_array); Mem_Free(transp_window); + + Mem_Free(SXW); + Mem_Free(SXWResources); } static void _read_files( void ) { @@ -463,8 +470,8 @@ static void _read_files( void ) { FILE *fin; int i, nfiles = SXW_NFILES; - SXW.f_files = Parm_name(F_SXW); /* aliased */ - MyFileName = SXW.f_files; + SXW->f_files = Parm_name(F_SXW); /* aliased */ + MyFileName = SXW->f_files; fin = OpenFile(MyFileName,"r"); for(i=0; i < nfiles; i++) { @@ -490,7 +497,7 @@ static void _read_roots_max(void) { char name[MAX_GROUPNAMELEN]; FILE *fp; - MyFileName = SXW.f_roots; + MyFileName = SXW->f_roots; fp = OpenFile(MyFileName, "r"); while (GetALine(fp, inbuf)) { @@ -504,13 +511,13 @@ static void _read_roots_max(void) { cnt++; lyr = 0; while ((p = strtok(NULL, " \t"))) { - SXWResources._roots_max[Ilg(lyr, g)] = atof(p); + SXWResources->_roots_max[Ilg(lyr, g)] = atof(p); lyr++; } - if (lyr != SXW.NTrLyrs) { + if (lyr != SXW->NTrLyrs) { LogError(logfp, LOGFATAL, "%s: Group : %s : Missing layer values. Match up with soils.in file. Include zeros if necessary. Layers needed %u. Layers defined %u", - MyFileName, name, SXW.NTrLyrs, lyr); + MyFileName, name, SXW->NTrLyrs, lyr); } } @@ -531,7 +538,7 @@ static void _read_phen(void) { char *p; FILE *fp; - MyFileName = SXW.f_phen; + MyFileName = SXW->f_phen; fp = OpenFile(MyFileName,"r"); @@ -549,7 +556,7 @@ static void _read_phen(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - SXWResources._phen[Igp(g,m)] = atof(p); + SXWResources->_phen[Igp(g,m)] = atof(p); m++; } @@ -575,7 +582,7 @@ static void _read_bvt(void) { FILE *fp; RealF bmass, transp; - MyFileName = SXW.f_bvt; + MyFileName = SXW->f_bvt; fp = OpenFile(MyFileName,"r"); GetALine(fp, inbuf); @@ -587,7 +594,7 @@ static void _read_bvt(void) { CloseFile(&fp); - SXWResources._bvt = bmass / transp; + SXWResources->_bvt = bmass / transp; } @@ -601,11 +608,11 @@ static void _read_prod(void) { IntUS cnt = 0; char *p; char * pch; - MyFileName = SXW.f_prod; + MyFileName = SXW->f_prod; fp = OpenFile(MyFileName, "r"); while (GetALine(fp, inbuf)) { - x = sscanf(inbuf, "%lf", &SXWResources._prod_litter[mon]); + x = sscanf(inbuf, "%lf", &SXWResources->_prod_litter[mon]); if (x < 1) { LogError(logfp, LOGFATAL, "%s: invalid record for litter %d.", MyFileName, mon + 1); @@ -640,11 +647,11 @@ static void _read_prod(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - SXWResources._prod_bmass[Igp(g, mon)] = atof(p); + SXWResources->_prod_bmass[Igp(g, mon)] = atof(p); mon++; } cnt++; - if(cnt == SXW.NGrps) + if(cnt == SXW->NGrps) break; } @@ -675,11 +682,11 @@ static void _read_prod(void) { LogError(logfp, LOGFATAL, "%s: More than 12 months of data found.", MyFileName); } - SXWResources._prod_pctlive[Igp(g, mon)] = atof(p); + SXWResources->_prod_pctlive[Igp(g, mon)] = atof(p); mon++; } cnt++; - if (cnt == SXW.NGrps) + if (cnt == SXW->NGrps) break; } @@ -708,13 +715,13 @@ static void _read_watin(void) { int lineno = 0; Bool found = FALSE; - MyFileName = SXW.f_watin; + MyFileName = SXW->f_watin; f = OpenFile(MyFileName, "r"); while( GetALine(f, inbuf) ) { if (++lineno == (eOutput + 2)) { - strcpy(_swOutDefName, DirName(SXW.f_watin)); + strcpy(_swOutDefName, DirName(SXW->f_watin)); strcat(_swOutDefName, inbuf); found = TRUE; break; @@ -746,17 +753,17 @@ static void _make_roots_arrays(void) { int size; char *fstr = "_make_roots_array()"; - size = SXW.NGrps * SXW.NTrLyrs; - SXWResources._roots_max = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + size = SXW->NGrps * SXW->NTrLyrs; + SXWResources->_roots_max = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - size = SXW.NGrps * SXW.NPds * SXW.NTrLyrs; - SXWResources._rootsXphen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - SXWResources._roots_active = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - SXWResources._roots_active_rel = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + size = SXW->NGrps * SXW->NPds * SXW->NTrLyrs; + SXWResources->_rootsXphen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources->_roots_active = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources->_roots_active_rel = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); //4 - Grass,Frob,Tree,Shrub - size = NVEGTYPES * SXW.NPds * SXW.NTrLyrs; - SXWResources._roots_active_sum = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + size = NVEGTYPES * SXW->NPds * SXW->NTrLyrs; + SXWResources->_roots_active_sum = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } static void _make_phen_arrays(void) { @@ -764,8 +771,8 @@ static void _make_phen_arrays(void) { int size; char *fstr = "_make_phen_arrays()"; - size = SXW.NGrps * MAX_MONTHS; - SXWResources._phen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + size = SXW->NGrps * MAX_MONTHS; + SXWResources->_phen = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } @@ -773,37 +780,37 @@ static void _make_prod_arrays(void) { int size; char *fstr = "_make_phen_arrays()"; - size = SXW.NGrps * MAX_MONTHS; - SXWResources._prod_bmass = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); - SXWResources._prod_pctlive = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + size = SXW->NGrps * MAX_MONTHS; + SXWResources->_prod_bmass = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXWResources->_prod_pctlive = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } static void _make_transp_arrays(void) { /*======================================================*/ -/* SXW.transp holds year-to-year values and is populated in SOILWAT. +/* SXW->transp holds year-to-year values and is populated in SOILWAT. * both are indexed by the macro Ilp(). */ char *fstr = "_make_transp_array()"; int size, k; - size = SXW.NPds * SXW.NSoLyrs; // monthly values for each soil layer - SXW.transpTotal = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + size = SXW->NPds * SXW->NSoLyrs; // monthly values for each soil layer + SXW->transpTotal = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); ForEachVegType(k) { - SXW.transpVeg[k] = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); + SXW->transpVeg[k] = (RealD *) Mem_Calloc(size, sizeof(RealD), fstr); } } static void _make_swc_array(void) { /*======================================================*/ -/* SXW.swc holds year-to-year values and is populated in SOILWAT. +/* SXW->swc holds year-to-year values and is populated in SOILWAT. * it is indexed by the macro Ilp(). only used if soilwat option * specified with debugfile */ char *fstr = "_make_swc_array()"; - int size = SXW.NPds * SXW.NSoLyrs; // monthly values for each soil layer + int size = SXW->NPds * SXW->NSoLyrs; // monthly values for each soil layer - SXW.swc = (RealF *) Mem_Calloc(size, sizeof(RealF *), fstr); + SXW->swc = (RealF *) Mem_Calloc(size, sizeof(RealF *), fstr); } static void _read_debugfile(void) { @@ -837,7 +844,7 @@ static void _read_debugfile(void) { TimeInt i; char name[256] = {0}; - f = OpenFile(SXW.debugfile, "r"); + f = OpenFile(SXW->debugfile, "r"); /* get name of output file */ if (!GetALine(f, inbuf)) { @@ -925,7 +932,7 @@ void _print_debuginfo(void) { //ForEachTranspLayer(t) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", SXWResources._rootsXphen[Iglp(r, t, p)]); + fprintf(f, "\t%.4f", SXWResources->_rootsXphen[Iglp(r, t, p)]); fprintf(f, "\n"); } } @@ -935,24 +942,24 @@ void _print_debuginfo(void) { /* sum actual total transpiration */ ForEachTrPeriod(p) { - //ForEachTranspLayer(t) sum += SXW.transp[Ilp(t,p)]; - for (t = 0; t < SXW.NSoLyrs; t++) - sum += SXW.transpTotal[Ilp(t, p)]; + //ForEachTranspLayer(t) sum += SXW->transp[Ilp(t,p)]; + for (t = 0; t < SXW->NSoLyrs; t++) + sum += SXW->transpTotal[Ilp(t, p)]; } fprintf(f, "\n================== %d =============================\n", SW_Model.year); - fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env->ppt, Env->temp, SXW.aet, sum, transp_window->added_transp, sum + transp_window->added_transp); + fprintf(f, "MAP = %d(mm)\tMAT = %5.2f(C)\tAET = %5.4f(cm)\tT = %5.4f(cm)\tTADDED = %5.4f(cm)\tAT = %5.4f(cm)\n\n", Env->ppt, Env->temp, SXW->aet, sum, transp_window->added_transp, sum + transp_window->added_transp); fprintf(f, "Group \tRelsize\tPR\tResource_cur\tResource_cur\n"); fprintf(f, "----- \t-------\t-----\t-no scaling-\t-with scaling-\n"); ForEachGroup(r) { sum1 += RGroup[r]->relsize; sum2 += RGroup[r]->pr; - sum3 += SXWResources._resource_cur[r]; - fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, RGroup[r]->relsize, RGroup[r]->pr, SXWResources._resource_cur[r]/SXWResources._bvt, SXWResources._resource_cur[r]); + sum3 += SXWResources->_resource_cur[r]; + fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, RGroup[r]->relsize, RGroup[r]->pr, SXWResources->_resource_cur[r]/SXWResources->_bvt, SXWResources->_resource_cur[r]); } fprintf(f, "----- \t-------\t-----\t-----\t\t-----\n"); - fprintf(f, "%s\t\t%.4f\t%.4f\t%.4f\t\t%.4f\n", "Total", sum1, sum2, sum3/SXWResources._bvt, sum3); + fprintf(f, "%s\t\t%.4f\t%.4f\t%.4f\t\t%.4f\n", "Total", sum1, sum2, sum3/SXWResources->_bvt, sum3); fprintf(f, "\n------ Production Values Daily Summed Across Types Monthly Averaged -------\n"); fprintf(f, "Month\tBMass\tPctLive\tLAIlive\tVegCov\tTotAGB\n"); @@ -1014,10 +1021,10 @@ void _print_debuginfo(void) { ForEachTrPeriod(p) fprintf(f, "\t%d", p + 1); fprintf(f, "\n"); - for (l = 0; l < SXW.NTrLyrs; l++) { + for (l = 0; l < SXW->NTrLyrs; l++) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", SXWResources._roots_active_sum[Itlp(t, l, p)]); + fprintf(f, "\t%.4f", SXWResources->_roots_active_sum[Itlp(t, l, p)]); fprintf(f, "\n"); } } @@ -1036,14 +1043,14 @@ void _print_debuginfo(void) { //ForEachTranspLayer(t) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) - fprintf(f, "\t%.4f", SXWResources._roots_active_rel[Iglp(r, t, p)]); + fprintf(f, "\t%.4f", SXWResources->_roots_active_rel[Iglp(r, t, p)]); fprintf(f, "\n"); } } fprintf(f, "\n------ Transpiration Total Values -------\nPeriod:"); //ForEachTranspLayer(t) - for (t = 0; t < SXW.NSoLyrs; t++) + for (t = 0; t < SXW->NSoLyrs; t++) fprintf(f, "\t\tL%d", t + 1); fprintf(f, "\n"); @@ -1051,8 +1058,8 @@ void _print_debuginfo(void) { { fprintf(f, "%d : ", p + 1); //ForEachTranspLayer(t) - for (t = 0; t < SXW.NSoLyrs; t++) - fprintf(f, "\t%.4f", SXW.transpTotal[Ilp(t, p)]); + for (t = 0; t < SXW->NSoLyrs; t++) + fprintf(f, "\t%.4f", SXW->transpTotal[Ilp(t, p)]); fprintf(f, "\n"); } @@ -1061,7 +1068,7 @@ void _print_debuginfo(void) { { fprintf(f, "%d : ", p + 1); ForEachSoilLayer(t) - fprintf(f, "\t%5.4f", SXW.swc[Ilp(t, p)]); + fprintf(f, "\t%5.4f", SXW->swc[Ilp(t, p)]); fprintf(f, "\n"); } @@ -1098,7 +1105,7 @@ void SXW_SetMemoryRefs( void) { NoteMemoryRef(_phen); NoteMemoryRef(_phen_grp_rel); NoteMemoryRef(_transp_grp_totals); - NoteMemoryRef(SXW.transp); + NoteMemoryRef(SXW->transp); SW_CTL_SetMemoryRefs(); @@ -1125,67 +1132,67 @@ void free_all_sxw_memory( void ) { int k; free_sxw_memory(); - Mem_Free(SXW.f_files); - Mem_Free(SXW.f_roots); - Mem_Free(SXW.f_phen); - Mem_Free(SXW.f_bvt); - Mem_Free(SXW.f_prod); - Mem_Free(SXW.f_watin); - - Mem_Free(SXW.transpTotal); + Mem_Free(SXW->f_files); + Mem_Free(SXW->f_roots); + Mem_Free(SXW->f_phen); + Mem_Free(SXW->f_bvt); + Mem_Free(SXW->f_prod); + Mem_Free(SXW->f_watin); + + Mem_Free(SXW->transpTotal); ForEachVegType(k) { - Mem_Free(SXW.transpVeg[k]); + Mem_Free(SXW->transpVeg[k]); } - //Mem_Free(SXW.sum_dSWA_repartitioned); // required for `_SWA_contribution_by_group` + //Mem_Free(SXW->sum_dSWA_repartitioned); // required for `_SWA_contribution_by_group` - Mem_Free(SXW.swc); + Mem_Free(SXW->swc); } /***********************************************************/ void free_sxw_memory( void ) { - Mem_Free(SXWResources._roots_max); - Mem_Free(SXWResources._rootsXphen); - Mem_Free(SXWResources._roots_active); - Mem_Free(SXWResources._roots_active_rel); - Mem_Free(SXWResources._roots_active_sum); - Mem_Free(SXWResources._phen); - Mem_Free(SXWResources._prod_bmass); - Mem_Free(SXWResources._prod_pctlive); + Mem_Free(SXWResources->_roots_max); + Mem_Free(SXWResources->_rootsXphen); + Mem_Free(SXWResources->_roots_active); + Mem_Free(SXWResources->_roots_active_rel); + Mem_Free(SXWResources->_roots_active_sum); + Mem_Free(SXWResources->_phen); + Mem_Free(SXWResources->_prod_bmass); + Mem_Free(SXWResources->_prod_pctlive); } /***********************************************************/ void load_sxw_memory( RealD* grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ) { //load memory from the grid free_sxw_memory(); - SXWResources._roots_max = Mem_Calloc(SXW.NGrps * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources._rootsXphen = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources._roots_active = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources._roots_active_rel = Mem_Calloc(SXW.NGrps * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources._roots_active_sum = Mem_Calloc(4 * SXW.NPds * SXW.NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources._phen = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - SXWResources._prod_bmass = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - SXWResources._prod_pctlive = Mem_Calloc(SXW.NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - - memcpy(SXWResources._roots_max, grid_roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWResources._rootsXphen, grid_rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWResources._roots_active, grid_roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWResources._roots_active_rel, grid_roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWResources._roots_active_sum, grid_roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(SXWResources._phen, grid_phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(SXWResources._prod_bmass, grid_prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(SXWResources._prod_pctlive, grid_prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + SXWResources->_roots_max = Mem_Calloc(SXW->NGrps * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources->_rootsXphen = Mem_Calloc(SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources->_roots_active = Mem_Calloc(SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources->_roots_active_rel = Mem_Calloc(SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources->_roots_active_sum = Mem_Calloc(4 * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); + SXWResources->_phen = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + SXWResources->_prod_bmass = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + SXWResources->_prod_pctlive = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); + + memcpy(SXWResources->_roots_max, grid_roots_max, SXW->NGrps * SXW->NTrLyrs * sizeof(RealD)); + memcpy(SXWResources->_rootsXphen, grid_rootsXphen, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(SXWResources->_roots_active, grid_roots_active, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(SXWResources->_roots_active_rel, grid_roots_active_rel, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(SXWResources->_roots_active_sum, grid_roots_active_sum, 4 * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(SXWResources->_phen, grid_phen, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(SXWResources->_prod_bmass, grid_prod_bmass, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(SXWResources->_prod_pctlive, grid_prod_pctlive, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); } /***********************************************************/ void save_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ) { //save memory to the grid - memcpy(grid_roots_max, SXWResources._roots_max, SXW.NGrps * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_rootsXphen, SXWResources._rootsXphen, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active, SXWResources._roots_active, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active_rel, SXWResources._roots_active_rel, SXW.NGrps * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_roots_active_sum, SXWResources._roots_active_sum, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); - memcpy(grid_phen, SXWResources._phen, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(grid_prod_bmass, SXWResources._prod_bmass, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(grid_prod_pctlive, SXWResources._prod_pctlive, SXW.NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_roots_max, SXWResources->_roots_max, SXW->NGrps * SXW->NTrLyrs * sizeof(RealD)); + memcpy(grid_rootsXphen, SXWResources->_rootsXphen, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active, SXWResources->_roots_active, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active_rel, SXWResources->_roots_active_rel, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(grid_roots_active_sum, SXWResources->_roots_active_sum, 4 * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); + memcpy(grid_phen, SXWResources->_phen, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_prod_bmass, SXWResources->_prod_bmass, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); + memcpy(grid_prod_pctlive, SXWResources->_prod_pctlive, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); } diff --git a/sxw.h b/sxw.h index 1c424f61..f368a741 100644 --- a/sxw.h +++ b/sxw.h @@ -153,30 +153,30 @@ struct temp_SXW_st{ } typedef SXW_resourceType; -#define ForEachTrPeriod(i) for((i)=0; (i)< SXW.NPds; (i)++) +#define ForEachTrPeriod(i) for((i)=0; (i)< SXW->NPds; (i)++) /* convert 3-d index to actual array index for group/layer/phenology 3d table */ -#define Iglp(g,l,p) (((g)*SXW.NTrLyrs*SXW.NPds) + ((l)*SXW.NPds) + (p)) +#define Iglp(g,l,p) (((g)*SXW->NTrLyrs*SXW->NPds) + ((l)*SXW->NPds) + (p)) /* convert 3-d index to actual array index for * veg-prod-type/layer/phenology */ -#define Itlp(t,l,p) (((t)*SXW.NTrLyrs*SXW.NPds) + ((l)*SXW.NPds) + (p)) +#define Itlp(t,l,p) (((t)*SXW->NTrLyrs*SXW->NPds) + ((l)*SXW->NPds) + (p)) // veg type, layer, timeperiod -#define Ivlp(v,l,p) (((v)*NVEGTYPES * SXW.NTrLyrs * SXW.NPds) + ((l)*SXW.NTrLyrs * SXW.NPds) + ((p)*SXW.NPds)) +#define Ivlp(v,l,p) (((v)*NVEGTYPES * SXW->NTrLyrs * SXW.NPds) + ((l)*SXW->NTrLyrs * SXW->NPds) + ((p)*SXW->NPds)) /* convert 2d layer by period indices to layer/phenology 1D index */ -#define Ilp(l,p) ((l)*SXW.NPds + (p)) +#define Ilp(l,p) ((l)*SXW->NPds + (p)) /* convert 2d group by period indices to group/phenology 1D index */ -#define Igp(g,p) ((g)*SXW.NPds + (p)) +#define Igp(g,p) ((g)*SXW->NPds + (p)) /* convert 2d group by layer indices to layer/period 1D index */ -#define Ilg(l,g) ((l)*SXW.NGrps + (g)) +#define Ilg(l,g) ((l)*SXW->NGrps + (g)) #endif diff --git a/sxw_environs.c b/sxw_environs.c index 479c8e34..b50483c5 100644 --- a/sxw_environs.c +++ b/sxw_environs.c @@ -30,7 +30,7 @@ /*************** Global Variable Declarations ***************/ /***********************************************************/ -extern SXW_t SXW; +extern SXW_t* SXW; extern SW_SITE SW_Site; extern SW_MODEL SW_Model; @@ -55,8 +55,8 @@ void _sxw_set_environs(void) { * need to convert ppt from cm to mm */ //Integer conversion always does floor so .5 is added - Env->ppt = (IntS) (SXW.ppt * 10 + .5); - Env->temp = SXW.temp; + Env->ppt = (IntS) (SXW->ppt * 10 + .5); + Env->temp = SXW->temp; } diff --git a/sxw_resource.c b/sxw_resource.c index e261d720..45056f84 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -47,7 +47,7 @@ //extern SW_SOILWAT SW_Soilwat; //extern SW_VEGPROD SW_VegProd; -extern SXW_resourceType SXWResources; +extern SXW_resourceType* SXWResources; /* ------ Running Averages ------ */ extern @@ -77,15 +77,15 @@ void _sxw_root_phen(void) { GrpIndex g; TimeInt p; - for (y = 0; y < (Globals->grpCount * SXW.NPds * SXW.NTrLyrs); y++) - SXWResources._rootsXphen[y] = 0; + for (y = 0; y < (Globals->grpCount * SXW->NPds * SXW->NTrLyrs); y++) + SXWResources->_rootsXphen[y] = 0; ForEachGroup(g) { int nLyrs = getNTranspLayers(RGroup[g]->veg_prod_type); for (y = 0; y < nLyrs; y++) { ForEachTrPeriod(p) { - SXWResources._rootsXphen[Iglp(g, y, p)] = SXWResources._roots_max[Ilg(y, g)] * SXWResources._phen[Igp(g, p)]; + SXWResources->_rootsXphen[Iglp(g, y, p)] = SXWResources->_roots_max[Ilg(y, g)] * SXWResources->_phen[Igp(g, p)]; } } } @@ -131,14 +131,14 @@ void _sxw_update_resource(void) { _sxw_update_root_tables(sizes); /* Assign transpiration (resource availability) to each STEPPE functional group */ - _transp_contribution_by_group(SXWResources._resource_cur); + _transp_contribution_by_group(SXWResources->_resource_cur); /* Scale transpiration resources by a constant, bvt, to convert resources * (cm) to biomass that can be supported by those resources (g/cm) */ ForEachGroup(g) { //printf("for groupName= %smresource_cur prior to multiplication: %f\n",RGroup[g]->name, _resource_cur[g]); - SXWResources._resource_cur[g] = SXWResources._resource_cur[g] * SXWResources._bvt; + SXWResources->_resource_cur[g] = SXWResources->_resource_cur[g] * SXWResources->_bvt; //printf("for groupName= %s, resource_cur post multiplication: %f\n\n",Rgroup[g]->name, _resource_cur[g]); } /* _print_debuginfo(); */ @@ -157,7 +157,7 @@ void _sxw_update_root_tables( RealF sizes[] ) { int t,nLyrs; /* Set some things to zero where 4 refers to Tree, Shrub, Grass, Forb */ - Mem_Set(SXWResources._roots_active_sum, 0, 4 * SXW.NPds * SXW.NTrLyrs * sizeof(RealD)); + Mem_Set(SXWResources->_roots_active_sum, 0, 4 * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); /* Calculate the active roots in each month and soil layer for each STEPPE * functional group based on the functional group biomass this year */ @@ -168,9 +168,9 @@ void _sxw_update_root_tables( RealF sizes[] ) { for (l = 0; l < nLyrs; l++) { ForEachTrPeriod(p) { - x = SXWResources._rootsXphen[Iglp(g, l, p)] * sizes[g]; - SXWResources._roots_active[Iglp(g, l, p)] = x; - SXWResources._roots_active_sum[Itlp(t, l, p)] += x; + x = SXWResources->_rootsXphen[Iglp(g, l, p)] * sizes[g]; + SXWResources->_roots_active[Iglp(g, l, p)] = x; + SXWResources->_roots_active_sum[Itlp(t, l, p)] += x; } } } @@ -184,11 +184,11 @@ void _sxw_update_root_tables( RealF sizes[] ) { for (l = 0; l < nLyrs; l++) { ForEachTrPeriod(p) { - SXWResources._roots_active_rel[Iglp(g, l, p)] = - ZRO(SXWResources._roots_active_sum[Itlp(t,l,p)]) ? + SXWResources->_roots_active_rel[Iglp(g, l, p)] = + ZRO(SXWResources->_roots_active_sum[Itlp(t,l,p)]) ? 0. : - SXWResources._roots_active[Iglp(g, l, p)] - / SXWResources._roots_active_sum[Itlp(t,l, p)]; + SXWResources->_roots_active[Iglp(g, l, p)] + / SXWResources->_roots_active_sum[Itlp(t,l, p)]; } } } @@ -234,19 +234,19 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { switch (t) { case 0://Tree - transp = SXW.transpVeg[SW_TREES]; + transp = SXW->transpVeg[SW_TREES]; break; case 1://Shrub - transp = SXW.transpVeg[SW_SHRUB]; + transp = SXW->transpVeg[SW_SHRUB]; break; case 2://Grass - transp = SXW.transpVeg[SW_GRASS]; + transp = SXW->transpVeg[SW_GRASS]; break; case 3://Forb - transp = SXW.transpVeg[SW_FORBS]; + transp = SXW->transpVeg[SW_FORBS]; break; default: - transp = SXW.transpTotal; + transp = SXW->transpTotal; break; } @@ -256,7 +256,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { ForEachTrPeriod(p) { int nLyrs = getNTranspLayers(RGroup[g]->veg_prod_type); for (l = 0; l < nLyrs; l++) { - use_by_group[g] += (RealF) (SXWResources._roots_active_rel[Iglp(g, l, p)] * transp[Ilp(l, p)]); + use_by_group[g] += (RealF) (SXWResources->_roots_active_rel[Iglp(g, l, p)] * transp[Ilp(l, p)]); } } //printf("for groupName= %s, use_by_group[g] in transp= %f \n",RGroup[g]->name,use_by_group[g] ); @@ -269,8 +269,8 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { //This check makes sure any remaining transpiration is divided proportionately among groups. ForEachTrPeriod(p) { - for (t = 0; t < SXW.NSoLyrs; t++) - sumTranspTotal += SXW.transpTotal[Ilp(t, p)]; + for (t = 0; t < SXW->NSoLyrs; t++) + sumTranspTotal += SXW->transpTotal[Ilp(t, p)]; } TranspRemaining = sumTranspTotal - sumUsedByGroup; @@ -278,7 +278,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { /* ------------- Begin testing to see if additional transpiration is necessary ------------- */ - transp_ratio = sumTranspTotal / SXW.ppt; + transp_ratio = sumTranspTotal / SXW->ppt; // Determines if the current year transpiration/ppt is greater than 1 standard deviations away // from the mean. If TRUE, add additional transpiration. @@ -341,7 +341,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { //printf("TranspRemaining: %f\tTranspRemaining+add_transp: %f\n",TranspRemaining,add_transp+TranspRemaining); /* -------------------- Recalculate the window including added_transp in the current year -------------------- */ - RealF added_transp_ratio = transp_window->added_transp / SXW.ppt; + RealF added_transp_ratio = transp_window->added_transp / SXW->ppt; //add added_transp to the average. This is technically part of the current year, so no need to subtract anything. transp_window->average += transp_window->added_transp/transp_window->size; //add added_transp ratio to the ratio average. This is technically part of the current year, so no need to subtract anything. @@ -351,7 +351,7 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { //put the new ratio in the window. Note: oldest_index has not been incremented, so it points to what was just added transp_window->ratios[transp_window->oldest_index] += added_transp_ratio; // calculate the new sum of squares value - RealF totalTranspRatio = (sumTranspTotal + transp_window->added_transp)/SXW.ppt; + RealF totalTranspRatio = (sumTranspTotal + transp_window->added_transp)/SXW->ppt; RealF ssqr = (totalTranspRatio - transp_window->ratio_average) * (totalTranspRatio - transp_window->ratio_average); // Subtract the sum of squares calculated above, which was stored in the array. Replace it with what was just calculated. transp_window->sum_of_sqrs += ssqr - transp_window->SoS_array[transp_window->oldest_index]; diff --git a/sxw_soilwat.c b/sxw_soilwat.c index 79c19555..19a94a7f 100644 --- a/sxw_soilwat.c +++ b/sxw_soilwat.c @@ -60,7 +60,7 @@ extern SW_SITE SW_Site; extern SW_MODEL SW_Model; extern SW_VEGPROD SW_VegProd; -extern SXW_resourceType SXWResources; +extern SXW_resourceType* SXWResources; #ifdef SXW_BYMAXSIZE extern RealF _Grp_BMass[]; /* added 2/28/03 */ @@ -108,9 +108,9 @@ void _sxw_sw_clear_transp(void) { /*======================================================*/ int k; - Mem_Set(SXW.transpTotal, 0, SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + Mem_Set(SXW->transpTotal, 0, SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); ForEachVegType(k) { - Mem_Set(SXW.transpVeg[k], 0, SXW.NPds * SXW.NSoLyrs * sizeof(RealD)); + Mem_Set(SXW->transpVeg[k], 0, SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); } } @@ -133,7 +133,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 1) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_TREES] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_TREES] += (RealF) SXWResources->_roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_TREES] += y->transp_coeff[SW_TREES]; } @@ -143,7 +143,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 2) { if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_SHRUB] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_SHRUB] += (RealF) SXWResources->_roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; /*printf("* lyr=%d, group=%s(%d), type=%d, tl=%d, rootmax=%f, relsize1=%f, relsize2=%f, trco=%f\n", t, RGroup[g]->name, g, RGroup[g]->veg_prod_type, getNTranspLayers(RGroup[g]->veg_prod_type), @@ -159,7 +159,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 3) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_GRASS] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_GRASS] += (RealF) SXWResources->_roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_GRASS] += y->transp_coeff[SW_GRASS]; } @@ -169,7 +169,7 @@ static void _update_transp_coeff(RealF relsize[]) { ForEachGroup(g) if (RGroup[g]->veg_prod_type == 4) if (getNTranspLayers(RGroup[g]->veg_prod_type)) - y->transp_coeff[SW_FORBS] += (RealF) SXWResources._roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + y->transp_coeff[SW_FORBS] += (RealF) SXWResources->_roots_max[Ilg(t, g)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; sum[SW_FORBS] += y->transp_coeff[SW_FORBS]; } @@ -256,24 +256,24 @@ static void _update_productivity(void) { ForEachGroup(g) { if (1 == RGroup[g]->veg_prod_type) { //tree - v->veg[SW_TREES].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_TREES].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_TREES].pct_live[m] += SXWResources->_prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_TREES].biomass[m] += SXWResources->_prod_bmass[Igp(g, m)] * bmassg[g]; } else if (2 == RGroup[g]->veg_prod_type) { //shrub - v->veg[SW_SHRUB].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_SHRUB].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_SHRUB].pct_live[m] += SXWResources->_prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_SHRUB].biomass[m] += SXWResources->_prod_bmass[Igp(g, m)] * bmassg[g]; } else if (3 == RGroup[g]->veg_prod_type) { //grass - v->veg[SW_GRASS].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_GRASS].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_GRASS].pct_live[m] += SXWResources->_prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_GRASS].biomass[m] += SXWResources->_prod_bmass[Igp(g, m)] * bmassg[g]; } else if (4 == RGroup[g]->veg_prod_type) { //forb - v->veg[SW_FORBS].pct_live[m] += SXWResources._prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; - v->veg[SW_FORBS].biomass[m] += SXWResources._prod_bmass[Igp(g, m)] * bmassg[g]; + v->veg[SW_FORBS].pct_live[m] += SXWResources->_prod_pctlive[Igp(g, m)] * RGroup[g]->rgroupFractionOfVegTypeBiomass; + v->veg[SW_FORBS].biomass[m] += SXWResources->_prod_bmass[Igp(g, m)] * bmassg[g]; } } - v->veg[SW_TREES].litter[m] = (vegTypeBiomass[0] * SXWResources._prod_litter[m]); - v->veg[SW_SHRUB].litter[m] = (vegTypeBiomass[1] * SXWResources._prod_litter[m]); - v->veg[SW_GRASS].litter[m] = (vegTypeBiomass[2] * SXWResources._prod_litter[m]); - v->veg[SW_FORBS].litter[m] = (vegTypeBiomass[3] * SXWResources._prod_litter[m]); + v->veg[SW_TREES].litter[m] = (vegTypeBiomass[0] * SXWResources->_prod_litter[m]); + v->veg[SW_SHRUB].litter[m] = (vegTypeBiomass[1] * SXWResources->_prod_litter[m]); + v->veg[SW_GRASS].litter[m] = (vegTypeBiomass[2] * SXWResources->_prod_litter[m]); + v->veg[SW_FORBS].litter[m] = (vegTypeBiomass[3] * SXWResources->_prod_litter[m]); } } diff --git a/sxw_sql.c b/sxw_sql.c index 0112abcf..50b6eac2 100644 --- a/sxw_sql.c +++ b/sxw_sql.c @@ -15,10 +15,10 @@ #include "sxw.h" extern SW_MODEL SW_Model; -extern SXW_t SXW; +extern SXW_t* SXW; extern SW_SITE SW_Site; extern SW_VEGPROD SW_VegProd; -extern SXW_resourceType SXWResources; +extern SXW_resourceType* SXWResources; static sqlite3 *db; static char sql[1024]; @@ -119,7 +119,7 @@ void insertSXWPhen(void) { { for(m=0;m<12;m++) { sql[0] = 0; - sprintf(sql, "INSERT INTO sxwphen (RGroupID, Month, GrowthPCT) VALUES (%d, %d, %f);", g+1, m+1,SXWResources._phen[Igp(g,m)]); + sprintf(sql, "INSERT INTO sxwphen (RGroupID, Month, GrowthPCT) VALUES (%d, %d, %f);", g+1, m+1,SXWResources->_phen[Igp(g,m)]); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); } @@ -139,7 +139,7 @@ void insertSXWProd(void) { for(m=0;m<12;m++) { sql[0] = 0; sprintf(sql, "INSERT INTO sxwprod (RGroupID, Month, BMASS, LITTER, PCTLIVE) VALUES (%d, %d, %f, %f, %f);", - g+1, m+1, SXWResources._prod_bmass[Igp(g,m)], SXWResources._prod_litter[m], SXWResources._prod_pctlive[Igp(g,m)]); + g+1, m+1, SXWResources->_prod_bmass[Igp(g,m)], SXWResources->_prod_litter[m], SXWResources->_prod_pctlive[Igp(g,m)]); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); } @@ -154,7 +154,7 @@ void insertInfo() { beginTransaction(); sprintf(sql, "INSERT INTO info (StartYear, Years, Iterations, RGroups, TranspirationLayers, SoilLayers, PlotSize, BVT) VALUES (%d, %d, %d, %d, %d, %d, %f, %f);", - SW_Model.startyr, Globals->runModelYears, Globals->runModelIterations, Globals->grpCount, SXW.NTrLyrs, SXW.NSoLyrs, Globals->plotsize, SXWResources._bvt); + SW_Model.startyr, Globals->runModelYears, Globals->runModelIterations, Globals->grpCount, SXW->NTrLyrs, SXW->NSoLyrs, Globals->plotsize, SXWResources->_bvt); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); endTransaction(); @@ -337,9 +337,9 @@ void insertOutputVars(RealF * _resource_cur, RealF added_transp) { ForEachTrPeriod(p) { - //ForEachTranspLayer(t) sum += SXW.transp[Ilp(t,p)]; - for (t = 0; t < SXW.NSoLyrs; t++) - sum += SXW.transpTotal[Ilp(t, p)]; + //ForEachTranspLayer(t) sum += SXW->transp[Ilp(t,p)]; + for (t = 0; t < SXW->NSoLyrs; t++) + sum += SXW->transpTotal[Ilp(t, p)]; } ForEachGroup(r) { @@ -348,7 +348,7 @@ void insertOutputVars(RealF * _resource_cur, RealF added_transp) { sum3 += _resource_cur[r]; } beginTransaction(); - insertSXWoutputVarsRow(Year, Iteration, Env->ppt, Env->temp, SXW.aet, sum, added_transp, sum+added_transp, sum1,sum2,sum3); + insertSXWoutputVarsRow(Year, Iteration, Env->ppt, Env->temp, SXW->aet, sum, added_transp, sum+added_transp, sum1,sum2,sum3); endTransaction(); } @@ -382,7 +382,7 @@ void insertRgroupInfo(RealF * _resource_cur) { beginTransaction(); ForEachGroup(r) { - insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),RGroup[r]->relsize, RGroup[r]->pr, _resource_cur[r]/SXWResources._bvt, _resource_cur[r]); + insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),RGroup[r]->relsize, RGroup[r]->pr, _resource_cur[r]/SXWResources->_bvt, _resource_cur[r]); } endTransaction(); } @@ -495,7 +495,7 @@ void insertRootsSum(RealD * _roots_active_sum) { beginTransaction(); for(i=1; i<=4; i++) { - for (l = 0; l < SXW.NTrLyrs; l++) { + for (l = 0; l < SXW->NTrLyrs; l++) { for (p = 0; p < 12; p++) { m[p] = _roots_active_sum[Itlp(i-1,l, p)]; } @@ -603,42 +603,42 @@ void insertTranspiration() { beginTransaction(); //Total - 0 - for (l = 0; l < SXW.NSoLyrs; l++) { + for (l = 0; l < SXW->NSoLyrs; l++) { for(p=0;p<12;p++) { - m[p] = SXW.transpTotal[Ilp(l, p)]; + m[p] = SXW->transpTotal[Ilp(l, p)]; } insertSXWoutputTranspirationRow(Year,Iteration,l+1,0,m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8],m[9],m[10],m[11]); } //Tree - 1 - for (l = 0; l < SXW.NSoLyrs; l++) { + for (l = 0; l < SXW->NSoLyrs; l++) { for(p=0;p<12;p++) { - m[p] = SXW.transpVeg[SW_TREES][Ilp(l, p)]; + m[p] = SXW->transpVeg[SW_TREES][Ilp(l, p)]; } insertSXWoutputTranspirationRow(Year,Iteration,l+1,1,m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8],m[9],m[10],m[11]); } //Shrub - 2 - for (l = 0; l < SXW.NSoLyrs; l++) { + for (l = 0; l < SXW->NSoLyrs; l++) { for(p=0;p<12;p++) { - m[p] = SXW.transpVeg[SW_SHRUB][Ilp(l, p)]; + m[p] = SXW->transpVeg[SW_SHRUB][Ilp(l, p)]; } insertSXWoutputTranspirationRow(Year,Iteration,l+1,2,m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8],m[9],m[10],m[11]); } //Grass - 3 - for (l = 0; l < SXW.NSoLyrs; l++) { + for (l = 0; l < SXW->NSoLyrs; l++) { for (p = 0; p < 12; p++) { - m[p] = SXW.transpVeg[SW_GRASS][Ilp(l, p)]; + m[p] = SXW->transpVeg[SW_GRASS][Ilp(l, p)]; } insertSXWoutputTranspirationRow(Year, Iteration, l+1, 3, m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11]); } //Forb - 4 - for (l = 0; l < SXW.NSoLyrs; l++) { + for (l = 0; l < SXW->NSoLyrs; l++) { for (p = 0; p < 12; p++) { - m[p] = SXW.transpVeg[SW_FORBS][Ilp(l, p)]; + m[p] = SXW->transpVeg[SW_FORBS][Ilp(l, p)]; } insertSXWoutputTranspirationRow(Year, Iteration, l+1, 4, m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11]); @@ -684,9 +684,9 @@ void insertSWCBulk() { int Iteration = Globals->currIter; beginTransaction(); - for (l = 0; l < SXW.NSoLyrs; l++) { + for (l = 0; l < SXW->NSoLyrs; l++) { for(p=0;p<12;p++) { - m[p] = SXW.swc[Ilp(l, p)]; + m[p] = SXW->swc[Ilp(l, p)]; } insertSXWoutputSWCBulkRow(Year,Iteration,l+1,m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8],m[9],m[10],m[11]); } diff --git a/sxw_tester.c b/sxw_tester.c index f0656905..a99c1dd8 100644 --- a/sxw_tester.c +++ b/sxw_tester.c @@ -99,7 +99,7 @@ static void _print_results(void) { ForEachTrPeriod(pd) { LOG(fp,"%d", pd); ForEachTreeTranspLayer(lyr) - LOG(fp,"\t%5.4f", SXW.transpTotal[Ilp(lyr,pd)]); + LOG(fp,"\t%5.4f", SXW->transpTotal[Ilp(lyr,pd)]); LOG_NL; } @@ -165,7 +165,7 @@ static void _print_results(void) { sum = 0.; ForEachTreeTranspLayer(lyr) { sum += _roots_active[Iglp(g,lyr,pd)] - * SXW.transpTotal[Ilp(lyr,pd)]; + * SXW->transpTotal[Ilp(lyr,pd)]; } LOG(fp,"\t%5.4f", sum); } @@ -179,7 +179,7 @@ static void _read_test_data( void) { /*======================================================*/ /* Read a set of arbitrary (non-baseline) group sizes and * transpiration values and populates the RGroup[g].relsizes - * and the SXW.transp array. This simulates retrieval from + * and the SXW->transp array. This simulates retrieval from * soilwat. */ LyrIndex lyr, cnt; @@ -202,7 +202,7 @@ static void _read_test_data( void) { cnt=0; while( GetALine(fp, inbuf) ) { p = strtok(inbuf,", \t"); /* g'teed to work via GetALine() */ - if (++cnt > SXW.NPds) break; + if (++cnt > SXW->NPds) break; pd = atoi(p) -1; lyr = 0; @@ -212,20 +212,20 @@ static void _read_test_data( void) { "Compare with soil layer definitions for SOILWAT.", fname); } - SXW.transpTotal[Ilp(lyr,pd)] = atof(p); + SXW->transpTotal[Ilp(lyr,pd)] = atof(p); lyr++; } } - if (cnt > SXW.NPds) { + if (cnt > SXW->NPds) { LogError(logfp, LOGFATAL, "Too many time periods found in %s. Expected %d.", - fname, SXW.NPds); + fname, SXW->NPds); } - if (cnt < SXW.NPds) { + if (cnt < SXW->NPds) { LogError(logfp, LOGFATAL, "Not enough time periods found in %s. Expected %d.", - fname, SXW.NPds); + fname, SXW->NPds); } CloseFile(&fp); diff --git a/sxw_vars.h b/sxw_vars.h index 05a78975..0896c1cb 100644 --- a/sxw_vars.h +++ b/sxw_vars.h @@ -19,7 +19,7 @@ #include "generic.h" -extern SXW_t SXW; +extern SXW_t* SXW; #endif From ca00257b54b1a7616d5302117eeb15439513b4af Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 24 Apr 2019 13:51:06 -0600 Subject: [PATCH 020/167] (issue #247) updated SOILWAT head --- sw_src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sw_src b/sw_src index 28f5cfad..5a23fe37 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit 28f5cfad846e4eb6bbb8ef51daf1cf59b801c47c +Subproject commit 5a23fe37f209b2b957342c68ea689bd3e9ebd9b7 From 804c2e25942ba8c611c50592e10e60ce62143fc5 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 24 Apr 2019 14:27:02 -0600 Subject: [PATCH 021/167] Added call to stat_Copy_Accumulators in load_cell. (issue #272) This takes care of shallow copying the accumulators. --- ST_grid.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index ed25b8ef..ef609071 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -163,10 +163,11 @@ struct grid_cell_st Bool duringSpinup; /* ---------------- accumulators -------------------- */ - StatType _Dist, _Ppt, _Temp, + StatType *_Dist, *_Ppt, *_Temp, *_Grp, *_Gsize, *_Gpr, *_Gmort, *_Gestab, *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; FireStatsType *_Gwf; + Bool stats_init; /* -------------- end accumulators ------------------ */ /* -------------------- SXW ------------------------- */ @@ -286,6 +287,9 @@ void stat_Load_Accumulators(int cell, int year); void stat_Save_Accumulators(int cell, int year); void stat_Free_Accumulators(void); void stat_Init_Accumulators(void); +void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, + StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, + StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); //functions from sxw.c //void free_sxw_memory( void ); @@ -1667,6 +1671,13 @@ static void load_cell(int row, int col){ /* TRUE if this cell is in spinup mode */ DuringSpinup = gridCells[row][col].duringSpinup; + + /* Copy this cell's accumulators into the local accumulators in ST_stats.c */ + stat_Copy_Accumulators(gridCells[row][col]._Dist, gridCells[row][col]._Ppt, gridCells[row][col]._Temp, + gridCells[row][col]._Grp, gridCells[row][col]._Gsize, gridCells[row][col]._Gpr, + gridCells[row][col]._Gmort, gridCells[row][col]._Gestab, gridCells[row][col]._Spp, + gridCells[row][col]._Indv, gridCells[row][col]._Smort, gridCells[row][col]._Sestab, + gridCells[row][col]._Sreceived, gridCells[row][col]._Gwf, gridCells[row][col].stats_init); } /***********************************************************/ From 873a2f5bcc230d7d38f7826fd0b18674560fb026 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 24 Apr 2019 14:38:41 -0600 Subject: [PATCH 022/167] Created and implemented new copy_sxw_variables funciton (issue #277) Created the function. It takes as inputs pointers to the new SXW variables and assigns these pointers to the local variables. (issue #272) Implemented this new function in the load_cell function. --- ST_grid.c | 5 +++++ sxw.c | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index ef609071..bc102d00 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -305,6 +305,8 @@ void save_sxw_memory(RealD * grid_roots_max, RealD* grid_rootsXphen, void _deallocate_memory(void); //void SXW_init( Bool init_SW ); +void copy_sxw(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); + /*********** Locally Used Function Declarations ************/ /***********************************************************/ @@ -1678,6 +1680,9 @@ static void load_cell(int row, int col){ gridCells[row][col]._Gmort, gridCells[row][col]._Gestab, gridCells[row][col]._Spp, gridCells[row][col]._Indv, gridCells[row][col]._Smort, gridCells[row][col]._Sestab, gridCells[row][col]._Sreceived, gridCells[row][col]._Gwf, gridCells[row][col].stats_init); + + /* Copy this cell's SXW variables into the loacl variables in sxw.c */ + copy_sxw(&gridCells[row][col].mySXW, &gridCells[row][col].mySXWResources, &gridCells[row][col].myTranspWindow); } /***********************************************************/ diff --git a/sxw.c b/sxw.c index 09b5122f..64146e93 100644 --- a/sxw.c +++ b/sxw.c @@ -135,6 +135,8 @@ void save_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* gri void free_sxw_memory( void ); void _deallocate_memory(void); +void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); + /****************** Begin Function Code ********************/ /***********************************************************/ void SXW_Init( Bool init_SW, char *f_roots ) { @@ -464,6 +466,13 @@ void _deallocate_memory(void){ Mem_Free(SXWResources); } +/* Shallow copy variables into the local sxw variables. */ +void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window){ + SXW = newSXW; + SXWResources = newSXWResources; + transp_window = newTransp_window; +} + static void _read_files( void ) { /*======================================================*/ /* read list of input files. */ From 8d58b081b3c470802b435ad177ab21df80e2fdc7 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 24 Apr 2019 14:42:19 -0600 Subject: [PATCH 023/167] (issue #277) changed name of copy_sxw function in ST_grid.c changed to copy_sxw_variables to match sxw.c --- ST_grid.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index bc102d00..b762c3f0 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -305,7 +305,7 @@ void save_sxw_memory(RealD * grid_roots_max, RealD* grid_rootsXphen, void _deallocate_memory(void); //void SXW_init( Bool init_SW ); -void copy_sxw(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); +void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); /*********** Locally Used Function Declarations ************/ @@ -1682,7 +1682,7 @@ static void load_cell(int row, int col){ gridCells[row][col]._Sreceived, gridCells[row][col]._Gwf, gridCells[row][col].stats_init); /* Copy this cell's SXW variables into the loacl variables in sxw.c */ - copy_sxw(&gridCells[row][col].mySXW, &gridCells[row][col].mySXWResources, &gridCells[row][col].myTranspWindow); + copy_sxw_variables(&gridCells[row][col].mySXW, &gridCells[row][col].mySXWResources, &gridCells[row][col].myTranspWindow); } /***********************************************************/ From 8a072e5afa9753b958749ba4fa19dd1835db240a Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 25 Apr 2019 14:41:33 -0600 Subject: [PATCH 024/167] (issue #280) removed unused SXW reference in ST_stats.c ST_stats.c externed "SXW_t SXW", but never used the variable. I removed this line and nothing changed. --- ST_stats.c | 1 - 1 file changed, 1 deletion(-) diff --git a/ST_stats.c b/ST_stats.c index 9b715c41..d0ab064f 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -28,7 +28,6 @@ #include "ST_structs.h" #include "ST_stats.h" #include "sxw.h" - extern SXW_t SXW; extern SW_SITE SW_Site; /************ External Variable Declarations ***************/ From 015f54bf972a9012ee5d6aa2e641c6138746ab2c Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 25 Apr 2019 15:57:26 -0600 Subject: [PATCH 025/167] (issue #281) restructured variable _SomeKillage For now this variable has been changed to a pointer and allocated in allocate_Globals. This allows us to move forward with the branch but is not the most readable solution. --- ST_main.c | 2 ++ ST_mortality.c | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/ST_main.c b/ST_main.c index 510613d0..d9d13afa 100644 --- a/ST_main.c +++ b/ST_main.c @@ -40,6 +40,7 @@ extern Bool print_IterationSummary; // defined in `SOILWAT2/SW_Output_outtext.c` extern Bool storeAllIterations; // defined in `SOILWAT2/SW_Output.c` extern SW_VEGPROD SW_VegProd; SW_FILE_STATUS SW_File_Status; +extern Bool* _SomeKillage; /************* External Function Declarations **************/ /***********************************************************/ @@ -413,6 +414,7 @@ void allocate_Globals(void){ Succulent = (SucculentType*) Mem_Calloc(1, sizeof(SucculentType), "allocate_Globals: Succulent"); Globals = (ModelType*) Mem_Calloc(1, sizeof(ModelType), "allocate_Globals: Globals"); Plot = (PlotType*) Mem_Calloc(1, sizeof(PlotType), "allocate_Globals: Plot"); + _SomeKillage = (Bool*) Mem_Calloc(1, sizeof(Bool), "allocate_Globals: _SomeKillage"); } void deallocate_Globals(void){ diff --git a/ST_mortality.c b/ST_mortality.c index 3ba62baa..3fae6220 100644 --- a/ST_mortality.c +++ b/ST_mortality.c @@ -67,7 +67,7 @@ void _kill_extra_growth(void); /************ File-Level Variable Declarations *************/ /***********************************************************/ -Bool _SomeKillage; +Bool *_SomeKillage; /* flag: some plant was reduced and PR is affected. */ /* 7/5/01 - currently flag is set but unused. */ extern @@ -137,7 +137,7 @@ void mort_Main( Bool *killed) { SppIndex sp; GroupType *g; - _SomeKillage = FALSE; + *_SomeKillage = FALSE; ForEachGroup(rg) { g = RGroup[rg]; @@ -197,7 +197,7 @@ void mort_Main( Bool *killed) { } /* end ForEachGroup(rg) */ - *killed = _SomeKillage; + killed = _SomeKillage; } /***********************************************************/ @@ -481,7 +481,7 @@ static void _pat( const SppIndex sp) { } } - if (k >= 0) _SomeKillage = TRUE; + if (k >= 0) *_SomeKillage = TRUE; } @@ -512,7 +512,7 @@ static void _mound( const SppIndex sp) { } - if (k) _SomeKillage = TRUE; + if (k) *_SomeKillage = TRUE; } @@ -538,7 +538,7 @@ static void _burrow( const SppIndex sp) { k = TRUE; } - if (k ) _SomeKillage = TRUE; + if (k ) *_SomeKillage = TRUE; } @@ -576,7 +576,7 @@ static void _succulents( const SppIndex sp) { indiv_Kill_Complete(kills[i], 7); - if (Species[sp]->est_count) _SomeKillage = TRUE; + if (Species[sp]->est_count) *_SomeKillage = TRUE; } @@ -628,7 +628,7 @@ static void _slow_growth( const SppIndex sp) { for( n=0; n <= k; n++ ) indiv_Kill_Complete(kills[n], 8); - if (k >= 0) _SomeKillage = TRUE; + if (k >= 0) *_SomeKillage = TRUE; } /***********************************************************/ @@ -674,7 +674,7 @@ static void _age_independent( const SppIndex sp) { indiv_Kill_Complete(kills[n], 9); } - if (k >= 0) _SomeKillage = TRUE; + if (k >= 0) *_SomeKillage = TRUE; Mem_Free(kills); @@ -723,7 +723,7 @@ static void _no_resources( GrpIndex rg) { for( i=0; i < nk; i++) indiv_Kill_Complete(indv_list[i], 10); - if (nk) _SomeKillage = TRUE; + if (nk) *_SomeKillage = TRUE; /* Check to see if this group's resources have been stretched, * and commit mortality of clonal plants which get additional @@ -786,7 +786,7 @@ static void _stretched_clonal( GrpIndex rg, Int start, Int last, indiv_Kill_Complete(clist[i], 11); } - if (nk >= 0) _SomeKillage = TRUE; + if (nk >= 0) *_SomeKillage = TRUE; } else { /* reduce inverse-proportionally */ @@ -818,7 +818,7 @@ static void _stretched_clonal( GrpIndex rg, Int start, Int last, indiv_reduction); } - if (np >= 0) _SomeKillage = TRUE; + if (np >= 0) *_SomeKillage = TRUE; } /* end if pm*/ } /* end if y >= 1*/ From 5b777b994261d14347aa58d068612ceb41dbef7f Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 25 Apr 2019 16:02:14 -0600 Subject: [PATCH 026/167] (issue #281) added _SomeKillage to deallocate_Globals function --- ST_main.c | 1 + 1 file changed, 1 insertion(+) diff --git a/ST_main.c b/ST_main.c index d9d13afa..7e68570d 100644 --- a/ST_main.c +++ b/ST_main.c @@ -422,6 +422,7 @@ void deallocate_Globals(void){ Mem_Free(Succulent); Mem_Free(Globals); Mem_Free(Plot); + Mem_Free(_SomeKillage); } /**************************************************************/ From 60f9f3df7d5efa83187752fe9af08b81d008fba8 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 30 Apr 2019 15:13:54 -0600 Subject: [PATCH 027/167] Moved allocate_gridCells into _init_grid_inputs (issue #286) This is necessary to ensure that the grid cells are available as soon as possible. --- ST_grid.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index b762c3f0..0e27d74e 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -453,7 +453,6 @@ void runGrid(void) Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; _init_grid_inputs();// reads the grid inputs in & initializes the global grid variables - allocate_gridCells(grid_Rows, grid_Cols); if (sd_Option2a || sd_Option2b) _run_spinup(); // does the initial spinup @@ -802,6 +801,8 @@ static void _init_grid_inputs(void) "Number of cells in grid exceeds MAX_CELLS defined in ST_defines.h"); Globals->nCells = (grid_Cols * grid_Rows); + /* Allocate the 2d array of cells now that we know how many we need */ + allocate_gridCells(grid_Rows, grid_Cols); GetALine(f, buf); i = sscanf(buf, "%d", &UseDisturbances); From a7e5409f6026193c577184eb7b371e2d6ad85fcc Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 1 May 2019 13:35:38 -0600 Subject: [PATCH 028/167] (issue #286) reordered init functions I moved _init_grid_inputs in front of _init_stepwat_inputs so we can allocate the gridCells before they are needed. --- ST_grid.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 0e27d74e..46baacbe 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -448,11 +448,11 @@ void runGrid(void) // this function sets up & runs the grid _init_grid_files(); // reads in files.in file - _init_stepwat_inputs(); // reads the stepwat inputs in + _init_grid_inputs(); // reads the grid inputs in & initializes the global grid variables + _init_stepwat_inputs(); // reads the stepwat inputs in //SWC hist file prefix needs to be cleared Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; - _init_grid_inputs();// reads the grid inputs in & initializes the global grid variables if (sd_Option2a || sd_Option2b) _run_spinup(); // does the initial spinup From d56e1a0642e3b6af4a25e727db2a1d1b1aa5a3f0 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 1 May 2019 13:41:30 -0600 Subject: [PATCH 029/167] Moved local variable declarations to the top, moved function description In RunGrid: declared all local variables at the start of the function. I also moved the function description to the top of the function, since most IDEs look there. --- ST_grid.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 46baacbe..35ceacb3 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -442,10 +442,15 @@ static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w) return result; } -/***********************************************************/ +/* Runs the gridded version of the code */ void runGrid(void) { - // this function sets up & runs the grid + int i, j; + Bool killedany; + IntS year, iter; + double prog_Percent = 0.0, prog_Incr, prog_Acc = 0.0; + char prog_Prefix[32]; + clock_t prog_Time; _init_grid_files(); // reads in files.in file _init_grid_inputs(); // reads the grid inputs in & initializes the global grid variables @@ -457,12 +462,6 @@ void runGrid(void) if (sd_Option2a || sd_Option2b) _run_spinup(); // does the initial spinup - double prog_Percent = 0.0, prog_Incr, prog_Acc = 0.0; - char prog_Prefix[32]; - clock_t prog_Time; - int i, j; - Bool killedany; - IntS year, iter; if (UseProgressBar) { prog_Incr = (((double) 1) From bbe9ba7fc8d62f996fccefef7c70881d1521a277 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 7 May 2019 15:40:21 -0600 Subject: [PATCH 030/167] Added SoilType struct to CellType. (issue #293) This allows each grid cell to hold its own soil info. I also changed the name of the type to SoilType for readability. I added some comments for each variable to make them easier to understand. Lastly, I moved the description of the structs to the top since most IDEs look there for information. --- ST_grid.c | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 35ceacb3..9d73811c 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -93,19 +93,26 @@ /***************** Structure Declarations ******************/ /***********************************************************/ - +// represents a single soil layer struct _grid_soil_lyr_st -{ // represents a single soil layer +{ + // Data for this soil layer float data[11]; + // Vertical width of this layer int width; }typedef Grid_Soil_Lyr; -struct _grid_soil_st -{ //represents the input data for all the soil layers of a cell +//represents the input data for all the soil layers of a cell +struct Soil_st +{ + // Number of soil layers (size of lyr array) int num_layers; + // Name of the roots file belonging to this cell char rootsFile[20]; + // Specific layer's information Grid_Soil_Lyr* lyr; -}typedef Grid_Soil_St; +}typedef SoilType; + struct _grid_disturb_st { @@ -175,6 +182,11 @@ struct grid_cell_st SXW_t mySXW; SXW_resourceType mySXWResources; /* ------------------ End SXW ----------------------- */ + + /* ------------------- Soils ------------------------ */ + // Soil layer information for this cell. + SoilType mySoils; + /* ------------------ End Soils --------------------- */ } typedef CellType; /************ Module Variable Declarations ***************/ @@ -228,7 +240,7 @@ SW_VEGPROD *grid_SW_VegProd, *spinup_SW_VegProd; SW_MODEL *grid_SW_Model, *spinup_SW_Model; // these two variables are used to store the soil/distubance inputs for each grid cell... also dynamically allocated/freed -Grid_Soil_St *grid_Soils; +SoilType *grid_Soils; Grid_Disturb_St *grid_Disturb; Grid_Init_Species_St *grid_initSpecies; @@ -987,7 +999,7 @@ static void _init_grid_globals(void) "_init_grid_globals()"); if (UseSoils) { - grid_Soils = Mem_Calloc(grid_Cells, sizeof(Grid_Soil_St), + grid_Soils = Mem_Calloc(grid_Cells, sizeof(SoilType), "_init_grid_globals()"); for (i = 0; i < grid_Cells; i++) grid_Soils[i].num_layers = 0; From c648091cc29c7195e3ef5e17fd657e0ddf37dbe9 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 9 May 2019 15:30:51 -0600 Subject: [PATCH 031/167] Added init Species struct to CellType struct (issue #296) I also allocated memory for mySpeciesInit and mySoils in allocate_gridCells because there is no existing functionality to allocate them. --- ST_grid.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index 9d73811c..b89666cc 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -144,7 +144,10 @@ struct _grid_sxw_st struct _grid_init_species_st { + /* TRUE is this cell should use spinup */ int use_SpinUp; + /* Array of Boolean values. TRUE if given species + should be included in spinup */ int *species_seed_avail; }typedef Grid_Init_Species_St; @@ -168,6 +171,8 @@ struct grid_cell_st Bool useSeedDispersal; /* TRUE if this cell is in spinup mode */ Bool duringSpinup; + /* species spinup information */ + Grid_Init_Species_St mySpeciesInit; /* ---------------- accumulators -------------------- */ StatType *_Dist, *_Ppt, *_Temp, @@ -877,11 +882,25 @@ static void _init_stepwat_inputs(void) /* Allocates memory for the grid cells. This only needs to be called once. */ static void allocate_gridCells(int rows, int cols){ - int i; + int i, j; gridCells = (CellType**) Mem_Calloc(rows, sizeof(CellType*), "allocate_gridCells: rows"); for(i = 0; i < rows; ++i){ gridCells[i] = (CellType*) Mem_Calloc(cols, sizeof(CellType), "allocate_gridCells: columns"); } + + /* Allocate all fields specific to gridded mode. This is not necessary for fields like mySpecies + since they are allocated elsewhere in the code.*/ + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + // lyr is a dynamically allocated array + gridCells[i][j].mySoils.lyr = (Grid_Soil_Lyr*) + Mem_Calloc(MAX_LAYERS, sizeof(Grid_Soil_Lyr), "allocate_gridCells: mySoils"); + + // species_seed_avail is a dynamically allocated array + gridCells[i][j].mySpeciesInit.species_seed_avail = (int*) + Mem_Calloc(MAX_SPECIES, sizeof(int), "allocate_gridCells: mySpeciesInit"); + } + } } /***********************************************************/ From 7151fe357ef7c09dc0b0bed7a0140f6ff83cee87 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Mon, 13 May 2019 18:08:13 -0600 Subject: [PATCH 032/167] Continued work on RunGrid() (issue #287) * Fixed indentation on RandSeed calls. * Changed for loop from 1-indexed to 0-indexed. * _load_cell to load_cell (my new function). * Moved Plot_Initialize into new loop. Each cell needs to be initialized, not just the one currently loaded. I also set currIter in this new loop. * removed call to stat_Load_Accumulators. Accumulators should be loaded inside load_cell. --- ST_grid.c | 44 ++++++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index b89666cc..50c182ec 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -503,29 +503,30 @@ void runGrid(void) if (BmassFlags.yearly || MortFlags.yearly) parm_Initialize(iter); - Plot_Initialize(); + // Initialize the plot for each grid cell + for (i = 0; i < grid_Rows; i++){ + for (j = 0; j < grid_Cols; j++){ + load_cell(i, j); + Plot_Initialize(); + Globals->currIter = iter; + } + } RandSeed(Globals->randseed, &environs_rng); - RandSeed(Globals->randseed, &mortality_rng); - RandSeed(Globals->randseed, &resgroups_rng); - RandSeed(Globals->randseed, &species_rng); - RandSeed(Globals->randseed, &grid_rng); - RandSeed(Globals->randseed, &markov_rng); - - if (iter > 1) - _free_grid_globals(); //frees the memory from when we called _load_grid_globals() last time... (doesn't need to be called on the first iteration because the memory hasn't been allocated yet) - - Globals->currIter = iter; - _load_grid_globals(); //allocates/initializes grid variables (specifically the ones that are going to change every iter) + RandSeed(Globals->randseed, &mortality_rng); + RandSeed(Globals->randseed, &resgroups_rng); + RandSeed(Globals->randseed, &species_rng); + RandSeed(Globals->randseed, &grid_rng); + RandSeed(Globals->randseed, &markov_rng); for (year = 1; year <= Globals->runModelYears; year++) { //for each year - for (i = 1; i <= grid_Rows; i++) - for (j = 1; j <= grid_Cols; j++) + for (i = 0; i < grid_Rows; i++){ + for (j = 0; j < grid_Cols; j++) { //for each cell //fprintf(stderr, "year: %d", year); - _load_cell(i, j, year, TRUE); + load_cell(i, j); if (year == 1 && (sd_Option2a || sd_Option2b)) { @@ -544,8 +545,6 @@ void runGrid(void) if (year > 1 && UseSeedDispersal) _set_sd_lyppt(i, j); - - rgroup_Establish(); /* excludes annuals */ Env_Generate(); //calls : SXW_Run_SOILWAT() which calls : _sxw_sw_run() which calls : SW_CTL_run_current_year() @@ -581,6 +580,7 @@ void runGrid(void) } } } /* end model run for this cell*/ + } /* end model run for this row */ if (UseSeedDispersal) _do_seed_dispersal(); @@ -618,15 +618,11 @@ void runGrid(void) } // outputs all of the mort and BMass files for each cell... - for (i = 1; i <= grid_Rows; i++) - for (j = 1; j <= grid_Cols; j++) + for (i = 0; i < grid_Rows; i++) + for (j = 0; j < grid_Cols; j++) { - int cell = j + ((i - 1) * grid_Cols) - 1; - _load_cell(i, j, 1, TRUE); - for (year = 2; year <= Globals->runModelYears; year++) // _load_cell gets the first years accumulators loaded, so we start at 2... - stat_Load_Accumulators(cell, year); - + load_cell(i, j); char fileMort[1024], fileBMass[1024], fileReceivedProb[1024]; sprintf(fileReceivedProb, "%s%d.csv", grid_files[9], cell); From d2788495b948f6fa1ac0fb583546a9a3a64bed3f Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 14 May 2019 15:40:57 -0600 Subject: [PATCH 033/167] Made RunGrid more similar to main (issue #287) * Added proportion_Recovery and save_annual_species_relsize from ST_species.c to ST_grid.c. * Added grazing_EndOfYear from ST_resgroup.c to ST_grid.c. * Removed references to progress bar (for now). * Replaced the gridded recovery and disturbances function and replaced them with the non-gridded versions. * Removed call to _save_cell. This shouldn't be necessary since we shallow copy everything. * Added and changed some documentation. --- ST_grid.c | 84 +++++++++++++++---------------------------------------- 1 file changed, 23 insertions(+), 61 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 50c182ec..ef232fcf 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -269,6 +269,11 @@ void rgroup_Extirpate(GrpIndex rg); /************* External Function Declarations **************/ /***********************************************************/ +//from ST_species.c +void proportion_Recovery(void); +void save_annual_species_relsize(void); + + //from ST_resgroups.c void rgroup_Grow(void); void rgroup_Establish(void); @@ -279,6 +284,7 @@ void rgroup_PartResources(void); //from ST_mortality.c void mort_Main(Bool *killed); void mort_EndOfYear(void); +void grazing_EndOfYear(void); //functions from ST_params.c void parm_Initialize(Int); @@ -365,6 +371,7 @@ static void _do_groups_and_species_extirpate(void); static void _do_grid_proportion_Recovery(int row, int col); static void _do_grid_grazing_EndOfYear(int row, int col); + //static void _copy_species(SpeciesType* to, SpeciesType* from, Bool deep); static IndivType* _create_empty_indv(void); //these 5 functions are used for copying/freeing the linked list of individuals correctly... @@ -479,15 +486,6 @@ void runGrid(void) if (sd_Option2a || sd_Option2b) _run_spinup(); // does the initial spinup - if (UseProgressBar) - { - prog_Incr = (((double) 1) - / ((double) ((Globals->runModelYears * grid_Cells) - * Globals->runModelIterations))); //gets how much progress we'll make in one year towards our goal of iter*years*cells - prog_Time = clock(); //used for timing - sprintf(prog_Prefix, "simulations: "); - } - char aString[2048]; sprintf(aString, "%s/%s", grid_directories[0], SW_Weather.name_prefix); @@ -545,40 +543,31 @@ void runGrid(void) if (year > 1 && UseSeedDispersal) _set_sd_lyppt(i, j); - rgroup_Establish(); /* excludes annuals */ + /* The following functions mimic ST_main.c. load_cell(i, j) ensures that all global variables reference the specific cell */ - Env_Generate(); //calls : SXW_Run_SOILWAT() which calls : _sxw_sw_run() which calls : SW_CTL_run_current_year() + rgroup_Establish(); // Establish individuals. Excludes annuals. - rgroup_PartResources(); - rgroup_Grow(); + Env_Generate(); // Generated the SOILWAT environment - mort_Main(&killedany); + rgroup_PartResources(); // Distribute resources + rgroup_Grow(); // Grow - rgroup_IncrAges(); + mort_Main(&killedany); // Mortality that occurs during the growing season - // Added functions for Grazing and mort_end_year as proportional killing effect before exporting biomass end of the year - _do_grid_grazing_EndOfYear(i, j); - _do_grid_disturbances(i, j); + rgroup_IncrAges(); // Increment ages of all plants - stat_Collect(year); + grazing_EndOfYear(); // Livestock grazing + + save_annual_species_relsize(); // Save annuals before we kill them - _save_cell(i, j, year, TRUE); + mort_EndOfYear(); // End of year mortality, for example age. - // Moved kill annual and kill extra growth after we export biomass, we also doing recoverly after killing year - _kill_annuals(); - _do_grid_proportion_Recovery(i, j); - _kill_extra_growth(); + stat_Collect(year); // Update the accumulators + + _kill_annuals(); // Kill annuals + proportion_Recovery(); // Recover from any disturbances + _kill_extra_growth(); // Kill superfluous growth - if (UseProgressBar) - { - prog_Percent += prog_Incr; //updating our percent done - if (prog_Percent > prog_Acc) - { //only update if 1% progress or more has been made since the last time we updated (this check is so it doesn't waste processing time that could be spent running the simulations by updating all of the time) - prog_Acc += 0.01; - _load_bar(prog_Prefix, prog_Time, - (int) (100 * prog_Percent), 100, 100, 10); //display our bar to the console - } - } } /* end model run for this cell*/ } /* end model run for this row */ @@ -605,18 +594,6 @@ void runGrid(void) } /*end iterations */ - if (UseProgressBar) - printf("\rsimulations took approximately: %.2f seconds\n", - ((double) (clock() - prog_Time) / CLOCKS_PER_SEC)); - - if (UseProgressBar) - { - prog_Percent = prog_Acc = 0.0; - prog_Incr = ((double) 1) / ((double) grid_Cells); - prog_Time = clock(); - sprintf(prog_Prefix, "outputting: "); - } - // outputs all of the mort and BMass files for each cell... for (i = 0; i < grid_Rows; i++) for (j = 0; j < grid_Cols; j++) @@ -639,17 +616,6 @@ void runGrid(void) stat_Output_Seed_Dispersal(fileReceivedProb, sd_Sep, sd_MakeHeader); - if (UseProgressBar) - { - prog_Percent += prog_Incr; - if (prog_Percent > prog_Acc) - { - prog_Acc += 0.01; - _load_bar(prog_Prefix, prog_Time, 100 * prog_Percent, 100, - 100, 10); - } - } - } //Here creating grid cells avg values output file char fileBMassCellAvg[1024]; @@ -657,12 +623,8 @@ void runGrid(void) if (BmassFlags.summary) stat_Output_AllCellAvgBmass(fileBMassCellAvg); - if (UseProgressBar) - printf("\routputting files took approximately %.2f seconds\n", - ((double) (clock() - prog_Time) / CLOCKS_PER_SEC)); _free_grid_memory(); // free our allocated memory since we do not need it anymore _deallocate_memory(); // sxw memory. - /*if(UseProgressBar)*/printf("!\n"); } /***********************************************************/ From 915086b45a121a948e8d7426229d5cf754def0b5 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 14 May 2019 16:59:57 -0600 Subject: [PATCH 034/167] Resolved incompatibility resulting from merging master into this branch * Updated SOILWAT2 head. * Changed two Globals references to pointers. --- ST_species.c | 2 +- sw_src | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ST_species.c b/ST_species.c index 14d4d668..e99a3c0b 100644 --- a/ST_species.c +++ b/ST_species.c @@ -289,7 +289,7 @@ void Species_Update_Newsize(SppIndex sp, RealF newsize) if(Species[sp]->relsize < 0){ LogError(logfp, LOGWARN, "Species_Update_Newsize: sum of %s individuals' relsizes = %f at year %d, iteration %d.", Species[sp]->name, - Species[sp]->relsize, Globals.currYear, Globals.currIter); + Species[sp]->relsize, Globals->currYear, Globals->currIter); Species[sp]->relsize = 0.0; } diff --git a/sw_src b/sw_src index f1483aa8..611c464e 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit f1483aa86da2ab050356fd6fbec940330904e136 +Subproject commit 611c464ea4a1d42b21dd10d447ad0cd31d4e34b8 From 1003e0c9797c001027048942cf06cbe8bbf672df Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 17 May 2019 12:12:58 -0600 Subject: [PATCH 035/167] Removed load_spinup_cell call and renamed a variable (issue #287) * aString -> SW_prefix_permanent. This name is more descriptive of what the variable does. * Removed _load_spinup_cell call. Instead, we will use the regular cells with dummy accumulators for spinup. * I also moved the call to allocate_Globals in ST_main to after would branch to gridded mode. This way we do not get a memory leak. --- ST_grid.c | 20 +++++--------------- ST_main.c | 3 ++- 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index ef232fcf..9fd0622d 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -486,8 +486,10 @@ void runGrid(void) if (sd_Option2a || sd_Option2b) _run_spinup(); // does the initial spinup - char aString[2048]; - sprintf(aString, "%s/%s", grid_directories[0], SW_Weather.name_prefix); + // SOILWAT resets SW_Weather.name_prefix every iteration. This is not the behavior we want + // so the name is stored here. + char SW_prefix_permanent[2048]; + sprintf(SW_prefix_permanent, "%s/%s", grid_directories[0], SW_Weather.name_prefix); for (iter = 1; iter <= Globals->runModelIterations; iter++) { //for each iteration @@ -496,7 +498,7 @@ void runGrid(void) * 06/15/2016 (akt) Added resetting correct historical weather file path, * as it was resetting to original path value (that was not correct for grid version)from input file after every iteration */ - sprintf(SW_Weather.name_prefix, "%s", aString); //updates the directory correctly for the weather files so soilwat can find them + sprintf(SW_Weather.name_prefix, "%s", SW_prefix_permanent); //updates the directory correctly for the weather files so soilwat can find them if (BmassFlags.yearly || MortFlags.yearly) parm_Initialize(iter); @@ -526,18 +528,6 @@ void runGrid(void) //fprintf(stderr, "year: %d", year); load_cell(i, j); - if (year == 1 && (sd_Option2a || sd_Option2b)) - { - //TODO: DM finish this... - - int cell = j + ((i - 1) * grid_Cols) - 1; // converts the row/col into an array index - int spinup_cell = grid_SoilTypes[cell]; // gets us the actual cell we want to load up from the spinup - - if ((sd_Option2b && grid_initSpecies[cell].use_SpinUp) - || sd_Option2a) - _load_spinup_cell(spinup_cell); // loads the spinup cell into the global variables - } - Globals->currYear = year; if (year > 1 && UseSeedDispersal) diff --git a/ST_main.c b/ST_main.c index 7e68570d..0baf600c 100644 --- a/ST_main.c +++ b/ST_main.c @@ -162,7 +162,6 @@ int main(int argc, char **argv) { storeAllIterations = FALSE; // dont want to store all soilwat output iterations unless -i flag STdebug_requested = FALSE; - allocate_Globals(); init_args(argc, argv); // read input arguments and intialize proper flags printf("STEPWAT init_args() executed successfully \n"); @@ -172,6 +171,8 @@ int main(int argc, char **argv) { return 0; } + allocate_Globals(); + parm_Initialize(0); SXW_Init(TRUE, NULL); // allocate SOILWAT2-memory From d893eb8843a1e341c71e7f0fd3f447f64b3204f8 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 17 May 2019 13:40:50 -0600 Subject: [PATCH 036/167] Changed structure and function calls of _run_spinup (issue #300) * spinup now mimics run_grid without seed dispersal or stats. * Added dummy accumulators to ensure that even if someone calls stat_Collect in spinup nothing will change. * Restructured spinup: We now loop through all cells and run spinup on the ones that requested it. * Removed calls to _init_spinup_globals and _load_spinup_globals. These are no longer necessary because we are using the actual gridCells. --- ST_grid.c | 77 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 49 insertions(+), 28 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 9fd0622d..cb12b84c 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -620,10 +620,12 @@ void runGrid(void) /***********************************************************/ static void _run_spinup(void) { - + StatType *dummy_Dist, *dummy_Ppt, *dummy_Temp, + *dummy_Grp, *dummy_Gsize, *dummy_Gpr, *dummy_Gmort, *dummy_Gestab, + *dummy_Spp, *dummy_Indv, *dummy_Smort, *dummy_Sestab, *dummy_Sreceived; + FireStatsType *dummy_Gwf; //does the spinup, it's pretty much like running the grid, except some differences like no seed dispersal and no need to deal with output accumulators - - int i, spinup_Cell; + int i, j; Bool killedany; IntS year, iter; @@ -637,12 +639,17 @@ static void _run_spinup(void) grid_SoilTypes[i] = 0; } - _init_spinup_globals(); - _load_spinup_globals(); - for (iter = 1; iter <= 1; iter++) { //for each iteration... only 1 iteration allowed for now + /* Since this is technically an iteration so we need to seed the RNGs. */ + RandSeed(Globals->randseed, &environs_rng); + RandSeed(Globals->randseed, &mortality_rng); + RandSeed(Globals->randseed, &resgroups_rng); + RandSeed(Globals->randseed, &species_rng); + RandSeed(Globals->randseed, &grid_rng); + RandSeed(Globals->randseed, &markov_rng); + if (BmassFlags.yearly || MortFlags.yearly) parm_Initialize(iter); @@ -653,39 +660,53 @@ static void _run_spinup(void) for (year = 1; year <= Globals->runModelYears; year++) { //for each year - for (spinup_Cell = 0; spinup_Cell < nSoilTypes; spinup_Cell++) - { // for each different soil type - - //int cell = soilTypes_Array[spinup_Cell]; // this is the first cell of this soiltypes actual cell number - //int j = cell % grid_Cols + 1; // this is the column of the first cell of this soiltype - //int i = ((cell + 1 - j) / grid_Cols) + 1; // this is the row of the first cell of this soiltype + for (i = 0; i < grid_Rows; ++i) + { // for each row + for(j = 0; j < grid_Cols; ++j) + { // for each column + // If we should run spinup on this cell + if(gridCells[i][j].mySpeciesInit.use_SpinUp){ + // Load up a cell + load_cell(i, j); + } else { + continue; // No spinup requested. Move on to next cell. + } - _load_spinup_cell(spinup_Cell); - Globals->currYear = year; + /* This step is important. load_cell loaded in the actual accumulators, but we do not want + to accumulate stats while in spinup. We need to load in dummy accumulators to ensure + we ignore everything that happens in spinup. */ + stat_Copy_Accumulators(dummy_Dist, dummy_Ppt, dummy_Temp, dummy_Grp, dummy_Gsize, dummy_Gpr, dummy_Gmort, dummy_Gestab, + dummy_Spp, dummy_Indv, dummy_Smort, dummy_Sestab, dummy_Sreceived, dummy_Gwf, TRUE); - // _do_grid_disturbances(i, j); + Globals->currYear = year; - rgroup_Establish(); /* excludes annuals */ + rgroup_Establish(); // Establish individuals. Excludes annuals. - Env_Generate(); //calls : SXW_Run_SOILWAT() which calls : _sxw_sw_run() which calls : SW_CTL_run_current_year() + Env_Generate(); // Generated the SOILWAT environment - rgroup_PartResources(); - rgroup_Grow(); + rgroup_PartResources(); // Distribute resources + rgroup_Grow(); // Grow - mort_Main(&killedany); + mort_Main(&killedany); // Mortality that occurs during the growing season - rgroup_IncrAges(); + rgroup_IncrAges(); // Increment ages of all plants - stat_Collect(year); - //mort_EndOfYear(); - _save_spinup_cell(spinup_Cell); + grazing_EndOfYear(); // Livestock grazing + + //save_annual_species_relsize(); // See stat_Collect below for why this is commented out. - _kill_annuals(); - _kill_extra_growth(); + mort_EndOfYear(); // End of year mortality, for example age. - } /* end model run for this cell*/ + /* stat_Collect was called in spinup, but I have no idea why. We definitely + do not want to use the accumulator values, so why collect them? -Chandler */ + //stat_Collect(year); - }/* end model run for this year*/ + _kill_annuals(); // Kill annuals + proportion_Recovery(); // Recover from any disturbances + _kill_extra_growth(); // Kill superfluous growth + } /* end column */ + } /* end row */ + } /* end model run for this year*/ ChDir(grid_directories[0]); SXW_Reset(); From 8b6974771e2e480c3a25389150eb66a777a29ba5 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 20 May 2019 09:28:33 -0600 Subject: [PATCH 037/167] Removed assignment of Globals->nCells This line was generating a seg fault because Globals->nCells was never allocated. In addition, nCells is an unnecessary field in myGlobals because it is constant for all cells. (issue #285) --- ST_grid.c | 1 - 1 file changed, 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index cb12b84c..6ac99892 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -785,7 +785,6 @@ static void _init_grid_inputs(void) LogError(logfp, LOGFATAL, "Number of cells in grid exceeds MAX_CELLS defined in ST_defines.h"); - Globals->nCells = (grid_Cols * grid_Rows); /* Allocate the 2d array of cells now that we know how many we need */ allocate_gridCells(grid_Rows, grid_Cols); From 2643aba6cec30bed6e83fb2c0f43d4459cacda8d Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 20 May 2019 14:12:09 -0600 Subject: [PATCH 038/167] Addressed comment made on commit d278849 Age mortality will be implemented in a function created in the clean_code_lowpriority branch. Once that branch is merged this comment will be incorrect. (issues #287 and #300) --- ST_grid.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 6ac99892..0e605ed1 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -550,7 +550,7 @@ void runGrid(void) save_annual_species_relsize(); // Save annuals before we kill them - mort_EndOfYear(); // End of year mortality, for example age. + mort_EndOfYear(); // End of year mortality. stat_Collect(year); // Update the accumulators @@ -695,7 +695,7 @@ static void _run_spinup(void) //save_annual_species_relsize(); // See stat_Collect below for why this is commented out. - mort_EndOfYear(); // End of year mortality, for example age. + mort_EndOfYear(); // End of year mortality. /* stat_Collect was called in spinup, but I have no idea why. We definitely do not want to use the accumulator values, so why collect them? -Chandler */ From ca6c274f9eb0fd09950fd5ed81a488c7dd5af132 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 22 May 2019 14:51:31 -0600 Subject: [PATCH 039/167] Overhauled _init_stepwat_inputs (issue #284) In ST_grid.c: * Changed mySpecies and myGroup to be compatable with the new implementation for RGroup and Species currently in the clean_code_lowpriority branch. This will be folded into gridded_code soon. * Added documentation above _init_stepwat_inputs expalining it's purpose andwhat must be called before it. * Restructured the function suth that tvery gridcell is loaded into globals then parm_Initialize and _init_SXW_inputs are called. In sxw.c: I accounted for gridded mode by wrapping the call to _allocate_memory in an if(!UseGrid) block. This ensures that we do not leak any memory. NOTE: To test these changes I had to modify the code slightly. The following changes need to occur before this commit will actually run, and by run I mean make it through _init_stepwat_inputs: * In parm_Initialize the boolean beenhere needs to be removed. for gridded mode we have multiple cells to initialize and it prevents us for initializing them. * I removed the call to _init_stepwat_inputs from runGrid() and moved it inside _init_grid_inputs. I explain why this needs to be changed in a comment on issue #286. --- ST_grid.c | 30 ++++++++++++++++++------------ sxw.c | 9 ++++++--- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 0e605ed1..b8c05356 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -155,9 +155,9 @@ struct _grid_init_species_st struct grid_cell_st { /* RGroup coresponding to this cell */ - GroupType myGroup; + GroupType *myGroup[MAX_RGROUPS]; /* Species corresponding to this cell */ - SpeciesType mySpecies; + SpeciesType *mySpecies[MAX_SPECIES]; /* Succulents corresponding to this cell */ SucculentType mySucculent; /* This cell's environment. We expect each cell to @@ -834,18 +834,25 @@ static void _init_SXW_inputs(Bool init_SW, char *f_roots) } } -/***********************************************************/ +/* Read in the STEPWAT2 files and populate the grid. This only needs to be called once. + DEPENDENCYS: allocate_gridCells() must be called first. */ static void _init_stepwat_inputs(void) { - // reads in the stepwat inputs - ChDir(grid_directories[0]); // changes to the folder that the stepwat input is in + int i, j; // Used as indices in gridCells - parm_SetFirstName(grid_files[6]);// correctly sets the name of the stepwat files.in file - parm_Initialize(0); // loads stepwat input files + ChDir(grid_directories[0]); // Change to folder with STEPWAT files + parm_SetFirstName(grid_files[6]); // Set the name of the STEPWAT "files.in" file - _init_SXW_inputs(TRUE, NULL); + /* Loop through all gridCells. */ + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + load_cell(i, j); // Load this cell into the global variables + parm_Initialize(0); // Initialize the STEPWAT variables + _init_SXW_inputs(TRUE, NULL); // Initialize the SXW and SOILWAT variables + } /* End for each column */ + } /* End for each row */ - ChDir(".."); // goes back to the folder that we were in + ChDir(".."); // go back to the folder we started in } /* Allocates memory for the grid cells. This only needs to be called once. */ @@ -1648,11 +1655,10 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) /* load gridCells[row][col] into the globals variables */ static void load_cell(int row, int col){ - /* These are commented out until the clean_code_lowpriority - * branch is merged into this branch + /* Commenting this out until clean_code_lowpriority is merged into this branch RGroup = &gridCells[row][col].myGroup; Species = &gridCells[row][col].mySpecies; - */ + */ /* Succulents corresponding to this cell */ Succulent = &gridCells[row][col].mySucculent; diff --git a/sxw.c b/sxw.c index e385804f..edb34ee6 100644 --- a/sxw.c +++ b/sxw.c @@ -153,10 +153,13 @@ void SXW_Init( Bool init_SW, char *f_roots ) { */ char roots[MAX_FILENAMESIZE] = { '\0' }; -RandSeed(Globals->randseed, &resource_rng); + RandSeed(Globals->randseed, &resource_rng); -/* Allocate memory for all local pointers */ -_allocate_memory(); + /* If we are running gridded mode we do not need to allocate any memory + because allocate_gridCells() in ST_grid did it for us. */ + if(!UseGrid){ + _allocate_memory(); //Allocate memory for all local pointers + } #ifdef SXW_BYMAXSIZE GrpIndex rg; SppIndex sp; From f6819faf31ec12ba6dd7ce0060c43ecbdb8f6bbe Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Wed, 22 May 2019 18:51:14 -0400 Subject: [PATCH 040/167] (Issue #305) Uncomment gridded code --- ST_grid.c | 6 +----- ST_main.c | 4 +--- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 9ae682e2..c042a834 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1,5 +1,3 @@ -#if 0 - /********************************************************/ // Source file: ST_grid.c // Type: module @@ -3167,6 +3165,4 @@ static void _read_init_species(void) grid_files[5]); CloseFile(&f); -} - -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/ST_main.c b/ST_main.c index 19e1f64a..67d77241 100644 --- a/ST_main.c +++ b/ST_main.c @@ -68,7 +68,7 @@ extern Bool* _SomeKillage; void stat_Output_AllMorts( void) ; void stat_Output_AllBmass(void) ; - /* void runGrid( void ); //for the grid... declared in ST_grid.c */ + void runGrid( void ); //for the grid... declared in ST_grid.c */ void _kill_annuals(void); void _kill_extra_growth(void); @@ -167,12 +167,10 @@ int main(int argc, char **argv) { printf("STEPWAT init_args() executed successfully \n"); - /* if (UseGrid == TRUE) { runGrid(); return 0; } - */ allocate_Globals(); From 0ec1b8c085115ddba6042332aabb66395ed18e13 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Wed, 22 May 2019 19:30:02 -0400 Subject: [PATCH 041/167] (Issue #306) Multiple changes (read description) * In ST_grid.c, remove argument from parm_Initialize * In ST_grid.c, change static arrays dependent on MAX_RGROUPS and MAX_SPECIES into dynamic arrays * Change member access to pointer-to-member access, especially when involving Globals --- ST_defines.h | 6 +++--- ST_grid.c | 12 ++++++------ ST_indivs.c | 4 ++-- ST_mortality.c | 8 ++++---- ST_params.c | 16 ++++++++-------- ST_resgroups.c | 14 +++++++------- ST_species.c | 2 +- ST_stats.c | 2 +- sxw.c | 6 +++--- sxw.h | 4 ++-- sxw_resource.c | 2 +- sxw_soilwat.c | 2 +- 12 files changed, 39 insertions(+), 39 deletions(-) diff --git a/ST_defines.h b/ST_defines.h index 11f3011c..c95767c5 100644 --- a/ST_defines.h +++ b/ST_defines.h @@ -26,15 +26,15 @@ /*************************************************** * Basic definitions ***************************************************/ -#define MAX_SPECIES (Globals.max_spp_per_grp * Globals.max_rgroups) +#define MAX_SPECIES (Globals->max_spp_per_grp * Globals->max_rgroups) #define MAX_SPECIESNAMELEN 4 /* keep around for SOILWAT for now */ /* output_Bmass_Yearly of ST_output.c and _make_header and _make_header_with_std * of ST_stats.c output different numbers of fields. Set MAX_OUTFIELDS to the * maximum number of fields these three functions are capable of outputting. */ -#define MAX_OUTFIELDS ((MAX_SPECIES * 2) + (Globals.max_rgroups * 6) + 8) +#define MAX_OUTFIELDS ((MAX_SPECIES * 2) + (Globals->max_rgroups * 6) + 8) -#define MAX_FIELDLEN (Globals.max_groupnamelen + 6) /* +6 for xtra chars like _RSize, etc */ +#define MAX_FIELDLEN (Globals->max_groupnamelen + 6) /* +6 for xtra chars like _RSize, etc */ #define MAX_CELLS 10000 // defines the maximum number of cells in the grid option /* Constants for flagging whether a sort is diff --git a/ST_grid.c b/ST_grid.c index c042a834..fa512a53 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -155,9 +155,9 @@ struct _grid_init_species_st struct grid_cell_st { /* RGroup coresponding to this cell */ - GroupType *myGroup[MAX_RGROUPS]; + GroupType **myGroup; /* Species corresponding to this cell */ - SpeciesType *mySpecies[MAX_SPECIES]; + SpeciesType **mySpecies; /* Succulents corresponding to this cell */ SucculentType mySucculent; /* This cell's environment. We expect each cell to @@ -207,8 +207,8 @@ int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader, sd_Option1a, sd_Option1b, sd_Option2a, sd_Option2b; //these are treated like booleans // these variables are for storing the globals in STEPPE... they are dynamically allocated/freed -SpeciesType *grid_Species[MAX_SPECIES], *spinup_Species[MAX_SPECIES]; -GroupType *grid_RGroup[MAX_RGROUPS], *spinup_RGroup[MAX_RGROUPS]; +SpeciesType **grid_Species, **spinup_Species; +GroupType **grid_RGroup, **spinup_RGroup; SucculentType *grid_Succulent, *spinup_Succulent; EnvType *grid_Env, *spinup_Env; PlotType *grid_Plot, *spinup_Plot; @@ -249,7 +249,7 @@ SoilType *grid_Soils; Grid_Disturb_St *grid_Disturb; Grid_Init_Species_St *grid_initSpecies; -Grid_SD_St *grid_SD[MAX_SPECIES]; //for seed dispersal +Grid_SD_St **grid_SD; //for seed dispersal // these variables are used for the soil types in the spinup options int nSoilTypes, *soilTypes_Array, *grid_SoilTypes; @@ -847,7 +847,7 @@ static void _init_stepwat_inputs(void) for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ load_cell(i, j); // Load this cell into the global variables - parm_Initialize(0); // Initialize the STEPWAT variables + parm_Initialize(); // Initialize the STEPWAT variables _init_SXW_inputs(TRUE, NULL); // Initialize the SXW and SOILWAT variables } /* End for each column */ } /* End for each row */ diff --git a/ST_indivs.c b/ST_indivs.c index 220ae183..6c42fd30 100644 --- a/ST_indivs.c +++ b/ST_indivs.c @@ -88,11 +88,11 @@ Bool indiv_New( SppIndex sp) { IndivType *p; static int id=0; - if (Species[sp]->est_count == Globals.max_indivs_per_spp) { + if (Species[sp]->est_count == Globals->max_indivs_per_spp) { LogError(logfp, LOGWARN, "Limit reached: %s is about to get %d " "indivs (max=%d)\n", Species[sp]->name, Species[sp]->est_count +1, - Globals.max_indivs_per_spp); + Globals->max_indivs_per_spp); } p = _create(); diff --git a/ST_mortality.c b/ST_mortality.c index aa3a588d..cf3beed0 100644 --- a/ST_mortality.c +++ b/ST_mortality.c @@ -455,7 +455,7 @@ static void _pat( const SppIndex sp) { Int i, k=-1; IndivType *p, **kills; - kills = (IndivType **)Mem_Calloc(Globals.max_indivs_per_spp, sizeof(IndivType *), "_pat"); + kills = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_pat"); /* ---------------------------------------------*/ /* Generate kill list, depending on sensitivity */ @@ -570,7 +570,7 @@ static void _succulents( const SppIndex sp) { RealF killamt = Succulent->reduction; int i, k=0; - kills = (IndivType **)Mem_Calloc(Globals.max_indivs_per_spp, sizeof(IndivType *), "_succulents"); + kills = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_succulents"); ForEachIndiv (p, Species[sp]) { if ( GT(p->relsize, killamt) ) @@ -618,7 +618,7 @@ static void _slow_growth( const SppIndex sp) { IndivType *ndv, **kills; - kills = (IndivType **)Mem_Calloc(Globals.max_indivs_per_spp, sizeof(IndivType *), "_slow_growth"); + kills = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_slow_growth"); slowrate = RGroup[Species[sp]->res_grp]->slowrate * Species[sp]->max_rate; @@ -775,7 +775,7 @@ static void _stretched_clonal( GrpIndex rg, Int start, Int last, IndivType **clist; /* list of clonal individuals */ - clist = (IndivType **)Mem_Calloc(Globals.max_indivs_per_spp, sizeof(IndivType *), "_stretched_clonal"); + clist = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_stretched_clonal"); /* get a list of remaining clonal plants, still ranked by size */ for( np=-1, i=start; i <= last; i++) { diff --git a/ST_params.c b/ST_params.c index eb0988fb..c32bf718 100644 --- a/ST_params.c +++ b/ST_params.c @@ -701,7 +701,7 @@ static void _maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource groups allowed.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals.max_rgroups) != 1) { + if (sscanf(inbuf, "%zu", &Globals->max_rgroups) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource groups allowed.", MyFileName); } @@ -709,7 +709,7 @@ static void _maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource group name length.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals.max_groupnamelen) != 1) { + if (sscanf(inbuf, "%zu", &Globals->max_groupnamelen) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource group name length.", MyFileName); } @@ -719,7 +719,7 @@ static void _maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species allowed per resource group.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals.max_spp_per_grp) != 1) { + if (sscanf(inbuf, "%zu", &Globals->max_spp_per_grp) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species allowed per resource group.", MyFileName); } @@ -727,7 +727,7 @@ static void _maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum individuals allowed per species.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals.max_indivs_per_spp) != 1) { + if (sscanf(inbuf, "%zu", &Globals->max_indivs_per_spp) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum individuals allowed per species.", MyFileName); } @@ -735,7 +735,7 @@ static void _maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species name length.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals.max_speciesnamelen) != 1) { + if (sscanf(inbuf, "%zu", &Globals->max_speciesnamelen) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species name length.", MyFileName); } @@ -775,8 +775,8 @@ static void _rgroup_init( void) { MyFileName = Parm_name(F_RGroup); f = OpenFile(MyFileName, "r"); - name = (char *)Mem_Calloc(Globals.max_groupnamelen + 1, sizeof(char), "_rgroup_init"); - RGroup = (GroupType **)Mem_Calloc(Globals.max_rgroups, sizeof(GroupType *), "_rgroup_init"); + name = (char *)Mem_Calloc(Globals->max_groupnamelen + 1, sizeof(char), "_rgroup_init"); + RGroup = (GroupType **)Mem_Calloc(Globals->max_rgroups, sizeof(GroupType *), "_rgroup_init"); /* ------------------------------------------------------------*/ /* Install all the defined groups, except for dry/wet/norm parms */ @@ -1026,7 +1026,7 @@ static void _species_init( void) { MyFileName = Parm_name( F_Species); f = OpenFile(MyFileName, "r"); - name = (char *)Mem_Calloc(Globals.max_speciesnamelen + 1, sizeof(char), "_species_init"); + name = (char *)Mem_Calloc(Globals->max_speciesnamelen + 1, sizeof(char), "_species_init"); Species = (SpeciesType **)Mem_Calloc(MAX_SPECIES, sizeof(SpeciesType *), "_species_init"); while( readspp) { diff --git a/ST_resgroups.c b/ST_resgroups.c index a858e96e..2651ed1d 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -301,8 +301,8 @@ void rgroup_ResPartIndiv(void) { *size_base, /* biomass of the functional group */ *size_obase; /* biomass of functional groups that can use extra resources */ - size_base = (RealF *)Mem_Calloc(Globals.max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); - size_obase = (RealF *)Mem_Calloc(Globals.max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); + size_base = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); + size_obase = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); /* Divide each group's normal resources to individuals */ ForEachGroup(rg) { @@ -870,9 +870,9 @@ static GroupType *_create(void) GroupType *p; p = (GroupType *) Mem_Calloc(1, sizeof(GroupType), "_create"); - p->name = (char *) Mem_Calloc(Globals.max_groupnamelen + 1, sizeof(char), "_create"); - p->est_spp = (SppIndex *) Mem_Calloc(Globals.max_spp_per_grp, sizeof(SppIndex), "_create"); - p->species = (SppIndex *) Mem_Calloc(Globals.max_spp_per_grp, sizeof(SppIndex), "_create"); + p->name = (char *) Mem_Calloc(Globals->max_groupnamelen + 1, sizeof(char), "_create"); + p->est_spp = (SppIndex *) Mem_Calloc(Globals->max_spp_per_grp, sizeof(SppIndex), "_create"); + p->species = (SppIndex *) Mem_Calloc(Globals->max_spp_per_grp, sizeof(SppIndex), "_create"); return (p); @@ -896,11 +896,11 @@ GrpIndex RGroup_New(void) /*------------------------------------------------------*/ GrpIndex i = (GrpIndex) Globals->grpCount; - if (++Globals->grpCount > Globals.max_rgroups) + if (++Globals->grpCount > Globals->max_rgroups) { LogError(logfp, LOGFATAL, "Too many groups specified (>%d)!\n" "You must adjust MAX_RGROUPS in maxrgroupspecies.in!", - Globals.max_rgroups); + Globals->max_rgroups); } RGroup[i] = _create(); diff --git a/ST_species.c b/ST_species.c index 151b0ec6..3d8651ff 100644 --- a/ST_species.c +++ b/ST_species.c @@ -385,7 +385,7 @@ static SpeciesType *_create(void) SpeciesType *p; p = (SpeciesType *) Mem_Calloc(1, sizeof(SpeciesType), "Species_Create"); - p->name = Mem_Calloc(Globals.max_speciesnamelen + 1, sizeof(char), "Species_Create"); + p->name = Mem_Calloc(Globals->max_speciesnamelen + 1, sizeof(char), "Species_Create"); return (p); diff --git a/ST_stats.c b/ST_stats.c index 09391baf..2c5157c5 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -351,7 +351,7 @@ static void _init( void) { _Gwf->prescribedFire = (int **) Mem_Calloc( 1, - sizeof(int **) * Globals.max_rgroups, + sizeof(int **) * Globals->max_rgroups, "_stat_init(Gwf->prescribedfire"); ForEachGroup(rg){ diff --git a/sxw.c b/sxw.c index 9e58de55..1905e178 100644 --- a/sxw.c +++ b/sxw.c @@ -160,7 +160,7 @@ void SXW_Init( Bool init_SW, char *f_roots ) { */ char roots[MAX_FILENAMESIZE] = { '\0' }; - _resource_cur = (RealF *)Mem_Calloc(Globals.max_rgroups, sizeof(RealF), "SXW_Init"); + SXWResources->_resource_cur = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "SXW_Init"); RandSeed(Globals->randseed, &resource_rng); @@ -286,7 +286,7 @@ void SXW_Run_SOILWAT (void) { GrpIndex g; RealF *sizes; - sizes = (RealF *)Mem_Calloc(Globals.max_rgroups, sizeof(RealF), "SXW_Run_SOILWAT"); + sizes = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "SXW_Run_SOILWAT"); /* compute production values for transp based on current plant sizes */ ForEachGroup(g) @@ -483,7 +483,7 @@ static void _read_roots_max(void) { char *name; FILE *fp; - name = (char *)Mem_Calloc(Globals.max_groupnamelen + 1, sizeof(char), "_read_roots_max"); + name = (char *)Mem_Calloc(Globals->max_groupnamelen + 1, sizeof(char), "_read_roots_max"); MyFileName = SXW->f_roots; fp = OpenFile(MyFileName, "r"); diff --git a/sxw.h b/sxw.h index da265432..7c00c0f3 100644 --- a/sxw.h +++ b/sxw.h @@ -132,8 +132,8 @@ struct temp_SXW_st{ /* simple vectors hold the resource information for each group */ /* curr/equ gives the available/required ratio */ - RealF _resource_cur[MAX_RGROUPS], /* current resource availability for each STEPPE functional type */ - _resource_pr[MAX_RGROUPS]; /* resource convertable to PR */ + RealF *_resource_cur, /* current resource availability for each STEPPE functional type */ + *_resource_pr; /* resource convertable to PR */ /* one vector for the production constants */ RealD _prod_litter[MAX_MONTHS]; diff --git a/sxw_resource.c b/sxw_resource.c index 19a5a841..022b5fcb 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -104,7 +104,7 @@ void _sxw_update_resource(void) { RealF *sizes; GrpIndex g; - sizes = (RealF *)Mem_Calloc(Globals.max_rgroups, sizeof(RealF), "_sxw_update_resource"); + sizes = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "_sxw_update_resource"); ForEachGroup(g) { diff --git a/sxw_soilwat.c b/sxw_soilwat.c index e95c7565..da22a977 100644 --- a/sxw_soilwat.c +++ b/sxw_soilwat.c @@ -196,7 +196,7 @@ static void _update_productivity(void) { *bmassg, vegTypeBiomass[4] = {0.}; - bmassg = (RealF *)Mem_Calloc(Globals.max_rgroups, sizeof(RealF), "_update_productivity"); + bmassg = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "_update_productivity"); #define Biomass(g) RGroup_GetBiomass(g) From e948b0bb2f0b4377b78f9aa0e776b54d6601f724 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Wed, 22 May 2019 19:57:33 -0400 Subject: [PATCH 042/167] (Issue #306) Change where _resource_cur is initialized --- sxw.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sxw.c b/sxw.c index 1905e178..59dd7c79 100644 --- a/sxw.c +++ b/sxw.c @@ -159,8 +159,6 @@ void SXW_Init( Bool init_SW, char *f_roots ) { * match sxwroots.in */ char roots[MAX_FILENAMESIZE] = { '\0' }; - - SXWResources->_resource_cur = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "SXW_Init"); RandSeed(Globals->randseed, &resource_rng); @@ -170,6 +168,8 @@ void SXW_Init( Bool init_SW, char *f_roots ) { _allocate_memory(); //Allocate memory for all local pointers } + SXWResources->_resource_cur = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "SXW_Init"); + _sxwfiles[0] = &SXW->f_roots; _sxwfiles[1] = &SXW->f_phen; _sxwfiles[3] = &SXW->f_prod; From 0b3274ad2db99b3b16e222e53f83293f4ce99d20 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Wed, 22 May 2019 23:03:05 -0400 Subject: [PATCH 043/167] (Issue #283) Implement grid file and directory enum * Create grid file and directory enum * Replace existing numerical indices with enum constants --- ST_grid.c | 116 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 71 insertions(+), 45 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index fa512a53..09a3fafb 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -197,8 +197,34 @@ struct grid_cell_st /************ Module Variable Declarations ***************/ /***********************************************************/ -#define N_GRID_FILES 11 -#define N_GRID_DIRECTORIES 1 +/* Indices for grid_directories go here */ +enum +{ + GRID_DIRECTORY_STEPWAT_INPUTS, + + /* Automatically generate number of directories since enums start at 0 */ + N_GRID_DIRECTORIES +}; + +/* Indices for grid_files go here */ +enum +{ + GRID_FILE_LOGFILE, + GRID_FILE_SETUP, + GRID_FILE_DISTURBANCES, + GRID_FILE_SOILS, + GRID_FILE_SEED_DISPERSAL, + GRID_FILE_INIT_SPECIES, + GRID_FILE_FILES, + + GRID_FILE_PREFIX_BMASSAVG, + GRID_FILE_PREFIX_MORTAVG, + GRID_FILE_PREFIX_RECEIVEDPROB, + GRID_FILE_PREFIX_BMASSCELLAVG, + + /* Automatically generate number of files since enums start at 0 */ + N_GRID_FILES +}; char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; @@ -489,7 +515,7 @@ void runGrid(void) // SOILWAT resets SW_Weather.name_prefix every iteration. This is not the behavior we want // so the name is stored here. char SW_prefix_permanent[2048]; - sprintf(SW_prefix_permanent, "%s/%s", grid_directories[0], SW_Weather.name_prefix); + sprintf(SW_prefix_permanent, "%s/%s", grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS], SW_Weather.name_prefix); for (iter = 1; iter <= Globals->runModelIterations; iter++) { //for each iteration @@ -576,7 +602,7 @@ void runGrid(void) _save_cell(i, j, Globals->runModelYears, TRUE); } //reset soilwat to initial condition - ChDir(grid_directories[0]); + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); SXW_Reset(); Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; @@ -592,9 +618,9 @@ void runGrid(void) load_cell(i, j); char fileMort[1024], fileBMass[1024], fileReceivedProb[1024]; - sprintf(fileReceivedProb, "%s%d.csv", grid_files[9], cell); - sprintf(fileMort, "%s%d.csv", grid_files[8], cell); - sprintf(fileBMass, "%s%d.csv", grid_files[7], cell); + sprintf(fileReceivedProb, "%s%d.csv", grid_files[GRID_FILE_PREFIX_RECEIVEDPROB], cell); + sprintf(fileMort, "%s%d.csv", grid_files[GRID_FILE_PREFIX_MORTAVG], cell); + sprintf(fileBMass, "%s%d.csv", grid_files[GRID_FILE_PREFIX_BMASSAVG], cell); parm_SetName(fileMort, F_MortAvg); parm_SetName(fileBMass, F_BMassAvg); @@ -609,7 +635,7 @@ void runGrid(void) } //Here creating grid cells avg values output file char fileBMassCellAvg[1024]; - sprintf(fileBMassCellAvg, "%s.csv", grid_files[10]); + sprintf(fileBMassCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_BMASSCELLAVG]); if (BmassFlags.summary) stat_Output_AllCellAvgBmass(fileBMassCellAvg); @@ -708,7 +734,7 @@ static void _run_spinup(void) } /* end row */ } /* end model run for this year*/ - ChDir(grid_directories[0]); + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); SXW_Reset(); //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. Mem_Free(SW_Soilwat.hist.file_prefix); @@ -750,12 +776,12 @@ static void _init_grid_files(void) LogError(stderr, LOGFATAL, "Invalid files.in"); // opens the log file... - if (!strcmp("stdout", grid_files[0])) + if (!strcmp("stdout", grid_files[GRID_FILE_LOGFILE])) logfp = stdout; else - logfp = OpenFile(grid_files[0], "w"); //grid_files[0] is the logfile to use + logfp = OpenFile(grid_files[GRID_FILE_LOGFILE], "w"); - /*printf("stepwat dir: %s\n", grid_directories[0]); + /*printf("stepwat dir: %s\n", grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); for(i = 0; i < N_GRID_FILES; i++) printf("%d : %s\n", i, grid_files[i]);*/ @@ -771,7 +797,7 @@ static void _init_grid_inputs(void) char buf[1024]; int i, j; - f = OpenFile(grid_files[1], "r"); //grid_files[1] is the grid inputs file + f = OpenFile(grid_files[GRID_FILE_SETUP], "r"); GetALine(f, buf); i = sscanf(buf, "%d %d", &grid_Rows, &grid_Cols); @@ -829,7 +855,7 @@ static void _init_SXW_inputs(Bool init_SW, char *f_roots) if (init_SW == TRUE) { char aString[2048]; - sprintf(aString, "%s/%s", grid_directories[0], SW_Weather.name_prefix); + sprintf(aString, "%s/%s", grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS], SW_Weather.name_prefix); sprintf(SW_Weather.name_prefix, "%s", aString); //updates the directory correctly for the weather files so soilwat can find them } } @@ -840,8 +866,8 @@ static void _init_stepwat_inputs(void) { int i, j; // Used as indices in gridCells - ChDir(grid_directories[0]); // Change to folder with STEPWAT files - parm_SetFirstName(grid_files[6]); // Set the name of the STEPWAT "files.in" file + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); // Change to folder with STEPWAT files + parm_SetFirstName(grid_files[GRID_FILE_FILES]); // Set the name of the STEPWAT "files.in" file /* Loop through all gridCells. */ for(i = 0; i < grid_Rows; ++i){ @@ -1079,7 +1105,7 @@ static void _load_grid_globals(void) SppIndex s; if (UseSoils) - ChDir(grid_directories[0]); //change the directory for _init_soil_layers() + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); //change the directory for _init_soil_layers() for (i = 0; i < grid_Cells; i++) { @@ -1190,7 +1216,7 @@ static void _load_spinup_globals(void) SppIndex s; if (UseSoils) - ChDir(grid_directories[0]); //change the directory for _init_soil_layers() + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); //change the directory for _init_soil_layers() for (i = 0; i < nSoilTypes; i++) { @@ -1655,7 +1681,7 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) /* load gridCells[row][col] into the globals variables */ static void load_cell(int row, int col){ - /* Commenting this out until clean_code_lowpriority is merged into this branch + /* Commenting this out until clean_code_lowpriority is merged into this branch RGroup = &gridCells[row][col].myGroup; Species = &gridCells[row][col].mySpecies; */ @@ -2097,7 +2123,7 @@ static void _read_disturbances_in(void) char buf[1024]; int i, cell, num; - f = OpenFile(grid_files[2], "r"); + f = OpenFile(grid_files[GRID_FILE_DISTURBANCES], "r"); GetALine2(f, buf, 1024); // gets rid of the first line (since it just defines the columns) for (i = 0; i < grid_Cells; i++) @@ -2122,11 +2148,11 @@ static void _read_disturbances_in(void) if (num != 12) LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", - grid_files[2], i + 2); + grid_files[GRID_FILE_DISTURBANCES], i + 2); } if (i != grid_Cells) LogError(logfp, LOGFATAL, "Invalid %s file wrong number of cells", - grid_files[2]); + grid_files[GRID_FILE_DISTURBANCES]); CloseFile(&f); } @@ -2182,7 +2208,7 @@ static void _read_soils_in(void) if (sd_Option2a || sd_Option2b) nSoilTypes = 0; //initialize our soil types counter - f = OpenFile(grid_files[3], "r"); + f = OpenFile(grid_files[GRID_FILE_SOILS], "r"); GetALine2(f, buf, 4096); // gets rid of the first line (since it just defines the columns)... it's only there for user readability for (i = 0; i < grid_Cells; i++) @@ -2222,14 +2248,14 @@ static void _read_soils_in(void) if (num < 5) if (!do_copy) - LogError(logfp, LOGFATAL, "Invalid %s file", grid_files[3]); + LogError(logfp, LOGFATAL, "Invalid %s file", grid_files[GRID_FILE_SOILS]); if (!do_copy) stringIndex = _get_value_index2(buf, 5); //gets us the index of the string that is right after what we just parsed in if (num_layers > MAX_LAYERS) LogError(logfp, LOGFATAL, "Invalid %s file line %d num_layers (%d) exceeds MAX_LAYERS (%d)", - grid_files[3], i + 2, num_layers, MAX_LAYERS); + grid_files[GRID_FILE_SOILS], i + 2, num_layers, MAX_LAYERS); if (do_copy == 1 && copy_cell > -1 && copy_cell < grid_Cells && cell != 0 && copy_cell < cell) @@ -2250,7 +2276,7 @@ static void _read_soils_in(void) else if (do_copy == 1) LogError(logfp, LOGFATAL, "Invalid %s file line %d invalid copy_cell attempt", - grid_files[3], i + 2); + grid_files[GRID_FILE_SOILS], i + 2); if (sd_Option2a || sd_Option2b) { @@ -2274,14 +2300,14 @@ static void _read_soils_in(void) if (num != 12) LogError(logfp, LOGFATAL, "Invalid '%s' file line %d invalid soil layer input", - grid_files[3], i + 2); + grid_files[GRID_FILE_SOILS], i + 2); k = stringIndex; stringIndex += _get_value_index(&buf[stringIndex], ',', 12); //updates the index of the string that we are at if (k == stringIndex) LogError(logfp, LOGFATAL, "Invalid %s file line %d not enough soil layers", - grid_files[3], i + 2); + grid_files[GRID_FILE_SOILS], i + 2); for (k = 0; k < 11; k++) grid_Soils[i].lyr[j].data[k] = d[k]; @@ -2292,7 +2318,7 @@ static void _read_soils_in(void) if (i != grid_Cells) LogError(logfp, LOGFATAL, "Invalid %s file, not enough cells", - grid_files[3]); + grid_files[GRID_FILE_SOILS]); /*for(i = 0; i < grid_Cells; i++) { printf("cell %d:\n", i); @@ -2570,26 +2596,26 @@ static void _read_seed_dispersal_in(void) SppIndex s; // read in the seed dispersal input file to get the constants that we need - f = OpenFile(grid_files[4], "r"); + f = OpenFile(grid_files[GRID_FILE_SEED_DISPERSAL], "r"); - VW = _read_a_float(f, buf, grid_files[4], "VW line"); + VW = _read_a_float(f, buf, grid_files[GRID_FILE_SEED_DISPERSAL], "VW line"); GetALine(f, buf); if (sscanf(buf, "%d", &sd_DoOutput) != 1) LogError(logfp, LOGFATAL, - "Invalid %s file: seed dispersal output line\n", grid_files[4]); + "Invalid %s file: seed dispersal output line\n", grid_files[GRID_FILE_SEED_DISPERSAL]); GetALine(f, buf); if (sscanf(buf, "%d", &sd_MakeHeader) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: seed dispersal make header line\n", - grid_files[4]); + grid_files[GRID_FILE_SEED_DISPERSAL]); GetALine(f, buf); if (sscanf(buf, "%c", &sd_Sep) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: seed dispersal seperator line\n", - grid_files[4]); + grid_files[GRID_FILE_SEED_DISPERSAL]); if (sd_Sep == 't') //dealing with tab and space special cases... sd_Sep = '\t'; @@ -2599,32 +2625,32 @@ static void _read_seed_dispersal_in(void) GetALine(f, buf); if (sscanf(buf, "%d", &sd_NYearsSeedsAvailable) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: option 1 line\n", - grid_files[4]); + grid_files[GRID_FILE_SEED_DISPERSAL]); GetALine(f, buf); if (sscanf(buf, "%d", &sd_Option1a) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: option 1a line\n", - grid_files[4]); + grid_files[GRID_FILE_SEED_DISPERSAL]); GetALine(f, buf); if (sscanf(buf, "%d", &sd_Option1b) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: option 1b line\n", - grid_files[4]); + grid_files[GRID_FILE_SEED_DISPERSAL]); GetALine(f, buf); if (sscanf(buf, "%d", &sd_Option2a) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: option 2a line\n", - grid_files[4]); + grid_files[GRID_FILE_SEED_DISPERSAL]); GetALine(f, buf); if (sscanf(buf, "%d", &sd_Option2b) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: option 2b line\n", - grid_files[4]); + grid_files[GRID_FILE_SEED_DISPERSAL]); if ((sd_Option1a && (sd_Option1b || sd_Option2a || sd_Option2b)) || (sd_Option2a && (sd_Option1a || sd_Option1b || sd_Option2b))) LogError(logfp, LOGFATAL, - "Invalid %s file: conflicting options chosen\n", grid_files[4]); + "Invalid %s file: conflicting options chosen\n", grid_files[GRID_FILE_SEED_DISPERSAL]); CloseFile(&f); @@ -3113,7 +3139,7 @@ static void _read_init_species(void) char buf[4096]; //open the file/do the reading - f = OpenFile(grid_files[5], "r"); //grid_files[5] is the grid_initSpecies.csv file + f = OpenFile(grid_files[GRID_FILE_INIT_SPECIES], "r"); GetALine2(f, buf, 4096); // gets rid of the first line (since it just defines the columns)... it's only there for user readability for (i = 0; i < grid_Cells; i++) @@ -3124,7 +3150,7 @@ static void _read_init_species(void) num = sscanf(buf, "%d,%d,%d,%d", &cell, &do_copy, ©_cell, &use_SpinUp); if (num != 4) - LogError(logfp, LOGFATAL, "Invalid %s file", grid_files[5]); + LogError(logfp, LOGFATAL, "Invalid %s file", grid_files[GRID_FILE_INIT_SPECIES]); grid_initSpecies[i].use_SpinUp = use_SpinUp; @@ -3143,7 +3169,7 @@ static void _read_init_species(void) else if (do_copy == 1) LogError(logfp, LOGFATAL, "Invalid %s file line %d invalid copy_cell attempt", - grid_files[5], i + 2); + grid_files[GRID_FILE_INIT_SPECIES], i + 2); //going through each species SppIndex s; @@ -3153,7 +3179,7 @@ static void _read_init_species(void) if (num != 1) LogError(logfp, LOGFATAL, "Invalid %s file line %d invalid species input", - grid_files[5], i + 2); + grid_files[GRID_FILE_INIT_SPECIES], i + 2); grid_initSpecies[i].species_seed_avail[s] = seeds_Avail; stringIndex += _get_value_index(&buf[stringIndex], ',', 1); @@ -3162,7 +3188,7 @@ static void _read_init_species(void) if (i != grid_Cells) LogError(logfp, LOGFATAL, "Invalid %s file, not enough cells", - grid_files[5]); + grid_files[GRID_FILE_INIT_SPECIES]); CloseFile(&f); } \ No newline at end of file From 790eb6c34d00ef31259caf6f60ad3521fa9b4e3f Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 23 May 2019 10:04:05 -0600 Subject: [PATCH 044/167] Spinup now uses the requested species (issue #300) All changes are in _run_Spinup. * Before iterating I swap species_seed_avail[sp] and Species[sp]->use_me. This ensures that the correct species are turned on for spinup as requested in grid_initSpecies.csv. * Of course I then swap them back at the end of spinup. * Lines 668 and 669 are necessary because Globals has not been allocated. gridCells[0][0], however, is guaranteed to exist, otherwise we would have no cells specified in inputs. We therefore use the information from gridCells[0][0] to determine how many iterations and years we run spinup. * I also updated the function description and moved it above the function so IDEs like Visual Studio can find it. * I added descriptions of all function variables to help future programmers. --- ST_grid.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 09a3fafb..ea44772f 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -643,18 +643,34 @@ void runGrid(void) _deallocate_memory(); // sxw memory. } -/***********************************************************/ +/* "Spinup" the model by running for Globals->runModelYears without seed dispersal or statistics outputs. */ static void _run_spinup(void) { + /* Dummy accumulators to ensure we do not collect statistics */ StatType *dummy_Dist, *dummy_Ppt, *dummy_Temp, *dummy_Grp, *dummy_Gsize, *dummy_Gpr, *dummy_Gmort, *dummy_Gestab, *dummy_Spp, *dummy_Indv, *dummy_Smort, *dummy_Sestab, *dummy_Sreceived; FireStatsType *dummy_Gwf; - //does the spinup, it's pretty much like running the grid, except some differences like no seed dispersal and no need to deal with output accumulators + + /* ints used for iterating over gridCells */ int i, j; - Bool killedany; + + /* ints used for iterating over years and iterations */ IntS year, iter; + /* For iterating over RGroup and Species */ + GrpIndex rg; + SppIndex sp; + IntS k; + + /* 'Globals' is not allocated in gridded mode. Therefore we need to implicitely remember years + and iterations. gridCells[0][0] is guaranteed to exist because it is populated first. */ + int iterations = gridCells[0][0].myGlobals.runModelIterations; + int total_years = gridCells[0][0].myGlobals.runModelYears; + + /* killedany for mortality functions, temporary_storage for swapping variables */ + Bool killedany, temporary_storage; + DuringSpinup = TRUE; if (!UseSoils) @@ -681,10 +697,32 @@ static void _run_spinup(void) Plot_Initialize(); - Globals->currIter = iter; - //_load_grid_globals(); //allocates/initializes grid variables (specifically the ones that are going to change every iter) - - for (year = 1; year <= Globals->runModelYears; year++) + /* Before we start iterating we need to swap Species[sp]->use_me and mySpeciesInit.species_seed_avail[sp]. + species_seed_avail is an array of booleans that represent whether the given species should be used + in spinup. use_me is a boolean that represents whether the given species should be used in production. + By swaping them we save space, but we have to remember to swap them back before the production run. */ + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee + that ForEachGroup would iterate correctly */ + + Globals->currIter = iter; // We need to do this before the "years" loop. + + /* Begin swaping variables */ + ForEachGroup(rg){ + ForEachGroupSpp(sp, rg, k){ + // Temporarily store use_me + temporary_storage = Species[sp]->use_me; + // Swap use_me + Species[sp]->use_me = gridCells[i][j].mySpeciesInit.species_seed_avail[sp]; + // Swap species_seed_avail[sp] + gridCells[i][j].mySpeciesInit.species_seed_avail[sp] = temporary_storage; + } /* End for each species */ + } /* End for each group */ + } /* End for each column */ + } /* End for each row */ + + for (year = 1; year <= total_years; year++) { //for each year for (i = 0; i < grid_Rows; ++i) { // for each row @@ -741,7 +779,27 @@ static void _run_spinup(void) SW_Soilwat.hist.file_prefix = NULL; ChDir(".."); //_free_grid_globals(); //free's the grid variables that change every iter - } /*end iterations */ + } /* End iterations */ + + /* Swap back Species[sp]->use_me and species_seed_avail[sp]. */ + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee + that ForEachGroup would iterate correctly */ + + /* Begin swaping variables */ + ForEachGroup(rg){ + ForEachGroupSpp(sp, rg, k){ + // Temporarily store use_me + temporary_storage = Species[sp]->use_me; + // Swap use_me + Species[sp]->use_me = gridCells[i][j].mySpeciesInit.species_seed_avail[sp]; + // Swap species_seed_avail[sp] + gridCells[i][j].mySpeciesInit.species_seed_avail[sp] = temporary_storage; + } /* End for each species */ + } /* End for each group */ + } /* End for each column */ + } /* End for each row */ DuringSpinup = FALSE; } From 3a08b51c47d53a004d575480a1f070a4995aa0d4 Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 23 May 2019 10:29:24 -0600 Subject: [PATCH 045/167] Created unload_cell function. (issue #304) * unload_cell sets all globals pointers to NULL. When used correctly this function will prevent unintended access to a gridCell without specifically loading it into globals. * I also updated the documentation of load_cell to reference unload_cell. --- ST_grid.c | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index ea44772f..8e81a35a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -378,6 +378,7 @@ static void _free_grid_globals(void); static void _free_spinup_globals(void); static void _load_cell(int row, int col, int year, Bool useAccumulators); static void load_cell(int row, int col); +static void unload_cell(void); static void _load_spinup_cell(int cell); static void _save_cell(int row, int col, int year, Bool useAccumulators); static void _save_spinup_cell(int cell); @@ -1737,7 +1738,8 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) grid_SXW_ptrs[cell].prod_pctlive); } -/* load gridCells[row][col] into the globals variables */ +/* Load gridCells[row][col] into the globals variables. + Any call to this function should have an accompanying call to unload_cell(). */ static void load_cell(int row, int col){ /* Commenting this out until clean_code_lowpriority is merged into this branch RGroup = &gridCells[row][col].myGroup; @@ -1774,6 +1776,31 @@ static void load_cell(int row, int col){ copy_sxw_variables(&gridCells[row][col].mySXW, &gridCells[row][col].mySXWResources, &gridCells[row][col].myTranspWindow); } +/* Nullify all global variables. This function should appear after every call to load_cell to prevent + accidental modification of a grid cell. + Example usage: + for i in rows{ + for j in columns{ + load_cell(i, j) + //additional functions + } + } + unload_cell() */ +static void unload_cell(){ + Species = NULL; + RGroup = NULL; + Succulent = NULL; + Env = NULL; + Plot = NULL; + Globals = NULL; + UseSeedDispersal = NULL; + DuringSpinup = NULL; + // Nullify the accumulators + stat_Copy_Accumulators(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,FALSE); + // Nullify sxw + copy_sxw_variables(NULL,NULL,NULL); +} + /***********************************************************/ static void _load_spinup_cell(int cell) { From 78cb4f32239d0dd4eeb439ea381de9c555d1b5ca Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 23 May 2019 10:44:54 -0600 Subject: [PATCH 046/167] Implemented unload_cell. unload_cell is now called after every load_cell loop. --- ST_grid.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 8e81a35a..5b5fbce0 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -538,6 +538,7 @@ void runGrid(void) Globals->currIter = iter; } } + unload_cell(); // Reset the global variables RandSeed(Globals->randseed, &environs_rng); RandSeed(Globals->randseed, &mortality_rng); @@ -587,9 +588,10 @@ void runGrid(void) } /* end model run for this cell*/ } /* end model run for this row */ - if (UseSeedDispersal) _do_seed_dispersal(); + + unload_cell(); // Reset the global variables }/* end model run for this year*/ // collects the data appropriately for the mort output... (ie. fills the accumulators in ST_stats.c with the values that they need) @@ -612,7 +614,7 @@ void runGrid(void) } /*end iterations */ // outputs all of the mort and BMass files for each cell... - for (i = 0; i < grid_Rows; i++) + for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) { int cell = j + ((i - 1) * grid_Cols) - 1; @@ -632,8 +634,10 @@ void runGrid(void) if (UseSeedDispersal && sd_DoOutput) stat_Output_Seed_Dispersal(fileReceivedProb, sd_Sep, sd_MakeHeader); - } + } + unload_cell(); // Reset the global variables + //Here creating grid cells avg values output file char fileBMassCellAvg[1024]; sprintf(fileBMassCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_BMASSCELLAVG]); @@ -722,6 +726,7 @@ static void _run_spinup(void) } /* End for each group */ } /* End for each column */ } /* End for each row */ + unload_cell(); // Reset the global variables for (year = 1; year <= total_years; year++) { //for each year @@ -771,6 +776,8 @@ static void _run_spinup(void) _kill_extra_growth(); // Kill superfluous growth } /* end column */ } /* end row */ + + unload_cell(); // Reset the global variables } /* end model run for this year*/ ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); @@ -801,6 +808,7 @@ static void _run_spinup(void) } /* End for each group */ } /* End for each column */ } /* End for each row */ + unload_cell(); // Reset the global variables DuringSpinup = FALSE; } @@ -936,6 +944,7 @@ static void _init_stepwat_inputs(void) _init_SXW_inputs(TRUE, NULL); // Initialize the SXW and SOILWAT variables } /* End for each column */ } /* End for each row */ + unload_cell(); // Reset the global variables ChDir(".."); // go back to the folder we started in } From a9780333b88e7da5632767fc2522209ebfd55eef Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 23 May 2019 10:48:41 -0600 Subject: [PATCH 047/167] Removed UseSeedDispersal and DuringSpinup from unload_cell The CI checks are stricter than my compiler, and didn't like that I set two booleans to NULL. I therefore removed them from the function. (issue #304) --- ST_grid.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 5b5fbce0..bc45ed8f 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1802,8 +1802,6 @@ static void unload_cell(){ Env = NULL; Plot = NULL; Globals = NULL; - UseSeedDispersal = NULL; - DuringSpinup = NULL; // Nullify the accumulators stat_Copy_Accumulators(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,FALSE); // Nullify sxw From 60724867223b22a73fd3f5552c2fa6c623f05d37 Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 23 May 2019 11:42:28 -0600 Subject: [PATCH 048/167] Uncommented Species and RGroup from load_cell clean_code_lowpriority is merged in so these lines can now be used. (issue #272) --- ST_grid.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index bc45ed8f..7bf60735 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1750,10 +1750,11 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) /* Load gridCells[row][col] into the globals variables. Any call to this function should have an accompanying call to unload_cell(). */ static void load_cell(int row, int col){ - /* Commenting this out until clean_code_lowpriority is merged into this branch - RGroup = &gridCells[row][col].myGroup; - Species = &gridCells[row][col].mySpecies; - */ + /* RGroup for this cell */ + RGroup = gridCells[row][col].myGroup; + + /*Species for this cell */ + Species = gridCells[row][col].mySpecies; /* Succulents corresponding to this cell */ Succulent = &gridCells[row][col].mySucculent; From 5f76e4228d0737674e45c1dd682bd54f3553ceb8 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Thu, 23 May 2019 16:50:06 -0400 Subject: [PATCH 049/167] (Issue #285) Move reading maxrgroupspecies.in outside parm_Initialize --- ST_main.c | 5 +++++ ST_params.c | 3 +-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ST_main.c b/ST_main.c index 67d77241..3e67c834 100644 --- a/ST_main.c +++ b/ST_main.c @@ -75,6 +75,8 @@ extern Bool* _SomeKillage; void _kill_maxage(void); void save_annual_species_relsize(void); + void maxrgroupspecies_init(void); + #ifdef DEBUG_MEM #define chkmem_f CheckMemoryIntegrity(FALSE); #define chkmem_t CheckMemoryIntegrity(TRUE); @@ -167,6 +169,9 @@ int main(int argc, char **argv) { printf("STEPWAT init_args() executed successfully \n"); + /* Read maxrgroupspecies.in before everything else, regardless of gridded or non-gridded mode. */ + maxrgroupspecies_init(); + if (UseGrid == TRUE) { runGrid(); return 0; diff --git a/ST_params.c b/ST_params.c index c32bf718..6b64e98c 100644 --- a/ST_params.c +++ b/ST_params.c @@ -98,7 +98,6 @@ void parm_Initialize() { _plot_init(); _bmassflags_init(); _mortflags_init(); - _maxrgroupspecies_init(); _rgroup_init(); _species_init(); _check_species(); @@ -685,7 +684,7 @@ static void _setNameLen(char *dest, char *src, Int len) { } /**************************************************************/ -static void _maxrgroupspecies_init( void) { +void maxrgroupspecies_init( void) { /*======================================================*/ FILE *f; From 74f2db3f1c642b3776d46249288f1ac9176fb971 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Thu, 23 May 2019 18:52:20 -0400 Subject: [PATCH 050/167] (Issue #307) Create struct for truly global variables Also transferred maxrgroupspecies.in variables to new struct --- ST_defines.h | 7 ++++--- ST_globals.h | 1 + ST_indivs.c | 4 ++-- ST_main.c | 1 + ST_mortality.c | 8 ++++---- ST_params.c | 16 ++++++++-------- ST_resgroups.c | 14 +++++++------- ST_species.c | 2 +- ST_stats.c | 2 +- ST_structs.h | 14 +++++++------- sxw.c | 6 +++--- sxw_resource.c | 2 +- sxw_soilwat.c | 2 +- 13 files changed, 41 insertions(+), 38 deletions(-) diff --git a/ST_defines.h b/ST_defines.h index c95767c5..abf5e061 100644 --- a/ST_defines.h +++ b/ST_defines.h @@ -26,15 +26,15 @@ /*************************************************** * Basic definitions ***************************************************/ -#define MAX_SPECIES (Globals->max_spp_per_grp * Globals->max_rgroups) +#define MAX_SPECIES (SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups) #define MAX_SPECIESNAMELEN 4 /* keep around for SOILWAT for now */ /* output_Bmass_Yearly of ST_output.c and _make_header and _make_header_with_std * of ST_stats.c output different numbers of fields. Set MAX_OUTFIELDS to the * maximum number of fields these three functions are capable of outputting. */ -#define MAX_OUTFIELDS ((MAX_SPECIES * 2) + (Globals->max_rgroups * 6) + 8) +#define MAX_OUTFIELDS ((MAX_SPECIES * 2) + (SuperGlobals.max_rgroups * 6) + 8) -#define MAX_FIELDLEN (Globals->max_groupnamelen + 6) /* +6 for xtra chars like _RSize, etc */ +#define MAX_FIELDLEN (SuperGlobals.max_groupnamelen + 6) /* +6 for xtra chars like _RSize, etc */ #define MAX_CELLS 10000 // defines the maximum number of cells in the grid option /* Constants for flagging whether a sort is @@ -179,6 +179,7 @@ typedef struct plot_st PlotType; typedef struct globals_st ModelType; typedef struct bmassflags_st BmassFlagsType; typedef struct mortflags_st MortFlagsType; +typedef struct superglobals_st GlobalType; #endif diff --git a/ST_globals.h b/ST_globals.h index 6262d7de..a326018d 100644 --- a/ST_globals.h +++ b/ST_globals.h @@ -27,6 +27,7 @@ extern PlotType *Plot; extern ModelType *Globals; extern BmassFlagsType BmassFlags; extern MortFlagsType MortFlags; +extern GlobalType SuperGlobals; extern Bool UseSeedDispersal; extern Bool UseGrid; diff --git a/ST_indivs.c b/ST_indivs.c index 6c42fd30..9554f8c0 100644 --- a/ST_indivs.c +++ b/ST_indivs.c @@ -88,11 +88,11 @@ Bool indiv_New( SppIndex sp) { IndivType *p; static int id=0; - if (Species[sp]->est_count == Globals->max_indivs_per_spp) { + if (Species[sp]->est_count == SuperGlobals.max_indivs_per_spp) { LogError(logfp, LOGWARN, "Limit reached: %s is about to get %d " "indivs (max=%d)\n", Species[sp]->name, Species[sp]->est_count +1, - Globals->max_indivs_per_spp); + SuperGlobals.max_indivs_per_spp); } p = _create(); diff --git a/ST_main.c b/ST_main.c index 3e67c834..0f7b7dd8 100644 --- a/ST_main.c +++ b/ST_main.c @@ -130,6 +130,7 @@ SucculentType *Succulent; EnvType *Env; PlotType *Plot; ModelType *Globals; +GlobalType SuperGlobals; BmassFlagsType BmassFlags; MortFlagsType MortFlags; diff --git a/ST_mortality.c b/ST_mortality.c index cf3beed0..02e44d67 100644 --- a/ST_mortality.c +++ b/ST_mortality.c @@ -455,7 +455,7 @@ static void _pat( const SppIndex sp) { Int i, k=-1; IndivType *p, **kills; - kills = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_pat"); + kills = (IndivType **)Mem_Calloc(SuperGlobals.max_indivs_per_spp, sizeof(IndivType *), "_pat"); /* ---------------------------------------------*/ /* Generate kill list, depending on sensitivity */ @@ -570,7 +570,7 @@ static void _succulents( const SppIndex sp) { RealF killamt = Succulent->reduction; int i, k=0; - kills = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_succulents"); + kills = (IndivType **)Mem_Calloc(SuperGlobals.max_indivs_per_spp, sizeof(IndivType *), "_succulents"); ForEachIndiv (p, Species[sp]) { if ( GT(p->relsize, killamt) ) @@ -618,7 +618,7 @@ static void _slow_growth( const SppIndex sp) { IndivType *ndv, **kills; - kills = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_slow_growth"); + kills = (IndivType **)Mem_Calloc(SuperGlobals.max_indivs_per_spp, sizeof(IndivType *), "_slow_growth"); slowrate = RGroup[Species[sp]->res_grp]->slowrate * Species[sp]->max_rate; @@ -775,7 +775,7 @@ static void _stretched_clonal( GrpIndex rg, Int start, Int last, IndivType **clist; /* list of clonal individuals */ - clist = (IndivType **)Mem_Calloc(Globals->max_indivs_per_spp, sizeof(IndivType *), "_stretched_clonal"); + clist = (IndivType **)Mem_Calloc(SuperGlobals.max_indivs_per_spp, sizeof(IndivType *), "_stretched_clonal"); /* get a list of remaining clonal plants, still ranked by size */ for( np=-1, i=start; i <= last; i++) { diff --git a/ST_params.c b/ST_params.c index 6b64e98c..0ad8faff 100644 --- a/ST_params.c +++ b/ST_params.c @@ -700,7 +700,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource groups allowed.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals->max_rgroups) != 1) { + if (sscanf(inbuf, "%u", &SuperGlobals.max_rgroups) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource groups allowed.", MyFileName); } @@ -708,7 +708,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource group name length.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals->max_groupnamelen) != 1) { + if (sscanf(inbuf, "%u", &SuperGlobals.max_groupnamelen) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource group name length.", MyFileName); } @@ -718,7 +718,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species allowed per resource group.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals->max_spp_per_grp) != 1) { + if (sscanf(inbuf, "%u", &SuperGlobals.max_spp_per_grp) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species allowed per resource group.", MyFileName); } @@ -726,7 +726,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum individuals allowed per species.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals->max_indivs_per_spp) != 1) { + if (sscanf(inbuf, "%u", &SuperGlobals.max_indivs_per_spp) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum individuals allowed per species.", MyFileName); } @@ -734,7 +734,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species name length.", MyFileName); } - if (sscanf(inbuf, "%zu", &Globals->max_speciesnamelen) != 1) { + if (sscanf(inbuf, "%u", &SuperGlobals.max_speciesnamelen) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species name length.", MyFileName); } @@ -774,8 +774,8 @@ static void _rgroup_init( void) { MyFileName = Parm_name(F_RGroup); f = OpenFile(MyFileName, "r"); - name = (char *)Mem_Calloc(Globals->max_groupnamelen + 1, sizeof(char), "_rgroup_init"); - RGroup = (GroupType **)Mem_Calloc(Globals->max_rgroups, sizeof(GroupType *), "_rgroup_init"); + name = (char *)Mem_Calloc(SuperGlobals.max_groupnamelen + 1, sizeof(char), "_rgroup_init"); + RGroup = (GroupType **)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(GroupType *), "_rgroup_init"); /* ------------------------------------------------------------*/ /* Install all the defined groups, except for dry/wet/norm parms */ @@ -1025,7 +1025,7 @@ static void _species_init( void) { MyFileName = Parm_name( F_Species); f = OpenFile(MyFileName, "r"); - name = (char *)Mem_Calloc(Globals->max_speciesnamelen + 1, sizeof(char), "_species_init"); + name = (char *)Mem_Calloc(SuperGlobals.max_speciesnamelen + 1, sizeof(char), "_species_init"); Species = (SpeciesType **)Mem_Calloc(MAX_SPECIES, sizeof(SpeciesType *), "_species_init"); while( readspp) { diff --git a/ST_resgroups.c b/ST_resgroups.c index 2651ed1d..5c3fd9eb 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -301,8 +301,8 @@ void rgroup_ResPartIndiv(void) { *size_base, /* biomass of the functional group */ *size_obase; /* biomass of functional groups that can use extra resources */ - size_base = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); - size_obase = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); + size_base = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); + size_obase = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "rgroup_ResPartIndiv"); /* Divide each group's normal resources to individuals */ ForEachGroup(rg) { @@ -870,9 +870,9 @@ static GroupType *_create(void) GroupType *p; p = (GroupType *) Mem_Calloc(1, sizeof(GroupType), "_create"); - p->name = (char *) Mem_Calloc(Globals->max_groupnamelen + 1, sizeof(char), "_create"); - p->est_spp = (SppIndex *) Mem_Calloc(Globals->max_spp_per_grp, sizeof(SppIndex), "_create"); - p->species = (SppIndex *) Mem_Calloc(Globals->max_spp_per_grp, sizeof(SppIndex), "_create"); + p->name = (char *) Mem_Calloc(SuperGlobals.max_groupnamelen + 1, sizeof(char), "_create"); + p->est_spp = (SppIndex *) Mem_Calloc(SuperGlobals.max_spp_per_grp, sizeof(SppIndex), "_create"); + p->species = (SppIndex *) Mem_Calloc(SuperGlobals.max_spp_per_grp, sizeof(SppIndex), "_create"); return (p); @@ -896,11 +896,11 @@ GrpIndex RGroup_New(void) /*------------------------------------------------------*/ GrpIndex i = (GrpIndex) Globals->grpCount; - if (++Globals->grpCount > Globals->max_rgroups) + if (++Globals->grpCount > SuperGlobals.max_rgroups) { LogError(logfp, LOGFATAL, "Too many groups specified (>%d)!\n" "You must adjust MAX_RGROUPS in maxrgroupspecies.in!", - Globals->max_rgroups); + SuperGlobals.max_rgroups); } RGroup[i] = _create(); diff --git a/ST_species.c b/ST_species.c index 3d8651ff..64891f32 100644 --- a/ST_species.c +++ b/ST_species.c @@ -385,7 +385,7 @@ static SpeciesType *_create(void) SpeciesType *p; p = (SpeciesType *) Mem_Calloc(1, sizeof(SpeciesType), "Species_Create"); - p->name = Mem_Calloc(Globals->max_speciesnamelen + 1, sizeof(char), "Species_Create"); + p->name = Mem_Calloc(SuperGlobals.max_speciesnamelen + 1, sizeof(char), "Species_Create"); return (p); diff --git a/ST_stats.c b/ST_stats.c index 2c5157c5..badb8854 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -351,7 +351,7 @@ static void _init( void) { _Gwf->prescribedFire = (int **) Mem_Calloc( 1, - sizeof(int **) * Globals->max_rgroups, + sizeof(int **) * SuperGlobals.max_rgroups, "_stat_init(Gwf->prescribedfire"); ForEachGroup(rg){ diff --git a/ST_structs.h b/ST_structs.h index 0ae590dd..3301c61b 100644 --- a/ST_structs.h +++ b/ST_structs.h @@ -293,11 +293,6 @@ struct globals_st { transp_window, /* Number of years for which transpiration data is kept*/ nCells; /* number of cells to use in Grid, only applicable if grid function is being used */ IntL randseed; /* random seed from input file */ - size_t max_rgroups, /* Maximum resource groups allowed. */ - max_groupnamelen, /* Maximum resource group name length. */ - max_spp_per_grp, /* Maximum species allowed per resource group. */ - max_indivs_per_spp, /* Maximum individuals allowed per species. */ - max_speciesnamelen; /* Maximum species name length. */ struct outfiles_st bmass, mort; }; @@ -330,7 +325,12 @@ struct mortflags_st { char sep; }; - - +struct superglobals_st { + size_t max_rgroups, /* Maximum resource groups allowed. */ + max_groupnamelen, /* Maximum resource group name length. */ + max_spp_per_grp, /* Maximum species allowed per resource group. */ + max_indivs_per_spp, /* Maximum individuals allowed per species. */ + max_speciesnamelen; /* Maximum species name length. */ +}; #endif diff --git a/sxw.c b/sxw.c index 59dd7c79..1b187495 100644 --- a/sxw.c +++ b/sxw.c @@ -168,7 +168,7 @@ void SXW_Init( Bool init_SW, char *f_roots ) { _allocate_memory(); //Allocate memory for all local pointers } - SXWResources->_resource_cur = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "SXW_Init"); + SXWResources->_resource_cur = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "SXW_Init"); _sxwfiles[0] = &SXW->f_roots; _sxwfiles[1] = &SXW->f_phen; @@ -286,7 +286,7 @@ void SXW_Run_SOILWAT (void) { GrpIndex g; RealF *sizes; - sizes = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "SXW_Run_SOILWAT"); + sizes = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "SXW_Run_SOILWAT"); /* compute production values for transp based on current plant sizes */ ForEachGroup(g) @@ -483,7 +483,7 @@ static void _read_roots_max(void) { char *name; FILE *fp; - name = (char *)Mem_Calloc(Globals->max_groupnamelen + 1, sizeof(char), "_read_roots_max"); + name = (char *)Mem_Calloc(SuperGlobals.max_groupnamelen + 1, sizeof(char), "_read_roots_max"); MyFileName = SXW->f_roots; fp = OpenFile(MyFileName, "r"); diff --git a/sxw_resource.c b/sxw_resource.c index 022b5fcb..e393718d 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -104,7 +104,7 @@ void _sxw_update_resource(void) { RealF *sizes; GrpIndex g; - sizes = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "_sxw_update_resource"); + sizes = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "_sxw_update_resource"); ForEachGroup(g) { diff --git a/sxw_soilwat.c b/sxw_soilwat.c index da22a977..bc3fd0f0 100644 --- a/sxw_soilwat.c +++ b/sxw_soilwat.c @@ -196,7 +196,7 @@ static void _update_productivity(void) { *bmassg, vegTypeBiomass[4] = {0.}; - bmassg = (RealF *)Mem_Calloc(Globals->max_rgroups, sizeof(RealF), "_update_productivity"); + bmassg = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "_update_productivity"); #define Biomass(g) RGroup_GetBiomass(g) From d7faa5082c8d05445276f01a897616b85f8bb880 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Thu, 23 May 2019 19:05:31 -0400 Subject: [PATCH 051/167] (Issue #285) Allow maxrgroupspecies.in to be read --- ST_grid.c | 8 ++++++++ ST_main.c | 8 +++++--- ST_params.c | 7 +++---- testing.sagebrush.master/files.in | 1 + 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 7bf60735..6f35d77e 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -216,6 +216,7 @@ enum GRID_FILE_SEED_DISPERSAL, GRID_FILE_INIT_SPECIES, GRID_FILE_FILES, + GRID_FILE_MAXRGROUPSPECIES, GRID_FILE_PREFIX_BMASSAVG, GRID_FILE_PREFIX_MORTAVG, @@ -356,6 +357,7 @@ void _deallocate_memory(void); void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); +void maxrgroupspecies_init(void); /*********** Locally Used Function Declarations ************/ /***********************************************************/ @@ -864,6 +866,12 @@ static void _init_grid_inputs(void) char buf[1024]; int i, j; + /* Read maxrgroupspecies.in */ + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); + parm_SetName(grid_files[GRID_FILE_MAXRGROUPSPECIES], F_MaxRGroupSpecies); + maxrgroupspecies_init(); + ChDir(".."); + f = OpenFile(grid_files[GRID_FILE_SETUP], "r"); GetALine(f, buf); diff --git a/ST_main.c b/ST_main.c index 0f7b7dd8..a77bddbf 100644 --- a/ST_main.c +++ b/ST_main.c @@ -75,6 +75,7 @@ extern Bool* _SomeKillage; void _kill_maxage(void); void save_annual_species_relsize(void); + void files_init(void); void maxrgroupspecies_init(void); #ifdef DEBUG_MEM @@ -170,14 +171,15 @@ int main(int argc, char **argv) { printf("STEPWAT init_args() executed successfully \n"); - /* Read maxrgroupspecies.in before everything else, regardless of gridded or non-gridded mode. */ - maxrgroupspecies_init(); - if (UseGrid == TRUE) { runGrid(); return 0; } + /* Read files.in and maxrgroupspecies.in before everything else */ + files_init(); + maxrgroupspecies_init(); + allocate_Globals(); parm_Initialize(); diff --git a/ST_params.c b/ST_params.c index 0ad8faff..ba52f15d 100644 --- a/ST_params.c +++ b/ST_params.c @@ -46,16 +46,16 @@ SppIndex species_New(void); void parm_SetFirstName( char *s); void parm_SetName( char *s, int which); void parm_free_memory( void ); + void maxrgroupspecies_init(void); + void files_init(void); /*********** Locally Used Function Declarations ************/ /***********************************************************/ static void _env_init( void); static void _plot_init( void); static void _setNameLen(char *dest, char *src, Int len); -static void _maxrgroupspecies_init( void); static void _rgroup_init( void); static void _species_init( void); -static void _files_init( void ); static void _check_species( void); static void _bmassflags_init( void); static void _mortflags_init( void); @@ -92,7 +92,6 @@ char *MyFileName; /**************************************************************/ void parm_Initialize() { /*======================================================*/ - _files_init(); _model_init(); _env_init(); _plot_init(); @@ -132,7 +131,7 @@ void parm_SetName( char *s, int which) { } /**************************************************************/ -static void _files_init( void ) { +void files_init( void ) { /*======================================================*/ /* 7-May-02 (cwb) added code to interface with SOILWAT */ diff --git a/testing.sagebrush.master/files.in b/testing.sagebrush.master/files.in index 243fc5ff..384dabba 100644 --- a/testing.sagebrush.master/files.in +++ b/testing.sagebrush.master/files.in @@ -11,6 +11,7 @@ Grid_Inputs/grid_seed_dispersal.in # name of grid seed dispersal setup file Grid_Inputs/grid_initSpecies.csv # name of grid species input file files.in # name of stepwat files.in file +Input/maxrgroupspecies.in # name of stepwat maxrgroupspecies.in file Output/g_bmassavg # name of the prefix given to the biomass output files Output/g_mortavg # name of the prefix given to the mortuary output files From 8e71c20ba70e0c2d36567ca432acd456ffd1a358 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 24 May 2019 11:29:18 -0600 Subject: [PATCH 052/167] Removed _copy_species from ST_grid.c (issue #167) This function is not necessary under the new implementation, and since it was already commented out I removed it. --- ST_grid.c | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 6f35d77e..37c5678a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -400,9 +400,6 @@ static void _do_groups_and_species_extirpate(void); static void _do_grid_proportion_Recovery(int row, int col); static void _do_grid_grazing_EndOfYear(int row, int col); - -//static void _copy_species(SpeciesType* to, SpeciesType* from, Bool deep); - static IndivType* _create_empty_indv(void); //these 5 functions are used for copying/freeing the linked list of individuals correctly... static void _free_individuals(IndivType *head); static void _free_head(IndivType *head); @@ -1033,32 +1030,6 @@ static IndivType* _copy_head(IndivType *head) return _copy_individuals(head); } -/**********************************************************/ -/* - static void _copy_species(SpeciesType* to, SpeciesType* from, Bool deep) { - if(deep) { - Mem_Free(to->kills); - Mem_Free(to->seedprod); - _free_head(to->IndvHead); //free_head() frees the memory allocated by the head and the memory allocated by each part of the linked list - } - - *to = *from; - to->est_count = from->est_count; - to->estabs = from->estabs; - to->relsize = from->relsize; - to->extragrowth = from->extragrowth; - to->allow_growth = from->allow_growth; - - if(deep) { - to->kills = Mem_Calloc(from->max_age, sizeof(IntUS), "_load_cell(Species[s]->kills)"); - to->seedprod = Mem_Calloc(from->viable_yrs, sizeof(RealF), "_load_cell(Species[s]->seedprod)"); - - memcpy(to->kills, from->kills, from->max_age * sizeof(IntUS)); - memcpy(to->seedprod, from->seedprod, from->viable_yrs * sizeof(RealF)); - to->IndvHead = _copy_head(from->IndvHead); //copy_head() deep copies the linked list structure (allocating memory when needed)... it will even allocate memory for the head of the list - } - } - */ /***********************************************************/ static void _init_grid_globals(void) { From 87d4f2e692a5f7a568f57308f3b07392678e0a0d Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Sat, 25 May 2019 18:39:38 -0400 Subject: [PATCH 053/167] (Issue #285) Overhaul _read_disturbances_in * Removed useless comments * Added disturbances field to CellType struct --- ST_grid.c | 58 ++++++++++++++++++++----------------------------------- 1 file changed, 21 insertions(+), 37 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 37c5678a..3313d234 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -173,6 +173,8 @@ struct grid_cell_st Bool duringSpinup; /* species spinup information */ Grid_Init_Species_St mySpeciesInit; + /* Disturbance information */ + Grid_Disturb_St myDisturb; /* ---------------- accumulators -------------------- */ StatType *_Dist, *_Ppt, *_Temp, @@ -2177,54 +2179,36 @@ static void _read_disturbances_in(void) // there should be no spaces in between, just commas separating the values // kill_yr will overwrite the kill year for each RGroup in the cell (0 means don't use, a # > 0 means kill everything at this year) - /* - //printf("inside _read_disturbances_in ()\n"); - - GrpIndex rg; - GroupType *g; - - ForEachGroup(rg) - { - g = RGroup[rg]; - // printf(" rgroup name= %s , killYear:%d, proportion_killed=%f,proportion_recovered=%f ,proportion_grazing=%f \n", - // g->name, g->killyr, g->proportion_killed, g->proportion_recovered, g->proportion_grazing); - } - */ - FILE *f; char buf[1024]; - int i, cell, num; + int i, j, cell, num; + Grid_Disturb_St *disturb; f = OpenFile(grid_files[GRID_FILE_DISTURBANCES], "r"); GetALine2(f, buf, 1024); // gets rid of the first line (since it just defines the columns) - for (i = 0; i < grid_Cells; i++) - { - if (!GetALine2(f, buf, 1024)) - break; - num = sscanf(buf, "%d,%d,%d,%d,%d,%d,%d,%d,%f,%d,%d,%d", &cell, - &grid_Disturb[i].choices[0], &grid_Disturb[i].choices[1], - &grid_Disturb[i].choices[2], &grid_Disturb[i].kill_yr, - &grid_Disturb[i].killfrq, &grid_Disturb[i].extirp, - &grid_Disturb[i].killfreq_startyr,&grid_Disturb[i].xgrow,&grid_Disturb[i].veg_prod_type, - &grid_Disturb[i].grazing_frq,&grid_Disturb[i].grazingfreq_startyr); + for (i = 0; i < grid_Rows; i++) { + for (j = 0; j < grid_Cols; j++) { + disturb = &gridCells[i][j].myDisturb; -// printf("values : cell=%d ,choices[0]=%d ,choices[1]=%d ,choices[2]=%d ,kill_yr=%d ,killfrq=%d ,extirp=%d ,killfreq_startyr=%d ,xgrow=%f ,veg_prod_type=%d ,grazing_frq=%d ,grazingfrd_start_year=%d \n", cell, -// grid_Disturb[i].choices[0], grid_Disturb[i].choices[1], -// grid_Disturb[i].choices[2], grid_Disturb[i].kill_yr, -// grid_Disturb[i].killfrq, grid_Disturb[i].extirp, -// grid_Disturb[i].killfreq_startyr,grid_Disturb[i].xgrow,grid_Disturb[i].veg_prod_type, -// grid_Disturb[i].grazing_frq,grid_Disturb[i].grazingfreq_startyr); + if (!GetALine2(f, buf, 1024)) + LogError(logfp, LOGFATAL, "Invalid %s file wrong number of cells", + grid_files[GRID_FILE_DISTURBANCES]); + // cell is a useless field, although we still read it in for now. + num = sscanf(buf, "%d,%d,%d,%d,%d,%d,%d,%d,%f,%d,%d,%d", &cell, + &disturb->choices[0], &disturb->choices[1], + &disturb->choices[2], &disturb->kill_yr, + &disturb->killfrq, &disturb->extirp, + &disturb->killfreq_startyr, &disturb->xgrow, &disturb->veg_prod_type, + &disturb->grazing_frq, &disturb->grazingfreq_startyr); - if (num != 12) - LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", - grid_files[GRID_FILE_DISTURBANCES], i + 2); + if (num != 12) + LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", + grid_files[GRID_FILE_DISTURBANCES], i + 2); + } } - if (i != grid_Cells) - LogError(logfp, LOGFATAL, "Invalid %s file wrong number of cells", - grid_files[GRID_FILE_DISTURBANCES]); CloseFile(&f); } From 6009138cc381e8984b5f62a06de5faae03e36f92 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Sat, 25 May 2019 18:39:38 -0400 Subject: [PATCH 054/167] Revert "(Issue #285) Overhaul _read_disturbances_in" This reverts commit 87d4f2e692a5f7a568f57308f3b07392678e0a0d. --- ST_grid.c | 58 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 3313d234..37c5678a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -173,8 +173,6 @@ struct grid_cell_st Bool duringSpinup; /* species spinup information */ Grid_Init_Species_St mySpeciesInit; - /* Disturbance information */ - Grid_Disturb_St myDisturb; /* ---------------- accumulators -------------------- */ StatType *_Dist, *_Ppt, *_Temp, @@ -2179,36 +2177,54 @@ static void _read_disturbances_in(void) // there should be no spaces in between, just commas separating the values // kill_yr will overwrite the kill year for each RGroup in the cell (0 means don't use, a # > 0 means kill everything at this year) + /* + //printf("inside _read_disturbances_in ()\n"); + + GrpIndex rg; + GroupType *g; + + ForEachGroup(rg) + { + g = RGroup[rg]; + // printf(" rgroup name= %s , killYear:%d, proportion_killed=%f,proportion_recovered=%f ,proportion_grazing=%f \n", + // g->name, g->killyr, g->proportion_killed, g->proportion_recovered, g->proportion_grazing); + } + */ + FILE *f; char buf[1024]; - int i, j, cell, num; - Grid_Disturb_St *disturb; + int i, cell, num; f = OpenFile(grid_files[GRID_FILE_DISTURBANCES], "r"); GetALine2(f, buf, 1024); // gets rid of the first line (since it just defines the columns) + for (i = 0; i < grid_Cells; i++) + { + if (!GetALine2(f, buf, 1024)) + break; - for (i = 0; i < grid_Rows; i++) { - for (j = 0; j < grid_Cols; j++) { - disturb = &gridCells[i][j].myDisturb; + num = sscanf(buf, "%d,%d,%d,%d,%d,%d,%d,%d,%f,%d,%d,%d", &cell, + &grid_Disturb[i].choices[0], &grid_Disturb[i].choices[1], + &grid_Disturb[i].choices[2], &grid_Disturb[i].kill_yr, + &grid_Disturb[i].killfrq, &grid_Disturb[i].extirp, + &grid_Disturb[i].killfreq_startyr,&grid_Disturb[i].xgrow,&grid_Disturb[i].veg_prod_type, + &grid_Disturb[i].grazing_frq,&grid_Disturb[i].grazingfreq_startyr); - if (!GetALine2(f, buf, 1024)) - LogError(logfp, LOGFATAL, "Invalid %s file wrong number of cells", - grid_files[GRID_FILE_DISTURBANCES]); +// printf("values : cell=%d ,choices[0]=%d ,choices[1]=%d ,choices[2]=%d ,kill_yr=%d ,killfrq=%d ,extirp=%d ,killfreq_startyr=%d ,xgrow=%f ,veg_prod_type=%d ,grazing_frq=%d ,grazingfrd_start_year=%d \n", cell, +// grid_Disturb[i].choices[0], grid_Disturb[i].choices[1], +// grid_Disturb[i].choices[2], grid_Disturb[i].kill_yr, +// grid_Disturb[i].killfrq, grid_Disturb[i].extirp, +// grid_Disturb[i].killfreq_startyr,grid_Disturb[i].xgrow,grid_Disturb[i].veg_prod_type, +// grid_Disturb[i].grazing_frq,grid_Disturb[i].grazingfreq_startyr); - // cell is a useless field, although we still read it in for now. - num = sscanf(buf, "%d,%d,%d,%d,%d,%d,%d,%d,%f,%d,%d,%d", &cell, - &disturb->choices[0], &disturb->choices[1], - &disturb->choices[2], &disturb->kill_yr, - &disturb->killfrq, &disturb->extirp, - &disturb->killfreq_startyr, &disturb->xgrow, &disturb->veg_prod_type, - &disturb->grazing_frq, &disturb->grazingfreq_startyr); - if (num != 12) - LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", - grid_files[GRID_FILE_DISTURBANCES], i + 2); - } + if (num != 12) + LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", + grid_files[GRID_FILE_DISTURBANCES], i + 2); } + if (i != grid_Cells) + LogError(logfp, LOGFATAL, "Invalid %s file wrong number of cells", + grid_files[GRID_FILE_DISTURBANCES]); CloseFile(&f); } From fa1b862abaa2f6ec6a37c9fb664d9f2347337142 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Tue, 28 May 2019 01:31:36 -0400 Subject: [PATCH 055/167] (Issue #284) Make RGroup and Species work correctly in gridded mode --- ST_grid.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 37c5678a..9597d1df 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -944,9 +944,13 @@ static void _init_stepwat_inputs(void) /* Loop through all gridCells. */ for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ - load_cell(i, j); // Load this cell into the global variables - parm_Initialize(); // Initialize the STEPWAT variables - _init_SXW_inputs(TRUE, NULL); // Initialize the SXW and SOILWAT variables + load_cell(i, j); // Load this cell into the global variables + parm_Initialize(); // Initialize the STEPWAT variables + gridCells[i][j].myGroup = RGroup; // This is necessary because load_cell only points RGroup to our cell-specific + // resource group array, not to the variable that points to that array. + gridCells[i][j].mySpecies = Species; // This is necessary because load_cell only points Species to our cell-specific + // species array, not to the variable that points to that array. + _init_SXW_inputs(TRUE, NULL); // Initialize the SXW and SOILWAT variables } /* End for each column */ } /* End for each row */ unload_cell(); // Reset the global variables From 8f6a344dd069a2439e2d904d3ec0495be0696f38 Mon Sep 17 00:00:00 2001 From: Chandler Haukap <31867049+chaukap@users.noreply.github.com> Date: Tue, 28 May 2019 14:19:05 -0600 Subject: [PATCH 056/167] Addressed typo in commit 873a2f5 --- ST_grid.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 9597d1df..67fdb6e9 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1765,7 +1765,7 @@ static void load_cell(int row, int col){ gridCells[row][col]._Indv, gridCells[row][col]._Smort, gridCells[row][col]._Sestab, gridCells[row][col]._Sreceived, gridCells[row][col]._Gwf, gridCells[row][col].stats_init); - /* Copy this cell's SXW variables into the loacl variables in sxw.c */ + /* Copy this cell's SXW variables into the local variables in sxw.c */ copy_sxw_variables(&gridCells[row][col].mySXW, &gridCells[row][col].mySXWResources, &gridCells[row][col].myTranspWindow); } @@ -3267,4 +3267,4 @@ static void _read_init_species(void) grid_files[GRID_FILE_INIT_SPECIES]); CloseFile(&f); -} \ No newline at end of file +} From 2556c1fbdecdae05a0da19148d3cb14aa0cced26 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Tue, 28 May 2019 22:57:16 -0400 Subject: [PATCH 057/167] (Issues #285 #286) Break up _init_grid_inputs --- ST_grid.c | 121 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 71 insertions(+), 50 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 67fdb6e9..d7c5a464 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -358,6 +358,7 @@ void _deallocate_memory(void); void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); void maxrgroupspecies_init(void); +void files_init(void); /*********** Locally Used Function Declarations ************/ /***********************************************************/ @@ -406,6 +407,10 @@ static void _free_head(IndivType *head); static IndivType* _copy_individuals(IndivType *head); static IndivType* _copy_head(IndivType *head); +static void _read_maxrgroupspecies(void); +static void _read_grid_setup(void); +static void _read_files(void); + /******************** Begin Model Code *********************/ /***********************************************************/ @@ -503,8 +508,11 @@ void runGrid(void) clock_t prog_Time; _init_grid_files(); // reads in files.in file + _read_maxrgroupspecies(); // reads in maxrgroupspecies.in file + _read_grid_setup(); // reads in grid_setup.in file + _read_files(); // reads in Stepwat_Inputs/files.in file + _init_stepwat_inputs(); // reads the stepwat inputs in _init_grid_inputs(); // reads the grid inputs in & initializes the global grid variables - _init_stepwat_inputs(); // reads the stepwat inputs in //SWC hist file prefix needs to be cleared Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; @@ -857,55 +865,6 @@ static void _init_grid_files(void) /***********************************************************/ static void _init_grid_inputs(void) { - // reads in the grid input file - - FILE *f; - char buf[1024]; - int i, j; - - /* Read maxrgroupspecies.in */ - ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); - parm_SetName(grid_files[GRID_FILE_MAXRGROUPSPECIES], F_MaxRGroupSpecies); - maxrgroupspecies_init(); - ChDir(".."); - - f = OpenFile(grid_files[GRID_FILE_SETUP], "r"); - - GetALine(f, buf); - i = sscanf(buf, "%d %d", &grid_Rows, &grid_Cols); - if (i != 2) - LogError(logfp, LOGFATAL, - "Invalid grid setup file (rows/cols line wrong)"); - - grid_Cells = grid_Cols * grid_Rows; - - if (grid_Cells > MAX_CELLS) - LogError(logfp, LOGFATAL, - "Number of cells in grid exceeds MAX_CELLS defined in ST_defines.h"); - - /* Allocate the 2d array of cells now that we know how many we need */ - allocate_gridCells(grid_Rows, grid_Cols); - - GetALine(f, buf); - i = sscanf(buf, "%d", &UseDisturbances); - if (i != 1) - LogError(logfp, LOGFATAL, - "Invalid grid setup file (disturbances line wrong)"); - - GetALine(f, buf); - i = sscanf(buf, "%d", &UseSoils); - if (i != 1) - LogError(logfp, LOGFATAL, "Invalid grid setup file (soils line wrong)"); - - GetALine(f, buf); - i = sscanf(buf, "%d", &j); - if (i != 1) - LogError(logfp, LOGFATAL, - "Invalid grid setup file (seed dispersal line wrong)"); - UseSeedDispersal = itob(j); - - CloseFile(&f); - _init_grid_globals(); // initializes the global grid variables if (UseDisturbances) _read_disturbances_in(); @@ -3268,3 +3227,65 @@ static void _read_init_species(void) CloseFile(&f); } + +/***********************************************************/ +static void _read_maxrgroupspecies(void) +{ + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); + parm_SetName(grid_files[GRID_FILE_MAXRGROUPSPECIES], F_MaxRGroupSpecies); + maxrgroupspecies_init(); + ChDir(".."); +} + +/***********************************************************/ +static void _read_files(void) +{ + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); + files_init(); + ChDir(".."); +} + +/***********************************************************/ +static void _read_grid_setup(void) +{ + FILE *f; + char buf[1024]; + int i, j; + + f = OpenFile(grid_files[GRID_FILE_SETUP], "r"); + + GetALine(f, buf); + i = sscanf(buf, "%d %d", &grid_Rows, &grid_Cols); + if (i != 2) + LogError(logfp, LOGFATAL, + "Invalid grid setup file (rows/cols line wrong)"); + + grid_Cells = grid_Cols * grid_Rows; + + if (grid_Cells > MAX_CELLS) + LogError(logfp, LOGFATAL, + "Number of cells in grid exceeds MAX_CELLS defined in ST_defines.h"); + + /* Allocate the 2d array of cells now that we know how many we need */ + allocate_gridCells(grid_Rows, grid_Cols); + + GetALine(f, buf); + i = sscanf(buf, "%d", &UseDisturbances); + if (i != 1) + LogError(logfp, LOGFATAL, + "Invalid grid setup file (disturbances line wrong)"); + + GetALine(f, buf); + i = sscanf(buf, "%d", &UseSoils); + if (i != 1) + LogError(logfp, LOGFATAL, "Invalid grid setup file (soils line wrong)"); + + GetALine(f, buf); + i = sscanf(buf, "%d", &j); + if (i != 1) + LogError(logfp, LOGFATAL, + "Invalid grid setup file (seed dispersal line wrong)"); + UseSeedDispersal = itob(j); + + CloseFile(&f); +} \ No newline at end of file From e5abfcb4df004fd3d3801d6a1eee4da6b28cf0c6 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Thu, 30 May 2019 16:17:50 -0400 Subject: [PATCH 058/167] (Issue #285) Overhaul _init_grid_inputs --- ST_grid.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index d7c5a464..cb91b294 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -865,7 +865,8 @@ static void _init_grid_files(void) /***********************************************************/ static void _init_grid_inputs(void) { - _init_grid_globals(); // initializes the global grid variables + int i, j; + if (UseDisturbances) _read_disturbances_in(); if (UseSeedDispersal) @@ -876,9 +877,15 @@ static void _init_grid_inputs(void) if (UseSoils) _read_soils_in(); - DuringSpinup = FALSE; -} + for(i = 0; i < grid_Rows; ++i) { + for(j = 0; j < grid_Cols; ++j) { + load_cell(i, j); + gridCells[i][j].duringSpinup = FALSE; + } + } + unload_cell(); +} /***********************************************************/ static void _init_SXW_inputs(Bool init_SW, char *f_roots) { From 60d78aeae51346771255d3646715ed2f6c43b403 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Thu, 30 May 2019 16:33:19 -0400 Subject: [PATCH 059/167] (Issue #285) Overhaul _read_disturbances_in --- ST_grid.c | 55 +++++++++++++++++++++++++------------------------------ 1 file changed, 25 insertions(+), 30 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index cb91b294..9b2c6113 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2147,48 +2147,42 @@ static void _read_disturbances_in(void) // there should be no spaces in between, just commas separating the values // kill_yr will overwrite the kill year for each RGroup in the cell (0 means don't use, a # > 0 means kill everything at this year) - /* - //printf("inside _read_disturbances_in ()\n"); - - GrpIndex rg; - GroupType *g; - - ForEachGroup(rg) - { - g = RGroup[rg]; - // printf(" rgroup name= %s , killYear:%d, proportion_killed=%f,proportion_recovered=%f ,proportion_grazing=%f \n", - // g->name, g->killyr, g->proportion_killed, g->proportion_recovered, g->proportion_grazing); - } - */ - FILE *f; char buf[1024]; - int i, cell, num; + int i, row, col, cell, num = 0, choices[3]; + GrpIndex rg; f = OpenFile(grid_files[GRID_FILE_DISTURBANCES], "r"); GetALine2(f, buf, 1024); // gets rid of the first line (since it just defines the columns) for (i = 0; i < grid_Cells; i++) { - if (!GetALine2(f, buf, 1024)) - break; + row = i / grid_Cols; + col = i % grid_Cols; - num = sscanf(buf, "%d,%d,%d,%d,%d,%d,%d,%d,%f,%d,%d,%d", &cell, - &grid_Disturb[i].choices[0], &grid_Disturb[i].choices[1], - &grid_Disturb[i].choices[2], &grid_Disturb[i].kill_yr, - &grid_Disturb[i].killfrq, &grid_Disturb[i].extirp, - &grid_Disturb[i].killfreq_startyr,&grid_Disturb[i].xgrow,&grid_Disturb[i].veg_prod_type, - &grid_Disturb[i].grazing_frq,&grid_Disturb[i].grazingfreq_startyr); + load_cell(row, col); -// printf("values : cell=%d ,choices[0]=%d ,choices[1]=%d ,choices[2]=%d ,kill_yr=%d ,killfrq=%d ,extirp=%d ,killfreq_startyr=%d ,xgrow=%f ,veg_prod_type=%d ,grazing_frq=%d ,grazingfrd_start_year=%d \n", cell, -// grid_Disturb[i].choices[0], grid_Disturb[i].choices[1], -// grid_Disturb[i].choices[2], grid_Disturb[i].kill_yr, -// grid_Disturb[i].killfrq, grid_Disturb[i].extirp, -// grid_Disturb[i].killfreq_startyr,grid_Disturb[i].xgrow,grid_Disturb[i].veg_prod_type, -// grid_Disturb[i].grazing_frq,grid_Disturb[i].grazingfreq_startyr); + if (!GetALine2(f, buf, 1024)) + break; + // xgrow and veg_prod_type not found in grid_disturbances.csv + ForEachGroup(rg) + num = sscanf(buf, "%d,%d,%d,%d,%hd,%f,%hd,%hd,%hu,%hd", &cell, + &choices[0], &choices[1], + &choices[2], &RGroup[rg]->killyr, + &RGroup[rg]->killfreq, &RGroup[rg]->extirp, + &RGroup[rg]->killfreq_startyr, + &RGroup[rg]->grazingfrq, &RGroup[rg]->grazingfreq_startyr); + + // Comes from _load_grid_globals + if (UseDisturbances) { + Globals->pat.use = choices[0]; + Globals->mound.use = choices[1]; + Globals->burrow.use = choices[2]; + } - if (num != 12) + // xgrow and veg_prod_type not found in grid_disturbances.csv + if (num != 10) LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", grid_files[GRID_FILE_DISTURBANCES], i + 2); } @@ -2196,6 +2190,7 @@ static void _read_disturbances_in(void) LogError(logfp, LOGFATAL, "Invalid %s file wrong number of cells", grid_files[GRID_FILE_DISTURBANCES]); + unload_cell(); CloseFile(&f); } From e27b2bd319dcea31f448a3705f5c86700b1ab2a7 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Thu, 30 May 2019 19:25:12 -0400 Subject: [PATCH 060/167] (Issue #285) Overhaul _read_init_species --- ST_grid.c | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 9b2c6113..80c210c9 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -3172,7 +3172,8 @@ static void _read_init_species(void) // there should be no spaces in between, just commas separating the values (ie it should be a .csv file, but does not account for all of the possibilities that a .csv file could be) FILE *f; - int i, j, num, cell, do_copy, copy_cell, use_SpinUp, seeds_Avail; + int i, j, num, cell, do_copy, copy_cell, use_SpinUp, seeds_Avail, + row, col, copy_cell_row, copy_cell_col; char buf[4096]; //open the file/do the reading @@ -3181,15 +3182,24 @@ static void _read_init_species(void) GetALine2(f, buf, 4096); // gets rid of the first line (since it just defines the columns)... it's only there for user readability for (i = 0; i < grid_Cells; i++) { + row = i / grid_Cols; + col = i % grid_Cols; + + load_cell(row, col); + if (!GetALine2(f, buf, 4096)) break; num = sscanf(buf, "%d,%d,%d,%d", &cell, &do_copy, ©_cell, &use_SpinUp); + + copy_cell_row = copy_cell / grid_Cols; + copy_cell_col = copy_cell % grid_Cols; + if (num != 4) LogError(logfp, LOGFATAL, "Invalid %s file", grid_files[GRID_FILE_INIT_SPECIES]); - grid_initSpecies[i].use_SpinUp = use_SpinUp; + gridCells[row][col].mySpeciesInit.use_SpinUp = use_SpinUp; int stringIndex = _get_value_index(buf, ',', 4); //gets us the index of the string that is right after what we just parsed in @@ -3197,10 +3207,10 @@ static void _read_init_species(void) && cell != 0 && copy_cell < cell) { //copy this cells values from a previous cell's for (j = 0; j < Globals->sppCount; j++) - grid_initSpecies[i].species_seed_avail[j] = - grid_initSpecies[copy_cell].species_seed_avail[j]; - grid_initSpecies[i].use_SpinUp = - grid_initSpecies[copy_cell].use_SpinUp; + gridCells[row][col].mySpeciesInit.species_seed_avail[j] = + gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.species_seed_avail[j]; + gridCells[row][col].mySpeciesInit.use_SpinUp = + gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.use_SpinUp; continue; } else if (do_copy == 1) @@ -3218,7 +3228,7 @@ static void _read_init_species(void) "Invalid %s file line %d invalid species input", grid_files[GRID_FILE_INIT_SPECIES], i + 2); - grid_initSpecies[i].species_seed_avail[s] = seeds_Avail; + gridCells[row][col].mySpeciesInit.species_seed_avail[s] = seeds_Avail; stringIndex += _get_value_index(&buf[stringIndex], ',', 1); } } @@ -3227,6 +3237,7 @@ static void _read_init_species(void) LogError(logfp, LOGFATAL, "Invalid %s file, not enough cells", grid_files[GRID_FILE_INIT_SPECIES]); + unload_cell(); CloseFile(&f); } From 0e90845d18de83c97294dbc0ef9d0ebc690e6d44 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Thu, 30 May 2019 19:50:47 -0400 Subject: [PATCH 061/167] (Issue #285) Overhaul _read_soils_in --- ST_grid.c | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 80c210c9..9cd97a11 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2239,7 +2239,7 @@ static void _read_soils_in(void) char seps[] = ","; char *token; int i, j, k, cell, num, do_copy, copy_cell, num_layers, depth, depthMin, - stringIndex; + stringIndex, row, col, copy_cell_row, copy_cell_col; float d[11]; if (sd_Option2a || sd_Option2b) @@ -2250,10 +2250,14 @@ static void _read_soils_in(void) GetALine2(f, buf, 4096); // gets rid of the first line (since it just defines the columns)... it's only there for user readability for (i = 0; i < grid_Cells; i++) { + row = i / grid_Cols; + col = i % grid_Cols; + + load_cell(row, col); + if (!GetALine2(f, buf, 4096)) break; - - grid_Soils[i].rootsFile[0] = '\0'; + gridCells[row][col].mySoils.rootsFile[0] = '\0'; rootsin[0] = '\0'; num = 0; @@ -2270,6 +2274,8 @@ static void _read_soils_in(void) break; case 2: copy_cell = atoi(token); + copy_cell_row = copy_cell / grid_Cols; + copy_cell_col = copy_cell % grid_Cols; break; case 3: num_layers = atoi(token); @@ -2297,16 +2303,17 @@ static void _read_soils_in(void) if (do_copy == 1 && copy_cell > -1 && copy_cell < grid_Cells && cell != 0 && copy_cell < cell) { //copy this cells values from a previous cell's - grid_Soils[i].lyr = Mem_Calloc(grid_Soils[copy_cell].num_layers, + gridCells[row][col].mySoils.lyr = Mem_Calloc(gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers, sizeof(Grid_Soil_Lyr), "_read_soils_in()"); - for (j = 0; j < grid_Soils[copy_cell].num_layers; j++) - grid_Soils[i].lyr[j] = grid_Soils[copy_cell].lyr[j]; - grid_Soils[i].num_layers = grid_Soils[copy_cell].num_layers; + for (j = 0; j < gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers; j++) + gridCells[row][col].mySoils.lyr[j] = gridCells[copy_cell_row][copy_cell_col].mySoils.lyr[j]; + gridCells[row][col].mySoils.num_layers = gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers; + // TODO: figure out how to change this code for our new struct if (sd_Option2a || sd_Option2b) - grid_SoilTypes[cell] = grid_SoilTypes[copy_cell]; + grid_SoilTypes[cell] = grid_SoilTypes[copy_cell]; - strcpy(grid_Soils[i].rootsFile, grid_Soils[copy_cell].rootsFile); + strcpy(gridCells[row][col].mySoils.rootsFile, gridCells[copy_cell_row][copy_cell_col].mySoils.rootsFile); continue; } @@ -2315,6 +2322,7 @@ static void _read_soils_in(void) "Invalid %s file line %d invalid copy_cell attempt", grid_files[GRID_FILE_SOILS], i + 2); + // TODO: figure out how to change this code for our new struct if (sd_Option2a || sd_Option2b) { grid_SoilTypes[cell] = nSoilTypes; @@ -2323,9 +2331,9 @@ static void _read_soils_in(void) } depthMin = 0; - grid_Soils[i].num_layers = num_layers; - strcpy(grid_Soils[i].rootsFile, rootsin); - grid_Soils[i].lyr = Mem_Calloc(num_layers, sizeof(Grid_Soil_Lyr), + gridCells[row][col].mySoils.num_layers = num_layers; + strcpy(gridCells[row][col].mySoils.rootsFile, rootsin); + gridCells[row][col].mySoils.lyr = Mem_Calloc(num_layers, sizeof(Grid_Soil_Lyr), "_read_soils_in()"); for (j = 0; j < num_layers; j++) { @@ -2347,8 +2355,8 @@ static void _read_soils_in(void) grid_files[GRID_FILE_SOILS], i + 2); for (k = 0; k < 11; k++) - grid_Soils[i].lyr[j].data[k] = d[k]; - grid_Soils[i].lyr[j].width = depth - depthMin; + gridCells[row][col].mySoils.lyr[j].data[k] = d[k]; + gridCells[row][col].mySoils.lyr[j].width = depth - depthMin; depthMin = depth; } } @@ -2357,15 +2365,7 @@ static void _read_soils_in(void) LogError(logfp, LOGFATAL, "Invalid %s file, not enough cells", grid_files[GRID_FILE_SOILS]); - /*for(i = 0; i < grid_Cells; i++) { - printf("cell %d:\n", i); - for(j = 0; j < grid_Soils[i].num_layers; j++) { - printf("layer %d : %d", j, grid_Soils[i].lyr[j].width); - for(k = 0; k < 11; k++) printf(" %f", grid_Soils[i].lyr[j].data[k]); - printf("\n"); - } - }*/ - + unload_cell(); CloseFile(&f); } From e7271e41435b254e3140e3d77833e9408ae8393a Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Fri, 31 May 2019 02:22:48 -0400 Subject: [PATCH 062/167] (Issue #285) Overhaul _read_seed_dispersal_in Also add seed dispersal to cell struct --- ST_grid.c | 52 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 9cd97a11..e41ae7d8 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -173,6 +173,8 @@ struct grid_cell_st Bool duringSpinup; /* species spinup information */ Grid_Init_Species_St mySpeciesInit; + /* seed dispersal information corresponding to this cell */ + Grid_SD_St *mySeedDispersal; /* ---------------- accumulators -------------------- */ StatType *_Dist, *_Ppt, *_Temp, @@ -2691,6 +2693,21 @@ static void _read_seed_dispersal_in(void) CloseFile(&f); + /* + * The following variables should be global (not cell-specific): + * Globals->sppCount + * Species[s]->sd_H + * Species[s]->sd_VT + * Globals->plotsize + * Species[s]->use_me + * Species[s]->use_dispersal + * + * Since the values of these variables do not change between cells, we can call load_cell(0, 0) + * to load their values so that ForEachSpecies and other lines of code do not segfault. + */ + load_cell(0, 0); + + // Begin reading cell-specific fields ForEachSpecies(s) { // set up grid_SD with the seed dispersal probabilities needed later on... @@ -2709,11 +2726,14 @@ static void _read_seed_dispersal_in(void) for (i = 0; i < grid_Cells; i++) { - grid_SD[s][i].cells = Mem_Calloc(maxCells, sizeof(int), + row = i / grid_Cols; + col = i % grid_Cols; + + gridCells[row][col].mySeedDispersal[s].cells = Mem_Calloc(maxCells, sizeof(int), "_read_seed_dispersal_in()"); //the cell number - grid_SD[s][i].prob = Mem_Calloc(maxCells, sizeof(float), + gridCells[row][col].mySeedDispersal[s].prob = Mem_Calloc(maxCells, sizeof(float), "_read_seed_dispersal_in()"); //the probability that the cell will disperse seeds to this distance - grid_SD[s][i].size = 0; //refers to the number of cells reachable... + gridCells[row][col].mySeedDispersal[s].size = 0; //refers to the number of cells reachable... } for (row = 1; row <= grid_Rows; row++) @@ -2734,26 +2754,30 @@ static void _read_seed_dispersal_in(void) if (!ZRO(pd)) { - grid_SD[s][cell].cells[k] = i + gridCells[row][col].mySeedDispersal[s].cells[k] = i + ((j - 1) * grid_Cols) - 1; - grid_SD[s][cell].prob[k] = pd; - grid_SD[s][cell].size++; + gridCells[row][col].mySeedDispersal[s].prob[k] = pd; + gridCells[row][col].mySeedDispersal[s].size++; k++; - //fprintf(stderr, "cell: %d; i: %d; j: %d; dist: %f; pd: %f %d %d\n", i + ( (j-1) * grid_Cols) - 1, i, j, d, pd, row, col); } } - //fprintf(stderr, "size %d index %d maxsize %d\n", grid_SD[cell].size, cell, maxCells); } - for (i = 0; i < grid_Cells; i++) - if (grid_SD[s][i].size > 0) + for (i = 0; i < grid_Cells; i++) { + row = i / grid_Cols; + col = i % grid_Cols; + + if (gridCells[row][col].mySeedDispersal[s].size > 0) { - grid_SD[s][i].cells = Mem_ReAlloc(grid_SD[s][i].cells, - grid_SD[s][i].size * sizeof(int)); - grid_SD[s][i].prob = Mem_ReAlloc(grid_SD[s][i].prob, - grid_SD[s][i].size * sizeof(float)); + gridCells[row][col].mySeedDispersal[s].cells = Mem_ReAlloc(gridCells[row][col].mySeedDispersal[s].cells, + gridCells[row][col].mySeedDispersal[s].size * sizeof(int)); + gridCells[row][col].mySeedDispersal[s].prob = Mem_ReAlloc(gridCells[row][col].mySeedDispersal[s].prob, + gridCells[row][col].mySeedDispersal[s].size * sizeof(float)); } + } } + + unload_cell(); } /***********************************************************/ From 29489fa3ade671e069c4d385e18df91946ad640a Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Fri, 31 May 2019 12:46:18 -0400 Subject: [PATCH 063/167] (Issue #285) Overhaul _init_grid_globals --- ST_grid.c | 63 +++---------------------------------------------------- 1 file changed, 3 insertions(+), 60 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index e41ae7d8..49113edf 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -869,6 +869,8 @@ static void _init_grid_inputs(void) { int i, j; + _init_grid_globals(); + if (UseDisturbances) _read_disturbances_in(); if (UseSeedDispersal) @@ -1007,70 +1009,11 @@ static void _init_grid_globals(void) { //initializes grid variables, allocating the memory necessary for them (this step is only needed to be done once) - GrpIndex c; - SppIndex s; - int i; - - grid_Succulent = Mem_Calloc(grid_Cells, sizeof(SucculentType), - "_init_grid_globals()"); - grid_Env = Mem_Calloc(grid_Cells, sizeof(EnvType), "_init_grid_globals()"); - grid_Plot = Mem_Calloc(grid_Cells, sizeof(PlotType), - "_init_grid_globals()"); - grid_Globals = Mem_Calloc(grid_Cells, sizeof(ModelType), - "_init_grid_globals()"); - - ForEachSpecies(s) - if (Species[s]->use_me) - grid_Species[s] = Mem_Calloc(grid_Cells, sizeof(SpeciesType), - "_init_grid_globals()"); - ForEachGroup(c) - if (RGroup[c]->use_me) - grid_RGroup[c] = Mem_Calloc(grid_Cells, sizeof(GroupType), - "_init_grid_globals()"); - - grid_SXW = Mem_Calloc(grid_Cells, sizeof(SXW_t), - "_init_grid_globals()"); - grid_SW_Soilwat = Mem_Calloc(grid_Cells, sizeof(SW_SOILWAT), - "_init_grid_globals()"); - grid_SW_Site = Mem_Calloc(grid_Cells, sizeof(SW_SITE), - "_init_grid_globals()"); - grid_SW_VegProd = Mem_Calloc(grid_Cells, sizeof(SW_VEGPROD), - "_init_grid_globals()"); - if (UseSoils) - { - grid_Soils = Mem_Calloc(grid_Cells, sizeof(SoilType), - "_init_grid_globals()"); - for (i = 0; i < grid_Cells; i++) - grid_Soils[i].num_layers = 0; - grid_SXW_ptrs = Mem_Calloc(grid_Cells, sizeof(Grid_SXW_St), - "_init_grid_globals()"); - } - - if (UseDisturbances) - grid_Disturb = Mem_Calloc(grid_Cells, sizeof(Grid_Disturb_St), - "_init_grid_globals()"); - if (UseSeedDispersal) - { - ForEachSpecies(s) - if (Species[s]->use_me && Species[s]->use_dispersal) - grid_SD[s] = Mem_Calloc(grid_Cells, sizeof(Grid_SD_St), - "_init_grid_globals()"); - - grid_initSpecies = Mem_Calloc(grid_Cells, sizeof(Grid_Init_Species_St), - "_init_grid_globals()"); - for (i = 0; i < grid_Cells; i++) - grid_initSpecies[i].species_seed_avail = Mem_Calloc( - Globals->sppCount, sizeof(int), "_init_grid_globals()"); - } - - //if(sd_Option2a || sd_Option2b) { + // Keep these until I know if the CellType struct accounts for these variables. soilTypes_Array = Mem_Calloc(grid_Cells, sizeof(int*), "_init_grid_globals()"); grid_SoilTypes = Mem_Calloc(grid_Cells, sizeof(int*), "_init_grid_globals()"); - //} - - stat_Init_Accumulators(); } /***********************************************************/ From 0c4c17531e2839bde8657fdf8d12143b6409c16f Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Fri, 31 May 2019 12:58:01 -0400 Subject: [PATCH 064/167] (Issue #285) Fixed bugs in _read_seed_dispersal_in * Allocated mySeedDispersal * Used correct indices for for-loop where row and col start at 1 --- ST_grid.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 49113edf..4c57bdab 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2636,6 +2636,13 @@ static void _read_seed_dispersal_in(void) CloseFile(&f); + for (i = 0; i < grid_Cells; i++) { + row = i / grid_Cols; + col = i % grid_Cols; + + gridCells[row][col].mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_read_seed_dispersal_in"); + } + /* * The following variables should be global (not cell-specific): * Globals->sppCount @@ -2697,10 +2704,10 @@ static void _read_seed_dispersal_in(void) if (!ZRO(pd)) { - gridCells[row][col].mySeedDispersal[s].cells[k] = i + gridCells[row - 1][col - 1].mySeedDispersal[s].cells[k] = i + ((j - 1) * grid_Cols) - 1; - gridCells[row][col].mySeedDispersal[s].prob[k] = pd; - gridCells[row][col].mySeedDispersal[s].size++; + gridCells[row - 1][col - 1].mySeedDispersal[s].prob[k] = pd; + gridCells[row - 1][col - 1].mySeedDispersal[s].size++; k++; } } From 1c723c2dc61fa76b0cd3809712e585945a0d08e2 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 3 Jun 2019 09:42:55 -0600 Subject: [PATCH 065/167] Fixed some issues with SXW initialization SXW was not being initialized properly. The issue stems from the fact that SXW, SXWResources and transp_window are local variables. To get around this I added three new functions: * getSXW returns a pointer to the local SXW variable * getSXWResources returns a pointer to the local SXWResources variable * getTranspWindow returns a pointer to the local transp_window variable We can use these functions to assign the corresponding variables in ST_grid.c to the newly allocated version in sxw.c. I also moved the initialization of SXW->_resource_cur inside of the _allocate_memory function. I removed the if(!UseGrid) block arround _allocate_memory, since we do in fact want to allocate memory even in gridded mode. In ST_grid.c I changed the SXW variables in CellType to pointers to make memory manipulation easier. --- ST_grid.c | 19 +++++++++++++++---- sxw.c | 28 +++++++++++++++++++++------- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 4c57bdab..5fb250d2 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -185,9 +185,9 @@ struct grid_cell_st /* -------------- end accumulators ------------------ */ /* -------------------- SXW ------------------------- */ - transp_t myTranspWindow; - SXW_t mySXW; - SXW_resourceType mySXWResources; + transp_t* myTranspWindow; + SXW_t* mySXW; + SXW_resourceType* mySXWResources; /* ------------------ End SXW ----------------------- */ /* ------------------- Soils ------------------------ */ @@ -362,6 +362,10 @@ void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp void maxrgroupspecies_init(void); void files_init(void); +SXW_t* getSXW(void); +SXW_resourceType* getSXWResources(void); +transp_t* getTranspWindow(void); + /*********** Locally Used Function Declarations ************/ /***********************************************************/ @@ -921,6 +925,13 @@ static void _init_stepwat_inputs(void) gridCells[i][j].mySpecies = Species; // This is necessary because load_cell only points Species to our cell-specific // species array, not to the variable that points to that array. _init_SXW_inputs(TRUE, NULL); // Initialize the SXW and SOILWAT variables + + // Set mySXW to the location of the newly allocated SXW + gridCells[i][j].mySXW = getSXW(); + // Set myTanspWindow to the location of the newly allocated transp window + gridCells[i][j].myTranspWindow = getTranspWindow(); + // Set mySXWResources to the location of the newly allocated SXW resources + gridCells[i][j].mySXWResources = getSXWResources(); } /* End for each column */ } /* End for each row */ unload_cell(); // Reset the global variables @@ -1677,7 +1688,7 @@ static void load_cell(int row, int col){ gridCells[row][col]._Sreceived, gridCells[row][col]._Gwf, gridCells[row][col].stats_init); /* Copy this cell's SXW variables into the local variables in sxw.c */ - copy_sxw_variables(&gridCells[row][col].mySXW, &gridCells[row][col].mySXWResources, &gridCells[row][col].myTranspWindow); + copy_sxw_variables(gridCells[row][col].mySXW, gridCells[row][col].mySXWResources, gridCells[row][col].myTranspWindow); } /* Nullify all global variables. This function should appear after every call to load_cell to prevent diff --git a/sxw.c b/sxw.c index 1b187495..302e4251 100644 --- a/sxw.c +++ b/sxw.c @@ -141,6 +141,9 @@ void load_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* gri void save_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ); void free_sxw_memory( void ); void _deallocate_memory(void); +SXW_t* getSXW(void); +SXW_resourceType* getSXWResources(void); +transp_t* getTranspWindow(void); void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); @@ -162,13 +165,7 @@ void SXW_Init( Bool init_SW, char *f_roots ) { RandSeed(Globals->randseed, &resource_rng); - /* If we are running gridded mode we do not need to allocate any memory - because allocate_gridCells() in ST_grid did it for us. */ - if(!UseGrid){ - _allocate_memory(); //Allocate memory for all local pointers - } - - SXWResources->_resource_cur = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "SXW_Init"); + _allocate_memory(); //Allocate memory for all local pointers _sxwfiles[0] = &SXW->f_roots; _sxwfiles[1] = &SXW->f_phen; @@ -429,6 +426,23 @@ static void _allocate_memory(void){ SXW = (SXW_t*) Mem_Calloc(1, sizeof(SXW_t), "_allocate_memory: SXW"); SXWResources = (SXW_resourceType*) Mem_Calloc(1, sizeof(SXW_resourceType), "_allocate_memory: SXWResources"); + + SXWResources->_resource_cur = (RealF *)Mem_Calloc(SuperGlobals.max_rgroups, sizeof(RealF), "_allocate_memory: _resource_cur"); +} + +/* Returns a pointer to the local SXW variable. */ +SXW_t* getSXW(void){ + return SXW; +} + +/* Returns a pointer to the local SXWResources variable. */ +SXW_resourceType* getSXWResources(void){ + return SXWResources; +} + +/* Returns a pointer to the local transp_window variable. */ +transp_t* getTranspWindow(void){ + return transp_window; } /* Deallocate any sxw local pointers. When running the non-gridded mode From 5afbc6d0fc215fc9693cadca6c1516279304880c Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 3 Jun 2019 11:30:07 -0600 Subject: [PATCH 066/167] Removed references to Globals without loading a cell The gridded code made calls to "Globals" without loading in a cell. This reulted in a seg fault. Instead, I now use gridCells[0][0].myGlobals because gridCells[0][0] is guaranteed to exist. (issue #287) --- ST_grid.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 5fb250d2..3fb6ffe1 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -531,7 +531,7 @@ void runGrid(void) char SW_prefix_permanent[2048]; sprintf(SW_prefix_permanent, "%s/%s", grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS], SW_Weather.name_prefix); - for (iter = 1; iter <= Globals->runModelIterations; iter++) + for (iter = 1; iter <= gridCells[0][0].myGlobals.runModelIterations; iter++) { //for each iteration /* @@ -553,14 +553,14 @@ void runGrid(void) } unload_cell(); // Reset the global variables - RandSeed(Globals->randseed, &environs_rng); - RandSeed(Globals->randseed, &mortality_rng); - RandSeed(Globals->randseed, &resgroups_rng); - RandSeed(Globals->randseed, &species_rng); - RandSeed(Globals->randseed, &grid_rng); - RandSeed(Globals->randseed, &markov_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &environs_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &mortality_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &resgroups_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &species_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &grid_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &markov_rng); - for (year = 1; year <= Globals->runModelYears; year++) + for (year = 1; year <= gridCells[0][0].myGlobals.runModelYears; year++) { //for each year for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) From 58d8a92ca87197f8e55656439d0de0bc3d338124 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 3 Jun 2019 13:46:39 -0600 Subject: [PATCH 067/167] Added someKillage to cellType _SomeKillage is a global variable that is referenced in ST_mortality.c. It is cell-specific and is therefore now accounted for in the cellType struct. (issue #287) --- ST_grid.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index 3fb6ffe1..42d28a3c 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -175,6 +175,8 @@ struct grid_cell_st Grid_Init_Species_St mySpeciesInit; /* seed dispersal information corresponding to this cell */ Grid_SD_St *mySeedDispersal; + + Bool* someKillage; /* ---------------- accumulators -------------------- */ StatType *_Dist, *_Ppt, *_Temp, @@ -284,6 +286,7 @@ Grid_SD_St **grid_SD; //for seed dispersal int nSoilTypes, *soilTypes_Array, *grid_SoilTypes; extern Bool UseProgressBar; +extern Bool* _SomeKillage; /******** Modular External Function Declarations ***********/ /* -- truly global functions are declared in functions.h --*/ @@ -958,6 +961,8 @@ static void allocate_gridCells(int rows, int cols){ // species_seed_avail is a dynamically allocated array gridCells[i][j].mySpeciesInit.species_seed_avail = (int*) Mem_Calloc(MAX_SPECIES, sizeof(int), "allocate_gridCells: mySpeciesInit"); + + gridCells[i][j].someKillage = (Bool*) Mem_Calloc(1, sizeof(Bool), "allocate_gridCells: someKillage"); } } } @@ -1680,6 +1685,8 @@ static void load_cell(int row, int col){ /* TRUE if this cell is in spinup mode */ DuringSpinup = gridCells[row][col].duringSpinup; + _SomeKillage = gridCells[row][col].someKillage; + /* Copy this cell's accumulators into the local accumulators in ST_stats.c */ stat_Copy_Accumulators(gridCells[row][col]._Dist, gridCells[row][col]._Ppt, gridCells[row][col]._Temp, gridCells[row][col]._Grp, gridCells[row][col]._Gsize, gridCells[row][col]._Gpr, From 93345f594ee8e12cac333915b60a81898eb08fad Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 4 Jun 2019 10:04:40 -0600 Subject: [PATCH 068/167] Added function to allocate gridCell accumulators (issue #284) As I explain of line 943 of ST_grid.c, the fact that accumulators are local makes allocating them difficult. Instead of taking the approach I took with SXW variables, I decided to add an allocation function to ST_grid.c. This function is similar to _init in ST_stats.c, except it loops though each cell to allocate it's unique accumulators. That being said, the gridded mode can now make it though the main loop and crashes at stat output. --- ST_grid.c | 204 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index 42d28a3c..113a6bd0 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -382,6 +382,7 @@ static void _init_stepwat_inputs(void); static void _init_grid_globals(void); static void _init_spinup_globals(void); static void allocate_gridCells(int rows, int cols); +static void allocate_accumulators(void); static void _load_grid_globals(void); static void _load_spinup_globals(void); static void _free_grid_memory(void); @@ -939,6 +940,12 @@ static void _init_stepwat_inputs(void) } /* End for each row */ unload_cell(); // Reset the global variables + /* Since the accumulators used in ST_stats.c are local, we need to allocate our accumulators in ST_grid. + The other option is to create get functions for every accumulator, which is what we do for SXW variables. + The reason we do not do this for accumulators is the sheer number of accumulators, which would require + 14 get functions (as of 4/5/19). */ + allocate_accumulators(); + ChDir(".."); // go back to the folder we started in } @@ -967,6 +974,203 @@ static void allocate_gridCells(int rows, int cols){ } } +/* Initialize each gridCell's accumulators. + Must be called after STEPWAT inputs have been read. */ +static void allocate_accumulators(void){ + int i, j; + SppIndex sp; + GrpIndex rg; + + /* Iterate across all cells */ + for(int i = 0; i < grid_Rows; ++i){ + for(int j = 0; j < grid_Cols; ++j){ + /* load_cell is not necessary for the actual accumulators, but it is necessary for + the ForEach loops. We still have to refer to the accumulators as + gridCells[i][j]. because the ST_stats accumulators are local. */ + load_cell(i,j); + + if (BmassFlags.dist) { + gridCells[i][j]._Dist = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(Dist)"); + gridCells[i][j]._Dist->s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(Dist)"); + } + if (BmassFlags.ppt) { + gridCells[i][j]._Ppt = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(PPT"); + gridCells[i][j]._Ppt->s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(PPT)"); + } + if (BmassFlags.tmp) { + gridCells[i][j]._Temp = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(Temp)"); + gridCells[i][j]._Temp->s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(Temp)"); + } + if (BmassFlags.grpb) { + gridCells[i][j]._Grp = (struct stat_st *) + Mem_Calloc( Globals->grpCount, + sizeof(struct stat_st), + "allocate_accumulators(Grp)"); + ForEachGroup(rg){ + gridCells[i][j]._Grp[rg].s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(Grp[rg].s)"); + } + + if (BmassFlags.size) { + gridCells[i][j]._Gsize = (struct stat_st *) + Mem_Calloc( Globals->grpCount, + sizeof(struct stat_st), + "allocate_accumulators(GSize)"); + ForEachGroup(rg){ + gridCells[i][j]._Gsize[rg].s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(GSize[rg].s)"); + } + } + if (BmassFlags.pr) { + gridCells[i][j]._Gpr = (struct stat_st *) + Mem_Calloc( Globals->grpCount, + sizeof(struct stat_st), + "allocate_accumulators(Gpr)"); + ForEachGroup(rg){ + gridCells[i][j]._Gpr[rg].s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(Gpr[rg].s)"); + } + } + + if (BmassFlags.wildfire || BmassFlags.prescribedfire) { + gridCells[i][j]._Gwf = (struct fire_st *) + Mem_Calloc( 1, sizeof(struct fire_st), + "allocate_accumulators(Gwf)"); + + gridCells[i][j]._Gwf->wildfire = (int *) Mem_Calloc( 1, + sizeof(int) * Globals->runModelYears, + "allocate_accumulators(Gwf->wildfire)"); + + gridCells[i][j]._Gwf->prescribedFire = (int **) Mem_Calloc( 1, + sizeof(int **) * SuperGlobals.max_rgroups, + "allocate_accumulators(Gwf->prescribedfire"); + + ForEachGroup(rg){ + gridCells[i][j]._Gwf->prescribedFire[rg] = (int *) + Mem_Calloc( Globals->runModelYears, + sizeof(int) * Globals->runModelYears, + "allocate_accumulators(Gwf->prescribedFire)"); + } + } + } + + if (MortFlags.group) { + gridCells[i][j]._Gestab = (struct stat_st *) + Mem_Calloc( Globals->grpCount, + sizeof(struct stat_st), + "allocate_accumulators(Gestab)"); + + gridCells[i][j]._Gmort = (struct stat_st *) + Mem_Calloc( Globals->grpCount, + sizeof(struct stat_st), + "allocate_accumulators(Gmort)"); + ForEachGroup(rg){ + gridCells[i][j]._Gestab[rg].s = (struct accumulators_st *) + Mem_Calloc( 1, sizeof(struct accumulators_st), + "allocate_accumulators(Gestab[rg].s)"); + gridCells[i][j]._Gmort[rg].s = (struct accumulators_st *) + Mem_Calloc( GrpMaxAge(rg), + sizeof(struct accumulators_st), + "allocate_accumulators(Gmort[rg].s)"); + } + } + + if (BmassFlags.sppb) { + gridCells[i][j]._Spp = (struct stat_st *) + Mem_Calloc( Globals->sppCount, + sizeof(struct stat_st), + "allocate_accumulators(Spp)"); + ForEachSpecies(sp){ + gridCells[i][j]._Spp[sp].s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(Spp[sp].s)"); + } + + if (BmassFlags.indv) { + gridCells[i][j]._Indv = (struct stat_st *) + Mem_Calloc( Globals->sppCount, + sizeof(struct stat_st), + "allocate_accumulators(Indv)"); + ForEachSpecies(sp){ + gridCells[i][j]._Indv[sp].s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(Indv[sp].s)"); + } + } + } + if (MortFlags.species) { + gridCells[i][j]._Sestab = (struct stat_st *) + Mem_Calloc( Globals->sppCount, + sizeof(struct stat_st), + "allocate_accumulators(Sestab)"); + + gridCells[i][j]._Smort = (struct stat_st *) + Mem_Calloc( Globals->sppCount, + sizeof(struct stat_st), + "allocate_accumulators(Smort)"); + + ForEachSpecies(sp){ + gridCells[i][j]._Sestab[sp].s = (struct accumulators_st *) + Mem_Calloc( 1, sizeof(struct accumulators_st), + "allocate_accumulators(Sestab[sp].s)"); + gridCells[i][j]._Smort[sp].s = (struct accumulators_st *) + Mem_Calloc( SppMaxAge(sp), + sizeof(struct accumulators_st), + "allocate_accumulators(Smort[sp].s)"); + } + } + + if (UseSeedDispersal) { + gridCells[i][j]._Sreceived = Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "allocate_accumulators(Sreceived)"); + + ForEachSpecies(sp) { + gridCells[i][j]._Sreceived[sp].s = (struct accumulators_st *) + Mem_Calloc( Globals->runModelYears, + sizeof(struct accumulators_st), + "allocate_accumulators(Sreceived[sp].s)"); + gridCells[i][j]._Sreceived[sp].name = &Species[sp]->name[0]; + } + } + + /* "appoint" names of columns*/ + if (BmassFlags.grpb) { + ForEachGroup(rg) + gridCells[i][j]._Grp[rg].name = &RGroup[rg]->name[0]; + } + if (MortFlags.group) { + ForEachGroup(rg) + gridCells[i][j]._Gmort[rg].name = &RGroup[rg]->name[0]; + } + if (BmassFlags.sppb) { + ForEachSpecies(sp) + gridCells[i][j]._Spp[sp].name = &Species[sp]->name[0]; + } + if (MortFlags.species) { + ForEachSpecies(sp) + gridCells[i][j]._Smort[sp].name = &Species[sp]->name[0]; + } + } /* End for each column */ + } /* End for each row */ + unload_cell(); // Unload the cell to protect the last cell from unintended modification. +} + /***********************************************************/ static IndivType* _create_empty_indv(void) { From bf83f863bc2e60530e4fe71d6c26e90124d1cbd6 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 4 Jun 2019 11:02:21 -0600 Subject: [PATCH 069/167] Moved printing general info to RunGrid (issue #287) SXW_Init was printing the non-gridded mode information to stdout. The problem with this was the fact that we call SXW_Init n times where n is the number of cells. This resulted in the same message being generated multiple times. I wrapped the print statement in SXW_Init in an if(!UseGrid) block to prevent the messages in gridded mode. I then added a series of print statements to RunGrid which are more descriptive of the gridded mode. --- ST_grid.c | 19 ++++++++++++++++--- sxw.c | 10 +++++++--- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 113a6bd0..55abcd9e 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -527,6 +527,22 @@ void runGrid(void) Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; + /* Print some general information to stdout */ + load_cell(0,0); + printf("Number of layers: %d\n", SW_Site.n_layers); + printf("Number of iterations: %d\n", Globals->runModelIterations); + printf("Number of years: %d\n", Globals->runModelYears); + printf("Number of cells: %d\n\n", grid_Cells); + if(UseDisturbances) printf("Using grid Disturbances file.\n"); + if(UseSoils) printf("Using grid soils file\n"); + if(UseSeedDispersal){ + printf("Seeds availible for %d years at the start of the simulation.\n",sd_NYearsSeedsAvailable); + if(sd_Option1a) printf("All species and cells are eligible for seed dispersal.\n"); + } + if(sd_Option2a) printf("Running Spinup for %s cells.\n", sd_Option2b ? "all" : "specified"); + unload_cell(); + /* END printing general info */ + if (sd_Option2a || sd_Option2b) _run_spinup(); // does the initial spinup @@ -1883,9 +1899,6 @@ static void load_cell(int row, int col){ /* Global variables corresponding to this cell */ Globals = &gridCells[row][col].myGlobals; - /* If TRUE this cell should use seed dispersal */ - UseSeedDispersal = gridCells[row][col].useSeedDispersal; - /* TRUE if this cell is in spinup mode */ DuringSpinup = gridCells[row][col].duringSpinup; diff --git a/sxw.c b/sxw.c index 302e4251..5322d088 100644 --- a/sxw.c +++ b/sxw.c @@ -207,9 +207,13 @@ void SXW_Init( Bool init_SW, char *f_roots ) { SXW->NSoLyrs = SW_Site.n_layers; - printf("Number of layers: %d\n", SW_Site.n_layers); - printf("Number of iterations: %d\n", Globals->runModelIterations); - printf("Number of years: %d\n", Globals->runModelYears); + /* Print general information to stdout. + If we are using gridded mode this functionallity will be handled in ST_grid.c */ + if(!UseGrid){ + printf("Number of layers: %d\n", SW_Site.n_layers); + printf("Number of iterations: %d\n", Globals->runModelIterations); + printf("Number of years: %d\n", Globals->runModelYears); + } _make_arrays(); From d346d9e67bb13d86ab942ee894801f79ce1b4888 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 4 Jun 2019 11:53:12 -0600 Subject: [PATCH 070/167] Changes _load_cell call in RunGrid, updated Spinup (issues #287 and #300) In RunGrid: * Replaced _load_cell with load_cell. * deleted _save_cell call. In _run_spinup: * Seeded RNGs with gridCells[0][0]'s randseed variable. * Initialized the plots of all cells instead of one. --- ST_grid.c | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 55abcd9e..da1ea03f 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -628,15 +628,17 @@ void runGrid(void) }/* end model run for this year*/ // collects the data appropriately for the mort output... (ie. fills the accumulators in ST_stats.c with the values that they need) - if (MortFlags.summary) - for (i = 1; i <= grid_Rows; i++) + if (MortFlags.summary){ + for (i = 1; i <= grid_Rows; i++){ for (j = 1; j <= grid_Cols; j++) { - _load_cell(i, j, Globals->runModelYears, TRUE); + load_cell(i, j); stat_Collect_GMort(); stat_Collect_SMort(); - _save_cell(i, j, Globals->runModelYears, TRUE); } + } + } + unload_cell(); //reset soilwat to initial condition ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); SXW_Reset(); @@ -723,17 +725,25 @@ static void _run_spinup(void) { //for each iteration... only 1 iteration allowed for now /* Since this is technically an iteration so we need to seed the RNGs. */ - RandSeed(Globals->randseed, &environs_rng); - RandSeed(Globals->randseed, &mortality_rng); - RandSeed(Globals->randseed, &resgroups_rng); - RandSeed(Globals->randseed, &species_rng); - RandSeed(Globals->randseed, &grid_rng); - RandSeed(Globals->randseed, &markov_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &environs_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &mortality_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &resgroups_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &species_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &grid_rng); + RandSeed(gridCells[0][0].myGlobals.randseed, &markov_rng); if (BmassFlags.yearly || MortFlags.yearly) parm_Initialize(); - Plot_Initialize(); + // Initialize the plot for each grid cell + for (i = 0; i < grid_Rows; i++){ + for (j = 0; j < grid_Cols; j++){ + load_cell(i, j); + Plot_Initialize(); + Globals->currIter = iter; + } + } + unload_cell(); // Reset the global variables /* Before we start iterating we need to swap Species[sp]->use_me and mySpeciesInit.species_seed_avail[sp]. species_seed_avail is an array of booleans that represent whether the given species should be used From 3201f8e9f0167df664ea6fcfb1948db2ddc54ab0 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 4 Jun 2019 14:02:38 -0600 Subject: [PATCH 071/167] SXW_Reset(void) -> SXW_Reset(char* SOILWAT_file) (issue #300) In _run_spinup we call SXW_Reinit, which calls SXW_Reset. SXW_Reset had a reference to SXW->f_watin which is not guaranteed to exist in gridded mode. I got around this by having the function accept the file name as an input parameter. This way, it can be used in gridded or non-gridded mode. --- ST_grid.c | 16 ++++------------ ST_main.c | 2 +- sxw.c | 14 +++++++------- sxw_funcs.h | 2 +- 4 files changed, 13 insertions(+), 21 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index da1ea03f..253140eb 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -641,7 +641,7 @@ void runGrid(void) unload_cell(); //reset soilwat to initial condition ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); - SXW_Reset(); + SXW_Reset(gridCells[0][0].mySXW->f_watin); Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; ChDir(".."); @@ -806,14 +806,8 @@ static void _run_spinup(void) grazing_EndOfYear(); // Livestock grazing - //save_annual_species_relsize(); // See stat_Collect below for why this is commented out. - mort_EndOfYear(); // End of year mortality. - /* stat_Collect was called in spinup, but I have no idea why. We definitely - do not want to use the accumulator values, so why collect them? -Chandler */ - //stat_Collect(year); - _kill_annuals(); // Kill annuals proportion_Recovery(); // Recover from any disturbances _kill_extra_growth(); // Kill superfluous growth @@ -824,12 +818,11 @@ static void _run_spinup(void) } /* end model run for this year*/ ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); - SXW_Reset(); + SXW_Reset(gridCells[0][0].mySXW->f_watin); //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; ChDir(".."); - //_free_grid_globals(); //free's the grid variables that change every iter } /* End iterations */ /* Swap back Species[sp]->use_me and species_seed_avail[sp]. */ @@ -837,7 +830,6 @@ static void _run_spinup(void) for(j = 0; j < grid_Cols; ++j){ load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee that ForEachGroup would iterate correctly */ - /* Begin swaping variables */ ForEachGroup(rg){ ForEachGroupSpp(sp, rg, k){ @@ -1008,8 +1000,8 @@ static void allocate_accumulators(void){ GrpIndex rg; /* Iterate across all cells */ - for(int i = 0; i < grid_Rows; ++i){ - for(int j = 0; j < grid_Cols; ++j){ + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ /* load_cell is not necessary for the actual accumulators, but it is necessary for the ForEach loops. We still have to refer to the accumulators as gridCells[i][j]. because the ST_stats accumulators are local. */ diff --git a/ST_main.c b/ST_main.c index a77bddbf..67d852d7 100644 --- a/ST_main.c +++ b/ST_main.c @@ -305,7 +305,7 @@ int main(int argc, char **argv) { { // don't reset in last iteration because we need to close files // before clearing/de-allocated SOILWAT2-memory - SXW_Reset(); + SXW_Reset(SXW->f_watin); } } /* end model run for this iteration*/ diff --git a/sxw.c b/sxw.c index 5322d088..7bfb9511 100644 --- a/sxw.c +++ b/sxw.c @@ -134,7 +134,7 @@ void _print_debuginfo(void); void debugCleanUp(void); static void _make_swc_array(void); static void SXW_SW_Setup_Echo(void); -static void SXW_Reinit(void); +static void SXW_Reinit(char* SOILWAT_file); //these last four functions are to be used in ST_grid.c void load_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ); @@ -194,7 +194,7 @@ void SXW_Init( Bool init_SW, char *f_roots ) { if (init_SW) { - SXW_Reinit(); + SXW_Reinit(SXW->f_watin); } SXW->NTrLyrs = SW_Site.n_transp_lyrs[0]; @@ -234,14 +234,14 @@ void SXW_Init( Bool init_SW, char *f_roots ) { @brief This function initializes and allocates SOILWAT2 structures, and reads SOIILWAT2 inputs. */ -static void SXW_Reinit(void) { +static void SXW_Reinit(char* SOILWAT_file) { char *temp; - temp = strdup(SXW->f_watin); + temp = strdup(SOILWAT_file); SW_CTL_init_model(temp); SW_CTL_obtain_inputs(); SW_OUT_set_SXWrequests(); - free(temp); + free(temp); } @@ -256,9 +256,9 @@ static void SXW_Reinit(void) { over from one STEPWAT2 iteration to the next. They are only de-allocated at the end of an entire STEPWAT2 run (see `ST_main.c/main()`). */ -void SXW_Reset(void) { +void SXW_Reset(char* SOILWAT_file) { SW_CTL_clear_model(FALSE); // don't reset output arrays - SXW_Reinit(); + SXW_Reinit(SOILWAT_file); } void SXW_InitPlot (void) { diff --git a/sxw_funcs.h b/sxw_funcs.h index 4f98bc55..9dcfc64f 100644 --- a/sxw_funcs.h +++ b/sxw_funcs.h @@ -19,7 +19,7 @@ RealF SXW_GetTranspiration( GrpIndex rg); void SXW_Init( Bool init_SW, char *f_roots ); -void SXW_Reset(void); +void SXW_Reset(char* SOILWAT_file); void SXW_Run_SOILWAT (void); void SXW_InitPlot (void); void SXW_PrintDebug(Bool cleanup) ; From 825388eb5fa63b5796f8fa18a35cfbf8d41f6a65 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 5 Jun 2019 10:22:37 -0600 Subject: [PATCH 072/167] Moved runModelYears, runModelIterations, nCells and randseed I moved these variables to the SuperGlobals struct because they are constant across all cells. I also updated the SOILWAT head to the commit that affects these changes. (issue #317) --- ST_grid.c | 62 +++++++++++++++++----------------- ST_main.c | 22 ++++++------ ST_params.c | 14 ++++---- ST_sql.c | 2 +- ST_stats.c | 94 ++++++++++++++++++++++++++-------------------------- ST_structs.h | 14 ++++---- sw_src | 2 +- sxw.c | 6 ++-- sxw_sql.c | 2 +- 9 files changed, 110 insertions(+), 108 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 253140eb..7f571625 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -530,8 +530,8 @@ void runGrid(void) /* Print some general information to stdout */ load_cell(0,0); printf("Number of layers: %d\n", SW_Site.n_layers); - printf("Number of iterations: %d\n", Globals->runModelIterations); - printf("Number of years: %d\n", Globals->runModelYears); + printf("Number of iterations: %d\n", SuperGlobals.runModelIterations); + printf("Number of years: %d\n", SuperGlobals.runModelYears); printf("Number of cells: %d\n\n", grid_Cells); if(UseDisturbances) printf("Using grid Disturbances file.\n"); if(UseSoils) printf("Using grid soils file\n"); @@ -551,7 +551,7 @@ void runGrid(void) char SW_prefix_permanent[2048]; sprintf(SW_prefix_permanent, "%s/%s", grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS], SW_Weather.name_prefix); - for (iter = 1; iter <= gridCells[0][0].myGlobals.runModelIterations; iter++) + for (iter = 1; iter <= SuperGlobals.runModelIterations; iter++) { //for each iteration /* @@ -573,14 +573,14 @@ void runGrid(void) } unload_cell(); // Reset the global variables - RandSeed(gridCells[0][0].myGlobals.randseed, &environs_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &mortality_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &resgroups_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &species_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &grid_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &markov_rng); + RandSeed(SuperGlobals.randseed, &environs_rng); + RandSeed(SuperGlobals.randseed, &mortality_rng); + RandSeed(SuperGlobals.randseed, &resgroups_rng); + RandSeed(SuperGlobals.randseed, &species_rng); + RandSeed(SuperGlobals.randseed, &grid_rng); + RandSeed(SuperGlobals.randseed, &markov_rng); - for (year = 1; year <= gridCells[0][0].myGlobals.runModelYears; year++) + for (year = 1; year <= SuperGlobals.runModelYears; year++) { //for each year for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) @@ -683,7 +683,7 @@ void runGrid(void) _deallocate_memory(); // sxw memory. } -/* "Spinup" the model by running for Globals->runModelYears without seed dispersal or statistics outputs. */ +/* "Spinup" the model by running for SuperGlobals.runModelYears without seed dispersal or statistics outputs. */ static void _run_spinup(void) { /* Dummy accumulators to ensure we do not collect statistics */ @@ -705,8 +705,8 @@ static void _run_spinup(void) /* 'Globals' is not allocated in gridded mode. Therefore we need to implicitely remember years and iterations. gridCells[0][0] is guaranteed to exist because it is populated first. */ - int iterations = gridCells[0][0].myGlobals.runModelIterations; - int total_years = gridCells[0][0].myGlobals.runModelYears; + int iterations = SuperGlobals.runModelIterations; + int total_years = SuperGlobals.runModelYears; /* killedany for mortality functions, temporary_storage for swapping variables */ Bool killedany, temporary_storage; @@ -725,12 +725,12 @@ static void _run_spinup(void) { //for each iteration... only 1 iteration allowed for now /* Since this is technically an iteration so we need to seed the RNGs. */ - RandSeed(gridCells[0][0].myGlobals.randseed, &environs_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &mortality_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &resgroups_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &species_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &grid_rng); - RandSeed(gridCells[0][0].myGlobals.randseed, &markov_rng); + RandSeed(SuperGlobals.randseed, &environs_rng); + RandSeed(SuperGlobals.randseed, &mortality_rng); + RandSeed(SuperGlobals.randseed, &resgroups_rng); + RandSeed(SuperGlobals.randseed, &species_rng); + RandSeed(SuperGlobals.randseed, &grid_rng); + RandSeed(SuperGlobals.randseed, &markov_rng); if (BmassFlags.yearly || MortFlags.yearly) parm_Initialize(); @@ -1010,21 +1010,21 @@ static void allocate_accumulators(void){ if (BmassFlags.dist) { gridCells[i][j]._Dist = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(Dist)"); gridCells[i][j]._Dist->s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(Dist)"); } if (BmassFlags.ppt) { gridCells[i][j]._Ppt = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(PPT"); gridCells[i][j]._Ppt->s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(PPT)"); } if (BmassFlags.tmp) { gridCells[i][j]._Temp = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(Temp)"); gridCells[i][j]._Temp->s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(Temp)"); } @@ -1035,7 +1035,7 @@ static void allocate_accumulators(void){ "allocate_accumulators(Grp)"); ForEachGroup(rg){ gridCells[i][j]._Grp[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(Grp[rg].s)"); } @@ -1047,7 +1047,7 @@ static void allocate_accumulators(void){ "allocate_accumulators(GSize)"); ForEachGroup(rg){ gridCells[i][j]._Gsize[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(GSize[rg].s)"); } @@ -1059,7 +1059,7 @@ static void allocate_accumulators(void){ "allocate_accumulators(Gpr)"); ForEachGroup(rg){ gridCells[i][j]._Gpr[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(Gpr[rg].s)"); } @@ -1071,7 +1071,7 @@ static void allocate_accumulators(void){ "allocate_accumulators(Gwf)"); gridCells[i][j]._Gwf->wildfire = (int *) Mem_Calloc( 1, - sizeof(int) * Globals->runModelYears, + sizeof(int) * SuperGlobals.runModelYears, "allocate_accumulators(Gwf->wildfire)"); gridCells[i][j]._Gwf->prescribedFire = (int **) Mem_Calloc( 1, @@ -1080,8 +1080,8 @@ static void allocate_accumulators(void){ ForEachGroup(rg){ gridCells[i][j]._Gwf->prescribedFire[rg] = (int *) - Mem_Calloc( Globals->runModelYears, - sizeof(int) * Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, + sizeof(int) * SuperGlobals.runModelYears, "allocate_accumulators(Gwf->prescribedFire)"); } } @@ -1115,7 +1115,7 @@ static void allocate_accumulators(void){ "allocate_accumulators(Spp)"); ForEachSpecies(sp){ gridCells[i][j]._Spp[sp].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(Spp[sp].s)"); } @@ -1127,7 +1127,7 @@ static void allocate_accumulators(void){ "allocate_accumulators(Indv)"); ForEachSpecies(sp){ gridCells[i][j]._Indv[sp].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(Indv[sp].s)"); } @@ -1160,7 +1160,7 @@ static void allocate_accumulators(void){ ForEachSpecies(sp) { gridCells[i][j]._Sreceived[sp].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "allocate_accumulators(Sreceived[sp].s)"); gridCells[i][j]._Sreceived[sp].name = &Species[sp]->name[0]; diff --git a/ST_main.c b/ST_main.c index 67d852d7..b93bfd6a 100644 --- a/ST_main.c +++ b/ST_main.c @@ -198,12 +198,12 @@ int main(int argc, char **argv) { ST_connect("Output/stdebug"); } - incr = (IntS) ((float) Globals->runModelIterations / 10); + incr = (IntS) ((float) SuperGlobals.runModelIterations / 10); if (incr == 0) incr = 1; /* --- Begin a new iteration ------ */ - for (iter = 1; iter <= Globals->runModelIterations; iter++) { + for (iter = 1; iter <= SuperGlobals.runModelIterations; iter++) { if (progfp == stderr) { if (iter % incr == 0) fprintf(progfp, "."); @@ -213,12 +213,12 @@ int main(int argc, char **argv) { Plot_Initialize(); - RandSeed(Globals->randseed, &environs_rng); - RandSeed(Globals->randseed, &mortality_rng); - RandSeed(Globals->randseed, &resgroups_rng); - RandSeed(Globals->randseed, &species_rng); - RandSeed(Globals->randseed, &grid_rng); - RandSeed(Globals->randseed, &markov_rng); + RandSeed(SuperGlobals.randseed, &environs_rng); + RandSeed(SuperGlobals.randseed, &mortality_rng); + RandSeed(SuperGlobals.randseed, &resgroups_rng); + RandSeed(SuperGlobals.randseed, &species_rng); + RandSeed(SuperGlobals.randseed, &grid_rng); + RandSeed(SuperGlobals.randseed, &markov_rng); Globals->currIter = iter; @@ -227,11 +227,11 @@ int main(int argc, char **argv) { } if (prepare_IterationSummary) { - print_IterationSummary = (Bool) (Globals->currIter == Globals->runModelIterations); + print_IterationSummary = (Bool) (Globals->currIter == SuperGlobals.runModelIterations); } /* ------ Begin running the model ------ */ - for (year = 1; year <= Globals->runModelYears; year++) { + for (year = 1; year <= SuperGlobals.runModelYears; year++) { //printf("------------------------Repetition/year = %d / %d\n", iter, year); @@ -301,7 +301,7 @@ int main(int argc, char **argv) { // dont need to restart if last iteration finished // this keeps it from re-writing the output folder and overwriting output files - if (Globals->currIter != Globals->runModelIterations) + if (Globals->currIter != SuperGlobals.runModelIterations) { // don't reset in last iteration because we need to close files // before clearing/de-allocated SOILWAT2-memory diff --git a/ST_params.c b/ST_params.c index ba52f15d..de146e72 100644 --- a/ST_params.c +++ b/ST_params.c @@ -184,17 +184,17 @@ static void _model_init( void) { &years, &seed); - Globals->runModelYears = years; - Globals->Max_Age = Globals->runModelYears; - Globals->runModelIterations = atoi(tmp); - if (Globals->runModelIterations < 1 || - Globals->runModelYears < 1 ) { + SuperGlobals.runModelYears = years; + Globals->Max_Age = SuperGlobals.runModelYears; + SuperGlobals.runModelIterations = atoi(tmp); + if (SuperGlobals.runModelIterations < 1 || + SuperGlobals.runModelYears < 1 ) { LogError(logfp, LOGFATAL,"Invalid parameters for RunModelIterations " "or RunModelYears (%s)", MyFileName); } Globals->bmass.suffixwidth = Globals->mort.suffixwidth = strlen(tmp); - Globals->randseed = (IntL) ((seed) ? -abs(seed) : 0); + SuperGlobals.randseed = (IntL) ((seed) ? -abs(seed) : 0); } CloseFile(&f); @@ -324,7 +324,7 @@ static void _check_species( void) { */ IntS i, cnt, maxage, minage, /* placeholders */ - runyrs = Globals->runModelYears; /* shorthand */ + runyrs = SuperGlobals.runModelYears; /* shorthand */ SppIndex sp; GrpIndex rg; Bool tripped = FALSE; diff --git a/ST_sql.c b/ST_sql.c index d051dca7..4d72c2a6 100644 --- a/ST_sql.c +++ b/ST_sql.c @@ -267,7 +267,7 @@ static void insertInfo(void) { beginTransaction(); sprintf(sql, "INSERT INTO info (Years, Iterations, Seed, RGroups, Species, PlotSize) VALUES (%d, %d, %d, %d, %d, %f);", - Globals->runModelYears, Globals->runModelIterations, (int) Globals->randseed, + SuperGlobals.runModelYears, SuperGlobals.runModelIterations, (int) SuperGlobals.randseed, Globals->grpCount, Globals->sppCount, Globals->plotsize); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); diff --git a/ST_stats.c b/ST_stats.c index badb8854..82dad85f 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -207,17 +207,17 @@ static void _init( void) { if (BmassFlags.dist) _Dist_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Dist)"); if (BmassFlags.ppt) _Ppt_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(PPT)"); if (BmassFlags.tmp) _Temp_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Temp)"); @@ -227,7 +227,7 @@ static void _init( void) { Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Grp)"); ForEachGroup(rg) _Grp_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Grp[rg].s)"); + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Grp[rg].s)"); if (BmassFlags.size) { @@ -235,7 +235,7 @@ static void _init( void) { Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(GSize)"); ForEachGroup(rg) _Gsize_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(GSize[rg].s)"); + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(GSize[rg].s)"); } if (BmassFlags.pr) { @@ -243,7 +243,7 @@ static void _init( void) { Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpr)"); ForEachGroup(rg) _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpr[rg].s)"); + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpr[rg].s)"); } if (BmassFlags.wildfire) { @@ -251,7 +251,7 @@ static void _init( void) { Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gwf)"); ForEachGroup(rg) _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gwf[rg].s)"); + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gwf[rg].s)"); } if (BmassFlags.prescribedfire) { @@ -259,7 +259,7 @@ static void _init( void) { Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpf)"); ForEachGroup(rg) _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpf[rg].s)"); + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpf[rg].s)"); } } @@ -269,7 +269,7 @@ static void _init( void) { Mem_Calloc( Globals->sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Spp)"); ForEachSpecies(sp) _Spp_grid_cell[sp].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Spp[sp].s)"); + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Spp[sp].s)"); if (BmassFlags.indv) { @@ -277,7 +277,7 @@ static void _init( void) { Mem_Calloc( Globals->sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Indv)"); ForEachSpecies(sp) _Indv_grid_cell[sp].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Indv[sp].s)"); + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Indv[sp].s)"); } } @@ -286,21 +286,21 @@ static void _init( void) { if (BmassFlags.dist) { _Dist = (StatType*) Mem_Calloc(1, sizeof(StatType), "_stat_init(Dist)"); _Dist->s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Dist)"); } if (BmassFlags.ppt) { _Ppt = (StatType*) Mem_Calloc(1, sizeof(StatType), "_stat_init(PPT"); _Ppt->s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(PPT)"); } if (BmassFlags.tmp) { _Temp = (StatType*) Mem_Calloc(1, sizeof(StatType), "_stat_init(Temp)"); _Temp->s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Temp)"); } @@ -311,7 +311,7 @@ static void _init( void) { "_stat_init(Grp)"); ForEachGroup(rg) _Grp[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Grp[rg].s)"); @@ -322,7 +322,7 @@ static void _init( void) { "_stat_init(GSize)"); ForEachGroup(rg) _Gsize[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(GSize[rg].s)"); } @@ -333,7 +333,7 @@ static void _init( void) { "_stat_init(Gpr)"); ForEachGroup(rg) _Gpr[rg].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Gpr[rg].s)"); } @@ -346,7 +346,7 @@ static void _init( void) { _Gwf->wildfire = (int *) Mem_Calloc( 1, - sizeof(int) * Globals->runModelYears, + sizeof(int) * SuperGlobals.runModelYears, "_stat_init(Gwf->wildfire)"); _Gwf->prescribedFire = (int **) @@ -356,8 +356,8 @@ static void _init( void) { ForEachGroup(rg){ _Gwf->prescribedFire[rg] = (int *) - Mem_Calloc( Globals->runModelYears, - sizeof(int) * Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, + sizeof(int) * SuperGlobals.runModelYears, "_stat_init(Gwf->prescribedFire)"); } } @@ -392,7 +392,7 @@ static void _init( void) { "_stat_init(Spp)"); ForEachSpecies(sp) _Spp[sp].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Spp[sp].s)"); @@ -403,7 +403,7 @@ static void _init( void) { "_stat_init(Indv)"); ForEachSpecies(sp) _Indv[sp].s = (struct accumulators_st *) - Mem_Calloc( Globals->runModelYears, + Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Indv[sp].s)"); } @@ -432,7 +432,7 @@ static void _init( void) { if (UseSeedDispersal && UseGrid) { _Sreceived = Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "_stat_init(Sreceived)"); ForEachSpecies(sp) { - _Sreceived[sp].s = (struct accumulators_st *)Mem_Calloc( Globals->runModelYears, sizeof(struct accumulators_st), "_stat_init(Sreceived[sp].s)"); + _Sreceived[sp].s = (struct accumulators_st *)Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), "_stat_init(Sreceived[sp].s)"); _Sreceived[sp].name = &Species[sp]->name[0]; } } @@ -459,20 +459,20 @@ static void _init( void) { /***********************************************************/ void stat_Init_Accumulators( void ) { //allocates memory for all of the grid accumulators - grid_Stat = Mem_Calloc(Globals->nCells, sizeof(accumulators_grid_st), "stat_Init_Accumulators()"); + grid_Stat = Mem_Calloc(SuperGlobals.nCells, sizeof(accumulators_grid_st), "stat_Init_Accumulators()"); int i, j; - for( i = 0; i < Globals->nCells; i++) { - if (BmassFlags.dist) grid_Stat[i].dist = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.ppt) grid_Stat[i].ppt = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.tmp) grid_Stat[i].temp = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + for( i = 0; i < SuperGlobals.nCells; i++) { + if (BmassFlags.dist) grid_Stat[i].dist = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.ppt) grid_Stat[i].ppt = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.tmp) grid_Stat[i].temp = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); if (BmassFlags.grpb) { - grid_Stat[i].grp1 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); // gave grp and gpr numbers attached to them so I wouldn't mix them up lol... bad (confusing) variable names on part of the original creator. - if (BmassFlags.size) grid_Stat[i].gsize = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.pr) grid_Stat[i].gpr2 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if (BmassFlags.wildfire) grid_Stat[i].gwf2 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if (BmassFlags.prescribedfire) grid_Stat[i].gpf2 = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].grp1 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); // gave grp and gpr numbers attached to them so I wouldn't mix them up lol... bad (confusing) variable names on part of the original creator. + if (BmassFlags.size) grid_Stat[i].gsize = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); + if (BmassFlags.pr) grid_Stat[i].gpr2 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + if (BmassFlags.wildfire) grid_Stat[i].gwf2 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + if (BmassFlags.prescribedfire) grid_Stat[i].gpf2 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); } if (MortFlags.group) { grid_Stat[i].gmort = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); @@ -484,8 +484,8 @@ void stat_Init_Accumulators( void ) { } } if(BmassFlags.sppb) { - grid_Stat[i].spp = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if(BmassFlags.indv) grid_Stat[i].indv = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].spp = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + if(BmassFlags.indv) grid_Stat[i].indv = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); } if (MortFlags.species) { grid_Stat[i].smort = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); @@ -498,10 +498,10 @@ void stat_Init_Accumulators( void ) { } if(UseSeedDispersal && UseGrid) - grid_Stat[i].sreceived = Mem_Calloc(Globals->runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); + grid_Stat[i].sreceived = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - for( j = 0; j < Globals->runModelYears; j++) { + for( j = 0; j < SuperGlobals.runModelYears; j++) { if (BmassFlags.grpb) { grid_Stat[i].grp1[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); if (BmassFlags.size) grid_Stat[i].gsize[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); @@ -648,8 +648,8 @@ void stat_Free_Accumulators( void ) { //frees all the memory allocated in stat_init_Accumulators() int i, j; - for( i = 0; i < Globals->nCells; i++) { - for( j = 0; j < Globals->runModelYears; j++) { + for( i = 0; i < SuperGlobals.nCells; i++) { + for( j = 0; j < SuperGlobals.runModelYears; j++) { if(BmassFlags.grpb) { Mem_Free(grid_Stat[i].grp1[j]); if (BmassFlags.size) Mem_Free(grid_Stat[i].gsize[j]); @@ -982,7 +982,7 @@ void stat_Output_AllBmassAvg() { fprintf(f, "%s", buf); } - for( yr=1; yr<= Globals->runModelYears; yr++) { + for( yr=1; yr<= SuperGlobals.runModelYears; yr++) { *buf = '\0'; if (BmassFlags.yr) sprintf(buf, "%d%c", yr, sep); @@ -1107,7 +1107,7 @@ void stat_Output_AllCellAvgBmass(const char * filename) fprintf(f, "%s", buf); } - for (yr = 1; yr <= Globals->runModelYears; yr++) + for (yr = 1; yr <= SuperGlobals.runModelYears; yr++) { *buf = '\0'; @@ -1222,7 +1222,7 @@ void stat_Output_AllBmass(void) { fprintf(f, "%s", buf); } - for( yr=1; yr<= Globals->runModelYears; yr++) { + for( yr=1; yr<= SuperGlobals.runModelYears; yr++) { *buf = '\0'; if (BmassFlags.yr) sprintf(buf, "%d%c", yr, sep); @@ -1342,7 +1342,7 @@ void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool make fprintf(f,"\n"); } - for( yr=1; yr<= Globals->runModelYears; yr++) { + for( yr=1; yr<= SuperGlobals.runModelYears; yr++) { *buf = '\0'; sprintf(buf, "%d%c", yr, sep); @@ -1382,15 +1382,15 @@ static void copyStruct(RealF val,RealF std_val,struct accumulators_grid_cell_st static RealF _get_gridcell_avg(struct accumulators_grid_cell_st *p) { - if (Globals->nCells == 0) + if (SuperGlobals.nCells == 0) return 0.0; - RealF avg = (RealF) (p->sum / (double) Globals->nCells); + RealF avg = (RealF) (p->sum / (double) SuperGlobals.nCells); return avg; } static int _get_gridcell_sum(struct accumulators_grid_cell_st *p) { - if (Globals->nCells == 0) + if (SuperGlobals.nCells == 0) return 0; int sum = (RealF) (p->sum); return sum; @@ -1400,9 +1400,9 @@ static int _get_gridcell_sum(struct accumulators_grid_cell_st *p) /***********************************************************/ static RealF _get_gridcell_std(struct accumulators_grid_cell_st *p) { - if (Globals->nCells == 0) + if (SuperGlobals.nCells == 0) return 0.0; - RealF avg = (RealF) (p->sum_std / (double) Globals->nCells); + RealF avg = (RealF) (p->sum_std / (double) SuperGlobals.nCells); return avg; } diff --git a/ST_structs.h b/ST_structs.h index 3301c61b..da63ff8f 100644 --- a/ST_structs.h +++ b/ST_structs.h @@ -283,16 +283,12 @@ struct globals_st { RealF plotsize, /* size of plot in square meters */ gsppt_prop, /* proportion of ppt during growing season*/ tempparm[2][3]; /* three parms for Warm/Cool growth mod*/ - IntUS runModelYears, /* number of years to run the model*/ - Max_Age, /* oldest plant; same as runModelYears for now */ + IntUS Max_Age, /* oldest plant; same as runModelYears for now */ currYear, - runModelIterations, /* run model this many times for statistics */ currIter, grpCount, /* number of groups defined*/ sppCount, /* number of species defined*/ - transp_window, /* Number of years for which transpiration data is kept*/ - nCells; /* number of cells to use in Grid, only applicable if grid function is being used */ - IntL randseed; /* random seed from input file */ + transp_window; /* Number of years for which transpiration data is kept*/ struct outfiles_st bmass, mort; }; @@ -331,6 +327,12 @@ struct superglobals_st { max_spp_per_grp, /* Maximum species allowed per resource group. */ max_indivs_per_spp, /* Maximum individuals allowed per species. */ max_speciesnamelen; /* Maximum species name length. */ + + IntUS runModelIterations, + runModelYears, + nCells; /* number of cells to use in Grid, only applicable if grid function is being used */ + + IntL randseed; }; #endif diff --git a/sw_src b/sw_src index 611c464e..0336a71c 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit 611c464ea4a1d42b21dd10d447ad0cd31d4e34b8 +Subproject commit 0336a71c5e2c98e9b82e867cb226a00547605db4 diff --git a/sxw.c b/sxw.c index 7bfb9511..43a94ba0 100644 --- a/sxw.c +++ b/sxw.c @@ -163,7 +163,7 @@ void SXW_Init( Bool init_SW, char *f_roots ) { */ char roots[MAX_FILENAMESIZE] = { '\0' }; - RandSeed(Globals->randseed, &resource_rng); + RandSeed(SuperGlobals.randseed, &resource_rng); _allocate_memory(); //Allocate memory for all local pointers @@ -211,8 +211,8 @@ void SXW_Init( Bool init_SW, char *f_roots ) { If we are using gridded mode this functionallity will be handled in ST_grid.c */ if(!UseGrid){ printf("Number of layers: %d\n", SW_Site.n_layers); - printf("Number of iterations: %d\n", Globals->runModelIterations); - printf("Number of years: %d\n", Globals->runModelYears); + printf("Number of iterations: %d\n", SuperGlobals.runModelIterations); + printf("Number of years: %d\n", SuperGlobals.runModelYears); } _make_arrays(); diff --git a/sxw_sql.c b/sxw_sql.c index 36a0bb8d..e00273d6 100644 --- a/sxw_sql.c +++ b/sxw_sql.c @@ -154,7 +154,7 @@ void insertInfo() { beginTransaction(); sprintf(sql, "INSERT INTO info (StartYear, Years, Iterations, RGroups, TranspirationLayers, SoilLayers, PlotSize, BVT) VALUES (%d, %d, %d, %d, %d, %d, %f, %f);", - SW_Model.startyr, Globals->runModelYears, Globals->runModelIterations, Globals->grpCount, SXW->NTrLyrs, SXW->NSoLyrs, Globals->plotsize, SXWResources->_bvt); + SW_Model.startyr, SuperGlobals.runModelYears, SuperGlobals.runModelIterations, Globals->grpCount, SXW->NTrLyrs, SXW->NSoLyrs, Globals->plotsize, SXWResources->_bvt); rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); sqlcheck(rc, zErrMsg); endTransaction(); From e95891c7e46c45a76f44596a25e73b4c793b7f1c Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 6 Jun 2019 11:44:20 -0600 Subject: [PATCH 073/167] Updated _set_sd_lyppt to use gridCells (issue #287) _set_sd_lyppt was causing the program to crash in main due to grid_SD and grid_Env not being allocated. I still need to figure out why the old implemetation has a lyppt value for every species, considering it sets them all to the same value, but for now the code can complete through this function. --- ST_grid.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 7f571625..14b0bd14 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -3130,12 +3130,13 @@ static void _do_seed_dispersal(void) /***********************************************************/ static void _set_sd_lyppt(int row, int col) { - int cell = col + ((row - 1) * grid_Cols) - 1; SppIndex s; - ForEachSpecies(s) - if (Species[s]->use_me && Species[s]->use_dispersal) - grid_SD[s][cell].lyppt = grid_Env[cell].ppt; + ForEachSpecies(s){ + if (Species[s]->use_me && Species[s]->use_dispersal){ + gridCells[row][col].mySeedDispersal->lyppt = gridCells[row][col].myEnvironment.ppt; + } + } } From 70da4f453c377e0230e2c8df7ceb7bed8e56da81 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 7 Jun 2019 09:42:23 -0600 Subject: [PATCH 074/167] Removed _set_sd_lyppt entirely (issue #287) After analyzing _set_sd_lyppt I determined that the Species loop is entirely unnecessary. Once I had removed it I realized that the entire function was one line of code. It seemed unintuitive to leave a one line local function in the code so I went ahead and removed the function entirely. I then moved the functionallity into RunGrid where the call used to be. --- ST_grid.c | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 14b0bd14..12649407 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -403,7 +403,6 @@ static float _read_a_float(FILE *f, char *buf, const char *filename, static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); static void _read_seed_dispersal_in(void); static void _do_seed_dispersal(void); -static void _set_sd_lyppt(int row, int col); static void _kill_groups_and_species(void); static int _do_grid_disturbances(int row, int col); static void _read_init_species(void); @@ -591,8 +590,11 @@ void runGrid(void) Globals->currYear = year; - if (year > 1 && UseSeedDispersal) - _set_sd_lyppt(i, j); + /* Seed dispersal needs to take into account last year's precipitation, + so we'll record it before calling Env_Generate(). */ + if (year > 1 && UseSeedDispersal){ + gridCells[i][j].mySeedDispersal->lyppt = gridCells[i][j].myEnvironment.ppt; + } /* The following functions mimic ST_main.c. load_cell(i, j) ensures that all global variables reference the specific cell */ @@ -3127,19 +3129,6 @@ static void _do_seed_dispersal(void) } } -/***********************************************************/ -static void _set_sd_lyppt(int row, int col) -{ - SppIndex s; - - ForEachSpecies(s){ - if (Species[s]->use_me && Species[s]->use_dispersal){ - gridCells[row][col].mySeedDispersal->lyppt = gridCells[row][col].myEnvironment.ppt; - } - } -} - - /* * */ From 2d55c58ad4ff31df5378ea07b19db71f2e701ca9 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 7 Jun 2019 10:01:10 -0600 Subject: [PATCH 075/167] Corrected 1-indexing issues (issue #287) The SMort and GMort loop started at one and ended at grid_Rows and gridCols, which is 1-indexing. The loop needs to be 0-indexed to iterate through cells properly. When creating output .csv files the formula to calculate cell number also expected 1-indexing which I had previously changed to 0-indexing, so I changed it. --- ST_grid.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 12649407..04683308 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -623,16 +623,16 @@ void runGrid(void) } /* end model run for this cell*/ } /* end model run for this row */ - if (UseSeedDispersal) - _do_seed_dispersal(); + //if (UseSeedDispersal) + //_do_seed_dispersal(); unload_cell(); // Reset the global variables }/* end model run for this year*/ // collects the data appropriately for the mort output... (ie. fills the accumulators in ST_stats.c with the values that they need) if (MortFlags.summary){ - for (i = 1; i <= grid_Rows; i++){ - for (j = 1; j <= grid_Cols; j++) + for (i = 0; i < grid_Rows; i++){ + for (j = 0; j < grid_Cols; j++) { load_cell(i, j); stat_Collect_GMort(); @@ -654,7 +654,7 @@ void runGrid(void) for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) { - int cell = j + ((i - 1) * grid_Cols) - 1; + int cell = (j + 1) + (i * grid_Cols) - 1; load_cell(i, j); char fileMort[1024], fileBMass[1024], fileReceivedProb[1024]; From 819bbb0d2199847df4ccac398b8e4fcbab93ebaa Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 7 Jun 2019 10:03:58 -0600 Subject: [PATCH 076/167] Uncommented _do_seed_dispersal I commented out _do_seed_dispersal for testing and forgot to change it back before commiting. This commit uncomments the function. --- ST_grid.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 04683308..eb1be731 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -623,8 +623,8 @@ void runGrid(void) } /* end model run for this cell*/ } /* end model run for this row */ - //if (UseSeedDispersal) - //_do_seed_dispersal(); + if (UseSeedDispersal) + _do_seed_dispersal(); unload_cell(); // Reset the global variables }/* end model run for this year*/ From 4862018376bccedd418a6d647f92b92666a2d188 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 7 Jun 2019 14:04:49 -0600 Subject: [PATCH 077/167] Removed strange values from grid_disturbances.csv grid_disturbances.csv had some strange values, like grazing_frq = 3 and grazingfrq_startyr = 4. I zeroed out all of these values by default. --- .../Grid_Inputs/grid_disturbances.csv | 146 +----------------- 1 file changed, 1 insertion(+), 145 deletions(-) diff --git a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv index dd4364a2..ef15644f 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv @@ -1,145 +1 @@ -cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfrq,extirp,killfreq_startyr,grazing_frq,grazingfrq_startyr -0,0,0,0,3,0,0,0,3,4 -1,0,0,0,3,0,0,0,3,4 -2,0,0,0,3,0,0,0,3,4 -3,0,0,0,3,0,0,0,3,4 -4,0,0,0,3,0,0,0,3,4 -5,0,0,0,3,0,0,0,3,4 -6,0,0,0,3,0,0,0,3,4 -7,0,0,0,3,0,0,0,3,4 -8,0,0,0,3,0,0,0,3,4 -9,0,0,0,3,0,0,0,3,4 -10,0,0,0,3,0,0,0,3,4 -11,0,0,0,3,0,0,0,3,4 -12,0,0,0,3,0,0,0,3,4 -13,0,0,0,3,0,0,0,3,4 -14,0,0,0,3,0,0,0,3,4 -15,0,0,0,3,0,0,0,3,4 -16,0,0,0,3,0,0,0,3,4 -17,0,0,0,0,0,0,0,0,0 -18,0,0,0,0,0,0,0,0,0 -19,0,0,0,0,0,0,0,0,0 -20,0,0,0,0,0,0,0,0,0 -21,0,0,0,0,0,0,0,0,0 -22,0,0,0,0,0,0,0,0,0 -23,0,0,0,0,0,0,0,0,0 -24,0,0,0,0,0,0,0,0,0 -25,0,0,0,0,0,0,0,0,0 -26,0,0,0,0,0,0,0,0,0 -27,0,0,0,0,0,0,0,0,0 -28,0,0,0,0,0,0,0,0,0 -29,0,0,0,0,0,0,0,0,0 -30,0,0,0,0,0,0,0,0,0 -31,0,0,0,0,0,0,0,0,0 -32,0,0,0,0,0,0,0,0,0 -33,0,0,0,0,0,0,0,0,0 -34,0,0,0,0,0,0,0,0,0 -35,0,0,0,0,0,0,0,0,0 -36,0,0,0,0,0,0,0,0,0 -37,0,0,0,0,0,0,0,0,0 -38,0,0,0,0,0,0,0,0,0 -39,0,0,0,0,0,0,0,0,0 -40,0,0,0,0,0,0,0,0,0 -41,0,0,0,0,0,0,0,0,0 -42,0,0,0,0,0,0,0,0,0 -43,0,0,0,0,0,0,0,0,0 -44,0,0,0,0,0,0,0,0,0 -45,0,0,0,0,0,0,0,0,0 -46,0,0,0,0,0,0,0,0,0 -47,0,0,0,0,0,0,0,0,0 -48,0,0,0,0,0,0,0,0,0 -49,0,0,0,0,0,0,0,0,0 -50,0,0,0,0,0,0,0,0,0 -51,0,0,0,0,0,0,0,0,0 -52,0,0,0,0,0,0,0,0,0 -53,0,0,0,0,0,0,0,0,0 -54,0,0,0,0,0,0,0,0,0 -55,0,0,0,0,0,0,0,0,0 -56,0,0,0,0,0,0,0,0,0 -57,0,0,0,0,0,0,0,0,0 -58,0,0,0,0,0,0,0,0,0 -59,0,0,0,0,0,0,0,0,0 -60,0,0,0,0,0,0,0,0,0 -61,0,0,0,0,0,0,0,0,0 -62,0,0,0,0,0,0,0,0,0 -63,0,0,0,0,0,0,0,0,0 -64,0,0,0,0,0,0,0,0,0 -65,0,0,0,0,0,0,0,0,0 -66,0,0,0,0,0,0,0,0,0 -67,0,0,0,0,0,0,0,0,0 -68,0,0,0,0,0,0,0,0,0 -69,0,0,0,0,0,0,0,0,0 -70,0,0,0,0,0,0,0,0,0 -71,0,0,0,0,0,0,0,0,0 -72,0,0,0,0,0,0,0,0,0 -73,0,0,0,0,0,0,0,0,0 -74,0,0,0,0,0,0,0,0,0 -75,0,0,0,0,0,0,0,0,0 -76,0,0,0,0,0,0,0,0,0 -77,0,0,0,0,0,0,0,0,0 -78,0,0,0,0,0,0,0,0,0 -79,0,0,0,0,0,0,0,0,0 -80,0,0,0,0,0,0,0,0,0 -81,0,0,0,0,0,0,0,0,0 -82,0,0,0,0,0,0,0,0,0 -83,0,0,0,0,0,0,0,0,0 -84,0,0,0,0,0,0,0,0,0 -85,0,0,0,0,0,0,0,0,0 -86,0,0,0,0,0,0,0,0,0 -87,0,0,0,0,0,0,0,0,0 -88,0,0,0,0,0,0,0,0,0 -89,0,0,0,0,0,0,0,0,0 -90,0,0,0,0,0,0,0,0,0 -91,0,0,0,0,0,0,0,0,0 -92,0,0,0,0,0,0,0,0,0 -93,0,0,0,0,0,0,0,0,0 -94,0,0,0,0,0,0,0,0,0 -95,0,0,0,0,0,0,0,0,0 -96,0,0,0,0,0,0,0,0,0 -97,0,0,0,0,0,0,0,0,0 -98,0,0,0,0,0,0,0,0,0 -99,0,0,0,0,0,0,0,0,0 -100,0,0,0,0,0,0,0,0,0 -101,0,0,0,0,0,0,0,0,0 -102,0,0,0,0,0,0,0,0,0 -103,0,0,0,0,0,0,0,0,0 -104,0,0,0,0,0,0,0,0,0 -105,0,0,0,0,0,0,0,0,0 -106,0,0,0,0,0,0,0,0,0 -107,0,0,0,0,0,0,0,0,0 -108,0,0,0,0,0,0,0,0,0 -109,0,0,0,0,0,0,0,0,0 -110,0,0,0,0,0,0,0,0,0 -111,0,0,0,0,0,0,0,0,0 -112,0,0,0,0,0,0,0,0,0 -113,0,0,0,0,0,0,0,0,0 -114,0,0,0,0,0,0,0,0,0 -115,0,0,0,0,0,0,0,0,0 -116,0,0,0,0,0,0,0,0,0 -117,0,0,0,0,0,0,0,0,0 -118,0,0,0,0,0,0,0,0,0 -119,0,0,0,0,0,0,0,0,0 -120,0,0,0,0,0,0,0,0,0 -121,0,0,0,0,0,0,0,0,0 -122,0,0,0,0,0,0,0,0,0 -123,0,0,0,0,0,0,0,0,0 -124,0,0,0,0,0,0,0,0,0 -125,0,0,0,0,0,0,0,0,0 -126,0,0,0,0,0,0,0,0,0 -127,0,0,0,0,0,0,0,0,0 -128,0,0,0,0,0,0,0,0,0 -129,0,0,0,0,0,0,0,0,0 -130,0,0,0,0,0,0,0,0,0 -131,0,0,0,0,0,0,0,0,0 -132,0,0,0,0,0,0,0,0,0 -133,0,0,0,0,0,0,0,0,0 -134,0,0,0,0,0,0,0,0,0 -135,0,0,0,0,0,0,0,0,0 -136,0,0,0,0,0,0,0,0,0 -137,0,0,0,0,0,0,0,0,0 -138,0,0,0,0,0,0,0,0,0 -139,0,0,0,0,0,0,0,0,0 -140,0,0,0,0,0,0,0,0,0 -141,0,0,0,0,0,0,0,0,0 -142,0,0,0,0,0,0,0,0,0 -143,0,0,0,0,0,0,0,0,0 +cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfrq,extirp,killfreq_startyr,grazing_frq,grazingfrq_startyr 0,0,0,0,0,0,0,0,0,0 1,0,0,0,0,0,0,0,0,0 2,0,0,0,0,0,0,0,0,0 3,0,0,0,0,0,0,0,0,0 4,0,0,0,0,0,0,0,0,0 5,0,0,0,0,0,0,0,0,0 6,0,0,0,0,0,0,0,0,0 7,0,0,0,0,0,0,0,0,0 8,0,0,0,0,0,0,0,0,0 9,0,0,0,0,0,0,0,0,0 10,0,0,0,0,0,0,0,0,0 11,0,0,0,0,0,0,0,0,0 12,0,0,0,0,0,0,0,0,0 13,0,0,0,0,0,0,0,0,0 14,0,0,0,0,0,0,0,0,0 15,0,0,0,0,0,0,0,0,0 16,0,0,0,0,0,0,0,0,0 17,0,0,0,0,0,0,0,0,0 18,0,0,0,0,0,0,0,0,0 19,0,0,0,0,0,0,0,0,0 20,0,0,0,0,0,0,0,0,0 21,0,0,0,0,0,0,0,0,0 22,0,0,0,0,0,0,0,0,0 23,0,0,0,0,0,0,0,0,0 24,0,0,0,0,0,0,0,0,0 25,0,0,0,0,0,0,0,0,0 26,0,0,0,0,0,0,0,0,0 27,0,0,0,0,0,0,0,0,0 28,0,0,0,0,0,0,0,0,0 29,0,0,0,0,0,0,0,0,0 30,0,0,0,0,0,0,0,0,0 31,0,0,0,0,0,0,0,0,0 32,0,0,0,0,0,0,0,0,0 33,0,0,0,0,0,0,0,0,0 34,0,0,0,0,0,0,0,0,0 35,0,0,0,0,0,0,0,0,0 36,0,0,0,0,0,0,0,0,0 37,0,0,0,0,0,0,0,0,0 38,0,0,0,0,0,0,0,0,0 39,0,0,0,0,0,0,0,0,0 40,0,0,0,0,0,0,0,0,0 41,0,0,0,0,0,0,0,0,0 42,0,0,0,0,0,0,0,0,0 43,0,0,0,0,0,0,0,0,0 44,0,0,0,0,0,0,0,0,0 45,0,0,0,0,0,0,0,0,0 46,0,0,0,0,0,0,0,0,0 47,0,0,0,0,0,0,0,0,0 48,0,0,0,0,0,0,0,0,0 49,0,0,0,0,0,0,0,0,0 50,0,0,0,0,0,0,0,0,0 51,0,0,0,0,0,0,0,0,0 52,0,0,0,0,0,0,0,0,0 53,0,0,0,0,0,0,0,0,0 54,0,0,0,0,0,0,0,0,0 55,0,0,0,0,0,0,0,0,0 56,0,0,0,0,0,0,0,0,0 57,0,0,0,0,0,0,0,0,0 58,0,0,0,0,0,0,0,0,0 59,0,0,0,0,0,0,0,0,0 60,0,0,0,0,0,0,0,0,0 61,0,0,0,0,0,0,0,0,0 62,0,0,0,0,0,0,0,0,0 63,0,0,0,0,0,0,0,0,0 64,0,0,0,0,0,0,0,0,0 65,0,0,0,0,0,0,0,0,0 66,0,0,0,0,0,0,0,0,0 67,0,0,0,0,0,0,0,0,0 68,0,0,0,0,0,0,0,0,0 69,0,0,0,0,0,0,0,0,0 70,0,0,0,0,0,0,0,0,0 71,0,0,0,0,0,0,0,0,0 72,0,0,0,0,0,0,0,0,0 73,0,0,0,0,0,0,0,0,0 74,0,0,0,0,0,0,0,0,0 75,0,0,0,0,0,0,0,0,0 76,0,0,0,0,0,0,0,0,0 77,0,0,0,0,0,0,0,0,0 78,0,0,0,0,0,0,0,0,0 79,0,0,0,0,0,0,0,0,0 80,0,0,0,0,0,0,0,0,0 81,0,0,0,0,0,0,0,0,0 82,0,0,0,0,0,0,0,0,0 83,0,0,0,0,0,0,0,0,0 84,0,0,0,0,0,0,0,0,0 85,0,0,0,0,0,0,0,0,0 86,0,0,0,0,0,0,0,0,0 87,0,0,0,0,0,0,0,0,0 88,0,0,0,0,0,0,0,0,0 89,0,0,0,0,0,0,0,0,0 90,0,0,0,0,0,0,0,0,0 91,0,0,0,0,0,0,0,0,0 92,0,0,0,0,0,0,0,0,0 93,0,0,0,0,0,0,0,0,0 94,0,0,0,0,0,0,0,0,0 95,0,0,0,0,0,0,0,0,0 96,0,0,0,0,0,0,0,0,0 97,0,0,0,0,0,0,0,0,0 98,0,0,0,0,0,0,0,0,0 99,0,0,0,0,0,0,0,0,0 100,0,0,0,0,0,0,0,0,0 101,0,0,0,0,0,0,0,0,0 102,0,0,0,0,0,0,0,0,0 103,0,0,0,0,0,0,0,0,0 104,0,0,0,0,0,0,0,0,0 105,0,0,0,0,0,0,0,0,0 106,0,0,0,0,0,0,0,0,0 107,0,0,0,0,0,0,0,0,0 108,0,0,0,0,0,0,0,0,0 109,0,0,0,0,0,0,0,0,0 110,0,0,0,0,0,0,0,0,0 111,0,0,0,0,0,0,0,0,0 112,0,0,0,0,0,0,0,0,0 113,0,0,0,0,0,0,0,0,0 114,0,0,0,0,0,0,0,0,0 115,0,0,0,0,0,0,0,0,0 116,0,0,0,0,0,0,0,0,0 117,0,0,0,0,0,0,0,0,0 118,0,0,0,0,0,0,0,0,0 119,0,0,0,0,0,0,0,0,0 120,0,0,0,0,0,0,0,0,0 121,0,0,0,0,0,0,0,0,0 122,0,0,0,0,0,0,0,0,0 123,0,0,0,0,0,0,0,0,0 124,0,0,0,0,0,0,0,0,0 125,0,0,0,0,0,0,0,0,0 126,0,0,0,0,0,0,0,0,0 127,0,0,0,0,0,0,0,0,0 128,0,0,0,0,0,0,0,0,0 129,0,0,0,0,0,0,0,0,0 130,0,0,0,0,0,0,0,0,0 131,0,0,0,0,0,0,0,0,0 132,0,0,0,0,0,0,0,0,0 133,0,0,0,0,0,0,0,0,0 134,0,0,0,0,0,0,0,0,0 135,0,0,0,0,0,0,0,0,0 136,0,0,0,0,0,0,0,0,0 137,0,0,0,0,0,0,0,0,0 138,0,0,0,0,0,0,0,0,0 139,0,0,0,0,0,0,0,0,0 140,0,0,0,0,0,0,0,0,0 141,0,0,0,0,0,0,0,0,0 142,0,0,0,0,0,0,0,0,0 143,0,0,0,0,0,0,0,0,0 \ No newline at end of file From 9ad09ecf0f224b1082dc0d5a2cc2b622edba3872 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Sun, 9 Jun 2019 16:48:54 -0400 Subject: [PATCH 078/167] (Issue #309) Convert _do_seed_dispersal to use gridCells --- ST_grid.c | 122 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 76 insertions(+), 46 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index eb1be731..7e5bc388 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2973,23 +2973,37 @@ static void _read_seed_dispersal_in(void) static void _do_seed_dispersal(void) { float biomass, randomN, LYPPT, presentProb, receivedProb; - int i, j, germ, sgerm, year; + int i, j, germ, sgerm, year, row, col; SppIndex s; + CellType *cell; + + // Load the first cell so we can access seedling_estab_prob and currYear, + // which are not specific to each cell. + load_cell(0, 0); if (Globals->currYear == 1 && !sd_Option1a && !sd_Option1b) { //since we have no previous data to go off of, use the current years... for (i = 0; i < grid_Cells; i++) - ForEachSpecies(s) - { - if (!(Species[s]->use_me && Species[s]->use_dispersal)) - continue; - grid_Species[s][i].allow_growth = grid_Species[s][i].sd_sgerm = - 1;// since it's the first year, we have to allow growth... - if (UseDisturbances) - if (1 == grid_Disturb[i].kill_yr) - grid_Species[s][i].allow_growth = 0; - grid_SD[s][i].lyppt = grid_Env[i].ppt; - } + { + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); + + ForEachSpecies(s) + { + if (!(Species[s]->use_me && Species[s]->use_dispersal)) + continue; + Species[s]->allow_growth = Species[s]->sd_sgerm = + 1;// since it's the first year, we have to allow growth... + if (UseDisturbances) + // RGroup[x]->killyr is the same for all x + if (1 == RGroup[0]->killyr) + Species[s]->allow_growth = 0; + cell->mySeedDispersal[s].lyppt = Env->ppt; + } + } } else { @@ -3008,23 +3022,28 @@ static void _do_seed_dispersal(void) for (i = 0; i < grid_Cells; i++) { + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); if (sd_Option1a && Globals->currYear <= sd_NYearsSeedsAvailable) { - grid_SD[s][i].seeds_present = 1; + cell->mySeedDispersal[s].seeds_present = 1; } else if (sd_Option1b && Globals->currYear <= sd_NYearsSeedsAvailable - && grid_initSpecies[i].species_seed_avail[s]) + && cell->mySpeciesInit.species_seed_avail[s]) { - grid_SD[s][i].seeds_present = 1; + cell->mySeedDispersal[s].seeds_present = 1; } - sgerm = (grid_SD[s][i].seeds_present - || grid_SD[s][i].seeds_received) && germ; //refers to whether the species has seeds available from the previous year and conditions are correct for germination this year - grid_Species[s][i].allow_growth = FALSE; - biomass = grid_Species[s][i].relsize - * grid_Species[s][i].mature_biomass; + sgerm = (cell->mySeedDispersal[s].seeds_present + || cell->mySeedDispersal[s].seeds_received) && germ; //refers to whether the species has seeds available from the previous year and conditions are correct for germination this year + Species[s]->allow_growth = FALSE; + biomass = Species[s]->relsize + * Species[s]->mature_biomass; if (UseDisturbances) { @@ -3038,15 +3057,13 @@ static void _do_seed_dispersal(void) //will fail and allow_growth will not become TRUE, then when Globals->currYear=8 this allow_growth= FALSE will carry forward and there will no call // to other functions like Species_Update_Newsize() so new size will not be updated and last year size will carry forward so in final output year 7 and year 8 will // have same output that is not correct. - grid_Species[s][i].allow_growth = TRUE; + Species[s]->allow_growth = TRUE; } } else if (sgerm || GT(biomass, 0.0)) - grid_Species[s][i].allow_growth = TRUE; - grid_Species[s][i].sd_sgerm = sgerm; //based upon whether we have received/produced seeds that germinated - //if(grid_Species[s][i].allow_growth == TRUE && i == 52 && s == 0 && Globals->currIter == 1) - // printf("%s allow_growth:%d year:%d sgerm:%d iter:%d\n", grid_Species[s][i].name, grid_Species[s][i].allow_growth, year, sgerm, Globals->currIter); + Species[s]->allow_growth = TRUE; + Species[s]->sd_sgerm = sgerm; //based upon whether we have received/produced seeds that germinated } } @@ -3063,27 +3080,33 @@ static void _do_seed_dispersal(void) // figure out which species in each cell produced seeds... for (i = 0; i < grid_Cells; i++) { - grid_SD[s][i].seeds_present = grid_SD[s][i].seeds_received = - grid_Species[s][i].received_prob = 0; + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); + + cell->mySeedDispersal[s].seeds_present = cell->mySeedDispersal[s].seeds_received = + Species[s]->received_prob = 0; biomass = 0; //getting the biggest individual in the species... - ForEachIndiv(indiv, &grid_Species[s][i]) - if (indiv->relsize * grid_Species[s][i].mature_biomass + ForEachIndiv(indiv, Species[s]) + if (indiv->relsize * Species[s]->mature_biomass > biomass) biomass = indiv->relsize - * grid_Species[s][i].mature_biomass; + * Species[s]->mature_biomass; if (GE(biomass, - grid_Species[s][i].mature_biomass - * grid_Species[s][i].sd_Param1)) + Species[s]->mature_biomass + * Species[s]->sd_Param1)) { randomN = RandUni(&grid_rng); - LYPPT = grid_SD[s][i].lyppt; - float PPTdry = grid_Species[s][i].sd_PPTdry, PPTwet = - grid_Species[s][i].sd_PPTwet; - float Pmin = grid_Species[s][i].sd_Pmin, Pmax = - grid_Species[s][i].sd_Pmax; + LYPPT = cell->mySeedDispersal[s].lyppt; + float PPTdry = Species[s]->sd_PPTdry, PPTwet = + Species[s]->sd_PPTwet; + float Pmin = Species[s]->sd_Pmin, Pmax = + Species[s]->sd_Pmax; //p3 = Pmin, if LYPPT < PPTdry //p3 = 1 - (1-Pmin) * exp(-d * (LYPPT - PPTdry)) with d = - ln((1 - Pmax)/(1 - Pmin)) / (PPTwet - PPTdry), if PPTdry <= LYPPT <= PPTwet @@ -3102,31 +3125,38 @@ static void _do_seed_dispersal(void) presentProb = Pmax; if (LE(randomN, presentProb)) - grid_SD[s][i].seeds_present = 1; + cell->mySeedDispersal[s].seeds_present = 1; } - //if(i == 0) printf("cell: %d lyppt: %f\n", i, grid_SD[i].lyppt); } // figure out which species in each cell received seeds... for (i = 0; i < grid_Cells; i++) { - if (grid_SD[s][i].seeds_present) + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); + + if (cell->mySeedDispersal[s].seeds_present) continue; receivedProb = 0; - for (j = 0; j < grid_SD[s][i].size; j++) - if (grid_SD[s][grid_SD[s][i].cells[j]].seeds_present) - receivedProb += grid_SD[s][i].prob[j]; + for (j = 0; j < cell->mySeedDispersal[s].size; j++) + if (cell->mySeedDispersal[cell->mySeedDispersal[s].cells[j]].seeds_present) + receivedProb += cell->mySeedDispersal[s].prob[j]; randomN = RandUni(&grid_rng); if (LE(randomN, receivedProb) && !ZRO(receivedProb)) - grid_SD[s][i].seeds_received = 1; + cell->mySeedDispersal[s].seeds_received = 1; else - grid_SD[s][i].seeds_received = 0; + cell->mySeedDispersal[s].seeds_received = 0; - grid_Species[s][i].received_prob = receivedProb; + Species[s]->received_prob = receivedProb; } } + + unload_cell(); } /* From 9a2a5f55e3cc3963be727a6075c1057069b027bd Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Sun, 9 Jun 2019 18:44:42 -0400 Subject: [PATCH 079/167] (Issue #309) Remove H and VT from grid_seed_dispersal.in --- testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in | 2 -- 1 file changed, 2 deletions(-) diff --git a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in b/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in index 3bcbe2bb..74646332 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in @@ -1,9 +1,7 @@ # Seed dispersal setup for STEPWAT grid version - DLM 07-29-13. This file contains constants that are used in seed dispersal. The rest of the seed dispersal inputs are set up on a species basis in the species input file. #CONSTANTS from the max distance function: MAXD = (H * VW) / VT. MAXD refers to the maximum distance that a seed can be dispersed to. If you're MAXD ends up being really small, then you can get kinda weird results, so be careful. -#30.0 # H - the average release height of the inflorescences (30 cm in the paper) 500.0 # VW - the mean horizontal wind speed (500 cm/sec in the paper) -#100.0 # VT - the average sinking velocity of the seeds (100 cm/sec in the paper) #SEED DISPERSAL OUTPUTS 1 # output seed dispersal (ie. the total probability that a cell received seeds for each cell for each year for each species)? 1 means yes, 0 means no From f454ce1c9c65556870cdb66c183e1d0ec83fc812 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 10 Jun 2019 13:59:02 -0600 Subject: [PATCH 080/167] Resolved errors introduced while merging pull request #320 --- ST_grid.c | 2 +- ST_main.c | 4 ++-- ST_sql.c | 4 ++-- sxw.c | 4 ++-- sxw_sql.c | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 50eef325..21876e3e 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -3042,7 +3042,7 @@ static void _do_seed_dispersal(void) sgerm = (cell->mySeedDispersal[s].seeds_present || cell->mySeedDispersal[s].seeds_received) && germ; //refers to whether the species has seeds available from the previous year and conditions are correct for germination this year Species[s]->allow_growth = FALSE; - biomass = Species[s]->relsize + biomass = getSpeciesRelsize(s) * Species[s]->mature_biomass; if (UseDisturbances) diff --git a/ST_main.c b/ST_main.c index fae5fa3e..eb5b7e53 100644 --- a/ST_main.c +++ b/ST_main.c @@ -637,7 +637,7 @@ void check_sizes(const char *chkpt) { if (LT(diff, fabs(spsize - getSpeciesRelsize(sp)))) { LogError(stdout, LOGWARN, "%s (%d:%d): SP: \"%s\" size error: " "SP=%.7f, ndv=%.7f", - chkpt, Globals.currIter, Globals.currYear, + chkpt, Globals->currIter, Globals->currYear, Species[sp]->name, getSpeciesRelsize(sp), spsize); } } @@ -645,7 +645,7 @@ void check_sizes(const char *chkpt) { if (LT(diff, fabs(rgsize - getRGroupRelsize(rg)))) { LogError(stdout, LOGWARN, "%s (%d:%d): RG \"%s\" size error: " "RG=%.7f, ndv=%.7f", - chkpt, Globals.currIter, Globals.currYear, + chkpt, Globals->currIter, Globals->currYear, RGroup[rg]->name, getRGroupRelsize(rg), rgsize); } } diff --git a/ST_sql.c b/ST_sql.c index 4d72c2a6..48c0dcbb 100644 --- a/ST_sql.c +++ b/ST_sql.c @@ -179,7 +179,7 @@ static void insertSpeciesYearInfoRow(int Year, int Iteration, int SpeciesID, int void insertSpecieYearInfo(SppIndex s) { SpeciesType *sp = Species[s]; - insertSpeciesYearInfoRow(Globals->currYear, Globals->currIter, s+1, sp->est_count, sp->estabs, sp->relsize, sp->extragrowth, sp->received_prob, sp->allow_growth, sp->sd_sgerm); + insertSpeciesYearInfoRow(Globals->currYear, Globals->currIter, s+1, sp->est_count, sp->estabs, getSpeciesRelsize(s), sp->extragrowth, sp->received_prob, sp->allow_growth, sp->sd_sgerm); } static void insertRGroupYearInfoRow(int Year, int Iteration, int RGroupID, int Estabs, int KillYr, int YrsNegPR, float mmExtraRes, float ResRequired, float ResAvail, float ResExtra, float PR, float RelSize, int EstSppCount, int Extirpated, int RegenOk) { @@ -206,7 +206,7 @@ static void insertRGroupYearInfoRow(int Year, int Iteration, int RGroupID, int E void insertRGroupYearInfo(GrpIndex g) { GroupType *rg = RGroup[g]; - insertRGroupYearInfoRow(Globals->currYear, Globals->currIter, g+1, rg->estabs, rg->killyr, rg->yrs_neg_pr, rg->mm_extra_res, rg->res_required, rg->res_avail, rg->res_extra, rg->pr, rg->relsize, rg->est_count, rg->extirpated, rg->regen_ok); + insertRGroupYearInfoRow(Globals->currYear, Globals->currIter, g+1, rg->estabs, rg->killyr, rg->yrs_neg_pr, rg->mm_extra_res, rg->res_required, rg->res_avail, rg->res_extra, rg->pr, getRGroupRelsize(g), rg->est_count, rg->extirpated, rg->regen_ok); } static void insertRgroups(void) { diff --git a/sxw.c b/sxw.c index 5b29e291..9407c988 100644 --- a/sxw.c +++ b/sxw.c @@ -963,8 +963,8 @@ void _print_debuginfo(void) { ForEachGroup(r) { sum1 += getRGroupRelsize(r); sum2 += RGroup[r]->pr; - sum3 += _resource_cur[r]; - fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, getRGroupRelsize(r), RGroup[r]->pr, _resource_cur[r]/_bvt, _resource_cur[r]); + sum3 += SXWResources->_resource_cur[r]; + fprintf(f, "%s\t%.4f\t%.4f\t%.4f\t\t%.4f\n", RGroup[r]->name, getRGroupRelsize(r), RGroup[r]->pr, SXWResources->_resource_cur[r]/_bvt, SXWResources->_resource_cur[r]); } fprintf(f, "----- \t-------\t-----\t-----\t\t-----\n"); fprintf(f, "%s\t\t%.4f\t%.4f\t%.4f\t\t%.4f\n", "Total", sum1, sum2, sum3/SXWResources->_bvt, sum3); diff --git a/sxw_sql.c b/sxw_sql.c index 7f8bf9b3..e1dc5b43 100644 --- a/sxw_sql.c +++ b/sxw_sql.c @@ -382,7 +382,7 @@ void insertRgroupInfo(RealF * _resource_cur) { beginTransaction(); ForEachGroup(r) { - insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),getRGroupRelsize(r), RGroup[r]->pr, _resource_cur[r]/_bvt, _resource_cur[r]); + insertSXWoutputRgroupRow(Year, Iteration, r+1, RGroup_GetBiomass(r),getRGroupRelsize(r), RGroup[r]->pr, SXWResources->_resource_cur[r]/SXWResources->_bvt, _resource_cur[r]); } endTransaction(); } From d262025e85844c28dcc94e08736bb17e48906ccc Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Wed, 12 Jun 2019 11:28:39 -0400 Subject: [PATCH 081/167] (Issue #309) Forgot to replace grid_Disturb[i] with RGroup[0] --- ST_grid.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 21876e3e..e7ad657a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -3047,13 +3047,13 @@ static void _do_seed_dispersal(void) if (UseDisturbances) { - if ((sgerm || year < grid_Disturb[i].kill_yr - || grid_Disturb[i].kill_yr <= 0 || GT(biomass, 0.0)) - /*&& (year != grid_Disturb[i].kill_yr)*/) + if ((sgerm || year < RGroup[0]->killyr + || RGroup[0]->killyr <= 0 || GT(biomass, 0.0)) + /*&& (year != RGroup[0].killyr)*/) { //commented above one condition as it was causing a bug there, next year of killing year will make //allow_growth flag to false as year = Globals->currYear - 1 , so for example if killing year= 6 and Globals->currYear=7 then here - // year variable will be 7-1 =6 that is equal to killing year 6, so this condition (year != grid_Disturb[i].kill_yr) + // year variable will be 7-1 =6 that is equal to killing year 6, so this condition (year != RGroup[0].killyr) //will fail and allow_growth will not become TRUE, then when Globals.currYear=8 this allow_growth= FALSE will carry forward and there will no call // to other functions. Last year size will carry forward so in final output year 7 and year 8 will // have same output that is not correct. From d8aa20e7d4ab0531df0b6615411f545b2a2b99cd Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 12 Jun 2019 11:04:27 -0600 Subject: [PATCH 082/167] Stat output fixed to point of completion (issue #310) gridded mode now ouputs the correct number of files with correct names. The actual values are still incorrect, but we have the code completing through outputs. * changed stat_Output_AllCellAvgBmass to Output_AllCellAvgBmass and defined the function in ST_grid.c. Since we need to be able to iterate across cells I moved this functionallity into ST_grid. I also prototypes the function as a proof of concept, but it still needs to be fully written. * Changed call to stat_Output_AllBmassAvg() to stat_Output_AllBmass(). I'm not sure why we called stat_Output_AllBmassAvg when stat_Output_AllBmass is the function we want (and the function main calls). --- ST_grid.c | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index e7ad657a..0284d6ed 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -335,7 +335,7 @@ void stat_Output_AllMorts(void); void stat_Output_AllBmass(void); //Adding functions for creating grid cells avg values output file void stat_Output_AllBmassAvg(void); -void stat_Output_AllCellAvgBmass(const char * filename); +void Output_AllCellAvgBmass(const char * filename); void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool makeHeader); void stat_Load_Accumulators(int cell, int year); @@ -667,7 +667,7 @@ void runGrid(void) if (MortFlags.summary) stat_Output_AllMorts(); if (BmassFlags.summary) - stat_Output_AllBmassAvg(); + stat_Output_AllBmass(); if (UseSeedDispersal && sd_DoOutput) stat_Output_Seed_Dispersal(fileReceivedProb, sd_Sep, sd_MakeHeader); @@ -678,8 +678,9 @@ void runGrid(void) //Here creating grid cells avg values output file char fileBMassCellAvg[1024]; sprintf(fileBMassCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_BMASSCELLAVG]); - if (BmassFlags.summary) - stat_Output_AllCellAvgBmass(fileBMassCellAvg); + if (BmassFlags.summary){ + Output_AllCellAvgBmass(fileBMassCellAvg); + } _free_grid_memory(); // free our allocated memory since we do not need it anymore _deallocate_memory(); // sxw memory. @@ -3532,4 +3533,27 @@ static void _read_grid_setup(void) UseSeedDispersal = itob(j); CloseFile(&f); +} + +void Output_AllCellAvgBmass(const char * filename){ + int i, j, year; + FILE* file; + file = fopen(filename, "w"); + float ppt, temp; + + for(year = 0; year < SuperGlobals.runModelYears; ++year){ + ppt = 0; + temp = 0; + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + ppt += gridCells[i][j]._Ppt->s[year].ave; + temp += gridCells[i][j]._Temp->s[year].ave; + } + } + ppt /= grid_Cells; + temp /= grid_Cells; + fprintf(file, "%f,%f\n", ppt, temp); + } + + fclose(file); } \ No newline at end of file From 02e1668e77a074b76fe2108cc667070b663a7979 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 12 Jun 2019 14:38:55 -0600 Subject: [PATCH 083/167] Continued work on all cell average function Output_AllCellAvgBmass now outputs the average bmasses and all additional requested information, except for standard deviation. I have a feeling standard deviation will be a little harder, so I am planning on spending a little more time on it. For now, the standard deviation columns are filled with "TODO". Since this function is inside ST_grid.c, I had to use _make_header_with_std from ST_stats.c. I therefore made the function non-static. --- ST_grid.c | 161 +++++++++++++++++++++++++++++++++++++++++++++++++---- ST_stats.c | 4 +- 2 files changed, 152 insertions(+), 13 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 0284d6ed..0804af99 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -345,6 +345,7 @@ void stat_Init_Accumulators(void); void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); +void _make_header_with_std( char *buf); //functions from sxw.c //void free_sxw_memory( void ); @@ -3536,24 +3537,162 @@ static void _read_grid_setup(void) } void Output_AllCellAvgBmass(const char * filename){ - int i, j, year; + int i, j, year; //for iterating + GrpIndex rg; //for iterating + SppIndex sp; //for iterating + + /* One accumulator for every accumulator in ST_stats.c */ + float ppt, temp, dist, wildfire, grp[SuperGlobals.max_rgroups], gsize[SuperGlobals.max_rgroups], + gpr[SuperGlobals.max_rgroups], prescribedfire[SuperGlobals.max_rgroups], + spp[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups], + indv[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups]; + + char buf[2048], tbuf[2048]; // Two buffers: one for accumulating and one for formatting. + char sep = BmassFlags.sep; // Separator specified in inputs + FILE* file; file = fopen(filename, "w"); - float ppt, temp; + + buf[0]='\0'; + + load_cell(0, 0); + + if(BmassFlags.header){ + _make_header_with_std(buf); + fprintf(file, "%s", buf); + } for(year = 0; year < SuperGlobals.runModelYears; ++year){ - ppt = 0; + *buf = '\0'; //Initialize buffer as empty string + + /* -------- Initialize all accumulators to 0 ------- */ + ppt = 0; temp = 0; - for(i = 0; i < grid_Rows; ++i){ - for(j = 0; j < grid_Cols; ++j){ - ppt += gridCells[i][j]._Ppt->s[year].ave; - temp += gridCells[i][j]._Temp->s[year].ave; - } + dist = 0; + wildfire = 0; + ForEachGroup(rg){ + grp[rg] = 0; + gsize[rg] = 0; + grp[rg] = 0; + prescribedfire[rg] = 0; + } + ForEachSpecies(sp){ + spp[sp] = 0; + indv[sp] = 0; } + /* ------ End Initialize all accumulators to 0 ------ */ + + for(i = 0; i < grid_Rows; ++i){ // For each row + for(j = 0; j < grid_Cols; ++j){ // For each column + /* ------------- Accumulate requested output ----------------- */ + if(BmassFlags.ppt) ppt += gridCells[i][j]._Ppt->s[year].ave; + if(BmassFlags.tmp) temp += gridCells[i][j]._Temp->s[year].ave; + if(BmassFlags.dist) dist += gridCells[i][j]._Dist->s[year].nobs; + if(BmassFlags.grpb) { + if(BmassFlags.wildfire){ + wildfire + gridCells[i][j]._Gwf->wildfire[year]; + } + ForEachGroup(rg){ + grp[rg] += gridCells[i][j]._Grp[rg].s[year].ave; + if(BmassFlags.size){ + gsize[rg] += gridCells[i][j]._Gsize[rg].s[year].ave; + } + if(BmassFlags.pr){ + gpr[rg] += gridCells[i][j]._Gpr[rg].s[year].ave; + } + if(BmassFlags.prescribedfire){ + prescribedfire[rg] += gridCells[i][j]._Gwf->prescribedFire[rg][year]; + } + } // End ForEachGroup + } // End grpb + if(BmassFlags.sppb){ + ForEachSpecies(sp){ + spp[sp] += gridCells[i][j]._Spp[sp].s[year].ave; + if(BmassFlags.indv){ + indv[sp] += gridCells[i][j]._Indv[sp].s[year].ave; + } + } // End ForEachSpecies + } // End sppb + /* ------------ End Accumulate requested output --------------- */ + } // End for each column + } // End for each row + + /* ---------------- Average all accumulators ---------------- */ ppt /= grid_Cells; temp /= grid_Cells; - fprintf(file, "%f,%f\n", ppt, temp); - } + dist /= grid_Cells; + wildfire /= grid_Cells; + ForEachGroup(rg){ + grp[rg] /= grid_Cells; + gsize[rg] /= grid_Cells; + grp[rg] /= grid_Cells; + prescribedfire[rg] /= grid_Cells; + } + ForEachSpecies(sp){ + spp[sp] /= grid_Cells; + indv[sp] /= grid_Cells; + } + /* --------------- End average all accumulators --------------- */ + + /* ----------------- Generate output string ------------------- */ + /* buf will hold the entire string. tbuf will format the output */ + if(BmassFlags.yr){ + sprintf(buf,"%d%c", year+1, sep); + } + if(BmassFlags.dist){ + sprintf(tbuf, "%ld%c", dist, sep); + strcat(buf, tbuf); + } + if(BmassFlags.ppt){ + sprintf(tbuf, "%f%cTODO%c", ppt, sep, sep); + strcat(buf, tbuf); + } + if (BmassFlags.pclass) { + sprintf(tbuf, "\"NA\"%c", sep); + strcat(buf, tbuf); + } + if(BmassFlags.tmp){ + sprintf(tbuf, "%f%cTODO%c", temp, sep, sep); + strcat(buf, tbuf); + } + if(BmassFlags.grpb){ + if(BmassFlags.wildfire){ + sprintf(tbuf, "%f%c", wildfire, sep); + strcat(buf, tbuf); + } + ForEachGroup(rg){ + sprintf(tbuf, "%f%cTODO%c", grp[rg], sep, sep); + strcat(buf, tbuf); + + if(BmassFlags.size){ + sprintf(tbuf, "%f%c", gsize[rg], sep); + strcat(buf, tbuf); + } + if(BmassFlags.pr){ + sprintf(tbuf, "%f%cTODO%c", gpr[rg], sep, sep); + strcat(buf, tbuf); + } + if(BmassFlags.prescribedfire){ + sprintf(tbuf, "%f%c", prescribedfire[rg], sep); + strcat(buf, tbuf); + } + } + } + if(BmassFlags.sppb){ + ForEachSpecies(sp){ + sprintf(tbuf, "%f%c", spp[sp], sep); + strcat(buf, tbuf); + if(BmassFlags.indv){ + sprintf(tbuf, "%f%c", indv[sp], sep); + strcat(buf, tbuf); + } + } + } + /* --------------- End generate output string ---------------- */ - fclose(file); + fprintf(file, "%s\n", buf); // Finally, print this line + } // End for each year + + unload_cell(); + fclose(file); // Close the file } \ No newline at end of file diff --git a/ST_stats.c b/ST_stats.c index fa7a8622..869ffed2 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -90,7 +90,7 @@ static RealF _get_gridcell_avg( struct accumulators_grid_cell_st *p); static int _get_gridcell_sum( struct accumulators_grid_cell_st *p); static RealF _get_gridcell_std( struct accumulators_grid_cell_st *p); static void _make_header( char *buf); -static void _make_header_with_std( char *buf); +void _make_header_with_std( char *buf); /* I'm making this a macro because it gets called a lot, but * note that the syntax checker is obviated, so make sure @@ -1408,7 +1408,7 @@ static RealF _get_gridcell_std(struct accumulators_grid_cell_st *p) /***********************************************************/ -static void _make_header_with_std( char *buf) { +void _make_header_with_std( char *buf) { char **fields; char tbuf[80]; From 2deb521d450ce6328368246ceba7f9c75fac95e1 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 12 Jun 2019 14:57:52 -0600 Subject: [PATCH 084/167] partially overhauled _free_grid_memory I removed all referenced to depreciated structs and arrays, then freed up most of the momory. I still need to free SXW, RGroup, Species and the accumulators, so do not attempt to run this branch on a supercomputer yet. --- ST_grid.c | 90 ++++++++----------------------------------------------- 1 file changed, 12 insertions(+), 78 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 0804af99..41f6b34c 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -326,6 +326,7 @@ void parm_free_memory(void); //from ST_main.c void Plot_Initialize(void); +void deallocate_Globals(void); //functions from ST_stats.c void stat_Collect(Int year); @@ -684,7 +685,6 @@ void runGrid(void) } _free_grid_memory(); // free our allocated memory since we do not need it anymore - _deallocate_memory(); // sxw memory. } /* "Spinup" the model by running for SuperGlobals.runModelYears without seed dispersal or statistics outputs. */ @@ -1638,88 +1638,22 @@ static void _free_spinup_globals(void) static void _free_grid_memory(void) { //frees all the memory allocated in this file ST_Grid.c (most of it is dynamically allocated in _init_grid_globals() & _load_grid_globals() functions) - - int i; + int i, j; GrpIndex c; SppIndex s; - _free_grid_globals(); - if (sd_Option2a || sd_Option2b) - _free_spinup_memory(); - - ForEachSpecies(s) - if (Species[s]->use_me) - Mem_Free(grid_Species[s]); - ForEachGroup(c) - if (RGroup[c]->use_me) - Mem_Free(grid_RGroup[c]); - - Mem_Free(grid_Succulent); - Mem_Free(grid_Env); - Mem_Free(grid_Plot); - Mem_Free(grid_Globals); - - Mem_Free(grid_SXW); - Mem_Free(grid_SW_Soilwat); - Mem_Free(grid_SW_Site); - Mem_Free(grid_SW_VegProd); - - if (UseSoils) - { - free_all_sxw_memory(); - Mem_Free(grid_SXW_ptrs); - for (i = 0; i < grid_Cells; i++) - Mem_Free(grid_Soils[i].lyr); - Mem_Free(grid_Soils); - } - if (UseDisturbances) - Mem_Free(grid_Disturb); - if (UseSeedDispersal) - { - ForEachSpecies(s) - if (Species[s]->use_me && Species[s]->use_dispersal) - { - for (i = 0; i < grid_Cells; i++) - { - Mem_Free(grid_SD[s][i].cells); - Mem_Free(grid_SD[s][i].prob); - grid_SD[s][i].size = 0; - } - Mem_Free(grid_SD[s]); - } - - for (i = 0; i < grid_Cells; i++) - Mem_Free(grid_initSpecies[i].species_seed_avail); - Mem_Free(grid_initSpecies); + /* Free memory that we have allocated in ST_grid.c */ + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + Mem_Free(gridCells[i][j].mySpeciesInit.species_seed_avail); + Mem_Free(gridCells[i][j].someKillage); + Mem_Free(gridCells[i][j].mySoils.lyr); + } } - - stat_Free_Accumulators(); //free our memory we allocated for all the accumulators now that they're unnecessary to have - - for (i = 0; i < N_GRID_DIRECTORIES; i++) //frees the strings allocated in _init_grid_files() - Mem_Free(grid_directories[i]); - for (i = 0; i < N_GRID_FILES; i++) - Mem_Free(grid_files[i]); - - // freeing random memory that other parts of steppe/soilwat allocate... this isn't quite everything but it's a good start - parm_free_memory(); //frees memory allocated in ST_params.c - - ForEachSpecies(s) - { - if (!Species[s]->use_me) - continue; - _free_head(Species[s]->IndvHead); - Mem_Free(Species[s]->kills); - Mem_Free(Species[s]->seedprod); + for(i = 0; i < grid_Rows; ++i){ + Mem_Free(gridCells[i]); } - - ForEachGroup(c) - if (RGroup[c]->use_me) - Mem_Free(RGroup[c]->kills); - - for (i = 0; i < SW_Site.n_layers + SW_Site.deepdrain; i++) - Mem_Free(SW_Site.lyr[i]); - Mem_Free(SW_Site.lyr); - + Mem_Free(gridCells); } /***********************************************************/ From d9115ed899812b25b7f26d821e58f512df2afd76 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 14 Jun 2019 10:16:32 -0600 Subject: [PATCH 085/167] (issue #310) corrected misstyped assignment I accidentally wrote + instead of +=. --- ST_grid.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index 41f6b34c..f6e7536b 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -3524,7 +3524,7 @@ void Output_AllCellAvgBmass(const char * filename){ if(BmassFlags.dist) dist += gridCells[i][j]._Dist->s[year].nobs; if(BmassFlags.grpb) { if(BmassFlags.wildfire){ - wildfire + gridCells[i][j]._Gwf->wildfire[year]; + wildfire += gridCells[i][j]._Gwf->wildfire[year]; } ForEachGroup(rg){ grp[rg] += gridCells[i][j]._Grp[rg].s[year].ave; From be912518e3fc3ed5ce09916f4257ebf129852c84 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 17 Jun 2019 11:04:53 -0600 Subject: [PATCH 086/167] Compressed all global deallocation into one function deallocate_Globals now handles all global pointers. I added RGroup and Species deallocation to complete the function. (issue #322) --- ST_main.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/ST_main.c b/ST_main.c index eb5b7e53..bf7b6399 100644 --- a/ST_main.c +++ b/ST_main.c @@ -423,12 +423,48 @@ void allocate_Globals(void){ _SomeKillage = (Bool*) Mem_Calloc(1, sizeof(Bool), "allocate_Globals: _SomeKillage"); } +/* Deallocates the global variables */ void deallocate_Globals(void){ + GrpIndex rg; + SppIndex sp; Mem_Free(Env); Mem_Free(Succulent); Mem_Free(Globals); Mem_Free(Plot); Mem_Free(_SomeKillage); + + /* Free Species */ + ForEachSpecies(sp){ + /* Start by freeing any pointers in the Species struct */ + Mem_Free(Species[sp]->kills); + Mem_Free(Species[sp]->seedprod); + Mem_Free(Species[sp]->name); + IndivType *indv = Species[sp]->IndvHead, *next; + /* Next free the linked list of individuals */ + while(indv){ + next = indv->Next; + Mem_Free(indv); + indv = next; + } + Mem_Free(next); + Mem_Free(indv); + /* Finally free the actual species */ + Mem_Free(Species[sp]); + } + /* Then free the entire array */ + Mem_Free(Species); + + /* Free RGroup */ + ForEachGroup(rg){ + /* Free all pointers in the RGroup struct */ + Mem_Free(RGroup[rg]->est_spp); + Mem_Free(RGroup[rg]->kills); + Mem_Free(RGroup[rg]->name); + Mem_Free(RGroup[rg]->species); + Mem_Free(RGroup[rg]); + } + /* Then free the entire array */ + Mem_Free(RGroup); } /**************************************************************/ From 010e6781623d5c02003b6ff986c0ccecef322f95 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 17 Jun 2019 14:06:32 -0600 Subject: [PATCH 087/167] Sealed up memory leaks This commit overhauls deallocation in both gridded and non-gridded modes. In ST_main.c * Added a boolean parameter to deallocate_Globals. * Wrapped some of the variables in an if statement dependent on the parameter. I did this because in gridded mode these pointers do not allocate any memory, but in non-gridded mode they do. In sxw.c: * Removed free_sxw_memory, _deallocate_memory, and load_sxw_memory * I removed free_sxw_memory because it overcomplicated the code. It's only call was in free_all_sxw_memory, so I combined them to make the code more readable. * I removed load_sxw_memory because it is depreciated, and referenced free_sxw_memory which I had already deleted. * I removed _deallocate_memory because it was redundant and unused. * In free_all_sxw_memory I went through each struct and deallocated every pointer to ensure no memory is leaked. * I did NOT delete SXW->f_files because it is never actually allocated memory. The previous call to Mem_Free(SXW->f_files.in) worked because it pointed to another variable which is allocated, but calling the function multiple times in gridded mode revealed that it is unnecessary. In ST_grid.c: * Added a few additional pointers to _free_grid_memory. * Added a loop which loads in a cell, then calls the non-gridded mode deallocation function. This reduces code reuse. --- ST_grid.c | 12 ++++++++- ST_main.c | 19 ++++++++------ sxw.c | 76 ++++++++++++++----------------------------------------- 3 files changed, 41 insertions(+), 66 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index f6e7536b..1cb57e1f 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -326,7 +326,7 @@ void parm_free_memory(void); //from ST_main.c void Plot_Initialize(void); -void deallocate_Globals(void); +void deallocate_Globals(Bool isGriddedMode); //functions from ST_stats.c void stat_Collect(Int year); @@ -1646,10 +1646,20 @@ static void _free_grid_memory(void) for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ Mem_Free(gridCells[i][j].mySpeciesInit.species_seed_avail); + Mem_Free(gridCells[i][j].mySeedDispersal->prob); + Mem_Free(gridCells[i][j].mySeedDispersal); Mem_Free(gridCells[i][j].someKillage); Mem_Free(gridCells[i][j].mySoils.lyr); + + /* Use deallocate_Globals from ST_main to deallocate global variables, + and free_all_sxw_memory from sxw to deallocate SXW variables. */ + load_cell(i,j); + deallocate_Globals(TRUE); + free_all_sxw_memory(); + unload_cell(); } } + for(i = 0; i < grid_Rows; ++i){ Mem_Free(gridCells[i]); } diff --git a/ST_main.c b/ST_main.c index bf7b6399..3b953f09 100644 --- a/ST_main.c +++ b/ST_main.c @@ -92,7 +92,7 @@ extern Bool* _SomeKillage; /***********************************************************/ void Plot_Initialize( void); void allocate_Globals(void); -void deallocate_Globals(void); +void deallocate_Globals(Bool isGriddedMode); static void usage(void) { char *s ="STEPPE plant community dynamics (SGS-LTER Jan-04).\n" @@ -329,7 +329,7 @@ int main(int argc, char **argv) { SW_CTL_clear_model(TRUE); // de-allocate all memory free_all_sxw_memory(); - deallocate_Globals(); + deallocate_Globals(FALSE); printf("\nend program\n"); fprintf(progfp, "\n"); @@ -424,15 +424,18 @@ void allocate_Globals(void){ } /* Deallocates the global variables */ -void deallocate_Globals(void){ +void deallocate_Globals(Bool isGriddedMode){ GrpIndex rg; SppIndex sp; - Mem_Free(Env); - Mem_Free(Succulent); - Mem_Free(Globals); - Mem_Free(Plot); - Mem_Free(_SomeKillage); + if(!isGriddedMode){ + Mem_Free(Env); + Mem_Free(Succulent); + Mem_Free(Globals); + Mem_Free(Plot); + Mem_Free(_SomeKillage); + } + /* Free Species */ ForEachSpecies(sp){ /* Start by freeing any pointers in the Species struct */ diff --git a/sxw.c b/sxw.c index 9407c988..5167001d 100644 --- a/sxw.c +++ b/sxw.c @@ -136,11 +136,7 @@ static void _make_swc_array(void); static void SXW_SW_Setup_Echo(void); static void SXW_Reinit(char* SOILWAT_file); -//these last four functions are to be used in ST_grid.c -void load_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ); void save_sxw_memory( RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ); -void free_sxw_memory( void ); -void _deallocate_memory(void); SXW_t* getSXW(void); SXW_resourceType* getSXWResources(void); transp_t* getTranspWindow(void); @@ -449,18 +445,6 @@ transp_t* getTranspWindow(void){ return transp_window; } -/* Deallocate any sxw local pointers. When running the non-gridded mode - * there is no need to call this since we only have one transp_window variable */ -void _deallocate_memory(void){ - Mem_Free(transp_window->ratios); - Mem_Free(transp_window->transp); - Mem_Free(transp_window->SoS_array); - Mem_Free(transp_window); - - Mem_Free(SXW); - Mem_Free(SXWResources); -} - /* Shallow copy variables into the local sxw variables. */ void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window){ SXW = newSXW; @@ -1139,26 +1123,13 @@ int getNTranspLayers(int veg_prod_type) { void free_all_sxw_memory( void ) { int k; - free_sxw_memory(); - Mem_Free(SXW->f_files); - Mem_Free(SXW->f_roots); - Mem_Free(SXW->f_phen); - Mem_Free(SXW->f_bvt); - Mem_Free(SXW->f_prod); - Mem_Free(SXW->f_watin); - - Mem_Free(SXW->transpTotal); - ForEachVegType(k) { - Mem_Free(SXW->transpVeg[k]); - } - - //Mem_Free(SXW->sum_dSWA_repartitioned); // required for `_SWA_contribution_by_group` - - Mem_Free(SXW->swc); -} + /* Free transp_window */ + Mem_Free(transp_window->ratios); + Mem_Free(transp_window->transp); + Mem_Free(transp_window->SoS_array); + Mem_Free(transp_window); -/***********************************************************/ -void free_sxw_memory( void ) { + /* Free SXWResources memory */ Mem_Free(SXWResources->_roots_max); Mem_Free(SXWResources->_rootsXphen); Mem_Free(SXWResources->_roots_active); @@ -1167,29 +1138,20 @@ void free_sxw_memory( void ) { Mem_Free(SXWResources->_phen); Mem_Free(SXWResources->_prod_bmass); Mem_Free(SXWResources->_prod_pctlive); -} + Mem_Free(SXWResources); -/***********************************************************/ -void load_sxw_memory( RealD* grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, RealD* grid_prod_pctlive ) { - //load memory from the grid - free_sxw_memory(); - SXWResources->_roots_max = Mem_Calloc(SXW->NGrps * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources->_rootsXphen = Mem_Calloc(SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources->_roots_active = Mem_Calloc(SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources->_roots_active_rel = Mem_Calloc(SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources->_roots_active_sum = Mem_Calloc(4 * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), "load_sxw_memory()"); - SXWResources->_phen = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - SXWResources->_prod_bmass = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - SXWResources->_prod_pctlive = Mem_Calloc(SXW->NGrps * MAX_MONTHS, sizeof(RealD), "load_sxw_memory()"); - - memcpy(SXWResources->_roots_max, grid_roots_max, SXW->NGrps * SXW->NTrLyrs * sizeof(RealD)); - memcpy(SXWResources->_rootsXphen, grid_rootsXphen, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); - memcpy(SXWResources->_roots_active, grid_roots_active, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); - memcpy(SXWResources->_roots_active_rel, grid_roots_active_rel, SXW->NGrps * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); - memcpy(SXWResources->_roots_active_sum, grid_roots_active_sum, 4 * SXW->NPds * SXW->NTrLyrs * sizeof(RealD)); - memcpy(SXWResources->_phen, grid_phen, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(SXWResources->_prod_bmass, grid_prod_bmass, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); - memcpy(SXWResources->_prod_pctlive, grid_prod_pctlive, SXW->NGrps * MAX_MONTHS * sizeof(RealD)); + /* Free SXW */ + Mem_Free(SXW->f_roots); + Mem_Free(SXW->f_phen); + Mem_Free(SXW->f_bvt); + Mem_Free(SXW->f_prod); + Mem_Free(SXW->f_watin); + Mem_Free(SXW->transpTotal); + ForEachVegType(k) { + Mem_Free(SXW->transpVeg[k]); + } + Mem_Free(SXW->swc); + Mem_Free(SXW); } /***********************************************************/ From a932dc500e18ba45e62b8a3f0baad0b60f15941e Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 17 Jun 2019 14:12:08 -0600 Subject: [PATCH 088/167] Removed references to load_sxw_memory from ST_grid These calls were causing the branch to break. (#322) --- ST_grid.c | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 1cb57e1f..14692657 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -350,11 +350,7 @@ void _make_header_with_std( char *buf); //functions from sxw.c //void free_sxw_memory( void ); -//void free_all_sxw_memory(void); -void load_sxw_memory(RealD * grid_roots_max, RealD* grid_rootsXphen, - RealD* grid_roots_active, RealD* grid_roots_active_rel, - RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, - RealD* grid_prod_pctlive); + void save_sxw_memory(RealD * grid_roots_max, RealD* grid_rootsXphen, RealD* grid_roots_active, RealD* grid_roots_active_rel, RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, @@ -1816,15 +1812,6 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) memcpy(SW_Site.lyr[j], grid_SW_Site[cell].lyr[j], sizeof(SW_LAYER_INFO)); } - - if (UseSoils) - load_sxw_memory(grid_SXW_ptrs[cell].roots_max, - grid_SXW_ptrs[cell].rootsXphen, - grid_SXW_ptrs[cell].roots_active, - grid_SXW_ptrs[cell].roots_active_rel, - grid_SXW_ptrs[cell].roots_active_sum, - grid_SXW_ptrs[cell].phen, grid_SXW_ptrs[cell].prod_bmass, - grid_SXW_ptrs[cell].prod_pctlive); } /* Load gridCells[row][col] into the globals variables. @@ -1995,16 +1982,6 @@ static void _load_spinup_cell(int cell) memcpy(SW_Site.lyr[j], spinup_SW_Site[cell].lyr[j], sizeof(SW_LAYER_INFO)); } - - if (UseSoils) - load_sxw_memory(spinup_SXW_ptrs[cell].roots_max, - spinup_SXW_ptrs[cell].rootsXphen, - spinup_SXW_ptrs[cell].roots_active, - spinup_SXW_ptrs[cell].roots_active_rel, - spinup_SXW_ptrs[cell].roots_active_sum, - spinup_SXW_ptrs[cell].phen, - spinup_SXW_ptrs[cell].prod_bmass, - spinup_SXW_ptrs[cell].prod_pctlive); } /***********************************************************/ From 25038dd55f3f41d65befd5bde942ae20c83bd884 Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Tue, 18 Jun 2019 17:28:37 -0400 Subject: [PATCH 089/167] (Issues #300 #301) Add _kill_maxage --- ST_grid.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index 14692657..78842bad 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -295,6 +295,7 @@ extern Bool* _SomeKillage; // Declare functions defined elsewhere: void runGrid(void); //to be called from ST_main.c void _kill_annuals(void); +void _kill_maxage(void); void _kill_extra_growth(void); void rgroup_Extirpate(GrpIndex rg); @@ -616,6 +617,7 @@ void runGrid(void) stat_Collect(year); // Update the accumulators _kill_annuals(); // Kill annuals + _kill_maxage(); // Kill plants that reach max age proportion_Recovery(); // Recover from any disturbances _kill_extra_growth(); // Kill superfluous growth @@ -809,6 +811,7 @@ static void _run_spinup(void) mort_EndOfYear(); // End of year mortality. _kill_annuals(); // Kill annuals + _kill_maxage(); // Kill plants that reach max age proportion_Recovery(); // Recover from any disturbances _kill_extra_growth(); // Kill superfluous growth } /* end column */ From df9fcfa2e25440b27c62c883e30264223797610c Mon Sep 17 00:00:00 2001 From: Frederick Pierson Date: Tue, 18 Jun 2019 17:28:37 -0400 Subject: [PATCH 090/167] (Issues #287 #301) Add _kill_maxage --- ST_grid.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index 14692657..78842bad 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -295,6 +295,7 @@ extern Bool* _SomeKillage; // Declare functions defined elsewhere: void runGrid(void); //to be called from ST_main.c void _kill_annuals(void); +void _kill_maxage(void); void _kill_extra_growth(void); void rgroup_Extirpate(GrpIndex rg); @@ -616,6 +617,7 @@ void runGrid(void) stat_Collect(year); // Update the accumulators _kill_annuals(); // Kill annuals + _kill_maxage(); // Kill plants that reach max age proportion_Recovery(); // Recover from any disturbances _kill_extra_growth(); // Kill superfluous growth @@ -809,6 +811,7 @@ static void _run_spinup(void) mort_EndOfYear(); // End of year mortality. _kill_annuals(); // Kill annuals + _kill_maxage(); // Kill plants that reach max age proportion_Recovery(); // Recover from any disturbances _kill_extra_growth(); // Kill superfluous growth } /* end column */ From a01823f28b1512957ed31ecfd4a1b597384f6dc9 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 19 Jun 2019 14:40:00 -0600 Subject: [PATCH 091/167] Added standard deviation calculation. To Output_AllCellAvgBmass. (issue #310) --- ST_grid.c | 58 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 17 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 78842bad..f9ac894c 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -3461,13 +3461,14 @@ static void _read_grid_setup(void) } void Output_AllCellAvgBmass(const char * filename){ - int i, j, year; //for iterating + int i, j, year, nobs = 0; //for iterating GrpIndex rg; //for iterating SppIndex sp; //for iterating /* One accumulator for every accumulator in ST_stats.c */ - float ppt, temp, dist, wildfire, grp[SuperGlobals.max_rgroups], gsize[SuperGlobals.max_rgroups], - gpr[SuperGlobals.max_rgroups], prescribedfire[SuperGlobals.max_rgroups], + float ppt, pptstd, pptsos, temp, tempstd, tempsos, dist, wildfire, grp[SuperGlobals.max_rgroups], grpstd[SuperGlobals.max_rgroups], grpsos[SuperGlobals.max_rgroups], + gsize[SuperGlobals.max_rgroups], + gpr[SuperGlobals.max_rgroups], gprsos[SuperGlobals.max_rgroups], gprstd[SuperGlobals.max_rgroups], prescribedfire[SuperGlobals.max_rgroups], spp[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups], indv[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups]; @@ -3490,14 +3491,23 @@ void Output_AllCellAvgBmass(const char * filename){ *buf = '\0'; //Initialize buffer as empty string /* -------- Initialize all accumulators to 0 ------- */ - ppt = 0; + nobs = 0; + ppt = 0; + pptstd = 0; + pptsos = 0; temp = 0; + tempstd = 0; + tempsos = 0; dist = 0; wildfire = 0; ForEachGroup(rg){ grp[rg] = 0; + grpsos[rg] = 0; + grpstd[rg] = 0; gsize[rg] = 0; - grp[rg] = 0; + gpr[rg] = 0; + gprsos[rg] = 0; + gprstd[rg] = 0; prescribedfire[rg] = 0; } ForEachSpecies(sp){ @@ -3509,20 +3519,38 @@ void Output_AllCellAvgBmass(const char * filename){ for(i = 0; i < grid_Rows; ++i){ // For each row for(j = 0; j < grid_Cols; ++j){ // For each column /* ------------- Accumulate requested output ----------------- */ - if(BmassFlags.ppt) ppt += gridCells[i][j]._Ppt->s[year].ave; - if(BmassFlags.tmp) temp += gridCells[i][j]._Temp->s[year].ave; + nobs++; + if(BmassFlags.ppt) { + + float old_ppt_ave = ppt; + ppt = get_running_mean(nobs, ppt, gridCells[i][j]._Ppt->s[year].ave); + pptsos += get_running_sqr(old_ppt_ave, ppt, gridCells[i][j]._Ppt->s[year].ave); + pptstd = final_running_sd(nobs, pptsos); + } + if(BmassFlags.tmp) { + float old_temp_ave = temp; + temp = get_running_mean(nobs, temp, gridCells[i][j]._Temp->s[year].ave); + tempsos += get_running_sqr(old_temp_ave, temp, gridCells[i][j]._Temp->s[year].ave); + tempstd = final_running_sd(nobs, tempsos); + } if(BmassFlags.dist) dist += gridCells[i][j]._Dist->s[year].nobs; if(BmassFlags.grpb) { if(BmassFlags.wildfire){ wildfire += gridCells[i][j]._Gwf->wildfire[year]; } ForEachGroup(rg){ - grp[rg] += gridCells[i][j]._Grp[rg].s[year].ave; + float old_grp_ave = grp[rg]; + grp[rg] = get_running_mean(nobs, grp[rg], gridCells[i][j]._Grp[rg].s[year].ave); + grpsos[rg] += get_running_sqr(old_grp_ave, grp[rg], gridCells[i][j]._Grp[rg].s[year].ave); + grpstd[rg] = final_running_sd(nobs, grpsos[rg]); if(BmassFlags.size){ gsize[rg] += gridCells[i][j]._Gsize[rg].s[year].ave; } if(BmassFlags.pr){ - gpr[rg] += gridCells[i][j]._Gpr[rg].s[year].ave; + float old_gpr_ave = gpr[rg]; + gpr[rg] = get_running_mean(nobs, gpr[rg], gridCells[i][j]._Gpr[rg].s[year].ave); + gprsos[rg] += get_running_sqr(old_gpr_ave, gpr[rg], gridCells[i][j]._Gpr[rg].s[year].ave); + gprstd[rg] = final_running_sd(nobs, gprsos[rg]); } if(BmassFlags.prescribedfire){ prescribedfire[rg] += gridCells[i][j]._Gwf->prescribedFire[rg][year]; @@ -3542,14 +3570,10 @@ void Output_AllCellAvgBmass(const char * filename){ } // End for each row /* ---------------- Average all accumulators ---------------- */ - ppt /= grid_Cells; - temp /= grid_Cells; dist /= grid_Cells; wildfire /= grid_Cells; ForEachGroup(rg){ - grp[rg] /= grid_Cells; gsize[rg] /= grid_Cells; - grp[rg] /= grid_Cells; prescribedfire[rg] /= grid_Cells; } ForEachSpecies(sp){ @@ -3568,7 +3592,7 @@ void Output_AllCellAvgBmass(const char * filename){ strcat(buf, tbuf); } if(BmassFlags.ppt){ - sprintf(tbuf, "%f%cTODO%c", ppt, sep, sep); + sprintf(tbuf, "%f%c%f%c", ppt, sep, pptstd, sep); strcat(buf, tbuf); } if (BmassFlags.pclass) { @@ -3576,7 +3600,7 @@ void Output_AllCellAvgBmass(const char * filename){ strcat(buf, tbuf); } if(BmassFlags.tmp){ - sprintf(tbuf, "%f%cTODO%c", temp, sep, sep); + sprintf(tbuf, "%f%c%f%c", temp, sep, tempstd, sep); strcat(buf, tbuf); } if(BmassFlags.grpb){ @@ -3585,7 +3609,7 @@ void Output_AllCellAvgBmass(const char * filename){ strcat(buf, tbuf); } ForEachGroup(rg){ - sprintf(tbuf, "%f%cTODO%c", grp[rg], sep, sep); + sprintf(tbuf, "%f%c%f%c", grp[rg], sep, grpstd[rg], sep); strcat(buf, tbuf); if(BmassFlags.size){ @@ -3593,7 +3617,7 @@ void Output_AllCellAvgBmass(const char * filename){ strcat(buf, tbuf); } if(BmassFlags.pr){ - sprintf(tbuf, "%f%cTODO%c", gpr[rg], sep, sep); + sprintf(tbuf, "%f%c%f%c", gpr[rg], sep, gprstd[rg], sep); strcat(buf, tbuf); } if(BmassFlags.prescribedfire){ From a99710348821fcbf02e40f56b03f2f5e3565d447 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 21 Jun 2019 10:49:12 -0600 Subject: [PATCH 092/167] Corrected deallocation of mySeedDispersal->prob (issue #322) --- ST_grid.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index f9ac894c..8bc9992a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1644,18 +1644,23 @@ static void _free_grid_memory(void) /* Free memory that we have allocated in ST_grid.c */ for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ - Mem_Free(gridCells[i][j].mySpeciesInit.species_seed_avail); - Mem_Free(gridCells[i][j].mySeedDispersal->prob); - Mem_Free(gridCells[i][j].mySeedDispersal); - Mem_Free(gridCells[i][j].someKillage); - Mem_Free(gridCells[i][j].mySoils.lyr); - /* Use deallocate_Globals from ST_main to deallocate global variables, and free_all_sxw_memory from sxw to deallocate SXW variables. */ load_cell(i,j); deallocate_Globals(TRUE); free_all_sxw_memory(); + // If seed dispersal is on we allocated additional memory + if(UseSeedDispersal) { + ForEachSpecies(s) { + Mem_Free(gridCells[i][j].mySeedDispersal[s].prob); + } + } unload_cell(); + + Mem_Free(gridCells[i][j].mySpeciesInit.species_seed_avail); + Mem_Free(gridCells[i][j].mySeedDispersal); + Mem_Free(gridCells[i][j].someKillage); + Mem_Free(gridCells[i][j].mySoils.lyr); } } From 2b83aca647a2ca410649b5435be2b0992f15eb1f Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 21 Jun 2019 11:26:59 -0600 Subject: [PATCH 093/167] Removed a few deprecated functions Including: * _save_cell * _save_spinup_cell * _load_spinup_cell Both save functions are no longer usefull becasue we switched to shallow copying, and `_load_spinup_cell` is replaced by `load_cell`. I also removed two unused variables from RunGrid and one from _free_grid_memory. I also addressed a compiler warning in Output_AllCellAvgBmass. --- ST_grid.c | 252 +----------------------------------------------------- 1 file changed, 2 insertions(+), 250 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 8bc9992a..c438145e 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -383,7 +383,6 @@ static void _init_spinup_globals(void); static void allocate_gridCells(int rows, int cols); static void allocate_accumulators(void); static void _load_grid_globals(void); -static void _load_spinup_globals(void); static void _free_grid_memory(void); static void _free_spinup_memory(void); static void _free_grid_globals(void); @@ -392,8 +391,6 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators); static void load_cell(int row, int col); static void unload_cell(void); static void _load_spinup_cell(int cell); -static void _save_cell(int row, int col, int year, Bool useAccumulators); -static void _save_spinup_cell(int cell); static void _read_disturbances_in(void); static void _read_soils_in(void); static void _init_soil_layers(int cell, int isSpinup); @@ -705,11 +702,6 @@ static void _run_spinup(void) SppIndex sp; IntS k; - /* 'Globals' is not allocated in gridded mode. Therefore we need to implicitely remember years - and iterations. gridCells[0][0] is guaranteed to exist because it is populated first. */ - int iterations = SuperGlobals.runModelIterations; - int total_years = SuperGlobals.runModelYears; - /* killedany for mortality functions, temporary_storage for swapping variables */ Bool killedany, temporary_storage; @@ -773,7 +765,7 @@ static void _run_spinup(void) } /* End for each row */ unload_cell(); // Reset the global variables - for (year = 1; year <= total_years; year++) + for (year = 1; year <= SuperGlobals.runModelYears; year++) { //for each year for (i = 0; i < grid_Rows; ++i) { // for each row @@ -1638,7 +1630,6 @@ static void _free_grid_memory(void) { //frees all the memory allocated in this file ST_Grid.c (most of it is dynamically allocated in _init_grid_globals() & _load_grid_globals() functions) int i, j; - GrpIndex c; SppIndex s; /* Free memory that we have allocated in ST_grid.c */ @@ -1992,245 +1983,6 @@ static void _load_spinup_cell(int cell) } } -/***********************************************************/ -static void _save_cell(int row, int col, int year, Bool useAccumulators) -{ - // saves the specified cell into the grid variables - - int cell = col + ((row - 1) * grid_Cols) - 1; // converts the row/col into an array index - int j, k; - GrpIndex c; - SppIndex s; - //fprintf(stderr, "saving cell: %d\n", cell); - - if (useAccumulators) - stat_Save_Accumulators(cell, year); - - ForEachSpecies(s) - { - if (!Species[s]->use_me) - continue; - - Mem_Free(grid_Species[s][cell].kills); - Mem_Free(grid_Species[s][cell].seedprod); - _free_head(grid_Species[s][cell].IndvHead); - - grid_Species[s][cell] = *Species[s]; - - grid_Species[s][cell].kills = Mem_Calloc(Species[s]->max_age, - sizeof(IntUS), "_save_cell(grid_Species[cell][s].kills)"); - grid_Species[s][cell].seedprod = Mem_Calloc(Species[s]->viable_yrs, - sizeof(RealF), "_save_cell(grid_Species[cell][s].seedprod)"); - - memcpy(grid_Species[s][cell].kills, Species[s]->kills, - Species[s]->max_age * sizeof(IntUS)); - memcpy(grid_Species[s][cell].seedprod, Species[s]->seedprod, - Species[s]->viable_yrs * sizeof(RealF)); - grid_Species[s][cell].IndvHead = _copy_head(Species[s]->IndvHead); - } - - ForEachGroup(c) - { - if (!RGroup[c]->use_me) - continue; - Mem_Free(grid_RGroup[c][cell].kills); //kills is the only pointer in the resourcegroup_st struct (which is what RGroup is defined as) - - grid_RGroup[c][cell] = *RGroup[c]; //does a shallow copy, we have to do the freeing/malloc/memcpy to deep copy (i.e. copy the values in the pointers instead of the addresses) the pointers - - grid_RGroup[c][cell].kills = Mem_Calloc(RGroup[c]->max_age, - sizeof(IntUS), "_save_cell(grid_RGroup[cell][c].kills)"); - memcpy(grid_RGroup[c][cell].kills, RGroup[c]->kills, - RGroup[c]->max_age * sizeof(IntUS)); - } - - grid_Succulent[cell] = *Succulent; - grid_Env[cell] = *Env; - grid_Plot[cell] = *Plot; - grid_Globals[cell] = *Globals; - - Mem_Free(grid_SXW[cell].f_roots); - Mem_Free(grid_SXW[cell].f_phen); - Mem_Free(grid_SXW[cell].f_bvt); - Mem_Free(grid_SXW[cell].f_prod); - Mem_Free(grid_SXW[cell].f_watin); - Mem_Free(grid_SXW[cell].transpTotal); - ForEachVegType(k) { - Mem_Free(grid_SXW[cell].transpVeg[k]); - } - Mem_Free(grid_SXW[cell].swc); - for (j = 0; - j < grid_SW_Site[cell].n_layers + grid_SW_Site[cell].deepdrain; - j++) - Mem_Free(grid_SW_Site[cell].lyr[j]); - Mem_Free(grid_SW_Site[cell].lyr); - - grid_SXW[cell] = *SXW; - grid_SW_Site[cell] = SW_Site; - grid_SW_Soilwat[cell] = SW_Soilwat; - grid_SW_VegProd[cell] = SW_VegProd; - - grid_SXW[cell].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); - ForEachVegType(k) { - grid_SXW[cell].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); - } - grid_SXW[cell].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), - "_save_cell(grid_SXW[cell].swc)"); - - grid_SXW[cell].f_roots = Str_Dup(SXW->f_roots); - grid_SXW[cell].f_phen = Str_Dup(SXW->f_phen); - grid_SXW[cell].f_bvt = Str_Dup(SXW->f_bvt); - grid_SXW[cell].f_prod = Str_Dup(SXW->f_prod); - grid_SXW[cell].f_watin = Str_Dup(SXW->f_watin); - memcpy(grid_SXW[cell].transpTotal, SXW->transpTotal, - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - ForEachVegType(k) { - memcpy(grid_SXW[cell].transpVeg[k], SXW->transpVeg[k], - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - } - memcpy(grid_SXW[cell].swc, SXW->swc, - SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); - - grid_SW_Site[cell].lyr = Mem_Calloc( - SW_Site.n_layers + SW_Site.deepdrain, sizeof(SW_LAYER_INFO *), - "_save_cell(grid_SW_Site[cell].lyr[j])"); - for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) - { - grid_SW_Site[cell].lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_save_cell(grid_SW_Site[cell].lyr[j])"); - memcpy(grid_SW_Site[cell].lyr[j], SW_Site.lyr[j], - sizeof(SW_LAYER_INFO)); - } - - if (UseSoils) - save_sxw_memory(grid_SXW_ptrs[cell].roots_max, - grid_SXW_ptrs[cell].rootsXphen, - grid_SXW_ptrs[cell].roots_active, - grid_SXW_ptrs[cell].roots_active_rel, - grid_SXW_ptrs[cell].roots_active_sum, - grid_SXW_ptrs[cell].phen, grid_SXW_ptrs[cell].prod_bmass, - grid_SXW_ptrs[cell].prod_pctlive); -} - -/***********************************************************/ -static void _save_spinup_cell(int cell) -{ - // saves the specified cell into the grid variables (from the spinup) - - int j, k; - GrpIndex c; - SppIndex s; - - ForEachSpecies(s) - { - if (!Species[s]->use_me) - continue; - - Mem_Free(spinup_Species[s][cell].kills); - Mem_Free(spinup_Species[s][cell].seedprod); - _free_head(spinup_Species[s][cell].IndvHead); - - spinup_Species[s][cell] = *Species[s]; - - spinup_Species[s][cell].kills = Mem_Calloc(Species[s]->max_age, - sizeof(IntUS), "_save_cell(grid_Species[cell][s].kills)"); - spinup_Species[s][cell].seedprod = Mem_Calloc(Species[s]->viable_yrs, - sizeof(RealF), "_save_cell(grid_Species[cell][s].seedprod)"); - - memcpy(spinup_Species[s][cell].kills, Species[s]->kills, - Species[s]->max_age * sizeof(IntUS)); - memcpy(spinup_Species[s][cell].seedprod, Species[s]->seedprod, - Species[s]->viable_yrs * sizeof(RealF)); - spinup_Species[s][cell].IndvHead = _copy_head(Species[s]->IndvHead); - } - - ForEachGroup(c) - { - if (!RGroup[c]->use_me) - continue; - Mem_Free(spinup_RGroup[c][cell].kills); //kills is the only pointer in the resourcegroup_st struct (which is what RGroup is defined as) - - spinup_RGroup[c][cell] = *RGroup[c]; //does a shallow copy, we have to do the freeing/malloc/memcpy to deep copy (i.e. copy the values in the pointers instead of the addresses) the pointers - - spinup_RGroup[c][cell].kills = Mem_Calloc(RGroup[c]->max_age, - sizeof(IntUS), "_save_cell(grid_RGroup[cell][c].kills)"); - memcpy(spinup_RGroup[c][cell].kills, RGroup[c]->kills, - RGroup[c]->max_age * sizeof(IntUS)); - } - - spinup_Succulent[cell] = *Succulent; - spinup_Env[cell] = *Env; - spinup_Plot[cell] = *Plot; - spinup_Globals[cell] = *Globals; - - Mem_Free(spinup_SXW[cell].f_roots); - Mem_Free(spinup_SXW[cell].f_phen); - Mem_Free(spinup_SXW[cell].f_bvt); - Mem_Free(spinup_SXW[cell].f_prod); - Mem_Free(spinup_SXW[cell].f_watin); - Mem_Free(spinup_SXW[cell].transpTotal); - ForEachVegType(k) { - Mem_Free(spinup_SXW[cell].transpVeg[k]); - } - Mem_Free(spinup_SXW[cell].swc); - for (j = 0; - j - < spinup_SW_Site[cell].n_layers - + spinup_SW_Site[cell].deepdrain; j++) - Mem_Free(spinup_SW_Site[cell].lyr[j]); - Mem_Free(spinup_SW_Site[cell].lyr); - - spinup_SXW[cell] = *SXW; - spinup_SW_Site[cell] = SW_Site; - spinup_SW_Soilwat[cell] = SW_Soilwat; - spinup_SW_VegProd[cell] = SW_VegProd; - - spinup_SXW[cell].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); - ForEachVegType(k) { - spinup_SXW[cell].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_save_cell(grid_SXW[cell].transp)"); - } - spinup_SXW[cell].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), - "_save_cell(grid_SXW[cell].swc)"); - - spinup_SXW[cell].f_roots = Str_Dup(SXW->f_roots); - spinup_SXW[cell].f_phen = Str_Dup(SXW->f_phen); - spinup_SXW[cell].f_bvt = Str_Dup(SXW->f_bvt); - spinup_SXW[cell].f_prod = Str_Dup(SXW->f_prod); - spinup_SXW[cell].f_watin = Str_Dup(SXW->f_watin); - memcpy(spinup_SXW[cell].transpTotal, SXW->transpTotal, - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - ForEachVegType(k) { - memcpy(spinup_SXW[cell].transpVeg[k], SXW->transpVeg[k], - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - } - memcpy(spinup_SXW[cell].swc, SXW->swc, - SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); - - spinup_SW_Site[cell].lyr = Mem_Calloc( - SW_Site.n_layers + SW_Site.deepdrain, sizeof(SW_LAYER_INFO *), - "_save_cell(grid_SW_Site[cell].lyr[j])"); - for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) - { - spinup_SW_Site[cell].lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_save_cell(grid_SW_Site[cell].lyr[j])"); - memcpy(spinup_SW_Site[cell].lyr[j], SW_Site.lyr[j], - sizeof(SW_LAYER_INFO)); - } - - if (UseSoils) - save_sxw_memory(spinup_SXW_ptrs[cell].roots_max, - spinup_SXW_ptrs[cell].rootsXphen, - spinup_SXW_ptrs[cell].roots_active, - spinup_SXW_ptrs[cell].roots_active_rel, - spinup_SXW_ptrs[cell].roots_active_sum, - spinup_SXW_ptrs[cell].phen, - spinup_SXW_ptrs[cell].prod_bmass, - spinup_SXW_ptrs[cell].prod_pctlive); -} - /**************************************************************/ static Bool GetALine2(FILE *f, char buf[], int limit) { @@ -3593,7 +3345,7 @@ void Output_AllCellAvgBmass(const char * filename){ sprintf(buf,"%d%c", year+1, sep); } if(BmassFlags.dist){ - sprintf(tbuf, "%ld%c", dist, sep); + sprintf(tbuf, "%f%c", dist, sep); strcat(buf, tbuf); } if(BmassFlags.ppt){ From 535650784a17141536ba1338a48d09db3bfbeb88 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 21 Jun 2019 13:19:25 -0600 Subject: [PATCH 094/167] Reset SXW for all grid cells By only resetting SXW for cell [0, 0] we were getting different PPT values across cells for years 1 through 31 which should not happen. Instead we needed to loop through cells and reset each SXW. (issue #287) --- ST_grid.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index c438145e..f617cec7 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -640,7 +640,13 @@ void runGrid(void) unload_cell(); //reset soilwat to initial condition ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); - SXW_Reset(gridCells[0][0].mySXW->f_watin); + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + load_cell(i, j); + SXW_Reset(gridCells[i][j].mySXW->f_watin); + unload_cell(); + } + } Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; ChDir(".."); From feab651c7b114e98a3373309bdeb3a689bec2c4b Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 21 Jun 2019 14:56:10 -0600 Subject: [PATCH 095/167] Fixed historical weather file not being used. I isolated this code from _run_spinup which makes SOILWAT use the historical weather correctly. I haven't figured out why we need to reset SXW before using it, but this seems to be an important step. I also tried placing this code segment above _run_spinup, since I thought it couldn;t hurt and it would make the code more readable, but this didn't prevent the bug. It seems that this snippet of code must be run once; either inside _run_spinup or in RunGrid. --- ST_grid.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index f617cec7..d7fba3d6 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -538,8 +538,16 @@ void runGrid(void) unload_cell(); /* END printing general info */ - if (sd_Option2a || sd_Option2b) + if (sd_Option2a || sd_Option2b) { _run_spinup(); // does the initial spinup + } else { + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); + SXW_Reset(gridCells[0][0].mySXW->f_watin); + //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. + Mem_Free(SW_Soilwat.hist.file_prefix); + SW_Soilwat.hist.file_prefix = NULL; + ChDir(".."); + } // SOILWAT resets SW_Weather.name_prefix every iteration. This is not the behavior we want // so the name is stored here. From 21f2748956ee60b5ebe89739af632139052d47e9 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Mon, 24 Jun 2019 10:41:01 -0600 Subject: [PATCH 096/167] Removed unnecessary Mem_free call (issue #327) I tested the program without these lines and the bug did not reappear. It looks like the only step needed to resolve this bug was calling SXW_Reset before starting iterations. --- ST_grid.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index d7fba3d6..5867ae87 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -541,11 +541,10 @@ void runGrid(void) if (sd_Option2a || sd_Option2b) { _run_spinup(); // does the initial spinup } else { + /* If no spinup is requested we still need to reset SXW to set the historical weather + file names. */ ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); SXW_Reset(gridCells[0][0].mySXW->f_watin); - //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. - Mem_Free(SW_Soilwat.hist.file_prefix); - SW_Soilwat.hist.file_prefix = NULL; ChDir(".."); } From 2973b8ed39aec63792a599a848c11dcdb6fce467 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 26 Jun 2019 11:52:41 -0600 Subject: [PATCH 097/167] Modified initialization parameters These changes make inputs easier to specify. They remove the boolean options and replace them with a string parameter that represents which type of initialization we would like. They also add some error checking to grid_initSpecies via _run_spinup. This commit is aimed at issue #328, but also modifies spinup (issue #300). In grid_setup.in: * added initialization parameter with an explaination of what options are valid. in grid_seed_dispersal.in: * removed option 1a, 1b, 2a, and 2b in ST_main.c: * added InitializationMethod as global variable. This follows the pattern ofother global variables even though the variable is only used in ST_grid.c. in ST_globals.h: * added InitializationMethod as externed variable. in ST_grid.c: * Renamed species_seed_avail to shouldBeInitialized. I did this to make the name of the variable more closely match it's purpose. The variable lists whether or not each species should be included in spinup or initial seed dispersal, so I renamed it accordingly. * Added an initialization type enumerator for the three different ways we can initialize the cells. * Removed the variables sd_Option1a, 1b, 2a, and 2b. They are no longer needed because of the new InitializationMethod variable. * Modified the general info print block to reflect the new InitializationMethod variable as well as the removal of sd_option1a and so forth. * Began using InitializationMethod in place of the former options. It makes the code more readable. * To compensate for the removal of sd_option2a and 2b I added some error checking to _run_spinup. If the user requests spinup for a given cell but no species are turned on for spinup the program now prints a log warning. --- ST_globals.h | 1 + ST_grid.c | 150 +++++++++--------- ST_main.c | 1 + .../Grid_Inputs/grid_seed_dispersal.in | 10 +- .../Grid_Inputs/grid_setup.in | 1 + 5 files changed, 83 insertions(+), 80 deletions(-) diff --git a/ST_globals.h b/ST_globals.h index a326018d..ea536956 100644 --- a/ST_globals.h +++ b/ST_globals.h @@ -30,5 +30,6 @@ extern MortFlagsType MortFlags; extern GlobalType SuperGlobals; extern Bool UseSeedDispersal; +extern int InitializationMethod; extern Bool UseGrid; extern Bool DuringSpinup; diff --git a/ST_grid.c b/ST_grid.c index 5867ae87..e390b3ef 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -148,7 +148,7 @@ struct _grid_init_species_st int use_SpinUp; /* Array of Boolean values. TRUE if given species should be included in spinup */ - int *species_seed_avail; + int *shouldBeInitialized; }typedef Grid_Init_Species_St; /* Struct to hold all plot-specific parameters */ @@ -231,11 +231,18 @@ enum N_GRID_FILES }; +/* Enumerator for initialization types */ +enum +{ + INIT_WITH_SPINUP, + INIT_WITH_SEEDS, + INIT_WITH_NOTHING +}; + char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; int grid_Cols, grid_Rows, grid_Cells, sd_NYearsSeedsAvailable; -int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader, sd_Option1a, - sd_Option1b, sd_Option2a, sd_Option2b; //these are treated like booleans +int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans // these variables are for storing the globals in STEPPE... they are dynamically allocated/freed SpeciesType **grid_Species, **spinup_Species; @@ -522,23 +529,24 @@ void runGrid(void) Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; - /* Print some general information to stdout */ - load_cell(0,0); + /* ------------------- Print some general information to stdout ----------------------- */ printf("Number of layers: %d\n", SW_Site.n_layers); printf("Number of iterations: %d\n", SuperGlobals.runModelIterations); printf("Number of years: %d\n", SuperGlobals.runModelYears); printf("Number of cells: %d\n\n", grid_Cells); if(UseDisturbances) printf("Using grid Disturbances file.\n"); if(UseSoils) printf("Using grid soils file\n"); - if(UseSeedDispersal){ + if(InitializationMethod == INIT_WITH_SEEDS){ printf("Seeds availible for %d years at the start of the simulation.\n",sd_NYearsSeedsAvailable); - if(sd_Option1a) printf("All species and cells are eligible for seed dispersal.\n"); + } else if(InitializationMethod == INIT_WITH_SPINUP) { + printf("Running Spinup\n"); } - if(sd_Option2a) printf("Running Spinup for %s cells.\n", sd_Option2b ? "all" : "specified"); - unload_cell(); - /* END printing general info */ + if(UseSeedDispersal){ + printf("Dispersing seeds between cells\n"); + } + /* --------------------------- END printing general info -------------------------------- */ - if (sd_Option2a || sd_Option2b) { + if (InitializationMethod == INIT_WITH_SPINUP) { _run_spinup(); // does the initial spinup } else { /* If no spinup is requested we still need to reset SXW to set the historical weather @@ -716,7 +724,7 @@ static void _run_spinup(void) IntS k; /* killedany for mortality functions, temporary_storage for swapping variables */ - Bool killedany, temporary_storage; + Bool killedany, temporary_storage, isAtLeastOneSpeciesOn; DuringSpinup = TRUE; @@ -752,12 +760,16 @@ static void _run_spinup(void) } unload_cell(); // Reset the global variables - /* Before we start iterating we need to swap Species[sp]->use_me and mySpeciesInit.species_seed_avail[sp]. - species_seed_avail is an array of booleans that represent whether the given species should be used - in spinup. use_me is a boolean that represents whether the given species should be used in production. + /* Before we start iterating we need to swap Species[sp]->use_me and mySpeciesInit.shouldBeInitialized[sp]. + shouldBeInitialized is an array of booleans that represent whether the given species should be used + in initialization. use_me is a boolean that represents whether the given species should be used in production. By swaping them we save space, but we have to remember to swap them back before the production run. */ for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ + if(!gridCells[i][j].mySpeciesInit.use_SpinUp){ + continue; + } + isAtLeastOneSpeciesOn = FALSE; load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee that ForEachGroup would iterate correctly */ @@ -769,11 +781,19 @@ static void _run_spinup(void) // Temporarily store use_me temporary_storage = Species[sp]->use_me; // Swap use_me - Species[sp]->use_me = gridCells[i][j].mySpeciesInit.species_seed_avail[sp]; - // Swap species_seed_avail[sp] - gridCells[i][j].mySpeciesInit.species_seed_avail[sp] = temporary_storage; + Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; + // Swap shouldBeInitialized[sp] + gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; + /* Make sure at least one species in this cell is turned on */ + if(Species[sp]->use_me) isAtLeastOneSpeciesOn = TRUE; } /* End for each species */ } /* End for each group */ + + if(!isAtLeastOneSpeciesOn){ + LogError(logfp, LOGWARN, + "Grid Cell %d %d is turned on for spinup, but none of the species in the cell are turned on.\n" + "This can be corrected in the init species file.", i, j); + } } /* End for each column */ } /* End for each row */ unload_cell(); // Reset the global variables @@ -833,9 +853,12 @@ static void _run_spinup(void) ChDir(".."); } /* End iterations */ - /* Swap back Species[sp]->use_me and species_seed_avail[sp]. */ + /* Swap back Species[sp]->use_me and shouldBeInitialized[sp]. */ for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ + if(!gridCells[i][j].mySpeciesInit.use_SpinUp){ + continue; + } load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee that ForEachGroup would iterate correctly */ /* Begin swaping variables */ @@ -844,9 +867,9 @@ static void _run_spinup(void) // Temporarily store use_me temporary_storage = Species[sp]->use_me; // Swap use_me - Species[sp]->use_me = gridCells[i][j].mySpeciesInit.species_seed_avail[sp]; - // Swap species_seed_avail[sp] - gridCells[i][j].mySpeciesInit.species_seed_avail[sp] = temporary_storage; + Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; + // Swap shouldBeInitialized[sp] + gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; } /* End for each species */ } /* End for each group */ } /* End for each column */ @@ -907,7 +930,7 @@ static void _init_grid_inputs(void) if (UseDisturbances) _read_disturbances_in(); - if (UseSeedDispersal) + if (UseSeedDispersal || InitializationMethod != INIT_WITH_NOTHING) { _read_seed_dispersal_in(); _read_init_species(); @@ -991,8 +1014,8 @@ static void allocate_gridCells(int rows, int cols){ gridCells[i][j].mySoils.lyr = (Grid_Soil_Lyr*) Mem_Calloc(MAX_LAYERS, sizeof(Grid_Soil_Lyr), "allocate_gridCells: mySoils"); - // species_seed_avail is a dynamically allocated array - gridCells[i][j].mySpeciesInit.species_seed_avail = (int*) + // shouldBeInitialized is a dynamically allocated array + gridCells[i][j].mySpeciesInit.shouldBeInitialized = (int*) Mem_Calloc(MAX_SPECIES, sizeof(int), "allocate_gridCells: mySpeciesInit"); gridCells[i][j].someKillage = (Bool*) Mem_Calloc(1, sizeof(Bool), "allocate_gridCells: someKillage"); @@ -1661,7 +1684,7 @@ static void _free_grid_memory(void) } unload_cell(); - Mem_Free(gridCells[i][j].mySpeciesInit.species_seed_avail); + Mem_Free(gridCells[i][j].mySpeciesInit.shouldBeInitialized); Mem_Free(gridCells[i][j].mySeedDispersal); Mem_Free(gridCells[i][j].someKillage); Mem_Free(gridCells[i][j].mySoils.lyr); @@ -1706,10 +1729,8 @@ static void _free_spinup_memory(void) Mem_Free(spinup_SXW_ptrs); } - //if(sd_Option2a || sd_Option2b) { Mem_Free(soilTypes_Array); Mem_Free(grid_SoilTypes); - //} } /***********************************************************/ @@ -2122,8 +2143,7 @@ static void _read_soils_in(void) stringIndex, row, col, copy_cell_row, copy_cell_col; float d[11]; - if (sd_Option2a || sd_Option2b) - nSoilTypes = 0; //initialize our soil types counter + nSoilTypes = 0; //initialize our soil types counter f = OpenFile(grid_files[GRID_FILE_SOILS], "r"); @@ -2190,8 +2210,7 @@ static void _read_soils_in(void) gridCells[row][col].mySoils.num_layers = gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers; // TODO: figure out how to change this code for our new struct - if (sd_Option2a || sd_Option2b) - grid_SoilTypes[cell] = grid_SoilTypes[copy_cell]; + grid_SoilTypes[cell] = grid_SoilTypes[copy_cell]; strcpy(gridCells[row][col].mySoils.rootsFile, gridCells[copy_cell_row][copy_cell_col].mySoils.rootsFile); @@ -2203,12 +2222,9 @@ static void _read_soils_in(void) grid_files[GRID_FILE_SOILS], i + 2); // TODO: figure out how to change this code for our new struct - if (sd_Option2a || sd_Option2b) - { - grid_SoilTypes[cell] = nSoilTypes; - soilTypes_Array[nSoilTypes] = cell; - nSoilTypes++; - } + grid_SoilTypes[cell] = nSoilTypes; + soilTypes_Array[nSoilTypes] = cell; + nSoilTypes++; depthMin = 0; gridCells[row][col].mySoils.num_layers = num_layers; @@ -2544,31 +2560,6 @@ static void _read_seed_dispersal_in(void) LogError(logfp, LOGFATAL, "Invalid %s file: option 1 line\n", grid_files[GRID_FILE_SEED_DISPERSAL]); - GetALine(f, buf); - if (sscanf(buf, "%d", &sd_Option1a) != 1) - LogError(logfp, LOGFATAL, "Invalid %s file: option 1a line\n", - grid_files[GRID_FILE_SEED_DISPERSAL]); - - GetALine(f, buf); - if (sscanf(buf, "%d", &sd_Option1b) != 1) - LogError(logfp, LOGFATAL, "Invalid %s file: option 1b line\n", - grid_files[GRID_FILE_SEED_DISPERSAL]); - - GetALine(f, buf); - if (sscanf(buf, "%d", &sd_Option2a) != 1) - LogError(logfp, LOGFATAL, "Invalid %s file: option 2a line\n", - grid_files[GRID_FILE_SEED_DISPERSAL]); - - GetALine(f, buf); - if (sscanf(buf, "%d", &sd_Option2b) != 1) - LogError(logfp, LOGFATAL, "Invalid %s file: option 2b line\n", - grid_files[GRID_FILE_SEED_DISPERSAL]); - - if ((sd_Option1a && (sd_Option1b || sd_Option2a || sd_Option2b)) - || (sd_Option2a && (sd_Option1a || sd_Option1b || sd_Option2b))) - LogError(logfp, LOGFATAL, - "Invalid %s file: conflicting options chosen\n", grid_files[GRID_FILE_SEED_DISPERSAL]); - CloseFile(&f); for (i = 0; i < grid_Cells; i++) { @@ -2677,7 +2668,7 @@ static void _do_seed_dispersal(void) // which are not specific to each cell. load_cell(0, 0); - if (Globals->currYear == 1 && !sd_Option1a && !sd_Option1b) + if (Globals->currYear == 1) { //since we have no previous data to go off of, use the current years... for (i = 0; i < grid_Cells; i++) { @@ -2724,13 +2715,12 @@ static void _do_seed_dispersal(void) load_cell(row, col); - if (sd_Option1a && Globals->currYear <= sd_NYearsSeedsAvailable) + if (Globals->currYear <= sd_NYearsSeedsAvailable) { cell->mySeedDispersal[s].seeds_present = 1; } - else if (sd_Option1b - && Globals->currYear <= sd_NYearsSeedsAvailable - && cell->mySpeciesInit.species_seed_avail[s]) + else if (Globals->currYear <= sd_NYearsSeedsAvailable + && cell->mySpeciesInit.shouldBeInitialized[s]) { cell->mySeedDispersal[s].seeds_present = 1; } @@ -3134,8 +3124,8 @@ static void _read_init_species(void) && cell != 0 && copy_cell < cell) { //copy this cells values from a previous cell's for (j = 0; j < Globals->sppCount; j++) - gridCells[row][col].mySpeciesInit.species_seed_avail[j] = - gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.species_seed_avail[j]; + gridCells[row][col].mySpeciesInit.shouldBeInitialized[j] = + gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.shouldBeInitialized[j]; gridCells[row][col].mySpeciesInit.use_SpinUp = gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.use_SpinUp; continue; @@ -3155,7 +3145,7 @@ static void _read_init_species(void) "Invalid %s file line %d invalid species input", grid_files[GRID_FILE_INIT_SPECIES], i + 2); - gridCells[row][col].mySpeciesInit.species_seed_avail[s] = seeds_Avail; + gridCells[row][col].mySpeciesInit.shouldBeInitialized[s] = seeds_Avail; stringIndex += _get_value_index(&buf[stringIndex], ',', 1); } } @@ -3189,7 +3179,7 @@ static void _read_files(void) static void _read_grid_setup(void) { FILE *f; - char buf[1024]; + char buf[1024], initializationType[1024]; int i, j; f = OpenFile(grid_files[GRID_FILE_SETUP], "r"); @@ -3227,6 +3217,22 @@ static void _read_grid_setup(void) "Invalid grid setup file (seed dispersal line wrong)"); UseSeedDispersal = itob(j); + GetALine(f, buf); + i = sscanf(buf, "%s", initializationType); + if(i < 1){ + LogError(logfp, LOGFATAL, "Invalid grid setup file (Initialization line wrong)"); + } + if(!strncmp(initializationType, "spinup", 6)){ + InitializationMethod = INIT_WITH_SPINUP; + } else if(!strncmp(initializationType, "seeds", 5)){ + InitializationMethod = INIT_WITH_SEEDS; + } else if(!strncmp(initializationType, "none", 4)){ + InitializationMethod = INIT_WITH_NOTHING; + } else { + LogError(logfp, LOGFATAL, + "Invalid grid setup file (Initialization line wrong. Valid options are \"spinup\", \"seeds\", or \"none\")"); + } + CloseFile(&f); } diff --git a/ST_main.c b/ST_main.c index 3b953f09..6fbe2010 100644 --- a/ST_main.c +++ b/ST_main.c @@ -137,6 +137,7 @@ MortFlagsType MortFlags; Bool UseGrid; Bool UseSeedDispersal; +int InitializationMethod; Bool DuringSpinup; Bool EchoInits; Bool UseProgressBar; diff --git a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in b/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in index 74646332..2f46374f 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in @@ -8,11 +8,5 @@ 1 # output header (ie. the names of all the species)? 1 means yes, 0 means no. Suggested: yes, as it's hard to figure out what all the numbers mean elsewise. , # output seperator... specify one of the following as a separator: t = tab, s = space, or any single character such as , | : etc (excluding '#','t', and 's'). Suggested: tab. -#Spinup and Seed Availability options -#NOTE: options 1a, 2a, and Xb are mutually exclusive. Options 1b and 2b can be combined. Cells can be empty of plants. -10 # option 1) number of years N at the beginning of the simulation during which seeds are available for germination. Input: N years. -0 # option 1a) all cells and species. 1 means yes, 0 means no. -0 # option 1b) input for each cell: seeds of which species are available during those first N years [names & order of all species in species.in]. 1 means yes, 0 means no. -# option 2) run one site without dispersal (ie, conditions of 1-site StepWat, ie, seeds available in every cell for every year) for inputted # of years x replications (eg, 500 years times 10 replications) as spinup -1 # option 2a) use this spinup as init condition in all cells. 1 means yes, 0 means no. -0 # option 2b) input for each cell whether or not to use this spinup as inits. 1 means yes, 0 means no. +#Seed Availability options +10 # number of years N at the beginning of the simulation during which seeds are available for germination. Input: N years. \ No newline at end of file diff --git a/testing.sagebrush.master/Grid_Inputs/grid_setup.in b/testing.sagebrush.master/Grid_Inputs/grid_setup.in index 70fac3bd..5c7b3427 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_setup.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_setup.in @@ -4,3 +4,4 @@ 1 # use disturbances csv file (0 or 1)... 0 means no, 1 means yes 1 # use soils csv file (0 or 1)... 0 means no, 1 means yes 1 # use seed dispersal (0 or 1)... 0 means no, 1 means yes +spinup # Initialization method. Options are "spinup", "seeds", or "none" From 5078beabc12f26414205ec4b588f1a3b33946414 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 3 Jul 2019 14:54:01 -0600 Subject: [PATCH 098/167] Created methods for saving and loading the spinup conditions. (issue #300) This was a major endevour, and I am not yet finished. * In ST_indivs.c I added a function for copying the contents of one individual to another individual. * In ST_species.c I added a function for copying the contents of one SpeciesType to another SpeciesType. * In ST_resgroups.c I added a function for copying the contents of one RGroup into another. * In ST_grid.c I added two functions and one variable: - spinupCells stores the state of gridCells after spinup. - saveAsSpinupConditions() facilitates saving to spinupCells - loadSpinupConditions() uses the copy functions above to deep copy the information from spinupCells to gridCells. This overhaul is not finished. I need to determine what other variables need to be deep copied. For now, you can try turning on species for spinup and see that their biomass is in fact stable before the main loop starts. NOTE: I turned UseSeedDispersal off by default. This is because seed dispersal does not work at this time. --- ST_grid.c | 49 ++++++++ ST_indivs.c | 25 ++++ ST_resgroups.c | 82 +++++++++++++ ST_species.c | 115 ++++++++++++++++++ .../Grid_Inputs/grid_setup.in | 2 +- 5 files changed, 272 insertions(+), 1 deletion(-) diff --git a/ST_grid.c b/ST_grid.c index e390b3ef..940cd094 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -253,6 +253,7 @@ PlotType *grid_Plot, *spinup_Plot; ModelType *grid_Globals, *spinup_Globals; CellType** gridCells; +CellType** spinupCells; // these two variables are for storing SXW variables... also dynamically allocated/freed SXW_t *grid_SXW, *spinup_SXW; @@ -312,6 +313,7 @@ void rgroup_Extirpate(GrpIndex rg); //from ST_species.c void proportion_Recovery(void); void save_annual_species_relsize(void); +void copy_species(const SpeciesType* src, SpeciesType* dest); //from ST_resgroups.c @@ -320,6 +322,7 @@ void rgroup_Establish(void); void rgroup_IncrAges(void); void rgroup_PartResources(void); //void rgroup_ResPartIndiv(void); +void copy_rgroup(const GroupType* src, GroupType* dest); //from ST_mortality.c void mort_Main(Bool *killed); @@ -381,6 +384,8 @@ transp_t* getTranspWindow(void); static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w); static double _time_remaining(clock_t start, char* timeChar, double percentDone); static void _run_spinup(void); +static void saveAsSpinupConditions(); +static void loadSpinupConditions(); static void _init_grid_files(void); static void _init_grid_inputs(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); @@ -583,6 +588,11 @@ void runGrid(void) } unload_cell(); // Reset the global variables + // If we used spinup we need to reset to the state of the program right after spinup. + if (InitializationMethod == INIT_WITH_SPINUP){ + loadSpinupConditions(); + } + RandSeed(SuperGlobals.randseed, &environs_rng); RandSeed(SuperGlobals.randseed, &mortality_rng); RandSeed(SuperGlobals.randseed, &resgroups_rng); @@ -876,9 +886,48 @@ static void _run_spinup(void) } /* End for each row */ unload_cell(); // Reset the global variables + // Save everything that has happened thus far. + saveAsSpinupConditions(); + DuringSpinup = FALSE; } +static void saveAsSpinupConditions(){ + // Save gridCells as spinupCells + spinupCells = gridCells; + // Nullify gridCells. This ensures we can no longer modify spinupCells on accident. + gridCells = NULL; + + // The easiest way to reallocate gridCells is reread the files. + _read_grid_setup(); // reads in grid_setup.in file + _read_files(); // reads in Stepwat_Inputs/files.in file + _init_stepwat_inputs(); // reads the stepwat inputs in + _init_grid_inputs(); // reads the grid inputs in & initializes the global grid variables +} + +static void loadSpinupConditions(){ + int row, col; + GrpIndex rg; + SppIndex sp; + + for(row = 0; row < grid_Rows; ++row){ + for(col = 0; col < grid_Cols; ++col){ + load_cell(row, col); + + ForEachSpecies(sp){ + copy_species(spinupCells[row][col].mySpecies[sp], Species[sp]); + } + + ForEachGroup(rg){ + copy_rgroup(spinupCells[row][col].myGroup[rg], RGroup[rg]); + } + + unload_cell(); + } + } + +} + /***********************************************************/ static void _init_grid_files(void) { diff --git a/ST_indivs.c b/ST_indivs.c index 1dade411..9d63f3aa 100644 --- a/ST_indivs.c +++ b/ST_indivs.c @@ -34,6 +34,7 @@ void species_Update_Kills( SppIndex sp, IntS age ); /* places; that is, they are not generally useful */ /* (like C++ friend functions) but have to be declared. */ Bool indiv_New( SppIndex sp); +void copy_individual(const IndivType* src, IndivType* dest); Bool indiv_Kill_Partial( MortalityType code, IndivType *ndv, RealF killamt); @@ -118,6 +119,30 @@ Bool indiv_New( SppIndex sp) { return( TRUE); } +/* Copy one individual's information to another individual. + Note: this does not modify either individual's linked list functionality. + Both individuals MUST be allocated. */ +void copy_individual(const IndivType* src, IndivType* dest){ + dest->id = src->id; + dest->normal_growth = src->normal_growth; + dest->pr = src->pr; + dest->prob_veggrow = src->prob_veggrow; + dest->prv_yr_relsize = src->prv_yr_relsize; + dest->relsize = src->relsize; + dest->res_avail = src->res_avail; + dest->res_extra = src->res_extra; + dest->res_required = src->res_required; + dest->slow_yrs = src->slow_yrs; + dest->yrs_neg_pr = src->yrs_neg_pr; + dest->age = src->age; + dest->growthrate = src->growthrate; + dest->grp_res_prop = src->grp_res_prop; + dest->killed = src->killed; + dest->killedby = src->killedby; + dest->mm_extra_res = src->mm_extra_res; + dest->myspecies = src->myspecies; +} + /**************************************************************/ static IndivType *_create ( void) { /*======================================================*/ diff --git a/ST_resgroups.c b/ST_resgroups.c index e39826f7..69faf93b 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -44,6 +44,7 @@ void rgroup_ResPartIndiv(void); void rgroup_DropSpecies(SppIndex sp); void rgroup_AddSpecies(GrpIndex rg, SppIndex sp); void rgroup_Extirpate(GrpIndex rg); +void copy_rgroup(const GroupType* src, GroupType* dest); /*********** Locally Used Function Declarations ************/ /***********************************************************/ @@ -976,6 +977,87 @@ void rgroup_Extirpate(GrpIndex rg) } +void copy_rgroup(const GroupType* src, GroupType* dest){ + int i; + SppIndex sp; + + // This would be very bad. + if(src == dest){ + return; + } + + /* -------------- Copy any arrays -------------- */ + Mem_Free(dest->kills); + dest->kills = (IntUS*) Mem_Calloc(GrpMaxAge(src->grp_num), sizeof(IntUS), "copy_rgroup: kills"); + for(i = 0; i < GrpMaxAge(src->grp_num); ++i){ + dest->kills[i] = src->kills[i]; + } + + Mem_Free(dest->est_spp); + dest->est_spp = (SppIndex*) Mem_Calloc(src->est_count, sizeof(SppIndex), "copy_rgroup: est_spp"); + for(i = 0; i < src->est_count; ++i){ + dest->est_spp[i] = src->est_spp[i]; + } + + /* ------------- Copy all fields --------------- */ + dest->cheatgrass_coefficient = src->cheatgrass_coefficient; + dest->depth = src->depth; + dest->est_annually = src->est_annually; + dest->est_count = src->est_count; + dest->estabs = src->estabs; + dest->extirp = src->extirp; + dest->extirpated = src->extirpated; + dest->grazingfreq_startyr = src->grazingfreq_startyr; + dest->grazingfrq = src->grazingfrq; + dest->grp_num = src->grp_num; + dest->ignition = src->ignition; + dest->killfreq = src->killfreq; + dest->killfreq_startyr = src->killfreq_startyr; + dest->killyr= src->killyr; + dest->max_age = src->max_age; + dest->max_bmass = src->max_bmass; + dest->max_density = src->max_density; + dest->max_per_sqm = src->max_per_sqm; + dest->max_spp = src->max_spp; + dest->max_spp_estab = src->max_spp_estab; + dest->max_stretch = src->max_stretch; + dest->min_res_req = src->min_res_req; + dest->mm_extra_res = src->mm_extra_res; + strcpy(dest->name, src->name); + dest->ppt_intcpt[0] = src->ppt_intcpt[0]; + dest->ppt_intcpt[1] = src->ppt_intcpt[1]; + dest->ppt_intcpt[2] = src->ppt_intcpt[2]; + dest->ppt_slope[0] = src->ppt_slope[0]; + dest->ppt_slope[1] = src->ppt_slope[1]; + dest->ppt_slope[2] = src->ppt_slope[2]; + dest->pr = src->pr; + dest->prescribedfire = src->prescribedfire; + dest->proportion_grazing = src->proportion_grazing; + dest->proportion_killed = src->proportion_killed; + dest->proportion_recovered = src->proportion_recovered; + dest->regen_ok = src->regen_ok; + dest->res_avail = src->res_avail; + dest->res_extra = src->res_extra; + dest->res_required = src->res_required; + dest->rgroupFractionOfVegTypeBiomass = src->rgroupFractionOfVegTypeBiomass; + dest->slowrate = src->slowrate; + dest->startyr = src->startyr; + dest->succulent = src->succulent; + dest->use_extra_res = src->use_extra_res; + dest->use_me = src->use_me; + dest->use_mort = src->use_mort; + dest->veg_prod_type = src->veg_prod_type; + dest->wild_fire_slope = src->wild_fire_slope; + dest->wildfire = src->wildfire; + dest->xgrow = src->xgrow; + dest->yrs_neg_pr = src->yrs_neg_pr; + + /* ---------------- Copy Species Array ----------------- */ + for(i = 0; i < SuperGlobals.max_spp_per_grp; ++i){ + dest->species[i] = src->species[i]; + } +} + /**************************************************************/ void RGroup_Kill(GrpIndex rg) { diff --git a/ST_species.c b/ST_species.c index edd1f294..6aad7c1e 100644 --- a/ST_species.c +++ b/ST_species.c @@ -41,6 +41,7 @@ void indiv_proportion_Grazing(IndivType *ndv, RealF proportionGrazing); void _delete(IndivType *ndv); void save_annual_species_relsize(void); +void copy_individual(const IndivType* src, IndivType* dest); /*------------------------------------------------------*/ /* Modular functions only used on one or two specific */ @@ -49,6 +50,7 @@ void save_annual_species_relsize(void); void species_Update_Kills(SppIndex sp, IntS age); void species_Update_Estabs(SppIndex sp, IntS num); SppIndex species_New(void); +void copy_species(const SpeciesType* src, SpeciesType* dest); /*********** Locally Used Function Declarations ************/ /***********************************************************/ @@ -252,6 +254,119 @@ SppIndex species_New(void) return i; } +/* Copy one Species' information to another Species. Note that both Species MUST be allocated. */ +void copy_species(const SpeciesType* src, SpeciesType* dest){ + int i; + IndivType *srcIndv, *destIndv, *next; + + // Error checking. If src == dest we would just end up loosing the linked list and some other variables. + if(!src || src == dest){ + return; + } + + /* ---- Reallocate and copy any arrays ---- */ + // kills + if(src->max_age > 1 && src->use_me){ + Mem_Free(dest->kills); + dest->kills = (IntUS*) Mem_Calloc(src->max_age, sizeof(IntUS), "copy_species: kills"); + for(i = 0; i < src->max_age; ++i){ + dest->kills[i] = src->kills[i]; + } + } + // seedprod + Mem_Free(dest->seedprod); + dest->seedprod = (IntUS*) Mem_Calloc(src->viable_yrs, sizeof(IntUS), "copy_species: seedprod"); + for(i = 0; i < src->viable_yrs; ++i){ + dest->seedprod[i] = src->seedprod[i]; + } + + /* ----------- Copy all fields ----------- */ + dest->allow_growth = src->allow_growth; + dest->alpha = src->alpha; + dest->ann_mort_prob = src->ann_mort_prob; + dest->beta = src->beta; + dest->cohort_surv = src->cohort_surv; + dest->disturbclass = src->disturbclass; + dest->est_count = src->est_count; + dest->estabs = src->estabs; + dest->exp_decay = src->exp_decay; + dest->extragrowth = src->extragrowth; + dest->intrin_rate = src->intrin_rate; + dest->isclonal = src->isclonal; + dest->lastyear_relsize = src->lastyear_relsize; + dest->mature_biomass = src->mature_biomass; + dest->max_age = src->max_age; + dest->max_rate = src->max_rate; + dest->max_seed_estab = src->max_seed_estab; + dest->max_slow = src->max_slow; + dest->max_vegunits = src->max_vegunits; + strcpy(dest->name, src->name); + dest->prob_veggrow[0] = src->prob_veggrow[0]; + dest->prob_veggrow[1] = src->prob_veggrow[1]; + dest->prob_veggrow[2] = src->prob_veggrow[2]; + dest->prob_veggrow[3] = src->prob_veggrow[3]; + dest->pseed = src->pseed; + dest->received_prob = src->received_prob; + dest->relseedlingsize = src->relseedlingsize; + dest->res_grp = src->res_grp; + dest->sd_H = src->sd_H; + dest->sd_Param1 = src->sd_Param1; + dest->sd_Pmax = src->sd_Pmax; + dest->sd_Pmin = src->sd_Pmin; + dest->sd_PPTdry = src->sd_PPTdry; + dest->sd_PPTwet = src->sd_PPTwet; + dest->sd_sgerm = src->sd_sgerm; + dest->sd_VT = src->sd_VT; + dest->seedbank = src->seedbank; + dest->seedling_biomass = src->seedling_biomass; + dest->seedling_estab_prob = src->seedling_estab_prob; + dest->seedling_estab_prob_old = src->seedling_estab_prob_old; + dest->sp_num = src->sp_num; + dest->tempclass = src->tempclass; + dest->use_dispersal = src->use_dispersal; + dest->use_me = src->use_me; + dest->use_temp_response = src->use_temp_response; + dest->var = src->var; + dest->viable_yrs = src->viable_yrs; + + /* ------------- DEEP Copy linked list ---------------- */ + // Destroy the old linked list + destIndv = dest->IndvHead; + while(destIndv){ + next = destIndv->Next; + Mem_Free(destIndv); + destIndv = next; + } + + srcIndv = src->IndvHead; + // If there is a list at all. + if(srcIndv){ + // Allocate a new individual + destIndv = (IndivType*) Mem_Calloc(1, sizeof(IndivType), "copy_species: individual"); + // This individual is the head of the list + dest->IndvHead = destIndv; + // Copy the individual information across + copy_individual(srcIndv, destIndv); + // Since this is the head there is nothing behind it. + destIndv->Prev = NULL; + // While there are more individuals + while(srcIndv->Next){ + // Move to the next individual in src + srcIndv = srcIndv->Next; + // Allocate the next entry in dest. + destIndv->Next = (IndivType*) Mem_Calloc(1, sizeof(IndivType), "copy_species: individual"); + // Doubly link the list before moving on. + destIndv->Next->Prev = destIndv; + // Move to the new entry + destIndv = destIndv->Next; + // copy the individual information across + copy_individual(srcIndv, destIndv); + } + // srcIndv->Next is false: we are at the end of the list. + destIndv->Next = NULL; + } +} + /**************************************************************/ static SpeciesType *_create(void) { diff --git a/testing.sagebrush.master/Grid_Inputs/grid_setup.in b/testing.sagebrush.master/Grid_Inputs/grid_setup.in index 5c7b3427..5b6a76a3 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_setup.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_setup.in @@ -3,5 +3,5 @@ 2 2 # rows cols 1 # use disturbances csv file (0 or 1)... 0 means no, 1 means yes 1 # use soils csv file (0 or 1)... 0 means no, 1 means yes -1 # use seed dispersal (0 or 1)... 0 means no, 1 means yes +0 # use seed dispersal (0 or 1)... 0 means no, 1 means yes spinup # Initialization method. Options are "spinup", "seeds", or "none" From de121d3c8e6026dc12a5bbb1154ef57950436965 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 5 Jul 2019 10:18:16 -0600 Subject: [PATCH 099/167] Continued work on Spinup (issue #300) Again this is a large commit. * In ST_functions.h I declared three new functions * In ST_environs.c I defined them: - copy_environment will copy the information from one EnvType to another. - copy_plot will copy one PlotType's info tho another PlotType. - copy_succulent will copy one SucculentType's info to another SucculentType. * In ST_grid.c I did a few things: - Moved printing of general info to new function printGeneralInfo() - added the three new copy functions to loadSpinupConditions() - Overhauled _free_spinup_memory and added it back into the program --- ST_environs.c | 43 +++++++++++++++++++++++ ST_functions.h | 3 ++ ST_grid.c | 92 +++++++++++++++++++++++--------------------------- 3 files changed, 89 insertions(+), 49 deletions(-) diff --git a/ST_environs.c b/ST_environs.c index 0a5d09ce..78ee70b8 100644 --- a/ST_environs.c +++ b/ST_environs.c @@ -60,6 +60,49 @@ void Env_Generate( void) { _make_disturbance(); } +/* Deep copy one EnvType's information to another. Note that both must be initialized + BEFORE calling this function. */ +void copy_environment(const EnvType* src, EnvType* dest){ + if(!src){ + return; + } + + dest->lyppt = src->lyppt; + dest->ppt = src->ppt; + dest->temp = src->temp; + dest->gsppt = src->gsppt; + dest->temp_reduction[0] = src->temp_reduction[0]; + dest->temp_reduction[1] = src->temp_reduction[1]; + dest->wet_dry = src->wet_dry; +} + +/* Deep copy one PlotType's information to another. Note that both must be initialized + BEFORE calling this function. */ +void copy_plot(const PlotType* src, PlotType* dest){ + if(!src){ + return; + } + + dest->disturbance = src->disturbance; + dest->disturbed = src->disturbed; + dest->pat_removed = src->pat_removed; +} + +/* Deep copy one SucculentType's information to another. Note that both must be initialized + BEFORE calling this function. */ +void copy_succulent(const SucculentType* src, SucculentType* dest){ + if(!src){ + return; + } + + dest->growth[0] = src->growth[0]; + dest->growth[1] = src->growth[1]; + dest->mort[0] = src->mort[0]; + dest->mort[1] = src->mort[1]; + dest->prob_death = src->prob_death; + dest->reduction = src->reduction; +} + /**************************************************************/ static void _make_ppt( void) { /*======================================================*/ diff --git a/ST_functions.h b/ST_functions.h index 6d1477b7..a58b1673 100644 --- a/ST_functions.h +++ b/ST_functions.h @@ -18,6 +18,9 @@ #include "ST_defines.h" void Env_Generate( void ); +void copy_environment(const EnvType* src, EnvType* dest); +void copy_plot(const PlotType* src, PlotType* dest); +void copy_succulent(const SucculentType* src, SucculentType* dest); /* See steppe_main.c for declarations of the following diff --git a/ST_grid.c b/ST_grid.c index 940cd094..51c51c09 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -253,7 +253,7 @@ PlotType *grid_Plot, *spinup_Plot; ModelType *grid_Globals, *spinup_Globals; CellType** gridCells; -CellType** spinupCells; +CellType** spinupCells = NULL; // these two variables are for storing SXW variables... also dynamically allocated/freed SXW_t *grid_SXW, *spinup_SXW; @@ -383,6 +383,7 @@ transp_t* getTranspWindow(void); static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w); static double _time_remaining(clock_t start, char* timeChar, double percentDone); +static void printGeneralInfo(void); static void _run_spinup(void); static void saveAsSpinupConditions(); static void loadSpinupConditions(); @@ -514,6 +515,26 @@ static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w) return result; } +/* Print information about the simulation to stdout. */ +static void printGeneralInfo(void){ + /* ------------------- Print some general information to stdout ----------------------- */ + printf("Number of layers: %d\n", SW_Site.n_layers); + printf("Number of iterations: %d\n", SuperGlobals.runModelIterations); + printf("Number of years: %d\n", SuperGlobals.runModelYears); + printf("Number of cells: %d\n\n", grid_Cells); + if(UseDisturbances) printf("Using grid Disturbances file.\n"); + if(UseSoils) printf("Using grid soils file\n"); + if(InitializationMethod == INIT_WITH_SEEDS){ + printf("Seeds availible for %d years at the start of the simulation.\n",sd_NYearsSeedsAvailable); + } else if(InitializationMethod == INIT_WITH_SPINUP) { + printf("Running Spinup\n"); + } + if(UseSeedDispersal){ + printf("Dispersing seeds between cells\n"); + } + /* --------------------------- END printing general info -------------------------------- */ +} + /* Runs the gridded version of the code */ void runGrid(void) { @@ -534,22 +555,7 @@ void runGrid(void) Mem_Free(SW_Soilwat.hist.file_prefix); SW_Soilwat.hist.file_prefix = NULL; - /* ------------------- Print some general information to stdout ----------------------- */ - printf("Number of layers: %d\n", SW_Site.n_layers); - printf("Number of iterations: %d\n", SuperGlobals.runModelIterations); - printf("Number of years: %d\n", SuperGlobals.runModelYears); - printf("Number of cells: %d\n\n", grid_Cells); - if(UseDisturbances) printf("Using grid Disturbances file.\n"); - if(UseSoils) printf("Using grid soils file\n"); - if(InitializationMethod == INIT_WITH_SEEDS){ - printf("Seeds availible for %d years at the start of the simulation.\n",sd_NYearsSeedsAvailable); - } else if(InitializationMethod == INIT_WITH_SPINUP) { - printf("Running Spinup\n"); - } - if(UseSeedDispersal){ - printf("Dispersing seeds between cells\n"); - } - /* --------------------------- END printing general info -------------------------------- */ + printGeneralInfo(); if (InitializationMethod == INIT_WITH_SPINUP) { _run_spinup(); // does the initial spinup @@ -711,6 +717,9 @@ void runGrid(void) } _free_grid_memory(); // free our allocated memory since we do not need it anymore + if(InitializationMethod == INIT_WITH_SPINUP) { + _free_spinup_memory(); + } } /* "Spinup" the model by running for SuperGlobals.runModelYears without seed dispersal or statistics outputs. */ @@ -922,6 +931,10 @@ static void loadSpinupConditions(){ copy_rgroup(spinupCells[row][col].myGroup[rg], RGroup[rg]); } + copy_environment(&spinupCells[row][col].myEnvironment, Env); + copy_plot(&spinupCells[row][col].myPlot, Plot); + copy_succulent(&spinupCells[row][col].mySucculent, Succulent); + unload_cell(); } } @@ -1710,7 +1723,7 @@ static void _free_spinup_globals(void) } -/***********************************************************/ +/* Free all memory allocated to the gridded mode during initialization. */ static void _free_grid_memory(void) { //frees all the memory allocated in this file ST_Grid.c (most of it is dynamically allocated in _init_grid_globals() & _load_grid_globals() functions) @@ -1746,40 +1759,21 @@ static void _free_grid_memory(void) Mem_Free(gridCells); } -/***********************************************************/ +/* Free memory allocated to spinupCells. This function should only be called once per simulation. */ static void _free_spinup_memory(void) { - // frees spinup memory - - GrpIndex c; - SppIndex s; - - _free_spinup_globals(); - - ForEachSpecies(s) - if (Species[s]->use_me) - Mem_Free(spinup_Species[s]); - ForEachGroup(c) - if (RGroup[c]->use_me) - Mem_Free(spinup_RGroup[c]); - - Mem_Free(spinup_Succulent); - Mem_Free(spinup_Env); - Mem_Free(spinup_Plot); - Mem_Free(spinup_Globals); - - Mem_Free(spinup_SXW); - Mem_Free(spinup_SW_Soilwat); - Mem_Free(spinup_SW_Site); - Mem_Free(spinup_SW_VegProd); - - if (UseSoils) - { - Mem_Free(spinup_SXW_ptrs); + // Remember where gridCells pointed. + CellType** locationOfGridCells = gridCells; + + // If spinupCells is allocated. + if(spinupCells){ + // move gridCells to point to spinupCells. This allows us to deallocate using _free_grid_memory(); + gridCells = spinupCells; + // Since we already have a function to deallocate gridCells we can use it. + _free_grid_memory(); + // And we need to reset gridCells in case it hasn't been deallocated. + gridCells = locationOfGridCells; } - - Mem_Free(soilTypes_Array); - Mem_Free(grid_SoilTypes); } /***********************************************************/ From d5c92f587b0d43fab0754900b652b8b7faf95006 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 5 Jul 2019 11:00:19 -0600 Subject: [PATCH 100/167] removed use_spinup column from grid_initSpecies.csv (issue #300) There was no reason to have this column in the file, since we can infer whether or not spinup should be used based on whether or not a species is turned on in the cell. This commit removed deprecated error checking from _run_spinup. Since the use_spinup column no longer exists the user can never make this mistake. This commit also introduces more error checking. If the user requests initialization with spinup but does not turn on any species for spinup they will be warned. --- ST_grid.c | 42 ++++++++++--------- .../Grid_Inputs/grid_initSpecies.csv | 2 +- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 51c51c09..8ff2a86b 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -743,7 +743,7 @@ static void _run_spinup(void) IntS k; /* killedany for mortality functions, temporary_storage for swapping variables */ - Bool killedany, temporary_storage, isAtLeastOneSpeciesOn; + Bool killedany, temporary_storage; DuringSpinup = TRUE; @@ -788,7 +788,6 @@ static void _run_spinup(void) if(!gridCells[i][j].mySpeciesInit.use_SpinUp){ continue; } - isAtLeastOneSpeciesOn = FALSE; load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee that ForEachGroup would iterate correctly */ @@ -803,16 +802,8 @@ static void _run_spinup(void) Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; // Swap shouldBeInitialized[sp] gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; - /* Make sure at least one species in this cell is turned on */ - if(Species[sp]->use_me) isAtLeastOneSpeciesOn = TRUE; } /* End for each species */ } /* End for each group */ - - if(!isAtLeastOneSpeciesOn){ - LogError(logfp, LOGWARN, - "Grid Cell %d %d is turned on for spinup, but none of the species in the cell are turned on.\n" - "This can be corrected in the init species file.", i, j); - } } /* End for each column */ } /* End for each row */ unload_cell(); // Reset the global variables @@ -3134,6 +3125,7 @@ static void _read_init_species(void) FILE *f; int i, j, num, cell, do_copy, copy_cell, use_SpinUp, seeds_Avail, row, col, copy_cell_row, copy_cell_col; + Bool isAnyCellOnForSpinup = FALSE; char buf[4096]; //open the file/do the reading @@ -3142,6 +3134,7 @@ static void _read_init_species(void) GetALine2(f, buf, 4096); // gets rid of the first line (since it just defines the columns)... it's only there for user readability for (i = 0; i < grid_Cells; i++) { + use_SpinUp = FALSE; row = i / grid_Cols; col = i % grid_Cols; @@ -3150,18 +3143,15 @@ static void _read_init_species(void) if (!GetALine2(f, buf, 4096)) break; - num = sscanf(buf, "%d,%d,%d,%d", &cell, &do_copy, ©_cell, - &use_SpinUp); + num = sscanf(buf, "%d,%d,%d", &cell, &do_copy, ©_cell); copy_cell_row = copy_cell / grid_Cols; copy_cell_col = copy_cell % grid_Cols; - if (num != 4) + if (num != 3) LogError(logfp, LOGFATAL, "Invalid %s file", grid_files[GRID_FILE_INIT_SPECIES]); - gridCells[row][col].mySpeciesInit.use_SpinUp = use_SpinUp; - - int stringIndex = _get_value_index(buf, ',', 4); //gets us the index of the string that is right after what we just parsed in + int stringIndex = _get_value_index(buf, ',', 3); //gets us the index of the string that is right after what we just parsed in if (do_copy == 1 && copy_cell > -1 && copy_cell < grid_Cells && cell != 0 && copy_cell < cell) @@ -3183,20 +3173,32 @@ static void _read_init_species(void) ForEachSpecies(s) { num = sscanf(&buf[stringIndex], "%d,", &seeds_Avail); - if (num != 1) - LogError(logfp, LOGFATAL, - "Invalid %s file line %d invalid species input", - grid_files[GRID_FILE_INIT_SPECIES], i + 2); + if (num != 1){ + LogError(logfp, LOGFATAL, "Invalid %s file line %d invalid species input", + grid_files[GRID_FILE_INIT_SPECIES], i + 2); + } + + if(seeds_Avail){ + use_SpinUp = TRUE; + isAnyCellOnForSpinup = TRUE; + } gridCells[row][col].mySpeciesInit.shouldBeInitialized[s] = seeds_Avail; stringIndex += _get_value_index(&buf[stringIndex], ',', 1); } + + gridCells[row][col].mySpeciesInit.use_SpinUp = use_SpinUp; } if (i != grid_Cells) LogError(logfp, LOGFATAL, "Invalid %s file, not enough cells", grid_files[GRID_FILE_INIT_SPECIES]); + if(!isAnyCellOnForSpinup){ + LogError(logfp, LOGWARN, "Initialization is on, but no species are turned on for initialization inside %s.", + grid_files[GRID_FILE_INIT_SPECIES]); + } + unload_cell(); CloseFile(&f); } diff --git a/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv b/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv index 4ad0ea15..26f3c160 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv @@ -1 +1 @@ -cell,copy_cell,copy_which,use_SpinUp,artr,trdu,cryp,amre,chen,acmi,phho,arfr,lipu,brar,vuoc,spp1,spp2,pose,koma,bogr,spcr,gusa,chvi 0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0 1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 3,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 5,1,0,0,,,,,,,,,,,,,,,,,,, 6,1,0,0,,,,,,,,,,,,,,,,,,, 7,1,0,0,,,,,,,,,,,,,,,,,,, 8,1,1,0,,,,,,,,,,,,,,,,,,, 9,1,1,0,,,,,,,,,,,,,,,,,,, 10,1,1,0,,,,,,,,,,,,,,,,,,, 11,1,1,0,,,,,,,,,,,,,,,,,,, 12,1,1,0,,,,,,,,,,,,,,,,,,, 13,1,1,0,,,,,,,,,,,,,,,,,,, 14,1,1,0,,,,,,,,,,,,,,,,,,, 15,1,2,0,,,,,,,,,,,,,,,,,,, 16,1,2,0,,,,,,,,,,,,,,,,,,, 17,1,2,0,,,,,,,,,,,,,,,,,,, 18,1,2,0,,,,,,,,,,,,,,,,,,, 19,1,2,0,,,,,,,,,,,,,,,,,,, 20,1,3,0,,,,,,,,,,,,,,,,,,, 21,1,3,0,,,,,,,,,,,,,,,,,,, 22,1,3,0,,,,,,,,,,,,,,,,,,, 23,1,3,0,,,,,,,,,,,,,,,,,,, 24,1,4,0,,,,,,,,,,,,,,,,,,, 25,1,4,0,,,,,,,,,,,,,,,,,,, 26,1,4,0,,,,,,,,,,,,,,,,,,, 27,1,4,0,,,,,,,,,,,,,,,,,,, 28,1,4,0,,,,,,,,,,,,,,,,,,, 29,1,4,0,,,,,,,,,,,,,,,,,,, 30,1,4,0,,,,,,,,,,,,,,,,,,, 31,1,4,0,,,,,,,,,,,,,,,,,,, 32,1,4,0,,,,,,,,,,,,,,,,,,, 33,1,4,0,,,,,,,,,,,,,,,,,,, 34,1,4,0,,,,,,,,,,,,,,,,,,, 35,1,4,0,,,,,,,,,,,,,,,,,,, 36,1,4,0,,,,,,,,,,,,,,,,,,, 37,1,4,0,,,,,,,,,,,,,,,,,,, 38,1,4,0,,,,,,,,,,,,,,,,,,, 39,1,4,0,,,,,,,,,,,,,,,,,,, 40,1,4,0,,,,,,,,,,,,,,,,,,, 41,1,4,0,,,,,,,,,,,,,,,,,,, 42,1,4,0,,,,,,,,,,,,,,,,,,, 43,1,4,0,,,,,,,,,,,,,,,,,,, 44,1,4,0,,,,,,,,,,,,,,,,,,, 45,1,4,0,,,,,,,,,,,,,,,,,,, 46,1,4,0,,,,,,,,,,,,,,,,,,, 47,1,4,0,,,,,,,,,,,,,,,,,,, 48,1,4,0,,,,,,,,,,,,,,,,,,, 49,1,4,0,,,,,,,,,,,,,,,,,,, 50,1,4,0,,,,,,,,,,,,,,,,,,, 51,1,4,0,,,,,,,,,,,,,,,,,,, 52,1,4,0,,,,,,,,,,,,,,,,,,, 53,1,4,0,,,,,,,,,,,,,,,,,,, 54,1,4,0,,,,,,,,,,,,,,,,,,, 55,1,4,0,,,,,,,,,,,,,,,,,,, 56,1,4,0,,,,,,,,,,,,,,,,,,, 57,1,4,0,,,,,,,,,,,,,,,,,,, 58,1,4,0,,,,,,,,,,,,,,,,,,, 59,1,4,0,,,,,,,,,,,,,,,,,,, 60,1,4,0,,,,,,,,,,,,,,,,,,, 61,1,4,0,,,,,,,,,,,,,,,,,,, 62,1,4,0,,,,,,,,,,,,,,,,,,, 63,1,4,0,,,,,,,,,,,,,,,,,,, 64,1,4,0,,,,,,,,,,,,,,,,,,, 65,1,4,0,,,,,,,,,,,,,,,,,,, 66,1,4,0,,,,,,,,,,,,,,,,,,, 67,1,4,0,,,,,,,,,,,,,,,,,,, 68,1,4,0,,,,,,,,,,,,,,,,,,, 69,1,4,0,,,,,,,,,,,,,,,,,,, 70,1,4,0,,,,,,,,,,,,,,,,,,, 71,1,4,0,,,,,,,,,,,,,,,,,,, 72,1,4,0,,,,,,,,,,,,,,,,,,, 73,1,4,0,,,,,,,,,,,,,,,,,,, 74,1,4,0,,,,,,,,,,,,,,,,,,, 75,1,4,0,,,,,,,,,,,,,,,,,,, 76,1,4,0,,,,,,,,,,,,,,,,,,, 77,1,4,0,,,,,,,,,,,,,,,,,,, 78,1,4,0,,,,,,,,,,,,,,,,,,, 79,1,4,0,,,,,,,,,,,,,,,,,,, 80,1,4,0,,,,,,,,,,,,,,,,,,, 81,1,4,0,,,,,,,,,,,,,,,,,,, 82,1,4,0,,,,,,,,,,,,,,,,,,, 83,1,4,0,,,,,,,,,,,,,,,,,,, 84,1,4,0,,,,,,,,,,,,,,,,,,, 85,1,4,0,,,,,,,,,,,,,,,,,,, 86,1,4,0,,,,,,,,,,,,,,,,,,, 87,1,4,0,,,,,,,,,,,,,,,,,,, 88,1,4,0,,,,,,,,,,,,,,,,,,, 89,1,4,0,,,,,,,,,,,,,,,,,,, 90,1,4,0,,,,,,,,,,,,,,,,,,, 91,1,4,0,,,,,,,,,,,,,,,,,,, 92,1,4,0,,,,,,,,,,,,,,,,,,, 93,1,4,0,,,,,,,,,,,,,,,,,,, 94,1,4,0,,,,,,,,,,,,,,,,,,, 95,1,4,0,,,,,,,,,,,,,,,,,,, 96,1,4,0,,,,,,,,,,,,,,,,,,, 97,1,4,0,,,,,,,,,,,,,,,,,,, 98,1,4,0,,,,,,,,,,,,,,,,,,, 99,1,4,0,,,,,,,,,,,,,,,,,,, 100,1,4,0,,,,,,,,,,,,,,,,,,, 101,1,4,0,,,,,,,,,,,,,,,,,,, 102,1,4,0,,,,,,,,,,,,,,,,,,, 103,1,4,0,,,,,,,,,,,,,,,,,,, 104,1,4,0,,,,,,,,,,,,,,,,,,, 105,1,4,0,,,,,,,,,,,,,,,,,,, 106,1,4,0,,,,,,,,,,,,,,,,,,, 107,1,4,0,,,,,,,,,,,,,,,,,,, 108,1,4,0,,,,,,,,,,,,,,,,,,, 109,1,4,0,,,,,,,,,,,,,,,,,,, 110,1,4,0,,,,,,,,,,,,,,,,,,, 111,1,4,0,,,,,,,,,,,,,,,,,,, 112,1,4,0,,,,,,,,,,,,,,,,,,, 113,1,4,0,,,,,,,,,,,,,,,,,,, 114,1,4,0,,,,,,,,,,,,,,,,,,, 115,1,4,0,,,,,,,,,,,,,,,,,,, 116,1,4,0,,,,,,,,,,,,,,,,,,, 117,1,4,0,,,,,,,,,,,,,,,,,,, 118,1,4,0,,,,,,,,,,,,,,,,,,, 119,1,4,0,,,,,,,,,,,,,,,,,,, 120,1,4,0,,,,,,,,,,,,,,,,,,, 121,1,4,0,,,,,,,,,,,,,,,,,,, 122,1,4,0,,,,,,,,,,,,,,,,,,, 123,1,4,0,,,,,,,,,,,,,,,,,,, 124,1,4,0,,,,,,,,,,,,,,,,,,, 125,1,4,0,,,,,,,,,,,,,,,,,,, 126,1,4,0,,,,,,,,,,,,,,,,,,, 127,1,4,0,,,,,,,,,,,,,,,,,,, 128,1,4,0,,,,,,,,,,,,,,,,,,, 129,1,4,0,,,,,,,,,,,,,,,,,,, 130,1,4,0,,,,,,,,,,,,,,,,,,, 131,1,4,0,,,,,,,,,,,,,,,,,,, 132,1,4,0,,,,,,,,,,,,,,,,,,, 133,1,4,0,,,,,,,,,,,,,,,,,,, 134,1,4,0,,,,,,,,,,,,,,,,,,, 135,1,4,0,,,,,,,,,,,,,,,,,,, 136,1,4,0,,,,,,,,,,,,,,,,,,, 137,1,4,0,,,,,,,,,,,,,,,,,,, 138,1,4,0,,,,,,,,,,,,,,,,,,, 139,1,4,0,,,,,,,,,,,,,,,,,,, 140,1,4,0,,,,,,,,,,,,,,,,,,, 141,1,4,0,,,,,,,,,,,,,,,,,,, 142,1,4,0,,,,,,,,,,,,,,,,,,, 143,1,4,0,,,,,,,,,,,,,,,,,,, \ No newline at end of file +cell,copy_cell,copy_which,artr,trdu,cryp,amre,chen,acmi,phho,arfr,lipu,brar,vuoc,spp1,spp2,pose,koma,bogr,spcr,gusa,chvi 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 5,1,0,,,,,,,,,,,,,,,,,,, 6,1,0,,,,,,,,,,,,,,,,,,, 7,1,0,,,,,,,,,,,,,,,,,,, 8,1,1,,,,,,,,,,,,,,,,,,, 9,1,1,,,,,,,,,,,,,,,,,,, 10,1,1,,,,,,,,,,,,,,,,,,, 11,1,1,,,,,,,,,,,,,,,,,,, 12,1,1,,,,,,,,,,,,,,,,,,, 13,1,1,,,,,,,,,,,,,,,,,,, 14,1,1,,,,,,,,,,,,,,,,,,, 15,1,2,,,,,,,,,,,,,,,,,,, 16,1,2,,,,,,,,,,,,,,,,,,, 17,1,2,,,,,,,,,,,,,,,,,,, 18,1,2,,,,,,,,,,,,,,,,,,, 19,1,2,,,,,,,,,,,,,,,,,,, 20,1,3,,,,,,,,,,,,,,,,,,, 21,1,3,,,,,,,,,,,,,,,,,,, 22,1,3,,,,,,,,,,,,,,,,,,, 23,1,3,,,,,,,,,,,,,,,,,,, 24,1,4,,,,,,,,,,,,,,,,,,, 25,1,4,,,,,,,,,,,,,,,,,,, 26,1,4,,,,,,,,,,,,,,,,,,, 27,1,4,,,,,,,,,,,,,,,,,,, 28,1,4,,,,,,,,,,,,,,,,,,, 29,1,4,,,,,,,,,,,,,,,,,,, 30,1,4,,,,,,,,,,,,,,,,,,, 31,1,4,,,,,,,,,,,,,,,,,,, 32,1,4,,,,,,,,,,,,,,,,,,, 33,1,4,,,,,,,,,,,,,,,,,,, 34,1,4,,,,,,,,,,,,,,,,,,, 35,1,4,,,,,,,,,,,,,,,,,,, 36,1,4,,,,,,,,,,,,,,,,,,, 37,1,4,,,,,,,,,,,,,,,,,,, 38,1,4,,,,,,,,,,,,,,,,,,, 39,1,4,,,,,,,,,,,,,,,,,,, 40,1,4,,,,,,,,,,,,,,,,,,, 41,1,4,,,,,,,,,,,,,,,,,,, 42,1,4,,,,,,,,,,,,,,,,,,, 43,1,4,,,,,,,,,,,,,,,,,,, 44,1,4,,,,,,,,,,,,,,,,,,, 45,1,4,,,,,,,,,,,,,,,,,,, 46,1,4,,,,,,,,,,,,,,,,,,, 47,1,4,,,,,,,,,,,,,,,,,,, 48,1,4,,,,,,,,,,,,,,,,,,, 49,1,4,,,,,,,,,,,,,,,,,,, 50,1,4,,,,,,,,,,,,,,,,,,, 51,1,4,,,,,,,,,,,,,,,,,,, 52,1,4,,,,,,,,,,,,,,,,,,, 53,1,4,,,,,,,,,,,,,,,,,,, 54,1,4,,,,,,,,,,,,,,,,,,, 55,1,4,,,,,,,,,,,,,,,,,,, 56,1,4,,,,,,,,,,,,,,,,,,, 57,1,4,,,,,,,,,,,,,,,,,,, 58,1,4,,,,,,,,,,,,,,,,,,, 59,1,4,,,,,,,,,,,,,,,,,,, 60,1,4,,,,,,,,,,,,,,,,,,, 61,1,4,,,,,,,,,,,,,,,,,,, 62,1,4,,,,,,,,,,,,,,,,,,, 63,1,4,,,,,,,,,,,,,,,,,,, 64,1,4,,,,,,,,,,,,,,,,,,, 65,1,4,,,,,,,,,,,,,,,,,,, 66,1,4,,,,,,,,,,,,,,,,,,, 67,1,4,,,,,,,,,,,,,,,,,,, 68,1,4,,,,,,,,,,,,,,,,,,, 69,1,4,,,,,,,,,,,,,,,,,,, 70,1,4,,,,,,,,,,,,,,,,,,, 71,1,4,,,,,,,,,,,,,,,,,,, 72,1,4,,,,,,,,,,,,,,,,,,, 73,1,4,,,,,,,,,,,,,,,,,,, 74,1,4,,,,,,,,,,,,,,,,,,, 75,1,4,,,,,,,,,,,,,,,,,,, 76,1,4,,,,,,,,,,,,,,,,,,, 77,1,4,,,,,,,,,,,,,,,,,,, 78,1,4,,,,,,,,,,,,,,,,,,, 79,1,4,,,,,,,,,,,,,,,,,,, 80,1,4,,,,,,,,,,,,,,,,,,, 81,1,4,,,,,,,,,,,,,,,,,,, 82,1,4,,,,,,,,,,,,,,,,,,, 83,1,4,,,,,,,,,,,,,,,,,,, 84,1,4,,,,,,,,,,,,,,,,,,, 85,1,4,,,,,,,,,,,,,,,,,,, 86,1,4,,,,,,,,,,,,,,,,,,, 87,1,4,,,,,,,,,,,,,,,,,,, 88,1,4,,,,,,,,,,,,,,,,,,, 89,1,4,,,,,,,,,,,,,,,,,,, 90,1,4,,,,,,,,,,,,,,,,,,, 91,1,4,,,,,,,,,,,,,,,,,,, 92,1,4,,,,,,,,,,,,,,,,,,, 93,1,4,,,,,,,,,,,,,,,,,,, 94,1,4,,,,,,,,,,,,,,,,,,, 95,1,4,,,,,,,,,,,,,,,,,,, 96,1,4,,,,,,,,,,,,,,,,,,, 97,1,4,,,,,,,,,,,,,,,,,,, 98,1,4,,,,,,,,,,,,,,,,,,, 99,1,4,,,,,,,,,,,,,,,,,,, 100,1,4,,,,,,,,,,,,,,,,,,, 101,1,4,,,,,,,,,,,,,,,,,,, 102,1,4,,,,,,,,,,,,,,,,,,, 103,1,4,,,,,,,,,,,,,,,,,,, 104,1,4,,,,,,,,,,,,,,,,,,, 105,1,4,,,,,,,,,,,,,,,,,,, 106,1,4,,,,,,,,,,,,,,,,,,, 107,1,4,,,,,,,,,,,,,,,,,,, 108,1,4,,,,,,,,,,,,,,,,,,, 109,1,4,,,,,,,,,,,,,,,,,,, 110,1,4,,,,,,,,,,,,,,,,,,, 111,1,4,,,,,,,,,,,,,,,,,,, 112,1,4,,,,,,,,,,,,,,,,,,, 113,1,4,,,,,,,,,,,,,,,,,,, 114,1,4,,,,,,,,,,,,,,,,,,, 115,1,4,,,,,,,,,,,,,,,,,,, 116,1,4,,,,,,,,,,,,,,,,,,, 117,1,4,,,,,,,,,,,,,,,,,,, 118,1,4,,,,,,,,,,,,,,,,,,, 119,1,4,,,,,,,,,,,,,,,,,,, 120,1,4,,,,,,,,,,,,,,,,,,, 121,1,4,,,,,,,,,,,,,,,,,,, 122,1,4,,,,,,,,,,,,,,,,,,, 123,1,4,,,,,,,,,,,,,,,,,,, 124,1,4,,,,,,,,,,,,,,,,,,, 125,1,4,,,,,,,,,,,,,,,,,,, 126,1,4,,,,,,,,,,,,,,,,,,, 127,1,4,,,,,,,,,,,,,,,,,,, 128,1,4,,,,,,,,,,,,,,,,,,, 129,1,4,,,,,,,,,,,,,,,,,,, 130,1,4,,,,,,,,,,,,,,,,,,, 131,1,4,,,,,,,,,,,,,,,,,,, 132,1,4,,,,,,,,,,,,,,,,,,, 133,1,4,,,,,,,,,,,,,,,,,,, 134,1,4,,,,,,,,,,,,,,,,,,, 135,1,4,,,,,,,,,,,,,,,,,,, 136,1,4,,,,,,,,,,,,,,,,,,, 137,1,4,,,,,,,,,,,,,,,,,,, 138,1,4,,,,,,,,,,,,,,,,,,, 139,1,4,,,,,,,,,,,,,,,,,,, 140,1,4,,,,,,,,,,,,,,,,,,, 141,1,4,,,,,,,,,,,,,,,,,,, 142,1,4,,,,,,,,,,,,,,,,,,, 143,1,4,,,,,,,,,,,,,,,,,,, \ No newline at end of file From f30821e0af549b41b00f8e386ba922bf1758bb47 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 5 Jul 2019 14:02:39 -0600 Subject: [PATCH 101/167] Updated grid_disturbances.in (issue #252) This commit added ignition, cheatgrass_coefficient and wildfire_slope to the disturbances.in file. I also cleaned up the function a little bit. --- ST_grid.c | 35 ++++++++----------- .../Grid_Inputs/grid_disturbances.csv | 2 +- 2 files changed, 15 insertions(+), 22 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 8ff2a86b..e8e62e89 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -385,8 +385,8 @@ static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w); static double _time_remaining(clock_t start, char* timeChar, double percentDone); static void printGeneralInfo(void); static void _run_spinup(void); -static void saveAsSpinupConditions(); -static void loadSpinupConditions(); +static void saveAsSpinupConditions(void); +static void loadSpinupConditions(void); static void _init_grid_files(void); static void _init_grid_inputs(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); @@ -581,8 +581,10 @@ void runGrid(void) */ sprintf(SW_Weather.name_prefix, "%s", SW_prefix_permanent); //updates the directory correctly for the weather files so soilwat can find them - if (BmassFlags.yearly || MortFlags.yearly) + if (BmassFlags.yearly || MortFlags.yearly){ parm_Initialize(); + _init_grid_inputs(); + } // Initialize the plot for each grid cell for (i = 0; i < grid_Rows; i++){ @@ -2084,7 +2086,7 @@ static void _read_disturbances_in(void) FILE *f; char buf[1024]; - int i, row, col, cell, num = 0, choices[3]; + int i, row, col, cell, num = 0; GrpIndex rg; f = OpenFile(grid_files[GRID_FILE_DISTURBANCES], "r"); @@ -2100,24 +2102,15 @@ static void _read_disturbances_in(void) if (!GetALine2(f, buf, 1024)) break; - // xgrow and veg_prod_type not found in grid_disturbances.csv - ForEachGroup(rg) - num = sscanf(buf, "%d,%d,%d,%d,%hd,%f,%hd,%hd,%hu,%hd", &cell, - &choices[0], &choices[1], - &choices[2], &RGroup[rg]->killyr, - &RGroup[rg]->killfreq, &RGroup[rg]->extirp, - &RGroup[rg]->killfreq_startyr, - &RGroup[rg]->grazingfrq, &RGroup[rg]->grazingfreq_startyr); - - // Comes from _load_grid_globals - if (UseDisturbances) { - Globals->pat.use = choices[0]; - Globals->mound.use = choices[1]; - Globals->burrow.use = choices[2]; - } + ForEachGroup(rg) { + num = sscanf(buf, "%d,%d,%d,%d,%d,%d,%f,%d,%d,%d,%f,%f,%f", &cell, + &Globals->pat.use, &Globals->mound.use, &Globals->burrow.use, &RGroup[rg]->killyr, + &RGroup[rg]->killfreq_startyr, &RGroup[rg]->killfreq, &RGroup[rg]->extirp, + &RGroup[rg]->grazingfrq, &RGroup[rg]->grazingfreq_startyr, &RGroup[rg]->ignition, + &RGroup[rg]->cheatgrass_coefficient, &RGroup[rg]->wild_fire_slope); + } - // xgrow and veg_prod_type not found in grid_disturbances.csv - if (num != 10) + if (num != 13) LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", grid_files[GRID_FILE_DISTURBANCES], i + 2); } diff --git a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv index ef15644f..f5141a0b 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv @@ -1 +1 @@ -cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfrq,extirp,killfreq_startyr,grazing_frq,grazingfrq_startyr 0,0,0,0,0,0,0,0,0,0 1,0,0,0,0,0,0,0,0,0 2,0,0,0,0,0,0,0,0,0 3,0,0,0,0,0,0,0,0,0 4,0,0,0,0,0,0,0,0,0 5,0,0,0,0,0,0,0,0,0 6,0,0,0,0,0,0,0,0,0 7,0,0,0,0,0,0,0,0,0 8,0,0,0,0,0,0,0,0,0 9,0,0,0,0,0,0,0,0,0 10,0,0,0,0,0,0,0,0,0 11,0,0,0,0,0,0,0,0,0 12,0,0,0,0,0,0,0,0,0 13,0,0,0,0,0,0,0,0,0 14,0,0,0,0,0,0,0,0,0 15,0,0,0,0,0,0,0,0,0 16,0,0,0,0,0,0,0,0,0 17,0,0,0,0,0,0,0,0,0 18,0,0,0,0,0,0,0,0,0 19,0,0,0,0,0,0,0,0,0 20,0,0,0,0,0,0,0,0,0 21,0,0,0,0,0,0,0,0,0 22,0,0,0,0,0,0,0,0,0 23,0,0,0,0,0,0,0,0,0 24,0,0,0,0,0,0,0,0,0 25,0,0,0,0,0,0,0,0,0 26,0,0,0,0,0,0,0,0,0 27,0,0,0,0,0,0,0,0,0 28,0,0,0,0,0,0,0,0,0 29,0,0,0,0,0,0,0,0,0 30,0,0,0,0,0,0,0,0,0 31,0,0,0,0,0,0,0,0,0 32,0,0,0,0,0,0,0,0,0 33,0,0,0,0,0,0,0,0,0 34,0,0,0,0,0,0,0,0,0 35,0,0,0,0,0,0,0,0,0 36,0,0,0,0,0,0,0,0,0 37,0,0,0,0,0,0,0,0,0 38,0,0,0,0,0,0,0,0,0 39,0,0,0,0,0,0,0,0,0 40,0,0,0,0,0,0,0,0,0 41,0,0,0,0,0,0,0,0,0 42,0,0,0,0,0,0,0,0,0 43,0,0,0,0,0,0,0,0,0 44,0,0,0,0,0,0,0,0,0 45,0,0,0,0,0,0,0,0,0 46,0,0,0,0,0,0,0,0,0 47,0,0,0,0,0,0,0,0,0 48,0,0,0,0,0,0,0,0,0 49,0,0,0,0,0,0,0,0,0 50,0,0,0,0,0,0,0,0,0 51,0,0,0,0,0,0,0,0,0 52,0,0,0,0,0,0,0,0,0 53,0,0,0,0,0,0,0,0,0 54,0,0,0,0,0,0,0,0,0 55,0,0,0,0,0,0,0,0,0 56,0,0,0,0,0,0,0,0,0 57,0,0,0,0,0,0,0,0,0 58,0,0,0,0,0,0,0,0,0 59,0,0,0,0,0,0,0,0,0 60,0,0,0,0,0,0,0,0,0 61,0,0,0,0,0,0,0,0,0 62,0,0,0,0,0,0,0,0,0 63,0,0,0,0,0,0,0,0,0 64,0,0,0,0,0,0,0,0,0 65,0,0,0,0,0,0,0,0,0 66,0,0,0,0,0,0,0,0,0 67,0,0,0,0,0,0,0,0,0 68,0,0,0,0,0,0,0,0,0 69,0,0,0,0,0,0,0,0,0 70,0,0,0,0,0,0,0,0,0 71,0,0,0,0,0,0,0,0,0 72,0,0,0,0,0,0,0,0,0 73,0,0,0,0,0,0,0,0,0 74,0,0,0,0,0,0,0,0,0 75,0,0,0,0,0,0,0,0,0 76,0,0,0,0,0,0,0,0,0 77,0,0,0,0,0,0,0,0,0 78,0,0,0,0,0,0,0,0,0 79,0,0,0,0,0,0,0,0,0 80,0,0,0,0,0,0,0,0,0 81,0,0,0,0,0,0,0,0,0 82,0,0,0,0,0,0,0,0,0 83,0,0,0,0,0,0,0,0,0 84,0,0,0,0,0,0,0,0,0 85,0,0,0,0,0,0,0,0,0 86,0,0,0,0,0,0,0,0,0 87,0,0,0,0,0,0,0,0,0 88,0,0,0,0,0,0,0,0,0 89,0,0,0,0,0,0,0,0,0 90,0,0,0,0,0,0,0,0,0 91,0,0,0,0,0,0,0,0,0 92,0,0,0,0,0,0,0,0,0 93,0,0,0,0,0,0,0,0,0 94,0,0,0,0,0,0,0,0,0 95,0,0,0,0,0,0,0,0,0 96,0,0,0,0,0,0,0,0,0 97,0,0,0,0,0,0,0,0,0 98,0,0,0,0,0,0,0,0,0 99,0,0,0,0,0,0,0,0,0 100,0,0,0,0,0,0,0,0,0 101,0,0,0,0,0,0,0,0,0 102,0,0,0,0,0,0,0,0,0 103,0,0,0,0,0,0,0,0,0 104,0,0,0,0,0,0,0,0,0 105,0,0,0,0,0,0,0,0,0 106,0,0,0,0,0,0,0,0,0 107,0,0,0,0,0,0,0,0,0 108,0,0,0,0,0,0,0,0,0 109,0,0,0,0,0,0,0,0,0 110,0,0,0,0,0,0,0,0,0 111,0,0,0,0,0,0,0,0,0 112,0,0,0,0,0,0,0,0,0 113,0,0,0,0,0,0,0,0,0 114,0,0,0,0,0,0,0,0,0 115,0,0,0,0,0,0,0,0,0 116,0,0,0,0,0,0,0,0,0 117,0,0,0,0,0,0,0,0,0 118,0,0,0,0,0,0,0,0,0 119,0,0,0,0,0,0,0,0,0 120,0,0,0,0,0,0,0,0,0 121,0,0,0,0,0,0,0,0,0 122,0,0,0,0,0,0,0,0,0 123,0,0,0,0,0,0,0,0,0 124,0,0,0,0,0,0,0,0,0 125,0,0,0,0,0,0,0,0,0 126,0,0,0,0,0,0,0,0,0 127,0,0,0,0,0,0,0,0,0 128,0,0,0,0,0,0,0,0,0 129,0,0,0,0,0,0,0,0,0 130,0,0,0,0,0,0,0,0,0 131,0,0,0,0,0,0,0,0,0 132,0,0,0,0,0,0,0,0,0 133,0,0,0,0,0,0,0,0,0 134,0,0,0,0,0,0,0,0,0 135,0,0,0,0,0,0,0,0,0 136,0,0,0,0,0,0,0,0,0 137,0,0,0,0,0,0,0,0,0 138,0,0,0,0,0,0,0,0,0 139,0,0,0,0,0,0,0,0,0 140,0,0,0,0,0,0,0,0,0 141,0,0,0,0,0,0,0,0,0 142,0,0,0,0,0,0,0,0,0 143,0,0,0,0,0,0,0,0,0 \ No newline at end of file +cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfreq_startyr,Prescribed_killfreq,extirp,grazing_frq,grazingfrq_startyr,ignition,cheatgrass_coefficient,wildfire_slope 0,0,0,0,0,0,0,0,0,0,12.05,-0.117,0.0093 1,0,0,0,0,5,30,0,0,0,0,-0.117,0.0093 2,0,0,0,0,0,0,0,0,0,12.05,-0.117,0.0093 3,0,0,0,0,1,100,0,0,0,0,-0.117,0.0093 4,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 5,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 6,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 7,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 8,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 9,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 10,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 11,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 12,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 13,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 14,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 15,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 16,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 17,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 18,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 19,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 20,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 21,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 22,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 23,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 24,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 25,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 26,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 27,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 28,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 29,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 30,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 31,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 32,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 33,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 34,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 35,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 36,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 37,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 38,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 39,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 40,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 41,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 42,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 43,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 44,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 45,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 46,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 47,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 48,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 49,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 50,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 51,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 52,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 53,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 54,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 55,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 56,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 57,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 58,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 59,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 60,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 61,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 62,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 63,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 64,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 65,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 66,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 67,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 68,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 69,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 70,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 71,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 72,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 73,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 74,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 75,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 76,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 77,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 78,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 79,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 80,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 81,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 82,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 83,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 84,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 85,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 86,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 87,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 88,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 89,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 90,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 91,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 92,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 93,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 94,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 95,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 96,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 97,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 98,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 99,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 100,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 101,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 102,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 103,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 104,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 105,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 106,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 107,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 108,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 109,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 110,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 111,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 112,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 113,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 114,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 115,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 116,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 117,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 118,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 119,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 120,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 121,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 122,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 123,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 124,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 125,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 126,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 127,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 128,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 129,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 130,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 131,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 132,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 133,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 134,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 135,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 136,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 137,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 138,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 139,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 140,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 141,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 142,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 143,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 \ No newline at end of file From 6803c7126b2ffb8fdd506980a575a9191af7bb78 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 8 Jul 2019 09:36:41 -0600 Subject: [PATCH 102/167] Removed unused functions (issue #311) See comments on the issue for descriptions of all of the functions removed. --- ST_grid.c | 731 ------------------------------------------------------ 1 file changed, 731 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index e8e62e89..3b5f15ef 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -392,18 +392,13 @@ static void _init_grid_inputs(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); static void _init_stepwat_inputs(void); static void _init_grid_globals(void); -static void _init_spinup_globals(void); static void allocate_gridCells(int rows, int cols); static void allocate_accumulators(void); -static void _load_grid_globals(void); static void _free_grid_memory(void); static void _free_spinup_memory(void); -static void _free_grid_globals(void); -static void _free_spinup_globals(void); static void _load_cell(int row, int col, int year, Bool useAccumulators); static void load_cell(int row, int col); static void unload_cell(void); -static void _load_spinup_cell(int cell); static void _read_disturbances_in(void); static void _read_soils_in(void); static void _init_soil_layers(int cell, int isSpinup); @@ -412,12 +407,7 @@ static float _read_a_float(FILE *f, char *buf, const char *filename, static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); static void _read_seed_dispersal_in(void); static void _do_seed_dispersal(void); -static void _kill_groups_and_species(void); -static int _do_grid_disturbances(int row, int col); static void _read_init_species(void); -static void _do_groups_and_species_extirpate(void); -static void _do_grid_proportion_Recovery(int row, int col); -static void _do_grid_grazing_EndOfYear(int row, int col); static IndivType* _create_empty_indv(void); //these 5 functions are used for copying/freeing the linked list of individuals correctly... static void _free_individuals(IndivType *head); @@ -1340,382 +1330,6 @@ static void _init_grid_globals(void) "_init_grid_globals()"); } -/***********************************************************/ -static void _init_spinup_globals(void) -{ - //initializes spinup variables, allocating the memory necessary for them (this step is only needed to be done once) - - GrpIndex c; - SppIndex s; - - spinup_Succulent = Mem_Calloc(nSoilTypes, sizeof(SucculentType), - "_init_spinup_globals()"); - spinup_Env = Mem_Calloc(nSoilTypes, sizeof(EnvType), - "_init_spinup_globals()"); - spinup_Plot = Mem_Calloc(nSoilTypes, sizeof(PlotType), - "_init_spinup_globals()"); - spinup_Globals = Mem_Calloc(nSoilTypes, sizeof(ModelType), - "_init_spinup_globals()"); - - ForEachSpecies(s) - if (Species[s]->use_me) - spinup_Species[s] = Mem_Calloc(nSoilTypes, sizeof(SpeciesType), - "_init_spinup_globals()"); - ForEachGroup(c) - if (RGroup[c]->use_me) - spinup_RGroup[c] = Mem_Calloc(nSoilTypes, sizeof(GroupType), - "_init_spinup_globals()"); - - spinup_SXW = Mem_Calloc(nSoilTypes, sizeof(SXW_t), - "_init_spinup_globals()"); - spinup_SW_Soilwat = Mem_Calloc(nSoilTypes, sizeof(SW_SOILWAT), - "_init_spinup_globals()"); - spinup_SW_Site = Mem_Calloc(nSoilTypes, sizeof(SW_SITE), - "_init_spinup_globals()"); - spinup_SW_VegProd = Mem_Calloc(nSoilTypes, sizeof(SW_VEGPROD), - "_init_spinup_globals()"); - if (UseSoils) - { - spinup_SXW_ptrs = Mem_Calloc(nSoilTypes, sizeof(Grid_SXW_St), - "_init_spinup_globals()"); - } -} - -/***********************************************************/ -static void _load_grid_globals(void) -{ - //this initializes/allocates memory needed... this step is needed to be done for every iteration - - int i, j, k; - GrpIndex c; - SppIndex s; - - if (UseSoils) - ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); //change the directory for _init_soil_layers() - for (i = 0; i < grid_Cells; i++) - { - - ForEachSpecies(s) - { //macros defined in ST_defines.h - if (!Species[s]->use_me) - continue; - grid_Species[s][i] = *Species[s]; - - grid_Species[s][i].kills = Mem_Calloc(Species[s]->max_age, - sizeof(IntUS), "_init_grid_globals()"); - grid_Species[s][i].seedprod = Mem_Calloc(Species[s]->viable_yrs, - sizeof(RealF), "_init_grid_globals()"); - - memcpy(grid_Species[s][i].kills, Species[s]->kills, - Species[s]->max_age * sizeof(IntUS)); - memcpy(grid_Species[s][i].seedprod, Species[s]->seedprod, - Species[s]->viable_yrs * sizeof(RealF)); - - grid_Species[s][i].IndvHead = _copy_head(Species[s]->IndvHead); //copy_head() deep copies the structure (allocating memory when needed)... it will even allocate memory for the head of the list - } - - ForEachGroup(c) - { - if (!RGroup[c]->use_me) - continue; - grid_RGroup[c][i] = *RGroup[c]; - grid_RGroup[c][i].kills = Mem_Calloc(RGroup[c]->max_age, - sizeof(IntUS), "_init_grid_globals()"); - - memcpy(grid_RGroup[c][i].kills, RGroup[c]->kills, - RGroup[c]->max_age * sizeof(IntUS)); - if (UseDisturbances) - { - grid_RGroup[c][i].killyr = grid_Disturb[i].kill_yr; - grid_RGroup[c][i].killfreq = grid_Disturb[i].killfrq; - grid_RGroup[c][i].extirp = grid_Disturb[i].extirp; - } - } - - grid_Succulent[i] = *Succulent; - grid_Env[i] = *Env; - grid_Plot[i] = *Plot; - grid_Globals[i] = *Globals; - - if (UseDisturbances) - { - grid_Globals[i].pat.use = grid_Disturb[i].choices[0]; - grid_Globals[i].mound.use = grid_Disturb[i].choices[1]; - grid_Globals[i].burrow.use = grid_Disturb[i].choices[2]; - } - if (UseSoils) - _init_soil_layers(i, 0); - - grid_SXW[i] = *SXW; - - grid_SXW[i].f_roots = Str_Dup(SXW->f_roots); - grid_SXW[i].f_phen = Str_Dup(SXW->f_phen); - grid_SXW[i].f_bvt = Str_Dup(SXW->f_bvt); - grid_SXW[i].f_prod = Str_Dup(SXW->f_prod); - grid_SXW[i].f_watin = Str_Dup(SXW->f_watin); - - grid_SXW[i].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_init_grid_globals()"); - ForEachVegType(k) { - grid_SXW[i].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_init_grid_globals()"); - } - grid_SXW[i].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), - "_init_grid_globals()"); - - memcpy(grid_SXW[i].transpTotal, SXW->transpTotal, - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - ForEachVegType(k) { - memcpy(grid_SXW[i].transpVeg[k], SXW->transpVeg[k], - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - } - memcpy(grid_SXW[i].swc, SXW->swc, - SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); - - grid_SW_Soilwat[i] = SW_Soilwat; - grid_SW_Site[i] = SW_Site; - grid_SW_VegProd[i] = SW_VegProd; - - grid_SW_Site[i].lyr = Mem_Calloc( - SW_Site.n_layers + SW_Site.deepdrain, - sizeof(SW_LAYER_INFO *), "_init_grid_globals()"); - for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) - { - grid_SW_Site[i].lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_init_grid_globals()"); - memcpy(grid_SW_Site[i].lyr[j], SW_Site.lyr[j], - sizeof(SW_LAYER_INFO)); - } - } - if (UseSoils) - ChDir(".."); //get back to our previous directory - -} - -/***********************************************************/ -static void _load_spinup_globals(void) -{ - //this initializes/allocates memory needed... this step is needed to be done for every iteration - - int i, j, k; - GrpIndex c; - SppIndex s; - - if (UseSoils) - ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); //change the directory for _init_soil_layers() - for (i = 0; i < nSoilTypes; i++) - { - - int cell = soilTypes_Array[i]; //this is the cell number of the first cell representing this soil type - - ForEachSpecies(s) - { //macros defined in ST_defines.h - if (!Species[s]->use_me) - continue; - spinup_Species[s][i] = *Species[s]; - - spinup_Species[s][i].kills = Mem_Calloc(Species[s]->max_age, - sizeof(IntUS), "_init_spinup_globals()"); - spinup_Species[s][i].seedprod = Mem_Calloc(Species[s]->viable_yrs, - sizeof(RealF), "_init_spinup_globals()"); - - memcpy(spinup_Species[s][i].kills, Species[s]->kills, - Species[s]->max_age * sizeof(IntUS)); - memcpy(spinup_Species[s][i].seedprod, Species[s]->seedprod, - Species[s]->viable_yrs * sizeof(RealF)); - - spinup_Species[s][i].IndvHead = _copy_head(Species[s]->IndvHead); //copy_head() deep copies the structure (allocating memory when needed)... it will even allocate memory for the head of the list - } - - ForEachGroup(c) - { - if (!RGroup[c]->use_me) - continue; - spinup_RGroup[c][i] = *RGroup[c]; - spinup_RGroup[c][i].kills = Mem_Calloc(RGroup[c]->max_age, - sizeof(IntUS), "_init_spinup_globals()"); - - memcpy(spinup_RGroup[c][i].kills, RGroup[c]->kills, - RGroup[c]->max_age * sizeof(IntUS)); - if (UseDisturbances) - { - spinup_RGroup[c][i].killyr = grid_Disturb[cell].kill_yr; - spinup_RGroup[c][i].killfreq = grid_Disturb[cell].killfrq; - spinup_RGroup[c][i].extirp = grid_Disturb[cell].extirp; - } - } - - spinup_Succulent[i] = *Succulent; - spinup_Env[i] = *Env; - spinup_Plot[i] = *Plot; - spinup_Globals[i] = *Globals; - - if (UseDisturbances) - { - spinup_Globals[i].pat.use = grid_Disturb[cell].choices[0]; - spinup_Globals[i].mound.use = grid_Disturb[cell].choices[1]; - spinup_Globals[i].burrow.use = grid_Disturb[cell].choices[2]; - } - if (UseSoils) //TODO: DM should i be cell value after lookup from soilTypes_Array - _init_soil_layers(i, 1); - - spinup_SXW[i] = *SXW; - - spinup_SXW[i].f_roots = Str_Dup(SXW->f_roots); - spinup_SXW[i].f_phen = Str_Dup(SXW->f_phen); - spinup_SXW[i].f_bvt = Str_Dup(SXW->f_bvt); - spinup_SXW[i].f_prod = Str_Dup(SXW->f_prod); - spinup_SXW[i].f_watin = Str_Dup(SXW->f_watin); - - spinup_SXW[i].transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_init_spinup_globals()"); - ForEachVegType(k) { - spinup_SXW[i].transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealD), "_init_grid_globals()"); - } - spinup_SXW[i].swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, - sizeof(RealF), "_init_grid_globals()"); - - memcpy(spinup_SXW[i].transpTotal, SXW->transpTotal, - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - ForEachVegType(k) { - memcpy(spinup_SXW[i].transpVeg[k], SXW->transpVeg[k], - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - } - memcpy(spinup_SXW[i].swc, SXW->swc, - SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); - - spinup_SW_Soilwat[i] = SW_Soilwat; - spinup_SW_Site[i] = SW_Site; - spinup_SW_VegProd[i] = SW_VegProd; - - spinup_SW_Site[i].lyr = Mem_Calloc( - SW_Site.n_layers + SW_Site.deepdrain, - sizeof(SW_LAYER_INFO *), "_init_grid_globals()"); - for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) - { - spinup_SW_Site[i].lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_init_grid_globals()"); - memcpy(spinup_SW_Site[i].lyr[j], SW_Site.lyr[j], - sizeof(SW_LAYER_INFO)); - } - } - if (UseSoils) - ChDir(".."); //get back to our previous directory - -} - -/***********************************************************/ -static void _free_grid_globals(void) -{ - //frees memory allocated in _load_grid_globals() function. - int i, j, k; - GrpIndex c; - SppIndex s; - - for (i = 0; i < grid_Cells; i++) - { - - ForEachSpecies(s) - { - if (!Species[s]->use_me) - continue; - Mem_Free(grid_Species[s][i].kills); - Mem_Free(grid_Species[s][i].seedprod); - _free_head(grid_Species[s][i].IndvHead); - } - - ForEachGroup(c) - if (RGroup[c]->use_me) - Mem_Free(grid_RGroup[c][i].kills); - - Mem_Free(grid_SXW[i].f_roots); - Mem_Free(grid_SXW[i].f_phen); - Mem_Free(grid_SXW[i].f_bvt); - Mem_Free(grid_SXW[i].f_prod); - Mem_Free(grid_SXW[i].f_watin); - Mem_Free(grid_SXW[i].transpTotal); - ForEachVegType(k) { - Mem_Free(grid_SXW[i].transpVeg[k]); - } - Mem_Free(grid_SXW[i].swc); - if (UseSoils) - { - Mem_Free(grid_SXW_ptrs[i].roots_max); - Mem_Free(grid_SXW_ptrs[i].rootsXphen); - Mem_Free(grid_SXW_ptrs[i].roots_active); - Mem_Free(grid_SXW_ptrs[i].roots_active_rel); - Mem_Free(grid_SXW_ptrs[i].roots_active_sum); - Mem_Free(grid_SXW_ptrs[i].phen); - Mem_Free(grid_SXW_ptrs[i].prod_bmass); - Mem_Free(grid_SXW_ptrs[i].prod_pctlive); - } - - for (j = 0; - j < grid_SW_Site[i].n_layers + grid_SW_Site[i].deepdrain; - j++) - Mem_Free(grid_SW_Site[i].lyr[j]); - Mem_Free(grid_SW_Site[i].lyr); - - } - -} - -/***********************************************************/ -static void _free_spinup_globals(void) -{ - //frees memory allocated in _load_spinup_globals() function. - int i, j, k; - GrpIndex c; - SppIndex s; - - for (i = 0; i < nSoilTypes; i++) - { - - ForEachSpecies(s) - { - if (!Species[s]->use_me) - continue; - Mem_Free(spinup_Species[s][i].kills); - Mem_Free(spinup_Species[s][i].seedprod); - _free_head(spinup_Species[s][i].IndvHead); - } - - ForEachGroup(c) - if (RGroup[c]->use_me) - Mem_Free(spinup_RGroup[c][i].kills); - - Mem_Free(spinup_SXW[i].f_roots); - Mem_Free(spinup_SXW[i].f_phen); - Mem_Free(spinup_SXW[i].f_bvt); - Mem_Free(spinup_SXW[i].f_prod); - Mem_Free(spinup_SXW[i].f_watin); - Mem_Free(spinup_SXW[i].transpTotal); - ForEachVegType(k) { - Mem_Free(spinup_SXW[i].transpVeg[k]); - } - Mem_Free(spinup_SXW[i].swc); - if (UseSoils) - { - Mem_Free(spinup_SXW_ptrs[i].roots_max); - Mem_Free(spinup_SXW_ptrs[i].rootsXphen); - Mem_Free(spinup_SXW_ptrs[i].roots_active); - Mem_Free(spinup_SXW_ptrs[i].roots_active_rel); - Mem_Free(spinup_SXW_ptrs[i].roots_active_sum); - Mem_Free(spinup_SXW_ptrs[i].phen); - Mem_Free(spinup_SXW_ptrs[i].prod_bmass); - Mem_Free(spinup_SXW_ptrs[i].prod_pctlive); - } - - for (j = 0; - j < spinup_SW_Site[i].n_layers + spinup_SW_Site[i].deepdrain; - j++) - Mem_Free(spinup_SW_Site[i].lyr[j]); - Mem_Free(spinup_SW_Site[i].lyr); - } - -} - /* Free all memory allocated to the gridded mode during initialization. */ static void _free_grid_memory(void) { @@ -1944,115 +1558,6 @@ static void unload_cell(){ copy_sxw_variables(NULL,NULL,NULL); } -/***********************************************************/ -static void _load_spinup_cell(int cell) -{ - // loads the specified cell into the global variables (from the spinup) - - int j, k; - GrpIndex c; - SppIndex s; - - ForEachSpecies(s) - { - if (!Species[s]->use_me) - continue; - - Mem_Free(Species[s]->kills); - Mem_Free(Species[s]->seedprod); - _free_head(Species[s]->IndvHead); //free_head() frees the memory allocated by the head and the memory allocated by each part of the linked list - - *Species[s] = spinup_Species[s][cell]; - - Species[s]->kills = Mem_Calloc(spinup_Species[s][cell].max_age, - sizeof(IntUS), "_load_spinup_cell(Species[s]->kills)"); - Species[s]->seedprod = Mem_Calloc(spinup_Species[s][cell].viable_yrs, - sizeof(RealF), "_load_spinup_cell(Species[s]->seedprod)"); - - memcpy(Species[s]->kills, spinup_Species[s][cell].kills, - spinup_Species[s][cell].max_age * sizeof(IntUS)); - memcpy(Species[s]->seedprod, spinup_Species[s][cell].seedprod, - spinup_Species[s][cell].viable_yrs * sizeof(RealF)); - Species[s]->IndvHead = _copy_head(spinup_Species[s][cell].IndvHead); //copy_head() deep copies the linked list structure (allocating memory when needed)... it will even allocate memory for the head of the list - - } - - ForEachGroup(c) - { - if (!RGroup[c]->use_me) - continue; - Mem_Free(RGroup[c]->kills); //kills is the only pointer in the resourcegroup_st struct (which is what RGroup is defined as)... we need to free it then reallocate it then memcpy it to get the deep copy we want - - *RGroup[c] = spinup_RGroup[c][cell]; //does a shallow copy, we have to do the freeing/malloc/memcpy to deep copy (ie copy the values in the pointers instead of the addresses) the pointers. A shallow copy will copy over the values for every non-pointer (C itself does not inherently know how to deep copy, so we must code this behaviour). - - RGroup[c]->kills = Mem_Calloc(spinup_RGroup[c][cell].max_age, - sizeof(IntUS), "_load_spinup_cell(RGroup[c]->kills"); - memcpy(RGroup[c]->kills, spinup_RGroup[c][cell].kills, - spinup_RGroup[c][cell].max_age * sizeof(IntUS)); - } - - *Succulent = spinup_Succulent[cell]; - *Env = spinup_Env[cell]; - *Plot = spinup_Plot[cell]; - *Globals = spinup_Globals[cell]; - - Mem_Free(SXW->f_roots); - Mem_Free(SXW->f_phen); - Mem_Free(SXW->f_bvt); - Mem_Free(SXW->f_prod); - Mem_Free(SXW->f_watin); - Mem_Free(SXW->transpTotal); - ForEachVegType(k) { - Mem_Free(SXW->transpVeg[k]); - } - if (SXW->swc != NULL) - Mem_Free(SXW->swc); - for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) - Mem_Free(SW_Site.lyr[j]); - Mem_Free(SW_Site.lyr); - - *SXW = spinup_SXW[cell]; - SW_Site = spinup_SW_Site[cell]; - SW_Soilwat = spinup_SW_Soilwat[cell]; - SW_VegProd = spinup_SW_VegProd[cell]; - - SXW->transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), - "_load_spinup_cell(SXW->transpTotal)"); - ForEachVegType(k) { - SXW->transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), - "_load_spinup_cell(SXW->transpVeg)"); - } - SXW->swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), - "_load_spinup_cell(SXW->swc)"); - - SXW->f_roots = Str_Dup(spinup_SXW[cell].f_roots); - SXW->f_phen = Str_Dup(spinup_SXW[cell].f_phen); - SXW->f_bvt = Str_Dup(spinup_SXW[cell].f_bvt); - SXW->f_prod = Str_Dup(spinup_SXW[cell].f_prod); - SXW->f_watin = Str_Dup(spinup_SXW[cell].f_watin); - memcpy(SXW->transpTotal, spinup_SXW[cell].transpTotal, - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - ForEachVegType(k) { - memcpy(SXW->transpVeg[k], spinup_SXW[cell].transpVeg[k], - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - } - memcpy(SXW->swc, spinup_SXW[cell].swc, - SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); - - SW_Site.lyr = Mem_Calloc( - spinup_SW_Site[cell].n_layers + spinup_SW_Site[cell].deepdrain, - sizeof(SW_LAYER_INFO *), "_load_spinup_cell(SW_Site.lyr)"); - for (j = 0; - j < spinup_SW_Site[cell].n_layers - + spinup_SW_Site[cell].deepdrain; j++) - { - SW_Site.lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_load_spinup_cell(SW_Site.lyr[j])"); - memcpy(SW_Site.lyr[j], spinup_SW_Site[cell].lyr[j], - sizeof(SW_LAYER_INFO)); - } -} - /**************************************************************/ static Bool GetALine2(FILE *f, char buf[], int limit) { @@ -2872,242 +2377,6 @@ static void _do_seed_dispersal(void) unload_cell(); } -/* - * - */ - -static void _do_groups_and_species_extirpate(void) -{ - //printf("inside _do_groups_and_species_extirpate()\n"); - GrpIndex rg; - ForEachGroup(rg) - { - rgroup_Extirpate(rg); - } -} - -/***********************************************************/ -static void _kill_groups_and_species(void) -{ - /* (AKT /Kyle) 11/17/2016 - *we may need to revisit this setting PR to 0 when we kill everything - *ForEachGroup(c) - *RGroup[c]->pr = 0.0; // reset the pr, so our output doesn't look weird - */ - - //printf("inside _kill_groups_and_species()\n"); - GrpIndex rg; - ForEachGroup(rg) - { - if (Globals->currYear < RGroup[rg]->startyr) - { - /* don't start trying to kill until RGroup[rg]->startyr year as nothing grow till now */ - continue; - } - Int i; - - ForEachEstSpp2( rg, i) - { - if (!Species[RGroup[rg]->est_spp[i]]->use_me) - { - continue; - } - else - { - // printf("calling Species_Proportion_Kill() with rgroup name= %s , RGroup[%d]->proportion_killed =%f for Species[%d]->name= %s \n",RGroup[rg]->name,rg, RGroup[rg]->proportion_killed, i, Species[RGroup[rg]->est_spp[i]]->name); - Species_Proportion_Kill(RGroup[rg]->est_spp[i], 6, RGroup[rg]->proportion_killed); - } - - } - - } - - -} - -/***********************************************************/ -static int _do_grid_disturbances(int row, int col) -{ - // return 1 if a disturbance occurs, else return 0 - - if(UseDisturbances) - { - int cell = col + ((row - 1) * grid_Cols) - 1; -// printf( "inside _do_grid_disturbances Globals->currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", -// Globals->currYear, cell, grid_Disturb[cell].kill_yr); - if ((Globals->currYear >=grid_Disturb[cell].killfreq_startyr) && GT((float)grid_Disturb[cell].killfrq, 0.)) - { - if (LT((float)grid_Disturb[cell].killfrq, 1.0)) - { - if (RandUni(&grid_rng) <= grid_Disturb[cell].killfrq) - { - grid_Disturb[cell].kill_yr = Globals->currYear; - } - - } - else if (((Globals->currYear - grid_Disturb[cell].killfreq_startyr) % (IntU) grid_Disturb[cell].killfrq) == 0) - { - grid_Disturb[cell].kill_yr = Globals->currYear; - } - - } - - if (Globals->currYear == grid_Disturb[cell].extirp) - { - _do_groups_and_species_extirpate(); - return 1; - } - else if (Globals->currYear == grid_Disturb[cell].kill_yr) - { -// printf( "current year matched with cell kill_year so calling _kill_groups_and_species() Globals->currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", -// Globals->currYear, cell, grid_Disturb[cell].kill_yr); - _kill_groups_and_species(); - return 1; - } - - - } - return 0; -} - - -static void _do_grid_proportion_Recovery(int row, int col) -{ - /*======================================================*/ - /* PURPOSE - Perform the sorts of proportion_Recovery one might expect at next year after the killing year - HISTORY - Nov 22 2016 -AKT -Added Species Proportion Recovery for Grid Version */ - /*======================================================*/ - if (UseDisturbances) - { - int cell = col + ((row - 1) * grid_Cols) - 1; -// printf( "inside _do_grid_proportion_Recovery Globals->currYear =%d, cell=%d, grid_Disturb[cell].kill_yr =%d \n", -// Globals->currYear, cell, grid_Disturb[cell].kill_yr); - if ((Globals->currYear >= grid_Disturb[cell].killfreq_startyr) && GT((float)grid_Disturb[cell].killfrq, 0.)) - { - if (LT((float)grid_Disturb[cell].killfrq, 1.0)) - { - if (RandUni(&grid_rng) <= grid_Disturb[cell].killfrq) - { - grid_Disturb[cell].kill_yr = Globals->currYear; - } - - } - else if (((Globals->currYear - grid_Disturb[cell].killfreq_startyr) % (IntU) grid_Disturb[cell].killfrq) == 0) - { - grid_Disturb[cell].kill_yr = Globals->currYear; - } - - } - - //rgroup proportion recovery - if (Globals->currYear == grid_Disturb[cell].kill_yr) - { - GrpIndex rg; - ForEachGroup(rg) - { - if (Globals->currYear < RGroup[rg]->startyr) - { - /* don't start trying to grow until RGroup[rg]->startyr year */ - continue; - } - - Int i; - - ForEachEstSpp2( rg, i) - { - if (!Species[RGroup[rg]->est_spp[i]]->use_me) - { - continue; - } - else - { - // printf( "calling Species_Proportion_Recovery() with rgroup name= %s , RGroup[%d]->proportion_recovered =%f for Species[%d]->name= %s \n", RGroup[rg]->name, rg, RGroup[rg]->proportion_recovered, i, Species[RGroup[rg]->est_spp[i]]->name); - Species_Proportion_Recovery(RGroup[rg]->est_spp[i], 6, - RGroup[rg]->proportion_recovered, - RGroup[rg]->proportion_killed); - } - - } - - } - - } - - } - -} - -static void _do_grid_grazing_EndOfYear(int row, int col) -{ - - /*======================================================*/ - /* PURPOSE - * Perform the sorts of grazing one might expect at end of year, it is based on grazing frequency - * HISTORY - * Nov 22 2016 -AKT -Added Species grazing EndOfYear for grid model - */ - /*======================================================*/ - - if (UseDisturbances) - { - IntU grazingyr = 0; - int cell = col + ((row - 1) * grid_Cols) - 1; - - if ((Globals->currYear >=grid_Disturb[cell].grazingfreq_startyr) && grid_Disturb[cell].grazing_frq > 0.) - { - if (grid_Disturb[cell].grazing_frq < 1.0) - { - if (RandUni(&grid_rng) <= grid_Disturb[cell].grazing_frq) - { - grazingyr = Globals->currYear; - } - - } - else if (((Globals->currYear - grid_Disturb[cell].grazingfreq_startyr) % (IntU) grid_Disturb[cell].grazing_frq) == 0) - { - grazingyr = Globals->currYear; - } - - } - - //rgroup proportion grazing - if (Globals->currYear == grazingyr) - { - GrpIndex rg; - ForEachGroup(rg) - { - if (Globals->currYear < RGroup[rg]->startyr) - { - /* don't start trying to grow or do grazing until RGroup[rg]->startyr year */ - continue; - } - - Int i; - - ForEachEstSpp2( rg, i) - { - if (!Species[RGroup[rg]->est_spp[i]]->use_me) - { - continue; - } - else - { - // printf( "year = %d, calling Species_Proportion_Grazing() with rgroup name= %s , RGroup[%d]->proportion_grazing =%f for Species[%d]->name= %s \n", Globals->currYear,RGroup[rg]->name, rg,RGroup[rg]->proportion_grazing, i, Species[RGroup[rg]->est_spp[i]]->name); - Species_Proportion_Grazing(RGroup[rg]->est_spp[i], RGroup[rg]->proportion_grazing); - } - - } - - } - - } - - } - -} - /***********************************************************/ static void _read_init_species(void) { From 02390dd300d4305737528225950c730540f194ba Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 8 Jul 2019 09:46:58 -0600 Subject: [PATCH 103/167] Corrected some compiler warnings These compiler warnings come incorrect format specifiers in input functions. (issue #286) I also removed one unused variable in ST_resgroups.c. --- ST_grid.c | 2 +- ST_params.c | 10 +++++----- ST_resgroups.c | 3 +-- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 3b5f15ef..2511e23a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1608,7 +1608,7 @@ static void _read_disturbances_in(void) break; ForEachGroup(rg) { - num = sscanf(buf, "%d,%d,%d,%d,%d,%d,%f,%d,%d,%d,%f,%f,%f", &cell, + num = sscanf(buf, "%d,%d,%d,%d,%hu,%hu,%f,%hu,%hu,%hu,%f,%f,%f", &cell, &Globals->pat.use, &Globals->mound.use, &Globals->burrow.use, &RGroup[rg]->killyr, &RGroup[rg]->killfreq_startyr, &RGroup[rg]->killfreq, &RGroup[rg]->extirp, &RGroup[rg]->grazingfrq, &RGroup[rg]->grazingfreq_startyr, &RGroup[rg]->ignition, diff --git a/ST_params.c b/ST_params.c index de146e72..18a436d4 100644 --- a/ST_params.c +++ b/ST_params.c @@ -699,7 +699,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource groups allowed.", MyFileName); } - if (sscanf(inbuf, "%u", &SuperGlobals.max_rgroups) != 1) { + if (sscanf(inbuf, "%zu", &SuperGlobals.max_rgroups) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource groups allowed.", MyFileName); } @@ -707,7 +707,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource group name length.", MyFileName); } - if (sscanf(inbuf, "%u", &SuperGlobals.max_groupnamelen) != 1) { + if (sscanf(inbuf, "%zu", &SuperGlobals.max_groupnamelen) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum resource group name length.", MyFileName); } @@ -717,7 +717,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species allowed per resource group.", MyFileName); } - if (sscanf(inbuf, "%u", &SuperGlobals.max_spp_per_grp) != 1) { + if (sscanf(inbuf, "%zu", &SuperGlobals.max_spp_per_grp) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species allowed per resource group.", MyFileName); } @@ -725,7 +725,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum individuals allowed per species.", MyFileName); } - if (sscanf(inbuf, "%u", &SuperGlobals.max_indivs_per_spp) != 1) { + if (sscanf(inbuf, "%zu", &SuperGlobals.max_indivs_per_spp) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum individuals allowed per species.", MyFileName); } @@ -733,7 +733,7 @@ void maxrgroupspecies_init( void) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species name length.", MyFileName); } - if (sscanf(inbuf, "%u", &SuperGlobals.max_speciesnamelen) != 1) { + if (sscanf(inbuf, "%zu", &SuperGlobals.max_speciesnamelen) != 1) { LogError(logfp, LOGFATAL, "%s: Could not read maximum species name length.", MyFileName); } diff --git a/ST_resgroups.c b/ST_resgroups.c index 69faf93b..297fd7c0 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -978,8 +978,7 @@ void rgroup_Extirpate(GrpIndex rg) } void copy_rgroup(const GroupType* src, GroupType* dest){ - int i; - SppIndex sp; + int i; // This would be very bad. if(src == dest){ From 3bd1fa4b7c3154fac8507f39ae77539f751ef9e9 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 8 Jul 2019 14:09:27 -0600 Subject: [PATCH 104/167] Overhauled progress bar (issue #314) I went ahead and made a new progress bar. There were a lot of moving peices in the old one which left a lot of room for bugs. --- ST_grid.c | 118 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 112 insertions(+), 6 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 2511e23a..def0a16d 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -239,6 +239,15 @@ enum INIT_WITH_NOTHING }; +enum status +{ + SPINUP, + DISPERSAL, + SIMULATION, + OUTPUT, + DONE +}; + char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; int grid_Cols, grid_Rows, grid_Cells, sd_NYearsSeedsAvailable; @@ -383,6 +392,8 @@ transp_t* getTranspWindow(void); static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w); static double _time_remaining(clock_t start, char* timeChar, double percentDone); +static void logProgress(int iteration, int year, int status); +static double calculateProgress(int year, int iteration, int status); static void printGeneralInfo(void); static void _run_spinup(void); static void saveAsSpinupConditions(void); @@ -505,6 +516,92 @@ static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w) return result; } +/* Log the program's progress using a progress bar. + Param iteration: integer greater than 0. Input 0 iff the program is not currently in an iteration loop. + Param year: integer greater than 0. Input 0 iff the program is not currently in a years loop. + Param status: Use the "status" enum to choose a value. */ +static void logProgress(int iteration, int year, int status){ + static char progressString[256]; + int index = 0; // Where we are in progressString + Bool needsProgressBar = FALSE; // By default we donot need a progress bar + progressString[0] = '\0'; // Empty the string + iteration--; // iteration loops are 1 indexed, but we need 0 indexing. + + switch(status){ + case SPINUP: + strcpy(progressString, "Spinup |"); + index += 12; // We have copied over 12 characters + needsProgressBar = TRUE; + break; + case DISPERSAL: + strcpy(progressString, "Dispersing seeds"); + index += 16; // We have copied over 16 characters + break; + case SIMULATION: + strcpy(progressString, "Simulating |"); + index += 12; // We have copied over 12 characters + needsProgressBar = TRUE; + break; + case OUTPUT: + strcpy(progressString, "Writing files"); + index += 13; // We have copied over 12 characters + break; + case DONE: + strcpy(progressString, "Done"); + // We need to pad the string with spaces to make sure we overwrite any progress bars. + for(index = 4; index < 40; ++index) progressString[index] = ' '; + break; + default: + break; + } + + // If our program is currently in a looping state we can make a progress bar using year and iteration. + if(needsProgressBar){ + int numberOfCharacters = 0; + double percentComplete = calculateProgress(year, iteration, status); + // Add '=' characters for every 5% complete. + while(percentComplete > 0){ + progressString[index] = '='; + index++; + numberOfCharacters++; + percentComplete -= 5; + } + // Add spaces until we hit 20 characters + while(numberOfCharacters < 20){ + progressString[index] = ' '; + numberOfCharacters++; + index++; + } + progressString[index++] = '|'; + progressString[index++] = '\0'; + } + + printf("\r%s", progressString); // print the string we generated + fflush(stdout); // Explicitly print the output. + + // If we are done we want to print a newline character so the terminal isn't appended to our "Done" string. + if(status == DONE){ + printf("\n"); + } +} + +/* Returns a double between 0 and 100 representing how close the program is to completing a given loop. + Param year: Current year in the loop. + Param iteration: Current iteration in the loop. + Param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. */ +double calculateProgress(int year, int iteration, int status){ + double percentComplete; + if(status == SPINUP){ + percentComplete = (year / (double) SuperGlobals.runModelYears); + } else if(status == SIMULATION) { + percentComplete = ((iteration * SuperGlobals.runModelYears) + year) + / (double) (SuperGlobals.runModelIterations * SuperGlobals.runModelYears); + } else { + return 0; // If the program isn't in spinup or simulation then this function isn't applicable. + } + return percentComplete * 100; +} + /* Print information about the simulation to stdout. */ static void printGeneralInfo(void){ /* ------------------- Print some general information to stdout ----------------------- */ @@ -522,6 +619,7 @@ static void printGeneralInfo(void){ if(UseSeedDispersal){ printf("Dispersing seeds between cells\n"); } + printf("\n"); /* --------------------------- END printing general info -------------------------------- */ } @@ -531,9 +629,6 @@ void runGrid(void) int i, j; Bool killedany; IntS year, iter; - double prog_Percent = 0.0, prog_Incr, prog_Acc = 0.0; - char prog_Prefix[32]; - clock_t prog_Time; _init_grid_files(); // reads in files.in file _read_maxrgroupspecies(); // reads in maxrgroupspecies.in file @@ -600,6 +695,9 @@ void runGrid(void) for (year = 1; year <= SuperGlobals.runModelYears; year++) { //for each year + if(UseProgressBar){ + logProgress(iter, year, SIMULATION); + } for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) { //for each cell @@ -676,6 +774,10 @@ void runGrid(void) } /*end iterations */ + if(UseProgressBar){ + logProgress(0, 0, OUTPUT); + } + // outputs all of the mort and BMass files for each cell... for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) @@ -712,6 +814,7 @@ void runGrid(void) if(InitializationMethod == INIT_WITH_SPINUP) { _free_spinup_memory(); } + logProgress(0, 0, DONE); } /* "Spinup" the model by running for SuperGlobals.runModelYears without seed dispersal or statistics outputs. */ @@ -802,6 +905,9 @@ static void _run_spinup(void) for (year = 1; year <= SuperGlobals.runModelYears; year++) { //for each year + if(UseProgressBar){ + logProgress(iter, year, SPINUP); + } for (i = 0; i < grid_Rows; ++i) { // for each row for(j = 0; j < grid_Cols; ++j) @@ -2549,9 +2655,9 @@ void Output_AllCellAvgBmass(const char * filename){ SppIndex sp; //for iterating /* One accumulator for every accumulator in ST_stats.c */ - float ppt, pptstd, pptsos, temp, tempstd, tempsos, dist, wildfire, grp[SuperGlobals.max_rgroups], grpstd[SuperGlobals.max_rgroups], grpsos[SuperGlobals.max_rgroups], - gsize[SuperGlobals.max_rgroups], - gpr[SuperGlobals.max_rgroups], gprsos[SuperGlobals.max_rgroups], gprstd[SuperGlobals.max_rgroups], prescribedfire[SuperGlobals.max_rgroups], + float ppt, pptstd, pptsos, temp, tempstd, tempsos, dist, wildfire, grp[SuperGlobals.max_rgroups], grpstd[SuperGlobals.max_rgroups], + grpsos[SuperGlobals.max_rgroups], gsize[SuperGlobals.max_rgroups], gpr[SuperGlobals.max_rgroups], + gprsos[SuperGlobals.max_rgroups], gprstd[SuperGlobals.max_rgroups], prescribedfire[SuperGlobals.max_rgroups], spp[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups], indv[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups]; From ec1587a797ffebdc00d3f56658d29e5fd5d04c39 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 8 Jul 2019 14:19:29 -0600 Subject: [PATCH 105/167] Removed old progress bar and improved new one. (issue #314) * I made Status a type so I could make it clear to the user that the "status" parameter needs to use the correct enumerator. (issue #311) * _load_bar and _time_remaining. --- ST_grid.c | 97 ++++--------------------------------------------------- 1 file changed, 6 insertions(+), 91 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index def0a16d..a6d7ecab 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -239,14 +239,14 @@ enum INIT_WITH_NOTHING }; -enum status +typedef enum { SPINUP, DISPERSAL, SIMULATION, OUTPUT, DONE -}; +} Status; char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; @@ -390,10 +390,8 @@ transp_t* getTranspWindow(void); /*********** Locally Used Function Declarations ************/ /***********************************************************/ -static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w); -static double _time_remaining(clock_t start, char* timeChar, double percentDone); -static void logProgress(int iteration, int year, int status); -static double calculateProgress(int year, int iteration, int status); +static void logProgress(int iteration, int year, Status status); +static double calculateProgress(int year, int iteration, Status status); static void printGeneralInfo(void); static void _run_spinup(void); static void saveAsSpinupConditions(void); @@ -433,94 +431,11 @@ static void _read_files(void); /******************** Begin Model Code *********************/ /***********************************************************/ -/***********************************************************/ -double _time_remaining(clock_t start, char* timeChar, double percentDone) -{ - // for use in _load_bar() function... pretty much it returns the amount of time left and a character in timeChar representing the units - // percent done must be from 0 to 1, with 0 representing no work done (0%) and 1 representing all of the work done (ie 100%) - clock_t timeElapsed = clock() - start; //gets the time since we started (this is in CPU cycles). We convert to seconds in the next part - double result = (((double) timeElapsed) / CLOCKS_PER_SEC) / percentDone - * (1.0 - percentDone); //gets estimated time left until the work is complete based upon timeElapsed and percentDone - - *timeChar = 's'; //get the biggest time units that we can use (ie no use displaying 120 seconds if we can display 2 minutes) - if (result > 60) - { - result /= 60.0; - *timeChar = 'm'; - if (result > 60) - { - result /= 60.0; - *timeChar = 'h'; - if (result > 24) - { - result /= 24.0; - *timeChar = 'd'; - if (result > 7) - { - result /= 7.0; - *timeChar = 'w'; - } - } - } - } - - return result; -} - -/***********************************************************/ -static int _load_bar(char* prefix, clock_t start, int x, int n, int r, int w) -{ - //loads a progress bar, x is how much progress has been made, n is how much progress to be done, r is how many times to update, and w is width of the progress bar - //wouldn't suggest using this if your stdout is being redirected somewhere else (it doesn't work right in that case and gives unwanted output) - //gotten from: http://www.rosshemsley.co.uk/2011/02/creating-a-progress-bar-in-c-or-any-other-console-app/ - - //modified to include an estimate of the time remaining... start must be a clock started (using clock() function) right before beginning the work - - // Only update r times. - if (x % (n / r) != 0) - return (int) ((x / (float) n) * 100); - - int i; - - printf("\r"); //we output a carriage-return character to put us back at the beginning of the line - if (prefix != NULL) - printf("%s", prefix); - - // Calculuate the ratio of complete-to-incomplete. - float ratio = x / (float) n; - int c = ratio * w; - int result = (int) (ratio * 100); - - if (result > 1) - { //we don't give an estimate if less than 2% of the work is complete because we don't have any data to go off of... - char timeChar; - double timeLeft = _time_remaining(start, &timeChar, (double) ratio); - if (timeLeft < 10) - printf("(est 0%.2f%c) ", timeLeft, timeChar); - else - printf("(est %.2f%c) ", timeLeft, timeChar); - } - - // Show the percentage complete. - printf("%3d%% [", (int) (ratio * 100)); - - // Show the load bar. - for (i = 0; i < c; i++) - printf("="); - - for (i = c; i < w; i++) - printf(" "); - - printf("]"); - fflush(stdout); //we do this to flush (ie. print) the output, since stdout typically waits for a newline character before flushing - return result; -} - /* Log the program's progress using a progress bar. Param iteration: integer greater than 0. Input 0 iff the program is not currently in an iteration loop. Param year: integer greater than 0. Input 0 iff the program is not currently in a years loop. Param status: Use the "status" enum to choose a value. */ -static void logProgress(int iteration, int year, int status){ +static void logProgress(int iteration, int year, Status status){ static char progressString[256]; int index = 0; // Where we are in progressString Bool needsProgressBar = FALSE; // By default we donot need a progress bar @@ -589,7 +504,7 @@ static void logProgress(int iteration, int year, int status){ Param year: Current year in the loop. Param iteration: Current iteration in the loop. Param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. */ -double calculateProgress(int year, int iteration, int status){ +double calculateProgress(int year, int iteration, Status status){ double percentComplete; if(status == SPINUP){ percentComplete = (year / (double) SuperGlobals.runModelYears); From 0a65e479ff2d593629175faad40623f80409c815 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 9 Jul 2019 14:22:55 -0600 Subject: [PATCH 106/167] Added two new functions related to Initialization (issue #300) * beginInitialization() takes care of swapping shouldBeInitialized with use_me. This needs to be done no matter what initialization method we choose so I moved the code out of _run_spinup and into it's own function. * endInitialization() is the sister function to beginInitialization(). It swaps the variables back and saves the state of the program. --- ST_grid.c | 96 +++++++++++++++++++++++++------------------------------ 1 file changed, 44 insertions(+), 52 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index a6d7ecab..16223ab1 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -394,6 +394,8 @@ static void logProgress(int iteration, int year, Status status); static double calculateProgress(int year, int iteration, Status status); static void printGeneralInfo(void); static void _run_spinup(void); +static void beginInitialization(void); +static void endInitialization(void); static void saveAsSpinupConditions(void); static void loadSpinupConditions(void); static void _init_grid_files(void); @@ -747,15 +749,10 @@ static void _run_spinup(void) /* ints used for iterating over years and iterations */ IntS year, iter; - /* For iterating over RGroup and Species */ - GrpIndex rg; - SppIndex sp; - IntS k; - - /* killedany for mortality functions, temporary_storage for swapping variables */ - Bool killedany, temporary_storage; + /* killedany for mortality functions */ + Bool killedany; - DuringSpinup = TRUE; + beginInitialization(); if (!UseSoils) { // if we're not using inputting soils then there is simply one soil type as all the soils are the same @@ -789,35 +786,6 @@ static void _run_spinup(void) } unload_cell(); // Reset the global variables - /* Before we start iterating we need to swap Species[sp]->use_me and mySpeciesInit.shouldBeInitialized[sp]. - shouldBeInitialized is an array of booleans that represent whether the given species should be used - in initialization. use_me is a boolean that represents whether the given species should be used in production. - By swaping them we save space, but we have to remember to swap them back before the production run. */ - for(i = 0; i < grid_Rows; ++i){ - for(j = 0; j < grid_Cols; ++j){ - if(!gridCells[i][j].mySpeciesInit.use_SpinUp){ - continue; - } - load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee - that ForEachGroup would iterate correctly */ - - Globals->currIter = iter; // We need to do this before the "years" loop. - - /* Begin swaping variables */ - ForEachGroup(rg){ - ForEachGroupSpp(sp, rg, k){ - // Temporarily store use_me - temporary_storage = Species[sp]->use_me; - // Swap use_me - Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; - // Swap shouldBeInitialized[sp] - gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; - } /* End for each species */ - } /* End for each group */ - } /* End for each column */ - } /* End for each row */ - unload_cell(); // Reset the global variables - for (year = 1; year <= SuperGlobals.runModelYears; year++) { //for each year if(UseProgressBar){ @@ -876,35 +844,58 @@ static void _run_spinup(void) ChDir(".."); } /* End iterations */ - /* Swap back Species[sp]->use_me and shouldBeInitialized[sp]. */ + endInitialization(); +} + +/* Prepares for initialization by turning on species that have requested initialization and turning off + species that have not requested initialization. This function should be accompanied by a call to + endInitialization. */ +static void beginInitialization(void){ + int i, j; /* For iterating over cells */ + SppIndex sp; /* For iterating over species */ + Bool temporary_storage; /* For swapping variables */ + + DuringSpinup = TRUE; + + /* Swap Species[sp]->use_me and mySpeciesInit.shouldBeInitialized[sp]. shouldBeInitialized is an array + of booleans that represent whether the given species should be used in initialization. use_me is a + boolean that represents whether the given species should be used in production. By swaping them we + save space, but we have to remember to swap them back before the production run. */ for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ if(!gridCells[i][j].mySpeciesInit.use_SpinUp){ - continue; + continue; } load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee - that ForEachGroup would iterate correctly */ + that ForEachGroup would iterate correctly */ + /* Begin swaping variables */ - ForEachGroup(rg){ - ForEachGroupSpp(sp, rg, k){ - // Temporarily store use_me - temporary_storage = Species[sp]->use_me; - // Swap use_me - Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; - // Swap shouldBeInitialized[sp] - gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; - } /* End for each species */ - } /* End for each group */ + ForEachSpecies(sp){ + // Temporarily store use_me + temporary_storage = Species[sp]->use_me; + // Swap use_me + Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; + // Swap shouldBeInitialized[sp] + gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; + } /* End for each species */ } /* End for each column */ } /* End for each row */ unload_cell(); // Reset the global variables +} - // Save everything that has happened thus far. +/* Return the program to the state it needs to be in for the main simulation. This should only be called if you + have called beginInitialization. */ +static void endInitialization(void){ + // Calling this function a second time will swap the variables back to their original state. + beginInitialization(); + // Save the state of the program as our initialization conditions. saveAsSpinupConditions(); - + // We have now exited spinup. DuringSpinup = FALSE; } +/* Save the current state of the program as spinup conditions. This is low level function. If you have already called + endInitialization() there is no need to call this function. */ static void saveAsSpinupConditions(){ // Save gridCells as spinupCells spinupCells = gridCells; @@ -918,6 +909,7 @@ static void saveAsSpinupConditions(){ _init_grid_inputs(); // reads the grid inputs in & initializes the global grid variables } +/* Load the state of the program right after initialization. */ static void loadSpinupConditions(){ int row, col; GrpIndex rg; From f1b3bb2146bf6e495d3386670adc135e60e13bca Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 9 Jul 2019 14:33:19 -0600 Subject: [PATCH 107/167] Modified general info printed to terminal (issue #314) From non-gridded mode: * removed number of soil layers From gridded mode: * removed number of soil layers * made D in Disturbances lower case. --- ST_grid.c | 3 +-- sxw.c | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 16223ab1..7e0e3155 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -522,11 +522,10 @@ double calculateProgress(int year, int iteration, Status status){ /* Print information about the simulation to stdout. */ static void printGeneralInfo(void){ /* ------------------- Print some general information to stdout ----------------------- */ - printf("Number of layers: %d\n", SW_Site.n_layers); printf("Number of iterations: %d\n", SuperGlobals.runModelIterations); printf("Number of years: %d\n", SuperGlobals.runModelYears); printf("Number of cells: %d\n\n", grid_Cells); - if(UseDisturbances) printf("Using grid Disturbances file.\n"); + if(UseDisturbances) printf("Using grid disturbances file\n"); if(UseSoils) printf("Using grid soils file\n"); if(InitializationMethod == INIT_WITH_SEEDS){ printf("Seeds availible for %d years at the start of the simulation.\n",sd_NYearsSeedsAvailable); diff --git a/sxw.c b/sxw.c index 5167001d..d03f2dda 100644 --- a/sxw.c +++ b/sxw.c @@ -206,7 +206,6 @@ void SXW_Init( Bool init_SW, char *f_roots ) { /* Print general information to stdout. If we are using gridded mode this functionallity will be handled in ST_grid.c */ if(!UseGrid){ - printf("Number of layers: %d\n", SW_Site.n_layers); printf("Number of iterations: %d\n", SuperGlobals.runModelIterations); printf("Number of years: %d\n", SuperGlobals.runModelYears); } From 573cecf7bf8f29a833d0e7323deba5d7ccaf4909 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 9 Jul 2019 14:59:21 -0600 Subject: [PATCH 108/167] Changed some variable names to make them more ambigous I generalized some variables associated with spinup so they can be applied to all initialization methods. This will allow us to use the variables regardless of the initialization method chosen. (issue #342) Variables changed: * DuringSpinup -> DuringInitialization * use_SpinUp -> useInitialization * saveAsSpinupConditions -> saveAsInitializationConditions * loadSpinupConditions -> loadInitializationConditions --- ST_globals.h | 2 +- ST_grid.c | 44 ++++++++++++++++++++++---------------------- ST_main.c | 2 +- ST_species.c | 2 +- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/ST_globals.h b/ST_globals.h index ea536956..abe482d7 100644 --- a/ST_globals.h +++ b/ST_globals.h @@ -32,4 +32,4 @@ extern GlobalType SuperGlobals; extern Bool UseSeedDispersal; extern int InitializationMethod; extern Bool UseGrid; -extern Bool DuringSpinup; +extern Bool DuringInitialization; diff --git a/ST_grid.c b/ST_grid.c index 7e0e3155..602da43a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -144,8 +144,8 @@ struct _grid_sxw_st struct _grid_init_species_st { - /* TRUE is this cell should use spinup */ - int use_SpinUp; + /* TRUE if at least one species has requested initialization */ + int useInitialization; /* Array of Boolean values. TRUE if given species should be included in spinup */ int *shouldBeInitialized; @@ -170,7 +170,7 @@ struct grid_cell_st /* If TRUE this cell should use seed dispersal */ Bool useSeedDispersal; /* TRUE if this cell is in spinup mode */ - Bool duringSpinup; + Bool DuringInitialization; /* species spinup information */ Grid_Init_Species_St mySpeciesInit; /* seed dispersal information corresponding to this cell */ @@ -396,8 +396,8 @@ static void printGeneralInfo(void); static void _run_spinup(void); static void beginInitialization(void); static void endInitialization(void); -static void saveAsSpinupConditions(void); -static void loadSpinupConditions(void); +static void saveAsInitializationConditions(void); +static void loadInitializationConditions(void); static void _init_grid_files(void); static void _init_grid_inputs(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); @@ -599,7 +599,7 @@ void runGrid(void) // If we used spinup we need to reset to the state of the program right after spinup. if (InitializationMethod == INIT_WITH_SPINUP){ - loadSpinupConditions(); + loadInitializationConditions(); } RandSeed(SuperGlobals.randseed, &environs_rng); @@ -795,7 +795,7 @@ static void _run_spinup(void) for(j = 0; j < grid_Cols; ++j) { // for each column // If we should run spinup on this cell - if(gridCells[i][j].mySpeciesInit.use_SpinUp){ + if(gridCells[i][j].mySpeciesInit.useInitialization){ // Load up a cell load_cell(i, j); } else { @@ -854,7 +854,7 @@ static void beginInitialization(void){ SppIndex sp; /* For iterating over species */ Bool temporary_storage; /* For swapping variables */ - DuringSpinup = TRUE; + DuringInitialization = TRUE; /* Swap Species[sp]->use_me and mySpeciesInit.shouldBeInitialized[sp]. shouldBeInitialized is an array of booleans that represent whether the given species should be used in initialization. use_me is a @@ -862,7 +862,7 @@ static void beginInitialization(void){ save space, but we have to remember to swap them back before the production run. */ for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ - if(!gridCells[i][j].mySpeciesInit.use_SpinUp){ + if(!gridCells[i][j].mySpeciesInit.useInitialization){ continue; } load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee @@ -888,14 +888,14 @@ static void endInitialization(void){ // Calling this function a second time will swap the variables back to their original state. beginInitialization(); // Save the state of the program as our initialization conditions. - saveAsSpinupConditions(); + saveAsInitializationConditions(); // We have now exited spinup. - DuringSpinup = FALSE; + DuringInitialization = FALSE; } /* Save the current state of the program as spinup conditions. This is low level function. If you have already called endInitialization() there is no need to call this function. */ -static void saveAsSpinupConditions(){ +static void saveAsInitializationConditions(){ // Save gridCells as spinupCells spinupCells = gridCells; // Nullify gridCells. This ensures we can no longer modify spinupCells on accident. @@ -909,7 +909,7 @@ static void saveAsSpinupConditions(){ } /* Load the state of the program right after initialization. */ -static void loadSpinupConditions(){ +static void loadInitializationConditions(){ int row, col; GrpIndex rg; SppIndex sp; @@ -998,7 +998,7 @@ static void _init_grid_inputs(void) for(i = 0; i < grid_Rows; ++i) { for(j = 0; j < grid_Cols; ++j) { load_cell(i, j); - gridCells[i][j].duringSpinup = FALSE; + gridCells[i][j].DuringInitialization = FALSE; } } @@ -1532,7 +1532,7 @@ static void load_cell(int row, int col){ Globals = &gridCells[row][col].myGlobals; /* TRUE if this cell is in spinup mode */ - DuringSpinup = gridCells[row][col].duringSpinup; + DuringInitialization = gridCells[row][col].DuringInitialization; _SomeKillage = gridCells[row][col].someKillage; @@ -2393,11 +2393,11 @@ static void _do_seed_dispersal(void) static void _read_init_species(void) { // reads the grid init species input - // the file should be something like: "cell,copy_cell,copy_which,use_SpinUp,(all the species names seperated by a comma)" + // the file should be something like: "cell,copy_cell,copy_which,(all the species names seperated by a comma)" // there should be no spaces in between, just commas separating the values (ie it should be a .csv file, but does not account for all of the possibilities that a .csv file could be) FILE *f; - int i, j, num, cell, do_copy, copy_cell, use_SpinUp, seeds_Avail, + int i, j, num, cell, do_copy, copy_cell, useInitialization, seeds_Avail, row, col, copy_cell_row, copy_cell_col; Bool isAnyCellOnForSpinup = FALSE; char buf[4096]; @@ -2408,7 +2408,7 @@ static void _read_init_species(void) GetALine2(f, buf, 4096); // gets rid of the first line (since it just defines the columns)... it's only there for user readability for (i = 0; i < grid_Cells; i++) { - use_SpinUp = FALSE; + useInitialization = FALSE; row = i / grid_Cols; col = i % grid_Cols; @@ -2433,8 +2433,8 @@ static void _read_init_species(void) for (j = 0; j < Globals->sppCount; j++) gridCells[row][col].mySpeciesInit.shouldBeInitialized[j] = gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.shouldBeInitialized[j]; - gridCells[row][col].mySpeciesInit.use_SpinUp = - gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.use_SpinUp; + gridCells[row][col].mySpeciesInit.useInitialization = + gridCells[copy_cell_row][copy_cell_col].mySpeciesInit.useInitialization; continue; } else if (do_copy == 1) @@ -2453,7 +2453,7 @@ static void _read_init_species(void) } if(seeds_Avail){ - use_SpinUp = TRUE; + useInitialization = TRUE; isAnyCellOnForSpinup = TRUE; } @@ -2461,7 +2461,7 @@ static void _read_init_species(void) stringIndex += _get_value_index(&buf[stringIndex], ',', 1); } - gridCells[row][col].mySpeciesInit.use_SpinUp = use_SpinUp; + gridCells[row][col].mySpeciesInit.useInitialization = useInitialization; } if (i != grid_Cells) diff --git a/ST_main.c b/ST_main.c index 6fbe2010..1fa6cdeb 100644 --- a/ST_main.c +++ b/ST_main.c @@ -138,7 +138,7 @@ MortFlagsType MortFlags; Bool UseGrid; Bool UseSeedDispersal; int InitializationMethod; -Bool DuringSpinup; +Bool DuringInitialization; Bool EchoInits; Bool UseProgressBar; Bool STdebug_requested; diff --git a/ST_species.c b/ST_species.c index 6aad7c1e..7b7bc4c3 100644 --- a/ST_species.c +++ b/ST_species.c @@ -69,7 +69,7 @@ IntS Species_NumEstablish(SppIndex sp) /*------------------------------------------------------*/ //special conditions if we're using the grid and seed dispersal options (as long as its not during the spinup, because we dont use seed dispersal during spinup) - if (UseGrid && UseSeedDispersal && !DuringSpinup) { + if (UseGrid && UseSeedDispersal && !DuringInitialization) { if (Species[sp]->sd_sgerm) { if (Species[sp]->max_seed_estab <= 1) { From 299774c5f7556d9d9747e927807457d9e8af6324 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sat, 13 Jul 2019 14:12:22 -0600 Subject: [PATCH 109/167] (issue #252) Removed cheatgrass parameters from grid_disturbances.csv I removed them because they are constant for all cells. --- ST_grid.c | 7 +- .../Grid_Inputs/grid_disturbances.csv | 146 +++++++++++++++++- 2 files changed, 148 insertions(+), 5 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 602da43a..e97925c4 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1620,14 +1620,13 @@ static void _read_disturbances_in(void) break; ForEachGroup(rg) { - num = sscanf(buf, "%d,%d,%d,%d,%hu,%hu,%f,%hu,%hu,%hu,%f,%f,%f", &cell, + num = sscanf(buf, "%d,%d,%d,%d,%hu,%hu,%f,%hu,%hu,%hu,%f", &cell, &Globals->pat.use, &Globals->mound.use, &Globals->burrow.use, &RGroup[rg]->killyr, &RGroup[rg]->killfreq_startyr, &RGroup[rg]->killfreq, &RGroup[rg]->extirp, - &RGroup[rg]->grazingfrq, &RGroup[rg]->grazingfreq_startyr, &RGroup[rg]->ignition, - &RGroup[rg]->cheatgrass_coefficient, &RGroup[rg]->wild_fire_slope); + &RGroup[rg]->grazingfrq, &RGroup[rg]->grazingfreq_startyr, &RGroup[rg]->ignition); } - if (num != 13) + if (num != 11) LogError(logfp, LOGFATAL, "Invalid %s file line %d wrong", grid_files[GRID_FILE_DISTURBANCES], i + 2); } diff --git a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv index f5141a0b..a659ecf8 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv @@ -1 +1,145 @@ -cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfreq_startyr,Prescribed_killfreq,extirp,grazing_frq,grazingfrq_startyr,ignition,cheatgrass_coefficient,wildfire_slope 0,0,0,0,0,0,0,0,0,0,12.05,-0.117,0.0093 1,0,0,0,0,5,30,0,0,0,0,-0.117,0.0093 2,0,0,0,0,0,0,0,0,0,12.05,-0.117,0.0093 3,0,0,0,0,1,100,0,0,0,0,-0.117,0.0093 4,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 5,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 6,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 7,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 8,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 9,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 10,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 11,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 12,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 13,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 14,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 15,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 16,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 17,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 18,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 19,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 20,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 21,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 22,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 23,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 24,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 25,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 26,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 27,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 28,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 29,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 30,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 31,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 32,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 33,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 34,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 35,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 36,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 37,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 38,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 39,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 40,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 41,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 42,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 43,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 44,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 45,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 46,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 47,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 48,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 49,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 50,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 51,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 52,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 53,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 54,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 55,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 56,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 57,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 58,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 59,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 60,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 61,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 62,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 63,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 64,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 65,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 66,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 67,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 68,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 69,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 70,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 71,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 72,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 73,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 74,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 75,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 76,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 77,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 78,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 79,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 80,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 81,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 82,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 83,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 84,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 85,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 86,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 87,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 88,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 89,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 90,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 91,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 92,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 93,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 94,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 95,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 96,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 97,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 98,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 99,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 100,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 101,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 102,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 103,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 104,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 105,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 106,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 107,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 108,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 109,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 110,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 111,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 112,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 113,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 114,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 115,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 116,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 117,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 118,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 119,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 120,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 121,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 122,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 123,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 124,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 125,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 126,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 127,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 128,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 129,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 130,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 131,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 132,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 133,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 134,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 135,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 136,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 137,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 138,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 139,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 140,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 141,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 142,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 143,0,0,0,0,0,0,0,0,0,0,-0.117,0.0093 \ No newline at end of file +cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfreq_startyr,Prescribed_killfreq,extirp,grazing_frq,grazingfrq_startyr,ignition +0,0,0,0,0,0,0,0,0,0,0 +1,0,0,0,0,5,80,0,0,0,0 +2,0,0,0,0,0,0,0,0,0,12.05 +3,0,0,0,0,1,100,0,0,0,0 +4,0,0,0,0,0,0,0,0,0,0 +5,0,0,0,0,0,0,0,0,0,0 +6,0,0,0,0,0,0,0,0,0,0 +7,0,0,0,0,0,0,0,0,0,0 +8,0,0,0,0,0,0,0,0,0,0 +9,0,0,0,0,0,0,0,0,0,0 +10,0,0,0,0,0,0,0,0,0,0 +11,0,0,0,0,0,0,0,0,0,0 +12,0,0,0,0,0,0,0,0,0,0 +13,0,0,0,0,0,0,0,0,0,0 +14,0,0,0,0,0,0,0,0,0,0 +15,0,0,0,0,0,0,0,0,0,0 +16,0,0,0,0,0,0,0,0,0,0 +17,0,0,0,0,0,0,0,0,0,0 +18,0,0,0,0,0,0,0,0,0,0 +19,0,0,0,0,0,0,0,0,0,0 +20,0,0,0,0,0,0,0,0,0,0 +21,0,0,0,0,0,0,0,0,0,0 +22,0,0,0,0,0,0,0,0,0,0 +23,0,0,0,0,0,0,0,0,0,0 +24,0,0,0,0,0,0,0,0,0,0 +25,0,0,0,0,0,0,0,0,0,0 +26,0,0,0,0,0,0,0,0,0,0 +27,0,0,0,0,0,0,0,0,0,0 +28,0,0,0,0,0,0,0,0,0,0 +29,0,0,0,0,0,0,0,0,0,0 +30,0,0,0,0,0,0,0,0,0,0 +31,0,0,0,0,0,0,0,0,0,0 +32,0,0,0,0,0,0,0,0,0,0 +33,0,0,0,0,0,0,0,0,0,0 +34,0,0,0,0,0,0,0,0,0,0 +35,0,0,0,0,0,0,0,0,0,0 +36,0,0,0,0,0,0,0,0,0,0 +37,0,0,0,0,0,0,0,0,0,0 +38,0,0,0,0,0,0,0,0,0,0 +39,0,0,0,0,0,0,0,0,0,0 +40,0,0,0,0,0,0,0,0,0,0 +41,0,0,0,0,0,0,0,0,0,0 +42,0,0,0,0,0,0,0,0,0,0 +43,0,0,0,0,0,0,0,0,0,0 +44,0,0,0,0,0,0,0,0,0,0 +45,0,0,0,0,0,0,0,0,0,0 +46,0,0,0,0,0,0,0,0,0,0 +47,0,0,0,0,0,0,0,0,0,0 +48,0,0,0,0,0,0,0,0,0,0 +49,0,0,0,0,0,0,0,0,0,0 +50,0,0,0,0,0,0,0,0,0,0 +51,0,0,0,0,0,0,0,0,0,0 +52,0,0,0,0,0,0,0,0,0,0 +53,0,0,0,0,0,0,0,0,0,0 +54,0,0,0,0,0,0,0,0,0,0 +55,0,0,0,0,0,0,0,0,0,0 +56,0,0,0,0,0,0,0,0,0,0 +57,0,0,0,0,0,0,0,0,0,0 +58,0,0,0,0,0,0,0,0,0,0 +59,0,0,0,0,0,0,0,0,0,0 +60,0,0,0,0,0,0,0,0,0,0 +61,0,0,0,0,0,0,0,0,0,0 +62,0,0,0,0,0,0,0,0,0,0 +63,0,0,0,0,0,0,0,0,0,0 +64,0,0,0,0,0,0,0,0,0,0 +65,0,0,0,0,0,0,0,0,0,0 +66,0,0,0,0,0,0,0,0,0,0 +67,0,0,0,0,0,0,0,0,0,0 +68,0,0,0,0,0,0,0,0,0,0 +69,0,0,0,0,0,0,0,0,0,0 +70,0,0,0,0,0,0,0,0,0,0 +71,0,0,0,0,0,0,0,0,0,0 +72,0,0,0,0,0,0,0,0,0,0 +73,0,0,0,0,0,0,0,0,0,0 +74,0,0,0,0,0,0,0,0,0,0 +75,0,0,0,0,0,0,0,0,0,0 +76,0,0,0,0,0,0,0,0,0,0 +77,0,0,0,0,0,0,0,0,0,0 +78,0,0,0,0,0,0,0,0,0,0 +79,0,0,0,0,0,0,0,0,0,0 +80,0,0,0,0,0,0,0,0,0,0 +81,0,0,0,0,0,0,0,0,0,0 +82,0,0,0,0,0,0,0,0,0,0 +83,0,0,0,0,0,0,0,0,0,0 +84,0,0,0,0,0,0,0,0,0,0 +85,0,0,0,0,0,0,0,0,0,0 +86,0,0,0,0,0,0,0,0,0,0 +87,0,0,0,0,0,0,0,0,0,0 +88,0,0,0,0,0,0,0,0,0,0 +89,0,0,0,0,0,0,0,0,0,0 +90,0,0,0,0,0,0,0,0,0,0 +91,0,0,0,0,0,0,0,0,0,0 +92,0,0,0,0,0,0,0,0,0,0 +93,0,0,0,0,0,0,0,0,0,0 +94,0,0,0,0,0,0,0,0,0,0 +95,0,0,0,0,0,0,0,0,0,0 +96,0,0,0,0,0,0,0,0,0,0 +97,0,0,0,0,0,0,0,0,0,0 +98,0,0,0,0,0,0,0,0,0,0 +99,0,0,0,0,0,0,0,0,0,0 +100,0,0,0,0,0,0,0,0,0,0 +101,0,0,0,0,0,0,0,0,0,0 +102,0,0,0,0,0,0,0,0,0,0 +103,0,0,0,0,0,0,0,0,0,0 +104,0,0,0,0,0,0,0,0,0,0 +105,0,0,0,0,0,0,0,0,0,0 +106,0,0,0,0,0,0,0,0,0,0 +107,0,0,0,0,0,0,0,0,0,0 +108,0,0,0,0,0,0,0,0,0,0 +109,0,0,0,0,0,0,0,0,0,0 +110,0,0,0,0,0,0,0,0,0,0 +111,0,0,0,0,0,0,0,0,0,0 +112,0,0,0,0,0,0,0,0,0,0 +113,0,0,0,0,0,0,0,0,0,0 +114,0,0,0,0,0,0,0,0,0,0 +115,0,0,0,0,0,0,0,0,0,0 +116,0,0,0,0,0,0,0,0,0,0 +117,0,0,0,0,0,0,0,0,0,0 +118,0,0,0,0,0,0,0,0,0,0 +119,0,0,0,0,0,0,0,0,0,0 +120,0,0,0,0,0,0,0,0,0,0 +121,0,0,0,0,0,0,0,0,0,0 +122,0,0,0,0,0,0,0,0,0,0 +123,0,0,0,0,0,0,0,0,0,0 +124,0,0,0,0,0,0,0,0,0,0 +125,0,0,0,0,0,0,0,0,0,0 +126,0,0,0,0,0,0,0,0,0,0 +127,0,0,0,0,0,0,0,0,0,0 +128,0,0,0,0,0,0,0,0,0,0 +129,0,0,0,0,0,0,0,0,0,0 +130,0,0,0,0,0,0,0,0,0,0 +131,0,0,0,0,0,0,0,0,0,0 +132,0,0,0,0,0,0,0,0,0,0 +133,0,0,0,0,0,0,0,0,0,0 +134,0,0,0,0,0,0,0,0,0,0 +135,0,0,0,0,0,0,0,0,0,0 +136,0,0,0,0,0,0,0,0,0,0 +137,0,0,0,0,0,0,0,0,0,0 +138,0,0,0,0,0,0,0,0,0,0 +139,0,0,0,0,0,0,0,0,0,0 +140,0,0,0,0,0,0,0,0,0,0 +141,0,0,0,0,0,0,0,0,0,0 +142,0,0,0,0,0,0,0,0,0,0 +143,0,0,0,0,0,0,0,0,0,0 From 8f8771db274e201949bd4381e5ec0befc9d561df Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sat, 13 Jul 2019 15:14:51 -0600 Subject: [PATCH 110/167] (issue #343) created a input parameter for spinup years. --- ST_grid.c | 12 ++++++++++-- ST_structs.h | 1 + testing.sagebrush.master/Grid_Inputs/grid_setup.in | 1 + 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index e97925c4..1aa888b5 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -509,7 +509,7 @@ static void logProgress(int iteration, int year, Status status){ double calculateProgress(int year, int iteration, Status status){ double percentComplete; if(status == SPINUP){ - percentComplete = (year / (double) SuperGlobals.runModelYears); + percentComplete = (year / (double) SuperGlobals.runInitializationYears); } else if(status == SIMULATION) { percentComplete = ((iteration * SuperGlobals.runModelYears) + year) / (double) (SuperGlobals.runModelIterations * SuperGlobals.runModelYears); @@ -785,7 +785,7 @@ static void _run_spinup(void) } unload_cell(); // Reset the global variables - for (year = 1; year <= SuperGlobals.runModelYears; year++) + for (year = 1; year <= SuperGlobals.runInitializationYears; year++) { //for each year if(UseProgressBar){ logProgress(iter, year, SPINUP); @@ -2551,6 +2551,14 @@ static void _read_grid_setup(void) "Invalid grid setup file (Initialization line wrong. Valid options are \"spinup\", \"seeds\", or \"none\")"); } + if(InitializationMethod != INIT_WITH_NOTHING){ + GetALine(f, buf); + i = sscanf(buf, "%hd", &SuperGlobals.runInitializationYears); + if(i < 1){ + LogError(logfp, LOGFATAL, "Invalid grid setup file (Initialization years line wrong)"); + } + } + CloseFile(&f); } diff --git a/ST_structs.h b/ST_structs.h index ca921f5e..229cf4ef 100644 --- a/ST_structs.h +++ b/ST_structs.h @@ -327,6 +327,7 @@ struct superglobals_st { max_speciesnamelen; /* Maximum species name length. */ IntUS runModelIterations, + runInitializationYears, runModelYears, nCells; /* number of cells to use in Grid, only applicable if grid function is being used */ diff --git a/testing.sagebrush.master/Grid_Inputs/grid_setup.in b/testing.sagebrush.master/Grid_Inputs/grid_setup.in index 5b6a76a3..857cdf79 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_setup.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_setup.in @@ -5,3 +5,4 @@ 1 # use soils csv file (0 or 1)... 0 means no, 1 means yes 0 # use seed dispersal (0 or 1)... 0 means no, 1 means yes spinup # Initialization method. Options are "spinup", "seeds", or "none" +300 # Number of years to perform initialization. From 3fdc724ccc196f6d07a212c8859f3855cb709556 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sat, 13 Jul 2019 16:17:45 -0600 Subject: [PATCH 111/167] (issue #344) moved VW to species.in. This commit looks bigger than it actually is because I fixed some formatting issues along the way. The only real changes I made were adding a VW field to the species struct, initializing this field in _species_init, and used it in _read_seed_dispersal_in. --- ST_grid.c | 18 +++-- ST_params.c | 70 ++++++++++--------- ST_structs.h | 15 ++-- .../Grid_Inputs/grid_seed_dispersal.in | 3 - .../Stepwat_Inputs/Input/species.in | 41 +++++------ 5 files changed, 75 insertions(+), 72 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 1aa888b5..b44b8481 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2067,15 +2067,13 @@ static void _read_seed_dispersal_in(void) FILE *f; char buf[1024]; - float sd_Rate, H, VW, VT, MAXD, plotLength, d, pd; + float sd_Rate, H, VW, VT, MAXD, plotLength, pd, d; int maxCells, i, j, k, MAXDP, row, col, cell; SppIndex s; // read in the seed dispersal input file to get the constants that we need f = OpenFile(grid_files[GRID_FILE_SEED_DISPERSAL], "r"); - VW = _read_a_float(f, buf, grid_files[GRID_FILE_SEED_DISPERSAL], "VW line"); - GetALine(f, buf); if (sscanf(buf, "%d", &sd_DoOutput) != 1) LogError(logfp, LOGFATAL, @@ -2132,6 +2130,7 @@ static void _read_seed_dispersal_in(void) // set up grid_SD with the seed dispersal probabilities needed later on... H = Species[s]->sd_H; VT = Species[s]->sd_VT; + VW = Species[s]->sd_VW; MAXD = ((H * VW) / VT) / 100.0; // divide by 100.0 because we want it in meters, not centimeters sd_Rate = -(log(0.05) / MAXD); //sd_Rate is the seed dispersal rate... 0.05 = exp(-RATE*MAXD) => RATE = -(ln(0.05)/MAXD) See Coffin et al. 1993 @@ -2155,16 +2154,13 @@ static void _read_seed_dispersal_in(void) gridCells[row][col].mySeedDispersal[s].size = 0; //refers to the number of cells reachable... } - for (row = 1; row <= grid_Rows; row++) - for (col = 1; col <= grid_Cols; col++) - { - + for (row = 1; row <= grid_Rows; row++){ + for (col = 1; col <= grid_Cols; col++){ cell = col + ((row - 1) * grid_Cols) - 1; k = 0; - for (i = 1; i <= grid_Rows; i++) - for (j = 1; j <= grid_Cols; j++) - { + for (i = 1; i <= grid_Rows; i++) { + for (j = 1; j <= grid_Cols; j++){ if (i == row && j == col) continue; @@ -2180,7 +2176,9 @@ static void _read_seed_dispersal_in(void) k++; } } + } } + } for (i = 0; i < grid_Cells; i++) { row = i / grid_Cols; diff --git a/ST_params.c b/ST_params.c index 18a436d4..119c93d8 100644 --- a/ST_params.c +++ b/ST_params.c @@ -1018,7 +1018,7 @@ static void _species_init( void) { pseed; RealF irate, ratep, estab, minb, maxb, cohort, xdecay, p1, p2, p3, p4, p5, p6, p7; - float var; + float var, VW; char clonal[5]; MyFileName = Parm_name( F_Species); @@ -1182,39 +1182,45 @@ static void _species_init( void) { MyFileName); } - /* ------------------------------------------------- */ - /* ------- read the seed dispersal parameters ------ */ - sppok = readspp = TRUE; - while( readspp ) { - if( !GetALine(f, inbuf) ) {sppok=FALSE; break;} - if( !isnull(strstr(inbuf,"[end]")) ) { - readspp=FALSE; - continue; - } + /* ------------------------------------------------- */ + /* ------- read the seed dispersal parameters ------ */ + sppok = readspp = TRUE; + while( readspp ) { + if( !GetALine(f, inbuf) ) { + sppok=FALSE; break; + } + if( !isnull(strstr(inbuf,"[end]")) ) { + readspp=FALSE; + continue; + } - x = sscanf( inbuf, "%s %hd %f %f %f %f %f %f %f", - name, &turnondispersal, &p1, &p2, &p3, &p4, &p5, &p6, &p7); - if(x < 9) - LogError(logfp, LOGFATAL, "%s: Too few columns in species seed dispersal inputs", MyFileName); - - sp = Species_Name2Index(name); - if(sp < 0) - LogError(logfp, LOGFATAL, "%s: Mismatched name (%s) for species seed dispersal inputs", MyFileName, name); - - Species[sp]->use_dispersal = itob(turnondispersal); - Species[sp]->allow_growth = TRUE; - Species[sp]->sd_sgerm = FALSE; - - Species[sp]->sd_Param1 = p1; - Species[sp]->sd_PPTdry = p2; - Species[sp]->sd_PPTwet = p3; - Species[sp]->sd_Pmin = p4; - Species[sp]->sd_Pmax = p5; - Species[sp]->sd_H = p6; - Species[sp]->sd_VT = p7; - } - if(!sppok) + x = sscanf( inbuf, "%s %hd %f %f %f %f %f %f %f %f", + name, &turnondispersal, &p1, &p2, &p3, &p4, &p5, &p6, &p7, &VW); + if(x < 10) { + LogError(logfp, LOGFATAL, "%s: Too few columns in species seed dispersal inputs", MyFileName); + } + + sp = Species_Name2Index(name); + if(sp < 0){ + LogError(logfp, LOGFATAL, "%s: Mismatched name (%s) for species seed dispersal inputs", MyFileName, name); + } + + Species[sp]->use_dispersal = itob(turnondispersal); + Species[sp]->allow_growth = TRUE; + Species[sp]->sd_sgerm = FALSE; + + Species[sp]->sd_Param1 = p1; + Species[sp]->sd_PPTdry = p2; + Species[sp]->sd_PPTwet = p3; + Species[sp]->sd_Pmin = p4; + Species[sp]->sd_Pmax = p5; + Species[sp]->sd_H = p6; + Species[sp]->sd_VT = p7; + Species[sp]->sd_VW = VW; + } + if(!sppok) { LogError(logfp, LOGFATAL, "%s: Incorrect/incomplete input in species seed dispersal input", MyFileName); + } Mem_Free(name); diff --git a/ST_structs.h b/ST_structs.h index 229cf4ef..c4bd04c4 100644 --- a/ST_structs.h +++ b/ST_structs.h @@ -123,13 +123,14 @@ struct species_st { cohort_surv, exp_decay, /* annuals: exponent for viability decay function */ prob_veggrow[4], /* 1 value for each mortality type, if clonal*/ - sd_Param1, /* for seed dispersal */ - sd_PPTdry, - sd_PPTwet, - sd_Pmin, - sd_Pmax, - sd_H, - sd_VT; + sd_Param1, /* for seed dispersal */ + sd_PPTdry, /* for seed dispersal */ + sd_PPTwet, /* for seed dispersal */ + sd_Pmin, /* for seed dispersal */ + sd_Pmax, /* for seed dispersal */ + sd_H, /* for seed dispersal */ + sd_VT, /* for seed dispersal */ + sd_VW; /* for seed dispersal */ TempClass tempclass; DisturbClass disturbclass; Bool isclonal, diff --git a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in b/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in index 2f46374f..3e8abff7 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in @@ -1,8 +1,5 @@ # Seed dispersal setup for STEPWAT grid version - DLM 07-29-13. This file contains constants that are used in seed dispersal. The rest of the seed dispersal inputs are set up on a species basis in the species input file. -#CONSTANTS from the max distance function: MAXD = (H * VW) / VT. MAXD refers to the maximum distance that a seed can be dispersed to. If you're MAXD ends up being really small, then you can get kinda weird results, so be careful. -500.0 # VW - the mean horizontal wind speed (500 cm/sec in the paper) - #SEED DISPERSAL OUTPUTS 1 # output seed dispersal (ie. the total probability that a cell received seeds for each cell for each year for each species)? 1 means yes, 0 means no 1 # output header (ie. the names of all the species)? 1 means yes, 0 means no. Suggested: yes, as it's hard to figure out what all the numbers mean elsewise. diff --git a/testing.sagebrush.master/Stepwat_Inputs/Input/species.in b/testing.sagebrush.master/Stepwat_Inputs/Input/species.in index e18907b5..c8ac9ca4 100644 --- a/testing.sagebrush.master/Stepwat_Inputs/Input/species.in +++ b/testing.sagebrush.master/Stepwat_Inputs/Input/species.in @@ -173,29 +173,30 @@ # Pmax = probability of producing seeds in a wet year # H = the average release height of the inflorescences (cm) # VT = the average sinking velocity of the seeds (cm/sec) +# VW - the mean horizontal wind speed (500 cm/sec in the paper) # # name dispersal param1 PPTdry PPTwet Pmin Pmax H VT - artr 1 0.5 105 520 0.01 0.55 30.0 100.0 - trdu 1 0.5 105 520 0.01 0.55 30.0 100.0 - cryp 1 0.5 105 520 0.01 0.55 30.0 100.0 - amre 1 0.5 105 520 0.01 0.55 30.0 100.0 - chen 1 0.5 105 520 0.01 0.55 30.0 100.0 - acmi 1 0.5 105 520 0.01 0.55 30.0 100.0 - phho 1 0.5 105 520 0.01 0.55 30.0 100.0 - arfr 1 0.5 105 520 0.01 0.55 30.0 100.0 - lipu 1 0.5 105 520 0.01 0.55 30.0 100.0 - brte 1 0.5 105 520 0.01 0.55 30.0 100.0 - vuoc 1 0.5 105 520 0.01 0.55 30.0 100.0 - pssp 1 0.5 105 520 0.01 0.55 30.0 100.0 - koma 1 0.5 105 520 0.01 0.55 30.0 100.0 - bogr 1 0.5 105 520 0.01 0.55 30.0 100.0 - spcr 1 0.5 105 520 0.01 0.55 30.0 100.0 - gusa 1 0.5 105 520 0.01 0.55 30.0 100.0 - chvi 1 0.5 105 520 0.01 0.55 30.0 100.0 - oppo 1 0.5 105 520 0.01 0.55 30.0 100.0 + artr 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + trdu 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + cryp 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + amre 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + chen 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + acmi 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + phho 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + arfr 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + lipu 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + brte 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + vuoc 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + pssp 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + koma 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + bogr 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + spcr 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + gusa 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + chvi 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 + oppo 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 -#spp1 1 0.5 105 520 0.01 0.55 30.0 100.0 -#spp2 1 0.5 105 520 0.01 0.55 30.0 100.0 +#spp1 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 +#spp2 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 [end] # this marks the end of the seed-dispersal parameters From 1e60f6af5396dc6f3ee710f3d35113d4f72a0d72 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sat, 13 Jul 2019 16:19:17 -0600 Subject: [PATCH 112/167] (issue #344) added VW column header to species.in I forgot to do this is the last commit. --- testing.sagebrush.master/Stepwat_Inputs/Input/species.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing.sagebrush.master/Stepwat_Inputs/Input/species.in b/testing.sagebrush.master/Stepwat_Inputs/Input/species.in index c8ac9ca4..6e1c4760 100644 --- a/testing.sagebrush.master/Stepwat_Inputs/Input/species.in +++ b/testing.sagebrush.master/Stepwat_Inputs/Input/species.in @@ -175,7 +175,7 @@ # VT = the average sinking velocity of the seeds (cm/sec) # VW - the mean horizontal wind speed (500 cm/sec in the paper) # -# name dispersal param1 PPTdry PPTwet Pmin Pmax H VT +# name dispersal param1 PPTdry PPTwet Pmin Pmax H VT VW artr 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 trdu 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 cryp 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 From 6ec9a3b73025723aa23a230725b86d6dccee8fd3 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sat, 13 Jul 2019 17:16:57 -0600 Subject: [PATCH 113/167] Combined grid_seed_dispersal.in and grid_setup.in (issue #351) I combined these files because they both have few parameters. I also combined number of years of seed dispersal and number of years of spinup into a single variable called runInitializationYears (issue #342) We no longer needed _read_seed_dispersal_in(), but we did need the algorithm for calculating MAXD for seed dispersal. Therefore I removed the fale reading section of code and renamed the function_init_seed_dispersal(). --- ST_grid.c | 81 ++++++++----------- .../Grid_Inputs/grid_seed_dispersal.in | 9 --- .../Grid_Inputs/grid_setup.in | 7 +- testing.sagebrush.master/files.in | 1 - 4 files changed, 41 insertions(+), 57 deletions(-) delete mode 100644 testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in diff --git a/ST_grid.c b/ST_grid.c index b44b8481..72b32b75 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -217,7 +217,6 @@ enum GRID_FILE_SETUP, GRID_FILE_DISTURBANCES, GRID_FILE_SOILS, - GRID_FILE_SEED_DISPERSAL, GRID_FILE_INIT_SPECIES, GRID_FILE_FILES, GRID_FILE_MAXRGROUPSPECIES, @@ -250,7 +249,7 @@ typedef enum char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; -int grid_Cols, grid_Rows, grid_Cells, sd_NYearsSeedsAvailable; +int grid_Cols, grid_Rows, grid_Cells; int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans // these variables are for storing the globals in STEPPE... they are dynamically allocated/freed @@ -416,7 +415,7 @@ static void _init_soil_layers(int cell, int isSpinup); static float _read_a_float(FILE *f, char *buf, const char *filename, const char *descriptor); static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); -static void _read_seed_dispersal_in(void); +static void _init_seed_dispersal(void); static void _do_seed_dispersal(void); static void _read_init_species(void); @@ -528,7 +527,7 @@ static void printGeneralInfo(void){ if(UseDisturbances) printf("Using grid disturbances file\n"); if(UseSoils) printf("Using grid soils file\n"); if(InitializationMethod == INIT_WITH_SEEDS){ - printf("Seeds availible for %d years at the start of the simulation.\n",sd_NYearsSeedsAvailable); + printf("Seeds availible for %d years at the start of the simulation.\n",SuperGlobals.runInitializationYears); } else if(InitializationMethod == INIT_WITH_SPINUP) { printf("Running Spinup\n"); } @@ -989,7 +988,7 @@ static void _init_grid_inputs(void) _read_disturbances_in(); if (UseSeedDispersal || InitializationMethod != INIT_WITH_NOTHING) { - _read_seed_dispersal_in(); + _init_seed_dispersal(); _read_init_species(); } if (UseSoils) @@ -2027,7 +2026,7 @@ static void _init_soil_layers(int cell, int isSpinup) static float _read_a_float(FILE *f, char *buf, const char *filename, const char *descriptor) { - //small function to reduce code duplication in the _read_seed_dispersal_in() function... + //small function to reduce code duplication in the _init_seed_dispersal() function... //f should be already open, and all of the character arrays should be pre-allocated before calling the function... float result; @@ -2060,54 +2059,22 @@ static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) } } -/***********************************************************/ -static void _read_seed_dispersal_in(void) +/* Initialize all derived seed dispersal variables. (variables that are not specified directly in inputs). + This function is safe to call multiple times, but it only needs to be called once.*/ +static void _init_seed_dispersal(void) { // reads the grid seed dispersal input file and sets up grid_SD with the correct values and probabilities - FILE *f; char buf[1024]; float sd_Rate, H, VW, VT, MAXD, plotLength, pd, d; int maxCells, i, j, k, MAXDP, row, col, cell; SppIndex s; - // read in the seed dispersal input file to get the constants that we need - f = OpenFile(grid_files[GRID_FILE_SEED_DISPERSAL], "r"); - - GetALine(f, buf); - if (sscanf(buf, "%d", &sd_DoOutput) != 1) - LogError(logfp, LOGFATAL, - "Invalid %s file: seed dispersal output line\n", grid_files[GRID_FILE_SEED_DISPERSAL]); - - GetALine(f, buf); - if (sscanf(buf, "%d", &sd_MakeHeader) != 1) - LogError(logfp, LOGFATAL, - "Invalid %s file: seed dispersal make header line\n", - grid_files[GRID_FILE_SEED_DISPERSAL]); - - GetALine(f, buf); - if (sscanf(buf, "%c", &sd_Sep) != 1) - LogError(logfp, LOGFATAL, - "Invalid %s file: seed dispersal seperator line\n", - grid_files[GRID_FILE_SEED_DISPERSAL]); - - if (sd_Sep == 't') //dealing with tab and space special cases... - sd_Sep = '\t'; - else if (sd_Sep == 's') - sd_Sep = ' '; - - GetALine(f, buf); - if (sscanf(buf, "%d", &sd_NYearsSeedsAvailable) != 1) - LogError(logfp, LOGFATAL, "Invalid %s file: option 1 line\n", - grid_files[GRID_FILE_SEED_DISPERSAL]); - - CloseFile(&f); - for (i = 0; i < grid_Cells; i++) { row = i / grid_Cols; col = i % grid_Cols; - gridCells[row][col].mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_read_seed_dispersal_in"); + gridCells[row][col].mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_init_seed_dispersal"); } /* @@ -2148,9 +2115,9 @@ static void _read_seed_dispersal_in(void) col = i % grid_Cols; gridCells[row][col].mySeedDispersal[s].cells = Mem_Calloc(maxCells, sizeof(int), - "_read_seed_dispersal_in()"); //the cell number + "_init_seed_dispersal()"); //the cell number gridCells[row][col].mySeedDispersal[s].prob = Mem_Calloc(maxCells, sizeof(float), - "_read_seed_dispersal_in()"); //the probability that the cell will disperse seeds to this distance + "_init_seed_dispersal()"); //the probability that the cell will disperse seeds to this distance gridCells[row][col].mySeedDispersal[s].size = 0; //refers to the number of cells reachable... } @@ -2256,11 +2223,11 @@ static void _do_seed_dispersal(void) load_cell(row, col); - if (Globals->currYear <= sd_NYearsSeedsAvailable) + if (Globals->currYear <= SuperGlobals.runInitializationYears) { cell->mySeedDispersal[s].seeds_present = 1; } - else if (Globals->currYear <= sd_NYearsSeedsAvailable + else if (Globals->currYear <= SuperGlobals.runInitializationYears && cell->mySpeciesInit.shouldBeInitialized[s]) { cell->mySeedDispersal[s].seeds_present = 1; @@ -2557,6 +2524,28 @@ static void _read_grid_setup(void) } } + GetALine(f, buf); + if (sscanf(buf, "%d", &sd_DoOutput) != 1) + LogError(logfp, LOGFATAL, + "Invalid %s file: seed dispersal output line\n", grid_files[GRID_FILE_SETUP]); + + GetALine(f, buf); + if (sscanf(buf, "%d", &sd_MakeHeader) != 1) + LogError(logfp, LOGFATAL, + "Invalid %s file: seed dispersal make header line\n", + grid_files[GRID_FILE_SETUP]); + + GetALine(f, buf); + if (sscanf(buf, "%c", &sd_Sep) != 1) + LogError(logfp, LOGFATAL, + "Invalid %s file: seed dispersal seperator line\n", + grid_files[GRID_FILE_SETUP]); + + if (sd_Sep == 't') //dealing with tab and space special cases... + sd_Sep = '\t'; + else if (sd_Sep == 's') + sd_Sep = ' '; + CloseFile(&f); } diff --git a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in b/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in deleted file mode 100644 index 3e8abff7..00000000 --- a/testing.sagebrush.master/Grid_Inputs/grid_seed_dispersal.in +++ /dev/null @@ -1,9 +0,0 @@ -# Seed dispersal setup for STEPWAT grid version - DLM 07-29-13. This file contains constants that are used in seed dispersal. The rest of the seed dispersal inputs are set up on a species basis in the species input file. - -#SEED DISPERSAL OUTPUTS -1 # output seed dispersal (ie. the total probability that a cell received seeds for each cell for each year for each species)? 1 means yes, 0 means no -1 # output header (ie. the names of all the species)? 1 means yes, 0 means no. Suggested: yes, as it's hard to figure out what all the numbers mean elsewise. -, # output seperator... specify one of the following as a separator: t = tab, s = space, or any single character such as , | : etc (excluding '#','t', and 's'). Suggested: tab. - -#Seed Availability options -10 # number of years N at the beginning of the simulation during which seeds are available for germination. Input: N years. \ No newline at end of file diff --git a/testing.sagebrush.master/Grid_Inputs/grid_setup.in b/testing.sagebrush.master/Grid_Inputs/grid_setup.in index 857cdf79..55ff2d1f 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_setup.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_setup.in @@ -5,4 +5,9 @@ 1 # use soils csv file (0 or 1)... 0 means no, 1 means yes 0 # use seed dispersal (0 or 1)... 0 means no, 1 means yes spinup # Initialization method. Options are "spinup", "seeds", or "none" -300 # Number of years to perform initialization. +300 # Number of years to perform initialization (whichever method you choose). + +#SEED DISPERSAL OUTPUTS +1 # output seed dispersal summary file? 1 means yes, 0 means no +1 # output header? 1 means yes, 0 means no. +, # output seperator. Valid options are: t = tab, s = space, or any single character such as , | : etc (excluding '#','t', and 's'). Suggested: tab. diff --git a/testing.sagebrush.master/files.in b/testing.sagebrush.master/files.in index 384dabba..ac708fd7 100644 --- a/testing.sagebrush.master/files.in +++ b/testing.sagebrush.master/files.in @@ -7,7 +7,6 @@ g_logfile.log # name of logfile (can also be stdout) Grid_Inputs/grid_setup.in # name of grid setup file Grid_Inputs/grid_disturbances.csv # name of grid disturbances input file Grid_Inputs/grid_soils.csv # name of grid soils input file -Grid_Inputs/grid_seed_dispersal.in # name of grid seed dispersal setup file Grid_Inputs/grid_initSpecies.csv # name of grid species input file files.in # name of stepwat files.in file From 3ce4b5fe1219b999aa0b779d0d99f29582676689 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 15 Jul 2019 09:23:32 -0600 Subject: [PATCH 114/167] Removed unused variables deprecated by merging grid_seed_dispersal and grid_setup These variables were in _init_seed_dispersal (formerly _read_seed_dispersal_in). --- ST_grid.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 72b32b75..eb0ef37a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2063,9 +2063,6 @@ static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) This function is safe to call multiple times, but it only needs to be called once.*/ static void _init_seed_dispersal(void) { - // reads the grid seed dispersal input file and sets up grid_SD with the correct values and probabilities - FILE *f; - char buf[1024]; float sd_Rate, H, VW, VT, MAXD, plotLength, pd, d; int maxCells, i, j, k, MAXDP, row, col, cell; SppIndex s; From 4be9ffcdf8ed70884011c05e2b48f5fea91e7f3f Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 15 Jul 2019 09:31:14 -0600 Subject: [PATCH 115/167] Removed deprecated function _read_a_float. This function is never used and it obfuscates the code. (issue #311) --- ST_grid.c | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index eb0ef37a..8eda64cb 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -412,8 +412,6 @@ static void unload_cell(void); static void _read_disturbances_in(void); static void _read_soils_in(void); static void _init_soil_layers(int cell, int isSpinup); -static float _read_a_float(FILE *f, char *buf, const char *filename, - const char *descriptor); static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); static void _init_seed_dispersal(void); static void _do_seed_dispersal(void); @@ -2022,22 +2020,6 @@ static void _init_soil_layers(int cell, int isSpinup) } } -/***********************************************************/ -static float _read_a_float(FILE *f, char *buf, const char *filename, - const char *descriptor) -{ - //small function to reduce code duplication in the _init_seed_dispersal() function... - //f should be already open, and all of the character arrays should be pre-allocated before calling the function... - float result; - - if (!GetALine(f, buf)) - LogError(logfp, LOGFATAL, "Invalid %s file: %s", filename, descriptor); - if (sscanf(buf, "%f", &result) != 1) - LogError(logfp, LOGFATAL, "Invalid %s file: %s", filename, descriptor); - - return result; -} - /***********************************************************/ static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) { From 6a77ca66f32c61fd849eb6d3d15059b076584b1b Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 15 Jul 2019 10:12:09 -0600 Subject: [PATCH 116/167] Continued work on the Initialization process. (issue #342) I added a new function called runInitialization which takes care of choosing the initialization method as well as saving after initialization. I also added _run_seed_initialization which will be the seed dispersal initialization function once it has been planned. For now it just lets the user know that they have chosen an option that is currently unavailible. Since runInitialization takes care of EVERYTHING involved with initialization I removed the calls to beginInitialization and endInitialization from _run_spinup. --- ST_grid.c | 42 +++++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 8eda64cb..10c246b2 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -393,6 +393,8 @@ static void logProgress(int iteration, int year, Status status); static double calculateProgress(int year, int iteration, Status status); static void printGeneralInfo(void); static void _run_spinup(void); +static void _run_seed_initialization(void); +static void runInitialization(void); static void beginInitialization(void); static void endInitialization(void); static void saveAsInitializationConditions(void); @@ -525,9 +527,12 @@ static void printGeneralInfo(void){ if(UseDisturbances) printf("Using grid disturbances file\n"); if(UseSoils) printf("Using grid soils file\n"); if(InitializationMethod == INIT_WITH_SEEDS){ - printf("Seeds availible for %d years at the start of the simulation.\n",SuperGlobals.runInitializationYears); + printf("Running seed dispersal as initialization\n"); } else if(InitializationMethod == INIT_WITH_SPINUP) { - printf("Running Spinup\n"); + printf("Running Spinup as initialization\n"); + } + if(InitializationMethod != INIT_WITH_NOTHING){ + printf("Number of initialization years: %d\n", SuperGlobals.runInitializationYears); } if(UseSeedDispersal){ printf("Dispersing seeds between cells\n"); @@ -555,8 +560,8 @@ void runGrid(void) printGeneralInfo(); - if (InitializationMethod == INIT_WITH_SPINUP) { - _run_spinup(); // does the initial spinup + if(InitializationMethod != INIT_WITH_NOTHING){ + runInitialization(); } else { /* If no spinup is requested we still need to reset SXW to set the historical weather file names. */ @@ -748,8 +753,6 @@ static void _run_spinup(void) /* killedany for mortality functions */ Bool killedany; - beginInitialization(); - if (!UseSoils) { // if we're not using inputting soils then there is simply one soil type as all the soils are the same nSoilTypes = 1; @@ -839,6 +842,31 @@ static void _run_spinup(void) SW_Soilwat.hist.file_prefix = NULL; ChDir(".."); } /* End iterations */ +} + +/* TODO: This is a dummy method. It needs to be implemented once seed dispersal is fully planned. */ +static void _run_seed_initialization(void){ + printf("You have attempted to initialize with seed dispersal.\n" + "This option is currently in development and will be availible soon.\n"); + return; +} + +/* Initializes the plot with whichever method you have specified with InitializationMethod. + This function takes care of EVERYTHING involved with initialization. + After calling this function you can load in the initialization information by calling loadInitializationConditions(). */ +static void runInitialization(void){ + beginInitialization(); + + switch (InitializationMethod){ + case INIT_WITH_SPINUP: + _run_spinup(); + break; + case INIT_WITH_SEEDS: + _run_seed_initialization(); + break; + default: + break; + } endInitialization(); } @@ -886,7 +914,7 @@ static void endInitialization(void){ beginInitialization(); // Save the state of the program as our initialization conditions. saveAsInitializationConditions(); - // We have now exited spinup. + // We have now exited initialization. DuringInitialization = FALSE; } From f7faa9dd480fa6e4e057069c8d4bdd872a3826b1 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 15 Jul 2019 10:45:59 -0600 Subject: [PATCH 117/167] Removed deprecated summary at the top of the file (issue #312) I replaced the explaination of deep copying with a brief explaination of gridded mode. I would add more documentation, but I think we are going to start developing a wiki page instead. --- ST_grid.c | 70 ++++++++++++------------------------------------------- 1 file changed, 15 insertions(+), 55 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 10c246b2..d7b41b32 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1,65 +1,25 @@ -/********************************************************/ +/********************************************************************************/ // Source file: ST_grid.c // Type: module // Application: STEPPE - plant community dynamics simulator // Purpose: This module handles the grid. // History: // (5/24/2013) -- INITIAL CODING - DLM -// -// WARNING: This module deals with a LARGE amount of dynamic memory allocation/deallocation (there can be potentially hundreds of thousands of allocations/frees called by this code depending on settings ran). -// Be very wary when editing it as even small changes could possibly cause massive memory errors/leaks to occur. In particular be careful when copy/freeing the linked list of individuals (I would suggest just using the code I wrote for this as it works and it's pretty easy to screw it up). -// Always keep in mind that for every time memory is allocated (every time alloc or calloc is called), a corresponding free is required. I would recommend valgrind or a similar program to debug memory errors as doing it without some kind of tool would be crazy. -/********************************************************/ +// (March - July 2019) -- Overhauled by Chandler Haukap with Fredrick Pierson +/********************************************************************************/ /* - - ---------------------------------------------------------------------------------------------------------------- - ---------------------------------------------------------------------------------------------------------------- - (DLM) : 7-16-2012 : General notes about this module and why it does certain things (put in the beginning so that they'd be seen) - ---------------------------------------------------------------------------------------------------------------- - ---------------------------------------------------------------------------------------------------------------- - - ---------------------------------------------------------------------------------------------------------------- - the general idea when copying over the dynamically allocated data is (ie. how to deep copy a structure): - ---------------------------------------------------------------------------------------------------------------- - - 1.) Free the dynamically allocated memory (use the _free_head() function to free a linked list of individuals) - 2.) Shallow copy the data (ie. *Species[s] = grid_Species[s][cell])... this will correctly copy all of the data of the structure that isn't a pointer. For the pointers it will simply copy the address (hence why it is a shallow copy). - 3.) Allocate the appropriate amount of memory for the pointers that are being copied to - 4.) Use memcpy to copy the data over to your newly allocated pointer (or use the _copy_head() function to copy the linked list of individuals) - 5.) Be careful at all stages of this process as it is easy to make a simple error that can be very aggravating to try and track down. - - ---------------------------------------------------------------------------------------------------------------- - explanation of why all this trouble is gone through when copying the memory (as it is not obvious by any means): - ---------------------------------------------------------------------------------------------------------------- - - First off, the sizes of all the dynamically allocated memory can be different for every grid cell. To deal with this we free and reallocate memory every time we copy a grid cell. - This also gets around the problem that doing a shallow copy via something like "*Species[s] = grid_Species[s][cell]" would overwrite the address of all the pointers contained within and cause a memory leak if they had already been allocated memory. - The only other way to copy the data would be to individually copy each data member of each structure which would lead to both a much larger code size and code that would break every time a new member is added to any structure in the program while providing likely no performance difference. - It is also important to know what the difference between a shallow copy and a deep copy is. When we are copying over all of these variables, what we want is a deep copy (never to be confused with a shallow copy). - A shallow copy of a structure is when all of the data members are copied over. However, the pointers are treated specially. Instead of copying the data contained within the pointers directly it simply copies the address. - This leaves two pointers that point to the same thing (not what we want) and if the pointer that is copied over was pointing to any memory it would subsequently cause a memory leak. - A deep copy of a structure will copy over all of the data members and copy the memory that the pointers are pointing to (not the addresses). It would be great if C inherently knew how to do this, but it does not. - C's copy constructor cannot know how to do this because it cannot know the length of the pointers. Also, it would be potentially confusing as it would have to allocate memory which would be unexpected. - We must code this behavior in so that we copy over the values held by the pointers into the copy's own separate memory. - - ---------------------------------------------------------------------------------------------------------------- - about performance concerns: - ---------------------------------------------------------------------------------------------------------------- - - This module (ST_grid.c) allocates/deallocates a very large amount of memory. It does so because it must in order to successfully run as desired. - The performance hit of all this memory management is surprisingly low in CPU execution time. Luckily, modern day implementations of malloc/free/memcpy are very fast. - After profiling the code the time spent allocating/deallocating/copying memory is completely negligible compared to the time spent doing calculations. - Where the approach has it's downsides is that the program requires a TON of memory in order to do large simulations (ie. it took around 2.8 GB for a 10,000 cell grid when I tried it). - This shouldn't be an issue in most cases. It is unavoidable though that at some point the number of cells in a simulation will be bounded by the amount of memory available. - Issues could possibly arise if you're trying to run a simulation that requires more memory then your system has available. I don't know of a way to easily check for that condition, so just don't do it. - - ---------------------------------------------------------------------------------------------------------------- - If any of the concepts I have been discussing seem confusing (or your knowledge of pointers feels rusty) I would suggest brushing up on your pointers/memory management. - Some things to go over would be correct free/alloc/memcpy usage (keep in mind that a free is needed for every corresponding alloc call, some people seem not to comprehend that a pointer of pointers (ie. int**) must be freed in multiple steps, otherwise you lose memory), pointer arithmetic, and the difference between arrays & pointers in C. - ---------------------------------------------------------------------------------------------------------------- - (AKT) : 9-7-2015 : Added extra Grid Cell Avg Output file for biomass values - */ -/********************************************************/ + Summary: + This module handles the gridded mode of STEPWAT2. To accomplish this we use a grid of cells represented by the + CellType struct. The entire grid of cells can be referenced by the gridCells variable which is a 2d array of + CellTypes. To allow this module to use the same functions as non-gridded mode the CellType structs must be loaded + into the global variables using the load_cell function. As long as a cell is loaded in you can be sure that all + functions will work as expected. + +    In addition to all of the functionality of non-gridded mode, gridded mode has two additional features: + initialization and seed dispersal. Initialization allows the user to run some small-scale simulation to allow + the environment to stabilize before recording any statistics. Seed dispersal allows each cell to disperse seeds + to nearby cells. +*/ /* =================================================== */ /* INCLUDES / DEFINES */ From bde26a7a015a911d219ee63fcc177a3f10b4ffcb Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 15 Jul 2019 11:58:05 -0600 Subject: [PATCH 118/167] Reviewed parameter initialization functions and made small changes. My intention with this commit was to review all changes to all input functions. Along the way I made a few programatic changes. I also added descriptions of every function directly above them. (issue #286) * I removed the function _init_grid_globals. The only thing left in the function was allocation of two old arrays that are set but never used. (issue #285) In _init_grid_inputs: * Added brackets to all dangling if statements. * Modified the logic around the calls to _init_seed_dispersal and _read_init_species. In _read_soils_in: * I commented out references to grid_SoilTypes and soilTypes_Array. These variables are deprecated but I still need to review them to ensure all of their functionallity is accounted for. In _run_spinup: * Since I removed _init_grid_globals I had to removed the refrences to the deprecated variables. These variables were set in _run_spinup, but never used for anything. --- ST_grid.c | 78 +++++++++++++++++-------------------------------------- 1 file changed, 24 insertions(+), 54 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index d7b41b32..6d8ed124 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -363,7 +363,6 @@ static void _init_grid_files(void); static void _init_grid_inputs(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); static void _init_stepwat_inputs(void); -static void _init_grid_globals(void); static void allocate_gridCells(int rows, int cols); static void allocate_accumulators(void); static void _free_grid_memory(void); @@ -713,14 +712,6 @@ static void _run_spinup(void) /* killedany for mortality functions */ Bool killedany; - if (!UseSoils) - { // if we're not using inputting soils then there is simply one soil type as all the soils are the same - nSoilTypes = 1; - soilTypes_Array[0] = 0; - for (i = 0; i < grid_Cells; i++) - grid_SoilTypes[i] = 0; - } - for (iter = 1; iter <= 1; iter++) { //for each iteration... only 1 iteration allowed for now @@ -921,11 +912,11 @@ static void loadInitializationConditions(){ } -/***********************************************************/ +/* Read the files.in file which was supplied to the program as an argument. + This function saves the file names it reads to grid_files and grid_directories. */ static void _init_grid_files(void) { // reads the files.in file - FILE *f; char buf[1024]; int i; @@ -956,29 +947,28 @@ static void _init_grid_files(void) else logfp = OpenFile(grid_files[GRID_FILE_LOGFILE], "w"); - /*printf("stepwat dir: %s\n", grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); - for(i = 0; i < N_GRID_FILES; i++) - printf("%d : %s\n", i, grid_files[i]);*/ - CloseFile(&f); } -/***********************************************************/ +/* Read all gridded mode files excluding grid_setup.in. This function overrided values specified in non-gridded + mode files, so make sure you have read the non-gridded mode files before calling this function.*/ static void _init_grid_inputs(void) { int i, j; - _init_grid_globals(); - - if (UseDisturbances) + if (UseDisturbances){ _read_disturbances_in(); - if (UseSeedDispersal || InitializationMethod != INIT_WITH_NOTHING) + } + if (UseSeedDispersal || InitializationMethod == INIT_WITH_SEEDS) { _init_seed_dispersal(); + } + if(InitializationMethod != INIT_WITH_NOTHING){ _read_init_species(); } - if (UseSoils) + if (UseSoils) { _read_soils_in(); + } for(i = 0; i < grid_Rows; ++i) { for(j = 0; j < grid_Cols; ++j) { @@ -986,10 +976,10 @@ static void _init_grid_inputs(void) gridCells[i][j].DuringInitialization = FALSE; } } - unload_cell(); } -/***********************************************************/ + +/* Read SXW input files */ static void _init_SXW_inputs(Bool init_SW, char *f_roots) { SXW_Init(init_SW, f_roots); // initializes soilwat @@ -1002,7 +992,7 @@ static void _init_SXW_inputs(Bool init_SW, char *f_roots) } /* Read in the STEPWAT2 files and populate the grid. This only needs to be called once. - DEPENDENCYS: allocate_gridCells() must be called first. */ + DEPENDENCYS: gridCells must be allocated first. */ static void _init_stepwat_inputs(void) { int i, j; // Used as indices in gridCells @@ -1315,18 +1305,6 @@ static IndivType* _copy_head(IndivType *head) return _copy_individuals(head); } -/***********************************************************/ -static void _init_grid_globals(void) -{ - //initializes grid variables, allocating the memory necessary for them (this step is only needed to be done once) - - // Keep these until I know if the CellType struct accounts for these variables. - soilTypes_Array = Mem_Calloc(grid_Cells, sizeof(int*), - "_init_grid_globals()"); - grid_SoilTypes = Mem_Calloc(grid_Cells, sizeof(int*), - "_init_grid_globals()"); -} - /* Free all memory allocated to the gridded mode during initialization. */ static void _free_grid_memory(void) { @@ -1578,14 +1556,9 @@ static Bool GetALine2(FILE *f, char buf[], int limit) return TRUE; } -/***********************************************************/ +/* Reads the grid disturbance CSV. This function will override disturbance inputs from non-gridded mode. */ static void _read_disturbances_in(void) { - // reads the grid disturbances input file - // the file should be something like: "cell,use_fecal_pats,use_ant_mounds,use_animal_burrows,kill_yr" - // there should be no spaces in between, just commas separating the values - // kill_yr will overwrite the kill year for each RGroup in the cell (0 means don't use, a # > 0 means kill everything at this year) - FILE *f; char buf[1024]; int i, row, col, cell, num = 0; @@ -1738,20 +1711,21 @@ static void _read_soils_in(void) gridCells[row][col].mySoils.num_layers = gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers; // TODO: figure out how to change this code for our new struct - grid_SoilTypes[cell] = grid_SoilTypes[copy_cell]; + // grid_SoilTypes[cell] = grid_SoilTypes[copy_cell]; strcpy(gridCells[row][col].mySoils.rootsFile, gridCells[copy_cell_row][copy_cell_col].mySoils.rootsFile); continue; } - else if (do_copy == 1) + else if (do_copy == 1){ LogError(logfp, LOGFATAL, "Invalid %s file line %d invalid copy_cell attempt", grid_files[GRID_FILE_SOILS], i + 2); + } // TODO: figure out how to change this code for our new struct - grid_SoilTypes[cell] = nSoilTypes; - soilTypes_Array[nSoilTypes] = cell; + // grid_SoilTypes[cell] = nSoilTypes; + // soilTypes_Array[nSoilTypes] = cell; nSoilTypes++; depthMin = 0; @@ -2320,13 +2294,9 @@ static void _do_seed_dispersal(void) unload_cell(); } -/***********************************************************/ +/* Read the species initialization CSV. This function only needs to be called if the user requests initialization.*/ static void _read_init_species(void) { - // reads the grid init species input - // the file should be something like: "cell,copy_cell,copy_which,(all the species names seperated by a comma)" - // there should be no spaces in between, just commas separating the values (ie it should be a .csv file, but does not account for all of the possibilities that a .csv file could be) - FILE *f; int i, j, num, cell, do_copy, copy_cell, useInitialization, seeds_Avail, row, col, copy_cell_row, copy_cell_col; @@ -2408,7 +2378,7 @@ static void _read_init_species(void) CloseFile(&f); } -/***********************************************************/ +/* Read the maxrgroupspecies file. */ static void _read_maxrgroupspecies(void) { ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); @@ -2417,7 +2387,7 @@ static void _read_maxrgroupspecies(void) ChDir(".."); } -/***********************************************************/ +/* Read the non-gridded mode files.in file. */ static void _read_files(void) { ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); @@ -2425,7 +2395,7 @@ static void _read_files(void) ChDir(".."); } -/***********************************************************/ +/* Reads the grid setup file and allocates gridCells.*/ static void _read_grid_setup(void) { FILE *f; From 9fcffa0abe94c88bc7acf27888694f3f4c4c75da Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 15 Jul 2019 14:20:53 -0600 Subject: [PATCH 119/167] Removed deprecated functions and removed unnecessary declarations (issue #311) * Removed deprecated _grid_disturb_st * Removed deprecated _grid_sxw_st * Removed deprecated pointers like grid_Species, grid_RGroup, ect. * Removed commented out declarations. * Reordered the function declarations. Some of the functions weren't under the correct label and runGrid() should have been in a category of it's own. * Removed functions that are declared but never used like stat_Output_AllBmassAvg * Removed functions dealing with linked list modification. These functions should have been in ST_species.c anyways. * Added call to parm_ree_memory at the end of runGrid. I saw that this function was unused but realized that it really should be used. * Commented out the definitions of _load_cell and _init_soil_layers. This way we can still look at them but they won't cause any compilation errors. * In _load_cell I removed a portion of code dealing with allocation of memory. This code will not help us and it was taking up a lot of space. --- ST_grid.c | 217 +++++------------------------------------------------- 1 file changed, 17 insertions(+), 200 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 6d8ed124..b2b5849f 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -73,22 +73,6 @@ struct Soil_st Grid_Soil_Lyr* lyr; }typedef SoilType; - -struct _grid_disturb_st -{ - int choices[3]; //used as boolean values (ie flags as to whether or not to use the specified disturbance) - int kill_yr, /* kill the group in this year; if 0, don't kill, but see killfreq */ - killfreq_startyr,/* start year for kill frequency*/ - killfrq, /* kill group at this frequency: <1=prob, >1=# years */ - extirp, /* year in which group is extirpated (0==ignore) */ - veg_prod_type, /* type of VegProd. 1 for tree, 2 for shrub, 3 for grass, 4 for forb */ - grazingfreq_startyr,/* start year for grazing frequency*/ - grazing_frq; /* grazing effect on group at this frequency: <1=prob, >1=# years */ - - RealF xgrow; /* ephemeral growth = mm extra ppt * xgrow */ - -}typedef Grid_Disturb_St; - struct _grid_sd_struct { //for seed dispersal //the idea is that this structure contains all of the cells that the cell represented can possibly disperse seeds to and the probability of the happening for each cell @@ -96,12 +80,6 @@ struct _grid_sd_struct float *prob, lyppt; }typedef Grid_SD_St; -struct _grid_sxw_st -{ //holds pointers dynamically allocated by SXW->c - RealD *roots_max, *rootsXphen, *roots_active, *roots_active_rel, - *roots_active_sum, *phen, *prod_bmass, *prod_pctlive; -}typedef Grid_SXW_St; - struct _grid_init_species_st { /* TRUE if at least one species has requested initialization */ @@ -212,21 +190,9 @@ char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; int grid_Cols, grid_Rows, grid_Cells; int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans -// these variables are for storing the globals in STEPPE... they are dynamically allocated/freed -SpeciesType **grid_Species, **spinup_Species; -GroupType **grid_RGroup, **spinup_RGroup; -SucculentType *grid_Succulent, *spinup_Succulent; -EnvType *grid_Env, *spinup_Env; -PlotType *grid_Plot, *spinup_Plot; -ModelType *grid_Globals, *spinup_Globals; - CellType** gridCells; CellType** spinupCells = NULL; -// these two variables are for storing SXW variables... also dynamically allocated/freed -SXW_t *grid_SXW, *spinup_SXW; -Grid_SXW_St *grid_SXW_ptrs, *spinup_SXW_ptrs; - // these are SOILWAT variables that we need... extern SW_SOILWAT SW_Soilwat; extern SW_SITE SW_Site; @@ -241,10 +207,6 @@ extern pcg32_random_t resgroups_rng; extern pcg32_random_t species_rng; extern pcg32_random_t markov_rng; -//This is Rgroup structure pointer that will read rgroup disturbance value, will be used in -// grid disturbance -//extern GroupType *RGroup [MAX_RGROUPS]; // don't need to extern here, because this is done in ST_Globals->h - // these are grids to store the SOILWAT variables... also dynamically allocated/freed SW_SOILWAT *grid_SW_Soilwat, *spinup_SW_Soilwat; SW_SITE *grid_SW_Site, *spinup_SW_Site; @@ -253,8 +215,6 @@ SW_MODEL *grid_SW_Model, *spinup_SW_Model; // these two variables are used to store the soil/distubance inputs for each grid cell... also dynamically allocated/freed SoilType *grid_Soils; -Grid_Disturb_St *grid_Disturb; -Grid_Init_Species_St *grid_initSpecies; Grid_SD_St **grid_SD; //for seed dispersal @@ -267,41 +227,33 @@ extern Bool* _SomeKillage; /******** Modular External Function Declarations ***********/ /* -- truly global functions are declared in functions.h --*/ /***********************************************************/ - -// Declare functions defined elsewhere: -void runGrid(void); //to be called from ST_main.c -void _kill_annuals(void); -void _kill_maxage(void); -void _kill_extra_growth(void); -void rgroup_Extirpate(GrpIndex rg); - -/************* External Function Declarations **************/ -/***********************************************************/ - //from ST_species.c void proportion_Recovery(void); void save_annual_species_relsize(void); void copy_species(const SpeciesType* src, SpeciesType* dest); - //from ST_resgroups.c void rgroup_Grow(void); void rgroup_Establish(void); void rgroup_IncrAges(void); void rgroup_PartResources(void); -//void rgroup_ResPartIndiv(void); void copy_rgroup(const GroupType* src, GroupType* dest); //from ST_mortality.c void mort_Main(Bool *killed); void mort_EndOfYear(void); void grazing_EndOfYear(void); +void _kill_annuals(void); +void _kill_maxage(void); +void _kill_extra_growth(void); //functions from ST_params.c void parm_Initialize(void); void parm_SetFirstName(char *s); void parm_SetName(char *s, int which); void parm_free_memory(void); +void files_init(void); +void maxrgroupspecies_init(void); //from ST_main.c void Plot_Initialize(void); @@ -313,42 +265,25 @@ void stat_Collect_GMort(void); void stat_Collect_SMort(void); void stat_Output_AllMorts(void); void stat_Output_AllBmass(void); -//Adding functions for creating grid cells avg values output file -void stat_Output_AllBmassAvg(void); void Output_AllCellAvgBmass(const char * filename); void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool makeHeader); -void stat_Load_Accumulators(int cell, int year); -void stat_Save_Accumulators(int cell, int year); -void stat_Free_Accumulators(void); -void stat_Init_Accumulators(void); void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); void _make_header_with_std( char *buf); -//functions from sxw.c -//void free_sxw_memory( void ); - -void save_sxw_memory(RealD * grid_roots_max, RealD* grid_rootsXphen, - RealD* grid_roots_active, RealD* grid_roots_active_rel, - RealD* grid_roots_active_sum, RealD* grid_phen, RealD* grid_prod_bmass, - RealD* grid_prod_pctlive); -void _deallocate_memory(void); -//void SXW_init( Bool init_SW ); - -void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); - -void maxrgroupspecies_init(void); -void files_init(void); - +/* Functions from sxw.c */ SXW_t* getSXW(void); SXW_resourceType* getSXWResources(void); transp_t* getTranspWindow(void); +void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); + +/********************** Exported Functions ***********************/ +void runGrid(void); //to be called from ST_main.c /*********** Locally Used Function Declarations ************/ /***********************************************************/ - static void logProgress(int iteration, int year, Status status); static double calculateProgress(int year, int iteration, Status status); static void printGeneralInfo(void); @@ -377,13 +312,6 @@ static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); static void _init_seed_dispersal(void); static void _do_seed_dispersal(void); static void _read_init_species(void); - -static IndivType* _create_empty_indv(void); //these 5 functions are used for copying/freeing the linked list of individuals correctly... -static void _free_individuals(IndivType *head); -static void _free_head(IndivType *head); -static IndivType* _copy_individuals(IndivType *head); -static IndivType* _copy_head(IndivType *head); - static void _read_maxrgroupspecies(void); static void _read_grid_setup(void); static void _read_files(void); @@ -687,7 +615,8 @@ void runGrid(void) Output_AllCellAvgBmass(fileBMassCellAvg); } - _free_grid_memory(); // free our allocated memory since we do not need it anymore + _free_grid_memory(); // Free our allocated memory since we do not need it anymore + parm_free_memory(); // Free memory allocated to the _files array in ST_params.c if(InitializationMethod == INIT_WITH_SPINUP) { _free_spinup_memory(); } @@ -1252,59 +1181,6 @@ static void allocate_accumulators(void){ unload_cell(); // Unload the cell to protect the last cell from unintended modification. } -/***********************************************************/ -static IndivType* _create_empty_indv(void) -{ - //simply allocates memory for an individual and returns the pointer to it - - return Mem_Calloc(1, sizeof(IndivType), "_create_empty_indv()"); - -} - -/***********************************************************/ -static void _free_individuals(IndivType *head) -{ - //frees the memory allocated in the linked list of individuals pointed to by head - if (head->Next != NULL) - _free_individuals(head->Next); //recursively call itself in order to free the next obj in the list (Mem_Free() will end up getting called on the objects in the list from last to first) - Mem_Free(head); -} - -/***********************************************************/ -static void _free_head(IndivType * head) -{ - if (head == NULL) - return; //if head == NULL then there is no memory to free, so just return - _free_individuals(head); -} - -/***********************************************************/ -static IndivType* _copy_individuals(IndivType *head) -{ - //performs a deep copy (not to be confused with a shallow copy) since that's what we want - IndivType *n = _create_empty_indv(); //allocate space for the individual to be copied to - - *n = *head; - - if (head->Next != NULL) - { - n->Next = _copy_individuals(head->Next); //recursively call itself in order to copy the next obj in the list - n->Next->Prev = n; - } - else - n->Next = NULL; - - return n; -} - -/***********************************************************/ -static IndivType* _copy_head(IndivType *head) -{ - if (head == NULL) - return NULL; //if head == NULL then there is nothing to copy... - return _copy_individuals(head); -} - /* Free all memory allocated to the gridded mode during initialization. */ static void _free_grid_memory(void) { @@ -1358,7 +1234,7 @@ static void _free_spinup_memory(void) } } -/***********************************************************/ +/* static void _load_cell(int row, int col, int year, Bool useAccumulators) { // loads the specified cell into the global variables @@ -1471,6 +1347,7 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) sizeof(SW_LAYER_INFO)); } } +*/ /* Load gridCells[row][col] into the globals variables. Any call to this function should have an accompanying call to unload_cell(). */ @@ -1767,7 +1644,7 @@ static void _read_soils_in(void) CloseFile(&f); } -/***********************************************************/ +/* static void _init_soil_layers(int cell, int isSpinup) { // initializes the soilwat soil layers for the cell correctly based upon the input gathered from our grid_soils input file @@ -1777,7 +1654,7 @@ static void _init_soil_layers(int cell, int isSpinup) i = cell; char* errtype; Bool evap_ok = TRUE, transp_ok_forb = TRUE, transp_ok_tree = TRUE, - transp_ok_shrub = TRUE, transp_ok_grass = TRUE; /* mitigate gaps in layers */ + transp_ok_shrub = TRUE, transp_ok_grass = TRUE; //mitigate gaps in layers Bool fail = FALSE; RealF fval = 0; @@ -1919,68 +1796,8 @@ static void _init_soil_layers(int cell, int isSpinup) init_site_info(); //in SW_Site.c, called to initialize layer data... _init_SXW_inputs(FALSE, grid_Soils[i].rootsFile); //we call this so that SXW can set the correct sizes/values up for the memory dynamically allocated in sxw.c - - if (!isSpinup) - { - - grid_SXW_ptrs[i].roots_max = Mem_Calloc(SXW->NGrps * SXW->NTrLyrs, - sizeof(RealD), "_init_soil_layers()"); - grid_SXW_ptrs[i].rootsXphen = Mem_Calloc( - SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - grid_SXW_ptrs[i].roots_active = Mem_Calloc( - SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - grid_SXW_ptrs[i].roots_active_rel = Mem_Calloc( - SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - grid_SXW_ptrs[i].roots_active_sum = Mem_Calloc( - 4 * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - grid_SXW_ptrs[i].phen = Mem_Calloc(SXW->NGrps * MAX_MONTHS, - sizeof(RealD), "_init_soil_layers()"); - grid_SXW_ptrs[i].prod_bmass = Mem_Calloc(SXW->NGrps * MAX_MONTHS, - sizeof(RealD), "_init_soil_layers()"); - grid_SXW_ptrs[i].prod_pctlive = Mem_Calloc(SXW->NGrps * MAX_MONTHS, - sizeof(RealD), "_init_soil_layers()"); - - save_sxw_memory(grid_SXW_ptrs[i].roots_max, grid_SXW_ptrs[i].rootsXphen, - grid_SXW_ptrs[i].roots_active, - grid_SXW_ptrs[i].roots_active_rel, - grid_SXW_ptrs[i].roots_active_sum, grid_SXW_ptrs[i].phen, - grid_SXW_ptrs[i].prod_bmass, grid_SXW_ptrs[i].prod_pctlive); - } - else - { - - spinup_SXW_ptrs[i].roots_max = Mem_Calloc(SXW->NGrps * SXW->NTrLyrs, - sizeof(RealD), "_init_soil_layers()"); - spinup_SXW_ptrs[i].rootsXphen = Mem_Calloc( - SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - spinup_SXW_ptrs[i].roots_active = Mem_Calloc( - SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - spinup_SXW_ptrs[i].roots_active_rel = Mem_Calloc( - SXW->NGrps * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - spinup_SXW_ptrs[i].roots_active_sum = Mem_Calloc( - 4 * SXW->NPds * SXW->NTrLyrs, sizeof(RealD), - "_init_soil_layers()"); - spinup_SXW_ptrs[i].phen = Mem_Calloc(SXW->NGrps * MAX_MONTHS, - sizeof(RealD), "_init_soil_layers()"); - spinup_SXW_ptrs[i].prod_bmass = Mem_Calloc(SXW->NGrps * MAX_MONTHS, - sizeof(RealD), "_init_soil_layers()"); - spinup_SXW_ptrs[i].prod_pctlive = Mem_Calloc(SXW->NGrps * MAX_MONTHS, - sizeof(RealD), "_init_soil_layers()"); - - save_sxw_memory(spinup_SXW_ptrs[i].roots_max, - spinup_SXW_ptrs[i].rootsXphen, spinup_SXW_ptrs[i].roots_active, - spinup_SXW_ptrs[i].roots_active_rel, - spinup_SXW_ptrs[i].roots_active_sum, spinup_SXW_ptrs[i].phen, - spinup_SXW_ptrs[i].prod_bmass, spinup_SXW_ptrs[i].prod_pctlive); - } } +*/ /***********************************************************/ static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) From 1219c12beab0e02857ee6a5bda82e7db38df5d0b Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 16 Jul 2019 10:34:23 -0600 Subject: [PATCH 120/167] Added a blocker to seed dispersal. (issue #326) I added a block of code that prevents seed dispersal from running. It also sets UseSeedDispersal to FALSE so the user doesn't have to throw away the current simulation. Obviously this will have to be removed once we have a definite plan for seed dispersal. --- ST_grid.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index b2b5849f..c35ded98 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1925,6 +1925,13 @@ static void _init_seed_dispersal(void) /***********************************************************/ static void _do_seed_dispersal(void) { + /************ TODO: overhaul seed dispersal. This block prevents seed dispersal from running. **************/ + printf("\nSeed dispersal during the simulation is not yet functional.\n" + "Check out GitHub for updates on this feature.\n"); + UseSeedDispersal = FALSE; + return; + /***********************************************************************************************************/ + float biomass, randomN, LYPPT, presentProb, receivedProb; int i, j, germ, sgerm, year, row, col; SppIndex s; From c23e28832a2ebb0eb7bd6deb5a062ae003e69954 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 16 Jul 2019 14:14:40 -0600 Subject: [PATCH 121/167] First attempt at fixing _init_seed_dispersal (issue #355) I will explain my changes on the issue because I want to discuss them. --- ST_grid.c | 168 +++++++++++++++++++++++------------------------------- 1 file changed, 70 insertions(+), 98 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index c35ded98..62952947 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -73,11 +73,17 @@ struct Soil_st Grid_Soil_Lyr* lyr; }typedef SoilType; +/* A struct for holding seed dispersal information. */ struct _grid_sd_struct { //for seed dispersal - //the idea is that this structure contains all of the cells that the cell represented can possibly disperse seeds to and the probability of the happening for each cell - int size, seeds_present, seeds_received, *cells; //seeds_present && seeds_received are treated as boolean values... cells & prob are to be the length of size - float *prob, lyppt; + /* TRUE if seeds are present. */ + Bool seeds_present; + /* TRUE if this cell has recieved any seeds. */ + Bool seeds_received; + /* probabilityOfDispersing[row][col] = the probability that this cell will disperse seeds to cell (row,col). */ + double **probabilityOfDispersing; + /* Last year's precipitation. */ + double lyppt; }typedef Grid_SD_St; struct _grid_init_species_st @@ -1185,7 +1191,7 @@ static void allocate_accumulators(void){ static void _free_grid_memory(void) { //frees all the memory allocated in this file ST_Grid.c (most of it is dynamically allocated in _init_grid_globals() & _load_grid_globals() functions) - int i, j; + int i, j, sd_i; SppIndex s; /* Free memory that we have allocated in ST_grid.c */ @@ -1199,7 +1205,10 @@ static void _free_grid_memory(void) // If seed dispersal is on we allocated additional memory if(UseSeedDispersal) { ForEachSpecies(s) { - Mem_Free(gridCells[i][j].mySeedDispersal[s].prob); + for(sd_i = 0; sd_i < grid_Rows; ++sd_i){ + Mem_Free(gridCells[i][j].mySeedDispersal[s].probabilityOfDispersing[sd_i]); + } + Mem_Free(gridCells[i][j].mySeedDispersal[s].probabilityOfDispersing); } } unload_cell(); @@ -1802,123 +1811,85 @@ static void _init_soil_layers(int cell, int isSpinup) /***********************************************************/ static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) { + double rowDist = row1 - row2; + double colDist = col1 - col2; + //returns the distance between the two grid cells if (row1 == row2) { - return (abs(col1-col2) * cellLen); + return (abs(colDist) * cellLen); } else if (col1 == col2) { - return (abs(row1-row2) * cellLen); + return (abs(rowDist) * cellLen); } else { // row1 != row2 && col1 != col2 //the problem can be thought of in terms of a right triangle... //using the pythagorean theorem: c = sqrt(a^2 + b^2)... c (the hypotenuse) represents the distance that we need. a is the distance between columns and b is the distance between rows. - return sqrt( - pow(abs(col1-col2)*cellLen, 2.0) + pow(abs(row1-row2)*cellLen, 2.0)); + return sqrt(pow(abs(colDist)*cellLen, 2.0) + pow(abs(rowDist)*cellLen, 2.0)); } } -/* Initialize all derived seed dispersal variables. (variables that are not specified directly in inputs). - This function is safe to call multiple times, but it only needs to be called once.*/ +/* Derives the probabilities that a given cell will disperse seeds to any other cell. + results of this function can be accessed using + gridCells[a][b].mySeedDispersal[s].probabilityOfDispersing[c][d] + where (a,b) are the coordinates of the sender, + (b, c) are the coordinates of the reciever, + and s is the species. */ static void _init_seed_dispersal(void) { - float sd_Rate, H, VW, VT, MAXD, plotLength, pd, d; - int maxCells, i, j, k, MAXDP, row, col, cell; - SppIndex s; - - for (i = 0; i < grid_Cells; i++) { - row = i / grid_Cols; - col = i % grid_Cols; - - gridCells[row][col].mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_init_seed_dispersal"); - } + int senderRow, senderCol, recieverRow, recieverCol; + SppIndex sp; + double MAXD; /* maximum distance that a given species can disperse seeds */ + double maxRate; /* Dispersability of the seeds */ + double plotWidth; /* width of the plots (all plots are equal and square) */ + double distanceBetweenPlots; /* distance between the sender and the reciever */ - /* - * The following variables should be global (not cell-specific): - * Globals->sppCount - * Species[s]->sd_H - * Species[s]->sd_VT - * Globals->plotsize - * Species[s]->use_me - * Species[s]->use_dispersal - * - * Since the values of these variables do not change between cells, we can call load_cell(0, 0) - * to load their values so that ForEachSpecies and other lines of code do not segfault. - */ - load_cell(0, 0); + /* sender denotes that these loops refer to the cell distributing seeds */ + for(senderRow = 0; senderCol < grid_Rows; ++senderRow){ + for(senderCol = 0; senderCol < grid_Cols; ++senderCol){ + /* Cell is loaded to ensure the ForEachSpecies loop works */ + load_cell(senderRow, senderCol); - // Begin reading cell-specific fields - ForEachSpecies(s) - { - // set up grid_SD with the seed dispersal probabilities needed later on... - H = Species[s]->sd_H; - VT = Species[s]->sd_VT; - VW = Species[s]->sd_VW; - MAXD = ((H * VW) / VT) / 100.0; // divide by 100.0 because we want it in meters, not centimeters - sd_Rate = -(log(0.05) / MAXD); //sd_Rate is the seed dispersal rate... 0.05 = exp(-RATE*MAXD) => RATE = -(ln(0.05)/MAXD) See Coffin et al. 1993 - - plotLength = sqrt(Globals->plotsize); - MAXDP = (int) ceil(MAXD / plotLength); //MAXD in terms of plots... rounds up to the nearest integer - maxCells = (int) pow((MAXDP * 2) + 1.0, 2.0); //gets the maximum number of cells that a grid cell can possibly disperse seeds to... it ends up being more then the maximum actually... - if (grid_Cells < maxCells) - maxCells = grid_Cells; - if (!(Species[s]->use_me && Species[s]->use_dispersal)) - continue; + /* Allocate seed dispersal information. */ + gridCells[senderRow][senderCol].mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_init_seed_dispersal"); - for (i = 0; i < grid_Cells; i++) - { - row = i / grid_Cols; - col = i % grid_Cols; + ForEachSpecies(sp){ + if (!(Species[sp]->use_me && Species[sp]->use_dispersal)){ + continue; + } - gridCells[row][col].mySeedDispersal[s].cells = Mem_Calloc(maxCells, sizeof(int), - "_init_seed_dispersal()"); //the cell number - gridCells[row][col].mySeedDispersal[s].prob = Mem_Calloc(maxCells, sizeof(float), - "_init_seed_dispersal()"); //the probability that the cell will disperse seeds to this distance - gridCells[row][col].mySeedDispersal[s].size = 0; //refers to the number of cells reachable... - } + /* These are the three values we need to calculate the probability of dispersal */ + MAXD = ((Species[sp]->sd_H * Species[sp]->sd_VW) / Species[sp]->sd_VT) / 100.0; // divided by 100 to convert from cm to m. + maxRate = -(log(0.005) / MAXD); + plotWidth = sqrt(Globals->plotsize); + + /* Allocate the probabilityOfDispersing 2d array */ + gridCells[senderRow][senderCol].mySeedDispersal[sp].probabilityOfDispersing = Mem_Calloc(grid_Rows, + sizeof(double*), "_init_seed_dispersal: probabilityOfDispersing"); + for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ + gridCells[senderRow][senderCol].mySeedDispersal[sp].probabilityOfDispersing[recieverRow] = + Mem_Calloc(grid_Cols, sizeof(double), "_init_seed_dispersal: probabilityOfDispersing[i]"); + } - for (row = 1; row <= grid_Rows; row++){ - for (col = 1; col <= grid_Cols; col++){ - cell = col + ((row - 1) * grid_Cols) - 1; - k = 0; - - for (i = 1; i <= grid_Rows; i++) { - for (j = 1; j <= grid_Cols; j++){ - if (i == row && j == col) - continue; - - d = _cell_dist(i, row, j, col, plotLength); //distance - pd = (d > MAXD) ? (0.0) : (exp(-sd_Rate * d)); //dispersal probability - - if (!ZRO(pd)) - { - gridCells[row - 1][col - 1].mySeedDispersal[s].cells[k] = i - + ((j - 1) * grid_Cols) - 1; - gridCells[row - 1][col - 1].mySeedDispersal[s].prob[k] = pd; - gridCells[row - 1][col - 1].mySeedDispersal[s].size++; - k++; + /* Loop through all possible recipients of seeds. */ + for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ + for(recieverCol = 0; recieverCol < grid_Cols; ++recieverCol){ + if(senderRow == recieverRow && senderCol == recieverCol){ + continue; // No need to calculate a probability for dispersal to itself } + + distanceBetweenPlots = _cell_dist(senderRow, recieverRow, senderCol, recieverCol, plotWidth); + + /* The value that we are after should be saved to the sender cell. */ + gridCells[senderRow][senderCol].mySeedDispersal[sp].probabilityOfDispersing[recieverRow][recieverCol] + = (distanceBetweenPlots > MAXD) ? (0.0) : (exp(-maxRate * distanceBetweenPlots)); } } } } - - for (i = 0; i < grid_Cells; i++) { - row = i / grid_Cols; - col = i % grid_Cols; - - if (gridCells[row][col].mySeedDispersal[s].size > 0) - { - gridCells[row][col].mySeedDispersal[s].cells = Mem_ReAlloc(gridCells[row][col].mySeedDispersal[s].cells, - gridCells[row][col].mySeedDispersal[s].size * sizeof(int)); - gridCells[row][col].mySeedDispersal[s].prob = Mem_ReAlloc(gridCells[row][col].mySeedDispersal[s].prob, - gridCells[row][col].mySeedDispersal[s].size * sizeof(float)); - } - } } - unload_cell(); } @@ -1931,7 +1902,7 @@ static void _do_seed_dispersal(void) UseSeedDispersal = FALSE; return; /***********************************************************************************************************/ - +/* float biomass, randomN, LYPPT, presentProb, receivedProb; int i, j, germ, sgerm, year, row, col; SppIndex s; @@ -2008,7 +1979,7 @@ static void _do_seed_dispersal(void) { if ((sgerm || year < RGroup[0]->killyr || RGroup[0]->killyr <= 0 || GT(biomass, 0.0)) - /*&& (year != RGroup[0].killyr)*/) + && (year != RGroup[0].killyr)) { //commented above one condition as it was causing a bug there, next year of killing year will make //allow_growth flag to false as year = Globals->currYear - 1 , so for example if killing year= 6 and Globals->currYear=7 then here @@ -2103,7 +2074,7 @@ static void _do_seed_dispersal(void) for (j = 0; j < cell->mySeedDispersal[s].size; j++) if (cell->mySeedDispersal[cell->mySeedDispersal[s].cells[j]].seeds_present) - receivedProb += cell->mySeedDispersal[s].prob[j]; + receivedProb += cell->mySeedDispersal[s].probabilityOfDispersing[j]; randomN = RandUni(&grid_rng); if (LE(randomN, receivedProb) && !ZRO(receivedProb)) @@ -2116,6 +2087,7 @@ static void _do_seed_dispersal(void) } unload_cell(); +*/ } /* Read the species initialization CSV. This function only needs to be called if the user requests initialization.*/ From dd9c53efcca94c7fc711e47e32dbb60d6d05c4b4 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 16 Jul 2019 14:38:33 -0600 Subject: [PATCH 122/167] Introduced a "sender" variable to improve code readability (issue #355) --- ST_grid.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 62952947..4f074adb 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1845,15 +1845,17 @@ static void _init_seed_dispersal(void) double maxRate; /* Dispersability of the seeds */ double plotWidth; /* width of the plots (all plots are equal and square) */ double distanceBetweenPlots; /* distance between the sender and the reciever */ + CellType* sender; /* sender denotes that these loops refer to the cell distributing seeds */ for(senderRow = 0; senderCol < grid_Rows; ++senderRow){ for(senderCol = 0; senderCol < grid_Cols; ++senderCol){ /* Cell is loaded to ensure the ForEachSpecies loop works */ load_cell(senderRow, senderCol); + sender = &gridCells[senderRow][senderCol]; /* Allocate seed dispersal information. */ - gridCells[senderRow][senderCol].mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_init_seed_dispersal"); + sender->mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_init_seed_dispersal"); ForEachSpecies(sp){ if (!(Species[sp]->use_me && Species[sp]->use_dispersal)){ @@ -1866,10 +1868,10 @@ static void _init_seed_dispersal(void) plotWidth = sqrt(Globals->plotsize); /* Allocate the probabilityOfDispersing 2d array */ - gridCells[senderRow][senderCol].mySeedDispersal[sp].probabilityOfDispersing = Mem_Calloc(grid_Rows, + sender->mySeedDispersal[sp].probabilityOfDispersing = Mem_Calloc(grid_Rows, sizeof(double*), "_init_seed_dispersal: probabilityOfDispersing"); for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ - gridCells[senderRow][senderCol].mySeedDispersal[sp].probabilityOfDispersing[recieverRow] = + sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow] = Mem_Calloc(grid_Cols, sizeof(double), "_init_seed_dispersal: probabilityOfDispersing[i]"); } @@ -1883,7 +1885,7 @@ static void _init_seed_dispersal(void) distanceBetweenPlots = _cell_dist(senderRow, recieverRow, senderCol, recieverCol, plotWidth); /* The value that we are after should be saved to the sender cell. */ - gridCells[senderRow][senderCol].mySeedDispersal[sp].probabilityOfDispersing[recieverRow][recieverCol] + sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow][recieverCol] = (distanceBetweenPlots > MAXD) ? (0.0) : (exp(-maxRate * distanceBetweenPlots)); } } From cd53202e30efcdbada533c4be507a5aed582bf6c Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 17 Jul 2019 10:17:31 -0600 Subject: [PATCH 123/167] (issue #312) Improved function and variable descriptions --- ST_grid.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 4f074adb..59404a5b 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -196,7 +196,9 @@ char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; int grid_Cols, grid_Rows, grid_Cells; int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans +/* gridCells[i][j] denotes the cell at position (i,j) */ CellType** gridCells; +/* Stores the state of the cells following spinup. */ CellType** spinupCells = NULL; // these are SOILWAT variables that we need... @@ -286,10 +288,12 @@ transp_t* getTranspWindow(void); void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); /********************** Exported Functions ***********************/ + void runGrid(void); //to be called from ST_main.c /*********** Locally Used Function Declarations ************/ /***********************************************************/ + static void logProgress(int iteration, int year, Status status); static double calculateProgress(int year, int iteration, Status status); static void printGeneralInfo(void); @@ -434,7 +438,7 @@ static void printGeneralInfo(void){ /* --------------------------- END printing general info -------------------------------- */ } -/* Runs the gridded version of the code */ +/* Run gridded mode. */ void runGrid(void) { int i, j; @@ -629,7 +633,7 @@ void runGrid(void) logProgress(0, 0, DONE); } -/* "Spinup" the model by running for SuperGlobals.runModelYears without seed dispersal or statistics outputs. */ +/* "Spinup" the model by running for SuperGlobals.runInitializationYears without seed dispersal or statistics outputs. */ static void _run_spinup(void) { /* Dummy accumulators to ensure we do not collect statistics */ @@ -739,7 +743,8 @@ static void _run_seed_initialization(void){ /* Initializes the plot with whichever method you have specified with InitializationMethod. This function takes care of EVERYTHING involved with initialization. - After calling this function you can load in the initialization information by calling loadInitializationConditions(). */ + After calling this function you can load in the initialization information by calling + loadInitializationConditions(). */ static void runInitialization(void){ beginInitialization(); @@ -1396,8 +1401,8 @@ static void load_cell(int row, int col){ copy_sxw_variables(gridCells[row][col].mySXW, gridCells[row][col].mySXWResources, gridCells[row][col].myTranspWindow); } -/* Nullify all global variables. This function should appear after every call to load_cell to prevent - accidental modification of a grid cell. +/* Nullify all global variables. This function should appear after every call + to load_cell to prevent accidental modification of a grid cell. Example usage: for i in rows{ for j in columns{ @@ -1513,14 +1518,9 @@ static int _get_value_index2(char* s, int nSeperators) return i; } -/***********************************************************/ +/* Read the grid soils input */ static void _read_soils_in(void) { - // reads the grid soils input - // the file should be something like: "cell,copy_cell,copy_which,num_layers,..." - // there should be no spaces in between, just commas separating the values - // this function reads in pretty much a .csv file, but it will not account for all of the possibilities that a .csv file could be written as (as accounting for all these possibilities would take a while to code and be unproductive) so keep that in mind - FILE *f; char buf[4096]; char rootsin[20]; @@ -1808,7 +1808,9 @@ static void _init_soil_layers(int cell, int isSpinup) } */ -/***********************************************************/ +/* Returns the distance in meters between two cells. + To calculate the distance between cells (a,b) and (c,d) with plot width w, + input _cell_dist(a, c, b, d, w) */ static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) { double rowDist = row1 - row2; @@ -1895,7 +1897,7 @@ static void _init_seed_dispersal(void) unload_cell(); } -/***********************************************************/ +/* Perform seed dispersal durring the simulation. This is NOT functional yet. */ static void _do_seed_dispersal(void) { /************ TODO: overhaul seed dispersal. This block prevents seed dispersal from running. **************/ @@ -2284,6 +2286,7 @@ static void _read_grid_setup(void) CloseFile(&f); } +/* Output a master .csv file containing the averages across all cells. */ void Output_AllCellAvgBmass(const char * filename){ int i, j, year, nobs = 0; //for iterating GrpIndex rg; //for iterating From b3cd79c7f943fcdcd3ae7e10398dd7513d4e93da Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 17 Jul 2019 11:04:06 -0600 Subject: [PATCH 124/167] Moved functionallity from _run_spinup to runInitialization issue #342 Most of the code in _run_spinup will be needed no matter which initialization method we choose. I therefore moved this code to runInitialization. The things I moved include: * The years loop. All initialization methods use SuperGlobals.runInitializationYears, so I moved the entire loop to the overarching initialization function. * Seeding the RNGs. * loading the cells and loading the dummy accumulators * unloading cells after initialization * the call to parm_Initialize * Plot initialization * The years loop * The cells loop * The logic to determine if the given cell needs initialization. * SXW cleanup after initialization. I also removed the iterations loop entirely from _run_spinup. Initialization will always last one iteration. These changes required me to modify the Status enumerator. I combined both initialization methods. I also modified the warning printed in _run_seed_initialization to ensure that it only prints once. --- ST_grid.c | 230 +++++++++++++++++++++++++----------------------------- 1 file changed, 108 insertions(+), 122 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 59404a5b..24d30f31 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -184,8 +184,7 @@ enum typedef enum { - SPINUP, - DISPERSAL, + INITIALIZATION, SIMULATION, OUTPUT, DONE @@ -341,18 +340,14 @@ static void logProgress(int iteration, int year, Status status){ iteration--; // iteration loops are 1 indexed, but we need 0 indexing. switch(status){ - case SPINUP: - strcpy(progressString, "Spinup |"); - index += 12; // We have copied over 12 characters - needsProgressBar = TRUE; - break; - case DISPERSAL: - strcpy(progressString, "Dispersing seeds"); - index += 16; // We have copied over 16 characters + case INITIALIZATION: + strcpy(progressString, "Initializing |"); + index += 14; // We have copied over 16 characters + needsProgressBar = TRUE; break; case SIMULATION: - strcpy(progressString, "Simulating |"); - index += 12; // We have copied over 12 characters + strcpy(progressString, "Simulating |"); + index += 14; // We have copied over 12 characters needsProgressBar = TRUE; break; case OUTPUT: @@ -404,7 +399,7 @@ static void logProgress(int iteration, int year, Status status){ Param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. */ double calculateProgress(int year, int iteration, Status status){ double percentComplete; - if(status == SPINUP){ + if(status == INITIALIZATION){ percentComplete = (year / (double) SuperGlobals.runInitializationYears); } else if(status == SIMULATION) { percentComplete = ((iteration * SuperGlobals.runModelYears) + year) @@ -633,111 +628,32 @@ void runGrid(void) logProgress(0, 0, DONE); } -/* "Spinup" the model by running for SuperGlobals.runInitializationYears without seed dispersal or statistics outputs. */ +/* "Spinup" the model by running without stat collection. */ static void _run_spinup(void) { - /* Dummy accumulators to ensure we do not collect statistics */ - StatType *dummy_Dist, *dummy_Ppt, *dummy_Temp, - *dummy_Grp, *dummy_Gsize, *dummy_Gpr, *dummy_Gmort, *dummy_Gestab, - *dummy_Spp, *dummy_Indv, *dummy_Smort, *dummy_Sestab, *dummy_Sreceived; - FireStatsType *dummy_Gwf; - - /* ints used for iterating over gridCells */ - int i, j; - - /* ints used for iterating over years and iterations */ - IntS year, iter; - - /* killedany for mortality functions */ - Bool killedany; - - for (iter = 1; iter <= 1; iter++) - { //for each iteration... only 1 iteration allowed for now - - /* Since this is technically an iteration so we need to seed the RNGs. */ - RandSeed(SuperGlobals.randseed, &environs_rng); - RandSeed(SuperGlobals.randseed, &mortality_rng); - RandSeed(SuperGlobals.randseed, &resgroups_rng); - RandSeed(SuperGlobals.randseed, &species_rng); - RandSeed(SuperGlobals.randseed, &grid_rng); - RandSeed(SuperGlobals.randseed, &markov_rng); - - if (BmassFlags.yearly || MortFlags.yearly) - parm_Initialize(); - - // Initialize the plot for each grid cell - for (i = 0; i < grid_Rows; i++){ - for (j = 0; j < grid_Cols; j++){ - load_cell(i, j); - Plot_Initialize(); - Globals->currIter = iter; - } - } - unload_cell(); // Reset the global variables - - for (year = 1; year <= SuperGlobals.runInitializationYears; year++) - { //for each year - if(UseProgressBar){ - logProgress(iter, year, SPINUP); - } - for (i = 0; i < grid_Rows; ++i) - { // for each row - for(j = 0; j < grid_Cols; ++j) - { // for each column - // If we should run spinup on this cell - if(gridCells[i][j].mySpeciesInit.useInitialization){ - // Load up a cell - load_cell(i, j); - } else { - continue; // No spinup requested. Move on to next cell. - } - - /* This step is important. load_cell loaded in the actual accumulators, but we do not want - to accumulate stats while in spinup. We need to load in dummy accumulators to ensure - we ignore everything that happens in spinup. */ - stat_Copy_Accumulators(dummy_Dist, dummy_Ppt, dummy_Temp, dummy_Grp, dummy_Gsize, dummy_Gpr, dummy_Gmort, dummy_Gestab, - dummy_Spp, dummy_Indv, dummy_Smort, dummy_Sestab, dummy_Sreceived, dummy_Gwf, TRUE); - - Globals->currYear = year; - - rgroup_Establish(); // Establish individuals. Excludes annuals. - - Env_Generate(); // Generated the SOILWAT environment - - rgroup_PartResources(); // Distribute resources - rgroup_Grow(); // Grow - - mort_Main(&killedany); // Mortality that occurs during the growing season - - rgroup_IncrAges(); // Increment ages of all plants - - grazing_EndOfYear(); // Livestock grazing - - mort_EndOfYear(); // End of year mortality. - - _kill_annuals(); // Kill annuals - _kill_maxage(); // Kill plants that reach max age - proportion_Recovery(); // Recover from any disturbances - _kill_extra_growth(); // Kill superfluous growth - } /* end column */ - } /* end row */ - - unload_cell(); // Reset the global variables - } /* end model run for this year*/ - - ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); - SXW_Reset(gridCells[0][0].mySXW->f_watin); - //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. - Mem_Free(SW_Soilwat.hist.file_prefix); - SW_Soilwat.hist.file_prefix = NULL; - ChDir(".."); - } /* End iterations */ + Bool killedany; // killedany for mortality functions + + rgroup_Establish(); // Establish individuals. Excludes annuals. + Env_Generate(); // Generated the SOILWAT environment + rgroup_PartResources(); // Distribute resources + rgroup_Grow(); // Grow + mort_Main(&killedany); // Mortality that occurs during the growing season + rgroup_IncrAges(); // Increment ages of all plants + grazing_EndOfYear(); // Livestock grazing + mort_EndOfYear(); // End of year mortality. + _kill_annuals(); // Kill annuals + _kill_maxage(); // Kill plants that reach max age + proportion_Recovery(); // Recover from any disturbances + _kill_extra_growth(); // Kill superfluous growth } /* TODO: This is a dummy method. It needs to be implemented once seed dispersal is fully planned. */ static void _run_seed_initialization(void){ - printf("You have attempted to initialize with seed dispersal.\n" - "This option is currently in development and will be availible soon.\n"); + if(Globals->currYear == 1){ + printf("\nYou have attempted to initialize with seed dispersal.\n" + "This option is currently in development and will be availible soon.\n"); + } + InitializationMethod = INIT_WITH_NOTHING; return; } @@ -748,16 +664,86 @@ static void _run_seed_initialization(void){ static void runInitialization(void){ beginInitialization(); - switch (InitializationMethod){ - case INIT_WITH_SPINUP: - _run_spinup(); - break; - case INIT_WITH_SEEDS: - _run_seed_initialization(); - break; - default: - break; - } + /* Dummy accumulators to ensure we do not collect statistics */ + StatType *dummy_Dist, *dummy_Ppt, *dummy_Temp, + *dummy_Grp, *dummy_Gsize, *dummy_Gpr, *dummy_Gmort, *dummy_Gestab, + *dummy_Spp, *dummy_Indv, *dummy_Smort, *dummy_Sestab, *dummy_Sreceived; + FireStatsType *dummy_Gwf; + + /* For iterating over gridCells */ + int i, j; + + /* For iterating over years */ + IntS year; + + /* Initialization is technically an iteration so we need to seed the RNGs. */ + RandSeed(SuperGlobals.randseed, &environs_rng); + RandSeed(SuperGlobals.randseed, &mortality_rng); + RandSeed(SuperGlobals.randseed, &resgroups_rng); + RandSeed(SuperGlobals.randseed, &species_rng); + RandSeed(SuperGlobals.randseed, &grid_rng); + RandSeed(SuperGlobals.randseed, &markov_rng); + + if (BmassFlags.yearly || MortFlags.yearly) + parm_Initialize(); + + // Initialize the plot for each grid cell + for (i = 0; i < grid_Rows; i++){ + for (j = 0; j < grid_Cols; j++){ + load_cell(i, j); + Plot_Initialize(); + Globals->currIter = 1; // Iteration doesn't really matter, I set it to 1 here just in case. + } + } + unload_cell(); // Reset the global variables + + for (year = 1; year <= SuperGlobals.runInitializationYears; year++) + { //for each year + if(UseProgressBar){ + logProgress(0, year, INITIALIZATION); // iter = 0 because we are not actually in an iterations loop. + } + for (i = 0; i < grid_Rows; ++i) + { // for each row + for(j = 0; j < grid_Cols; ++j) + { // for each column + // If we should run spinup on this cell + if(gridCells[i][j].mySpeciesInit.useInitialization){ + // Load up a cell + load_cell(i, j); + } else { + continue; // No spinup requested. Move on to next cell. + } + + /* This step is important. load_cell loaded in the actual accumulators, but we do not want + to accumulate stats while in spinup. We need to load in dummy accumulators to ensure + we ignore everything that happens in spinup. */ + stat_Copy_Accumulators(dummy_Dist, dummy_Ppt, dummy_Temp, dummy_Grp, dummy_Gsize, dummy_Gpr, dummy_Gmort, dummy_Gestab, + dummy_Spp, dummy_Indv, dummy_Smort, dummy_Sestab, dummy_Sreceived, dummy_Gwf, TRUE); + + Globals->currYear = year; + + switch (InitializationMethod){ + case INIT_WITH_SPINUP: + _run_spinup(); + break; + case INIT_WITH_SEEDS: + _run_seed_initialization(); + break; + default: + break; + } + + } /* end column */ + } /* end row */ + unload_cell(); // Reset the global variables + } /* end model run for this year*/ + + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); + SXW_Reset(gridCells[0][0].mySXW->f_watin); + //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. + Mem_Free(SW_Soilwat.hist.file_prefix); + SW_Soilwat.hist.file_prefix = NULL; + ChDir(".."); endInitialization(); } From e09fa9f9db6b22793860c30e99abc17a8c0e4fa6 Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 18 Jul 2019 10:43:26 -0600 Subject: [PATCH 125/167] Separated initialization from ST_grid and added header files (Large commit) (issue #342) In this commit I added three files: ST_grid.h, ST_initialization.c, and ST_initialization.h. See below for a description of each: ST_initialization.c: * Contains all of the functions from ST_grid.c that were related to initialization. I did this to separate the two features. * ST_grid.c now contains ONLY the functions that deal with gridded mode and the progress bar. ST_initialization.h: * Contains declarations for the functions we want to be called from other files. * Contains the Status enumerator (previously in ST_grid.c) so all files that include ST_initialization.h can use it. * Contains the declarations for initializationCells, initializationMethod, and DuringInitialization. * initializationMethod and DuringInitialization were removed from ST_globals.h. This way it is clear that the variables belong to the initialization module. ST_grid.h: * Moved the declarations for a few functions here. These functions could all be reasonably called from other files. This allowed me to remove the declaration of runGrid() from ST_main.c and the declarations of load_cell and unload_cell from ST_initialization.c. * Removed all functions related to initialization. * Moved the definitions of all structs and enumerators from ST_grid.c to this file. I modified 6 other files: makefile: * Added rule for ST_initialization.o. * Removed all header files from the rule for ST_grid.o. Header files are NOT needed in makefile rules. ST_globals.h: * Removed UseSeedDispersal, InitializationMethod and DuringInitialization. * These variables are now defined in the grid and initialization headers. ST_grid.c: * Moved module-level function declarations to the header file. * Moved all structs and enumerators to the header files. * Removed time.h from include statements. It is not needed. * Moved some of the include statements to ST_grid.h. The include statements that I moved are all required to use the module. ST_main.c: * Added and include statement for ST_initialization.h. ST_initialization.h contains ST_grid.h so we get both of them. * Removed redeclaration of runGrid(). * Removed declaration of UseSeedDispersal, InitializationMethod, and DuringInitialization. All of these are now declared in the header files. ST_species.c * Added an include statement for ST_initialization.h. ST_species.c needs some information about seed dispersal and initialization. ST_stats.c * Added an include statement for ST_initialization.h, just like ST_species.c --- ST_globals.h | 3 - ST_grid.c | 492 +++++--------------------------------------- ST_grid.h | 179 ++++++++++++++++ ST_initialization.c | 307 +++++++++++++++++++++++++++ ST_initialization.h | 41 ++++ ST_main.c | 6 +- ST_species.c | 1 + ST_stats.c | 1 + makefile | 12 +- 9 files changed, 593 insertions(+), 449 deletions(-) create mode 100644 ST_grid.h create mode 100644 ST_initialization.c create mode 100644 ST_initialization.h diff --git a/ST_globals.h b/ST_globals.h index abe482d7..9acea629 100644 --- a/ST_globals.h +++ b/ST_globals.h @@ -29,7 +29,4 @@ extern BmassFlagsType BmassFlags; extern MortFlagsType MortFlags; extern GlobalType SuperGlobals; -extern Bool UseSeedDispersal; -extern int InitializationMethod; extern Bool UseGrid; -extern Bool DuringInitialization; diff --git a/ST_grid.c b/ST_grid.c index 24d30f31..2624cd49 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -24,14 +24,13 @@ /* =================================================== */ /* INCLUDES / DEFINES */ /* --------------------------------------------------- */ - #include #include #include #include #include #include -#include +#include "ST_grid.h" #include "ST_steppe.h" #include "generic.h" #include "filefuncs.h" @@ -39,181 +38,14 @@ #include "ST_globals.h" #include "ST_stats.h" #include "rands.h" - #include "sxw_funcs.h" -#include "sxw.h" -#include "sxw_vars.h" - -#include "SW_Site.h" -#include "SW_SoilWater.h" -#include "SW_VegProd.h" -#include "SW_Model.h" -#include "SW_Weather.h" -#include "sw_src/pcg/pcg_basic.h" - -/***************** Structure Declarations ******************/ -/***********************************************************/ -// represents a single soil layer -struct _grid_soil_lyr_st -{ - // Data for this soil layer - float data[11]; - // Vertical width of this layer - int width; -}typedef Grid_Soil_Lyr; - -//represents the input data for all the soil layers of a cell -struct Soil_st -{ - // Number of soil layers (size of lyr array) - int num_layers; - // Name of the roots file belonging to this cell - char rootsFile[20]; - // Specific layer's information - Grid_Soil_Lyr* lyr; -}typedef SoilType; - -/* A struct for holding seed dispersal information. */ -struct _grid_sd_struct -{ //for seed dispersal - /* TRUE if seeds are present. */ - Bool seeds_present; - /* TRUE if this cell has recieved any seeds. */ - Bool seeds_received; - /* probabilityOfDispersing[row][col] = the probability that this cell will disperse seeds to cell (row,col). */ - double **probabilityOfDispersing; - /* Last year's precipitation. */ - double lyppt; -}typedef Grid_SD_St; - -struct _grid_init_species_st -{ - /* TRUE if at least one species has requested initialization */ - int useInitialization; - /* Array of Boolean values. TRUE if given species - should be included in spinup */ - int *shouldBeInitialized; -}typedef Grid_Init_Species_St; - -/* Struct to hold all plot-specific parameters */ -struct grid_cell_st -{ - /* RGroup coresponding to this cell */ - GroupType **myGroup; - /* Species corresponding to this cell */ - SpeciesType **mySpecies; - /* Succulents corresponding to this cell */ - SucculentType mySucculent; - /* This cell's environment. We expect each cell to - * have slightly different weather each year */ - EnvType myEnvironment; - /* Cell's plot data */ - PlotType myPlot; - /* Global variables corresponding to this cell */ - ModelType myGlobals; - /* If TRUE this cell should use seed dispersal */ - Bool useSeedDispersal; - /* TRUE if this cell is in spinup mode */ - Bool DuringInitialization; - /* species spinup information */ - Grid_Init_Species_St mySpeciesInit; - /* seed dispersal information corresponding to this cell */ - Grid_SD_St *mySeedDispersal; - - Bool* someKillage; - - /* ---------------- accumulators -------------------- */ - StatType *_Dist, *_Ppt, *_Temp, - *_Grp, *_Gsize, *_Gpr, *_Gmort, *_Gestab, - *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; - FireStatsType *_Gwf; - Bool stats_init; - /* -------------- end accumulators ------------------ */ - - /* -------------------- SXW ------------------------- */ - transp_t* myTranspWindow; - SXW_t* mySXW; - SXW_resourceType* mySXWResources; - /* ------------------ End SXW ----------------------- */ - - /* ------------------- Soils ------------------------ */ - // Soil layer information for this cell. - SoilType mySoils; - /* ------------------ End Soils --------------------- */ -} typedef CellType; - -/************ Module Variable Declarations ***************/ -/***********************************************************/ +#include "ST_initialization.h" -/* Indices for grid_directories go here */ -enum -{ - GRID_DIRECTORY_STEPWAT_INPUTS, - - /* Automatically generate number of directories since enums start at 0 */ - N_GRID_DIRECTORIES -}; - -/* Indices for grid_files go here */ -enum -{ - GRID_FILE_LOGFILE, - GRID_FILE_SETUP, - GRID_FILE_DISTURBANCES, - GRID_FILE_SOILS, - GRID_FILE_INIT_SPECIES, - GRID_FILE_FILES, - GRID_FILE_MAXRGROUPSPECIES, - - GRID_FILE_PREFIX_BMASSAVG, - GRID_FILE_PREFIX_MORTAVG, - GRID_FILE_PREFIX_RECEIVEDPROB, - GRID_FILE_PREFIX_BMASSCELLAVG, - - /* Automatically generate number of files since enums start at 0 */ - N_GRID_FILES -}; - -/* Enumerator for initialization types */ -enum -{ - INIT_WITH_SPINUP, - INIT_WITH_SEEDS, - INIT_WITH_NOTHING -}; - -typedef enum -{ - INITIALIZATION, - SIMULATION, - OUTPUT, - DONE -} Status; - -char *grid_files[N_GRID_FILES], *grid_directories[N_GRID_DIRECTORIES], sd_Sep; +char sd_Sep; -int grid_Cols, grid_Rows, grid_Cells; +int grid_Cells; int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans -/* gridCells[i][j] denotes the cell at position (i,j) */ -CellType** gridCells; -/* Stores the state of the cells following spinup. */ -CellType** spinupCells = NULL; - -// these are SOILWAT variables that we need... -extern SW_SOILWAT SW_Soilwat; -extern SW_SITE SW_Site; -extern SW_VEGPROD SW_VegProd; -extern SW_WEATHER SW_Weather; -extern pcg32_random_t grid_rng; //this file's unique random number generator - -/* We need to seed these RNGs when using the gridded mode but do not use them in this file. */ -extern pcg32_random_t environs_rng; -extern pcg32_random_t mortality_rng; -extern pcg32_random_t resgroups_rng; -extern pcg32_random_t species_rng; -extern pcg32_random_t markov_rng; - // these are grids to store the SOILWAT variables... also dynamically allocated/freed SW_SOILWAT *grid_SW_Soilwat, *spinup_SW_Soilwat; SW_SITE *grid_SW_Site, *spinup_SW_Site; @@ -228,8 +60,28 @@ Grid_SD_St **grid_SD; //for seed dispersal // these variables are used for the soil types in the spinup options int nSoilTypes, *soilTypes_Array, *grid_SoilTypes; -extern Bool UseProgressBar; -extern Bool* _SomeKillage; +/***************************** Externed variables **********************************/ +/* Note that in an ideal world we wouldn't need to extern any variables because + every module would declate them in a header file. Hopefully we can get this + cleaned up soon! -CH */ + +// these are SOILWAT variables that we need... +extern SW_SOILWAT SW_Soilwat; +extern SW_SITE SW_Site; +extern SW_VEGPROD SW_VegProd; +extern SW_WEATHER SW_Weather; + +extern pcg32_random_t grid_rng; // Gridded mode's unique RNG. + +/* We need to seed these RNGs when using the gridded mode but do not use them in this file. */ +extern pcg32_random_t environs_rng; // Used exclusively in ST_environs.c +extern pcg32_random_t mortality_rng; // Used exclusively in ST_mortality.c +extern pcg32_random_t resgroups_rng; // Used exclusively in ST_resgroups.c +extern pcg32_random_t species_rng; // Used exclusively in ST_species.c +extern pcg32_random_t markov_rng; // Used exclusively in SW_Markov.c + +extern Bool UseProgressBar; // From ST_main.c +extern Bool* _SomeKillage; // From ST_mortality.c /******** Modular External Function Declarations ***********/ /* -- truly global functions are declared in functions.h --*/ @@ -286,34 +138,16 @@ SXW_resourceType* getSXWResources(void); transp_t* getTranspWindow(void); void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); -/********************** Exported Functions ***********************/ - -void runGrid(void); //to be called from ST_main.c - /*********** Locally Used Function Declarations ************/ /***********************************************************/ -static void logProgress(int iteration, int year, Status status); static double calculateProgress(int year, int iteration, Status status); static void printGeneralInfo(void); -static void _run_spinup(void); -static void _run_seed_initialization(void); -static void runInitialization(void); -static void beginInitialization(void); -static void endInitialization(void); -static void saveAsInitializationConditions(void); -static void loadInitializationConditions(void); static void _init_grid_files(void); -static void _init_grid_inputs(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); -static void _init_stepwat_inputs(void); static void allocate_gridCells(int rows, int cols); static void allocate_accumulators(void); -static void _free_grid_memory(void); -static void _free_spinup_memory(void); static void _load_cell(int row, int col, int year, Bool useAccumulators); -static void load_cell(int row, int col); -static void unload_cell(void); static void _read_disturbances_in(void); static void _read_soils_in(void); static void _init_soil_layers(int cell, int isSpinup); @@ -324,6 +158,8 @@ static void _read_init_species(void); static void _read_maxrgroupspecies(void); static void _read_grid_setup(void); static void _read_files(void); +static void _init_stepwat_inputs(void); +static void _init_grid_inputs(void); /******************** Begin Model Code *********************/ /***********************************************************/ @@ -332,7 +168,7 @@ static void _read_files(void); Param iteration: integer greater than 0. Input 0 iff the program is not currently in an iteration loop. Param year: integer greater than 0. Input 0 iff the program is not currently in a years loop. Param status: Use the "status" enum to choose a value. */ -static void logProgress(int iteration, int year, Status status){ +void logProgress(int iteration, int year, Status status){ static char progressString[256]; int index = 0; // Where we are in progressString Bool needsProgressBar = FALSE; // By default we donot need a progress bar @@ -418,12 +254,12 @@ static void printGeneralInfo(void){ printf("Number of cells: %d\n\n", grid_Cells); if(UseDisturbances) printf("Using grid disturbances file\n"); if(UseSoils) printf("Using grid soils file\n"); - if(InitializationMethod == INIT_WITH_SEEDS){ + if(initializationMethod == INIT_WITH_SEEDS){ printf("Running seed dispersal as initialization\n"); - } else if(InitializationMethod == INIT_WITH_SPINUP) { + } else if(initializationMethod == INIT_WITH_SPINUP) { printf("Running Spinup as initialization\n"); } - if(InitializationMethod != INIT_WITH_NOTHING){ + if(initializationMethod != INIT_WITH_NOTHING){ printf("Number of initialization years: %d\n", SuperGlobals.runInitializationYears); } if(UseSeedDispersal){ @@ -452,7 +288,7 @@ void runGrid(void) printGeneralInfo(); - if(InitializationMethod != INIT_WITH_NOTHING){ + if(initializationMethod != INIT_WITH_NOTHING){ runInitialization(); } else { /* If no spinup is requested we still need to reset SXW to set the historical weather @@ -492,7 +328,7 @@ void runGrid(void) unload_cell(); // Reset the global variables // If we used spinup we need to reset to the state of the program right after spinup. - if (InitializationMethod == INIT_WITH_SPINUP){ + if (initializationMethod == INIT_WITH_SPINUP){ loadInitializationConditions(); } @@ -620,224 +456,14 @@ void runGrid(void) Output_AllCellAvgBmass(fileBMassCellAvg); } - _free_grid_memory(); // Free our allocated memory since we do not need it anymore + free_grid_memory(); // Free our allocated memory since we do not need it anymore parm_free_memory(); // Free memory allocated to the _files array in ST_params.c - if(InitializationMethod == INIT_WITH_SPINUP) { - _free_spinup_memory(); + if(initializationMethod == INIT_WITH_SPINUP) { + freeInitializationMemory(); } logProgress(0, 0, DONE); } -/* "Spinup" the model by running without stat collection. */ -static void _run_spinup(void) -{ - Bool killedany; // killedany for mortality functions - - rgroup_Establish(); // Establish individuals. Excludes annuals. - Env_Generate(); // Generated the SOILWAT environment - rgroup_PartResources(); // Distribute resources - rgroup_Grow(); // Grow - mort_Main(&killedany); // Mortality that occurs during the growing season - rgroup_IncrAges(); // Increment ages of all plants - grazing_EndOfYear(); // Livestock grazing - mort_EndOfYear(); // End of year mortality. - _kill_annuals(); // Kill annuals - _kill_maxage(); // Kill plants that reach max age - proportion_Recovery(); // Recover from any disturbances - _kill_extra_growth(); // Kill superfluous growth -} - -/* TODO: This is a dummy method. It needs to be implemented once seed dispersal is fully planned. */ -static void _run_seed_initialization(void){ - if(Globals->currYear == 1){ - printf("\nYou have attempted to initialize with seed dispersal.\n" - "This option is currently in development and will be availible soon.\n"); - } - InitializationMethod = INIT_WITH_NOTHING; - return; -} - -/* Initializes the plot with whichever method you have specified with InitializationMethod. - This function takes care of EVERYTHING involved with initialization. - After calling this function you can load in the initialization information by calling - loadInitializationConditions(). */ -static void runInitialization(void){ - beginInitialization(); - - /* Dummy accumulators to ensure we do not collect statistics */ - StatType *dummy_Dist, *dummy_Ppt, *dummy_Temp, - *dummy_Grp, *dummy_Gsize, *dummy_Gpr, *dummy_Gmort, *dummy_Gestab, - *dummy_Spp, *dummy_Indv, *dummy_Smort, *dummy_Sestab, *dummy_Sreceived; - FireStatsType *dummy_Gwf; - - /* For iterating over gridCells */ - int i, j; - - /* For iterating over years */ - IntS year; - - /* Initialization is technically an iteration so we need to seed the RNGs. */ - RandSeed(SuperGlobals.randseed, &environs_rng); - RandSeed(SuperGlobals.randseed, &mortality_rng); - RandSeed(SuperGlobals.randseed, &resgroups_rng); - RandSeed(SuperGlobals.randseed, &species_rng); - RandSeed(SuperGlobals.randseed, &grid_rng); - RandSeed(SuperGlobals.randseed, &markov_rng); - - if (BmassFlags.yearly || MortFlags.yearly) - parm_Initialize(); - - // Initialize the plot for each grid cell - for (i = 0; i < grid_Rows; i++){ - for (j = 0; j < grid_Cols; j++){ - load_cell(i, j); - Plot_Initialize(); - Globals->currIter = 1; // Iteration doesn't really matter, I set it to 1 here just in case. - } - } - unload_cell(); // Reset the global variables - - for (year = 1; year <= SuperGlobals.runInitializationYears; year++) - { //for each year - if(UseProgressBar){ - logProgress(0, year, INITIALIZATION); // iter = 0 because we are not actually in an iterations loop. - } - for (i = 0; i < grid_Rows; ++i) - { // for each row - for(j = 0; j < grid_Cols; ++j) - { // for each column - // If we should run spinup on this cell - if(gridCells[i][j].mySpeciesInit.useInitialization){ - // Load up a cell - load_cell(i, j); - } else { - continue; // No spinup requested. Move on to next cell. - } - - /* This step is important. load_cell loaded in the actual accumulators, but we do not want - to accumulate stats while in spinup. We need to load in dummy accumulators to ensure - we ignore everything that happens in spinup. */ - stat_Copy_Accumulators(dummy_Dist, dummy_Ppt, dummy_Temp, dummy_Grp, dummy_Gsize, dummy_Gpr, dummy_Gmort, dummy_Gestab, - dummy_Spp, dummy_Indv, dummy_Smort, dummy_Sestab, dummy_Sreceived, dummy_Gwf, TRUE); - - Globals->currYear = year; - - switch (InitializationMethod){ - case INIT_WITH_SPINUP: - _run_spinup(); - break; - case INIT_WITH_SEEDS: - _run_seed_initialization(); - break; - default: - break; - } - - } /* end column */ - } /* end row */ - unload_cell(); // Reset the global variables - } /* end model run for this year*/ - - ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); - SXW_Reset(gridCells[0][0].mySXW->f_watin); - //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. - Mem_Free(SW_Soilwat.hist.file_prefix); - SW_Soilwat.hist.file_prefix = NULL; - ChDir(".."); - - endInitialization(); -} - -/* Prepares for initialization by turning on species that have requested initialization and turning off - species that have not requested initialization. This function should be accompanied by a call to - endInitialization. */ -static void beginInitialization(void){ - int i, j; /* For iterating over cells */ - SppIndex sp; /* For iterating over species */ - Bool temporary_storage; /* For swapping variables */ - - DuringInitialization = TRUE; - - /* Swap Species[sp]->use_me and mySpeciesInit.shouldBeInitialized[sp]. shouldBeInitialized is an array - of booleans that represent whether the given species should be used in initialization. use_me is a - boolean that represents whether the given species should be used in production. By swaping them we - save space, but we have to remember to swap them back before the production run. */ - for(i = 0; i < grid_Rows; ++i){ - for(j = 0; j < grid_Cols; ++j){ - if(!gridCells[i][j].mySpeciesInit.useInitialization){ - continue; - } - load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee - that ForEachGroup would iterate correctly */ - - /* Begin swaping variables */ - ForEachSpecies(sp){ - // Temporarily store use_me - temporary_storage = Species[sp]->use_me; - // Swap use_me - Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; - // Swap shouldBeInitialized[sp] - gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; - } /* End for each species */ - } /* End for each column */ - } /* End for each row */ - unload_cell(); // Reset the global variables -} - -/* Return the program to the state it needs to be in for the main simulation. This should only be called if you - have called beginInitialization. */ -static void endInitialization(void){ - // Calling this function a second time will swap the variables back to their original state. - beginInitialization(); - // Save the state of the program as our initialization conditions. - saveAsInitializationConditions(); - // We have now exited initialization. - DuringInitialization = FALSE; -} - -/* Save the current state of the program as spinup conditions. This is low level function. If you have already called - endInitialization() there is no need to call this function. */ -static void saveAsInitializationConditions(){ - // Save gridCells as spinupCells - spinupCells = gridCells; - // Nullify gridCells. This ensures we can no longer modify spinupCells on accident. - gridCells = NULL; - - // The easiest way to reallocate gridCells is reread the files. - _read_grid_setup(); // reads in grid_setup.in file - _read_files(); // reads in Stepwat_Inputs/files.in file - _init_stepwat_inputs(); // reads the stepwat inputs in - _init_grid_inputs(); // reads the grid inputs in & initializes the global grid variables -} - -/* Load the state of the program right after initialization. */ -static void loadInitializationConditions(){ - int row, col; - GrpIndex rg; - SppIndex sp; - - for(row = 0; row < grid_Rows; ++row){ - for(col = 0; col < grid_Cols; ++col){ - load_cell(row, col); - - ForEachSpecies(sp){ - copy_species(spinupCells[row][col].mySpecies[sp], Species[sp]); - } - - ForEachGroup(rg){ - copy_rgroup(spinupCells[row][col].myGroup[rg], RGroup[rg]); - } - - copy_environment(&spinupCells[row][col].myEnvironment, Env); - copy_plot(&spinupCells[row][col].myPlot, Plot); - copy_succulent(&spinupCells[row][col].mySucculent, Succulent); - - unload_cell(); - } - } - -} - /* Read the files.in file which was supplied to the program as an argument. This function saves the file names it reads to grid_files and grid_directories. */ static void _init_grid_files(void) @@ -885,11 +511,11 @@ static void _init_grid_inputs(void) if (UseDisturbances){ _read_disturbances_in(); } - if (UseSeedDispersal || InitializationMethod == INIT_WITH_SEEDS) + if (UseSeedDispersal || initializationMethod == INIT_WITH_SEEDS) { _init_seed_dispersal(); } - if(InitializationMethod != INIT_WITH_NOTHING){ + if(initializationMethod != INIT_WITH_NOTHING){ _read_init_species(); } if (UseSoils) { @@ -956,6 +582,15 @@ static void _init_stepwat_inputs(void) ChDir(".."); // go back to the folder we started in } +/* Reread input files. Be careful because this function reallocates the grid. + Make sure you call free_grid_memory before calling this function. */ +void rereadInputs(void){ + _read_grid_setup(); + _read_files(); + _init_stepwat_inputs(); + _init_grid_inputs(); +} + /* Allocates memory for the grid cells. This only needs to be called once. */ static void allocate_gridCells(int rows, int cols){ int i, j; @@ -1179,7 +814,7 @@ static void allocate_accumulators(void){ } /* Free all memory allocated to the gridded mode during initialization. */ -static void _free_grid_memory(void) +void free_grid_memory(void) { //frees all the memory allocated in this file ST_Grid.c (most of it is dynamically allocated in _init_grid_globals() & _load_grid_globals() functions) int i, j, sd_i; @@ -1217,23 +852,6 @@ static void _free_grid_memory(void) Mem_Free(gridCells); } -/* Free memory allocated to spinupCells. This function should only be called once per simulation. */ -static void _free_spinup_memory(void) -{ - // Remember where gridCells pointed. - CellType** locationOfGridCells = gridCells; - - // If spinupCells is allocated. - if(spinupCells){ - // move gridCells to point to spinupCells. This allows us to deallocate using _free_grid_memory(); - gridCells = spinupCells; - // Since we already have a function to deallocate gridCells we can use it. - _free_grid_memory(); - // And we need to reset gridCells in case it hasn't been deallocated. - gridCells = locationOfGridCells; - } -} - /* static void _load_cell(int row, int col, int year, Bool useAccumulators) { @@ -1351,7 +969,7 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators) /* Load gridCells[row][col] into the globals variables. Any call to this function should have an accompanying call to unload_cell(). */ -static void load_cell(int row, int col){ +void load_cell(int row, int col){ /* RGroup for this cell */ RGroup = gridCells[row][col].myGroup; @@ -1397,7 +1015,7 @@ static void load_cell(int row, int col){ } } unload_cell() */ -static void unload_cell(){ +void unload_cell(){ Species = NULL; RGroup = NULL; Succulent = NULL; @@ -2229,17 +1847,17 @@ static void _read_grid_setup(void) LogError(logfp, LOGFATAL, "Invalid grid setup file (Initialization line wrong)"); } if(!strncmp(initializationType, "spinup", 6)){ - InitializationMethod = INIT_WITH_SPINUP; + initializationMethod = INIT_WITH_SPINUP; } else if(!strncmp(initializationType, "seeds", 5)){ - InitializationMethod = INIT_WITH_SEEDS; + initializationMethod = INIT_WITH_SEEDS; } else if(!strncmp(initializationType, "none", 4)){ - InitializationMethod = INIT_WITH_NOTHING; + initializationMethod = INIT_WITH_NOTHING; } else { LogError(logfp, LOGFATAL, "Invalid grid setup file (Initialization line wrong. Valid options are \"spinup\", \"seeds\", or \"none\")"); } - if(InitializationMethod != INIT_WITH_NOTHING){ + if(initializationMethod != INIT_WITH_NOTHING){ GetALine(f, buf); i = sscanf(buf, "%hd", &SuperGlobals.runInitializationYears); if(i < 1){ diff --git a/ST_grid.h b/ST_grid.h new file mode 100644 index 00000000..5ad5dec4 --- /dev/null +++ b/ST_grid.h @@ -0,0 +1,179 @@ +/******************************************************************/ +/* ST_grid.h + This header defines global functions, variables, structs and + enumerators from ST_grid.c. If you are looking for the functions + that this module exports check the bottom of the file. + + Initial programming by Chandler Haukap. */ +/******************************************************************/ + +#ifndef GRID_H +#define GRID_H + +/******** These modules are necessary to compile ST_grid.c ********/ +#include "ST_stats.h" +#include "ST_defines.h" +#include "sw_src/pcg/pcg_basic.h" +#include "sxw_vars.h" +#include "SW_Site.h" +#include "SW_SoilWater.h" +#include "SW_VegProd.h" +#include "SW_Model.h" +#include "SW_Weather.h" + +/*********************** Grid Structures ****************************/ +// represents a single soil layer +struct _grid_soil_lyr_st +{ + // Data for this soil layer + float data[11]; + // Vertical width of this layer + int width; +}typedef Grid_Soil_Lyr; + +//represents the input data for all the soil layers of a cell +struct Soil_st +{ + // Number of soil layers (size of lyr array) + int num_layers; + // Name of the roots file belonging to this cell + char rootsFile[20]; + // Specific layer's information + Grid_Soil_Lyr* lyr; +}typedef SoilType; + +/* Holds seed dispersal information. */ +struct _grid_sd_struct +{ //for seed dispersal + /* TRUE if seeds are present. */ + Bool seeds_present; + /* TRUE if this cell has recieved any seeds. */ + Bool seeds_received; + /* probabilityOfDispersing[row][col] = the probability that this cell will disperse seeds to cell (row,col). */ + double **probabilityOfDispersing; + /* Last year's precipitation. */ + double lyppt; +}typedef Grid_SD_St; + +/* Initialization information. */ +struct _grid_init_species_st +{ + /* TRUE if at least one species has requested initialization */ + int useInitialization; + /* Array of Boolean values. TRUE if given species + should be included in spinup */ + int *shouldBeInitialized; +}typedef Grid_Init_Species_St; + +/* Holds all plot-specific parameters */ +struct grid_cell_st +{ + /* RGroup coresponding to this cell */ + GroupType **myGroup; + /* Species corresponding to this cell */ + SpeciesType **mySpecies; + /* Succulents corresponding to this cell */ + SucculentType mySucculent; + /* This cell's environment. We expect each cell to + * have slightly different weather each year */ + EnvType myEnvironment; + /* Cell's plot data */ + PlotType myPlot; + /* Global variables corresponding to this cell */ + ModelType myGlobals; + /* If TRUE this cell should use seed dispersal */ + Bool useSeedDispersal; + /* TRUE if this cell is in spinup mode */ + Bool DuringInitialization; + /* species spinup information */ + Grid_Init_Species_St mySpeciesInit; + /* seed dispersal information corresponding to this cell */ + Grid_SD_St *mySeedDispersal; + + Bool* someKillage; + + /* ---------------- accumulators -------------------- */ + StatType *_Dist, *_Ppt, *_Temp, + *_Grp, *_Gsize, *_Gpr, *_Gmort, *_Gestab, + *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; + FireStatsType *_Gwf; + Bool stats_init; + /* -------------- end accumulators ------------------ */ + + /* -------------------- SXW ------------------------- */ + transp_t* myTranspWindow; + SXW_t* mySXW; + SXW_resourceType* mySXWResources; + /* ------------------ End SXW ----------------------- */ + + /* ------------------- Soils ------------------------ */ + // Soil layer information for this cell. + SoilType mySoils; + /* ------------------ End Soils --------------------- */ +} typedef CellType; + + +/**************************** Enumerators *********************************/ +/* Indices for grid_directories go here */ +typedef enum +{ + GRID_DIRECTORY_STEPWAT_INPUTS, + + /* Automatically generate number of directories since enums start at 0 */ + N_GRID_DIRECTORIES +} Directory_Indices; + +/* Indices for grid_files go here */ +typedef enum +{ + GRID_FILE_LOGFILE, + GRID_FILE_SETUP, + GRID_FILE_DISTURBANCES, + GRID_FILE_SOILS, + GRID_FILE_INIT_SPECIES, + GRID_FILE_FILES, + GRID_FILE_MAXRGROUPSPECIES, + + GRID_FILE_PREFIX_BMASSAVG, + GRID_FILE_PREFIX_MORTAVG, + GRID_FILE_PREFIX_RECEIVEDPROB, + GRID_FILE_PREFIX_BMASSCELLAVG, + + /* Automatically generate number of files since enums start at 0 */ + N_GRID_FILES +} File_Indices; + +/* Possible states of the program */ +typedef enum +{ + INITIALIZATION, + SIMULATION, + OUTPUT, + DONE +} Status; + +/************************ Exported Variable Declarations **************************/ + +/* gridCells[i][j] denotes the cell at position (i,j) */ +CellType** gridCells; +/* Rows in the grid */ +int grid_Rows; +/* Columns in the grid */ +int grid_Cols; +/* Array of file names. Use the File_Indices enum to pick the correct index. */ +char *grid_files[N_GRID_FILES]; +/* Array of directory names. Use the Directory_Indices enum to pick the correct index. */ +char *grid_directories[N_GRID_DIRECTORIES]; +/* TRUE if we should run seed dispersal between years during the main simulation. */ +Bool UseSeedDispersal; + +/**************************** Exported Functions **********************************/ + +void runGrid(void); +void load_cell(int row, int col); +void unload_cell(void); +void logProgress(int iteration, int year, Status status); +void rereadInputs(void); +void free_grid_memory(void); + +#endif \ No newline at end of file diff --git a/ST_initialization.c b/ST_initialization.c new file mode 100644 index 00000000..dedae349 --- /dev/null +++ b/ST_initialization.c @@ -0,0 +1,307 @@ +/***********************************************************************/ +// ST_initialization.c +// Contains definitions of all functions related to initialization. +// The current initialization methods are _run_seed_initialization +// and _run_spinup. This file uses the "_" prefix to function names +// to denote private functions that should NEVER be called outside +// of this file. +// +// TO ADD AN INITIALIZATION METHOD: +// Adding a method is simple. runInitialization() takes care of memory +// management, iterating, and loading cells. All you need to do in your +// new function is define what the program should do for ONE year and +// for ONE cell. Once you have your function written, add an entry for +// it to the InitializationMethod enumerator in ST_initialization.h, +// add your method to _read_grid_setup() of ST_grid.c, then add your +// function to the switch statement in runInitialization(). To see +// an example initialization function check out _run_spinup(). +/***********************************************************************/ + +// ST_initialization.h contains declarations for runInitialization and loadInitializationConditions +#include "ST_initialization.h" +#include "ST_grid.h" +#include "ST_stats.h" +#include "ST_globals.h" +#include "ST_defines.h" +#include "sw_src/pcg/pcg_basic.h" +#include "sw_src/rands.h" +#include "sxw_funcs.h" +#include "myMemory.h" +#include "filefuncs.h" + +/********** Local functions. These should all be treated as private. *************/ +static void _run_spinup(void); +static void _run_seed_initialization(void); +static void _beginInitialization(void); +static void _endInitialization(void); +static void _saveAsInitializationConditions(void); + +/***************************** Externed variables **********************************/ +/* Note that in an ideal world we wouldn't need to extern any variables because + every module would declate them in a header file. Hopefully we can get this + cleaned up soon! -CH */ + +// these are SOILWAT variables that we need... +extern SW_SOILWAT SW_Soilwat; +extern SW_SITE SW_Site; +extern SW_VEGPROD SW_VegProd; +extern SW_WEATHER SW_Weather; + +extern pcg32_random_t grid_rng; // Gridded mode's unique RNG. + +/* We need to seed these RNGs when using the gridded mode but do not use them in this file. */ +extern pcg32_random_t environs_rng; // Used exclusively in ST_environs.c +extern pcg32_random_t mortality_rng; // Used exclusively in ST_mortality.c +extern pcg32_random_t resgroups_rng; // Used exclusively in ST_resgroups.c +extern pcg32_random_t species_rng; // Used exclusively in ST_species.c +extern pcg32_random_t markov_rng; // Used exclusively in SW_Markov.c + +extern Bool UseProgressBar; // From ST_main.c +extern Bool* _SomeKillage; // From ST_mortality.c + +/********* Modular functions defined elsewhere ************/ +/* Again, we should clean this up eventually. -CH */ + +void rgroup_Establish(void); +void Env_Generate(void); +void rgroup_PartResources(void); +void rgroup_Grow(void); +void mort_Main(Bool* killed); +void rgroup_IncrAges(void); +void grazing_EndOfYear(void); +void mort_EndOfYear(void); +void _kill_annuals(void); +void _kill_maxage(void); +void proportion_Recovery(void); +void _kill_extra_growth(void); +void parm_Initialize(void); +void Plot_Initialize(void); +void copy_rgroup(const GroupType* src, GroupType* dest); +void copy_species(const SpeciesType* src, SpeciesType* dest); +void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, + StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, + StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); + +/* Initializes the plot with whichever method you have specified with initializationMethod. + This function takes care of EVERYTHING involved with initialization. + After calling this function you can load in the initialization information by calling + loadInitializationConditions(). */ +void runInitialization(void){ + _beginInitialization(); + + /* Dummy accumulators to ensure we do not collect statistics */ + StatType *dummy_Dist, *dummy_Ppt, *dummy_Temp, + *dummy_Grp, *dummy_Gsize, *dummy_Gpr, *dummy_Gmort, *dummy_Gestab, + *dummy_Spp, *dummy_Indv, *dummy_Smort, *dummy_Sestab, *dummy_Sreceived; + FireStatsType *dummy_Gwf; + + /* For iterating over gridCells */ + int i, j; + + /* For iterating over years */ + IntS year; + + /* Initialization is technically an iteration so we need to seed the RNGs. */ + RandSeed(SuperGlobals.randseed, &environs_rng); + RandSeed(SuperGlobals.randseed, &mortality_rng); + RandSeed(SuperGlobals.randseed, &resgroups_rng); + RandSeed(SuperGlobals.randseed, &species_rng); + RandSeed(SuperGlobals.randseed, &grid_rng); + RandSeed(SuperGlobals.randseed, &markov_rng); + + if (BmassFlags.yearly || MortFlags.yearly) + parm_Initialize(); + + // Initialize the plot for each grid cell + for (i = 0; i < grid_Rows; i++){ + for (j = 0; j < grid_Cols; j++){ + load_cell(i, j); + Plot_Initialize(); + Globals->currIter = 1; // Iteration doesn't really matter, I set it to 1 here just in case. + } + } + unload_cell(); // Reset the global variables + + for (year = 1; year <= SuperGlobals.runInitializationYears; year++) + { //for each year + if(UseProgressBar){ + logProgress(0, year, INITIALIZATION); // iter = 0 because we are not actually in an iterations loop. + } + for (i = 0; i < grid_Rows; ++i) + { // for each row + for(j = 0; j < grid_Cols; ++j) + { // for each column + // If we should run spinup on this cell + if(gridCells[i][j].mySpeciesInit.useInitialization){ + // Load up a cell + load_cell(i, j); + } else { + continue; // No spinup requested. Move on to next cell. + } + + /* This step is important. load_cell loaded in the actual accumulators, but we do not want + to accumulate stats while in spinup. We need to load in dummy accumulators to ensure + we ignore everything that happens in spinup. */ + stat_Copy_Accumulators(dummy_Dist, dummy_Ppt, dummy_Temp, dummy_Grp, dummy_Gsize, dummy_Gpr, dummy_Gmort, dummy_Gestab, + dummy_Spp, dummy_Indv, dummy_Smort, dummy_Sestab, dummy_Sreceived, dummy_Gwf, TRUE); + + Globals->currYear = year; + + switch (initializationMethod){ + case INIT_WITH_SPINUP: + _run_spinup(); + break; + case INIT_WITH_SEEDS: + _run_seed_initialization(); + break; + default: + break; + } + + } /* end column */ + } /* end row */ + unload_cell(); // Reset the global variables + } /* end model run for this year*/ + + ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); + SXW_Reset(gridCells[0][0].mySXW->f_watin); + //TODO: This is a shortcut. swc history is not used and shouldn't be until this is fixed. + Mem_Free(SW_Soilwat.hist.file_prefix); + SW_Soilwat.hist.file_prefix = NULL; + ChDir(".."); + + _endInitialization(); +} + +/* Prepares for initialization by turning on species that have requested initialization and turning off + species that have not requested initialization. This function should be accompanied by a call to + _endInitialization. */ +static void _beginInitialization(void){ + int i, j; /* For iterating over cells */ + SppIndex sp; /* For iterating over species */ + Bool temporary_storage; /* For swapping variables */ + + DuringInitialization = TRUE; + + /* Swap Species[sp]->use_me and mySpeciesInit.shouldBeInitialized[sp]. shouldBeInitialized is an array + of booleans that represent whether the given species should be used in initialization. use_me is a + boolean that represents whether the given species should be used in production. By swaping them we + save space, but we have to remember to swap them back before the production run. */ + for(i = 0; i < grid_Rows; ++i){ + for(j = 0; j < grid_Cols; ++j){ + if(!gridCells[i][j].mySpeciesInit.useInitialization){ + continue; + } + load_cell(i, j); /* We could do this without loading the cell, but there would be no guarantee + that ForEachGroup would iterate correctly */ + + /* Begin swaping variables */ + ForEachSpecies(sp){ + // Temporarily store use_me + temporary_storage = Species[sp]->use_me; + // Swap use_me + Species[sp]->use_me = gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp]; + // Swap shouldBeInitialized[sp] + gridCells[i][j].mySpeciesInit.shouldBeInitialized[sp] = temporary_storage; + } /* End for each species */ + } /* End for each column */ + } /* End for each row */ + unload_cell(); // Reset the global variables +} + +/* Return the program to the state it needs to be in for the main simulation. This should only be called if you + have called _beginInitialization. */ +static void _endInitialization(void){ + // Calling this function a second time will swap the variables back to their original state. + _beginInitialization(); + // Save the state of the program as our initialization conditions. + _saveAsInitializationConditions(); + // We have now exited initialization. + DuringInitialization = FALSE; +} + +/* Save the current state of the program as spinup conditions. This is low level function. If you have already called + _endInitialization() there is no need to call this function. */ +static void _saveAsInitializationConditions(){ + // Save gridCells as initializationCells + initializationCells = gridCells; + // Nullify gridCells. This ensures we can no longer modify initializationCells on accident. + gridCells = NULL; + + // The easiest way to reallocate gridCells is reread the files. + rereadInputs(); +} + +/* Load the state of the program right after initialization. */ +void loadInitializationConditions(){ + int row, col; + GrpIndex rg; + SppIndex sp; + + for(row = 0; row < grid_Rows; ++row){ + for(col = 0; col < grid_Cols; ++col){ + load_cell(row, col); + + ForEachSpecies(sp){ + copy_species(initializationCells[row][col].mySpecies[sp], Species[sp]); + } + + ForEachGroup(rg){ + copy_rgroup(initializationCells[row][col].myGroup[rg], RGroup[rg]); + } + + copy_environment(&initializationCells[row][col].myEnvironment, Env); + copy_plot(&initializationCells[row][col].myPlot, Plot); + copy_succulent(&initializationCells[row][col].mySucculent, Succulent); + + unload_cell(); + } + } + +} + +/* "Spinup" the model by running without stat collection. */ +static void _run_spinup(void) +{ + Bool killedany; // killedany for mortality functions + + rgroup_Establish(); // Establish individuals. Excludes annuals. + Env_Generate(); // Generated the SOILWAT environment + rgroup_PartResources(); // Distribute resources + rgroup_Grow(); // Grow + mort_Main(&killedany); // Mortality that occurs during the growing season + rgroup_IncrAges(); // Increment ages of all plants + grazing_EndOfYear(); // Livestock grazing + mort_EndOfYear(); // End of year mortality. + _kill_annuals(); // Kill annuals + _kill_maxage(); // Kill plants that reach max age + proportion_Recovery(); // Recover from any disturbances + _kill_extra_growth(); // Kill superfluous growth +} + +/* TODO: This is a dummy method. It needs to be implemented once seed dispersal is fully planned. */ +static void _run_seed_initialization(void){ + if(Globals->currYear == 1){ + printf("\nYou have attempted to initialize with seed dispersal.\n" + "This option is currently in development and will be availible soon.\n"); + } + initializationMethod = INIT_WITH_NOTHING; + return; +} + +/* Free memory allocated to initializationCells. This function should only be called once per simulation. */ +void freeInitializationMemory(void) +{ + // Remember where gridCells pointed. + CellType** locationOfGridCells = gridCells; + + // If initializationCells is allocated. + if(initializationCells){ + // move gridCells to point to initializationCells. This allows us to deallocate using free_grid_memory(); + gridCells = initializationCells; + // Since we already have a function to deallocate gridCells we can use it. + free_grid_memory(); + // And we need to reset gridCells in case it hasn't been deallocated. + gridCells = locationOfGridCells; + } +} \ No newline at end of file diff --git a/ST_initialization.h b/ST_initialization.h new file mode 100644 index 00000000..31abdb3f --- /dev/null +++ b/ST_initialization.h @@ -0,0 +1,41 @@ +/***********************************************************************/ +/* ST_initialization.h + This header defines the functions exported from ST_initialization.c. + Initialization is currently only availible when running gridded + mode. + + Initial programming by Chandler Haukap. */ +/***********************************************************************/ + +#ifndef INITIALIZATION_H +#define INITIALIZATION_H + +/* This module only functions in the context of gridded mode. */ +#include"ST_grid.h" + +/**************** Enumerator for initialization types ******************/ + +/* Possible methods of initialization. */ +typedef enum +{ + INIT_WITH_SPINUP, + INIT_WITH_SEEDS, + INIT_WITH_NOTHING +} InitializationMethod; + +/********** Exported functions defined in ST_initialization.c ***********/ + +void runInitialization(void); +void loadInitializationConditions(void); +void freeInitializationMemory(void); + +/************************ Exported variables ****************************/ + +/* Stores the state of the cells following spinup. */ +CellType** initializationCells; +/* The method of initialization specified in inputs. */ +InitializationMethod initializationMethod; +/* TRUE if the program is currently in initialization. */ +Bool DuringInitialization; + +#endif \ No newline at end of file diff --git a/ST_main.c b/ST_main.c index 1fa6cdeb..841d1cdf 100644 --- a/ST_main.c +++ b/ST_main.c @@ -33,6 +33,7 @@ #include "sw_src/SW_Output_outtext.h" #include "sw_src/SW_Output_outarray.h" #include "sw_src/rands.h" +#include "ST_initialization.h" extern SXW_t* SXW; extern Bool prepare_IterationSummary; // defined in `SOILWAT2/SW_Output.c` @@ -68,8 +69,6 @@ extern Bool* _SomeKillage; void stat_Output_AllMorts( void) ; void stat_Output_AllBmass(void) ; - void runGrid( void ); //for the grid... declared in ST_grid.c */ - void _kill_annuals(void); void _kill_extra_growth(void); void _kill_maxage(void); @@ -136,9 +135,6 @@ BmassFlagsType BmassFlags; MortFlagsType MortFlags; Bool UseGrid; -Bool UseSeedDispersal; -int InitializationMethod; -Bool DuringInitialization; Bool EchoInits; Bool UseProgressBar; Bool STdebug_requested; diff --git a/ST_species.c b/ST_species.c index 7b7bc4c3..92796940 100644 --- a/ST_species.c +++ b/ST_species.c @@ -23,6 +23,7 @@ #include "myMemory.h" #include "rands.h" #include "sw_src/pcg/pcg_basic.h" +#include "ST_initialization.h" extern pcg32_random_t species_rng; diff --git a/ST_stats.c b/ST_stats.c index 869ffed2..fa65fc16 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -27,6 +27,7 @@ #include "sw_src/SW_Site.h" #include "ST_structs.h" #include "ST_stats.h" +#include "ST_initialization.h" #include "sxw.h" extern SW_SITE SW_Site; diff --git a/makefile b/makefile index 81a9aefc..41824f27 100644 --- a/makefile +++ b/makefile @@ -55,7 +55,8 @@ SRCS =\ $(Src)/ST_species.c\ $(Src)/ST_stats.c\ $(Src)/ST_grid.c\ - $(Src)/ST_sql.c + $(Src)/ST_sql.c\ + $(Src)/ST_initialization.c #$(Src)/sxw_tester.c EXOBJS =\ @@ -98,7 +99,8 @@ EXOBJS =\ $(oDir)/ST_stats.o\ $(oDir)/sxw_environs.o\ $(oDir)/ST_grid.o\ - $(oDir)/ST_sql.o + $(oDir)/ST_sql.o\ + $(oDir)/ST_initialization.o #$(oDir)/sxw_tester.o ALLOBJS = $(EXOBJS) @@ -349,9 +351,11 @@ $(oDir)/sw_src/SW_VegEstab.o: sw_src/SW_VegEstab.c sw_src/generic.h sw_src/filef sw_src/SW_Model.h sw_src/SW_SoilWater.h sw_src/SW_Weather.h sw_src/SW_VegEstab.h $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< -$(oDir)/ST_grid.o: ST_grid.c ST_steppe.h ST_defines.h sw_src/generic.h \ - ST_globals.h sw_src/myMemory.h ST_globals.h sw_src/pcg/pcg_basic.h +$(oDir)/ST_grid.o: ST_grid.c $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< $(oDir)/ST_sql.o: ST_sql.c ST_steppe.h ST_globals.h $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< + +$(oDir)/ST_initialization.o: ST_initialization.c + $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< From cab74303521cfc2a4ad6a8d6ea4eecccad887753 Mon Sep 17 00:00:00 2001 From: chaukap Date: Fri, 19 Jul 2019 12:00:09 -0600 Subject: [PATCH 126/167] (issue #359) Created progress bar .c and .h files. This commit creates ST_progressBar.c and ST_progressBar.h. These files make the progress bar stand-alone (except for a reference to SuperGlobals). Here are summaries for all of the files I modifed: ST_grid.c: I removed the definitions for logProgress and calculateProgress, as well as the declaration of calculateProgress. ST_grid.h: I removed the Status enumerator as well as the declaration for logProgress. ST_progressBar.h: I added the Status enumerator and the declaration for logProgress. ST_progressBar.c: I added the definitions for logProgress and calculateProgress (renamed _calculateProgress). I also add the declaration for _calculateProgress. Last, I added two new functions called _calculateInitializationProgress and _calculateSimulationProgress. These two functions make the module easier to understand and expand. ST_main.c: Added an include statement for the progress bar module, then implemented the progress bar. I also removed the "."s that the program was printing in place of a progress bar. ST_initialization.c: Added an include statement for the progress bar module. makefile: Added rule for ST_progressBar.c --- ST_grid.c | 84 +------------------------------- ST_grid.h | 10 ---- ST_initialization.c | 1 + ST_main.c | 20 ++++---- ST_progressBar.c | 115 ++++++++++++++++++++++++++++++++++++++++++++ ST_progressBar.h | 34 +++++++++++++ makefile | 9 +++- 7 files changed, 169 insertions(+), 104 deletions(-) create mode 100644 ST_progressBar.c create mode 100644 ST_progressBar.h diff --git a/ST_grid.c b/ST_grid.c index 2624cd49..ab7af55a 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -40,6 +40,7 @@ #include "rands.h" #include "sxw_funcs.h" #include "ST_initialization.h" +#include "ST_progressBar.h" char sd_Sep; @@ -141,7 +142,6 @@ void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp /*********** Locally Used Function Declarations ************/ /***********************************************************/ -static double calculateProgress(int year, int iteration, Status status); static void printGeneralInfo(void); static void _init_grid_files(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); @@ -164,88 +164,6 @@ static void _init_grid_inputs(void); /******************** Begin Model Code *********************/ /***********************************************************/ -/* Log the program's progress using a progress bar. - Param iteration: integer greater than 0. Input 0 iff the program is not currently in an iteration loop. - Param year: integer greater than 0. Input 0 iff the program is not currently in a years loop. - Param status: Use the "status" enum to choose a value. */ -void logProgress(int iteration, int year, Status status){ - static char progressString[256]; - int index = 0; // Where we are in progressString - Bool needsProgressBar = FALSE; // By default we donot need a progress bar - progressString[0] = '\0'; // Empty the string - iteration--; // iteration loops are 1 indexed, but we need 0 indexing. - - switch(status){ - case INITIALIZATION: - strcpy(progressString, "Initializing |"); - index += 14; // We have copied over 16 characters - needsProgressBar = TRUE; - break; - case SIMULATION: - strcpy(progressString, "Simulating |"); - index += 14; // We have copied over 12 characters - needsProgressBar = TRUE; - break; - case OUTPUT: - strcpy(progressString, "Writing files"); - index += 13; // We have copied over 12 characters - break; - case DONE: - strcpy(progressString, "Done"); - // We need to pad the string with spaces to make sure we overwrite any progress bars. - for(index = 4; index < 40; ++index) progressString[index] = ' '; - break; - default: - break; - } - - // If our program is currently in a looping state we can make a progress bar using year and iteration. - if(needsProgressBar){ - int numberOfCharacters = 0; - double percentComplete = calculateProgress(year, iteration, status); - // Add '=' characters for every 5% complete. - while(percentComplete > 0){ - progressString[index] = '='; - index++; - numberOfCharacters++; - percentComplete -= 5; - } - // Add spaces until we hit 20 characters - while(numberOfCharacters < 20){ - progressString[index] = ' '; - numberOfCharacters++; - index++; - } - progressString[index++] = '|'; - progressString[index++] = '\0'; - } - - printf("\r%s", progressString); // print the string we generated - fflush(stdout); // Explicitly print the output. - - // If we are done we want to print a newline character so the terminal isn't appended to our "Done" string. - if(status == DONE){ - printf("\n"); - } -} - -/* Returns a double between 0 and 100 representing how close the program is to completing a given loop. - Param year: Current year in the loop. - Param iteration: Current iteration in the loop. - Param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. */ -double calculateProgress(int year, int iteration, Status status){ - double percentComplete; - if(status == INITIALIZATION){ - percentComplete = (year / (double) SuperGlobals.runInitializationYears); - } else if(status == SIMULATION) { - percentComplete = ((iteration * SuperGlobals.runModelYears) + year) - / (double) (SuperGlobals.runModelIterations * SuperGlobals.runModelYears); - } else { - return 0; // If the program isn't in spinup or simulation then this function isn't applicable. - } - return percentComplete * 100; -} - /* Print information about the simulation to stdout. */ static void printGeneralInfo(void){ /* ------------------- Print some general information to stdout ----------------------- */ diff --git a/ST_grid.h b/ST_grid.h index 5ad5dec4..63b554ae 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -143,15 +143,6 @@ typedef enum N_GRID_FILES } File_Indices; -/* Possible states of the program */ -typedef enum -{ - INITIALIZATION, - SIMULATION, - OUTPUT, - DONE -} Status; - /************************ Exported Variable Declarations **************************/ /* gridCells[i][j] denotes the cell at position (i,j) */ @@ -172,7 +163,6 @@ Bool UseSeedDispersal; void runGrid(void); void load_cell(int row, int col); void unload_cell(void); -void logProgress(int iteration, int year, Status status); void rereadInputs(void); void free_grid_memory(void); diff --git a/ST_initialization.c b/ST_initialization.c index dedae349..53fc1cd0 100644 --- a/ST_initialization.c +++ b/ST_initialization.c @@ -28,6 +28,7 @@ #include "sxw_funcs.h" #include "myMemory.h" #include "filefuncs.h" +#include "ST_progressBar.h" /********** Local functions. These should all be treated as private. *************/ static void _run_spinup(void); diff --git a/ST_main.c b/ST_main.c index 841d1cdf..e9d09975 100644 --- a/ST_main.c +++ b/ST_main.c @@ -34,6 +34,7 @@ #include "sw_src/SW_Output_outarray.h" #include "sw_src/rands.h" #include "ST_initialization.h" +#include "ST_progressBar.h" extern SXW_t* SXW; extern Bool prepare_IterationSummary; // defined in `SOILWAT2/SW_Output.c` @@ -201,13 +202,6 @@ int main(int argc, char **argv) { /* --- Begin a new iteration ------ */ for (iter = 1; iter <= SuperGlobals.runModelIterations; iter++) { - if (progfp == stderr) { - if (iter % incr == 0) - fprintf(progfp, "."); - } else { - fprintf(progfp, "%d\n", iter); - } - Plot_Initialize(); RandSeed(SuperGlobals.randseed, &environs_rng); @@ -229,6 +223,9 @@ int main(int argc, char **argv) { /* ------ Begin running the model ------ */ for (year = 1; year <= SuperGlobals.runModelYears; year++) { + if(UseProgressBar){ + logProgress(iter, year, SIMULATION); + } //printf("------------------------Repetition/year = %d / %d\n", iter, year); @@ -306,6 +303,10 @@ int main(int argc, char **argv) { } } /* end model run for this iteration*/ + if(UseProgressBar){ + logProgress(0, 0, OUTPUT); + } + /*------------------------------------------------------*/ if (MortFlags.summary) stat_Output_AllMorts(); @@ -328,8 +329,9 @@ int main(int argc, char **argv) { deallocate_Globals(FALSE); - printf("\nend program\n"); - fprintf(progfp, "\n"); + // This isn't wrapped in an if statement on purpose. + // We should print "Done" either way. + logProgress(0, 0, DONE); return 0; } diff --git a/ST_progressBar.c b/ST_progressBar.c new file mode 100644 index 00000000..aa2d0a83 --- /dev/null +++ b/ST_progressBar.c @@ -0,0 +1,115 @@ +/**************************************************************************/ +/* ST_progressBar.c + Function definitions for a progress bar printed to the terminal. + See ST_progressBar.h for a description of how to add a new Status. + */ +/**************************************************************************/ + +#include "ST_progressBar.h" +#include "ST_defines.h" +#include "ST_globals.h" +#include + +/*************** Local Function(s). Treat these as private. ***************/ + +double _calculateProgress(int year, int iteration, Status status); +double _calculateInitializationProgress(int year); +double _calculateSimulationProgress(int year, int iteration); + +/*********************** Function Definitions *****************************/ + +/* Log the program's progress using a progress bar. + Param iteration: integer greater than 0. Input 0 iff the program is not currently in an iteration loop. + Param year: integer greater than 0. Input 0 iff the program is not currently in a years loop. + Param status: Use the "status" enum to choose a value. */ +void logProgress(int iteration, int year, Status status){ + static char progressString[256]; + int index = 0; // Where we are in progressString + Bool needsProgressBar = FALSE; // By default we donot need a progress bar + progressString[0] = '\0'; // Empty the string + iteration--; // iteration loops are 1 indexed, but we need 0 indexing. + + switch(status){ + case INITIALIZATION: + strcpy(progressString, "Initializing |"); + index += 14; // We have copied over 16 characters + needsProgressBar = TRUE; + break; + case SIMULATION: + strcpy(progressString, "Simulating |"); + index += 14; // We have copied over 12 characters + needsProgressBar = TRUE; + break; + case OUTPUT: + strcpy(progressString, "Writing files"); + index += 13; // We have copied over 12 characters + break; + case DONE: + strcpy(progressString, "Done"); + // We need to pad the string with spaces to make sure we overwrite any progress bars. + for(index = 4; index < 40; ++index) progressString[index] = ' '; + break; + default: + break; + } + + // If our program is currently in a looping state we can make a progress bar using year and iteration. + if(needsProgressBar){ + int numberOfCharacters = 0; + double percentComplete = _calculateProgress(year, iteration, status); + // Add '=' characters for every 5% complete. + while(percentComplete > 0){ + progressString[index] = '='; + index++; + numberOfCharacters++; + percentComplete -= 5; + } + // Add spaces until we hit 20 characters + while(numberOfCharacters < 20){ + progressString[index] = ' '; + numberOfCharacters++; + index++; + } + progressString[index++] = '|'; + progressString[index++] = '\0'; + } + + printf("\r%s", progressString); // print the string we generated + fflush(stdout); // Explicitly print the output. + + // If we are done we want to print a newline character so the terminal isn't appended to our "Done" string. + if(status == DONE){ + printf("\n"); + } +} + +/* Returns a double between 0 and 100 representing how close the program is to completing a given loop. + Param year: Current year in the loop. + Param iteration: Current iteration in the loop. + Param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. */ +double _calculateProgress(int year, int iteration, Status status){ + double percentComplete; + if(status == INITIALIZATION){ + percentComplete = _calculateInitializationProgress(year); + } else if(status == SIMULATION) { + percentComplete = _calculateSimulationProgress(year, iteration); + } else { + return 0; // No other Status has defined how to calculate progress. + } + return percentComplete; +} + +/* Algorithm for calculating how far along initialization is. + Returns a percentage between 0 and 100. */ +double _calculateInitializationProgress(int year){ + return (year / (double) SuperGlobals.runInitializationYears) * 100; +} + +/* Algorithm for calculating how far along the simulation is. + Returns a percentage between 0 and 100. */ +double _calculateSimulationProgress(int year, int iteration){ + double prog = ((iteration * SuperGlobals.runModelYears) + year) + / (double) (SuperGlobals.runModelIterations * SuperGlobals.runModelYears); + + return prog * 100; +} \ No newline at end of file diff --git a/ST_progressBar.h b/ST_progressBar.h new file mode 100644 index 00000000..9883f82b --- /dev/null +++ b/ST_progressBar.h @@ -0,0 +1,34 @@ +/******************************************************************/ +/* ST_progressBar.h + Defines all exported objects from ST_progressBar.c. + + TO ADD STATUSES: + Adding a Status is easy. Start by adding your entry to the + Status enum. Then, define what message your status should + print in the switch statement in logProgress() defined in + ST_progressBar.c. Finally, if your Status requires a + progress bar, create a function for calculating progress + in ST_progressBar.c then add your function to + _calculateProgress(). +*/ +/******************************************************************/ + +#ifndef PROGRESSBAR_H +#define PROGRESSBAR_H + +/*********************** Enumerator(s) ****************************/ + +/* States of the program that the progress bar recognises. */ +typedef enum +{ + INITIALIZATION, + SIMULATION, + OUTPUT, + DONE +} Status; + +/******************** Exported Function(s) ************************/ + +void logProgress(int iteration, int year, Status status); + +#endif \ No newline at end of file diff --git a/makefile b/makefile index 41824f27..7a00caf8 100644 --- a/makefile +++ b/makefile @@ -56,7 +56,8 @@ SRCS =\ $(Src)/ST_stats.c\ $(Src)/ST_grid.c\ $(Src)/ST_sql.c\ - $(Src)/ST_initialization.c + $(Src)/ST_initialization.c\ + $(Src)/ST_progressBar.c #$(Src)/sxw_tester.c EXOBJS =\ @@ -100,7 +101,8 @@ EXOBJS =\ $(oDir)/sxw_environs.o\ $(oDir)/ST_grid.o\ $(oDir)/ST_sql.o\ - $(oDir)/ST_initialization.o + $(oDir)/ST_initialization.o\ + $(oDir)/ST_progressBar.o #$(oDir)/sxw_tester.o ALLOBJS = $(EXOBJS) @@ -359,3 +361,6 @@ $(oDir)/ST_sql.o: ST_sql.c ST_steppe.h ST_globals.h $(oDir)/ST_initialization.o: ST_initialization.c $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< + +$(oDir)/ST_progressBar.o: ST_progressBar.c + $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< \ No newline at end of file From 9e22edc3c48ed7d86c4a69a655c70fc23d88b25b Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 22 Jul 2019 09:03:47 -0600 Subject: [PATCH 127/167] Addressed comment on commit f7faa9d issue #312. Changed the description of initialization. I also decreased the line length of the summary to make it easier to read on smaller screens. --- ST_grid.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index ab7af55a..3d95ba61 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -9,16 +9,17 @@ /********************************************************************************/ /* Summary: - This module handles the gridded mode of STEPWAT2. To accomplish this we use a grid of cells represented by the - CellType struct. The entire grid of cells can be referenced by the gridCells variable which is a 2d array of - CellTypes. To allow this module to use the same functions as non-gridded mode the CellType structs must be loaded - into the global variables using the load_cell function. As long as a cell is loaded in you can be sure that all + This module handles the gridded mode of STEPWAT2. To accomplish this we use a grid of cells + represented by the CellType struct. The entire grid of cells can be referenced by the + gridCells variable which is a 2d array of CellTypes. To allow this module to use the same + functions as non-gridded mode the CellType structs must be loaded into the global variables + using the load_cell function. As long as a cell is loaded in you can be sure that all functions will work as expected. -    In addition to all of the functionality of non-gridded mode, gridded mode has two additional features: - initialization and seed dispersal. Initialization allows the user to run some small-scale simulation to allow - the environment to stabilize before recording any statistics. Seed dispersal allows each cell to disperse seeds - to nearby cells. +    In addition to all of the functionality of non-gridded mode, gridded mode has two additional + features: initialization and seed dispersal. Initialization allows vegetation to establish + before the simulation experiments begin. Seed dispersal allows each cell to disperse seeds + to nearby cells. */ /* =================================================== */ From c6dd45bde0f9445d8d56401ea5067e32ee96a823 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 22 Jul 2019 11:19:39 -0600 Subject: [PATCH 128/167] Created seed dispersal module (.c and .h files) This commit affects issues #355, #353, #352, and #309. I moved all code associated with seed dispersal into it's own file. This way it can potentially be added to non-gridded mode, not to mention that this makes the code much more readable. In ST_grid.c: * removed declarations and definitions for _cell_dist, _init_seed_dispersal and _do_seed_dispersal. They are now defined in ST_seedDispersal.c. _init_seed_dispersal has been renamed to initDispersalParameters and _do_seed_dispersal has been renamed to disperseSeeds. In ST_grid.h: * Removed declaration of UseSeedDispersal flag. It has been moved to ST_seedDispersal.h. In ST_main.c: * added an include statement for the new .h file. In ST_species.c: * added an include statement for the new .h file. In ST_stats.c: * added an include statement for the new .h file. In ST_seedDispersal.h: * Created the file. * Declared the two functions we want to export. * Declared the UseSeedDispersal flag. In ST_seedDispersal.c: * Declared _cell_dist (formerly in ST_grid.c) * Created two new functions (_do_bulk_dispersal and _do_precise_dispersal) to be written later. * Added definition for initDispersalParameters (formerly _init_seed_dispersal) * Added definition for disperseSeeds (formerly _do_seed_dispersal) --- ST_grid.c | 294 +---------------------------------------- ST_grid.h | 2 - ST_main.c | 1 + ST_seedDispersal.c | 318 +++++++++++++++++++++++++++++++++++++++++++++ ST_seedDispersal.h | 12 ++ ST_species.c | 1 + ST_stats.c | 1 + makefile | 9 +- 8 files changed, 343 insertions(+), 295 deletions(-) create mode 100644 ST_seedDispersal.c create mode 100644 ST_seedDispersal.h diff --git a/ST_grid.c b/ST_grid.c index 3d95ba61..d4b7c05c 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -42,6 +42,7 @@ #include "sxw_funcs.h" #include "ST_initialization.h" #include "ST_progressBar.h" +#include "ST_seedDispersal.h" char sd_Sep; @@ -152,9 +153,6 @@ static void _load_cell(int row, int col, int year, Bool useAccumulators); static void _read_disturbances_in(void); static void _read_soils_in(void); static void _init_soil_layers(int cell, int isSpinup); -static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); -static void _init_seed_dispersal(void); -static void _do_seed_dispersal(void); static void _read_init_species(void); static void _read_maxrgroupspecies(void); static void _read_grid_setup(void); @@ -307,7 +305,7 @@ void runGrid(void) } /* end model run for this cell*/ } /* end model run for this row */ if (UseSeedDispersal) - _do_seed_dispersal(); + disperseSeeds(); unload_cell(); // Reset the global variables }/* end model run for this year*/ @@ -432,7 +430,7 @@ static void _init_grid_inputs(void) } if (UseSeedDispersal || initializationMethod == INIT_WITH_SEEDS) { - _init_seed_dispersal(); + initDispersalParameters(); } if(initializationMethod != INIT_WITH_NOTHING){ _read_init_species(); @@ -1331,292 +1329,6 @@ static void _init_soil_layers(int cell, int isSpinup) } */ -/* Returns the distance in meters between two cells. - To calculate the distance between cells (a,b) and (c,d) with plot width w, - input _cell_dist(a, c, b, d, w) */ -static float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) -{ - double rowDist = row1 - row2; - double colDist = col1 - col2; - - //returns the distance between the two grid cells - if (row1 == row2) - { - return (abs(colDist) * cellLen); - } - else if (col1 == col2) - { - return (abs(rowDist) * cellLen); - } - else - { // row1 != row2 && col1 != col2 - //the problem can be thought of in terms of a right triangle... - //using the pythagorean theorem: c = sqrt(a^2 + b^2)... c (the hypotenuse) represents the distance that we need. a is the distance between columns and b is the distance between rows. - return sqrt(pow(abs(colDist)*cellLen, 2.0) + pow(abs(rowDist)*cellLen, 2.0)); - } -} - -/* Derives the probabilities that a given cell will disperse seeds to any other cell. - results of this function can be accessed using - gridCells[a][b].mySeedDispersal[s].probabilityOfDispersing[c][d] - where (a,b) are the coordinates of the sender, - (b, c) are the coordinates of the reciever, - and s is the species. */ -static void _init_seed_dispersal(void) -{ - int senderRow, senderCol, recieverRow, recieverCol; - SppIndex sp; - double MAXD; /* maximum distance that a given species can disperse seeds */ - double maxRate; /* Dispersability of the seeds */ - double plotWidth; /* width of the plots (all plots are equal and square) */ - double distanceBetweenPlots; /* distance between the sender and the reciever */ - CellType* sender; - - /* sender denotes that these loops refer to the cell distributing seeds */ - for(senderRow = 0; senderCol < grid_Rows; ++senderRow){ - for(senderCol = 0; senderCol < grid_Cols; ++senderCol){ - /* Cell is loaded to ensure the ForEachSpecies loop works */ - load_cell(senderRow, senderCol); - sender = &gridCells[senderRow][senderCol]; - - /* Allocate seed dispersal information. */ - sender->mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "_init_seed_dispersal"); - - ForEachSpecies(sp){ - if (!(Species[sp]->use_me && Species[sp]->use_dispersal)){ - continue; - } - - /* These are the three values we need to calculate the probability of dispersal */ - MAXD = ((Species[sp]->sd_H * Species[sp]->sd_VW) / Species[sp]->sd_VT) / 100.0; // divided by 100 to convert from cm to m. - maxRate = -(log(0.005) / MAXD); - plotWidth = sqrt(Globals->plotsize); - - /* Allocate the probabilityOfDispersing 2d array */ - sender->mySeedDispersal[sp].probabilityOfDispersing = Mem_Calloc(grid_Rows, - sizeof(double*), "_init_seed_dispersal: probabilityOfDispersing"); - for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ - sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow] = - Mem_Calloc(grid_Cols, sizeof(double), "_init_seed_dispersal: probabilityOfDispersing[i]"); - } - - /* Loop through all possible recipients of seeds. */ - for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ - for(recieverCol = 0; recieverCol < grid_Cols; ++recieverCol){ - if(senderRow == recieverRow && senderCol == recieverCol){ - continue; // No need to calculate a probability for dispersal to itself - } - - distanceBetweenPlots = _cell_dist(senderRow, recieverRow, senderCol, recieverCol, plotWidth); - - /* The value that we are after should be saved to the sender cell. */ - sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow][recieverCol] - = (distanceBetweenPlots > MAXD) ? (0.0) : (exp(-maxRate * distanceBetweenPlots)); - } - } - } - } - } - unload_cell(); -} - -/* Perform seed dispersal durring the simulation. This is NOT functional yet. */ -static void _do_seed_dispersal(void) -{ - /************ TODO: overhaul seed dispersal. This block prevents seed dispersal from running. **************/ - printf("\nSeed dispersal during the simulation is not yet functional.\n" - "Check out GitHub for updates on this feature.\n"); - UseSeedDispersal = FALSE; - return; - /***********************************************************************************************************/ -/* - float biomass, randomN, LYPPT, presentProb, receivedProb; - int i, j, germ, sgerm, year, row, col; - SppIndex s; - CellType *cell; - - // Load the first cell so we can access seedling_estab_prob and currYear, - // which are not specific to each cell. - load_cell(0, 0); - - if (Globals->currYear == 1) - { //since we have no previous data to go off of, use the current years... - for (i = 0; i < grid_Cells; i++) - { - row = i / grid_Cols; - col = i % grid_Cols; - cell = &gridCells[row][col]; - - load_cell(row, col); - - ForEachSpecies(s) - { - if (!(Species[s]->use_me && Species[s]->use_dispersal)) - continue; - Species[s]->allow_growth = Species[s]->sd_sgerm = - 1;// since it's the first year, we have to allow growth... - if (UseDisturbances) - // RGroup[x]->killyr is the same for all x - if (1 == RGroup[0]->killyr) - Species[s]->allow_growth = 0; - cell->mySeedDispersal[s].lyppt = Env->ppt; - } - } - } - else - { - // figure out whether or not to allow growth for the current year... based upon whether the species already has plants or germination allowed this year and seeds received last year... - ForEachSpecies(s) - { - - if (!(Species[s]->use_me && Species[s]->use_dispersal)) - continue; - - // germination probability - randomN = RandUni(&grid_rng); - germ = LE(randomN, Species[s]->seedling_estab_prob); - - year = Globals->currYear - 1; - - for (i = 0; i < grid_Cells; i++) - { - row = i / grid_Cols; - col = i % grid_Cols; - cell = &gridCells[row][col]; - - load_cell(row, col); - - if (Globals->currYear <= SuperGlobals.runInitializationYears) - { - cell->mySeedDispersal[s].seeds_present = 1; - } - else if (Globals->currYear <= SuperGlobals.runInitializationYears - && cell->mySpeciesInit.shouldBeInitialized[s]) - { - cell->mySeedDispersal[s].seeds_present = 1; - } - - sgerm = (cell->mySeedDispersal[s].seeds_present - || cell->mySeedDispersal[s].seeds_received) && germ; //refers to whether the species has seeds available from the previous year and conditions are correct for germination this year - Species[s]->allow_growth = FALSE; - biomass = getSpeciesRelsize(s) - * Species[s]->mature_biomass; - - if (UseDisturbances) - { - if ((sgerm || year < RGroup[0]->killyr - || RGroup[0]->killyr <= 0 || GT(biomass, 0.0)) - && (year != RGroup[0].killyr)) - { - //commented above one condition as it was causing a bug there, next year of killing year will make - //allow_growth flag to false as year = Globals->currYear - 1 , so for example if killing year= 6 and Globals->currYear=7 then here - // year variable will be 7-1 =6 that is equal to killing year 6, so this condition (year != RGroup[0].killyr) - //will fail and allow_growth will not become TRUE, then when Globals.currYear=8 this allow_growth= FALSE will carry forward and there will no call - // to other functions. Last year size will carry forward so in final output year 7 and year 8 will - // have same output that is not correct. - Species[s]->allow_growth = TRUE; - } - - } - else if (sgerm || GT(biomass, 0.0)) - Species[s]->allow_growth = TRUE; - Species[s]->sd_sgerm = sgerm; //based upon whether we have received/produced seeds that germinated - } - } - - } - - // calculate whether or not seeds were received/produced this year, this data is used the next time the function is called - ForEachSpecies(s) - { - if (!(Species[s]->use_me && Species[s]->use_dispersal)) - continue; - - IndivType* indiv; - - // figure out which species in each cell produced seeds... - for (i = 0; i < grid_Cells; i++) - { - row = i / grid_Cols; - col = i % grid_Cols; - cell = &gridCells[row][col]; - - load_cell(row, col); - - cell->mySeedDispersal[s].seeds_present = cell->mySeedDispersal[s].seeds_received = - Species[s]->received_prob = 0; - - biomass = 0; //getting the biggest individual in the species... - ForEachIndiv(indiv, Species[s]) - if (indiv->relsize * Species[s]->mature_biomass - > biomass) - biomass = indiv->relsize - * Species[s]->mature_biomass; - - if (GE(biomass, - Species[s]->mature_biomass - * Species[s]->sd_Param1)) - { - randomN = RandUni(&grid_rng); - - LYPPT = cell->mySeedDispersal[s].lyppt; - float PPTdry = Species[s]->sd_PPTdry, PPTwet = - Species[s]->sd_PPTwet; - float Pmin = Species[s]->sd_Pmin, Pmax = - Species[s]->sd_Pmax; - - //p3 = Pmin, if LYPPT < PPTdry - //p3 = 1 - (1-Pmin) * exp(-d * (LYPPT - PPTdry)) with d = - ln((1 - Pmax)/(1 - Pmin)) / (PPTwet - PPTdry), if PPTdry <= LYPPT <= PPTwet - //p3 = Pmax, if LYPPT > PPTwet - - presentProb = 0.0; - if (PPTdry <= LYPPT && LYPPT <= PPTwet) - { - float d = -log(((1 - Pmax) / (1 - Pmin))) - / (PPTwet - PPTdry); //log is the natural log in STD c's math.h - presentProb = 1 - (1 - Pmin) * exp((-d * (LYPPT - PPTdry))); - } - else if (LYPPT < PPTdry) - presentProb = Pmin; - else if (LYPPT > PPTwet) - presentProb = Pmax; - - if (LE(randomN, presentProb)) - cell->mySeedDispersal[s].seeds_present = 1; - } - } - - // figure out which species in each cell received seeds... - for (i = 0; i < grid_Cells; i++) - { - row = i / grid_Cols; - col = i % grid_Cols; - cell = &gridCells[row][col]; - - load_cell(row, col); - - if (cell->mySeedDispersal[s].seeds_present) - continue; - receivedProb = 0; - - for (j = 0; j < cell->mySeedDispersal[s].size; j++) - if (cell->mySeedDispersal[cell->mySeedDispersal[s].cells[j]].seeds_present) - receivedProb += cell->mySeedDispersal[s].probabilityOfDispersing[j]; - - randomN = RandUni(&grid_rng); - if (LE(randomN, receivedProb) && !ZRO(receivedProb)) - cell->mySeedDispersal[s].seeds_received = 1; - else - cell->mySeedDispersal[s].seeds_received = 0; - - Species[s]->received_prob = receivedProb; - } - } - - unload_cell(); -*/ -} - /* Read the species initialization CSV. This function only needs to be called if the user requests initialization.*/ static void _read_init_species(void) { diff --git a/ST_grid.h b/ST_grid.h index 63b554ae..bbcd8aed 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -155,8 +155,6 @@ int grid_Cols; char *grid_files[N_GRID_FILES]; /* Array of directory names. Use the Directory_Indices enum to pick the correct index. */ char *grid_directories[N_GRID_DIRECTORIES]; -/* TRUE if we should run seed dispersal between years during the main simulation. */ -Bool UseSeedDispersal; /**************************** Exported Functions **********************************/ diff --git a/ST_main.c b/ST_main.c index e9d09975..eb92461b 100644 --- a/ST_main.c +++ b/ST_main.c @@ -35,6 +35,7 @@ #include "sw_src/rands.h" #include "ST_initialization.h" #include "ST_progressBar.h" +#include "ST_seedDispersal.h" extern SXW_t* SXW; extern Bool prepare_IterationSummary; // defined in `SOILWAT2/SW_Output.c` diff --git a/ST_seedDispersal.c b/ST_seedDispersal.c new file mode 100644 index 00000000..c90ac9de --- /dev/null +++ b/ST_seedDispersal.c @@ -0,0 +1,318 @@ + +#include "ST_globals.h" +#include "ST_defines.h" +#include "ST_grid.h" +#include "ST_seedDispersal.h" +#include "rands.h" +#include "myMemory.h" + +int _do_bulk_dispersal(SppIndex sp); +void _do_precise_dispersal(int leftoverSeeds, SppIndex sp); +float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); + +pcg32_random_t dispersal_rng; // Used exclusively in this file + +/* Derives the probabilities that a given cell will disperse seeds to any other cell. + results of this function can be accessed using + gridCells[a][b].mySeedDispersal[s].probabilityOfDispersing[c][d] + where (a,b) are the coordinates of the sender, + (b, c) are the coordinates of the reciever, + and s is the species. */ +void initDispersalParameters(void) +{ + int senderRow, senderCol, recieverRow, recieverCol; + SppIndex sp; + double MAXD; /* maximum distance that a given species can disperse seeds */ + double maxRate; /* Dispersability of the seeds */ + double plotWidth; /* width of the plots (all plots are equal and square) */ + double distanceBetweenPlots; /* distance between the sender and the reciever */ + CellType* sender; + + RandSeed(SuperGlobals.randseed, &dispersal_rng); + + /* sender denotes that these loops refer to the cell distributing seeds */ + for(senderRow = 0; senderCol < grid_Rows; ++senderRow){ + for(senderCol = 0; senderCol < grid_Cols; ++senderCol){ + /* Cell is loaded to ensure the ForEachSpecies loop works */ + load_cell(senderRow, senderCol); + sender = &gridCells[senderRow][senderCol]; + + /* Allocate seed dispersal information. */ + sender->mySeedDispersal = Mem_Calloc(MAX_SPECIES, sizeof(Grid_SD_St), "initDispersalParameters"); + + ForEachSpecies(sp){ + if (!(Species[sp]->use_me && Species[sp]->use_dispersal)){ + continue; + } + + /* These are the three values we need to calculate the probability of dispersal */ + MAXD = ((Species[sp]->sd_H * Species[sp]->sd_VW) / Species[sp]->sd_VT) / 100.0; // divided by 100 to convert from cm to m. + maxRate = -(log(0.005) / MAXD); + plotWidth = sqrt(Globals->plotsize); + + /* Allocate the probabilityOfDispersing 2d array */ + sender->mySeedDispersal[sp].probabilityOfDispersing = Mem_Calloc(grid_Rows, + sizeof(double*), "initDispersalParameters: probabilityOfDispersing"); + for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ + sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow] = + Mem_Calloc(grid_Cols, sizeof(double), "initDispersalParameters: probabilityOfDispersing[i]"); + } + + /* Loop through all possible recipients of seeds. */ + for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ + for(recieverCol = 0; recieverCol < grid_Cols; ++recieverCol){ + if(senderRow == recieverRow && senderCol == recieverCol){ + continue; // No need to calculate a probability for dispersal to itself + } + + distanceBetweenPlots = _cell_dist(senderRow, recieverRow, senderCol, recieverCol, plotWidth); + + /* The value that we are after should be saved to the sender cell. */ + sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow][recieverCol] + = (distanceBetweenPlots > MAXD) ? (0.0) : (exp(-maxRate * distanceBetweenPlots)); + } + } + } + } + } + unload_cell(); +} + +/* Perform seed dispersal durring the simulation. This is NOT functional yet. */ +void disperseSeeds(void) +{ + /************ TODO: overhaul seed dispersal. This block prevents seed dispersal from running. **************/ + printf("\nSeed dispersal during the simulation is not yet functional.\n" + "Check out GitHub for updates on this feature.\n"); + UseSeedDispersal = FALSE; + return; + /***********************************************************************************************************/ + +/* TODO: discuss this implementation: + SppIndex sp; + ForEachSpecies(sp){ + int leftovers = _do_bulk_dispersal(sp); + _do_precise_dispersal(leftovers, sp); + } +*/ + +/* + float biomass, randomN, LYPPT, presentProb, receivedProb; + int i, j, germ, sgerm, year, row, col; + SppIndex s; + CellType *cell; + + // Load the first cell so we can access seedling_estab_prob and currYear, + // which are not specific to each cell. + load_cell(0, 0); + + if (Globals->currYear == 1) + { //since we have no previous data to go off of, use the current years... + for (i = 0; i < grid_Cells; i++) + { + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); + + ForEachSpecies(s) + { + if (!(Species[s]->use_me && Species[s]->use_dispersal)) + continue; + Species[s]->allow_growth = Species[s]->sd_sgerm = + 1;// since it's the first year, we have to allow growth... + if (UseDisturbances) + // RGroup[x]->killyr is the same for all x + if (1 == RGroup[0]->killyr) + Species[s]->allow_growth = 0; + cell->mySeedDispersal[s].lyppt = Env->ppt; + } + } + } + else + { + // figure out whether or not to allow growth for the current year... based upon whether the species already has plants or germination allowed this year and seeds received last year... + ForEachSpecies(s) + { + + if (!(Species[s]->use_me && Species[s]->use_dispersal)) + continue; + + // germination probability + randomN = RandUni(&grid_rng); + germ = LE(randomN, Species[s]->seedling_estab_prob); + + year = Globals->currYear - 1; + + for (i = 0; i < grid_Cells; i++) + { + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); + + if (Globals->currYear <= SuperGlobals.runInitializationYears) + { + cell->mySeedDispersal[s].seeds_present = 1; + } + else if (Globals->currYear <= SuperGlobals.runInitializationYears + && cell->mySpeciesInit.shouldBeInitialized[s]) + { + cell->mySeedDispersal[s].seeds_present = 1; + } + + sgerm = (cell->mySeedDispersal[s].seeds_present + || cell->mySeedDispersal[s].seeds_received) && germ; //refers to whether the species has seeds available from the previous year and conditions are correct for germination this year + Species[s]->allow_growth = FALSE; + biomass = getSpeciesRelsize(s) + * Species[s]->mature_biomass; + + if (UseDisturbances) + { + if ((sgerm || year < RGroup[0]->killyr + || RGroup[0]->killyr <= 0 || GT(biomass, 0.0)) + && (year != RGroup[0].killyr)) + { + //commented above one condition as it was causing a bug there, next year of killing year will make + //allow_growth flag to false as year = Globals->currYear - 1 , so for example if killing year= 6 and Globals->currYear=7 then here + // year variable will be 7-1 =6 that is equal to killing year 6, so this condition (year != RGroup[0].killyr) + //will fail and allow_growth will not become TRUE, then when Globals.currYear=8 this allow_growth= FALSE will carry forward and there will no call + // to other functions. Last year size will carry forward so in final output year 7 and year 8 will + // have same output that is not correct. + Species[s]->allow_growth = TRUE; + } + + } + else if (sgerm || GT(biomass, 0.0)) + Species[s]->allow_growth = TRUE; + Species[s]->sd_sgerm = sgerm; //based upon whether we have received/produced seeds that germinated + } + } + + } + + // calculate whether or not seeds were received/produced this year, this data is used the next time the function is called + ForEachSpecies(s) + { + if (!(Species[s]->use_me && Species[s]->use_dispersal)) + continue; + + IndivType* indiv; + + // figure out which species in each cell produced seeds... + for (i = 0; i < grid_Cells; i++) + { + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); + + cell->mySeedDispersal[s].seeds_present = cell->mySeedDispersal[s].seeds_received = + Species[s]->received_prob = 0; + + biomass = 0; //getting the biggest individual in the species... + ForEachIndiv(indiv, Species[s]) + if (indiv->relsize * Species[s]->mature_biomass + > biomass) + biomass = indiv->relsize + * Species[s]->mature_biomass; + + if (GE(biomass, + Species[s]->mature_biomass + * Species[s]->sd_Param1)) + { + randomN = RandUni(&grid_rng); + + LYPPT = cell->mySeedDispersal[s].lyppt; + float PPTdry = Species[s]->sd_PPTdry, PPTwet = + Species[s]->sd_PPTwet; + float Pmin = Species[s]->sd_Pmin, Pmax = + Species[s]->sd_Pmax; + + //p3 = Pmin, if LYPPT < PPTdry + //p3 = 1 - (1-Pmin) * exp(-d * (LYPPT - PPTdry)) with d = - ln((1 - Pmax)/(1 - Pmin)) / (PPTwet - PPTdry), if PPTdry <= LYPPT <= PPTwet + //p3 = Pmax, if LYPPT > PPTwet + + presentProb = 0.0; + if (PPTdry <= LYPPT && LYPPT <= PPTwet) + { + float d = -log(((1 - Pmax) / (1 - Pmin))) + / (PPTwet - PPTdry); //log is the natural log in STD c's math.h + presentProb = 1 - (1 - Pmin) * exp((-d * (LYPPT - PPTdry))); + } + else if (LYPPT < PPTdry) + presentProb = Pmin; + else if (LYPPT > PPTwet) + presentProb = Pmax; + + if (LE(randomN, presentProb)) + cell->mySeedDispersal[s].seeds_present = 1; + } + } + + // figure out which species in each cell received seeds... + for (i = 0; i < grid_Cells; i++) + { + row = i / grid_Cols; + col = i % grid_Cols; + cell = &gridCells[row][col]; + + load_cell(row, col); + + if (cell->mySeedDispersal[s].seeds_present) + continue; + receivedProb = 0; + + for (j = 0; j < cell->mySeedDispersal[s].size; j++) + if (cell->mySeedDispersal[cell->mySeedDispersal[s].cells[j]].seeds_present) + receivedProb += cell->mySeedDispersal[s].probabilityOfDispersing[j]; + + randomN = RandUni(&grid_rng); + if (LE(randomN, receivedProb) && !ZRO(receivedProb)) + cell->mySeedDispersal[s].seeds_received = 1; + else + cell->mySeedDispersal[s].seeds_received = 0; + + Species[s]->received_prob = receivedProb; + } + } + + unload_cell(); +*/ +} + +int _do_bulk_dispersal(SppIndex sp){ + return 0; +} + +void _do_precise_dispersal(int leftoverSeeds, SppIndex sp){ + return; +} + +/* Returns the distance in meters between two cells. + To calculate the distance between cells (a,b) and (c,d) with plot width w, + input _cell_dist(a, c, b, d, w) */ +float _cell_dist(int row1, int row2, int col1, int col2, float cellLen) +{ + double rowDist = row1 - row2; + double colDist = col1 - col2; + + //returns the distance between the two grid cells + if (row1 == row2) + { + return (abs(colDist) * cellLen); + } + else if (col1 == col2) + { + return (abs(rowDist) * cellLen); + } + else + { // row1 != row2 && col1 != col2 + //the problem can be thought of in terms of a right triangle... + //using the pythagorean theorem: c = sqrt(a^2 + b^2)... c (the hypotenuse) represents the distance that we need. a is the distance between columns and b is the distance between rows. + return sqrt(pow(abs(colDist)*cellLen, 2.0) + pow(abs(rowDist)*cellLen, 2.0)); + } +} \ No newline at end of file diff --git a/ST_seedDispersal.h b/ST_seedDispersal.h new file mode 100644 index 00000000..c0b0e55f --- /dev/null +++ b/ST_seedDispersal.h @@ -0,0 +1,12 @@ + + +#ifndef SEEDDISPERSAL_H +#define SEEDDISPERSAL_H + +/* TRUE if we should run seed dispersal between years during the main simulation. */ +Bool UseSeedDispersal; + +void disperseSeeds(void); +void initDispersalParameters(void); + +#endif \ No newline at end of file diff --git a/ST_species.c b/ST_species.c index 92796940..660a1724 100644 --- a/ST_species.c +++ b/ST_species.c @@ -24,6 +24,7 @@ #include "rands.h" #include "sw_src/pcg/pcg_basic.h" #include "ST_initialization.h" +#include "ST_seedDispersal.h" extern pcg32_random_t species_rng; diff --git a/ST_stats.c b/ST_stats.c index fa65fc16..f6767477 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -28,6 +28,7 @@ #include "ST_structs.h" #include "ST_stats.h" #include "ST_initialization.h" +#include "ST_seedDispersal.h" #include "sxw.h" extern SW_SITE SW_Site; diff --git a/makefile b/makefile index 7a00caf8..f0344ff6 100644 --- a/makefile +++ b/makefile @@ -57,7 +57,8 @@ SRCS =\ $(Src)/ST_grid.c\ $(Src)/ST_sql.c\ $(Src)/ST_initialization.c\ - $(Src)/ST_progressBar.c + $(Src)/ST_progressBar.c\ + $(Src)/ST_seedDispersal.c #$(Src)/sxw_tester.c EXOBJS =\ @@ -102,7 +103,8 @@ EXOBJS =\ $(oDir)/ST_grid.o\ $(oDir)/ST_sql.o\ $(oDir)/ST_initialization.o\ - $(oDir)/ST_progressBar.o + $(oDir)/ST_progressBar.o\ + $(oDir)/ST_seedDispersal.o #$(oDir)/sxw_tester.o ALLOBJS = $(EXOBJS) @@ -363,4 +365,7 @@ $(oDir)/ST_initialization.o: ST_initialization.c $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< $(oDir)/ST_progressBar.o: ST_progressBar.c + $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< + +$(oDir)/ST_seedDispersal.o: ST_seedDispersal.c $(CC) $(C_FLAGS) $(CPPFLAGS) $(incDirs) -c -o $@ $< \ No newline at end of file From b25a9ba2449a5883c5f0b02bbb8d304cdaf608a3 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 22 Jul 2019 11:24:55 -0600 Subject: [PATCH 129/167] Added some documentation to the ST_seedDispersal files. I forgot to add comments at the top of the files before pushing commit c6dd45b. --- ST_seedDispersal.c | 8 +++++++- ST_seedDispersal.h | 7 ++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/ST_seedDispersal.c b/ST_seedDispersal.c index c90ac9de..7bed235f 100644 --- a/ST_seedDispersal.c +++ b/ST_seedDispersal.c @@ -1,3 +1,8 @@ +/********************************************************************************* + * ST_seedDispersal.c + * + * Contains definitions for all functions belonging to the seed dispersal module. + *********************************************************************************/ #include "ST_globals.h" #include "ST_defines.h" @@ -10,7 +15,8 @@ int _do_bulk_dispersal(SppIndex sp); void _do_precise_dispersal(int leftoverSeeds, SppIndex sp); float _cell_dist(int row1, int row2, int col1, int col2, float cellLen); -pcg32_random_t dispersal_rng; // Used exclusively in this file +/* RNG unique to seed dispersal. */ +pcg32_random_t dispersal_rng; /* Derives the probabilities that a given cell will disperse seeds to any other cell. results of this function can be accessed using diff --git a/ST_seedDispersal.h b/ST_seedDispersal.h index c0b0e55f..a729e98b 100644 --- a/ST_seedDispersal.h +++ b/ST_seedDispersal.h @@ -1,4 +1,9 @@ - +/********************************************************************************* + * ST_seedDispersal.h + * + * Contains declarations for exported functions from the seed dispersal module. + * It also contains the declaration for the UseSeedDispersal flag. + *********************************************************************************/ #ifndef SEEDDISPERSAL_H #define SEEDDISPERSAL_H From cb94da8f4044ee0fdbc3acafd7fad2f3754aa93e Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 22 Jul 2019 11:37:59 -0600 Subject: [PATCH 130/167] Addressing comments on commit c23e288 I also moved the seed dispersal struct to ST_seedDispersal.h. --- ST_grid.c | 4 ++-- ST_grid.h | 14 +------------- ST_seedDispersal.c | 18 +++++++++--------- ST_seedDispersal.h | 16 +++++++++++++++- 4 files changed, 27 insertions(+), 25 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index d4b7c05c..2ce46e5c 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -749,9 +749,9 @@ void free_grid_memory(void) if(UseSeedDispersal) { ForEachSpecies(s) { for(sd_i = 0; sd_i < grid_Rows; ++sd_i){ - Mem_Free(gridCells[i][j].mySeedDispersal[s].probabilityOfDispersing[sd_i]); + Mem_Free(gridCells[i][j].mySeedDispersal[s].dispersalProb[sd_i]); } - Mem_Free(gridCells[i][j].mySeedDispersal[s].probabilityOfDispersing); + Mem_Free(gridCells[i][j].mySeedDispersal[s].dispersalProb); } } unload_cell(); diff --git a/ST_grid.h b/ST_grid.h index bbcd8aed..65954ecb 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -20,6 +20,7 @@ #include "SW_VegProd.h" #include "SW_Model.h" #include "SW_Weather.h" +#include "ST_seedDispersal.h" /*********************** Grid Structures ****************************/ // represents a single soil layer @@ -42,19 +43,6 @@ struct Soil_st Grid_Soil_Lyr* lyr; }typedef SoilType; -/* Holds seed dispersal information. */ -struct _grid_sd_struct -{ //for seed dispersal - /* TRUE if seeds are present. */ - Bool seeds_present; - /* TRUE if this cell has recieved any seeds. */ - Bool seeds_received; - /* probabilityOfDispersing[row][col] = the probability that this cell will disperse seeds to cell (row,col). */ - double **probabilityOfDispersing; - /* Last year's precipitation. */ - double lyppt; -}typedef Grid_SD_St; - /* Initialization information. */ struct _grid_init_species_st { diff --git a/ST_seedDispersal.c b/ST_seedDispersal.c index 7bed235f..0aa74c0c 100644 --- a/ST_seedDispersal.c +++ b/ST_seedDispersal.c @@ -20,7 +20,7 @@ pcg32_random_t dispersal_rng; /* Derives the probabilities that a given cell will disperse seeds to any other cell. results of this function can be accessed using - gridCells[a][b].mySeedDispersal[s].probabilityOfDispersing[c][d] + gridCells[a][b].mySeedDispersal[s].dispersalProb[c][d] where (a,b) are the coordinates of the sender, (b, c) are the coordinates of the reciever, and s is the species. */ @@ -28,7 +28,7 @@ void initDispersalParameters(void) { int senderRow, senderCol, recieverRow, recieverCol; SppIndex sp; - double MAXD; /* maximum distance that a given species can disperse seeds */ + double MAXD; /* maximum seed dispersal distance for a given species */ double maxRate; /* Dispersability of the seeds */ double plotWidth; /* width of the plots (all plots are equal and square) */ double distanceBetweenPlots; /* distance between the sender and the reciever */ @@ -56,12 +56,12 @@ void initDispersalParameters(void) maxRate = -(log(0.005) / MAXD); plotWidth = sqrt(Globals->plotsize); - /* Allocate the probabilityOfDispersing 2d array */ - sender->mySeedDispersal[sp].probabilityOfDispersing = Mem_Calloc(grid_Rows, - sizeof(double*), "initDispersalParameters: probabilityOfDispersing"); + /* Allocate the dispersalProb 2d array */ + sender->mySeedDispersal[sp].dispersalProb = Mem_Calloc(grid_Rows, + sizeof(double*), "initDispersalParameters: dispersalProb"); for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ - sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow] = - Mem_Calloc(grid_Cols, sizeof(double), "initDispersalParameters: probabilityOfDispersing[i]"); + sender->mySeedDispersal[sp].dispersalProb[recieverRow] = + Mem_Calloc(grid_Cols, sizeof(double), "initDispersalParameters: dispersalProb[i]"); } /* Loop through all possible recipients of seeds. */ @@ -74,7 +74,7 @@ void initDispersalParameters(void) distanceBetweenPlots = _cell_dist(senderRow, recieverRow, senderCol, recieverCol, plotWidth); /* The value that we are after should be saved to the sender cell. */ - sender->mySeedDispersal[sp].probabilityOfDispersing[recieverRow][recieverCol] + sender->mySeedDispersal[sp].dispersalProb[recieverRow][recieverCol] = (distanceBetweenPlots > MAXD) ? (0.0) : (exp(-maxRate * distanceBetweenPlots)); } } @@ -274,7 +274,7 @@ void disperseSeeds(void) for (j = 0; j < cell->mySeedDispersal[s].size; j++) if (cell->mySeedDispersal[cell->mySeedDispersal[s].cells[j]].seeds_present) - receivedProb += cell->mySeedDispersal[s].probabilityOfDispersing[j]; + receivedProb += cell->mySeedDispersal[s].dispersalProb[j]; randomN = RandUni(&grid_rng); if (LE(randomN, receivedProb) && !ZRO(receivedProb)) diff --git a/ST_seedDispersal.h b/ST_seedDispersal.h index a729e98b..0e1b84d1 100644 --- a/ST_seedDispersal.h +++ b/ST_seedDispersal.h @@ -2,12 +2,26 @@ * ST_seedDispersal.h * * Contains declarations for exported functions from the seed dispersal module. - * It also contains the declaration for the UseSeedDispersal flag. + * It also contains the declaration for the UseSeedDispersal flag and the + * seed dispersal struct. *********************************************************************************/ #ifndef SEEDDISPERSAL_H #define SEEDDISPERSAL_H +/* Holds seed dispersal information. */ +struct _grid_sd_struct +{ //for seed dispersal + /* TRUE if seeds are present. */ + Bool seeds_present; + /* TRUE if this cell has recieved any seeds. */ + Bool seeds_received; + /* dispersalProb[row][col] = the probability that this cell will disperse seeds to cell (row,col). */ + double **dispersalProb; + /* Last year's precipitation. */ + double lyppt; +}typedef Grid_SD_St; + /* TRUE if we should run seed dispersal between years during the main simulation. */ Bool UseSeedDispersal; From 2cce478b63d9e1d306bac23dca9a16593906efee Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 24 Jul 2019 08:34:39 -0600 Subject: [PATCH 131/167] Sealed additional memory leaks (issue #322) There were two sources of memory leaks that I found using valgrind. * All arrays from SXWResources were not completely freed. * The accumulators were never freed. I took take of both of these sources. --- ST_grid.c | 2 ++ sxw.c | 23 ++++++++++++----------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 2ce46e5c..56918597 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -133,6 +133,7 @@ void stat_Output_Seed_Dispersal(const char * filename, const char sep, void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); +void stat_free_mem(void); void _make_header_with_std( char *buf); /* Functions from sxw.c */ @@ -745,6 +746,7 @@ void free_grid_memory(void) load_cell(i,j); deallocate_Globals(TRUE); free_all_sxw_memory(); + stat_free_mem(); // If seed dispersal is on we allocated additional memory if(UseSeedDispersal) { ForEachSpecies(s) { diff --git a/sxw.c b/sxw.c index d03f2dda..ea8f4c23 100644 --- a/sxw.c +++ b/sxw.c @@ -1128,17 +1128,6 @@ void free_all_sxw_memory( void ) { Mem_Free(transp_window->SoS_array); Mem_Free(transp_window); - /* Free SXWResources memory */ - Mem_Free(SXWResources->_roots_max); - Mem_Free(SXWResources->_rootsXphen); - Mem_Free(SXWResources->_roots_active); - Mem_Free(SXWResources->_roots_active_rel); - Mem_Free(SXWResources->_roots_active_sum); - Mem_Free(SXWResources->_phen); - Mem_Free(SXWResources->_prod_bmass); - Mem_Free(SXWResources->_prod_pctlive); - Mem_Free(SXWResources); - /* Free SXW */ Mem_Free(SXW->f_roots); Mem_Free(SXW->f_phen); @@ -1151,6 +1140,18 @@ void free_all_sxw_memory( void ) { } Mem_Free(SXW->swc); Mem_Free(SXW); + + Mem_Free(SXWResources->_phen); + Mem_Free(SXWResources->_prod_bmass); + Mem_Free(SXWResources->_prod_pctlive); + Mem_Free(SXWResources->_resource_cur); + Mem_Free(SXWResources->_resource_pr); + Mem_Free(SXWResources->_roots_active); + Mem_Free(SXWResources->_roots_active_rel); + Mem_Free(SXWResources->_roots_active_sum); + Mem_Free(SXWResources->_roots_max); + Mem_Free(SXWResources->_rootsXphen); + Mem_Free(SXWResources); } /***********************************************************/ From 0485b900ecf70e60a555263565cf1588dfb98681 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sat, 27 Jul 2019 16:07:33 -0600 Subject: [PATCH 132/167] Added input parameter for individual cell output (issue #360) writeIndividualFiles, declared in ST_grid.h, determines if a bmass, mort, and seed dispersal file is written for each individual cell. The parameter is in grid_setup.in. --- ST_grid.c | 28 +++++++++++-------- ST_grid.h | 2 ++ .../Grid_Inputs/grid_setup.in | 3 +- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 56918597..010b2ca8 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -356,13 +356,15 @@ void runGrid(void) parm_SetName(fileMort, F_MortAvg); parm_SetName(fileBMass, F_BMassAvg); - if (MortFlags.summary) + if (MortFlags.summary && writeIndividualFiles){ stat_Output_AllMorts(); - if (BmassFlags.summary) + } + if (BmassFlags.summary && writeIndividualFiles){ stat_Output_AllBmass(); - if (UseSeedDispersal && sd_DoOutput) - stat_Output_Seed_Dispersal(fileReceivedProb, sd_Sep, - sd_MakeHeader); + } + if (UseSeedDispersal && sd_DoOutput && writeIndividualFiles){ + stat_Output_Seed_Dispersal(fileReceivedProb, sd_Sep, sd_MakeHeader); + } } } unload_cell(); // Reset the global variables @@ -1490,12 +1492,16 @@ static void _read_grid_setup(void) "Invalid grid setup file (Initialization line wrong. Valid options are \"spinup\", \"seeds\", or \"none\")"); } - if(initializationMethod != INIT_WITH_NOTHING){ - GetALine(f, buf); - i = sscanf(buf, "%hd", &SuperGlobals.runInitializationYears); - if(i < 1){ - LogError(logfp, LOGFATAL, "Invalid grid setup file (Initialization years line wrong)"); - } + GetALine(f, buf); + i = sscanf(buf, "%hd", &SuperGlobals.runInitializationYears); + if(i < 1){ + LogError(logfp, LOGFATAL, "Invalid grid setup file (Initialization years line wrong)"); + } + + GetALine(f, buf); + i = sscanf(buf, "%hd", &writeIndividualFiles); + if(i < 1){ + LogError(logfp, LOGFATAL, "Invalid grid setup file (Individual output line wrong)"); } GetALine(f, buf); diff --git a/ST_grid.h b/ST_grid.h index 65954ecb..5bd1ee37 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -143,6 +143,8 @@ int grid_Cols; char *grid_files[N_GRID_FILES]; /* Array of directory names. Use the Directory_Indices enum to pick the correct index. */ char *grid_directories[N_GRID_DIRECTORIES]; +/* TRUE if every cell should write its own summary file. */ +Bool writeIndividualFiles; /**************************** Exported Functions **********************************/ diff --git a/testing.sagebrush.master/Grid_Inputs/grid_setup.in b/testing.sagebrush.master/Grid_Inputs/grid_setup.in index 55ff2d1f..f3685ab3 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_setup.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_setup.in @@ -5,7 +5,8 @@ 1 # use soils csv file (0 or 1)... 0 means no, 1 means yes 0 # use seed dispersal (0 or 1)... 0 means no, 1 means yes spinup # Initialization method. Options are "spinup", "seeds", or "none" -300 # Number of years to perform initialization (whichever method you choose). +300 # Number of years to perform initialization (whichever method you choose). +1 # Write separate output files for each cell. #SEED DISPERSAL OUTPUTS 1 # output seed dispersal summary file? 1 means yes, 0 means no From d33d857ba2f00173978a319a0352889321fd5749 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Sun, 28 Jul 2019 16:34:24 -0600 Subject: [PATCH 133/167] Hard-coded UseSeedDispersal to FALSE See issue #362 for an explanation of why this is necessary. --- ST_grid.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ST_grid.c b/ST_grid.c index 010b2ca8..2938b125 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1476,6 +1476,13 @@ static void _read_grid_setup(void) "Invalid grid setup file (seed dispersal line wrong)"); UseSeedDispersal = itob(j); + // TODO: Remove this block once seed dispersal works. + if(UseSeedDispersal){ + printf("\nSeed dispersal during the simulation is not yet functional.\n" + "Check out GitHub for updates on this feature.\n"); + UseSeedDispersal = FALSE; + } + GetALine(f, buf); i = sscanf(buf, "%s", initializationType); if(i < 1){ From bfc8776cd10ab1b258672116b29f72dea646e176 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 29 Jul 2019 10:57:06 -0600 Subject: [PATCH 134/167] Added function to calculate average mortality (issue #361) This new function averages mortality values across all cells. --- ST_grid.c | 135 +++++++++++++++++++++++++++++- ST_grid.h | 1 + testing.sagebrush.master/files.in | 1 + 3 files changed, 134 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 2938b125..18c1dcd7 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -128,6 +128,7 @@ void stat_Collect_SMort(void); void stat_Output_AllMorts(void); void stat_Output_AllBmass(void); void Output_AllCellAvgBmass(const char * filename); +void Output_AllCellAvgMort(const char* fileName); void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool makeHeader); void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, @@ -370,11 +371,15 @@ void runGrid(void) unload_cell(); // Reset the global variables //Here creating grid cells avg values output file - char fileBMassCellAvg[1024]; - sprintf(fileBMassCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_BMASSCELLAVG]); + char fileBMassCellAvg[1024], fileMortCellAvg[1024]; if (BmassFlags.summary){ + sprintf(fileBMassCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_BMASSCELLAVG]); Output_AllCellAvgBmass(fileBMassCellAvg); } + if (MortFlags.summary){ + sprintf(fileMortCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_MORTCELLAVG]); + Output_AllCellAvgMort(fileMortCellAvg); + } free_grid_memory(); // Free our allocated memory since we do not need it anymore parm_free_memory(); // Free memory allocated to the _files array in ST_params.c @@ -1646,7 +1651,7 @@ void Output_AllCellAvgBmass(const char * filename){ } // End for each column } // End for each row - /* ---------------- Average all accumulators ---------------- */ + /* ------------------ Average all accumulators ----------------- */ dist /= grid_Cells; wildfire /= grid_Cells; ForEachGroup(rg){ @@ -1720,4 +1725,128 @@ void Output_AllCellAvgBmass(const char * filename){ unload_cell(); fclose(file); // Close the file +} + +/* Output the average mortality across cells. */ +void Output_AllCellAvgMort(const char* fileName){ + if (!MortFlags.summary) return; + + /* We need a cell loaded for the ForEach loops. */ + load_cell(0,0); + + FILE *file; + IntS age; + GrpIndex rg; + SppIndex sp; + char sep = MortFlags.sep; + + int row, col, nobs = 0; + + float Gestab[SuperGlobals.max_rgroups], + Sestab[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups], + Gmort[SuperGlobals.max_rgroups][Globals->Max_Age], + Smort[SuperGlobals.max_spp_per_grp * SuperGlobals.max_rgroups][Globals->Max_Age]; + + file = OpenFile( fileName, "w"); + + /* --------------------- Initialize values ----------------------- */ + ForEachSpecies(sp){ + Sestab[sp] = 0; + for(age = 0; age < Globals->Max_Age; ++age){ + Smort[sp][age] = 0; + } + } + ForEachGroup(rg){ + Gestab[rg] = 0; + for(age = 0; age < Globals->Max_Age; ++age){ + Gmort[rg][age] = 0; + } + } + /* ------------------ End initializing values -------------------- */ + + /* ----------------------------- Calculate averaged values ------------------------------------- */ + for(row = 0; row < grid_Rows; row++){ + for(col = 0; col < grid_Cols; col++){ + nobs++; + if (MortFlags.group) { + ForEachGroup(rg){ + Gestab[rg] = get_running_mean(nobs, Gestab[rg], gridCells[row][col]._Gestab[rg].s[0].ave); + } + } + + if (MortFlags.species) { + ForEachSpecies(sp){ + Sestab[sp] = get_running_mean(nobs, Sestab[sp], gridCells[row][col]._Sestab[sp].s[0].ave); + } + } + + /* print one line of kill frequencies per age */ + for(age=0; age < Globals->Max_Age; age++) { + if (MortFlags.group) { + ForEachGroup(rg){ + Gmort[rg][age] = get_running_mean(nobs, Gmort[rg][age], gridCells[row][col]._Gmort[rg].s[age].ave); + } + } + if (MortFlags.species) { + ForEachSpecies(sp) { + Smort[sp][age] = get_running_mean(nobs, Smort[sp][age], gridCells[row][col]._Smort[sp].s[age].ave); + } + } + } + } + } + /* --------------------------- End calculating averaged values -------------------------------- */ + + /* --------------------- Print header ------------------ */ + fprintf(file, "Age"); + if (MortFlags.group) { + ForEachGroup(rg) { + fprintf(file,"%c%s", sep, RGroup[rg]->name); + } + } + if (MortFlags.species) { + ForEachSpecies(sp) + fprintf(file,"%c%s", sep, Species[sp]->name); + } + fprintf(file,"\n"); + fprintf(file,"Estabs"); + /* ---------------------- End header ------------------- */ + + /* --------------------- Print values ------------------ */ + if(MortFlags.group){ + ForEachGroup(rg){ + fprintf(file,"%c%5.1f", sep, Gestab[rg]); + } + } + + if (MortFlags.species) { + ForEachSpecies(sp){ + fprintf(file,"%c%5.1f", sep, Sestab[sp]); + } + } + + fprintf(file,"\n"); + + /* print one line of kill frequencies per age */ + for(age=0; age < Globals->Max_Age; age++) { + fprintf(file,"%d", age+1); + if (MortFlags.group) { + ForEachGroup(rg) + fprintf(file,"%c%5.1f", sep, ( age < GrpMaxAge(rg) ) + ? Gmort[rg][age] + : 0.); + } + if (MortFlags.species) { + ForEachSpecies(sp) { + fprintf(file,"%c%5.1f", sep, ( age < SppMaxAge(sp)) + ? Smort[sp][age] + : 0.); + } + } + fprintf(file,"\n"); + } + /* ----------------- End printing values --------------- */ + + unload_cell(); + CloseFile(&file); } \ No newline at end of file diff --git a/ST_grid.h b/ST_grid.h index 5bd1ee37..f2aeb8cd 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -126,6 +126,7 @@ typedef enum GRID_FILE_PREFIX_MORTAVG, GRID_FILE_PREFIX_RECEIVEDPROB, GRID_FILE_PREFIX_BMASSCELLAVG, + GRID_FILE_PREFIX_MORTCELLAVG, /* Automatically generate number of files since enums start at 0 */ N_GRID_FILES diff --git a/testing.sagebrush.master/files.in b/testing.sagebrush.master/files.in index ac708fd7..f87545b5 100644 --- a/testing.sagebrush.master/files.in +++ b/testing.sagebrush.master/files.in @@ -16,3 +16,4 @@ Output/g_bmassavg # name of the prefix given to the biomass output files Output/g_mortavg # name of the prefix given to the mortuary output files Output/g_receivedprob # name of the prefix given to the seed disperal received probability output files Output/g_bmass_cell_avg # name of the prefix given to the biomass grid cell avg output files +Output/g_mort_cell_avg # name of the prefix given to the mortality grid cell avg output files From a898b360d81893b3017c1d84158417706424e2be Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 30 Jul 2019 11:55:39 -0600 Subject: [PATCH 135/167] Resolved some compiler warnings These warnings showed up on my Ubuntu machine: * SXW was externed twice; once in ST_main and once in an include statement in ST_main. * Reading in Bools using sscanf was giving warnings when using "%d" so I changed them to "%u" and the warning went away. * Env_Generate was declared twice in ST_initialization.c. Once in the file and once in an include statement. --- ST_grid.c | 4 ++-- ST_initialization.c | 3 +-- ST_main.c | 1 - 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 18c1dcd7..8c411c04 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -999,7 +999,7 @@ static void _read_disturbances_in(void) break; ForEachGroup(rg) { - num = sscanf(buf, "%d,%d,%d,%d,%hu,%hu,%f,%hu,%hu,%hu,%f", &cell, + num = sscanf(buf, "%d,%u,%u,%u,%hu,%hu,%f,%hu,%hu,%hu,%f", &cell, &Globals->pat.use, &Globals->mound.use, &Globals->burrow.use, &RGroup[rg]->killyr, &RGroup[rg]->killfreq_startyr, &RGroup[rg]->killfreq, &RGroup[rg]->extirp, &RGroup[rg]->grazingfrq, &RGroup[rg]->grazingfreq_startyr, &RGroup[rg]->ignition); @@ -1511,7 +1511,7 @@ static void _read_grid_setup(void) } GetALine(f, buf); - i = sscanf(buf, "%hd", &writeIndividualFiles); + i = sscanf(buf, "%u", &writeIndividualFiles); if(i < 1){ LogError(logfp, LOGFATAL, "Invalid grid setup file (Individual output line wrong)"); } diff --git a/ST_initialization.c b/ST_initialization.c index 53fc1cd0..66809726 100644 --- a/ST_initialization.c +++ b/ST_initialization.c @@ -63,8 +63,7 @@ extern Bool* _SomeKillage; // From ST_mortality.c /********* Modular functions defined elsewhere ************/ /* Again, we should clean this up eventually. -CH */ -void rgroup_Establish(void); -void Env_Generate(void); +void rgroup_Establish(void); void rgroup_PartResources(void); void rgroup_Grow(void); void mort_Main(Bool* killed); diff --git a/ST_main.c b/ST_main.c index eb92461b..b4f11479 100644 --- a/ST_main.c +++ b/ST_main.c @@ -36,7 +36,6 @@ #include "ST_initialization.h" #include "ST_progressBar.h" #include "ST_seedDispersal.h" -extern SXW_t* SXW; extern Bool prepare_IterationSummary; // defined in `SOILWAT2/SW_Output.c` extern Bool print_IterationSummary; // defined in `SOILWAT2/SW_Output_outtext.c` From 7575ffd16e59acb94d5159ea5e2dfa19ddaf5771 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 30 Jul 2019 13:38:03 -0600 Subject: [PATCH 136/167] (issue #369) removed mort_EndOfYear form spinup mort_EndOfYear performed fire and extirpation. Since we don't expect to have either of these during spinup I removed the call. grazing_EndOfYear performed grazing, and we don't want that in spinup either. --- ST_initialization.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ST_initialization.c b/ST_initialization.c index 66809726..c35385e8 100644 --- a/ST_initialization.c +++ b/ST_initialization.c @@ -68,8 +68,6 @@ void rgroup_PartResources(void); void rgroup_Grow(void); void mort_Main(Bool* killed); void rgroup_IncrAges(void); -void grazing_EndOfYear(void); -void mort_EndOfYear(void); void _kill_annuals(void); void _kill_maxage(void); void proportion_Recovery(void); @@ -271,8 +269,6 @@ static void _run_spinup(void) rgroup_Grow(); // Grow mort_Main(&killedany); // Mortality that occurs during the growing season rgroup_IncrAges(); // Increment ages of all plants - grazing_EndOfYear(); // Livestock grazing - mort_EndOfYear(); // End of year mortality. _kill_annuals(); // Kill annuals _kill_maxage(); // Kill plants that reach max age proportion_Recovery(); // Recover from any disturbances From 7f2d9e8c70491f63dd2c45309d5d5994fe08ba48 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 31 Jul 2019 11:26:11 -0600 Subject: [PATCH 137/167] Issue #367 modified SoilType struct to match SOILWAT better We are going to use a funciton from SOILWAT2 to swap soils with the following signature: void _set_layers(LyrIndex nlyrs, RealF *dmax, RealF *matricd, RealF *f_gravel, RealF *evco, RealF *trco_grass, RealF *trco_shrub, RealF *trco_tree, RealF *trco_forb, RealF *psand, RealF *pclay, RealF *imperm, RealF *soiltemp) It therefore makes the code more readable to have all of the parameters in _sel_layers match one to one with a field from the SoilType struct. --- ST_grid.c | 102 ++++++++++++++++++++++++++++++++++++++---------------- ST_grid.h | 24 +++++++------ 2 files changed, 87 insertions(+), 39 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 8c411c04..e77698dd 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -528,10 +528,6 @@ static void allocate_gridCells(int rows, int cols){ since they are allocated elsewhere in the code.*/ for(i = 0; i < grid_Rows; ++i){ for(j = 0; j < grid_Cols; ++j){ - // lyr is a dynamically allocated array - gridCells[i][j].mySoils.lyr = (Grid_Soil_Lyr*) - Mem_Calloc(MAX_LAYERS, sizeof(Grid_Soil_Lyr), "allocate_gridCells: mySoils"); - // shouldBeInitialized is a dynamically allocated array gridCells[i][j].mySpeciesInit.shouldBeInitialized = (int*) Mem_Calloc(MAX_SPECIES, sizeof(int), "allocate_gridCells: mySpeciesInit"); @@ -768,7 +764,19 @@ void free_grid_memory(void) Mem_Free(gridCells[i][j].mySpeciesInit.shouldBeInitialized); Mem_Free(gridCells[i][j].mySeedDispersal); Mem_Free(gridCells[i][j].someKillage); - Mem_Free(gridCells[i][j].mySoils.lyr); + + Mem_Free(gridCells[i][j].mySoils.depth); + Mem_Free(gridCells[i][j].mySoils.evco); + Mem_Free(gridCells[i][j].mySoils.gravel); + Mem_Free(gridCells[i][j].mySoils.imperm); + Mem_Free(gridCells[i][j].mySoils.matricd); + Mem_Free(gridCells[i][j].mySoils.pclay); + Mem_Free(gridCells[i][j].mySoils.psand); + Mem_Free(gridCells[i][j].mySoils.soiltemp); + Mem_Free(gridCells[i][j].mySoils.trco_forb); + Mem_Free(gridCells[i][j].mySoils.trco_grass); + Mem_Free(gridCells[i][j].mySoils.trco_shrub); + Mem_Free(gridCells[i][j].mySoils.trco_tree); } } @@ -1056,7 +1064,7 @@ static void _read_soils_in(void) char rootsin[20]; char seps[] = ","; char *token; - int i, j, k, cell, num, do_copy, copy_cell, num_layers, depth, depthMin, + int i, j, k, cell, num, do_copy, copy_cell, num_layers, depth, stringIndex, row, col, copy_cell_row, copy_cell_col; float d[11]; @@ -1117,38 +1125,66 @@ static void _read_soils_in(void) "Invalid %s file line %d num_layers (%d) exceeds MAX_LAYERS (%d)", grid_files[GRID_FILE_SOILS], i + 2, num_layers, MAX_LAYERS); - if (do_copy == 1 && copy_cell > -1 && copy_cell < grid_Cells - && cell != 0 && copy_cell < cell) + if (do_copy && copy_cell > -1 && copy_cell < grid_Cells && copy_cell < cell) { //copy this cells values from a previous cell's - gridCells[row][col].mySoils.lyr = Mem_Calloc(gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers, - sizeof(Grid_Soil_Lyr), "_read_soils_in()"); - for (j = 0; j < gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers; j++) - gridCells[row][col].mySoils.lyr[j] = gridCells[copy_cell_row][copy_cell_col].mySoils.lyr[j]; - gridCells[row][col].mySoils.num_layers = gridCells[copy_cell_row][copy_cell_col].mySoils.num_layers; - - // TODO: figure out how to change this code for our new struct - // grid_SoilTypes[cell] = grid_SoilTypes[copy_cell]; + CellType* srcCell = &gridCells[copy_cell_row][copy_cell_col]; + CellType* destCell = &gridCells[row][col]; + num_layers = srcCell->mySoils.num_layers; + + destCell->mySoils.num_layers = num_layers; + destCell->mySoils.depth = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.evco = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.gravel = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.imperm = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.matricd = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.trco_forb = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.pclay = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.psand = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.soiltemp = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.trco_grass = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.trco_shrub = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + destCell->mySoils.trco_tree = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + + for (j = 0; j < srcCell->mySoils.num_layers; j++){ + destCell->mySoils.depth[j] = srcCell->mySoils.depth[j]; + destCell->mySoils.evco[j] = srcCell->mySoils.evco[j]; + destCell->mySoils.gravel[j] = srcCell->mySoils.gravel[j]; + destCell->mySoils.imperm[j] = srcCell->mySoils.imperm[j]; + destCell->mySoils.matricd[j] = srcCell->mySoils.matricd[j]; + destCell->mySoils.pclay[j] = srcCell->mySoils.pclay[j]; + destCell->mySoils.psand[j] = srcCell->mySoils.psand[j]; + destCell->mySoils.soiltemp[j] = srcCell->mySoils.soiltemp[j]; + destCell->mySoils.trco_forb[j] = srcCell->mySoils.trco_forb[j]; + destCell->mySoils.trco_grass[j] = srcCell->mySoils.trco_grass[j]; + destCell->mySoils.trco_shrub[j] = srcCell->mySoils.trco_shrub[j]; + destCell->mySoils.trco_tree[j] = srcCell->mySoils.trco_tree[j]; + } strcpy(gridCells[row][col].mySoils.rootsFile, gridCells[copy_cell_row][copy_cell_col].mySoils.rootsFile); - continue; - } - else if (do_copy == 1){ + } else if (do_copy == 1){ LogError(logfp, LOGFATAL, "Invalid %s file line %d invalid copy_cell attempt", grid_files[GRID_FILE_SOILS], i + 2); } - // TODO: figure out how to change this code for our new struct - // grid_SoilTypes[cell] = nSoilTypes; - // soilTypes_Array[nSoilTypes] = cell; nSoilTypes++; - depthMin = 0; gridCells[row][col].mySoils.num_layers = num_layers; strcpy(gridCells[row][col].mySoils.rootsFile, rootsin); - gridCells[row][col].mySoils.lyr = Mem_Calloc(num_layers, sizeof(Grid_Soil_Lyr), - "_read_soils_in()"); + gridCells[row][col].mySoils.depth = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.evco = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.gravel = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.imperm = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.matricd = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.trco_forb = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.pclay = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.psand = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.soiltemp = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.trco_grass = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.trco_shrub = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + gridCells[row][col].mySoils.trco_tree = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); + for (j = 0; j < num_layers; j++) { //the idea behind using &buf[stringIndex] is that we start scanning at the point in the string that is right after what we just parsed... the & is there because we have to send sscanf the pointer that points to that location @@ -1168,10 +1204,18 @@ static void _read_soils_in(void) "Invalid %s file line %d not enough soil layers", grid_files[GRID_FILE_SOILS], i + 2); - for (k = 0; k < 11; k++) - gridCells[row][col].mySoils.lyr[j].data[k] = d[k]; - gridCells[row][col].mySoils.lyr[j].width = depth - depthMin; - depthMin = depth; + gridCells[row][col].mySoils.depth[j] = d[0]; + gridCells[row][col].mySoils.matricd[j] = d[1]; + gridCells[row][col].mySoils.gravel[j] = d[2]; + gridCells[row][col].mySoils.evco[j] = d[3]; + gridCells[row][col].mySoils.trco_grass[j] = d[4]; + gridCells[row][col].mySoils.trco_shrub[j] = d[5]; + gridCells[row][col].mySoils.trco_tree[j] = d[6]; + gridCells[row][col].mySoils.trco_forb[j] = d[7]; + gridCells[row][col].mySoils.psand[j] = d[8]; + gridCells[row][col].mySoils.pclay[j] = d[9]; + gridCells[row][col].mySoils.imperm[j] = d[10]; + gridCells[row][col].mySoils.depth[j] = depth; } } diff --git a/ST_grid.h b/ST_grid.h index f2aeb8cd..233f994c 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -23,14 +23,6 @@ #include "ST_seedDispersal.h" /*********************** Grid Structures ****************************/ -// represents a single soil layer -struct _grid_soil_lyr_st -{ - // Data for this soil layer - float data[11]; - // Vertical width of this layer - int width; -}typedef Grid_Soil_Lyr; //represents the input data for all the soil layers of a cell struct Soil_st @@ -39,8 +31,20 @@ struct Soil_st int num_layers; // Name of the roots file belonging to this cell char rootsFile[20]; - // Specific layer's information - Grid_Soil_Lyr* lyr; + // Specific layer's information. The size of these arrays is the + // same as num_layers. + RealF *depth; /* Each Layer's max depth */ + RealF *matricd; /* Each Layer's matricx */ + RealF *gravel; /* Each Layer's gravel content */ + RealF *evco; /* Each Layer's evco */ + RealF *trco_grass; /* Each Layer's trco for grass */ + RealF *trco_shrub; /* Each Layer's trco for shrubs */ + RealF *trco_tree; /* Each Layer's trco for tree */ + RealF *trco_forb; /* Each Layer's trco for forbs */ + RealF *psand; /* Each Layer's sand content */ + RealF *pclay; /* Each Layer's clay content */ + RealF *imperm; /* Each layer's impermiability */ + RealF *soiltemp; /* Each Layer's temperature */ }typedef SoilType; /* Initialization information. */ From 977e31d2501d348575c6de9bd007438e5788aa49 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 2 Aug 2019 11:29:46 -0600 Subject: [PATCH 138/167] Overhauled soil layer swapping (issue #367) This commit is coupled with a commit to SOILWAT2. On the STEPWAT side I only had to add a call to set_soilLayers(). I also removed the deprecated _load_cell and _init_soil_layers. #311. In grid_soils.in I had to modify the parameters. Transp coefficient values didn't sum to one which was crashing the program. It is unclear to me if this file had every been properly implemented, but it now contains the same inputs as soils.in from SOILWAT2. --- ST_grid.c | 305 ++---------------- .../Grid_Inputs/grid_soils.csv | 11 +- 2 files changed, 32 insertions(+), 284 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index e77698dd..13799b34 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -151,10 +151,8 @@ static void _init_grid_files(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); static void allocate_gridCells(int rows, int cols); static void allocate_accumulators(void); -static void _load_cell(int row, int col, int year, Bool useAccumulators); static void _read_disturbances_in(void); static void _read_soils_in(void); -static void _init_soil_layers(int cell, int isSpinup); static void _read_init_species(void); static void _read_maxrgroupspecies(void); static void _read_grid_setup(void); @@ -786,121 +784,6 @@ void free_grid_memory(void) Mem_Free(gridCells); } -/* -static void _load_cell(int row, int col, int year, Bool useAccumulators) -{ - // loads the specified cell into the global variables - - int cell = col + ((row - 1) * grid_Cols) - 1; // converts the row/col into an array index - int j, k; - GrpIndex c; - SppIndex s; - //fprintf(stderr, " loading cell: %d; ", cell); - if (useAccumulators) - stat_Load_Accumulators(cell, year); - - ForEachSpecies(s) - { - if (!Species[s]->use_me) - continue; - - Mem_Free(Species[s]->kills); - Mem_Free(Species[s]->seedprod); - _free_head(Species[s]->IndvHead); //free_head() frees the memory allocated by the head and the memory allocated by each part of the linked list - - *Species[s] = grid_Species[s][cell]; - - Species[s]->kills = Mem_Calloc(grid_Species[s][cell].max_age, - sizeof(IntUS), "_load_cell(Species[s]->kills)"); - Species[s]->seedprod = Mem_Calloc(grid_Species[s][cell].viable_yrs, - sizeof(RealF), "_load_cell(Species[s]->seedprod)"); - - memcpy(Species[s]->kills, grid_Species[s][cell].kills, - grid_Species[s][cell].max_age * sizeof(IntUS)); - memcpy(Species[s]->seedprod, grid_Species[s][cell].seedprod, - grid_Species[s][cell].viable_yrs * sizeof(RealF)); - Species[s]->IndvHead = _copy_head(grid_Species[s][cell].IndvHead); //copy_head() deep copies the linked list structure (allocating memory when needed)... it will even allocate memory for the head of the list - - } - - ForEachGroup(c) - { - if (!RGroup[c]->use_me) - continue; - Mem_Free(RGroup[c]->kills); //kills is the only pointer in the resourcegroup_st struct (which is what RGroup is defined as)... we need to free it then reallocate it then memcpy it to get the deep copy we want - - *RGroup[c] = grid_RGroup[c][cell]; //does a shallow copy, we have to do the freeing/malloc/memcpy to deep copy (ie copy the values in the pointers instead of the addresses) the pointers. A shallow copy will copy over the values for every non-pointer (C itself does not inherently know how to deep copy, so we must code this behaviour). - - RGroup[c]->kills = Mem_Calloc(grid_RGroup[c][cell].max_age, - sizeof(IntUS), "_load_cell(RGroup[c]->kills"); - memcpy(RGroup[c]->kills, grid_RGroup[c][cell].kills, - grid_RGroup[c][cell].max_age * sizeof(IntUS)); - } - - *Succulent = grid_Succulent[cell]; - *Env = grid_Env[cell]; - *Plot = grid_Plot[cell]; - *Globals = grid_Globals[cell]; - - Mem_Free(SXW->f_roots); - Mem_Free(SXW->f_phen); - Mem_Free(SXW->f_bvt); - Mem_Free(SXW->f_prod); - Mem_Free(SXW->f_watin); - Mem_Free(SXW->transpTotal); - ForEachVegType(k) { - Mem_Free(SXW->transpVeg[k]); - } - - if (SXW->swc != NULL) - Mem_Free(SXW->swc); - for (j = 0; j < SW_Site.n_layers + SW_Site.deepdrain; j++) - Mem_Free(SW_Site.lyr[j]); - Mem_Free(SW_Site.lyr); - - *SXW = grid_SXW[cell]; - SW_Site = grid_SW_Site[cell]; - SW_Soilwat = grid_SW_Soilwat[cell]; - SW_VegProd = grid_SW_VegProd[cell]; - - SXW->transpTotal = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), - "_load_cell(SXW->transp)"); - ForEachVegType(k) { - SXW->transpVeg[k] = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealD), - "_load_cell(SXW->transp)"); - } - SXW->swc = Mem_Calloc(SXW->NPds * SXW->NSoLyrs, sizeof(RealF), - "_load_cell(SXW->swc)"); - - SXW->f_roots = Str_Dup(grid_SXW[cell].f_roots); - SXW->f_phen = Str_Dup(grid_SXW[cell].f_phen); - SXW->f_bvt = Str_Dup(grid_SXW[cell].f_bvt); - SXW->f_prod = Str_Dup(grid_SXW[cell].f_prod); - SXW->f_watin = Str_Dup(grid_SXW[cell].f_watin); - memcpy(SXW->transpTotal, grid_SXW[cell].transpTotal, - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - ForEachVegType(k) { - memcpy(SXW->transpVeg[k], grid_SXW[cell].transpVeg[k], - SXW->NPds * SXW->NSoLyrs * sizeof(RealD)); - } - memcpy(SXW->swc, grid_SXW[cell].swc, - SXW->NPds * SXW->NSoLyrs * sizeof(RealF)); - - SW_Site.lyr = Mem_Calloc( - grid_SW_Site[cell].n_layers + grid_SW_Site[cell].deepdrain, - sizeof(SW_LAYER_INFO *), "_load_cell(SW_Site.lyr)"); - for (j = 0; - j < grid_SW_Site[cell].n_layers + grid_SW_Site[cell].deepdrain; - j++) - { - SW_Site.lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_load_cell(SW_Site.lyr[j])"); - memcpy(SW_Site.lyr[j], grid_SW_Site[cell].lyr[j], - sizeof(SW_LAYER_INFO)); - } -} -*/ - /* Load gridCells[row][col] into the globals variables. Any call to this function should have an accompanying call to unload_cell(). */ void load_cell(int row, int col){ @@ -937,6 +820,17 @@ void load_cell(int row, int col){ /* Copy this cell's SXW variables into the local variables in sxw.c */ copy_sxw_variables(gridCells[row][col].mySXW, gridCells[row][col].mySXWResources, gridCells[row][col].myTranspWindow); + + // If we have read in the soil information num_layers will be > 0. + // Otherwise we haven't read the file so there is no point wasting time on this. + if(gridCells[row][col].mySoils.num_layers > 0){ + RealD soilRegionsLowerBounds[3] = { 30, 70, 100 }; + set_soillayers(gridCells[row][col].mySoils.num_layers, gridCells[row][col].mySoils.depth, gridCells[row][col].mySoils.matricd, + gridCells[row][col].mySoils.gravel, gridCells[row][col].mySoils.evco, gridCells[row][col].mySoils.trco_grass, + gridCells[row][col].mySoils.trco_shrub, gridCells[row][col].mySoils.trco_tree, gridCells[row][col].mySoils.trco_forb, + gridCells[row][col].mySoils.psand, gridCells[row][col].mySoils.pclay, gridCells[row][col].mySoils.imperm, + gridCells[row][col].mySoils.soiltemp, 3, soilRegionsLowerBounds); + } } /* Nullify all global variables. This function should appear after every call @@ -1204,18 +1098,18 @@ static void _read_soils_in(void) "Invalid %s file line %d not enough soil layers", grid_files[GRID_FILE_SOILS], i + 2); - gridCells[row][col].mySoils.depth[j] = d[0]; - gridCells[row][col].mySoils.matricd[j] = d[1]; - gridCells[row][col].mySoils.gravel[j] = d[2]; - gridCells[row][col].mySoils.evco[j] = d[3]; - gridCells[row][col].mySoils.trco_grass[j] = d[4]; - gridCells[row][col].mySoils.trco_shrub[j] = d[5]; - gridCells[row][col].mySoils.trco_tree[j] = d[6]; - gridCells[row][col].mySoils.trco_forb[j] = d[7]; - gridCells[row][col].mySoils.psand[j] = d[8]; - gridCells[row][col].mySoils.pclay[j] = d[9]; - gridCells[row][col].mySoils.imperm[j] = d[10]; gridCells[row][col].mySoils.depth[j] = depth; + gridCells[row][col].mySoils.matricd[j] = d[0]; + gridCells[row][col].mySoils.gravel[j] = d[1]; + gridCells[row][col].mySoils.evco[j] = d[2]; + gridCells[row][col].mySoils.trco_grass[j] = d[3]; + gridCells[row][col].mySoils.trco_shrub[j] = d[4]; + gridCells[row][col].mySoils.trco_tree[j] = d[5]; + gridCells[row][col].mySoils.trco_forb[j] = d[6]; + gridCells[row][col].mySoils.psand[j] = d[7]; + gridCells[row][col].mySoils.pclay[j] = d[8]; + gridCells[row][col].mySoils.imperm[j] = d[9]; + gridCells[row][col].mySoils.soiltemp[j] = d[10]; } } @@ -1227,161 +1121,6 @@ static void _read_soils_in(void) CloseFile(&f); } -/* -static void _init_soil_layers(int cell, int isSpinup) -{ - // initializes the soilwat soil layers for the cell correctly based upon the input gathered from our grid_soils input file - // pretty much takes the data from grid_Soils (read in in _read_soils_in()) and converts it to what SW_Site needs... - // this function does generally the same things that the _read_layers() function in SW_Site.c does, except that it does it in a way that lets us use it in the grid... - int i, j; - i = cell; - char* errtype; - Bool evap_ok = TRUE, transp_ok_forb = TRUE, transp_ok_tree = TRUE, - transp_ok_shrub = TRUE, transp_ok_grass = TRUE; //mitigate gaps in layers - Bool fail = FALSE; - RealF fval = 0; - - if (SW_Site.deepdrain) - SW_Site.n_layers++; - for (j = 0; j < SW_Site.n_layers; j++) - Mem_Free(SW_Site.lyr[j]); - Mem_Free(SW_Site.lyr); - - SW_Site.n_layers = grid_Soils[i].num_layers; - SW_Site.n_evap_lyrs = SW_Site.n_transp_lyrs[SW_FORBS] = - SW_Site.n_transp_lyrs[SW_TREES] = SW_Site.n_transp_lyrs[SW_SHRUB] = - SW_Site.n_transp_lyrs[SW_GRASS] = 0; - - SW_Site.lyr = Mem_Calloc(SW_Site.n_layers + SW_Site.deepdrain, - sizeof(SW_LAYER_INFO *), "_init_grid_globals()"); - for (j = 0; j < SW_Site.n_layers; j++) - { - if (LT(grid_Soils[i].lyr[j].data[0], 0.)) - { - fail = TRUE; - fval = grid_Soils[i].lyr[j].data[0]; - errtype = Str_Dup("bulk density"); - } - else if (LT(grid_Soils[i].lyr[j].data[1], - 0.) || GT(grid_Soils[i].lyr[j].data[1], 1.0)) - { - fail = TRUE; - fval = grid_Soils[i].lyr[j].data[1]; - errtype = Str_Dup("gravel content"); - } - else if (LE(grid_Soils[i].lyr[j].data[7], 0.)) - { - fail = TRUE; - fval = grid_Soils[i].lyr[j].data[7]; - errtype = Str_Dup("sand proportion"); - } - else if (LE(grid_Soils[i].lyr[j].data[8], 0.)) - { - fail = TRUE; - fval = grid_Soils[i].lyr[j].data[8]; - errtype = Str_Dup("clay proportion"); - } - else if (LT(grid_Soils[i].lyr[j].data[9], 0.)) - { - fail = TRUE; - fval = grid_Soils[i].lyr[j].data[9]; - errtype = Str_Dup("impermeability"); - } - if (fail) - { - LogError(logfp, LOGFATAL, "Invalid %s (%5.4f) in layer %d.\n", - errtype, fval, j + 1); - } - - SW_Site.lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_init_grid_globals()"); - - //indexes (for grid_Soils[i].lyr[j].data): - //0 1 2 3 4 5 6 7 8 9 10 - //matricd gravel_content evco trco_grass trco_shrub trco_tree trco_forb %sand %clay imperm soiltemp - SW_Site.lyr[j]->width = grid_Soils[i].lyr[j].width; - SW_Site.lyr[j]->soilMatric_density = grid_Soils[i].lyr[j].data[0]; - SW_Site.lyr[j]->fractionVolBulk_gravel = grid_Soils[i].lyr[j].data[1]; - SW_Site.lyr[j]->evap_coeff = grid_Soils[i].lyr[j].data[2]; - SW_Site.lyr[j]->transp_coeff[3] = grid_Soils[i].lyr[j].data[3]; - SW_Site.lyr[j]->transp_coeff[1] = grid_Soils[i].lyr[j].data[4]; - SW_Site.lyr[j]->transp_coeff[0] = grid_Soils[i].lyr[j].data[5]; - SW_Site.lyr[j]->transp_coeff[2] = grid_Soils[i].lyr[j].data[6]; - SW_Site.lyr[j]->fractionWeightMatric_sand = - grid_Soils[i].lyr[j].data[7]; - SW_Site.lyr[j]->fractionWeightMatric_clay = - grid_Soils[i].lyr[j].data[8]; - SW_Site.lyr[j]->impermeability = grid_Soils[i].lyr[j].data[9]; - SW_Site.lyr[j]->my_transp_rgn[0] = 0; - SW_Site.lyr[j]->my_transp_rgn[2] = 0; - SW_Site.lyr[j]->my_transp_rgn[1] = 0; - SW_Site.lyr[j]->my_transp_rgn[3] = 0; - SW_Site.lyr[j]->sTemp = grid_Soils[i].lyr[j].data[10]; - - if (evap_ok) - { - if (GT(SW_Site.lyr[j]->evap_coeff, 0.0)) - SW_Site.n_evap_lyrs++; - else - evap_ok = FALSE; - } - if (transp_ok_tree) - { - if (GT(SW_Site.lyr[j]->transp_coeff[0], 0.0)) - SW_Site.n_transp_lyrs[SW_TREES]++; - else - transp_ok_tree = FALSE; - } - if (transp_ok_shrub) - { - if (GT(SW_Site.lyr[j]->transp_coeff[1], 0.0)) - SW_Site.n_transp_lyrs[SW_SHRUB]++; - else - transp_ok_shrub = FALSE; - } - if (transp_ok_grass) - { - if (GT(SW_Site.lyr[j]->transp_coeff[3], 0.0)) - SW_Site.n_transp_lyrs[SW_GRASS]++; - else - transp_ok_grass = FALSE; - } - if (transp_ok_forb) - { - if (GT(SW_Site.lyr[j]->transp_coeff[2], 0.0)) - SW_Site.n_transp_lyrs[SW_FORBS]++; - else - transp_ok_forb = FALSE; - } - water_eqn(SW_Site.lyr[j]->fractionVolBulk_gravel, - SW_Site.lyr[j]->fractionWeightMatric_sand, - SW_Site.lyr[j]->fractionWeightMatric_clay, j); //in SW_Site.c, called to initialize some layer data... - SW_Site.lyr[j]->swcBulk_fieldcap = SW_SWPmatric2VWCBulk( - SW_Site.lyr[j]->fractionVolBulk_gravel, 0.333, j) - * SW_Site.lyr[j]->width; - SW_Site.lyr[j]->swcBulk_wiltpt = SW_SWPmatric2VWCBulk( - SW_Site.lyr[j]->fractionVolBulk_gravel, 15, j) - * SW_Site.lyr[j]->width; - //From calculate_soilBulkDensity in SW_Site.c - SW_Site.lyr[j]->soilBulk_density = SW_Site.lyr[j]->soilMatric_density - * (1 - SW_Site.lyr[j]->fractionVolBulk_gravel) - + (SW_Site.lyr[j]->fractionVolBulk_gravel * 2.65); - //already checked for max_layers condition - } - if (SW_Site.deepdrain) - { - SW_Site.n_layers++; - SW_Site.lyr[j] = Mem_Calloc(1, sizeof(SW_LAYER_INFO), - "_init_grid_globals()"); - SW_Site.lyr[j]->width = 1.0; - } - - init_site_info(); //in SW_Site.c, called to initialize layer data... - - _init_SXW_inputs(FALSE, grid_Soils[i].rootsFile); //we call this so that SXW can set the correct sizes/values up for the memory dynamically allocated in sxw.c -} -*/ - /* Read the species initialization CSV. This function only needs to be called if the user requests initialization.*/ static void _read_init_species(void) { diff --git a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv index efe52634..a42d078d 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv @@ -1 +1,10 @@ -cell,copy_cell,copy_which,num_layers,sxw_roots,1_depth,1_matricd,1_gravel_content,1_evco,1_trco_grass,1_trco_shrub,1_trco_tree,1_trco_forb,1_sand,1_clay,1_imperm,1_soiltemp,2_depth,2_matricd,2_gravel_content,2_evco,2_trco_grass,2_trco_shrub,2_trco_tree,2_trco_forb,2_sand,2_clay,2_imperm,2_soiltemp,3_depth,3_matricd,3_gravel_content,3_evco,3_trco_grass,3_trco_shrub,3_trco_tree,3_trco_forb,3_sand,3_clay,3_imperm,3_soiltemp,4_depth,4_matricd,4_gravel_content,4_evco,4_trco_grass,4_trco_shrub,4_trco_tree,4_trco_forb,4_sand,4_clay,4_imperm,4_soiltemp,5_depth,5_matricd,5_gravel_content,5_evco,5_trco_grass,5_trco_shrub,5_trco_tree,5_trco_forb,5_sand,5_clay,5_imperm,5_soiltemp,6_depth,6_matricd,6_gravel_content,6_evco,6_trco_grass,6_trco_shrub,6_trco_tree,6_trco_forb,6_sand,6_clay,6_imperm,6_soiltemp,7_depth,7_matricd,7_gravel_content,7_evco,7_trco_grass,7_trco_shrub,7_trco_tree,7_trco_forb,7_sand,7_clay,7_imperm,7_soiltemp,8_depth,8_matricd,8_gravel_content,8_evco,8_trco_grass,8_trco_shrub,8_trco_tree,8_trco_forb,8_sand,8_clay,8_imperm,8_soiltemp,9_depth,9_matricd,9_gravel_content,9_evco,9_trco_grass,9_trco_shrub,9_trco_tree,9_trco_forb,9_sand,9_clay,9_imperm,9_soiltemp 0,0,0,8,sxwroots1.in,5,1.43,0,0.812,0.169,0.169,0.169,0.169,0.51,0.15,0,0.186,10,1.41,0,0.153,0.173,0.173,0.173,0.173,0.44,0.26,0,0.372,20,1.39,0,0.034,0.339,0.339,0.339,0.339,0.35,0.41,0,0.744,30,1.39,0,0,0.186,0.186,0.186,0.186,0.32,0.45,0,1.116,40,1.38,0,0,0.133,0.133,0.133,0.133,0.31,0.47,0,1.488,60,1.15,0,0,0,0.1,0,0,0.32,0.47,0,2.232,80,1.31,0,0,0,0,0,0,0.57,0.28,0,2.975,85,1.31,0,0,0,0,0,0,0.57,0.28,0,2.975,,,,,,,,,,,, 1,0,0,9,sxwroots2.in,5,1.43,0,0.812,0.169,0.169,0.169,0.169,0.51,0.15,0,0.186,10,1.41,0,0.153,0.173,0.173,0.173,0.173,0.44,0.26,0,0.372,20,1.39,0,0.034,0.339,0.239,0.339,0.339,0.35,0.41,0,0.744,30,1.39,0,0,0.186,0.186,0.186,0.186,0.32,0.45,0,1.116,40,1.38,0,0,0.133,0.133,0.133,0.133,0.31,0.47,0,1.488,60,1.15,0,0,0,0.1,0,0,0.32,0.47,0,2.232,80,1.31,0,0,0,0,0,0,0.57,0.28,0,2.975,85,1.31,0,0,0,0,0,0,0.57,0.28,0,2.975,90,1.31,0,0,0,0,0,0,0.57,0.28,0,2.975 2,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 3,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 4,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 5,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 6,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 7,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 8,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, \ No newline at end of file +cell,copy_cell,copy_which,num_layers,sxw_roots,1_depth,1_matricd,1_gravel_content,1_evco,1_trco_grass,1_trco_shrub,1_trco_tree,1_trco_forb,1_sand,1_clay,1_imperm,1_soiltemp,2_depth,2_matricd,2_gravel_content,2_evco,2_trco_grass,2_trco_shrub,2_trco_tree,2_trco_forb,2_sand,2_clay,2_imperm,2_soiltemp,3_depth,3_matricd,3_gravel_content,3_evco,3_trco_grass,3_trco_shrub,3_trco_tree,3_trco_forb,3_sand,3_clay,3_imperm,3_soiltemp,4_depth,4_matricd,4_gravel_content,4_evco,4_trco_grass,4_trco_shrub,4_trco_tree,4_trco_forb,4_sand,4_clay,4_imperm,4_soiltemp,5_depth,5_matricd,5_gravel_content,5_evco,5_trco_grass,5_trco_shrub,5_trco_tree,5_trco_forb,5_sand,5_clay,5_imperm,5_soiltemp,6_depth,6_matricd,6_gravel_content,6_evco,6_trco_grass,6_trco_shrub,6_trco_tree,6_trco_forb,6_sand,6_clay,6_imperm,6_soiltemp,7_depth,7_matricd,7_gravel_content,7_evco,7_trco_grass,7_trco_shrub,7_trco_tree,7_trco_forb,7_sand,7_clay,7_imperm,7_soiltemp,8_depth,8_matricd,8_gravel_content,8_evco,8_trco_grass,8_trco_shrub,8_trco_tree,8_trco_forb,8_sand,8_clay,8_imperm,8_soiltemp,9_depth,9_matricd,9_gravel_content,9_evco,9_trco_grass,9_trco_shrub,9_trco_tree,9_trco_forb,9_sand,9_clay,9_imperm,9_soiltemp +0,0,0,8,sxwroots1.in,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,,,,,,,,,,,, +1,0,0,8,sxwroots2.in,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,,,,,,,,,,,, +2,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +3,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +4,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +5,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +6,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +7,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +8,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, From 1c3546d3ed752f0f60a37ed6b957d2370027e24f Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 2 Aug 2019 11:51:15 -0600 Subject: [PATCH 139/167] updated SOILWAT head to latest commit on Bugfix_247 --- sw_src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sw_src b/sw_src index 0336a71c..b25edb81 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit 0336a71c5e2c98e9b82e867cb226a00547605db4 +Subproject commit b25edb81fe302646524bfa2dd2df284f09a3e164 From 20698f24c1fa068ac545fa19354343f5062b1e96 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Mon, 5 Aug 2019 15:27:28 -0600 Subject: [PATCH 140/167] #374 overhauled grid_soils.csv To accomplish the new look I had to rewrite _read_soils_in(). I also had to move the sxwroots file column to the end of the file. Otherwise scanf would read the entire line as a single char* --- ST_grid.c | 304 ++++++++---------- .../Grid_Inputs/grid_soils.csv | 58 +++- 2 files changed, 177 insertions(+), 185 deletions(-) mode change 100644 => 100755 testing.sagebrush.master/Grid_Inputs/grid_soils.csv diff --git a/ST_grid.c b/ST_grid.c index 13799b34..e88f9480 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -60,9 +60,6 @@ SoilType *grid_Soils; Grid_SD_St **grid_SD; //for seed dispersal -// these variables are used for the soil types in the spinup options -int nSoilTypes, *soilTypes_Array, *grid_SoilTypes; - /***************************** Externed variables **********************************/ /* Note that in an ideal world we wouldn't need to extern any variables because every module would declate them in a header file. Hopefully we can get this @@ -146,6 +143,7 @@ void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp /*********** Locally Used Function Declarations ************/ /***********************************************************/ +void _copy_soils(SoilType* src, SoilType* dest); static void printGeneralInfo(void); static void _init_grid_files(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); @@ -935,190 +933,146 @@ static int _get_value_index(char* s, char seperator, int nSeperators) return i; } -static int _get_value_index2(char* s, int nSeperators) -{ - //pretty much this function goes through s until it find nSeperators worth of seperators and then returns the index of the next character - //this is used to do most of the parsing in the _read_soils_in() function - int i = 0, sep = 0; - while (1) - { - i++; - if (*s++ == '\0') //checks if the current char equals the seperator... and then increments the char pointer - if (++sep == nSeperators) //needs ++sep, not sep++ - break; - } - return i; -} - -/* Read the grid soils input */ -static void _read_soils_in(void) -{ - FILE *f; +/* Read the grid_soils.csv file and assign values to all gridCells.mySoils variables. */ +static void _read_soils_in(void){ + int i, row, col, entriesRead, cellNum, cellToCopy, + layerRead; + SoilType* destSoil; char buf[4096]; - char rootsin[20]; - char seps[] = ","; - char *token; - int i, j, k, cell, num, do_copy, copy_cell, num_layers, depth, - stringIndex, row, col, copy_cell_row, copy_cell_col; - float d[11]; - - nSoilTypes = 0; //initialize our soil types counter - - f = OpenFile(grid_files[GRID_FILE_SOILS], "r"); - - GetALine2(f, buf, 4096); // gets rid of the first line (since it just defines the columns)... it's only there for user readability - for (i = 0; i < grid_Cells; i++) - { - row = i / grid_Cols; + Bool copyAnotherCell; // TRUE if we need to copy another cell + + /* tempSoil is allocated the maximum amount of memory that a SoilType could need. + It will serve to read in parameters. */ + SoilType tempSoil; + tempSoil.depth = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.evco = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.gravel = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.imperm = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.matricd = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.pclay = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.psand = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.soiltemp = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.trco_forb = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.trco_grass = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.trco_shrub = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + tempSoil.trco_tree = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); + + FILE* f = OpenFile(grid_files[GRID_FILE_SOILS], "r"); + GetALine(f, buf); // Throw out the header line. + + for(i = 0; i < grid_Cells; ++i){ + row = i / grid_Cols; col = i % grid_Cols; - load_cell(row, col); - - if (!GetALine2(f, buf, 4096)) - break; - gridCells[row][col].mySoils.rootsFile[0] = '\0'; - rootsin[0] = '\0'; - - num = 0; - token = strtok(buf, seps); - while (token != NULL && num < 5) - { - switch (num) - { - case 0: - cell = atoi(token); - break; - case 1: - do_copy = atoi(token); - break; - case 2: - copy_cell = atoi(token); - copy_cell_row = copy_cell / grid_Cols; - copy_cell_col = copy_cell % grid_Cols; - break; - case 3: - num_layers = atoi(token); - break; - case 4: - strcpy(rootsin, token); - break; + load_cell(row, col); + destSoil = &gridCells[row][col].mySoils; + + tempSoil.num_layers = 0; + copyAnotherCell = FALSE; + do { + GetALine(f, buf); + /* If the user defined all columns except copy_cell. */ + entriesRead = sscanf(buf, "%d,,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%s", + &cellNum, &layerRead, &tempSoil.depth[tempSoil.num_layers], + &tempSoil.matricd[tempSoil.num_layers], &tempSoil.gravel[tempSoil.num_layers], + &tempSoil.evco[tempSoil.num_layers], &tempSoil.trco_grass[tempSoil.num_layers], + &tempSoil.trco_shrub[tempSoil.num_layers], &tempSoil.trco_tree[tempSoil.num_layers], + &tempSoil.trco_forb[tempSoil.num_layers], &tempSoil.psand[tempSoil.num_layers], + &tempSoil.pclay[tempSoil.num_layers], &tempSoil.imperm[tempSoil.num_layers], + &tempSoil.soiltemp[tempSoil.num_layers], tempSoil.rootsFile); + /* If the user entered a cell to copy but also entered all parameters */ + if(entriesRead == 1){ + entriesRead = sscanf(buf, "%d,%d,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%s", + &cellNum, &cellToCopy, &layerRead, &tempSoil.depth[tempSoil.num_layers], + &tempSoil.matricd[tempSoil.num_layers], &tempSoil.gravel[tempSoil.num_layers], + &tempSoil.evco[tempSoil.num_layers], &tempSoil.trco_grass[tempSoil.num_layers], + &tempSoil.trco_shrub[tempSoil.num_layers], &tempSoil.trco_tree[tempSoil.num_layers], + &tempSoil.trco_forb[tempSoil.num_layers], &tempSoil.psand[tempSoil.num_layers], + &tempSoil.pclay[tempSoil.num_layers], &tempSoil.imperm[tempSoil.num_layers], + &tempSoil.soiltemp[tempSoil.num_layers], tempSoil.rootsFile); } - num++; - if (num != 5) - token = strtok(NULL, seps); - } - - if (num < 5) - if (!do_copy) - LogError(logfp, LOGFATAL, "Invalid %s file", grid_files[GRID_FILE_SOILS]); - if (!do_copy) - stringIndex = _get_value_index2(buf, 5); //gets us the index of the string that is right after what we just parsed in - if (num_layers > MAX_LAYERS) - LogError(logfp, LOGFATAL, - "Invalid %s file line %d num_layers (%d) exceeds MAX_LAYERS (%d)", - grid_files[GRID_FILE_SOILS], i + 2, num_layers, MAX_LAYERS); + /* if the user only defined a cell to copy */ + if(entriesRead == 2){ + copyAnotherCell = TRUE; + /* Error checking. These are the only valid number of columns. */ + } else if(entriesRead != 0 && entriesRead != 15 && entriesRead != 16){ + LogError(logfp, LOGFATAL, "%s: Incorrect number of columns in grid soils file. (%d)", + grid_files[GRID_FILE_SOILS], entriesRead); + } - if (do_copy && copy_cell > -1 && copy_cell < grid_Cells && copy_cell < cell) - { //copy this cells values from a previous cell's - CellType* srcCell = &gridCells[copy_cell_row][copy_cell_col]; - CellType* destCell = &gridCells[row][col]; - num_layers = srcCell->mySoils.num_layers; - - destCell->mySoils.num_layers = num_layers; - destCell->mySoils.depth = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.evco = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.gravel = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.imperm = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.matricd = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.trco_forb = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.pclay = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.psand = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.soiltemp = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.trco_grass = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.trco_shrub = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - destCell->mySoils.trco_tree = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - - for (j = 0; j < srcCell->mySoils.num_layers; j++){ - destCell->mySoils.depth[j] = srcCell->mySoils.depth[j]; - destCell->mySoils.evco[j] = srcCell->mySoils.evco[j]; - destCell->mySoils.gravel[j] = srcCell->mySoils.gravel[j]; - destCell->mySoils.imperm[j] = srcCell->mySoils.imperm[j]; - destCell->mySoils.matricd[j] = srcCell->mySoils.matricd[j]; - destCell->mySoils.pclay[j] = srcCell->mySoils.pclay[j]; - destCell->mySoils.psand[j] = srcCell->mySoils.psand[j]; - destCell->mySoils.soiltemp[j] = srcCell->mySoils.soiltemp[j]; - destCell->mySoils.trco_forb[j] = srcCell->mySoils.trco_forb[j]; - destCell->mySoils.trco_grass[j] = srcCell->mySoils.trco_grass[j]; - destCell->mySoils.trco_shrub[j] = srcCell->mySoils.trco_shrub[j]; - destCell->mySoils.trco_tree[j] = srcCell->mySoils.trco_tree[j]; - } + if(entriesRead > 2){ + tempSoil.num_layers++; + } + } while (entriesRead != 0); - strcpy(gridCells[row][col].mySoils.rootsFile, gridCells[copy_cell_row][copy_cell_col].mySoils.rootsFile); - continue; - } else if (do_copy == 1){ - LogError(logfp, LOGFATAL, - "Invalid %s file line %d invalid copy_cell attempt", - grid_files[GRID_FILE_SOILS], i + 2); - } + if(copyAnotherCell){ + if(cellToCopy > i){ + LogError(logfp, LOGFATAL, "%s: Attempted to copy values that have not been read yet.\n" + "\tIf you want to copy a soil make sure you define the layers" + "the FIRST time you use it.", grid_files[GRID_FILE_SOILS]); + } - nSoilTypes++; - - gridCells[row][col].mySoils.num_layers = num_layers; - strcpy(gridCells[row][col].mySoils.rootsFile, rootsin); - gridCells[row][col].mySoils.depth = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.evco = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.gravel = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.imperm = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.matricd = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.trco_forb = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.pclay = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.psand = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.soiltemp = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.trco_grass = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.trco_shrub = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - gridCells[row][col].mySoils.trco_tree = Mem_Calloc(num_layers, sizeof(RealF), "_read_soils_in()"); - - for (j = 0; j < num_layers; j++) - { - //the idea behind using &buf[stringIndex] is that we start scanning at the point in the string that is right after what we just parsed... the & is there because we have to send sscanf the pointer that points to that location - num = sscanf(&buf[stringIndex], - "%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f", &depth, &d[0], &d[1], - &d[2], &d[3], &d[4], &d[5], &d[6], &d[7], &d[8], &d[9], - &d[10]); - if (num != 12) - LogError(logfp, LOGFATAL, - "Invalid '%s' file line %d invalid soil layer input", - grid_files[GRID_FILE_SOILS], i + 2); - - k = stringIndex; - stringIndex += _get_value_index(&buf[stringIndex], ',', 12); //updates the index of the string that we are at - if (k == stringIndex) - LogError(logfp, LOGFATAL, - "Invalid %s file line %d not enough soil layers", - grid_files[GRID_FILE_SOILS], i + 2); - - gridCells[row][col].mySoils.depth[j] = depth; - gridCells[row][col].mySoils.matricd[j] = d[0]; - gridCells[row][col].mySoils.gravel[j] = d[1]; - gridCells[row][col].mySoils.evco[j] = d[2]; - gridCells[row][col].mySoils.trco_grass[j] = d[3]; - gridCells[row][col].mySoils.trco_shrub[j] = d[4]; - gridCells[row][col].mySoils.trco_tree[j] = d[5]; - gridCells[row][col].mySoils.trco_forb[j] = d[6]; - gridCells[row][col].mySoils.psand[j] = d[7]; - gridCells[row][col].mySoils.pclay[j] = d[8]; - gridCells[row][col].mySoils.imperm[j] = d[9]; - gridCells[row][col].mySoils.soiltemp[j] = d[10]; + _copy_soils(&gridCells[cellToCopy / grid_Cols][cellToCopy % grid_Cols].mySoils, destSoil); + } else { + _copy_soils(&tempSoil, destSoil); } } - if (i != grid_Cells) - LogError(logfp, LOGFATAL, "Invalid %s file, not enough cells", - grid_files[GRID_FILE_SOILS]); - - unload_cell(); + unload_cell(); CloseFile(&f); + + Mem_Free(tempSoil.soiltemp); + Mem_Free(tempSoil.trco_forb); + Mem_Free(tempSoil.trco_grass); + Mem_Free(tempSoil.trco_shrub); + Mem_Free(tempSoil.trco_tree); + Mem_Free(tempSoil.depth); + Mem_Free(tempSoil.evco); + Mem_Free(tempSoil.gravel); + Mem_Free(tempSoil.imperm); + Mem_Free(tempSoil.matricd); + Mem_Free(tempSoil.pclay); + Mem_Free(tempSoil.psand); +} + +/* Copy one SoilType variable to another. + param src: An allocated and assigned SoilType + param dest: An unallocated SoilType + + note: dest will be allocated memory, so do not call this function + if dest is already allocated. */ +void _copy_soils(SoilType* src, SoilType* dest){ + int i; + + dest->num_layers = src->num_layers; + dest->gravel = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: gravel"); + dest->depth = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: depth"); + dest->matricd = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: matricd"); + dest->evco = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: evco"); + dest->trco_grass = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: trco_grass"); + dest->trco_shrub = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: trco_shrub"); + dest->trco_tree = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: trco_tree"); + dest->trco_forb = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: trco_forb"); + dest->psand = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: psand"); + dest->pclay = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: pclay"); + dest->imperm = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: imperm"); + dest->soiltemp = Mem_Calloc(src->num_layers, sizeof(RealF), "_copy_Soils: soiltemp"); + + for(i = 0; i < src->num_layers; ++i){ + dest->gravel[i] = src->gravel[i]; + dest->evco[i] = src->evco[i]; + dest->depth[i] = src->depth[i]; + dest->matricd[i] = src->matricd[i]; + dest->trco_shrub[i] = src->trco_shrub[i]; + dest->trco_grass[i] = src->trco_grass[i]; + dest->trco_forb[i] = src->trco_forb[i]; + dest->trco_tree[i] = src->trco_tree[i]; + dest->psand[i] = src->psand[i]; + dest->pclay[i] = src->pclay[i]; + dest->imperm[i] = src->imperm[i]; + dest->soiltemp[i] = src->soiltemp[i]; + } } /* Read the species initialization CSV. This function only needs to be called if the user requests initialization.*/ diff --git a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv old mode 100644 new mode 100755 index a42d078d..2ad54a84 --- a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv @@ -1,10 +1,48 @@ -cell,copy_cell,copy_which,num_layers,sxw_roots,1_depth,1_matricd,1_gravel_content,1_evco,1_trco_grass,1_trco_shrub,1_trco_tree,1_trco_forb,1_sand,1_clay,1_imperm,1_soiltemp,2_depth,2_matricd,2_gravel_content,2_evco,2_trco_grass,2_trco_shrub,2_trco_tree,2_trco_forb,2_sand,2_clay,2_imperm,2_soiltemp,3_depth,3_matricd,3_gravel_content,3_evco,3_trco_grass,3_trco_shrub,3_trco_tree,3_trco_forb,3_sand,3_clay,3_imperm,3_soiltemp,4_depth,4_matricd,4_gravel_content,4_evco,4_trco_grass,4_trco_shrub,4_trco_tree,4_trco_forb,4_sand,4_clay,4_imperm,4_soiltemp,5_depth,5_matricd,5_gravel_content,5_evco,5_trco_grass,5_trco_shrub,5_trco_tree,5_trco_forb,5_sand,5_clay,5_imperm,5_soiltemp,6_depth,6_matricd,6_gravel_content,6_evco,6_trco_grass,6_trco_shrub,6_trco_tree,6_trco_forb,6_sand,6_clay,6_imperm,6_soiltemp,7_depth,7_matricd,7_gravel_content,7_evco,7_trco_grass,7_trco_shrub,7_trco_tree,7_trco_forb,7_sand,7_clay,7_imperm,7_soiltemp,8_depth,8_matricd,8_gravel_content,8_evco,8_trco_grass,8_trco_shrub,8_trco_tree,8_trco_forb,8_sand,8_clay,8_imperm,8_soiltemp,9_depth,9_matricd,9_gravel_content,9_evco,9_trco_grass,9_trco_shrub,9_trco_tree,9_trco_forb,9_sand,9_clay,9_imperm,9_soiltemp -0,0,0,8,sxwroots1.in,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,,,,,,,,,,,, -1,0,0,8,sxwroots2.in,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,,,,,,,,,,,, -2,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -3,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -4,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -5,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -6,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -7,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, -8,1,1,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +cell,copy_cell,layer,depth,matricd,gravel_content,evco,trco_grass,trco_shrub,trco_tree,trco_forb,sand,clay,imperm,soiltemp,sxw_roots +0,,1,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,sxwroots1.in +0,,2,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,sxwroots1.in +0,,3,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,sxwroots1.in +0,,4,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,sxwroots1.in +0,,5,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,sxwroots1.in +0,,6,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,sxwroots1.in +0,,7,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots1.in +0,,8,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots1.in +,,,,,,,,,,,,,,, +1,,1,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,sxwroots2.in +1,,2,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,sxwroots2.in +1,,3,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,sxwroots2.in +1,,4,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,sxwroots2.in +1,,5,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,sxwroots2.in +1,,6,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,sxwroots2.in +1,,7,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots2.in +1,,8,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots2.in +,,,,,,,,,,,,,,, +2,0,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +3,1,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +4,0,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +5,1,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +6,0,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +7,1,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +8,0,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +9,1,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +10,0,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +11,1,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +12,0,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +13,1,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +14,0,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +15,1,,,,,,,,,,,,,, +,,,,,,,,,,,,,,, +16,0,,,,,,,,,,,,,, From c06c04c108db58f0bcfd0b47e34950269fa8a7ab Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 6 Aug 2019 10:28:16 -0600 Subject: [PATCH 141/167] Addressed seg faults in copy_ functions copy_species and copy_rgroup were both seg faulting if MortFlags.summary was FALSE. This was because the kills array is only allocated memory if the user requests mortality output. (issue #313) --- ST_resgroups.c | 10 ++++++---- ST_species.c | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/ST_resgroups.c b/ST_resgroups.c index 297fd7c0..ec492870 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -986,10 +986,12 @@ void copy_rgroup(const GroupType* src, GroupType* dest){ } /* -------------- Copy any arrays -------------- */ - Mem_Free(dest->kills); - dest->kills = (IntUS*) Mem_Calloc(GrpMaxAge(src->grp_num), sizeof(IntUS), "copy_rgroup: kills"); - for(i = 0; i < GrpMaxAge(src->grp_num); ++i){ - dest->kills[i] = src->kills[i]; + if(MortFlags.summary){ + Mem_Free(dest->kills); + dest->kills = (IntUS*) Mem_Calloc(GrpMaxAge(src->grp_num), sizeof(IntUS), "copy_rgroup: kills"); + for(i = 0; i < GrpMaxAge(src->grp_num); ++i){ + dest->kills[i] = src->kills[i]; + } } Mem_Free(dest->est_spp); diff --git a/ST_species.c b/ST_species.c index 660a1724..f6d4ee51 100644 --- a/ST_species.c +++ b/ST_species.c @@ -267,8 +267,8 @@ void copy_species(const SpeciesType* src, SpeciesType* dest){ } /* ---- Reallocate and copy any arrays ---- */ - // kills - if(src->max_age > 1 && src->use_me){ + // kills: Note that this array is allocated iff MortFlags.summary. + if(src->max_age > 1 && src->use_me && MortFlags.summary){ Mem_Free(dest->kills); dest->kills = (IntUS*) Mem_Calloc(src->max_age, sizeof(IntUS), "copy_species: kills"); for(i = 0; i < src->max_age; ++i){ From edd0abf0a8e0ff4adbb2f900024ec309b00c4688 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 6 Aug 2019 13:04:10 -0600 Subject: [PATCH 142/167] Updated SOILWAT2 head to latest commit on Bugfix_247 --- sw_src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sw_src b/sw_src index b25edb81..b7f28752 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit b25edb81fe302646524bfa2dd2df284f09a3e164 +Subproject commit b7f28752eda914d59f3ef21ebb588b326b008d59 From d0f2aef1f1b0bc669cbe0b0c29b4808a35c5f599 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 7 Aug 2019 17:59:04 -0600 Subject: [PATCH 143/167] #372 Located bug causing non-gridded mode to crash This was an oversight on my part. I call mem_free on a variable that is guaranteed to be NULL because of the loop above it. I'm not sure why this is only now crashing the program but it should be fixed now. --- ST_main.c | 1 - 1 file changed, 1 deletion(-) diff --git a/ST_main.c b/ST_main.c index 5706912c..fcd06cec 100644 --- a/ST_main.c +++ b/ST_main.c @@ -448,7 +448,6 @@ void deallocate_Globals(Bool isGriddedMode){ Mem_Free(indv); indv = next; } - Mem_Free(next); Mem_Free(indv); /* Finally free the actual species */ Mem_Free(Species[sp]); From 213fbb37b2b271bf0af895cf6eaa7908c13406df Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 8 Aug 2019 14:51:32 -0600 Subject: [PATCH 144/167] Addressing comments on pull request #375 UseGrid == TRUE is the same as UseGrid. incr is legacy code for the old version of the progress bar. --- ST_main.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/ST_main.c b/ST_main.c index fcd06cec..876b1391 100644 --- a/ST_main.c +++ b/ST_main.c @@ -153,7 +153,7 @@ extern pcg32_random_t markov_rng; /******************** Begin Model Code *********************/ /***********************************************************/ int main(int argc, char **argv) { - IntS year, iter, incr; + IntS year, iter; Bool killedany; logged = FALSE; @@ -169,7 +169,7 @@ int main(int argc, char **argv) { printf("STEPWAT init_args() executed successfully \n"); - if (UseGrid == TRUE) { + if (UseGrid) { runGrid(); return 0; } @@ -196,10 +196,6 @@ int main(int argc, char **argv) { ST_connect("Output/stdebug"); } - incr = (IntS) ((float) SuperGlobals.runModelIterations / 10); - if (incr == 0) - incr = 1; - /* --- Begin a new iteration ------ */ for (iter = 1; iter <= SuperGlobals.runModelIterations; iter++) { Plot_Initialize(); From 52599884e241a313723a2800c0f8ba02836873a8 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 9 Aug 2019 11:49:18 -0600 Subject: [PATCH 145/167] Multiple changes to ST_stats. * Removed deprecated stats function (issue #311) * Moved function declarations to ST_stats.h (pull request #375) * Removed deprecated grid accumulators In ST_stats.h: * Added function declarations that should be exported to other files * Removed all gridded stats structs. They are completely deprecated. In ST_stats.c: * Removed all functions that were previously only useful for gridded mode. * Removed function declarations that were moved to ST_stats.h. * Renamed _make_header and _make_header_with_std to make_header and make_header_with_std, respectively. In ST_main.c: * Removed redeclarations. * Added and include statement for ST_stats.h. In ST_grid.c: * Removed redeclaration of functions. * Moved declaration of Output_AllCellAvg Bmass and Mort to where the rest of the local functions are declared. In ST_initialization.c: * Added include statement for ST_stats.h * Removed redeclaration of stat_Copy_Accumulators. --- ST_grid.c | 20 +- ST_initialization.c | 4 +- ST_main.c | 8 +- ST_stats.c | 675 +------------------------------------------- ST_stats.h | 31 +- 5 files changed, 30 insertions(+), 708 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 83393545..85af041e 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -118,22 +118,6 @@ void maxrgroupspecies_init(void); void Plot_Initialize(void); void deallocate_Globals(Bool isGriddedMode); -//functions from ST_stats.c -void stat_Collect(Int year); -void stat_Collect_GMort(void); -void stat_Collect_SMort(void); -void stat_Output_AllMorts(void); -void stat_Output_AllBmass(void); -void Output_AllCellAvgBmass(const char * filename); -void Output_AllCellAvgMort(const char* fileName); -void stat_Output_Seed_Dispersal(const char * filename, const char sep, - Bool makeHeader); -void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, - StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, - StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); -void stat_free_mem(void); -void _make_header_with_std( char *buf); - /* Functions from sxw.c */ SXW_t* getSXW(void); SXW_resourceType* getSXWResources(void); @@ -148,6 +132,8 @@ static void printGeneralInfo(void); static void _init_grid_files(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); static void allocate_gridCells(int rows, int cols); +static void Output_AllCellAvgBmass(const char* filename); +static void Output_AllCellAvgMort(const char* filename); static void allocate_accumulators(void); static void _read_disturbances_in(void); static void _read_soils_in(void); @@ -1302,7 +1288,7 @@ void Output_AllCellAvgBmass(const char * filename){ load_cell(0, 0); if(BmassFlags.header){ - _make_header_with_std(buf); + make_header_with_std(buf); fprintf(file, "%s", buf); } diff --git a/ST_initialization.c b/ST_initialization.c index c35385e8..53925ea4 100644 --- a/ST_initialization.c +++ b/ST_initialization.c @@ -29,6 +29,7 @@ #include "myMemory.h" #include "filefuncs.h" #include "ST_progressBar.h" +#include "ST_stats.h" /********** Local functions. These should all be treated as private. *************/ static void _run_spinup(void); @@ -76,9 +77,6 @@ void parm_Initialize(void); void Plot_Initialize(void); void copy_rgroup(const GroupType* src, GroupType* dest); void copy_species(const SpeciesType* src, SpeciesType* dest); -void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, - StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, - StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); /* Initializes the plot with whichever method you have specified with initializationMethod. This function takes care of EVERYTHING involved with initialization. diff --git a/ST_main.c b/ST_main.c index 876b1391..4a22c5ea 100644 --- a/ST_main.c +++ b/ST_main.c @@ -33,6 +33,7 @@ #include "sw_src/SW_Output_outtext.h" #include "sw_src/SW_Output_outarray.h" #include "sw_src/rands.h" +#include "ST_stats.h" #include "ST_initialization.h" #include "ST_progressBar.h" #include "ST_seedDispersal.h" @@ -63,13 +64,6 @@ extern Bool* _SomeKillage; void output_Bmass_Yearly( Int year ); void output_Mort_Yearly( void ); - void stat_Collect( Int year ) ; - void stat_Collect_GMort ( void ) ; - void stat_Collect_SMort ( void ) ; - - void stat_Output_AllMorts( void) ; - void stat_Output_AllBmass(void) ; - void _kill_annuals(void); void _kill_extra_growth(void); void _kill_maxage(void); diff --git a/ST_stats.c b/ST_stats.c index f6767477..3669f862 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -26,73 +26,23 @@ #include "myMemory.h" #include "sw_src/SW_Site.h" #include "ST_structs.h" -#include "ST_stats.h" +#include "ST_stats.h" // Contains most of the function declarations. #include "ST_initialization.h" #include "ST_seedDispersal.h" #include "sxw.h" - extern SW_SITE SW_Site; - -/************ External Variable Declarations ***************/ -/***********************************************************/ #include "ST_globals.h" -/******** Modular External Function Declarations ***********/ -/* -- truly global functions are declared in functions.h --*/ -/***********************************************************/ - - -/*------------------------------------------------------*/ -/* Modular functions only used on one or two specific */ -/* places; that is, they are not generally useful */ -/* (like C++ friend functions) but have to be declared. */ - void stat_Collect( Int year ) ; - void stat_Collect_GMort ( void ) ; - void stat_Collect_SMort ( void ) ; - void stat_Output_YrMorts( void ) ; - void stat_Output_AllMorts( void) ; - void stat_Output_AllBmass(void) ; - - //Adding below two functions for creating grid cells avg values output file - void stat_Output_AllBmassAvg(void); - void stat_Output_AllCellAvgBmass(const char * filename); - void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool makeHeader); - void stat_free_mem( void ); - - void stat_Load_Accumulators( int cell, int year ); //these accumulators were added to use in the gridded option... there overall purpose is to save/load data to allow steppe to output correctly when running multiple grid cells - void stat_Save_Accumulators( int cell, int year ); - void stat_Free_Accumulators( void ); - void stat_Init_Accumulators( void ); - - void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, - StatType* newGpr, StatType* newGmort, StatType* newGestab, StatType* newSpp, StatType* newIndv, - StatType* newSmort, StatType* newSestab, StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); - -/************************ Local Structure Defs *************/ -/***********************************************************/ +/* ----------------- Local Variables --------------------- */ StatType *_Dist, *_Ppt, *_Temp, *_Grp, *_Gsize, *_Gpr, *_Gmort, *_Gestab, *_Spp, *_Indv, *_Smort, *_Sestab, *_Sreceived; -accumulators_grid_st *grid_Stat; - FireStatsType *_Gwf; -GridStatsType _Dist_grid_cell, _Ppt_grid_cell, _Temp_grid_cell, - *_Grp_grid_cell, *_Gsize_grid_cell, *_Gpr_grid_cell,*_Gwf_grid_cell,*_Gpf_grid_cell, *_Gmort_grid_cell, *_Gestab_grid_cell, - *_Spp_grid_cell, *_Indv_grid_cell, *_Smort_grid_cell, *_Sestab_grid_cell, *_Sreceived_grid_cell; - /*************** Local Function Declarations ***************/ -/***********************************************************/ static void _init( void); static RealF _get_avg( struct accumulators_st *p); static RealF _get_std( struct accumulators_st *p); -//Adding below three functions for copying grid cell values,calculating avg and SD,these values will be used in grid cells avg output file -static void copyStruct(RealF val,RealF std_val,struct accumulators_grid_cell_st *p ); -static RealF _get_gridcell_avg( struct accumulators_grid_cell_st *p); -static int _get_gridcell_sum( struct accumulators_grid_cell_st *p); -static RealF _get_gridcell_std( struct accumulators_grid_cell_st *p); -static void _make_header( char *buf); -void _make_header_with_std( char *buf); /* I'm making this a macro because it gets called a lot, but * note that the syntax checker is obviated, so make sure @@ -203,88 +153,6 @@ static void _init( void) { SppIndex sp; GrpIndex rg; -// Memory allocation for local structures that will hold grid cells values for calculating avg - if (UseGrid) - { - - if (BmassFlags.dist) - _Dist_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, - sizeof(struct accumulators_grid_cell_st), - "_stat_init(Dist)"); - if (BmassFlags.ppt) - _Ppt_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, - sizeof(struct accumulators_grid_cell_st), - "_stat_init(PPT)"); - if (BmassFlags.tmp) - _Temp_grid_cell.s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, - sizeof(struct accumulators_grid_cell_st), - "_stat_init(Temp)"); - - if (BmassFlags.grpb) - { - _Grp_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Grp)"); - ForEachGroup(rg) - _Grp_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Grp[rg].s)"); - - if (BmassFlags.size) - { - _Gsize_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(GSize)"); - ForEachGroup(rg) - _Gsize_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(GSize[rg].s)"); - } - if (BmassFlags.pr) - { - _Gpr_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpr)"); - ForEachGroup(rg) - _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpr[rg].s)"); - } - if (BmassFlags.wildfire) - { - _Gpr_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gwf)"); - ForEachGroup(rg) - _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gwf[rg].s)"); - } - if (BmassFlags.prescribedfire) - { - _Gpr_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals->grpCount, sizeof(struct stat_grid_cell_st), "_stat_init(Gpf)"); - ForEachGroup(rg) - _Gpr_grid_cell[rg].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Gpf[rg].s)"); - } - } - - if (BmassFlags.sppb) - { - _Spp_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals->sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Spp)"); - ForEachSpecies(sp) - _Spp_grid_cell[sp].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Spp[sp].s)"); - - if (BmassFlags.indv) - { - _Indv_grid_cell = (struct stat_grid_cell_st *) - Mem_Calloc( Globals->sppCount, sizeof(struct stat_grid_cell_st), "_stat_init(Indv)"); - ForEachSpecies(sp) - _Indv_grid_cell[sp].s = (struct accumulators_grid_cell_st *) - Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_grid_cell_st), "_stat_init(Indv[sp].s)"); - } - } - - } - if (BmassFlags.dist) { _Dist = (StatType*) Mem_Calloc(1, sizeof(StatType), "_stat_init(Dist)"); _Dist->s = (struct accumulators_st *) @@ -458,253 +326,6 @@ static void _init( void) { } } -/***********************************************************/ -void stat_Init_Accumulators( void ) { - //allocates memory for all of the grid accumulators - grid_Stat = Mem_Calloc(SuperGlobals.nCells, sizeof(accumulators_grid_st), "stat_Init_Accumulators()"); - - int i, j; - for( i = 0; i < SuperGlobals.nCells; i++) { - if (BmassFlags.dist) grid_Stat[i].dist = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.ppt) grid_Stat[i].ppt = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.tmp) grid_Stat[i].temp = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - - if (BmassFlags.grpb) { - grid_Stat[i].grp1 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); // gave grp and gpr numbers attached to them so I wouldn't mix them up lol... bad (confusing) variable names on part of the original creator. - if (BmassFlags.size) grid_Stat[i].gsize = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.pr) grid_Stat[i].gpr2 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if (BmassFlags.wildfire) grid_Stat[i].gwf2 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if (BmassFlags.prescribedfire) grid_Stat[i].gpf2 = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - } - if (MortFlags.group) { - grid_Stat[i].gmort = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - grid_Stat[i].gestab = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - GrpIndex gp; - ForEachGroup(gp) { - grid_Stat[i].gmort[gp] = Mem_Calloc(GrpMaxAge(gp), sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - grid_Stat[i].gestab[gp] = Mem_Calloc(1, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - } - } - if(BmassFlags.sppb) { - grid_Stat[i].spp = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - if(BmassFlags.indv) grid_Stat[i].indv = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - } - if (MortFlags.species) { - grid_Stat[i].smort = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - grid_Stat[i].sestab = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - SppIndex sp; - ForEachSpecies(sp) { - grid_Stat[i].smort[sp] = Mem_Calloc(SppMaxAge(sp), sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - grid_Stat[i].sestab[sp] = Mem_Calloc(1, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - } - } - - if(UseSeedDispersal && UseGrid) - grid_Stat[i].sreceived = Mem_Calloc(SuperGlobals.runModelYears, sizeof(struct accumulators_st*), "stat_Init_Accumulators()"); - - - for( j = 0; j < SuperGlobals.runModelYears; j++) { - if (BmassFlags.grpb) { - grid_Stat[i].grp1[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.size) grid_Stat[i].gsize[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.pr) grid_Stat[i].gpr2[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.wildfire) grid_Stat[i].gwf2[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if (BmassFlags.prescribedfire) grid_Stat[i].gpf2[j] = Mem_Calloc(Globals->grpCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - } - if(BmassFlags.sppb) { - grid_Stat[i].spp[j] = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - if(BmassFlags.indv) grid_Stat[i].indv[j] = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - } - if(UseSeedDispersal && UseGrid) - grid_Stat[i].sreceived[j] = Mem_Calloc(Globals->sppCount, sizeof(struct accumulators_st), "stat_Init_Accumulators()"); - } - } -} - -/***********************************************************/ -void stat_Load_Accumulators(int cell, int year) { - //loads the accumulators for the cell at the given year - - if (firsttime) { - firsttime = FALSE; - _init(); - } - IntS age; - int yr; - yr = year - 1; - - if(MortFlags.species) { - SppIndex sp; - - ForEachSpecies(sp) { - if ( !Species[sp]->use_me) continue; - _copy_over(&_Sestab[sp].s[0], &grid_Stat[cell].sestab[sp][0]); - IntS age; - for (age=0; age < SppMaxAge(sp); age++) - _copy_over(&_Smort[sp].s[age], &grid_Stat[cell].smort[sp][age]); - } - } - if(MortFlags.group) { - GrpIndex rg; - - ForEachGroup(rg) { - if (!RGroup[rg]->use_me) continue; - _copy_over(&_Gestab[rg].s[0], &grid_Stat[cell].gestab[rg][0]); - for (age=0; age < GrpMaxAge(rg); age++) - _copy_over(&_Gmort[rg].s[age], &grid_Stat[cell].gmort[rg][age]); - } - } - - if (BmassFlags.tmp) _copy_over(&_Temp->s[yr], &grid_Stat[cell].temp[yr]); - if (BmassFlags.ppt) _copy_over(&_Ppt->s[yr], &grid_Stat[cell].ppt[yr]); - if (BmassFlags.dist) _copy_over(&_Dist->s[yr], &grid_Stat[cell].dist[yr]); - - if(BmassFlags.grpb) { - GrpIndex c; - ForEachGroup(c) { - _copy_over(&_Grp[c].s[yr], &grid_Stat[cell].grp1[yr][c]); - if (BmassFlags.size) _copy_over(&_Gsize[c].s[yr], &grid_Stat[cell].gsize[yr][c]); - if (BmassFlags.pr) _copy_over(&_Gpr[c].s[yr], &grid_Stat[cell].gpr2[yr][c]); - } - } - - if(BmassFlags.sppb) { - SppIndex s; - ForEachSpecies(s) { - _copy_over(&_Spp[s].s[yr], &grid_Stat[cell].spp[yr][s]); - if (BmassFlags.indv) _copy_over(&_Indv[s].s[yr], &grid_Stat[cell].indv[yr][s]); - } - } - - if(UseGrid && UseSeedDispersal) { - SppIndex s; - ForEachSpecies(s) - _copy_over(&_Sreceived[s].s[yr], &grid_Stat[cell].sreceived[yr][s]); - } -} - -/***********************************************************/ -void stat_Save_Accumulators(int cell, int year) { - //saves the accumulators for the cell at the given year - - if (firsttime) { - firsttime = FALSE; - _init(); - } - IntS age; - int yr; - yr = year - 1; - - if(MortFlags.species) { - SppIndex sp; - - ForEachSpecies(sp) { - if ( !Species[sp]->use_me) continue; - _copy_over(&grid_Stat[cell].sestab[sp][0], &_Sestab[sp].s[0]); - for (age=0; age < SppMaxAge(sp); age++) - _copy_over(&grid_Stat[cell].smort[sp][age], &_Smort[sp].s[age]); - } - } - if(MortFlags.group) { - GrpIndex rg; - - ForEachGroup(rg) { - if (!RGroup[rg]->use_me) continue; - _copy_over(&grid_Stat[cell].gestab[rg][0], &_Gestab[rg].s[0]); - for (age=0; age < GrpMaxAge(rg); age++) - _copy_over(&grid_Stat[cell].gmort[rg][age], &_Gmort[rg].s[age]); - } - } - - if (BmassFlags.tmp) _copy_over(&grid_Stat[cell].temp[yr], &_Temp->s[yr]); - if (BmassFlags.ppt) _copy_over(&grid_Stat[cell].ppt[yr], &_Ppt->s[yr]); - if (BmassFlags.dist) _copy_over(&grid_Stat[cell].dist[yr], &_Dist->s[yr]); - - if(BmassFlags.grpb) { - GrpIndex c; - ForEachGroup(c) { - _copy_over(&grid_Stat[cell].grp1[yr][c], &_Grp[c].s[yr]); - if (BmassFlags.size) _copy_over(&grid_Stat[cell].gsize[yr][c], &_Gsize[c].s[yr]); - if (BmassFlags.pr) _copy_over(&grid_Stat[cell].gpr2[yr][c], &_Gpr[c].s[yr]); - } - } - - if(BmassFlags.sppb) { - SppIndex s; - ForEachSpecies(s) { - _copy_over(&grid_Stat[cell].spp[yr][s], &_Spp[s].s[yr]); - if (BmassFlags.indv) _copy_over(&grid_Stat[cell].indv[yr][s], &_Indv[s].s[yr]); - } - } - - if(UseGrid && UseSeedDispersal) { - SppIndex s; - ForEachSpecies(s) - _copy_over(&grid_Stat[cell].sreceived[yr][s], &_Sreceived[s].s[yr]); - } - -} - -/***********************************************************/ -void stat_Free_Accumulators( void ) { - //frees all the memory allocated in stat_init_Accumulators() - - int i, j; - for( i = 0; i < SuperGlobals.nCells; i++) { - for( j = 0; j < SuperGlobals.runModelYears; j++) { - if(BmassFlags.grpb) { - Mem_Free(grid_Stat[i].grp1[j]); - if (BmassFlags.size) Mem_Free(grid_Stat[i].gsize[j]); - if (BmassFlags.pr) Mem_Free(grid_Stat[i].gpr2[j]); - if (BmassFlags.wildfire) Mem_Free(grid_Stat[i].gwf2[j]); - if (BmassFlags.prescribedfire) Mem_Free(grid_Stat[i].gpf2[j]); - } - if(BmassFlags.sppb) { - Mem_Free(grid_Stat[i].spp[j]); - if(BmassFlags.indv) Mem_Free(grid_Stat[i].indv[j]); - } - if(UseSeedDispersal && UseGrid) - Mem_Free(grid_Stat[i].sreceived[j]); - } - - if (BmassFlags.dist) Mem_Free(grid_Stat[i].dist); - if (BmassFlags.ppt) Mem_Free(grid_Stat[i].ppt); - if (BmassFlags.tmp) Mem_Free(grid_Stat[i].temp); - - if(BmassFlags.grpb) { - Mem_Free(grid_Stat[i].grp1);// gave grp and gpr numbers attached to them so I wouldn't mix them up lol... bad (confusing) variable names on part of the original creator. - if (BmassFlags.size) Mem_Free(grid_Stat[i].gsize); - if (BmassFlags.size) Mem_Free(grid_Stat[i].gpr2); - } - if (MortFlags.group) { - GrpIndex gp; - ForEachGroup(gp) { - Mem_Free(grid_Stat[i].gmort[gp]); - Mem_Free(grid_Stat[i].gestab[gp]); - } - Mem_Free(grid_Stat[i].gmort); - Mem_Free(grid_Stat[i].gestab); - } - if(BmassFlags.sppb) { - Mem_Free(grid_Stat[i].spp); - if(BmassFlags.indv) Mem_Free(grid_Stat[i].indv); - } - if (MortFlags.species) { - SppIndex sp; - ForEachSpecies(sp) { - Mem_Free(grid_Stat[i].smort[sp]); - Mem_Free(grid_Stat[i].sestab[sp]); - } - Mem_Free(grid_Stat[i].smort); - Mem_Free(grid_Stat[i].sestab); - } - if(UseSeedDispersal && UseGrid) - Mem_Free(grid_Stat[i].sreceived); - } - Mem_Free(grid_Stat); - stat_free_mem(); -} - /* Shallow copies StatType and FireStatsType pointers to the local pointers. This is intended to be used with gridded mode to load in a given cell */ void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, @@ -963,247 +584,6 @@ void stat_Output_AllMorts( void) { CloseFile(&f); } - -//This function will create individual grid cell output file and copy values to calculate for calculating grid cell avg values -/***********************************************************/ -void stat_Output_AllBmassAvg() { - char buf[1024], tbuf[80], sep = BmassFlags.sep; - IntS yr; - GrpIndex rg; - SppIndex sp; - FILE *f; - - if (!BmassFlags.summary) return; - - f = OpenFile( Parm_name( F_BMassAvg), "w"); - - buf[0]='\0'; - - if (BmassFlags.header) { - _make_header(buf); - fprintf(f, "%s", buf); - } - - for( yr=1; yr<= SuperGlobals.runModelYears; yr++) { - *buf = '\0'; - if (BmassFlags.yr) - sprintf(buf, "%d%c", yr, sep); - - if (BmassFlags.dist) { - sprintf(tbuf, "%ld%c", _Dist->s[yr-1].nobs, sep); - _Dist_grid_cell.s[yr-1].nobs = _Dist->s[yr-1].nobs; - strcat(buf, tbuf); - } - - if (BmassFlags.ppt) - { - RealF avg = _get_avg(&_Ppt->s[yr - 1]); - RealF std = _get_std(&_Ppt->s[yr - 1]); - sprintf(tbuf, "%f%c%f%c", avg, sep, std, sep); - copyStruct(avg, std, &_Ppt_grid_cell.s[yr - 1]); - strcat(buf, tbuf); - } - - if (BmassFlags.pclass) - { - sprintf(tbuf, "\"NA\"%c", sep); - strcat(buf, tbuf); - } - - if (BmassFlags.tmp) - { - RealF avg = _get_avg(&_Temp->s[yr - 1]); - RealF std = _get_std(&_Temp->s[yr - 1]); - sprintf(tbuf, "%f%c%f%c", avg, sep, std, sep); - copyStruct(avg,std, &_Temp_grid_cell.s[yr - 1]); - strcat(buf, tbuf); - } - - if (BmassFlags.grpb) - { - ForEachGroup(rg) - { - RealF avg = _get_avg(&_Grp[rg].s[yr - 1]); - sprintf(tbuf, "%f%c", avg, sep); - copyStruct(avg,0.0, &_Grp_grid_cell[rg].s[yr - 1]); - strcat(buf, tbuf); - - if (BmassFlags.size) - { - RealF sizeAvg = _get_avg(&_Gsize[rg].s[yr - 1]); - sprintf(tbuf, "%f%c",sizeAvg , sep); - copyStruct(sizeAvg,0.0,&_Gsize_grid_cell[rg].s[yr - 1]); - strcat(buf, tbuf); - } - - if (BmassFlags.pr) - { - RealF prAvg = _get_avg(&_Gpr[rg].s[yr - 1]); - RealF std = _get_std(&_Gpr[rg].s[yr - 1]); - sprintf(tbuf, "%f%c%f%c", prAvg, sep,std , sep); - copyStruct(prAvg,std,&_Gpr_grid_cell[rg].s[yr - 1]); - strcat(buf, tbuf); - } - if (BmassFlags.wildfire) - { - double wfsum = _Gwf->wildfire[yr-1]; - sprintf(tbuf, "%f%c", wfsum, sep); - strcat(buf, tbuf); - } - if (BmassFlags.prescribedfire) - { - double pfsum = _Gwf->prescribedFire[rg][yr-1]; - sprintf(tbuf, "%f%c", pfsum, sep); - strcat(buf, tbuf); - } - } - } - - - if (BmassFlags.sppb) - { - ForEachSpecies(sp) - { - RealF spAvg = _get_avg(&_Spp[sp].s[yr - 1]); - sprintf(tbuf, "%f%c", spAvg, sep); - copyStruct(spAvg,0.0,&_Spp_grid_cell[sp].s[yr - 1]); - strcat(buf, tbuf); - - if (BmassFlags.indv) - { - RealF indvAvg = _get_avg(&_Indv[sp].s[yr - 1]); - sprintf(tbuf, "%f%c", indvAvg, sep); - copyStruct(indvAvg,0.0,&_Indv_grid_cell[sp].s[yr - 1]); - strcat(buf, tbuf); - } - - } - } - - fprintf( f, "%s\n", buf); - } /* end of foreach year */ - CloseFile(&f); - -} - -//This function will create grid cell avg values output file -void stat_Output_AllCellAvgBmass(const char * filename) -{ - - char buf[1024], tbuf[80], sep = BmassFlags.sep; - IntS yr; - GrpIndex rg; - SppIndex sp; - FILE *f; - - if (!BmassFlags.summary) - return; - - f = OpenFile(filename, "w"); - - buf[0] = '\0'; - - if (BmassFlags.header) - { - _make_header(buf); - fprintf(f, "%s", buf); - } - - for (yr = 1; yr <= SuperGlobals.runModelYears; yr++) - { - - *buf = '\0'; - if (BmassFlags.yr) - sprintf(buf, "%d%c", yr, sep); - - if (BmassFlags.dist) - { - sprintf(tbuf, "%ld%c", _Dist_grid_cell.s[yr - 1].nobs, sep); - strcat(buf, tbuf); - } - - if (BmassFlags.ppt) - { - sprintf(tbuf, "%f%c%f%c", - _get_gridcell_avg(&_Ppt_grid_cell.s[yr - 1]), sep, - _get_gridcell_std(&_Ppt_grid_cell.s[yr - 1]), sep); - strcat(buf, tbuf); - } - - if (BmassFlags.pclass) - { - sprintf(tbuf, "\"NA\"%c", sep); - strcat(buf, tbuf); - } - - if (BmassFlags.tmp) - { - sprintf(tbuf, "%f%c%f%c", - _get_gridcell_avg(&_Temp_grid_cell.s[yr - 1]), sep, - _get_gridcell_std(&_Temp_grid_cell.s[yr - 1]), sep); - strcat(buf, tbuf); - } - - if (BmassFlags.grpb) - { - ForEachGroup(rg) - { - sprintf(tbuf, "%f%c", _get_gridcell_avg(&_Grp_grid_cell[rg].s[yr - 1]), sep); - strcat(buf, tbuf); - - if (BmassFlags.size) - { - sprintf(tbuf, "%f%c", _get_gridcell_avg(&_Gsize_grid_cell[rg].s[yr - 1]), sep); - strcat(buf, tbuf); - } - - if (BmassFlags.pr) - { - sprintf(tbuf, "%f%c%f%c", - _get_gridcell_avg(&_Gpr_grid_cell[rg].s[yr - 1]), sep, - _get_gridcell_std(&_Gpr_grid_cell[rg].s[yr - 1]), sep); - strcat(buf, tbuf); - } - if (BmassFlags.wildfire) - { - sprintf(tbuf, "%d%c", _get_gridcell_sum(&_Gsize_grid_cell[rg].s[yr - 1]), sep); - strcat(buf, tbuf); - } - if (BmassFlags.prescribedfire) - { - sprintf(tbuf, "%f%c", _get_gridcell_avg(&_Gsize_grid_cell[rg].s[yr - 1]), sep); - strcat(buf, tbuf); - } - } - } - - if (BmassFlags.sppb) - { - ForEachSpecies(sp) - { - sprintf(tbuf, "%f%c",_get_gridcell_avg( &_Spp_grid_cell[sp].s[yr-1]), sep); - strcat( buf, tbuf); - - if (BmassFlags.indv) - { - sprintf(tbuf, "%f%c", _get_gridcell_avg( &_Indv_grid_cell[sp].s[yr-1]), sep); - strcat( buf, tbuf); - } - - } - } - - fprintf(f, "%s\n", buf); - } /* end of foreach year */ - CloseFile(&f); - -} - - - - - - /***********************************************************/ void stat_Output_AllBmass(void) { @@ -1220,7 +600,7 @@ void stat_Output_AllBmass(void) { buf[0]='\0'; if (BmassFlags.header) { - _make_header_with_std(buf); + make_header_with_std(buf); fprintf(f, "%s", buf); } @@ -1372,45 +752,8 @@ static RealF _get_std(struct accumulators_st *p) return p->sd; } - - -static void copyStruct(RealF val,RealF std_val,struct accumulators_grid_cell_st *p) -{ - p->sum = p->sum + val; - p->sum_std = p->sum_std + std_val; -} - -/***********************************************************/ -static RealF _get_gridcell_avg(struct accumulators_grid_cell_st *p) -{ - - if (SuperGlobals.nCells == 0) - return 0.0; - RealF avg = (RealF) (p->sum / (double) SuperGlobals.nCells); - return avg; -} -static int _get_gridcell_sum(struct accumulators_grid_cell_st *p) -{ - - if (SuperGlobals.nCells == 0) - return 0; - int sum = (RealF) (p->sum); - return sum; -} - - -/***********************************************************/ -static RealF _get_gridcell_std(struct accumulators_grid_cell_st *p) -{ - if (SuperGlobals.nCells == 0) - return 0.0; - RealF avg = (RealF) (p->sum_std / (double) SuperGlobals.nCells); - return avg; -} - - /***********************************************************/ -void _make_header_with_std( char *buf) { +void make_header_with_std( char *buf) { char **fields; char tbuf[80]; @@ -1418,10 +761,10 @@ void _make_header_with_std( char *buf) { SppIndex sp; Int i, fc=0; - fields = (char **)Mem_Calloc(MAX_OUTFIELDS * 2, sizeof(char *), "_make_header_with_std"); + fields = (char **)Mem_Calloc(MAX_OUTFIELDS * 2, sizeof(char *), "make_header_with_std"); for (i = 0; i < MAX_OUTFIELDS * 2; i++) { - fields[i] = (char *)Mem_Calloc(MAX_FIELDLEN + 1, sizeof(char), "_make_header_with_std"); + fields[i] = (char *)Mem_Calloc(MAX_FIELDLEN + 1, sizeof(char), "make_header_with_std"); } /* Set up headers */ @@ -1495,7 +838,7 @@ void _make_header_with_std( char *buf) { } /***********************************************************/ -static void _make_header( char *buf) { +void make_header( char *buf) { char **fields; char tbuf[80]; @@ -1503,10 +846,10 @@ static void _make_header( char *buf) { SppIndex sp; Int i, fc=0; - fields = (char **)Mem_Calloc(MAX_OUTFIELDS * 2, sizeof(char *), "_make_header"); + fields = (char **)Mem_Calloc(MAX_OUTFIELDS * 2, sizeof(char *), "make_header"); for (i = 0; i < MAX_OUTFIELDS * 2; i++) { - fields[i] = (char *)Mem_Calloc(MAX_FIELDLEN + 1, sizeof(char), "_make_header"); + fields[i] = (char *)Mem_Calloc(MAX_FIELDLEN + 1, sizeof(char), "make_header"); } /* Set up headers */ diff --git a/ST_stats.h b/ST_stats.h index 4e19174a..ce6a1fec 100644 --- a/ST_stats.h +++ b/ST_stats.h @@ -8,6 +8,7 @@ #ifndef STATS_STRUCT_DEF #define STATS_STRUCT_DEF +#include "ST_defines.h" /* Basic struct that holds average, sum of differences squared, standard deviation * and number of entries. This is enough information to calculate running values without @@ -24,26 +25,26 @@ struct stat_st { struct accumulators_st *s; } typedef StatType; -typedef struct { - struct accumulators_st *dist, *temp, *ppt, **grp1, **gsize, **gpr2, **gwf2, **gpf2, - **gmort, **gestab, **spp, **indv, **smort, **sestab, **sreceived; -} accumulators_grid_st; - /* Struct for wildfire and prescribed fire stats. */ struct fire_st { int *wildfire; int **prescribedFire; } typedef FireStatsType; -// Structure for holding sum values of all the grid cells -struct accumulators_grid_cell_st { - double sum, sum_std; - unsigned long nobs; -}; - -struct stat_grid_cell_st { - char *name; /* array of ptrs to names in RGroup & Species */ - struct accumulators_grid_cell_st *s; /* array of holding all the years values */ -} typedef GridStatsType; +/*----------------------- Exported Functions ---------------------------------- */ +void stat_Collect( Int year ) ; +void stat_Collect_GMort ( void ) ; +void stat_Collect_SMort ( void ) ; +void stat_Output_YrMorts( void ) ; +void stat_Output_AllMorts( void) ; +void stat_Output_AllBmass(void) ; +void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool makeHeader); +void stat_free_mem( void ); +void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, + StatType* newGsize, StatType* newGpr, StatType* newGmort, StatType* newGestab, + StatType* newSpp, StatType* newIndv, StatType* newSmort, StatType* newSestab, + StatType* newSrecieved, FireStatsType* newGwf, Bool firstTime); +void make_header( char *buf); +void make_header_with_std( char *buf); #endif \ No newline at end of file From 8fa4da7a9b97f079be95c45fbfd3c220ef4babac Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 9 Aug 2019 14:10:21 -0600 Subject: [PATCH 146/167] Added error check to _read_soils_in previously, if grid_soils.csv didn't contain sufficient entries, the program would loop infinitely. Now the program halts and prints out a log error. --- ST_grid.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 85af041e..d76a14d2 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -926,6 +926,7 @@ static void _read_soils_in(void){ SoilType* destSoil; char buf[4096]; Bool copyAnotherCell; // TRUE if we need to copy another cell + Bool entryFound; /* tempSoil is allocated the maximum amount of memory that a SoilType could need. It will serve to read in parameters. */ @@ -955,8 +956,9 @@ static void _read_soils_in(void){ tempSoil.num_layers = 0; copyAnotherCell = FALSE; - do { - GetALine(f, buf); + entryFound = FALSE; + entriesRead = 1; // This is just to get us in the loop. + while (entriesRead != 0 && GetALine(f, buf)) { /* If the user defined all columns except copy_cell. */ entriesRead = sscanf(buf, "%d,,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%s", &cellNum, &layerRead, &tempSoil.depth[tempSoil.num_layers], @@ -990,7 +992,13 @@ static void _read_soils_in(void){ if(entriesRead > 2){ tempSoil.num_layers++; } - } while (entriesRead != 0); + + entryFound = TRUE; + } + + if(!entryFound){ + LogError(logfp, LOGFATAL, "Not enough soils specified in %s.", grid_files[GRID_FILE_SOILS]); + } if(copyAnotherCell){ if(cellToCopy > i){ From c8b009466f93b849dbca1b07a4607fe4e26611ab Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Mon, 12 Aug 2019 11:01:52 -0600 Subject: [PATCH 147/167] Removed spaces between grid_soils.csv entries (issue #374) To accomplish this I restructured _read_soils_in and added a new function. _read_soil_line takes in a string, a destination cell, and a layer number. It returns -2 when the layer is successfully read in, -1 if it fails, and a value > -1 when the user wants to copy another cell. _read_soils_in uses this function to determine it's behavior. --- ST_grid.c | 134 ++++++++++-------- ST_grid.h | 6 + .../Grid_Inputs/grid_soils.csv | 89 ++++++------ 3 files changed, 122 insertions(+), 107 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index d76a14d2..f34e55c0 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -137,6 +137,7 @@ static void Output_AllCellAvgMort(const char* filename); static void allocate_accumulators(void); static void _read_disturbances_in(void); static void _read_soils_in(void); +static int _read_soil_line(char* buf, SoilType* destination, int layer); static void _read_init_species(void); static void _read_maxrgroupspecies(void); static void _read_grid_setup(void); @@ -921,12 +922,8 @@ static int _get_value_index(char* s, char seperator, int nSeperators) /* Read the grid_soils.csv file and assign values to all gridCells.mySoils variables. */ static void _read_soils_in(void){ - int i, row, col, entriesRead, cellNum, cellToCopy, - layerRead; - SoilType* destSoil; + int i, row, col, lineReadReturnValue; char buf[4096]; - Bool copyAnotherCell; // TRUE if we need to copy another cell - Bool entryFound; /* tempSoil is allocated the maximum amount of memory that a SoilType could need. It will serve to read in parameters. */ @@ -945,71 +942,48 @@ static void _read_soils_in(void){ tempSoil.trco_tree = Mem_Calloc(MAX_LAYERS, sizeof(RealF), "_read_soils_in: tempSoil"); FILE* f = OpenFile(grid_files[GRID_FILE_SOILS], "r"); - GetALine(f, buf); // Throw out the header line. + if(!GetALine(f, buf)){ // Throw out the header line. + LogError(logfp, LOGFATAL, "%s file empty.", grid_files[GRID_FILE_SOILS]); + } for(i = 0; i < grid_Cells; ++i){ row = i / grid_Cols; col = i % grid_Cols; - load_cell(row, col); - destSoil = &gridCells[row][col].mySoils; - - tempSoil.num_layers = 0; - copyAnotherCell = FALSE; - entryFound = FALSE; - entriesRead = 1; // This is just to get us in the loop. - while (entriesRead != 0 && GetALine(f, buf)) { - /* If the user defined all columns except copy_cell. */ - entriesRead = sscanf(buf, "%d,,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%s", - &cellNum, &layerRead, &tempSoil.depth[tempSoil.num_layers], - &tempSoil.matricd[tempSoil.num_layers], &tempSoil.gravel[tempSoil.num_layers], - &tempSoil.evco[tempSoil.num_layers], &tempSoil.trco_grass[tempSoil.num_layers], - &tempSoil.trco_shrub[tempSoil.num_layers], &tempSoil.trco_tree[tempSoil.num_layers], - &tempSoil.trco_forb[tempSoil.num_layers], &tempSoil.psand[tempSoil.num_layers], - &tempSoil.pclay[tempSoil.num_layers], &tempSoil.imperm[tempSoil.num_layers], - &tempSoil.soiltemp[tempSoil.num_layers], tempSoil.rootsFile); - /* If the user entered a cell to copy but also entered all parameters */ - if(entriesRead == 1){ - entriesRead = sscanf(buf, "%d,%d,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%s", - &cellNum, &cellToCopy, &layerRead, &tempSoil.depth[tempSoil.num_layers], - &tempSoil.matricd[tempSoil.num_layers], &tempSoil.gravel[tempSoil.num_layers], - &tempSoil.evco[tempSoil.num_layers], &tempSoil.trco_grass[tempSoil.num_layers], - &tempSoil.trco_shrub[tempSoil.num_layers], &tempSoil.trco_tree[tempSoil.num_layers], - &tempSoil.trco_forb[tempSoil.num_layers], &tempSoil.psand[tempSoil.num_layers], - &tempSoil.pclay[tempSoil.num_layers], &tempSoil.imperm[tempSoil.num_layers], - &tempSoil.soiltemp[tempSoil.num_layers], tempSoil.rootsFile); - } - - /* if the user only defined a cell to copy */ - if(entriesRead == 2){ - copyAnotherCell = TRUE; - /* Error checking. These are the only valid number of columns. */ - } else if(entriesRead != 0 && entriesRead != 15 && entriesRead != 16){ - LogError(logfp, LOGFATAL, "%s: Incorrect number of columns in grid soils file. (%d)", - grid_files[GRID_FILE_SOILS], entriesRead); - } - - if(entriesRead > 2){ - tempSoil.num_layers++; - } - entryFound = TRUE; - } - - if(!entryFound){ - LogError(logfp, LOGFATAL, "Not enough soils specified in %s.", grid_files[GRID_FILE_SOILS]); + if(!GetALine(f, buf)){ + LogError(logfp, LOGFATAL, "Too few lines in %s", grid_files[GRID_FILE_SOILS]); } - - if(copyAnotherCell){ - if(cellToCopy > i){ + lineReadReturnValue = _read_soil_line(buf, &tempSoil, 0); + if (lineReadReturnValue == SOIL_READ_FAILURE){ + LogError(logfp, LOGFATAL, "Error reading %s file.", grid_files[GRID_FILE_SOILS]); + } + /* If _read_soil_line didnt return SUCCESS or FAILURE, + it returned a cell number to copy. */ + else if (lineReadReturnValue != SOIL_READ_SUCCESS){ + if(lineReadReturnValue > i){ LogError(logfp, LOGFATAL, "%s: Attempted to copy values that have not been read yet.\n" "\tIf you want to copy a soil make sure you define the layers" "the FIRST time you use it.", grid_files[GRID_FILE_SOILS]); } - - _copy_soils(&gridCells[cellToCopy / grid_Cols][cellToCopy % grid_Cols].mySoils, destSoil); - } else { - _copy_soils(&tempSoil, destSoil); + _copy_soils(&gridCells[lineReadReturnValue / grid_Cols][lineReadReturnValue % grid_Cols].mySoils, &gridCells[row][col].mySoils); + } + /* If we get here we have successfully populated the first layer of soil. + Now we must populate the rest. */ + else { + for(int j = 1; j < tempSoil.num_layers; ++j){ + if(!GetALine(f, buf)){ + LogError(logfp, LOGFATAL, "Too few lines in %s", grid_files[GRID_FILE_SOILS]); + } + lineReadReturnValue = _read_soil_line(buf, &tempSoil, j); + if(lineReadReturnValue != SOIL_READ_SUCCESS){ + LogError(logfp, LOGFATAL, "Different behavior is specified between layers %d and %d of" + " cell %d in file %s. (Perhaps you specified a cell to copy in one" + " but not the other?)", j, j+1, i, grid_files[GRID_FILE_SOILS]); + } + } + /* And finally copy the temporary soil into the grid. */ + _copy_soils(&tempSoil, &gridCells[row][col].mySoils); } } @@ -1030,6 +1004,48 @@ static void _read_soils_in(void){ Mem_Free(tempSoil.psand); } +/* Reads a line of soil input from buf into destination. + + Param buf: line of soil input. + Param destination: SoilType struct to fill. + Param layer: layer number of destination to fill (0 indexed). + + Return: SOIL_READ_FAILURE if buf is incorrectly formatted. + SOIL_READ_SUCCESS if destination is populated correctly. + Otherwise returns the cell number that destination should copy. */ +static int _read_soil_line(char* buf, SoilType* destination, int layer){ + int entriesRead, cellToCopy, cellNum, layerRead; + entriesRead = sscanf(buf, "%d,,%d,%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%s", + &cellNum, &destination->num_layers, &layerRead, &destination->depth[layer], + &destination->matricd[layer], &destination->gravel[layer], + &destination->evco[layer], &destination->trco_grass[layer], + &destination->trco_shrub[layer], &destination->trco_tree[layer], + &destination->trco_forb[layer], &destination->psand[layer], + &destination->pclay[layer], &destination->imperm[layer], + &destination->soiltemp[layer], destination->rootsFile); + + if(cellNum > grid_Cells || layerRead > destination->num_layers){ + LogError(logfp, LOGFATAL, "%s: cells out of order or too many layers.", grid_files[GRID_FILE_SOILS]); + } + + /* If the user specified a cell to copy we will perform the copy, regardless + of whether or not they also entered parameters. */ + if(entriesRead == 1){ + entriesRead = sscanf(buf, "%d,%d", &cellNum, &cellToCopy); + if(entriesRead == 2){ + return cellToCopy; + } else { + return SOIL_READ_FAILURE; + } + } + + if(entriesRead == 16) { + return SOIL_READ_SUCCESS; + } else { + return SOIL_READ_FAILURE; + } +} + /* Copy one SoilType variable to another. param src: An allocated and assigned SoilType param dest: An unallocated SoilType diff --git a/ST_grid.h b/ST_grid.h index 233f994c..6aba8d6a 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -136,6 +136,12 @@ typedef enum N_GRID_FILES } File_Indices; +typedef enum +{ + SOIL_READ_SUCCESS = -2, + SOIL_READ_FAILURE = -1, +} Soil_Read_Return_Values; + /************************ Exported Variable Declarations **************************/ /* gridCells[i][j] denotes the cell at position (i,j) */ diff --git a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv index 2ad54a84..63bdafc4 100755 --- a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv @@ -1,48 +1,41 @@ -cell,copy_cell,layer,depth,matricd,gravel_content,evco,trco_grass,trco_shrub,trco_tree,trco_forb,sand,clay,imperm,soiltemp,sxw_roots -0,,1,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,sxwroots1.in -0,,2,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,sxwroots1.in -0,,3,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,sxwroots1.in -0,,4,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,sxwroots1.in -0,,5,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,sxwroots1.in -0,,6,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,sxwroots1.in -0,,7,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots1.in -0,,8,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots1.in -,,,,,,,,,,,,,,, -1,,1,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,sxwroots2.in -1,,2,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,sxwroots2.in -1,,3,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,sxwroots2.in -1,,4,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,sxwroots2.in -1,,5,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,sxwroots2.in -1,,6,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,sxwroots2.in -1,,7,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots2.in -1,,8,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots2.in -,,,,,,,,,,,,,,, -2,0,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -3,1,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -4,0,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -5,1,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -6,0,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -7,1,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -8,0,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -9,1,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -10,0,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -11,1,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -12,0,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -13,1,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -14,0,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -15,1,,,,,,,,,,,,,, -,,,,,,,,,,,,,,, -16,0,,,,,,,,,,,,,, +cell,copy_cell,num_layers,layer,depth,matricd,gravel_content,evco,trco_grass,trco_shrub,trco_tree,trco_forb,sand,clay,imperm,soiltemp,sxw_roots +0,,8,1,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,sxwroots1.in +0,,8,2,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,sxwroots1.in +0,,8,3,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,sxwroots1.in +0,,8,4,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,sxwroots1.in +0,,8,5,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,sxwroots1.in +0,,8,6,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,sxwroots1.in +0,,8,7,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots1.in +0,,8,8,150,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots1.in +1,,8,1,10,1.43,0,0.5,0.1,0.1,0.1,0.1,0.45,0.18,0,0.186,sxwroots2.in +1,,8,2,20,1.41,0,0.35,0.25,0.25,0.25,0.25,0.48,0.19,0,0.372,sxwroots2.in +1,,8,3,30,1.39,0,0.15,0.3,0.3,0.3,0.3,0.53,0.16,0,0.744,sxwroots2.in +1,,8,4,40,1.39,0,0,0.2,0.2,0.2,0.2,0.53,0.16,0,1.116,sxwroots2.in +1,,8,5,60,1.38,0,0,0.1,0.1,0.1,0.1,0.53,0.16,0,1.488,sxwroots2.in +1,,8,6,80,1.15,0,0,0.05,0.05,0.05,0.05,0.53,0.16,0,2.232,sxwroots2.in +1,,8,7,100,1.31,0,0,0,0,0,0,0.53,0.16,0,2.975,sxwroots2.in +1,,8,8,150,1.31,0,0,0,0,0,0,0.49,0.2,0,2.975,sxwroots2.in +2,0,,,,,,,,,,,,,,, +3,1,,,,,,,,,,,,,,, +4,0,,,,,,,,,,,,,,, +5,1,,,,,,,,,,,,,,, +6,0,,,,,,,,,,,,,,, +7,1,,,,,,,,,,,,,,, +8,0,,,,,,,,,,,,,,, +9,1,,,,,,,,,,,,,,, +10,0,,,,,,,,,,,,,,, +11,1,,,,,,,,,,,,,,, +12,0,,,,,,,,,,,,,,, +13,1,,,,,,,,,,,,,,, +14,0,,,,,,,,,,,,,,, +15,1,,,,,,,,,,,,,,, +16,0,,,,,,,,,,,,,,, +17,1,,,,,,,,,,,,,,, +18,0,,,,,,,,,,,,,,, +19,1,,,,,,,,,,,,,,, +20,0,,,,,,,,,,,,,,, +21,1,,,,,,,,,,,,,,, +22,0,,,,,,,,,,,,,,, +23,1,,,,,,,,,,,,,,, +24,0,,,,,,,,,,,,,,, +25,1,,,,,,,,,,,,,,, From 9b99edd8a59ce6cf16158c7b7afa0330bf43e1c4 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Thu, 15 Aug 2019 10:43:35 -0600 Subject: [PATCH 148/167] Addressing comments on PR #375 In the makefile I removed the commented out sxw_tester.o because the file is deprecated. However, I left the rule in for now in case we need the file in the future. In ST_environs.c I added a break statement to the default case of a switch. I also put parenthesis around Plot->disturb -1 to make it clearer that this is one clause. I removed the ternary because the first clause sufficed for setting Plot->pat_removed. --- ST_environs.c | 6 +++--- makefile | 2 -- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/ST_environs.c b/ST_environs.c index 78ee70b8..c26be8fd 100644 --- a/ST_environs.c +++ b/ST_environs.c @@ -257,7 +257,8 @@ static void _make_disturbance( void) { case NoDisturb: // Does nothing but prevent a compiler warning case LastDisturb: default: - Plot->disturbed = (Plot->disturbed) ? Plot->disturbed -1 : 0; + Plot->disturbed = (Plot->disturbed) ? (Plot->disturbed - 1) : 0; + break; } if (Plot->disturbed == 0) Plot->disturbance = NoDisturb; @@ -279,8 +280,7 @@ static void _make_disturbance( void) { event = (RandUni(&environs_rng) <= Globals->pat.occur) ? event : NoDisturb; if (event == NoDisturb) break; - Plot->pat_removed = (RandUni(&environs_rng) <= Globals->pat.removal) - ? TRUE : FALSE; + Plot->pat_removed = (RandUni(&environs_rng) <= Globals->pat.removal); Plot->disturbed = 0; break; case AntMound: diff --git a/makefile b/makefile index f0344ff6..56fc59ed 100644 --- a/makefile +++ b/makefile @@ -59,7 +59,6 @@ SRCS =\ $(Src)/ST_initialization.c\ $(Src)/ST_progressBar.c\ $(Src)/ST_seedDispersal.c - #$(Src)/sxw_tester.c EXOBJS =\ $(oDir)/sqlite-amalgamation/sqlite3.o\ @@ -105,7 +104,6 @@ EXOBJS =\ $(oDir)/ST_initialization.o\ $(oDir)/ST_progressBar.o\ $(oDir)/ST_seedDispersal.o - #$(oDir)/sxw_tester.o ALLOBJS = $(EXOBJS) ALLBIN = $(Bin)/stepwat From e27a4be28515268adc73b1584aef59c0d17d57b6 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Mon, 19 Aug 2019 14:42:44 -0600 Subject: [PATCH 149/167] Addressing comments on PR #375 Modified comments and removed print statements. --- ST_mortality.c | 5 +---- ST_resgroups.c | 4 ---- ST_species.c | 3 --- sxw_soilwat.c | 2 +- 4 files changed, 2 insertions(+), 12 deletions(-) diff --git a/ST_mortality.c b/ST_mortality.c index 7f29c325..953db5b1 100644 --- a/ST_mortality.c +++ b/ST_mortality.c @@ -345,8 +345,6 @@ void grazing_EndOfYear( void){ IntU grazingyr =0; g = RGroup[rg]; - //printf("inside grazing_EndOfYear() year=%d, rgroupName=%s, grazingfreq_startyr=%d, grazingfreq=%d, proportionGrazing=%f startYear=%d \n",Globals->currYear,g->name,g->grazingfreq_startyr,g->grazingfrq,g->proportion_grazing, RGroup[rg]->startyr); - if (Globals->currYear < RGroup[rg]->startyr) { /* Grazing cannot occur for an RGroup[rg] until the year that RGroup[rg] is turned on */ @@ -381,8 +379,7 @@ void grazing_EndOfYear( void){ { continue; } - //printf( "year=%d calling Species_Proportion_Grazing() rgroupName=%s, est_count =%d,grazingfreq_startyr=%d, grazingfreq=%d, proportionGrazing=%f \n",Globals->currYear,g->name,RGroup[rg]->est_count,g->grazingfreq_startyr,g->grazingfrq,g->proportion_grazing); - + /* Remove plant biomass to implement grazing using the proportion_grazing specified in inputs */ Species_Proportion_Grazing(RGroup[rg]->est_spp[i],RGroup[rg]->proportion_grazing ); } diff --git a/ST_resgroups.c b/ST_resgroups.c index ec492870..da7ff7de 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -651,7 +651,6 @@ void rgroup_Establish(void) { /* Establishment for species that belong to annual functional groups*/ if (Species[sp]->max_age == 1) { - //printf("Globals->currYear = %hu, call to _add_annuals sp=%d Species[sp]->lastyear_relsize : %.5f \n", Globals->currYear, sp, Species[sp]->lastyear_relsize); num_est = _add_annuals(rg, sp, Species[sp]->lastyear_relsize); // printf("g->seedbank annuals=%d \n",g->seedbank); } @@ -662,9 +661,6 @@ void rgroup_Establish(void) { } if (num_est) { - /* printf("%d %d %d %d\n", - Globals->currIter, Globals->currYear, sp, num_est); */ - Species_Add_Indiv(sp, num_est); species_Update_Estabs(sp, num_est); } diff --git a/ST_species.c b/ST_species.c index f6d4ee51..4e2b0203 100644 --- a/ST_species.c +++ b/ST_species.c @@ -543,10 +543,7 @@ void save_annual_species_relsize() { ForEachSpecies(sp) { if (Species[sp]->max_age == 1) { - //printf("Globals.currYear = %d, sp=%d , Species[sp]->relsize=%.5f ,old value lastyear_relsize : %.5f \n", Globals.currYear, sp, Species[sp]->relsize, Species[sp]->lastyear_relsize); Species[sp]->lastyear_relsize = getSpeciesRelsize(sp); - //Species[sp]->lastyear_relsize = 2; - //printf("Globals->currYear = %d, sp=%d new updated value lastyear_relsize : %.5f \n", Globals->currYear, sp, Species[sp]->lastyear_relsize); } } } diff --git a/sxw_soilwat.c b/sxw_soilwat.c index 67ecc77b..c319c701 100644 --- a/sxw_soilwat.c +++ b/sxw_soilwat.c @@ -141,7 +141,7 @@ static void _update_transp_coeff(void) { /*printf("* lyr=%d, group=%s(%d), type=%d, tl=%d, rootmax=%f, relsize2=%f, trco=%f\n", l, RGroup[g]->name, g, RGroup[g]->veg_prod_type, getNTranspLayers(RGroup[g]->veg_prod_type), - SXWResources->_roots_max[Ilg(l, g)], RGroup[g]->relsize, y->transp_coeff[SW_SHRUB]); + SXWResources->_roots_max[Ilg(l, g)], getRGroupRelsize(g), y->transp_coeff[SW_SHRUB]); */ } sum[SW_SHRUB] += y->transp_coeff[SW_SHRUB]; From 5c965a855dfcf58bb7309b63ebbb776b9c2bda46 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Wed, 28 Aug 2019 10:39:09 -0600 Subject: [PATCH 150/167] Addressing comments on PR #375 I removed two externed SOIWLAT2 variables that were unused, changed a few variables from type int to type Bool, and removed legacy arrays. --- ST_grid.c | 23 +++++------------------ 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index f34e55c0..0b6f2adc 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -47,18 +47,7 @@ char sd_Sep; int grid_Cells; -int UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans - -// these are grids to store the SOILWAT variables... also dynamically allocated/freed -SW_SOILWAT *grid_SW_Soilwat, *spinup_SW_Soilwat; -SW_SITE *grid_SW_Site, *spinup_SW_Site; -SW_VEGPROD *grid_SW_VegProd, *spinup_SW_VegProd; -SW_MODEL *grid_SW_Model, *spinup_SW_Model; - -// these two variables are used to store the soil/distubance inputs for each grid cell... also dynamically allocated/freed -SoilType *grid_Soils; - -Grid_SD_St **grid_SD; //for seed dispersal +Bool UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans /***************************** Externed variables **********************************/ /* Note that in an ideal world we wouldn't need to extern any variables because @@ -67,8 +56,6 @@ Grid_SD_St **grid_SD; //for seed dispersal // these are SOILWAT variables that we need... extern SW_SOILWAT SW_Soilwat; -extern SW_SITE SW_Site; -extern SW_VEGPROD SW_VegProd; extern SW_WEATHER SW_Weather; extern pcg32_random_t grid_rng; // Gridded mode's unique RNG. @@ -1211,13 +1198,13 @@ static void _read_grid_setup(void) allocate_gridCells(grid_Rows, grid_Cols); GetALine(f, buf); - i = sscanf(buf, "%d", &UseDisturbances); + i = sscanf(buf, "%u", &UseDisturbances); if (i != 1) LogError(logfp, LOGFATAL, "Invalid grid setup file (disturbances line wrong)"); GetALine(f, buf); - i = sscanf(buf, "%d", &UseSoils); + i = sscanf(buf, "%u", &UseSoils); if (i != 1) LogError(logfp, LOGFATAL, "Invalid grid setup file (soils line wrong)"); @@ -1264,12 +1251,12 @@ static void _read_grid_setup(void) } GetALine(f, buf); - if (sscanf(buf, "%d", &sd_DoOutput) != 1) + if (sscanf(buf, "%u", &sd_DoOutput) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: seed dispersal output line\n", grid_files[GRID_FILE_SETUP]); GetALine(f, buf); - if (sscanf(buf, "%d", &sd_MakeHeader) != 1) + if (sscanf(buf, "%u", &sd_MakeHeader) != 1) LogError(logfp, LOGFATAL, "Invalid %s file: seed dispersal make header line\n", grid_files[GRID_FILE_SETUP]); From 5b1b91901f1d12d39b50fb3c19751af28fefd4e5 Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 26 Sep 2019 11:25:19 -0600 Subject: [PATCH 151/167] Removed unused includes and fixed a typo Addressing comments made on pull request #375. --- ST_grid.c | 5 +---- ST_stats.c | 4 ---- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 0b6f2adc..56820139 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -26,11 +26,8 @@ /* INCLUDES / DEFINES */ /* --------------------------------------------------- */ #include -#include #include -#include #include -#include #include "ST_grid.h" #include "ST_steppe.h" #include "generic.h" @@ -439,7 +436,7 @@ static void _init_SXW_inputs(Bool init_SW, char *f_roots) } /* Read in the STEPWAT2 files and populate the grid. This only needs to be called once. - DEPENDENCYS: gridCells must be allocated first. */ + DEPENDENCIES: gridCells must be allocated first. */ static void _init_stepwat_inputs(void) { int i, j; // Used as indices in gridCells diff --git a/ST_stats.c b/ST_stats.c index 3669f862..6af88067 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -18,18 +18,14 @@ /* INCLUDES / DEFINES */ /* --------------------------------------------------- */ -#include #include #include #include "ST_steppe.h" #include "filefuncs.h" #include "myMemory.h" -#include "sw_src/SW_Site.h" #include "ST_structs.h" #include "ST_stats.h" // Contains most of the function declarations. -#include "ST_initialization.h" #include "ST_seedDispersal.h" -#include "sxw.h" #include "ST_globals.h" /* ----------------- Local Variables --------------------- */ From d3cb3fd4fccce2d88f75b909c533a7c3360514bc Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 26 Sep 2019 11:43:56 -0600 Subject: [PATCH 152/167] Removed unused print satements and redundancies Addressing comments on pull request #375 --- ST_grid.c | 5 ++--- ST_indivs.c | 5 +---- ST_main.c | 2 -- ST_seedDispersal.c | 1 + 4 files changed, 4 insertions(+), 9 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 56820139..c030e6ee 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -233,8 +233,7 @@ void runGrid(void) for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) { //for each cell - - //fprintf(stderr, "year: %d", year); + load_cell(i, j); Globals->currYear = year; @@ -427,7 +426,7 @@ static void _init_grid_inputs(void) static void _init_SXW_inputs(Bool init_SW, char *f_roots) { SXW_Init(init_SW, f_roots); // initializes soilwat - if (init_SW == TRUE) + if (init_SW) { char aString[2048]; sprintf(aString, "%s/%s", grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS], SW_Weather.name_prefix); diff --git a/ST_indivs.c b/ST_indivs.c index a8723942..6c121be8 100644 --- a/ST_indivs.c +++ b/ST_indivs.c @@ -112,11 +112,8 @@ Bool indiv_New( SppIndex sp) { p->Prev = NULL; Species[sp]->IndvHead = p; - //sql for inserting new indiv - //if(!UseGrid) - // insertIndiv(p); id++; - return( TRUE); + return TRUE; } /* Copy one individual's information to another individual. diff --git a/ST_main.c b/ST_main.c index 4a22c5ea..5c1ebd68 100644 --- a/ST_main.c +++ b/ST_main.c @@ -217,8 +217,6 @@ int main(int argc, char **argv) { logProgress(iter, year, SIMULATION); } - //printf("------------------------Repetition/year = %d / %d\n", iter, year); - Globals->currYear = year; rgroup_Establish(); diff --git a/ST_seedDispersal.c b/ST_seedDispersal.c index 0aa74c0c..a62cb15c 100644 --- a/ST_seedDispersal.c +++ b/ST_seedDispersal.c @@ -295,6 +295,7 @@ int _do_bulk_dispersal(SppIndex sp){ } void _do_precise_dispersal(int leftoverSeeds, SppIndex sp){ + /* This function is not implemented yet. */ return; } From 103ca00e5be9bf31031bf73b7d9cfd26f904029a Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 26 Sep 2019 12:04:03 -0600 Subject: [PATCH 153/167] Removed commented-out code Addressing comments on pull request #375 --- sxw.c | 3 --- sxw_resource.c | 8 ++------ 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/sxw.c b/sxw.c index 5306352a..6259795f 100644 --- a/sxw.c +++ b/sxw.c @@ -1046,7 +1046,6 @@ void _print_debuginfo(void) { fprintf(f, "\n"); int nLyrs = getNTranspLayers(RGroup[r]->veg_prod_type); for (t = 0; t < nLyrs; t++) { - //ForEachTranspLayer(t) { fprintf(f, "%d", t + 1); ForEachTrPeriod(p) fprintf(f, "\t%.4f", SXWResources->_roots_active_rel[Iglp(r, t, p)]); @@ -1055,7 +1054,6 @@ void _print_debuginfo(void) { } fprintf(f, "\n------ Transpiration Total Values -------\nPeriod:"); - //ForEachTranspLayer(t) for (t = 0; t < SXW->NSoLyrs; t++) fprintf(f, "\t\tL%d", t + 1); fprintf(f, "\n"); @@ -1063,7 +1061,6 @@ void _print_debuginfo(void) { ForEachTrPeriod(p) { fprintf(f, "%d : ", p + 1); - //ForEachTranspLayer(t) for (t = 0; t < SXW->NSoLyrs; t++) fprintf(f, "\t%.4f", SXW->transpTotal[Ilp(t, p)]); fprintf(f, "\n"); diff --git a/sxw_resource.c b/sxw_resource.c index 8413ee5f..98824978 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -115,7 +115,7 @@ void _sxw_update_resource(void) { sizes[g] = RGroup_GetBiomass(g); } - /* Update the active relative roots based on current biomass values */ + /* Update the active relative roots based on current biomass values */ _sxw_update_root_tables(sizes); /* Assign transpiration (resource availability) to each STEPPE functional group */ @@ -129,9 +129,8 @@ void _sxw_update_resource(void) { SXWResources->_resource_cur[g] = SXWResources->_resource_cur[g] * SXWResources->_bvt; //printf("for groupName= %s, resource_cur post multiplication: %f\n\n",Rgroup[g]->name, _resource_cur[g]); } -/* _print_debuginfo(); */ - Mem_Free(sizes); + Mem_Free(sizes); } void _sxw_update_root_tables( RealF sizes[] ) { @@ -320,8 +319,6 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { // If this year's transpiration is notably low (1 sd below the mean), add additional transpired water if (transp_ratio < (transp_window->ratio_average - 1 * transp_ratio_sd)) { - //printf("Year %d below 1 sd: ratio = %f, average = %f, sd = %f\n", Globals->currYear,transp_ratio, - //transp_window->ratio_average, transp_ratio_sd); RealF min = transp_window->ratio_average - transp_ratio_sd; RealF max = transp_window->ratio_average + transp_ratio_sd; @@ -331,7 +328,6 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { LogError(logfp, LOGNOTE, "sxw_resource: Added transpiration less than 0.\n"); } //printf("Year %d:\tTranspiration to add: %f\n",Globals->currYear,add_transp); - //printf("TranspRemaining: %f\tTranspRemaining+add_transp: %f\n",TranspRemaining,add_transp+TranspRemaining); /* -------------------- Recalculate the window including added_transp in the current year -------------------- */ RealF added_transp_ratio = transp_window->added_transp / SXW->ppt; From 2a1ff374752caf7b58801ed557394e091d9e839a Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 26 Sep 2019 12:15:41 -0600 Subject: [PATCH 154/167] Removed commented-out statements Addressing pull request #375. I tried to leave one debug statement in each function If they seemed useful. --- ST_mortality.c | 1 - sxw.c | 1 - sxw_resource.c | 5 ++--- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/ST_mortality.c b/ST_mortality.c index 6d20c059..5916526e 100644 --- a/ST_mortality.c +++ b/ST_mortality.c @@ -374,7 +374,6 @@ void grazing_EndOfYear( void){ //Implement grazing if this year is a year where grazing should occur if (Globals->currYear == grazingyr) { - //printf( "currYear is equal to grazingYear so will iterate all the Species for doing grazing, RGroup[g]->est_count =%d \n",RGroup[rg]->est_count); Int i; ForEachEstSpp2( rg, i) { diff --git a/sxw.c b/sxw.c index 6259795f..7b7620a6 100644 --- a/sxw.c +++ b/sxw.c @@ -948,7 +948,6 @@ void _print_debuginfo(void) { /* sum actual total transpiration */ ForEachTrPeriod(p) { - //ForEachTranspLayer(t) sum += SXW->transp[Ilp(t,p)]; for (t = 0; t < SXW->NSoLyrs; t++) sum += SXW->transpTotal[Ilp(t, p)]; } diff --git a/sxw_resource.c b/sxw_resource.c index 98824978..e9d1cc14 100644 --- a/sxw_resource.c +++ b/sxw_resource.c @@ -125,9 +125,9 @@ void _sxw_update_resource(void) { * (cm) to biomass that can be supported by those resources (g/cm) */ ForEachGroup(g) { -//printf("for groupName= %smresource_cur prior to multiplication: %f\n",RGroup[g]->name, _resource_cur[g]); +//printf("%s: _resource_cur pre-multiplication = %f. Post multiplication = %f.\n",RGroup[g]->name, + //_resource_cur[g], SXWResources->_resource_cur[g] * SXWResources->_bvt); SXWResources->_resource_cur[g] = SXWResources->_resource_cur[g] * SXWResources->_bvt; -//printf("for groupName= %s, resource_cur post multiplication: %f\n\n",Rgroup[g]->name, _resource_cur[g]); } Mem_Free(sizes); @@ -235,7 +235,6 @@ static void _transp_contribution_by_group(RealF use_by_group[]) { use_by_group[g] += (RealF) (SXWResources->_roots_active_rel[Iglp(g, l, p)] * transp[Ilp(l, p)]); } } - //printf("for groupName= %s, use_by_group[g] in transp= %f \n",RGroup[g]->name,use_by_group[g] ); sumUsedByGroup += use_by_group[g]; //printf(" sumUsedByGroup in transp=%f \n",sumUsedByGroup); From c8605b7cfbd409422d8664085f46bbd5815b3721 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 27 Sep 2019 15:10:35 -0600 Subject: [PATCH 155/167] Added back a print statement in ST_main.c (pull request #375) --- ST_main.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ST_main.c b/ST_main.c index 5c1ebd68..16099287 100644 --- a/ST_main.c +++ b/ST_main.c @@ -217,6 +217,8 @@ int main(int argc, char **argv) { logProgress(iter, year, SIMULATION); } + //printf("------------------------Repetition/year = %d / %d\n", iter, year); + Globals->currYear = year; rgroup_Establish(); From af5d2f8eeb9a61f500cc8f83867235083a7beff5 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 4 Nov 2019 13:21:24 -0700 Subject: [PATCH 156/167] Small changes requested in PR #375 In ST_grid.c: * Added references to GitHub in the file header. * Reduced the maximum column to 80 in the file header. This makes it displayable on most monitors and *might* encourage people to read it. * Corrected typos. * Added "_" prefixes for local functions that didn't have them already. * Updated some weak comments. * Fixed some dangling if statements. In ST_grid.h: * Removed "_" prefix from an exported struct. In ST_progressBar.c: * Fixed some typos. * Changed parameter names for the _calculateProgress function to make them more robust. --- ST_grid.c | 183 +++++++++++++++++++++++++---------------------- ST_grid.h | 2 +- ST_progressBar.c | 20 +++--- 3 files changed, 110 insertions(+), 95 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index c030e6ee..d4481637 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -1,30 +1,33 @@ -/********************************************************************************/ -// Source file: ST_grid.c -// Type: module -// Application: STEPPE - plant community dynamics simulator -// Purpose: This module handles the grid. -// History: -// (5/24/2013) -- INITIAL CODING - DLM -// (March - July 2019) -- Overhauled by Chandler Haukap with Fredrick Pierson -/********************************************************************************/ +/*****************************************************************************/ +// Source file: ST_grid.c +// Type: module +// Application: STEPPE - plant community dynamics simulator +// Purpose: This module handles the grid. +// History: +// (5/24/2013) -- INITIAL CODING - DLM +// (March - July 2019) -- Overhauled by Chandler Haukap with Fredrick Pierson +// See issue #262 and pull request #375 on GitHub +/*****************************************************************************/ /* Summary: - This module handles the gridded mode of STEPWAT2. To accomplish this we use a grid of cells - represented by the CellType struct. The entire grid of cells can be referenced by the - gridCells variable which is a 2d array of CellTypes. To allow this module to use the same - functions as non-gridded mode the CellType structs must be loaded into the global variables - using the load_cell function. As long as a cell is loaded in you can be sure that all - functions will work as expected. - -    In addition to all of the functionality of non-gridded mode, gridded mode has two additional - features: initialization and seed dispersal. Initialization allows vegetation to establish - before the simulation experiments begin. Seed dispersal allows each cell to disperse seeds - to nearby cells. + This module handles the gridded mode of STEPWAT2. To accomplish this we use + a grid of cells represented by the CellType struct. The entire grid of + cells can be referenced by the gridCells variable which is a 2d array of + CellTypes. To allow this module to use the same functions as non-gridded + mode the CellType structs must be loaded into the global variables using + the load_cell function. As long as a cell is loaded in you can be sure that + all functions will work as expected. + +    In addition to all of the functionality of non-gridded mode, gridded mode + has two additional features: initialization and seed dispersal. + Initialization allows vegetation to establish before the simulation + experiments begin. Seed dispersal allows each cell to disperse seeds to + nearby cells. */ -/* =================================================== */ -/* INCLUDES / DEFINES */ -/* --------------------------------------------------- */ +/*******************************************************/ +/* -------------- INCLUDES / DEFINES ----------------- */ +/*******************************************************/ #include #include #include @@ -48,7 +51,7 @@ Bool UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated /***************************** Externed variables **********************************/ /* Note that in an ideal world we wouldn't need to extern any variables because - every module would declate them in a header file. Hopefully we can get this + every module would declare them in a header file. Hopefully we can get this cleaned up soon! -CH */ // these are SOILWAT variables that we need... @@ -108,17 +111,17 @@ SXW_resourceType* getSXWResources(void); transp_t* getTranspWindow(void); void copy_sxw_variables(SXW_t* newSXW, SXW_resourceType* newSXWResources, transp_t* newTransp_window); -/*********** Locally Used Function Declarations ************/ /***********************************************************/ - +/* --------- Locally Used Function Declarations ---------- */ +/***********************************************************/ void _copy_soils(SoilType* src, SoilType* dest); static void printGeneralInfo(void); static void _init_grid_files(void); static void _init_SXW_inputs(Bool init_SW, char *f_roots); -static void allocate_gridCells(int rows, int cols); -static void Output_AllCellAvgBmass(const char* filename); -static void Output_AllCellAvgMort(const char* filename); -static void allocate_accumulators(void); +static void _allocate_gridCells(int rows, int cols); +static void _Output_AllCellAvgBmass(const char* filename); +static void _Output_AllCellAvgMort(const char* filename); +static void _allocate_accumulators(void); static void _read_disturbances_in(void); static void _read_soils_in(void); static int _read_soil_line(char* buf, SoilType* destination, int layer); @@ -196,7 +199,7 @@ void runGrid(void) * 06/15/2016 (akt) Added resetting correct historical weather file path, * as it was resetting to original path value (that was not correct for grid version)from input file after every iteration */ - sprintf(SW_Weather.name_prefix, "%s", SW_prefix_permanent); //updates the directory correctly for the weather files so soilwat can find them + sprintf(SW_Weather.name_prefix, "%s", SW_prefix_permanent); //updates the directory of the weather files so SOILWAT2 can find them if (BmassFlags.yearly || MortFlags.yearly){ parm_Initialize(); @@ -272,13 +275,15 @@ void runGrid(void) } /* end model run for this cell*/ } /* end model run for this row */ - if (UseSeedDispersal) + if (UseSeedDispersal){ disperseSeeds(); + } unload_cell(); // Reset the global variables }/* end model run for this year*/ - // collects the data appropriately for the mort output... (ie. fills the accumulators in ST_stats.c with the values that they need) + // collects the data for the mort output, + // i.e. fills the accumulators in ST_stats.c. if (MortFlags.summary){ for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) @@ -303,13 +308,13 @@ void runGrid(void) SW_Soilwat.hist.file_prefix = NULL; ChDir(".."); - } /*end iterations */ + } /* end iterations */ if(UseProgressBar){ logProgress(0, 0, OUTPUT); } - // outputs all of the mort and BMass files for each cell... + // Output all of the mort and BMass files for each cell. for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) { @@ -336,15 +341,15 @@ void runGrid(void) } unload_cell(); // Reset the global variables - //Here creating grid cells avg values output file + // Output the Bmass and Mort average statistics (if requested). char fileBMassCellAvg[1024], fileMortCellAvg[1024]; if (BmassFlags.summary){ sprintf(fileBMassCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_BMASSCELLAVG]); - Output_AllCellAvgBmass(fileBMassCellAvg); + _Output_AllCellAvgBmass(fileBMassCellAvg); } if (MortFlags.summary){ sprintf(fileMortCellAvg, "%s.csv", grid_files[GRID_FILE_PREFIX_MORTCELLAVG]); - Output_AllCellAvgMort(fileMortCellAvg); + _Output_AllCellAvgMort(fileMortCellAvg); } free_grid_memory(); // Free our allocated memory since we do not need it anymore @@ -385,10 +390,12 @@ static void _init_grid_files(void) LogError(stderr, LOGFATAL, "Invalid files.in"); // opens the log file... - if (!strcmp("stdout", grid_files[GRID_FILE_LOGFILE])) - logfp = stdout; - else - logfp = OpenFile(grid_files[GRID_FILE_LOGFILE], "w"); + if (!strcmp("stdout", grid_files[GRID_FILE_LOGFILE])){ + logfp = stdout; + } + else { + logfp = OpenFile(grid_files[GRID_FILE_LOGFILE], "w"); + } CloseFile(&f); } @@ -468,7 +475,7 @@ static void _init_stepwat_inputs(void) The other option is to create get functions for every accumulator, which is what we do for SXW variables. The reason we do not do this for accumulators is the sheer number of accumulators, which would require 14 get functions (as of 4/5/19). */ - allocate_accumulators(); + _allocate_accumulators(); ChDir(".."); // go back to the folder we started in } @@ -483,11 +490,11 @@ void rereadInputs(void){ } /* Allocates memory for the grid cells. This only needs to be called once. */ -static void allocate_gridCells(int rows, int cols){ +static void _allocate_gridCells(int rows, int cols){ int i, j; - gridCells = (CellType**) Mem_Calloc(rows, sizeof(CellType*), "allocate_gridCells: rows"); + gridCells = (CellType**) Mem_Calloc(rows, sizeof(CellType*), "_allocate_gridCells: rows"); for(i = 0; i < rows; ++i){ - gridCells[i] = (CellType*) Mem_Calloc(cols, sizeof(CellType), "allocate_gridCells: columns"); + gridCells[i] = (CellType*) Mem_Calloc(cols, sizeof(CellType), "_allocate_gridCells: columns"); } /* Allocate all fields specific to gridded mode. This is not necessary for fields like mySpecies @@ -496,16 +503,16 @@ static void allocate_gridCells(int rows, int cols){ for(j = 0; j < grid_Cols; ++j){ // shouldBeInitialized is a dynamically allocated array gridCells[i][j].mySpeciesInit.shouldBeInitialized = (int*) - Mem_Calloc(MAX_SPECIES, sizeof(int), "allocate_gridCells: mySpeciesInit"); + Mem_Calloc(MAX_SPECIES, sizeof(int), "_allocate_gridCells: mySpeciesInit"); - gridCells[i][j].someKillage = (Bool*) Mem_Calloc(1, sizeof(Bool), "allocate_gridCells: someKillage"); + gridCells[i][j].someKillage = (Bool*) Mem_Calloc(1, sizeof(Bool), "_allocate_gridCells: someKillage"); } } } /* Initialize each gridCell's accumulators. Must be called after STEPWAT inputs have been read. */ -static void allocate_accumulators(void){ +static void _allocate_accumulators(void){ int i, j; SppIndex sp; GrpIndex rg; @@ -519,81 +526,81 @@ static void allocate_accumulators(void){ load_cell(i,j); if (BmassFlags.dist) { - gridCells[i][j]._Dist = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(Dist)"); + gridCells[i][j]._Dist = (StatType*) Mem_Calloc(1, sizeof(StatType), "_allocate_accumulators(Dist)"); gridCells[i][j]._Dist->s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(Dist)"); + "_allocate_accumulators(Dist)"); } if (BmassFlags.ppt) { - gridCells[i][j]._Ppt = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(PPT"); + gridCells[i][j]._Ppt = (StatType*) Mem_Calloc(1, sizeof(StatType), "_allocate_accumulators(PPT"); gridCells[i][j]._Ppt->s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(PPT)"); + "_allocate_accumulators(PPT)"); } if (BmassFlags.tmp) { - gridCells[i][j]._Temp = (StatType*) Mem_Calloc(1, sizeof(StatType), "allocate_accumulators(Temp)"); + gridCells[i][j]._Temp = (StatType*) Mem_Calloc(1, sizeof(StatType), "_allocate_accumulators(Temp)"); gridCells[i][j]._Temp->s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(Temp)"); + "_allocate_accumulators(Temp)"); } if (BmassFlags.grpb) { gridCells[i][j]._Grp = (struct stat_st *) Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), - "allocate_accumulators(Grp)"); + "_allocate_accumulators(Grp)"); ForEachGroup(rg){ gridCells[i][j]._Grp[rg].s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(Grp[rg].s)"); + "_allocate_accumulators(Grp[rg].s)"); } if (BmassFlags.size) { gridCells[i][j]._Gsize = (struct stat_st *) Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), - "allocate_accumulators(GSize)"); + "_allocate_accumulators(GSize)"); ForEachGroup(rg){ gridCells[i][j]._Gsize[rg].s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(GSize[rg].s)"); + "_allocate_accumulators(GSize[rg].s)"); } } if (BmassFlags.pr) { gridCells[i][j]._Gpr = (struct stat_st *) Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), - "allocate_accumulators(Gpr)"); + "_allocate_accumulators(Gpr)"); ForEachGroup(rg){ gridCells[i][j]._Gpr[rg].s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(Gpr[rg].s)"); + "_allocate_accumulators(Gpr[rg].s)"); } } if (BmassFlags.wildfire || BmassFlags.prescribedfire) { gridCells[i][j]._Gwf = (struct fire_st *) Mem_Calloc( 1, sizeof(struct fire_st), - "allocate_accumulators(Gwf)"); + "_allocate_accumulators(Gwf)"); gridCells[i][j]._Gwf->wildfire = (int *) Mem_Calloc( 1, sizeof(int) * SuperGlobals.runModelYears, - "allocate_accumulators(Gwf->wildfire)"); + "_allocate_accumulators(Gwf->wildfire)"); gridCells[i][j]._Gwf->prescribedFire = (int **) Mem_Calloc( 1, sizeof(int **) * SuperGlobals.max_rgroups, - "allocate_accumulators(Gwf->prescribedfire"); + "_allocate_accumulators(Gwf->prescribedfire"); ForEachGroup(rg){ gridCells[i][j]._Gwf->prescribedFire[rg] = (int *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(int) * SuperGlobals.runModelYears, - "allocate_accumulators(Gwf->prescribedFire)"); + "_allocate_accumulators(Gwf->prescribedFire)"); } } } @@ -602,20 +609,20 @@ static void allocate_accumulators(void){ gridCells[i][j]._Gestab = (struct stat_st *) Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), - "allocate_accumulators(Gestab)"); + "_allocate_accumulators(Gestab)"); gridCells[i][j]._Gmort = (struct stat_st *) Mem_Calloc( Globals->grpCount, sizeof(struct stat_st), - "allocate_accumulators(Gmort)"); + "_allocate_accumulators(Gmort)"); ForEachGroup(rg){ gridCells[i][j]._Gestab[rg].s = (struct accumulators_st *) Mem_Calloc( 1, sizeof(struct accumulators_st), - "allocate_accumulators(Gestab[rg].s)"); + "_allocate_accumulators(Gestab[rg].s)"); gridCells[i][j]._Gmort[rg].s = (struct accumulators_st *) Mem_Calloc( GrpMaxAge(rg), sizeof(struct accumulators_st), - "allocate_accumulators(Gmort[rg].s)"); + "_allocate_accumulators(Gmort[rg].s)"); } } @@ -623,24 +630,24 @@ static void allocate_accumulators(void){ gridCells[i][j]._Spp = (struct stat_st *) Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), - "allocate_accumulators(Spp)"); + "_allocate_accumulators(Spp)"); ForEachSpecies(sp){ gridCells[i][j]._Spp[sp].s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(Spp[sp].s)"); + "_allocate_accumulators(Spp[sp].s)"); } if (BmassFlags.indv) { gridCells[i][j]._Indv = (struct stat_st *) Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), - "allocate_accumulators(Indv)"); + "_allocate_accumulators(Indv)"); ForEachSpecies(sp){ gridCells[i][j]._Indv[sp].s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(Indv[sp].s)"); + "_allocate_accumulators(Indv[sp].s)"); } } } @@ -648,32 +655,32 @@ static void allocate_accumulators(void){ gridCells[i][j]._Sestab = (struct stat_st *) Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), - "allocate_accumulators(Sestab)"); + "_allocate_accumulators(Sestab)"); gridCells[i][j]._Smort = (struct stat_st *) Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), - "allocate_accumulators(Smort)"); + "_allocate_accumulators(Smort)"); ForEachSpecies(sp){ gridCells[i][j]._Sestab[sp].s = (struct accumulators_st *) Mem_Calloc( 1, sizeof(struct accumulators_st), - "allocate_accumulators(Sestab[sp].s)"); + "_allocate_accumulators(Sestab[sp].s)"); gridCells[i][j]._Smort[sp].s = (struct accumulators_st *) Mem_Calloc( SppMaxAge(sp), sizeof(struct accumulators_st), - "allocate_accumulators(Smort[sp].s)"); + "_allocate_accumulators(Smort[sp].s)"); } } if (UseSeedDispersal) { - gridCells[i][j]._Sreceived = Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "allocate_accumulators(Sreceived)"); + gridCells[i][j]._Sreceived = Mem_Calloc( Globals->sppCount, sizeof(struct stat_st), "_allocate_accumulators(Sreceived)"); ForEachSpecies(sp) { gridCells[i][j]._Sreceived[sp].s = (struct accumulators_st *) Mem_Calloc( SuperGlobals.runModelYears, sizeof(struct accumulators_st), - "allocate_accumulators(Sreceived[sp].s)"); + "_allocate_accumulators(Sreceived[sp].s)"); gridCells[i][j]._Sreceived[sp].name = &Species[sp]->name[0]; } } @@ -887,11 +894,17 @@ static void _read_disturbances_in(void) CloseFile(&f); } -/***********************************************************/ +/* Iterates through s until it find nSeperators worth of seperators + * + * Used to do most of the parsing in the \ref _read_soils_in() function + * + * \param s is a char* array. + * \param separator is the character used as a separator, for example tab or space. + * \param nSeparators is the nuber of separators to read. + * + * \return index of the character following the last separator. */ static int _get_value_index(char* s, char seperator, int nSeperators) { - //pretty much this function goes through s until it find nSeperators worth of seperators and then returns the index of the next character - //this is used to do most of the parsing in the _read_soils_in() function int i = 0, sep = 0; while (*s) { @@ -1191,7 +1204,7 @@ static void _read_grid_setup(void) "Number of cells in grid exceeds MAX_CELLS defined in ST_defines.h"); /* Allocate the 2d array of cells now that we know how many we need */ - allocate_gridCells(grid_Rows, grid_Cols); + _allocate_gridCells(grid_Rows, grid_Cols); GetALine(f, buf); i = sscanf(buf, "%u", &UseDisturbances); @@ -1272,7 +1285,7 @@ static void _read_grid_setup(void) } /* Output a master .csv file containing the averages across all cells. */ -void Output_AllCellAvgBmass(const char * filename){ +void _Output_AllCellAvgBmass(const char * filename){ int i, j, year, nobs = 0; //for iterating GrpIndex rg; //for iterating SppIndex sp; //for iterating @@ -1458,7 +1471,7 @@ void Output_AllCellAvgBmass(const char * filename){ } /* Output the average mortality across cells. */ -void Output_AllCellAvgMort(const char* fileName){ +void _Output_AllCellAvgMort(const char* fileName){ if (!MortFlags.summary) return; /* We need a cell loaded for the ForEach loops. */ diff --git a/ST_grid.h b/ST_grid.h index 6aba8d6a..405d98f2 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -48,7 +48,7 @@ struct Soil_st }typedef SoilType; /* Initialization information. */ -struct _grid_init_species_st +struct grid_init_species_st { /* TRUE if at least one species has requested initialization */ int useInitialization; diff --git a/ST_progressBar.c b/ST_progressBar.c index aa2d0a83..0463e1e9 100644 --- a/ST_progressBar.c +++ b/ST_progressBar.c @@ -12,7 +12,7 @@ /*************** Local Function(s). Treat these as private. ***************/ -double _calculateProgress(int year, int iteration, Status status); +double _calculateProgress(int innerLoopIteration, int outerLoopIteration, Status status); double _calculateInitializationProgress(int year); double _calculateSimulationProgress(int year, int iteration); @@ -21,11 +21,11 @@ double _calculateSimulationProgress(int year, int iteration); /* Log the program's progress using a progress bar. Param iteration: integer greater than 0. Input 0 iff the program is not currently in an iteration loop. Param year: integer greater than 0. Input 0 iff the program is not currently in a years loop. - Param status: Use the "status" enum to choose a value. */ + Param status: Use the "Status" enum to choose a value. */ void logProgress(int iteration, int year, Status status){ static char progressString[256]; int index = 0; // Where we are in progressString - Bool needsProgressBar = FALSE; // By default we donot need a progress bar + Bool needsProgressBar = FALSE; // By default we do not need a progress bar progressString[0] = '\0'; // Empty the string iteration--; // iteration loops are 1 indexed, but we need 0 indexing. @@ -84,15 +84,17 @@ void logProgress(int iteration, int year, Status status){ } /* Returns a double between 0 and 100 representing how close the program is to completing a given loop. - Param year: Current year in the loop. - Param iteration: Current iteration in the loop. - Param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. */ -double _calculateProgress(int year, int iteration, Status status){ + * + * \param innerLoopIteration is the iteration of the inner loop. Most likely this is the "year" loop. + * \param outerLoopIteration is the iteration of the outer loop. Most likely this is the "iteration" loop. + * \param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. + */ +double _calculateProgress(int innerLoopIteration, int outerLoopIteration, Status status){ double percentComplete; if(status == INITIALIZATION){ - percentComplete = _calculateInitializationProgress(year); + percentComplete = _calculateInitializationProgress(innerLoopIteration); } else if(status == SIMULATION) { - percentComplete = _calculateSimulationProgress(year, iteration); + percentComplete = _calculateSimulationProgress(innerLoopIteration, outerLoopIteration); } else { return 0; // No other Status has defined how to calculate progress. } From 0fd76ca0d51a0a57caadd4f4cde8b6a29fa47105 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 6 Nov 2019 12:10:41 -0700 Subject: [PATCH 157/167] Addressing comments on pull request #375 Fixed a typo and improved the documentation of _calculateProgress. --- ST_grid.c | 2 +- ST_progressBar.c | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index d4481637..046a41d7 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -900,7 +900,7 @@ static void _read_disturbances_in(void) * * \param s is a char* array. * \param separator is the character used as a separator, for example tab or space. - * \param nSeparators is the nuber of separators to read. + * \param nSeparators is the number of separators to read. * * \return index of the character following the last separator. */ static int _get_value_index(char* s, char seperator, int nSeperators) diff --git a/ST_progressBar.c b/ST_progressBar.c index 0463e1e9..e6c65f47 100644 --- a/ST_progressBar.c +++ b/ST_progressBar.c @@ -85,9 +85,12 @@ void logProgress(int iteration, int year, Status status){ /* Returns a double between 0 and 100 representing how close the program is to completing a given loop. * - * \param innerLoopIteration is the iteration of the inner loop. Most likely this is the "year" loop. - * \param outerLoopIteration is the iteration of the outer loop. Most likely this is the "iteration" loop. + * \param innerLoopIteration is the iteration of the inner loop. + * \param outerLoopIteration is the iteration of the outer loop. * \param status: Use the "status" enumerator. Valid options are SPINUP or SIMULATION. + * + * Example usage for a loop with the structure "For iterations { for years {...} }": + * _calculateProgress(, , SIMULATION); */ double _calculateProgress(int innerLoopIteration, int outerLoopIteration, Status status){ double percentComplete; From 715e1e34fef952f8d9d5a3cefb40f125d7d1bc92 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 12 Nov 2019 13:14:44 -0700 Subject: [PATCH 158/167] Addressing comments on pull request #375 Mostly spelling mistakes and a few comment improvements. The more concerning issues were not corrected with this commit. --- ST_environs.c | 13 +++++-------- ST_grid.h | 8 ++++---- ST_indivs.c | 5 +++++ ST_initialization.c | 36 +++++++++++++++++++++++++++--------- ST_initialization.h | 2 +- ST_params.c | 9 ++++----- ST_progressBar.c | 8 ++++++-- ST_progressBar.h | 4 +++- ST_resgroups.c | 14 +++++++++++++- ST_seedDispersal.c | 31 +++++++++++++++++-------------- ST_stats.h | 9 ++++++--- 11 files changed, 91 insertions(+), 48 deletions(-) diff --git a/ST_environs.c b/ST_environs.c index c26be8fd..a1d4aa95 100644 --- a/ST_environs.c +++ b/ST_environs.c @@ -109,7 +109,7 @@ static void _make_ppt( void) { /* If not running SOILWAT,take a random number from normal distribution with*/ /* mean, stddev that is between min & max from */ /* the Globals->ppt structure.*/ -/* Also set the growing season precip. */ +/* Also determine growing season precipitation. */ /* HISTORY */ /* Chris Bennett @ LTER-CSU 6/15/2000 */ @@ -117,13 +117,10 @@ static void _make_ppt( void) { * The ppt and gsppt are set in _sxw_set_environs() * but we still pass through this code to set the * Dry/Wet/Normal state. - * KAP 1/26/2017 The above note by CB is not correct. Env->ppt - * is set in _sxw_set_environs, but gsppt is not, it is - * set below. When using SOILWAT or not, the gsspt, ppt.dry, - * and ppt.wet is currently fixed each year and read from env.in - * We should consider calculating gsspt in the _sxw_set_environs - * function when running SOILWAT (so it is not fixed), and allowing - * what constitutes a wet and dry year to vary across sites. */ + * KAP 1/26/2017 We should consider calculating amount of growing-season + * precipitation this year in the _sxw_set_environs function when + * running SOILWAT (so it is not fixed), and allowing what constitutes + * a wet and dry year to vary across sites. */ /*------------------------------------------------------*/ diff --git a/ST_grid.h b/ST_grid.h index 405d98f2..52729982 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -4,7 +4,7 @@ enumerators from ST_grid.c. If you are looking for the functions that this module exports check the bottom of the file. - Initial programming by Chandler Haukap. */ + Initial programming by Chandler Haukap in August 2019. */ /******************************************************************/ #ifndef GRID_H @@ -24,7 +24,7 @@ /*********************** Grid Structures ****************************/ -//represents the input data for all the soil layers of a cell +// Contains the input data for all the soil layers of a cell struct Soil_st { // Number of soil layers (size of lyr array) @@ -60,7 +60,7 @@ struct grid_init_species_st /* Holds all plot-specific parameters */ struct grid_cell_st { - /* RGroup coresponding to this cell */ + /* RGroup corresponding to this cell */ GroupType **myGroup; /* Species corresponding to this cell */ SpeciesType **mySpecies; @@ -154,7 +154,7 @@ int grid_Cols; char *grid_files[N_GRID_FILES]; /* Array of directory names. Use the Directory_Indices enum to pick the correct index. */ char *grid_directories[N_GRID_DIRECTORIES]; -/* TRUE if every cell should write its own summary file. */ +/* TRUE if every cell should write its own output file. */ Bool writeIndividualFiles; /**************************** Exported Functions **********************************/ diff --git a/ST_indivs.c b/ST_indivs.c index 6c121be8..245ad83a 100644 --- a/ST_indivs.c +++ b/ST_indivs.c @@ -112,6 +112,11 @@ Bool indiv_New( SppIndex sp) { p->Prev = NULL; Species[sp]->IndvHead = p; + // This functionality is unused, but it might be useful in the future. + //sql for inserting new indiv + //if(!UseGrid) + // insertIndiv(p); + id++; return TRUE; } diff --git a/ST_initialization.c b/ST_initialization.c index 53925ea4..3499c462 100644 --- a/ST_initialization.c +++ b/ST_initialization.c @@ -2,9 +2,10 @@ // ST_initialization.c // Contains definitions of all functions related to initialization. // The current initialization methods are _run_seed_initialization -// and _run_spinup. This file uses the "_" prefix to function names -// to denote private functions that should NEVER be called outside -// of this file. +// and _run_spinup. Note that _run_seed_initialization is non-functional +// as of 12/11/19, but the logic is in place to call the function. This +// file uses the "_" prefix in function names to denote private +// functions that should NEVER be called outside of this file. // // TO ADD AN INITIALIZATION METHOD: // Adding a method is simple. runInitialization() takes care of memory @@ -40,7 +41,7 @@ static void _saveAsInitializationConditions(void); /***************************** Externed variables **********************************/ /* Note that in an ideal world we wouldn't need to extern any variables because - every module would declate them in a header file. Hopefully we can get this + every module would declare them in a header file. Hopefully we can get this cleaned up soon! -CH */ // these are SOILWAT variables that we need... @@ -118,8 +119,9 @@ void runInitialization(void){ } unload_cell(); // Reset the global variables + /* Iterate through the number of years requested in inputs. */ for (year = 1; year <= SuperGlobals.runInitializationYears; year++) - { //for each year + { if(UseProgressBar){ logProgress(0, year, INITIALIZATION); // iter = 0 because we are not actually in an iterations loop. } @@ -216,8 +218,10 @@ static void _endInitialization(void){ DuringInitialization = FALSE; } -/* Save the current state of the program as spinup conditions. This is low level function. If you have already called - _endInitialization() there is no need to call this function. */ +/* Save the current state of the program as spinup conditions. + * + * This is low level function. If you have already called + * _endInitialization() there is no need to call this function. */ static void _saveAsInitializationConditions(){ // Save gridCells as initializationCells initializationCells = gridCells; @@ -256,7 +260,9 @@ void loadInitializationConditions(){ } -/* "Spinup" the model by running without stat collection. */ +/* "Spinup" the model by running without stat collection, fire, or grazing. + * + * Fire and grazing will potentially be added to spinup as a future feature. */ static void _run_spinup(void) { Bool killedany; // killedany for mortality functions @@ -273,7 +279,19 @@ static void _run_spinup(void) _kill_extra_growth(); // Kill superfluous growth } -/* TODO: This is a dummy method. It needs to be implemented once seed dispersal is fully planned. */ +/* TODO: This is a dummy method. It needs to be implemented once seed dispersal is fully planned. + * + * Note on implementing: The logic behind calling this function already exists. You can view the + * function call inside runInitialization, but the important thing to note is that this + * function is called inside the following structure: + * + * for each year + * for each grid cell + * _run_seed_initialization + * + * You can assume that prior to this function being called the correct grid cell has been loaded + * into the global variables (RGroup, Species, Env, ect.) and that this function must + * operate on a yearly time step. */ static void _run_seed_initialization(void){ if(Globals->currYear == 1){ printf("\nYou have attempted to initialize with seed dispersal.\n" diff --git a/ST_initialization.h b/ST_initialization.h index 31abdb3f..8b7ede62 100644 --- a/ST_initialization.h +++ b/ST_initialization.h @@ -4,7 +4,7 @@ Initialization is currently only availible when running gridded mode. - Initial programming by Chandler Haukap. */ + Initial programming by Chandler Haukap in August of 2019. */ /***********************************************************************/ #ifndef INITIALIZATION_H diff --git a/ST_params.c b/ST_params.c index 1e8d1c49..ce36fd97 100644 --- a/ST_params.c +++ b/ST_params.c @@ -231,7 +231,6 @@ static void _env_init( void) { nitems = 8; break; case 2: - nitems = 5; x=sscanf( inbuf, "%f %f %f %f %f", &Globals->temp.avg, &Globals->temp.std, &Globals->temp.min, &Globals->temp.max, @@ -1024,8 +1023,8 @@ static void _species_init( void) { viable, pseed; RealF irate, ratep, estab, minb, maxb, cohort, xdecay, - p1, p2, p3, p4, p5, p6, p7; - float var, VW; + p1, p2, p3, p4, p5, p6, p7, p8; + float var; char clonal[5]; MyFileName = Parm_name( F_Species); @@ -1203,7 +1202,7 @@ static void _species_init( void) { } x = sscanf( inbuf, "%s %hd %f %f %f %f %f %f %f %f", - name, &turnondispersal, &p1, &p2, &p3, &p4, &p5, &p6, &p7, &VW); + name, &turnondispersal, &p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8); if(x < 10) { LogError(logfp, LOGFATAL, "%s: Too few columns in species seed dispersal inputs", MyFileName); } @@ -1224,7 +1223,7 @@ static void _species_init( void) { Species[sp]->sd_Pmax = p5; Species[sp]->sd_H = p6; Species[sp]->sd_VT = p7; - Species[sp]->sd_VW = VW; + Species[sp]->sd_VW = p8; } if(!sppok) { LogError(logfp, LOGFATAL, "%s: Incorrect/incomplete input in species seed dispersal input", MyFileName); diff --git a/ST_progressBar.c b/ST_progressBar.c index e6c65f47..3c6d78d6 100644 --- a/ST_progressBar.c +++ b/ST_progressBar.c @@ -2,6 +2,8 @@ /* ST_progressBar.c Function definitions for a progress bar printed to the terminal. See ST_progressBar.h for a description of how to add a new Status. + + \author Chandler Haukap in August 2019 */ /**************************************************************************/ @@ -19,8 +21,10 @@ double _calculateSimulationProgress(int year, int iteration); /*********************** Function Definitions *****************************/ /* Log the program's progress using a progress bar. - Param iteration: integer greater than 0. Input 0 iff the program is not currently in an iteration loop. - Param year: integer greater than 0. Input 0 iff the program is not currently in a years loop. + Param iteration: integer greater than 0. Input 0 if and only if the program + is not currently in an iteration loop. + Param year: integer greater than 0. Input 0 if and only if the program is + not currently in a years loop. Param status: Use the "Status" enum to choose a value. */ void logProgress(int iteration, int year, Status status){ static char progressString[256]; diff --git a/ST_progressBar.h b/ST_progressBar.h index 9883f82b..f9c7bd78 100644 --- a/ST_progressBar.h +++ b/ST_progressBar.h @@ -10,6 +10,8 @@ progress bar, create a function for calculating progress in ST_progressBar.c then add your function to _calculateProgress(). + + \author Chandler Haukap in August 2019 */ /******************************************************************/ @@ -18,7 +20,7 @@ /*********************** Enumerator(s) ****************************/ -/* States of the program that the progress bar recognises. */ +/* States of the program that the progress bar recognizes. */ typedef enum { INITIALIZATION, diff --git a/ST_resgroups.c b/ST_resgroups.c index 4d234eab..07494905 100644 --- a/ST_resgroups.c +++ b/ST_resgroups.c @@ -993,10 +993,22 @@ void rgroup_Extirpate(GrpIndex rg) } +/* Copy one GroupType's variables to another GroupType. Both GroupTypes must be + * allocated before calling this function. + * + * \param src is the source of the data to be copied over. + * \param dest is destination to recieve the data. + * + * \sideeffect dest will be reallocated to the size of src, and all fields of + * dest will be overwritten with src's data. + */ void copy_rgroup(const GroupType* src, GroupType* dest){ int i; - // This would be very bad. + /* The first step of this algorithm is to deallocate dest's memory so it + * can be reallocated to the size of src. If dest and src are the same + * the net sum of this function would be to deallocate all of the fields + * of the GroupType. */ if(src == dest){ return; } diff --git a/ST_seedDispersal.c b/ST_seedDispersal.c index a62cb15c..2207c977 100644 --- a/ST_seedDispersal.c +++ b/ST_seedDispersal.c @@ -22,16 +22,16 @@ pcg32_random_t dispersal_rng; results of this function can be accessed using gridCells[a][b].mySeedDispersal[s].dispersalProb[c][d] where (a,b) are the coordinates of the sender, - (b, c) are the coordinates of the reciever, + (b, c) are the coordinates of the receiver, and s is the species. */ void initDispersalParameters(void) { - int senderRow, senderCol, recieverRow, recieverCol; + int senderRow, senderCol, receiverRow, receiverCol; SppIndex sp; double MAXD; /* maximum seed dispersal distance for a given species */ double maxRate; /* Dispersability of the seeds */ double plotWidth; /* width of the plots (all plots are equal and square) */ - double distanceBetweenPlots; /* distance between the sender and the reciever */ + double distanceBetweenPlots; /* distance between the sender and the receiver */ CellType* sender; RandSeed(SuperGlobals.randseed, &dispersal_rng); @@ -39,7 +39,8 @@ void initDispersalParameters(void) /* sender denotes that these loops refer to the cell distributing seeds */ for(senderRow = 0; senderCol < grid_Rows; ++senderRow){ for(senderCol = 0; senderCol < grid_Cols; ++senderCol){ - /* Cell is loaded to ensure the ForEachSpecies loop works */ + /* Cell is loaded to ensure the global Species pointer points to a valid SpeciesType so the + ForEachSpecies loop is able to iterate. */ load_cell(senderRow, senderCol); sender = &gridCells[senderRow][senderCol]; @@ -51,7 +52,8 @@ void initDispersalParameters(void) continue; } - /* These are the three values we need to calculate the probability of dispersal */ + /* These are the three values we need to calculate the probability of dispersal + * according to EQ 5 in Coffin & Lauenroth 1989. */ MAXD = ((Species[sp]->sd_H * Species[sp]->sd_VW) / Species[sp]->sd_VT) / 100.0; // divided by 100 to convert from cm to m. maxRate = -(log(0.005) / MAXD); plotWidth = sqrt(Globals->plotsize); @@ -59,22 +61,23 @@ void initDispersalParameters(void) /* Allocate the dispersalProb 2d array */ sender->mySeedDispersal[sp].dispersalProb = Mem_Calloc(grid_Rows, sizeof(double*), "initDispersalParameters: dispersalProb"); - for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ - sender->mySeedDispersal[sp].dispersalProb[recieverRow] = + for(receiverRow = 0; receiverRow < grid_Rows; ++receiverRow){ + sender->mySeedDispersal[sp].dispersalProb[receiverRow] = Mem_Calloc(grid_Cols, sizeof(double), "initDispersalParameters: dispersalProb[i]"); } /* Loop through all possible recipients of seeds. */ - for(recieverRow = 0; recieverRow < grid_Rows; ++recieverRow){ - for(recieverCol = 0; recieverCol < grid_Cols; ++recieverCol){ - if(senderRow == recieverRow && senderCol == recieverCol){ + for(receiverRow = 0; receiverRow < grid_Rows; ++receiverRow){ + for(receiverCol = 0; receiverCol < grid_Cols; ++receiverCol){ + if(senderRow == receiverRow && senderCol == receiverCol){ continue; // No need to calculate a probability for dispersal to itself } - distanceBetweenPlots = _cell_dist(senderRow, recieverRow, senderCol, recieverCol, plotWidth); + distanceBetweenPlots = _cell_dist(senderRow, receiverRow, senderCol, receiverCol, plotWidth); - /* The value that we are after should be saved to the sender cell. */ - sender->mySeedDispersal[sp].dispersalProb[recieverRow][recieverCol] + /* The value that we are after should be saved to the sender cell. + * this equation comes directly from equation 4 in Coffin and Lauenroth 1989. */ + sender->mySeedDispersal[sp].dispersalProb[receiverRow][receiverCol] = (distanceBetweenPlots > MAXD) ? (0.0) : (exp(-maxRate * distanceBetweenPlots)); } } @@ -84,7 +87,7 @@ void initDispersalParameters(void) unload_cell(); } -/* Perform seed dispersal durring the simulation. This is NOT functional yet. */ +/* Perform seed dispersal during the simulation. This is NOT functional yet. */ void disperseSeeds(void) { /************ TODO: overhaul seed dispersal. This block prevents seed dispersal from running. **************/ diff --git a/ST_stats.h b/ST_stats.h index ce6a1fec..e1f8a9a2 100644 --- a/ST_stats.h +++ b/ST_stats.h @@ -1,8 +1,11 @@ -/* Chandler Haukap- This file defines all structs used in ST_stats.c. - * It was created to allow the gridded code to instanciate accumulators +/* \file ST_stats.h + * \author Chandler Haukap in August 2019 + * + * This file defines all structs used in ST_stats.c. + * It was created to allow the gridded code to instantiate accumulators * without including ST_stats.c. * - * To read the documentation related to creating this struct see issues + * To read the documentation related to creating this file see issues * #259 and #266 on GitHub */ #ifndef STATS_STRUCT_DEF From d192856dbcd01c4005afab745dc2d199d12ed594 Mon Sep 17 00:00:00 2001 From: chaukap Date: Wed, 13 Nov 2019 13:35:51 -0700 Subject: [PATCH 159/167] Addressing comments on pull request #375 * Removed calls to parm_Initialize in ST_grid.c and ST_initialization.c * Removed call to proportion_Recovery in spinup. * Modified some documentation. --- ST_grid.c | 5 ----- ST_initialization.c | 4 ---- ST_species.c | 2 +- ST_stats.c | 6 +++++- 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 046a41d7..f9bcfbda 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -201,11 +201,6 @@ void runGrid(void) */ sprintf(SW_Weather.name_prefix, "%s", SW_prefix_permanent); //updates the directory of the weather files so SOILWAT2 can find them - if (BmassFlags.yearly || MortFlags.yearly){ - parm_Initialize(); - _init_grid_inputs(); - } - // Initialize the plot for each grid cell for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++){ diff --git a/ST_initialization.c b/ST_initialization.c index 3499c462..4ea0349c 100644 --- a/ST_initialization.c +++ b/ST_initialization.c @@ -106,9 +106,6 @@ void runInitialization(void){ RandSeed(SuperGlobals.randseed, &grid_rng); RandSeed(SuperGlobals.randseed, &markov_rng); - if (BmassFlags.yearly || MortFlags.yearly) - parm_Initialize(); - // Initialize the plot for each grid cell for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++){ @@ -275,7 +272,6 @@ static void _run_spinup(void) rgroup_IncrAges(); // Increment ages of all plants _kill_annuals(); // Kill annuals _kill_maxage(); // Kill plants that reach max age - proportion_Recovery(); // Recover from any disturbances _kill_extra_growth(); // Kill superfluous growth } diff --git a/ST_species.c b/ST_species.c index 4e2b0203..52cc86f2 100644 --- a/ST_species.c +++ b/ST_species.c @@ -267,7 +267,7 @@ void copy_species(const SpeciesType* src, SpeciesType* dest){ } /* ---- Reallocate and copy any arrays ---- */ - // kills: Note that this array is allocated iff MortFlags.summary. + // kills: Note that this array is allocated if and only if MortFlags.summary. if(src->max_age > 1 && src->use_me && MortFlags.summary){ Mem_Free(dest->kills); dest->kills = (IntUS*) Mem_Calloc(src->max_age, sizeof(IntUS), "copy_species: kills"); diff --git a/ST_stats.c b/ST_stats.c index 6af88067..5491ae90 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -8,8 +8,12 @@ // History: // (6/15/2000) -- INITIAL CODING - cwb // 1/9/01 - revised to make extensive use of malloc() */ -// 5/28/2013 (DLM) - added module level variable accumulators (grid_Stat) for the grid and functions to deal with them (stat_Load_Accumulators(), stat_Save_Accumulators() stat_Free_Accumulators(), and stat_Init_Accumulators()). These functions are called from ST_grid.c and manage the output accumulators so that the gridded version can output correctly. The accumulators are dynamically allocated, so be careful with them. +// 5/28/2013 (DLM) - added module level variable accumulators (grid_Stat) for the grid and functions. // 07/30/2016 (AKT) Fixed bug at std_dev calculation +// 8/30/2019 (Chandler Haukap) - Removed grid_Stat accumulators and functionality. +// Gridded mode accumulators are now stored in the Celltype struct in +// ST_grid.h and swapped into this module using a call to +// stat_Copy_Accumulators(). // /********************************************************/ /********************************************************/ From 0291723e1666c675b912701b8bf52bd3c9624196 Mon Sep 17 00:00:00 2001 From: chaukap Date: Thu, 14 Nov 2019 12:05:20 -0700 Subject: [PATCH 160/167] Continued addressing comments on pull request #375 Mostly documentation, and in ST_seedDispersal I added back a few lines of code that could help us when overhauling seed dispersal. --- ST_grid.c | 28 ++++++++++++++++------------ ST_grid.h | 1 - ST_seedDispersal.c | 4 +++- sxw.c | 1 - sxw.h | 15 +++++++++------ 5 files changed, 28 insertions(+), 21 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index f9bcfbda..293e9c18 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -2,7 +2,7 @@ // Source file: ST_grid.c // Type: module // Application: STEPPE - plant community dynamics simulator -// Purpose: This module handles the grid. +// Purpose: This module performs gridded mode simulations. // History: // (5/24/2013) -- INITIAL CODING - DLM // (March - July 2019) -- Overhauled by Chandler Haukap with Fredrick Pierson @@ -232,6 +232,7 @@ void runGrid(void) for (j = 0; j < grid_Cols; j++) { //for each cell + /* Ensure that all global variables reference the specific cell */ load_cell(i, j); Globals->currYear = year; @@ -242,14 +243,14 @@ void runGrid(void) gridCells[i][j].mySeedDispersal->lyppt = gridCells[i][j].myEnvironment.ppt; } - /* The following functions mimic ST_main.c. load_cell(i, j) ensures that all global variables reference the specific cell */ + /* The following functions mimic ST_main.c. */ - rgroup_Establish(); // Establish individuals. Excludes annuals. + rgroup_Establish(); // Establish individuals. - Env_Generate(); // Generated the SOILWAT environment + Env_Generate(); // Run SOILWAT2 to generate resources. rgroup_PartResources(); // Distribute resources - rgroup_Grow(); // Grow + rgroup_Grow(); // Implement plant growth mort_Main(&killedany); // Mortality that occurs during the growing season @@ -313,7 +314,7 @@ void runGrid(void) for (i = 0; i < grid_Rows; i++){ for (j = 0; j < grid_Cols; j++) { - int cell = (j + 1) + (i * grid_Cols) - 1; + int cell = j + (i * grid_Cols); load_cell(i, j); char fileMort[1024], fileBMass[1024], fileReceivedProb[1024]; @@ -458,7 +459,7 @@ static void _init_stepwat_inputs(void) // Set mySXW to the location of the newly allocated SXW gridCells[i][j].mySXW = getSXW(); - // Set myTanspWindow to the location of the newly allocated transp window + // Set myTranspWindow to the location of the newly allocated transp window gridCells[i][j].myTranspWindow = getTranspWindow(); // Set mySXWResources to the location of the newly allocated SXW resources gridCells[i][j].mySXWResources = getSXWResources(); @@ -565,6 +566,7 @@ static void _allocate_accumulators(void){ "_allocate_accumulators(GSize[rg].s)"); } } + if (BmassFlags.pr) { gridCells[i][j]._Gpr = (struct stat_st *) Mem_Calloc( Globals->grpCount, @@ -598,7 +600,7 @@ static void _allocate_accumulators(void){ "_allocate_accumulators(Gwf->prescribedFire)"); } } - } + } if (MortFlags.group) { gridCells[i][j]._Gestab = (struct stat_st *) @@ -645,7 +647,7 @@ static void _allocate_accumulators(void){ "_allocate_accumulators(Indv[sp].s)"); } } - } + } if (MortFlags.species) { gridCells[i][j]._Sestab = (struct stat_st *) Mem_Calloc( Globals->sppCount, @@ -826,11 +828,13 @@ void unload_cell(){ copy_sxw_variables(NULL,NULL,NULL); } -/**************************************************************/ +/* + * \brief Similar to the getaline function in filefuncs.c, except this one + * checks for carriage return characters and doesn't deal with whitespace. + * It treats '\r', '\n', and '\r\n' all like they are valid line feeds. + */ static Bool GetALine2(FILE *f, char buf[], int limit) { - //this is similar to the getaline function in filefuncs.c, except this one checks for carriage return characters and doesn't deal with whitespace/... (since excel writes them into .csv files for some aggravating reason)... this one is probably less efficient overall though. - //this is treating '\r', '\n', and '\r\n' all like they are valid line feed characters... in reality '\r' by itself should never be, but it's not like I can stop excel from outputting .csv files however the heck it feels like... //only read limit characters int i = 0, aChar; aChar = getc(f); diff --git a/ST_grid.h b/ST_grid.h index 52729982..5be0ec53 100644 --- a/ST_grid.h +++ b/ST_grid.h @@ -104,7 +104,6 @@ struct grid_cell_st /* ------------------ End Soils --------------------- */ } typedef CellType; - /**************************** Enumerators *********************************/ /* Indices for grid_directories go here */ typedef enum diff --git a/ST_seedDispersal.c b/ST_seedDispersal.c index 2207c977..dd8c256b 100644 --- a/ST_seedDispersal.c +++ b/ST_seedDispersal.c @@ -26,7 +26,7 @@ pcg32_random_t dispersal_rng; and s is the species. */ void initDispersalParameters(void) { - int senderRow, senderCol, receiverRow, receiverCol; + int senderRow, senderCol, receiverRow, receiverCol, MAXDP, maxCells; SppIndex sp; double MAXD; /* maximum seed dispersal distance for a given species */ double maxRate; /* Dispersability of the seeds */ @@ -57,6 +57,8 @@ void initDispersalParameters(void) MAXD = ((Species[sp]->sd_H * Species[sp]->sd_VW) / Species[sp]->sd_VT) / 100.0; // divided by 100 to convert from cm to m. maxRate = -(log(0.005) / MAXD); plotWidth = sqrt(Globals->plotsize); + MAXDP = (int) ceil(MAXD / plotWidth); //MAXD in terms of plots... rounds up to the nearest integer + maxCells = (int) pow((MAXDP * 2) + 1.0, 2.0); /* Allocate the dispersalProb 2d array */ sender->mySeedDispersal[sp].dispersalProb = Mem_Calloc(grid_Rows, diff --git a/sxw.c b/sxw.c index 7b7620a6..8afdbd12 100644 --- a/sxw.c +++ b/sxw.c @@ -1173,7 +1173,6 @@ void free_all_sxw_memory( void ) { Mem_Free(SXWResources->_prod_bmass); Mem_Free(SXWResources->_prod_pctlive); Mem_Free(SXWResources->_resource_cur); - Mem_Free(SXWResources->_resource_pr); Mem_Free(SXWResources->_roots_active); Mem_Free(SXWResources->_roots_active_rel); Mem_Free(SXWResources->_roots_active_sum); diff --git a/sxw.h b/sxw.h index 7c00c0f3..42ab0805 100644 --- a/sxw.h +++ b/sxw.h @@ -119,21 +119,24 @@ struct transp_data { struct temp_SXW_st{ /* ----- 3d arrays ------- */ RealD * _rootsXphen, /* relative roots X phen in each lyr,grp,pd */ - * _roots_active, /* "active" in terms of size and phenology */ + * _roots_active, // "active" in terms of size and phenology + // relative to the total roots_phen_lyr_group * _roots_active_rel; /* ----- 2D arrays ------- */ /* rgroup by layer, ie, group-level values */ - RealD * _roots_max, /* read from root distr. file */ - * _roots_active_sum, /* used in sxw_resource */ + RealD * _roots_max, // root distribution with depth for STEPPE functional + // groups, read from input. + * _roots_active_sum, // active roots in each month and soil layer for + // STEPPE functional groups in the current year. /* rgroup by period */ - * _phen; /* phenology read from file */ + * _phen; // phenological activity for each month for STEPPE + // functional groups, read from input. /* simple vectors hold the resource information for each group */ /* curr/equ gives the available/required ratio */ - RealF *_resource_cur, /* current resource availability for each STEPPE functional type */ - *_resource_pr; /* resource convertable to PR */ + RealF *_resource_cur; /* current resource availability for each STEPPE functional type */ /* one vector for the production constants */ RealD _prod_litter[MAX_MONTHS]; From fd179cc92b25acec5ae58c9b590796da9a354a1e Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Fri, 15 Nov 2019 13:06:51 -0700 Subject: [PATCH 161/167] Addressed more comments on pull request #375 * Removed makeHeader option for seed dispersal output. The header is now made regardless. * Removed SXW_BYMAXSIZE in sxw.c. * Removed an old comment. --- ST_grid.c | 10 ++-------- ST_stats.c | 16 ++++++++-------- ST_stats.h | 2 +- sxw.c | 10 ++++------ sxw_sql.c | 1 - .../Grid_Inputs/grid_setup.in | 1 - 6 files changed, 15 insertions(+), 25 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 293e9c18..6ef52b53 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -47,7 +47,7 @@ char sd_Sep; int grid_Cells; -Bool UseDisturbances, UseSoils, sd_DoOutput, sd_MakeHeader; //these are treated like booleans +Bool UseDisturbances, UseSoils, sd_DoOutput; //these are treated like booleans /***************************** Externed variables **********************************/ /* Note that in an ideal world we wouldn't need to extern any variables because @@ -331,7 +331,7 @@ void runGrid(void) stat_Output_AllBmass(); } if (UseSeedDispersal && sd_DoOutput && writeIndividualFiles){ - stat_Output_Seed_Dispersal(fileReceivedProb, sd_Sep, sd_MakeHeader); + stat_Output_Seed_Dispersal(fileReceivedProb, sd_Sep); } } } @@ -1263,12 +1263,6 @@ static void _read_grid_setup(void) LogError(logfp, LOGFATAL, "Invalid %s file: seed dispersal output line\n", grid_files[GRID_FILE_SETUP]); - GetALine(f, buf); - if (sscanf(buf, "%u", &sd_MakeHeader) != 1) - LogError(logfp, LOGFATAL, - "Invalid %s file: seed dispersal make header line\n", - grid_files[GRID_FILE_SETUP]); - GetALine(f, buf); if (sscanf(buf, "%c", &sd_Sep) != 1) LogError(logfp, LOGFATAL, diff --git a/ST_stats.c b/ST_stats.c index 5491ae90..5145c113 100644 --- a/ST_stats.c +++ b/ST_stats.c @@ -706,7 +706,7 @@ void stat_Output_AllBmass(void) { /***********************************************************/ -void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool makeHeader) { +void stat_Output_Seed_Dispersal(const char * filename, const char sep) { //do stuff... char buf[1024], tbuf[80]; IntS yr; @@ -715,14 +715,14 @@ void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool make f = OpenFile(filename, "w"); - if(makeHeader) { - fprintf(f,"Year"); - ForEachSpecies(sp) { - fprintf(f, "%c%s_prob", sep, Species[sp]->name); - fprintf(f, "%c%s_std", sep, Species[sp]->name); - } - fprintf(f,"\n"); + /* ---------- Make a header for the file --------- */ + fprintf(f,"Year"); + ForEachSpecies(sp) { + fprintf(f, "%c%s_prob", sep, Species[sp]->name); + fprintf(f, "%c%s_std", sep, Species[sp]->name); } + fprintf(f,"\n"); + /* ------------------ END header ----------------- */ for( yr=1; yr<= SuperGlobals.runModelYears; yr++) { *buf = '\0'; diff --git a/ST_stats.h b/ST_stats.h index e1f8a9a2..b8d2acbb 100644 --- a/ST_stats.h +++ b/ST_stats.h @@ -41,7 +41,7 @@ void stat_Collect_SMort ( void ) ; void stat_Output_YrMorts( void ) ; void stat_Output_AllMorts( void) ; void stat_Output_AllBmass(void) ; -void stat_Output_Seed_Dispersal(const char * filename, const char sep, Bool makeHeader); +void stat_Output_Seed_Dispersal(const char * filename, const char sep); void stat_free_mem( void ); void stat_Copy_Accumulators(StatType* newDist, StatType* newPpt, StatType* newTemp, StatType* newGrp, StatType* newGsize, StatType* newGpr, StatType* newGmort, StatType* newGestab, diff --git a/sxw.c b/sxw.c index 8afdbd12..ae5c69d4 100644 --- a/sxw.c +++ b/sxw.c @@ -33,7 +33,10 @@ * defined with double vs single precision and take * appropriate casting measures. * 07-16-12 (DLM) - made a ton of changes to try and - * get it to compile with the new updated version of soilwat (version 23) */ + * get it to compile with the new updated version of soilwat (version 23) + * 11-15-19 - Chandler Haukap - The functionality described by cwb on February + * 28 2002 has been entirely deprecated. I removed the last reference + * to SXW_BYMAXSIZE and _Grp_BMass today. */ /********************************************************/ /********************************************************/ @@ -93,11 +96,6 @@ transp_t* transp_window; pcg32_random_t resource_rng; //rng for swx_resource.c functions. SXW_resourceType* SXWResources; -#ifdef SXW_BYMAXSIZE -/* addition to meet changes specified at the top of the file */ -RealF _Grp_BMass[MAX_RGROUPS]; -#endif - /* and one vector for the production constants */ RealD _prod_litter[MAX_MONTHS]; RealD * _prod_bmass; diff --git a/sxw_sql.c b/sxw_sql.c index c9d0c8e0..4a41df10 100644 --- a/sxw_sql.c +++ b/sxw_sql.c @@ -337,7 +337,6 @@ void insertOutputVars(RealF * _resource_cur, RealF added_transp) { ForEachTrPeriod(p) { - //ForEachTranspLayer(t) sum += SXW->transp[Ilp(t,p)]; for (t = 0; t < SXW->NSoLyrs; t++) sum += SXW->transpTotal[Ilp(t, p)]; } diff --git a/testing.sagebrush.master/Grid_Inputs/grid_setup.in b/testing.sagebrush.master/Grid_Inputs/grid_setup.in index f3685ab3..b69a3860 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_setup.in +++ b/testing.sagebrush.master/Grid_Inputs/grid_setup.in @@ -10,5 +10,4 @@ spinup # Initialization method. Options are "spinup", "seeds", or "none" #SEED DISPERSAL OUTPUTS 1 # output seed dispersal summary file? 1 means yes, 0 means no -1 # output header? 1 means yes, 0 means no. , # output seperator. Valid options are: t = tab, s = space, or any single character such as , | : etc (excluding '#','t', and 's'). Suggested: tab. From 6a53657d4f4a0095511f5d20ab224f7e30130f7b Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 18 Nov 2019 12:57:07 -0700 Subject: [PATCH 162/167] Modified two comments as discussed in pull request #375 --- ST_environs.c | 7 +------ testing.sagebrush.master/Stepwat_Inputs/Input/species.in | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/ST_environs.c b/ST_environs.c index a1d4aa95..e339718a 100644 --- a/ST_environs.c +++ b/ST_environs.c @@ -116,12 +116,7 @@ static void _make_ppt( void) { /* cwb - 6-Dec-02 -- added code to interface with STEPWAT. * The ppt and gsppt are set in _sxw_set_environs() * but we still pass through this code to set the - * Dry/Wet/Normal state. - * KAP 1/26/2017 We should consider calculating amount of growing-season - * precipitation this year in the _sxw_set_environs function when - * running SOILWAT (so it is not fixed), and allowing what constitutes - * a wet and dry year to vary across sites. */ - + * Dry/Wet/Normal state. */ /*------------------------------------------------------*/ IntS i; diff --git a/testing.sagebrush.master/Stepwat_Inputs/Input/species.in b/testing.sagebrush.master/Stepwat_Inputs/Input/species.in index 62219d9b..d6028d08 100644 --- a/testing.sagebrush.master/Stepwat_Inputs/Input/species.in +++ b/testing.sagebrush.master/Stepwat_Inputs/Input/species.in @@ -173,7 +173,7 @@ # Pmax = probability of producing seeds in a wet year # H = the average release height of the inflorescences (cm) # VT = the average sinking velocity of the seeds (cm/sec) -# VW - the mean horizontal wind speed (500 cm/sec in the paper) +# VW - the mean horizontal wind speed (500 cm/sec in Coffin and Lauenroth 1989) # # name dispersal param1 PPTdry PPTwet Pmin Pmax H VT VW artr 1 0.5 105 520 0.01 0.55 30.0 100.0 500.0 From f70d4af5c5f99d415c4d5aabd3c55ac7a5fbc27f Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 19 Nov 2019 11:35:14 -0700 Subject: [PATCH 163/167] Reduced number of cells specified in grid input CSVs Some of the input CSVs had over 100 cells specified by default, which was a little excessive. I limited the number to 16, so the user can run a 4 x 4 grid without changing inputs. --- .../Grid_Inputs/grid_disturbances.csv | 128 ------------------ .../Grid_Inputs/grid_initSpecies.csv | 2 +- .../Grid_Inputs/grid_soils.csv | 10 -- 3 files changed, 1 insertion(+), 139 deletions(-) diff --git a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv index a659ecf8..69e4defd 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_disturbances.csv @@ -15,131 +15,3 @@ cell,fecal_pat_use,ant_mound_use,animal_burrows_use,kill_yr,killfreq_startyr,Pre 13,0,0,0,0,0,0,0,0,0,0 14,0,0,0,0,0,0,0,0,0,0 15,0,0,0,0,0,0,0,0,0,0 -16,0,0,0,0,0,0,0,0,0,0 -17,0,0,0,0,0,0,0,0,0,0 -18,0,0,0,0,0,0,0,0,0,0 -19,0,0,0,0,0,0,0,0,0,0 -20,0,0,0,0,0,0,0,0,0,0 -21,0,0,0,0,0,0,0,0,0,0 -22,0,0,0,0,0,0,0,0,0,0 -23,0,0,0,0,0,0,0,0,0,0 -24,0,0,0,0,0,0,0,0,0,0 -25,0,0,0,0,0,0,0,0,0,0 -26,0,0,0,0,0,0,0,0,0,0 -27,0,0,0,0,0,0,0,0,0,0 -28,0,0,0,0,0,0,0,0,0,0 -29,0,0,0,0,0,0,0,0,0,0 -30,0,0,0,0,0,0,0,0,0,0 -31,0,0,0,0,0,0,0,0,0,0 -32,0,0,0,0,0,0,0,0,0,0 -33,0,0,0,0,0,0,0,0,0,0 -34,0,0,0,0,0,0,0,0,0,0 -35,0,0,0,0,0,0,0,0,0,0 -36,0,0,0,0,0,0,0,0,0,0 -37,0,0,0,0,0,0,0,0,0,0 -38,0,0,0,0,0,0,0,0,0,0 -39,0,0,0,0,0,0,0,0,0,0 -40,0,0,0,0,0,0,0,0,0,0 -41,0,0,0,0,0,0,0,0,0,0 -42,0,0,0,0,0,0,0,0,0,0 -43,0,0,0,0,0,0,0,0,0,0 -44,0,0,0,0,0,0,0,0,0,0 -45,0,0,0,0,0,0,0,0,0,0 -46,0,0,0,0,0,0,0,0,0,0 -47,0,0,0,0,0,0,0,0,0,0 -48,0,0,0,0,0,0,0,0,0,0 -49,0,0,0,0,0,0,0,0,0,0 -50,0,0,0,0,0,0,0,0,0,0 -51,0,0,0,0,0,0,0,0,0,0 -52,0,0,0,0,0,0,0,0,0,0 -53,0,0,0,0,0,0,0,0,0,0 -54,0,0,0,0,0,0,0,0,0,0 -55,0,0,0,0,0,0,0,0,0,0 -56,0,0,0,0,0,0,0,0,0,0 -57,0,0,0,0,0,0,0,0,0,0 -58,0,0,0,0,0,0,0,0,0,0 -59,0,0,0,0,0,0,0,0,0,0 -60,0,0,0,0,0,0,0,0,0,0 -61,0,0,0,0,0,0,0,0,0,0 -62,0,0,0,0,0,0,0,0,0,0 -63,0,0,0,0,0,0,0,0,0,0 -64,0,0,0,0,0,0,0,0,0,0 -65,0,0,0,0,0,0,0,0,0,0 -66,0,0,0,0,0,0,0,0,0,0 -67,0,0,0,0,0,0,0,0,0,0 -68,0,0,0,0,0,0,0,0,0,0 -69,0,0,0,0,0,0,0,0,0,0 -70,0,0,0,0,0,0,0,0,0,0 -71,0,0,0,0,0,0,0,0,0,0 -72,0,0,0,0,0,0,0,0,0,0 -73,0,0,0,0,0,0,0,0,0,0 -74,0,0,0,0,0,0,0,0,0,0 -75,0,0,0,0,0,0,0,0,0,0 -76,0,0,0,0,0,0,0,0,0,0 -77,0,0,0,0,0,0,0,0,0,0 -78,0,0,0,0,0,0,0,0,0,0 -79,0,0,0,0,0,0,0,0,0,0 -80,0,0,0,0,0,0,0,0,0,0 -81,0,0,0,0,0,0,0,0,0,0 -82,0,0,0,0,0,0,0,0,0,0 -83,0,0,0,0,0,0,0,0,0,0 -84,0,0,0,0,0,0,0,0,0,0 -85,0,0,0,0,0,0,0,0,0,0 -86,0,0,0,0,0,0,0,0,0,0 -87,0,0,0,0,0,0,0,0,0,0 -88,0,0,0,0,0,0,0,0,0,0 -89,0,0,0,0,0,0,0,0,0,0 -90,0,0,0,0,0,0,0,0,0,0 -91,0,0,0,0,0,0,0,0,0,0 -92,0,0,0,0,0,0,0,0,0,0 -93,0,0,0,0,0,0,0,0,0,0 -94,0,0,0,0,0,0,0,0,0,0 -95,0,0,0,0,0,0,0,0,0,0 -96,0,0,0,0,0,0,0,0,0,0 -97,0,0,0,0,0,0,0,0,0,0 -98,0,0,0,0,0,0,0,0,0,0 -99,0,0,0,0,0,0,0,0,0,0 -100,0,0,0,0,0,0,0,0,0,0 -101,0,0,0,0,0,0,0,0,0,0 -102,0,0,0,0,0,0,0,0,0,0 -103,0,0,0,0,0,0,0,0,0,0 -104,0,0,0,0,0,0,0,0,0,0 -105,0,0,0,0,0,0,0,0,0,0 -106,0,0,0,0,0,0,0,0,0,0 -107,0,0,0,0,0,0,0,0,0,0 -108,0,0,0,0,0,0,0,0,0,0 -109,0,0,0,0,0,0,0,0,0,0 -110,0,0,0,0,0,0,0,0,0,0 -111,0,0,0,0,0,0,0,0,0,0 -112,0,0,0,0,0,0,0,0,0,0 -113,0,0,0,0,0,0,0,0,0,0 -114,0,0,0,0,0,0,0,0,0,0 -115,0,0,0,0,0,0,0,0,0,0 -116,0,0,0,0,0,0,0,0,0,0 -117,0,0,0,0,0,0,0,0,0,0 -118,0,0,0,0,0,0,0,0,0,0 -119,0,0,0,0,0,0,0,0,0,0 -120,0,0,0,0,0,0,0,0,0,0 -121,0,0,0,0,0,0,0,0,0,0 -122,0,0,0,0,0,0,0,0,0,0 -123,0,0,0,0,0,0,0,0,0,0 -124,0,0,0,0,0,0,0,0,0,0 -125,0,0,0,0,0,0,0,0,0,0 -126,0,0,0,0,0,0,0,0,0,0 -127,0,0,0,0,0,0,0,0,0,0 -128,0,0,0,0,0,0,0,0,0,0 -129,0,0,0,0,0,0,0,0,0,0 -130,0,0,0,0,0,0,0,0,0,0 -131,0,0,0,0,0,0,0,0,0,0 -132,0,0,0,0,0,0,0,0,0,0 -133,0,0,0,0,0,0,0,0,0,0 -134,0,0,0,0,0,0,0,0,0,0 -135,0,0,0,0,0,0,0,0,0,0 -136,0,0,0,0,0,0,0,0,0,0 -137,0,0,0,0,0,0,0,0,0,0 -138,0,0,0,0,0,0,0,0,0,0 -139,0,0,0,0,0,0,0,0,0,0 -140,0,0,0,0,0,0,0,0,0,0 -141,0,0,0,0,0,0,0,0,0,0 -142,0,0,0,0,0,0,0,0,0,0 -143,0,0,0,0,0,0,0,0,0,0 diff --git a/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv b/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv index 26f3c160..e4a9c805 100644 --- a/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_initSpecies.csv @@ -1 +1 @@ -cell,copy_cell,copy_which,artr,trdu,cryp,amre,chen,acmi,phho,arfr,lipu,brar,vuoc,spp1,spp2,pose,koma,bogr,spcr,gusa,chvi 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 5,1,0,,,,,,,,,,,,,,,,,,, 6,1,0,,,,,,,,,,,,,,,,,,, 7,1,0,,,,,,,,,,,,,,,,,,, 8,1,1,,,,,,,,,,,,,,,,,,, 9,1,1,,,,,,,,,,,,,,,,,,, 10,1,1,,,,,,,,,,,,,,,,,,, 11,1,1,,,,,,,,,,,,,,,,,,, 12,1,1,,,,,,,,,,,,,,,,,,, 13,1,1,,,,,,,,,,,,,,,,,,, 14,1,1,,,,,,,,,,,,,,,,,,, 15,1,2,,,,,,,,,,,,,,,,,,, 16,1,2,,,,,,,,,,,,,,,,,,, 17,1,2,,,,,,,,,,,,,,,,,,, 18,1,2,,,,,,,,,,,,,,,,,,, 19,1,2,,,,,,,,,,,,,,,,,,, 20,1,3,,,,,,,,,,,,,,,,,,, 21,1,3,,,,,,,,,,,,,,,,,,, 22,1,3,,,,,,,,,,,,,,,,,,, 23,1,3,,,,,,,,,,,,,,,,,,, 24,1,4,,,,,,,,,,,,,,,,,,, 25,1,4,,,,,,,,,,,,,,,,,,, 26,1,4,,,,,,,,,,,,,,,,,,, 27,1,4,,,,,,,,,,,,,,,,,,, 28,1,4,,,,,,,,,,,,,,,,,,, 29,1,4,,,,,,,,,,,,,,,,,,, 30,1,4,,,,,,,,,,,,,,,,,,, 31,1,4,,,,,,,,,,,,,,,,,,, 32,1,4,,,,,,,,,,,,,,,,,,, 33,1,4,,,,,,,,,,,,,,,,,,, 34,1,4,,,,,,,,,,,,,,,,,,, 35,1,4,,,,,,,,,,,,,,,,,,, 36,1,4,,,,,,,,,,,,,,,,,,, 37,1,4,,,,,,,,,,,,,,,,,,, 38,1,4,,,,,,,,,,,,,,,,,,, 39,1,4,,,,,,,,,,,,,,,,,,, 40,1,4,,,,,,,,,,,,,,,,,,, 41,1,4,,,,,,,,,,,,,,,,,,, 42,1,4,,,,,,,,,,,,,,,,,,, 43,1,4,,,,,,,,,,,,,,,,,,, 44,1,4,,,,,,,,,,,,,,,,,,, 45,1,4,,,,,,,,,,,,,,,,,,, 46,1,4,,,,,,,,,,,,,,,,,,, 47,1,4,,,,,,,,,,,,,,,,,,, 48,1,4,,,,,,,,,,,,,,,,,,, 49,1,4,,,,,,,,,,,,,,,,,,, 50,1,4,,,,,,,,,,,,,,,,,,, 51,1,4,,,,,,,,,,,,,,,,,,, 52,1,4,,,,,,,,,,,,,,,,,,, 53,1,4,,,,,,,,,,,,,,,,,,, 54,1,4,,,,,,,,,,,,,,,,,,, 55,1,4,,,,,,,,,,,,,,,,,,, 56,1,4,,,,,,,,,,,,,,,,,,, 57,1,4,,,,,,,,,,,,,,,,,,, 58,1,4,,,,,,,,,,,,,,,,,,, 59,1,4,,,,,,,,,,,,,,,,,,, 60,1,4,,,,,,,,,,,,,,,,,,, 61,1,4,,,,,,,,,,,,,,,,,,, 62,1,4,,,,,,,,,,,,,,,,,,, 63,1,4,,,,,,,,,,,,,,,,,,, 64,1,4,,,,,,,,,,,,,,,,,,, 65,1,4,,,,,,,,,,,,,,,,,,, 66,1,4,,,,,,,,,,,,,,,,,,, 67,1,4,,,,,,,,,,,,,,,,,,, 68,1,4,,,,,,,,,,,,,,,,,,, 69,1,4,,,,,,,,,,,,,,,,,,, 70,1,4,,,,,,,,,,,,,,,,,,, 71,1,4,,,,,,,,,,,,,,,,,,, 72,1,4,,,,,,,,,,,,,,,,,,, 73,1,4,,,,,,,,,,,,,,,,,,, 74,1,4,,,,,,,,,,,,,,,,,,, 75,1,4,,,,,,,,,,,,,,,,,,, 76,1,4,,,,,,,,,,,,,,,,,,, 77,1,4,,,,,,,,,,,,,,,,,,, 78,1,4,,,,,,,,,,,,,,,,,,, 79,1,4,,,,,,,,,,,,,,,,,,, 80,1,4,,,,,,,,,,,,,,,,,,, 81,1,4,,,,,,,,,,,,,,,,,,, 82,1,4,,,,,,,,,,,,,,,,,,, 83,1,4,,,,,,,,,,,,,,,,,,, 84,1,4,,,,,,,,,,,,,,,,,,, 85,1,4,,,,,,,,,,,,,,,,,,, 86,1,4,,,,,,,,,,,,,,,,,,, 87,1,4,,,,,,,,,,,,,,,,,,, 88,1,4,,,,,,,,,,,,,,,,,,, 89,1,4,,,,,,,,,,,,,,,,,,, 90,1,4,,,,,,,,,,,,,,,,,,, 91,1,4,,,,,,,,,,,,,,,,,,, 92,1,4,,,,,,,,,,,,,,,,,,, 93,1,4,,,,,,,,,,,,,,,,,,, 94,1,4,,,,,,,,,,,,,,,,,,, 95,1,4,,,,,,,,,,,,,,,,,,, 96,1,4,,,,,,,,,,,,,,,,,,, 97,1,4,,,,,,,,,,,,,,,,,,, 98,1,4,,,,,,,,,,,,,,,,,,, 99,1,4,,,,,,,,,,,,,,,,,,, 100,1,4,,,,,,,,,,,,,,,,,,, 101,1,4,,,,,,,,,,,,,,,,,,, 102,1,4,,,,,,,,,,,,,,,,,,, 103,1,4,,,,,,,,,,,,,,,,,,, 104,1,4,,,,,,,,,,,,,,,,,,, 105,1,4,,,,,,,,,,,,,,,,,,, 106,1,4,,,,,,,,,,,,,,,,,,, 107,1,4,,,,,,,,,,,,,,,,,,, 108,1,4,,,,,,,,,,,,,,,,,,, 109,1,4,,,,,,,,,,,,,,,,,,, 110,1,4,,,,,,,,,,,,,,,,,,, 111,1,4,,,,,,,,,,,,,,,,,,, 112,1,4,,,,,,,,,,,,,,,,,,, 113,1,4,,,,,,,,,,,,,,,,,,, 114,1,4,,,,,,,,,,,,,,,,,,, 115,1,4,,,,,,,,,,,,,,,,,,, 116,1,4,,,,,,,,,,,,,,,,,,, 117,1,4,,,,,,,,,,,,,,,,,,, 118,1,4,,,,,,,,,,,,,,,,,,, 119,1,4,,,,,,,,,,,,,,,,,,, 120,1,4,,,,,,,,,,,,,,,,,,, 121,1,4,,,,,,,,,,,,,,,,,,, 122,1,4,,,,,,,,,,,,,,,,,,, 123,1,4,,,,,,,,,,,,,,,,,,, 124,1,4,,,,,,,,,,,,,,,,,,, 125,1,4,,,,,,,,,,,,,,,,,,, 126,1,4,,,,,,,,,,,,,,,,,,, 127,1,4,,,,,,,,,,,,,,,,,,, 128,1,4,,,,,,,,,,,,,,,,,,, 129,1,4,,,,,,,,,,,,,,,,,,, 130,1,4,,,,,,,,,,,,,,,,,,, 131,1,4,,,,,,,,,,,,,,,,,,, 132,1,4,,,,,,,,,,,,,,,,,,, 133,1,4,,,,,,,,,,,,,,,,,,, 134,1,4,,,,,,,,,,,,,,,,,,, 135,1,4,,,,,,,,,,,,,,,,,,, 136,1,4,,,,,,,,,,,,,,,,,,, 137,1,4,,,,,,,,,,,,,,,,,,, 138,1,4,,,,,,,,,,,,,,,,,,, 139,1,4,,,,,,,,,,,,,,,,,,, 140,1,4,,,,,,,,,,,,,,,,,,, 141,1,4,,,,,,,,,,,,,,,,,,, 142,1,4,,,,,,,,,,,,,,,,,,, 143,1,4,,,,,,,,,,,,,,,,,,, \ No newline at end of file +cell,copy_cell,copy_which,artr,trdu,cryp,amre,chen,acmi,phho,arfr,lipu,brar,vuoc,spp1,spp2,pose,koma,bogr,spcr,gusa,chvi 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 5,1,0,,,,,,,,,,,,,,,,,,, 6,1,0,,,,,,,,,,,,,,,,,,, 7,1,0,,,,,,,,,,,,,,,,,,, 8,1,1,,,,,,,,,,,,,,,,,,, 9,1,1,,,,,,,,,,,,,,,,,,, 10,1,1,,,,,,,,,,,,,,,,,,, 11,1,1,,,,,,,,,,,,,,,,,,, 12,1,1,,,,,,,,,,,,,,,,,,, 13,1,1,,,,,,,,,,,,,,,,,,, 14,1,1,,,,,,,,,,,,,,,,,,, 15,1,2,,,,,,,,,,,,,,,,,,, \ No newline at end of file diff --git a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv index 63bdafc4..c8ecc4b7 100755 --- a/testing.sagebrush.master/Grid_Inputs/grid_soils.csv +++ b/testing.sagebrush.master/Grid_Inputs/grid_soils.csv @@ -29,13 +29,3 @@ cell,copy_cell,num_layers,layer,depth,matricd,gravel_content,evco,trco_grass,trc 13,1,,,,,,,,,,,,,,, 14,0,,,,,,,,,,,,,,, 15,1,,,,,,,,,,,,,,, -16,0,,,,,,,,,,,,,,, -17,1,,,,,,,,,,,,,,, -18,0,,,,,,,,,,,,,,, -19,1,,,,,,,,,,,,,,, -20,0,,,,,,,,,,,,,,, -21,1,,,,,,,,,,,,,,, -22,0,,,,,,,,,,,,,,, -23,1,,,,,,,,,,,,,,, -24,0,,,,,,,,,,,,,,, -25,1,,,,,,,,,,,,,,, From 01db611c2b161fbebadba79c1a0141cfbfa3b8b9 Mon Sep 17 00:00:00 2001 From: chaukap Date: Tue, 19 Nov 2019 12:05:32 -0700 Subject: [PATCH 164/167] Improved documentation of unusual code in runGrid() This code snippet confused me for a long time. Without it the program crashed, but it was unclear why. I did some investigating and this is the best explaination I could come up with. --- ST_grid.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ST_grid.c b/ST_grid.c index 6ef52b53..b47b8493 100644 --- a/ST_grid.c +++ b/ST_grid.c @@ -180,8 +180,9 @@ void runGrid(void) if(initializationMethod != INIT_WITH_NOTHING){ runInitialization(); } else { - /* If no spinup is requested we still need to reset SXW to set the historical weather - file names. */ + /* SXW expects to be run from the testing.sagebrush.master/Stepwat_Inputs directory. + However, we are running from the testing.sagebrush.master directory. To find the + location of the SOILWAT input files we need to manually set SXW->f_watin. */ ChDir(grid_directories[GRID_DIRECTORY_STEPWAT_INPUTS]); SXW_Reset(gridCells[0][0].mySXW->f_watin); ChDir(".."); From f944a0927c6375c48e3abfdcda507327e1191585 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 26 Nov 2019 14:37:46 -0700 Subject: [PATCH 165/167] Updated sw_src to latest commit on Bugfix_247_STEPWAT_compatability --- sw_src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sw_src b/sw_src index b7f28752..6fa0c011 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit b7f28752eda914d59f3ef21ebb588b326b008d59 +Subproject commit 6fa0c011d6a729f2800c6f13ace128557f39d129 From 2889da31a66ad01dd0e3da1e83c198e8c6a62d43 Mon Sep 17 00:00:00 2001 From: Chandler Haukap Date: Tue, 26 Nov 2019 15:01:34 -0700 Subject: [PATCH 166/167] Updated ST_params.c To work with gridded mode. --- ST_params.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ST_params.c b/ST_params.c index 95d475db..b531565e 100644 --- a/ST_params.c +++ b/ST_params.c @@ -1147,7 +1147,7 @@ static void _species_init( void) { Species[sp]->exp_decay = xdecay; Species[sp]->seedprod = (IntUS *) Mem_Calloc( viable, sizeof(IntUS), "species_init()"); Species[sp]->var = var; - Species[sp]->pseed = pseed / Globals.plotsize; + Species[sp]->pseed = pseed / Globals->plotsize; } /* end while readspp*/ From a4dd5f71abbb79038319acff31a81a207ab2e531 Mon Sep 17 00:00:00 2001 From: chaukap Date: Mon, 2 Dec 2019 11:40:15 -0700 Subject: [PATCH 167/167] Update SOILWAT2 head The SOILWAT2 companion branch to gridded_code was just merged into master. Before I merge gridded_code into master I needed to update the SOILWAT2 head to incorporate the changes. After this commit (and testing) I will merge gridded_code. --- sw_src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sw_src b/sw_src index 6fa0c011..9fe0a657 160000 --- a/sw_src +++ b/sw_src @@ -1 +1 @@ -Subproject commit 6fa0c011d6a729f2800c6f13ace128557f39d129 +Subproject commit 9fe0a6578515ed69126481dfcf340f525db608c7