-
Notifications
You must be signed in to change notification settings - Fork 24
/
riversys.c
3463 lines (3053 loc) · 121 KB
/
riversys.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "riversys.h"
//Read topo data and build the network.
//Also creates id_to_loc.
Link** Create_River_Network(UnivVars* GlobalVars,unsigned int* N,unsigned int*** id_to_loc,ConnData** db_connections)
{
Link **system,**upstream_order;
FILE* riverdata = NULL;
PGresult *mainres,*res;
unsigned int *link_ids,*dbres_link_id,*dbres_parent,sizeres = 0,i,j,k,**loc_to_children,*numparents,id,max_children = 10,*loc_to_children_array,loc,curr_loc;
link_ids = dbres_link_id = dbres_parent = NULL;
int db;
if(GlobalVars->rvr_flag == 0) //Read topo data from file
{
if(my_rank == 0)
{
riverdata = fopen(GlobalVars->rvr_filename,"r");
if(!riverdata)
{
if(my_rank == 0) printf("Error: file %s not found for .rvr file.\n",GlobalVars->rvr_filename);
*N = 0;
return NULL;
}
if(CheckWinFormat(riverdata))
{
printf("Error: File %s appears to be in Windows format. Try converting to unix format using 'dos2unix' at the command line.\n",GlobalVars->rvr_filename);
fclose(riverdata);
return NULL;
}
fscanf(riverdata,"%u",N);
link_ids = (unsigned int*) malloc(*N*sizeof(unsigned int));
loc_to_children_array = (unsigned int*) calloc(*N*max_children,sizeof(unsigned int));
loc_to_children = (unsigned int**) malloc(*N*sizeof(unsigned int*)); //This holds the ID of the children
for(i=0;i<*N;i++) loc_to_children[i] = &(loc_to_children_array[i*max_children]);
numparents = (unsigned int*) malloc(*N*sizeof(unsigned int));
for(i=0;i<*N;i++)
{
fscanf(riverdata,"%u %u",&(link_ids[i]),&(numparents[i]));
for(j=0;j<numparents[i];j++)
{
fscanf(riverdata,"%u",&id);
loc_to_children[i][j] = id;
}
if(numparents[i] > max_children)
{
printf("Error: assumed no link has more than %u parents, but link %u has %u.\n",max_children,link_ids[i],numparents[i]);
printf("If this is not an error in the input data, modify max_children in riversys.c, function Create_River_Network.\n");
return NULL;
}
}
fclose(riverdata);
//Broadcast data
MPI_Bcast(N,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(link_ids,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(loc_to_children_array,*N*max_children,MPI_UNSIGNED,0,MPI_COMM_WORLD); //Yeah, this is probably not the most efficient...
MPI_Bcast(numparents,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
}
else
{
MPI_Bcast(N,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
link_ids = (unsigned int*) malloc(*N*sizeof(unsigned int));
loc_to_children_array = (unsigned int*) malloc(*N*max_children*sizeof(unsigned int));
loc_to_children = (unsigned int**) malloc(*N*sizeof(unsigned int*)); //This holds the ID of the children
for(i=0;i<*N;i++) loc_to_children[i] = &(loc_to_children_array[i*max_children]);
numparents = (unsigned int*) malloc(*N*sizeof(unsigned int));
MPI_Bcast(link_ids,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(loc_to_children_array,*N*max_children,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(numparents,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
}
}
else if(GlobalVars->rvr_flag == 1) //Download topo data from database
{
//if(my_rank == 0) printf("\nTransferring topology data from database...\n");
//MPI_Barrier(MPI_COMM_WORLD);
//start = time(NULL);
if(my_rank == 0)
{
if(GlobalVars->outletlink == 0) //Grab entire network
{
//Note: parent_id on the SQL database is like the child id here
db = ConnectPGDB(db_connections[ASYNCH_DB_LOC_TOPO]);
if(db)
{
printf("[%i]: Error connecting to the topology database.\n",my_rank);
return NULL;
}
mainres = PQexec(db_connections[ASYNCH_DB_LOC_TOPO]->conn,db_connections[ASYNCH_DB_LOC_TOPO]->queries[0]); //For all link ids
res = PQexec(db_connections[ASYNCH_DB_LOC_TOPO]->conn,db_connections[ASYNCH_DB_LOC_TOPO]->queries[1]); //For parent data
if(CheckResError(res,"querying connectivity") || CheckResError(mainres,"querying DEM data"))
return NULL;
DisconnectPGDB(db_connections[ASYNCH_DB_LOC_TOPO]);
*N = PQntuples(mainres);
//Get the list of link ids
link_ids = (unsigned int*) malloc(*N*sizeof(unsigned int));
for(i=0;i<*N;i++) link_ids[i] = atoi(PQgetvalue(mainres,i,0));
PQclear(mainres);
sizeres = PQntuples(res);
}
else //Grab a sub basin (Note: all link ids (except the outlet) is in the second column of res)
{
db = ConnectPGDB(db_connections[ASYNCH_DB_LOC_TOPO]);
if(db)
{
printf("[%i]: Error connecting to the topology database.\n",my_rank);
return NULL;
}
//Make the queries
//Be careful to not overload the database
sprintf(db_connections[ASYNCH_DB_LOC_TOPO]->query,db_connections[ASYNCH_DB_LOC_TOPO]->queries[2],GlobalVars->outletlink); //For parent data
res = PQexec(db_connections[ASYNCH_DB_LOC_TOPO]->conn,db_connections[ASYNCH_DB_LOC_TOPO]->query);
if(CheckResError(res,"querying connectivity")) return NULL;
DisconnectPGDB(db_connections[ASYNCH_DB_LOC_TOPO]);
*N = PQntuples(res) + 1;
//Get the list of link ids
link_ids = (unsigned int*) malloc(*N*sizeof(unsigned int));
for(i=0;i<*N-1;i++) link_ids[i] = atoi(PQgetvalue(res,i,1));
link_ids[i] = GlobalVars->outletlink;
merge_sort_1D(link_ids,*N);
sizeres = *N - 1;
}
dbres_link_id = (unsigned int*) malloc(sizeres*sizeof(unsigned int));
dbres_parent = (unsigned int*) malloc(sizeres*sizeof(unsigned int));
for(i=0;i<sizeres;i++)
{
dbres_link_id[i] = atoi(PQgetvalue(res,i,0));
dbres_parent[i] = atoi(PQgetvalue(res,i,1));
}
PQclear(res);
//Modify the data format
loc_to_children_array = (unsigned int*) calloc(*N*max_children,sizeof(unsigned int));
loc_to_children = (unsigned int**) malloc(*N*sizeof(unsigned int*)); //This holds the IDs of the parents. Really needs a better name...
for(i=0;i<*N;i++) loc_to_children[i] = &(loc_to_children_array[i*max_children]);
numparents = (unsigned int*) malloc(*N*sizeof(unsigned int));
curr_loc = 0;
for(i=0;i<sizeres;i+=j)
{
//Select the next link
id = dbres_link_id[i];
if(id == link_ids[curr_loc]) //Extract parents
{
//Count the parents
for(j=0;i+j<sizeres;j++)
if(dbres_link_id[i+j] != id) break;
//Set the number of parents
numparents[curr_loc] = j;
//Set the information to find the child links
for(k=0;k<j;k++)
loc_to_children[curr_loc][k] = dbres_parent[i+k];
}
else //No parents
{
numparents[curr_loc] = 0;
j = 0;
}
//Set the next location
curr_loc++;
}
for(;curr_loc<*N;curr_loc++) //Finish any leaves at the end of link_ids
numparents[curr_loc] = 0;
//Send sizes and data to other processes
MPI_Bcast(N,1,MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(link_ids,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(loc_to_children_array,*N*max_children,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(numparents,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
//Clean up
free(dbres_link_id);
free(dbres_parent);
}
else
{
//Receive data
MPI_Bcast(N,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
link_ids = (unsigned int*) malloc(*N*sizeof(unsigned int));
loc_to_children_array = (unsigned int*) calloc(*N*max_children,sizeof(unsigned int));
loc_to_children = (unsigned int**) malloc(*N*sizeof(unsigned int*)); //This holds the ID of the children
for(i=0;i<*N;i++) loc_to_children[i] = &(loc_to_children_array[i*max_children]);
numparents = (unsigned int*) calloc(*N,sizeof(unsigned int));
MPI_Bcast(link_ids,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(loc_to_children_array,*N*max_children,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(numparents,*N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
}
//MPI_Barrier(MPI_COMM_WORLD);
//stop = time(NULL);
//if(my_rank == 0) printf("Time to receive data: %f\n",difftime(stop,start));
}
else
{
if(my_rank == 0) printf("Error: Bad topology flag %hi in .gbl file.\n",GlobalVars->rvr_flag);
*N = 0;
return NULL;
}
//Make a list of ids and locations, sorted by id
*id_to_loc = malloc(*N*sizeof(int*));
for(i=0;i<*N;i++) (*id_to_loc)[i] = malloc(2*sizeof(int)); //!!!! This should really have an array... !!!!
for(i=0;i<*N;i++)
{
(*id_to_loc)[i][0] = link_ids[i];
(*id_to_loc)[i][1] = i;
}
merge_sort_ids(*id_to_loc,*N);
//Check for crapiness
if(my_rank == 0 && *N < (unsigned int)np)
printf("\nWarning: using more processes (%i) than links (%u).\n",np,*N);
//Allocate some space for the network
system = (Link**) malloc(*N*sizeof(Link*));
for(i=0;i<*N;i++) system[i] = (Link*) malloc(sizeof(Link));
//Build the network
GlobalVars->max_parents = 0;
for(i=0;i<*N;i++)
{
system[i]->location = i;
system[i]->ID = link_ids[i];
//Set the parents
system[i]->numparents = numparents[i];
system[i]->parents = (Link**) malloc(system[i]->numparents * sizeof(Link*));
system[i]->c = NULL;
GlobalVars->max_parents = (GlobalVars->max_parents > numparents[i]) ? GlobalVars->max_parents : numparents[i];
//Set a few other data
system[i]->output_user = NULL;
system[i]->peakoutput_user = NULL;
system[i]->f = NULL;
system[i]->params = NULL;
system[i]->dam = 0;
system[i]->method = NULL;
system[i]->errorinfo = NULL;
system[i]->qvs = NULL;
system[i]->discont = NULL;
system[i]->discont_start = 0;
system[i]->discont_end = GlobalVars->discont_size-1;
system[i]->discont_count = 0;
system[i]->discont_send = NULL;
system[i]->discont_order_send = NULL;
system[i]->discont_send_count = 0;
system[i]->res = 0;
system[i]->num_dense = 0;
system[i]->dense_indices = NULL;
system[i]->dim = 0;
system[i]->diff_start = 0;
system[i]->no_ini_start = 0;
system[i]->disk_iterations = 0;
system[i]->forcing_buff = NULL;
system[i]->forcing_values = NULL;
system[i]->forcing_change_times = NULL;
system[i]->forcing_indices = NULL;
system[i]->save_flag = 0;
system[i]->peak_flag = 0;
system[i]->user = NULL;
//system[i]->equations = NULL;
}
//Setup the child and parent information
for(i=0;i<*N;i++)
{
for(j=0;j<system[i]->numparents;j++)
{
curr_loc = find_link_by_idtoloc(loc_to_children[i][j],*id_to_loc,*N);
if(curr_loc > *N)
{
if(my_rank == 0) printf("Error: Invalid id in topology data (%u).\n",loc_to_children[i][j]);
*N = 0;
return NULL;
}
system[i]->parents[j] = system[curr_loc];
system[curr_loc]->c = system[i];
}
}
//Set an outletlink id. This only sets one outlet, and only if rvr_flag is not set.
if(GlobalVars->prm_flag == 1 && GlobalVars->rvr_flag == 0)
{
for(i=0;i<*N;i++)
if(system[i]->c == NULL) break;
GlobalVars->outletlink = system[i]->ID;
}
//Clean up
free(loc_to_children);
free(loc_to_children_array);
free(link_ids);
free(numparents);
return system;
}
//Read in the local paramters for the network.
//Returns 1 if there is an error, 0 otherwise.
//If load_all == 1, then the parameters for every link are available on every proc.
//If load_all == 0, then the parameters are only available for links assigned to this proc.
int Load_Local_Parameters(Link** system,unsigned int N,unsigned int* my_sys,unsigned int my_N,int* assignments,short int* getting,unsigned int** id_to_loc,UnivVars* GlobalVars,ConnData** db_connections,short int load_all,model* custom_model,void* external)
{
unsigned int i,j,*db_link_id,curr_loc;
int db;
double *db_params_array,**db_params;
PGresult *res;
FILE* paramdata;
//Error checking
if(!load_all && (!assignments || !getting))
{
if(my_rank == 0)
{
printf("Error loading link parameters: network partitioning must occur before loading parameters.\n");
printf("(Hint: either partition the network before loading parameters, or load parameters at every link.)\n");
}
return 1;
}
//Allocate space
db_link_id = (unsigned int*) malloc(N*sizeof(unsigned int));
db_params_array = (double*) malloc(N*GlobalVars->disk_params*sizeof(double));
db_params = (double**) malloc(N*sizeof(double*));
for(i=0;i<N;i++) db_params[i] = &(db_params_array[i*GlobalVars->disk_params]);
//Read parameters
if(my_rank == 0)
{
if(GlobalVars->prm_flag == 0)
{
paramdata = fopen(GlobalVars->prm_filename,"r");
if(paramdata == NULL)
{
printf("Error: file %s not found for .prm file.\n",GlobalVars->prm_filename);
return 1;
}
if(CheckWinFormat(paramdata))
{
printf("Error: File %s appears to be in Windows format. Try converting to unix format using 'dos2unix' at the command line.\n",GlobalVars->prm_filename);
fclose(paramdata);
return 1;
}
fscanf(paramdata,"%u",&i);
if(i != N)
{
printf("Error: expected %u links in parameter file. Got %u.\n",N,i);
return 1;
}
for(i=0;i<N;i++)
{
fscanf(paramdata,"%u",&(db_link_id[i]));
for(j=0;j<GlobalVars->disk_params;j++)
{
if(fscanf(paramdata,"%lf",&(db_params[i][j])) == 0)
{
printf("Error reading from parameter file %s.\n",GlobalVars->prm_filename);
return 1;
}
}
}
fclose(paramdata);
}
else if(GlobalVars->prm_flag == 1)
{
//printf("\nTransferring parameter data from database...\n");
//start = time(NULL);
if(GlobalVars->outletlink == 0) //Grab entire network
{
db = ConnectPGDB(db_connections[ASYNCH_DB_LOC_PARAMS]);
if(db)
{
printf("[%i]: Error connecting to the parameter database.\n",my_rank);
return 1;
}
res = PQexec(db_connections[ASYNCH_DB_LOC_PARAMS]->conn,db_connections[ASYNCH_DB_LOC_PARAMS]->queries[0]);
if(CheckResError(res,"querying DEM data")) return 1;
DisconnectPGDB(db_connections[ASYNCH_DB_LOC_PARAMS]);
}
else //Grab a sub basin
{
db = ConnectPGDB(db_connections[ASYNCH_DB_LOC_PARAMS]);
if(db)
{
printf("[%i]: Error connecting to the parameter database.\n",my_rank);
return 1;
}
//Make the queries
sprintf(db_connections[ASYNCH_DB_LOC_PARAMS]->query,db_connections[ASYNCH_DB_LOC_PARAMS]->queries[1],GlobalVars->outletlink);
res = PQexec(db_connections[ASYNCH_DB_LOC_PARAMS]->conn,db_connections[ASYNCH_DB_LOC_PARAMS]->query);
if(CheckResError(res,"querying DEM data")) return 1;
DisconnectPGDB(db_connections[ASYNCH_DB_LOC_PARAMS]);
}
i = PQntuples(res);
if(i != N)
{
printf("Error processing link parameters: Got %u, expected %u.\n(Hint: make sure your topology and parameter sources have the same number of links.)\n",i,N);
return 1;
}
//Load buffers
for(i=0;i<N;i++) db_link_id[i] = atoi(PQgetvalue(res,i,0));
for(i=0;i<N;i++)
for(j=0;j<GlobalVars->disk_params;j++)
db_params[i][j] = atof(PQgetvalue(res,i,1+j));
//Cleanup
PQclear(res);
}
//stop = time(NULL);
//printf("Time to receive data: %f\n",difftime(stop,start));
}
//Broadcast data
MPI_Bcast(db_link_id,N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(db_params_array,N*GlobalVars->disk_params,MPI_DOUBLE,0,MPI_COMM_WORLD);
//Unpack the data
if(load_all)
{
for(i=0;i<N;i++)
{
curr_loc = find_link_by_idtoloc(db_link_id[i],id_to_loc,N);
if(curr_loc > N)
{
if(my_rank == 0) printf("Error: link id %u appears in the link parameters, but not in the topology data.\n(Hint: make sure your topology and parameter sources are correct.)\n",db_link_id[i]);
return 1;
}
system[curr_loc]->params = v_get(GlobalVars->params_size);
for(j=0;j<GlobalVars->disk_params;j++)
system[curr_loc]->params->ve[j] = db_params[i][j];
if(custom_model) custom_model->Convert(system[curr_loc]->params,GlobalVars->type,external);
else ConvertParams(system[curr_loc]->params,GlobalVars->type,external);
}
}
else //Just load the local parameters
{
for(i=0;i<N;i++)
{
curr_loc = find_link_by_idtoloc(db_link_id[i],id_to_loc,N);
if(curr_loc > N)
{
if(my_rank == 0) printf("Error: link id %u appears in the link parameters, but not in the topology data.\n(Hint: make sure your topology and parameter sources are correct.)\n",db_link_id[i]);
return 1;
}
else
{
if(assignments[curr_loc] == my_rank || getting[curr_loc])
{
system[curr_loc]->params = v_get(GlobalVars->params_size);
for(j=0;j<GlobalVars->disk_params;j++)
system[curr_loc]->params->ve[j] = db_params[i][j];
if(custom_model) custom_model->Convert(system[curr_loc]->params,GlobalVars->type,external);
else ConvertParams(system[curr_loc]->params,GlobalVars->type,external);
}
}
}
}
//Clean up
free(db_link_id);
free(db_params_array);
free(db_params);
return 0;
}
//Partitions the network amongst different MPI processes.
//!!!! Perhaps the leaves info could be moved deeper? How about errors here? !!!!
int Parition_Network(Link** system,unsigned int N,UnivVars* GlobalVars,unsigned int** my_sys,unsigned int* my_N,int** assignments,TransData** my_data,short int** getting,model* custom_model)
{
unsigned int i,j;
Link *current,*prev;//**upstream_order = (Link**) malloc(N*sizeof(Link*));
/*
//Order the links by upstream area
for(i=0;i<N;i++)
upstream_order[i] = system[i];
merge_sort(upstream_order,N,GlobalVars->area_idx);
*/
//Perform a DFS to sort the leaves
Link** stack = malloc(N*sizeof(Link*)); //Holds the index in system
int stack_size = 0;
Link** leaves = malloc(N*sizeof(Link*));
unsigned int leaves_size = 0;
unsigned short int numparents;
for(j=0;j<N;j++) //!!!! Iterate over a list of roots? No need to sort then... !!!!
{
if(system[j]->c == NULL)
{
stack[0] = system[j];
stack_size = 1;
while(stack_size > 0)
{
current = stack[stack_size-1]; //Top of stack
numparents = current->numparents;
if(numparents == 0)
{
stack_size--;
leaves[leaves_size] = current;
leaves_size++;
}
else
{
//If current is not a leaf, replace it with its parents
for(i=0;i<numparents;i++)
{
stack[stack_size - 1 + i] = current->parents[numparents - 1 - i];
//stack[stack_size - 1 + i]->c = current;
}
stack_size += numparents - 1;
}
}
}
//else
// break;
}
//!!!! Why is this needed? !!!!
//Calculate the distance and number of upstream links for each link
for(i=0;i<N;i++) system[i]->distance = 0;
for(i=0;i<leaves_size;i++)
{
prev = leaves[i];
prev->distance = 1;
for(current = prev->c; current != NULL; current = current->c)
{
if(current->distance > prev->distance+1) break;
else current->distance = prev->distance + 1;
prev = current;
}
}
//Partition the system and assign the links
*my_data = Initialize_TransData();
*getting = (short int*) malloc(N*sizeof(short int));
if(custom_model && custom_model->Partitioning)
*assignments = custom_model->Partitioning(system,N,leaves,leaves_size,my_sys,my_N,*my_data,*getting);
else
{
*assignments = Partition_System_By_Leaves(system,N,leaves,leaves_size,my_sys,my_N,*my_data,*getting);
//*assignments = Partition_System_By_Leaves_2(system,N,leaves,leaves_size,my_sys,my_N,*my_data,*getting);
//*assignments = Partition_METIS_Traditional(system,N,leaves,leaves_size,my_sys,my_N,*my_data,*getting,GlobalVars);
//*assignments = Partition_METIS_RainChanges(system,N,leaves,leaves_size,my_sys,my_N,*my_data,*getting,GlobalVars);
//*assignments = Partition_METIS_RainVolume(system,N,leaves,leaves_size,my_sys,my_N,*my_data,*getting,GlobalVars); //!!!! Requires params for all links !!!!
}
//Clean up
free(stack);
free(leaves);
//free(upstream_order);
return 0;
}
//Reads numerical error tolerances. Builds RK methods.
//!!!! I'm not really sure how to handle specifying the dimension here. Should the rkd file allow a variable number of tols? !!!!
int Build_RKData(Link** system,char rk_filename[],unsigned int N,unsigned int* my_sys,unsigned int my_N,int* assignments,short int* getting,UnivVars* GlobalVars,ErrorData* GlobalErrors,RKMethod*** AllMethods,unsigned int* nummethods)
{
unsigned int i,j,size,*link_ids,*methods;
FILE* rkdata;
double *filedata_abs,*filedata_rel,*filedata_abs_dense,*filedata_rel_dense;
//Build all the RKMethods
*nummethods = 4;
*AllMethods = malloc(*nummethods * sizeof(RKMethod*));
(*AllMethods)[0] = RKDense3_2();
(*AllMethods)[1] = TheRKDense4_3();
(*AllMethods)[2] = DOPRI5_dense();
(*AllMethods)[3] = RadauIIA3_dense();
GlobalVars->max_localorder = (*AllMethods)[0]->localorder;
GlobalVars->max_s = (*AllMethods)[0]->s;
for(i=1;i<*nummethods;i++)
{
GlobalVars->max_localorder = (GlobalVars->max_localorder < (*AllMethods)[i]->localorder) ? (*AllMethods)[i]->localorder : GlobalVars->max_localorder;
GlobalVars->max_s = (GlobalVars->max_s > (*AllMethods)[i]->s) ? GlobalVars->max_s : (*AllMethods)[i]->s;
//!!!! Note: Use a +1 for Radau solver? !!!!
}
if(rk_filename[0] != '\0')
{
link_ids = (unsigned int*) malloc(N*sizeof(unsigned int));
methods = (unsigned int*) malloc(N*sizeof(unsigned int));
if(my_rank == 0)
{
rkdata = fopen(rk_filename,"r");
if(rkdata == NULL)
{
printf("Error: file %s not found for .rkd file\n",rk_filename);
return 1;
}
if(CheckWinFormat(rkdata))
{
printf("Error: File %s appears to be in Windows format. Try converting to unix format using 'dos2unix' at the command line.\n",rk_filename);
fclose(rkdata);
return 1;
}
fscanf(rkdata,"%u %u",&i,&size);
if(i != N)
{
printf("Error: the number of links in the rkd file differ from the number in the topology data (Got %u, expected %u).\n",i,N);
return 1;
}
MPI_Bcast(&size,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
filedata_abs = (double*) malloc(N*size*sizeof(double));
filedata_rel = (double*) malloc(N*size*sizeof(double));
filedata_abs_dense = (double*) malloc(N*size*sizeof(double));
filedata_rel_dense = (double*) malloc(N*size*sizeof(double));
methods = (unsigned int*) malloc(size*sizeof(unsigned int));
//Read the file
for(i=0;i<N;i++)
{
if(fscanf(rkdata,"%u",&(link_ids[i])) == 0)
{
printf("Error reading .rkd file: Not enough links in file (expected %u, got %u).\n",N,i);
return 1;
}
for(j=0;j<size;i++) fscanf(rkdata,"%lf",&(filedata_abs[i*size+j]));
for(j=0;j<size;i++) fscanf(rkdata,"%lf",&(filedata_rel[i*size+j]));
for(j=0;j<size;i++) fscanf(rkdata,"%lf",&(filedata_abs_dense[i*size+j]));
for(j=0;j<size;i++) fscanf(rkdata,"%lf",&(filedata_rel_dense[i*size+j]));
fscanf(rkdata,"%u",&(methods[i]));
}
}
else
{
MPI_Bcast(&size,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
filedata_abs = (double*) malloc(N*size*sizeof(double));
filedata_rel = (double*) malloc(N*size*sizeof(double));
filedata_abs_dense = (double*) malloc(N*size*sizeof(double));
filedata_rel_dense = (double*) malloc(N*size*sizeof(double));
}
//Broadcast data
MPI_Bcast(link_ids,N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
MPI_Bcast(filedata_abs,N*size,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(filedata_rel,N*size,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(filedata_abs_dense,N*size,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(filedata_rel_dense,N*size,MPI_DOUBLE,0,MPI_COMM_WORLD);
MPI_Bcast(methods,N,MPI_UNSIGNED,0,MPI_COMM_WORLD);
//Construct error data at each link
for(i=0;i<N;i++)
{
if(assignments[i] == my_rank || getting[i])
{
system[i]->errorinfo = (ErrorData*) malloc(sizeof(ErrorData));
system[i]->errorinfo->abstol = v_get(size);
system[i]->errorinfo->reltol = v_get(size);
system[i]->errorinfo->abstol_dense = v_get(size);
system[i]->errorinfo->reltol_dense = v_get(size);
system[i]->errorinfo->facmax = GlobalErrors->facmax;
system[i]->errorinfo->facmin = GlobalErrors->facmin;
system[i]->errorinfo->fac = GlobalErrors->fac;
for(j=0;j<size;j++)
{
system[i]->errorinfo->abstol->ve[j] = filedata_abs[i*size+j];
system[i]->errorinfo->reltol->ve[j] = filedata_rel[i*size+j];
system[i]->errorinfo->abstol_dense->ve[j] = filedata_abs_dense[i*size+j];
system[i]->errorinfo->reltol_dense->ve[j] = filedata_rel_dense[i*size+j];
}
system[i]->method = (*AllMethods)[methods[i]];
}
}
}
else
{
for(i=0;i<N;i++)
{
if(assignments[i] == my_rank || getting[i])
{
system[i]->errorinfo = GlobalErrors;
system[i]->method = (*AllMethods)[GlobalVars->method];
}
}
}
return 0;
}
//Runs the init routine for the model. Also performs precalculations.
//Returns 0 if everything is ok, 1 if an error occurred.
int Initialize_Model(Link** system,unsigned int N,unsigned int* my_sys,unsigned int my_N,int* assignments,short int* getting,UnivVars* GlobalVars,model* custom_model,void* external)
{
unsigned int i,j,max_dim = 0,smallest_dim;
int my_error_code = 0,error_code;
for(i=0;i<N;i++)
{
if(assignments[i] == my_rank || getting[i])
{
if(custom_model)
{
custom_model->Routines(system[i],GlobalVars->type,system[i]->method->exp_imp,system[i]->dam,external);
custom_model->Precalculations(system[i],GlobalVars->global_params,system[i]->params,GlobalVars->disk_params,GlobalVars->params_size,system[i]->dam,GlobalVars->type,external);
}
else
{
InitRoutines(system[i],GlobalVars->type,system[i]->method->exp_imp,system[i]->dam,external);
Precalculations(system[i],GlobalVars->global_params,system[i]->params,GlobalVars->disk_params,GlobalVars->params_size,system[i]->dam,GlobalVars->type,external);
}
max_dim = (max_dim < system[i]->dim) ? system[i]->dim : max_dim;
//Be sure the problem dimension and number of error tolerances are compatible
if(assignments[i] == my_rank)
{
smallest_dim = system[i]->errorinfo->abstol->dim;
if(smallest_dim > system[i]->errorinfo->reltol->dim) smallest_dim = system[i]->errorinfo->reltol->dim;
if(smallest_dim > system[i]->errorinfo->abstol_dense->dim) smallest_dim = system[i]->errorinfo->abstol_dense->dim;
if(smallest_dim > system[i]->errorinfo->reltol_dense->dim) smallest_dim = system[i]->errorinfo->reltol_dense->dim;
if(GlobalVars->min_error_tolerances > smallest_dim)
{
printf("[%i] Error: link id %u does not have enough error tolerances (got %u, expected %u)\n",my_rank,system[i]->ID,smallest_dim,system[i]->dim);
my_error_code = 1;
break;
}
}
}
}
//Check if an error occurred
MPI_Allreduce(&my_error_code,&error_code,1,MPI_INT,MPI_LOR,MPI_COMM_WORLD);
if(error_code) return 1;
//Make sure all procs know how large the problem is everywhere
MPI_Allreduce(&max_dim,&(GlobalVars->max_dim),1,MPI_UNSIGNED,MPI_MAX,MPI_COMM_WORLD);
for(i=0;i<N;i++)
MPI_Bcast(&(system[i]->dim),1,MPI_UNSIGNED,assignments[i],MPI_COMM_WORLD);
//Mix dense_indices with print_indices
unsigned int loc,num_to_add;
Link* current;
unsigned int* states_to_add = (unsigned int*) malloc(GlobalVars->num_states_for_printing*sizeof(unsigned int)); //!!!! Only mix if save_flag set !!!!
for(loc=0;loc<N;loc++)
{
if(assignments[loc] == my_rank || getting[loc])
{
current = system[loc];
num_to_add = 0;
for(i=0;i<GlobalVars->num_states_for_printing;i++)
{
if(GlobalVars->print_indices[i] > current->dim) continue; //State is not present at this link
for(j=0;j<current->num_dense;j++)
if(GlobalVars->print_indices[i] == current->dense_indices[j]) break;
if(j == current->num_dense)
states_to_add[num_to_add++] = GlobalVars->print_indices[i];
}
if(num_to_add)
{
current->dense_indices = (unsigned int*) realloc(current->dense_indices,(current->num_dense + num_to_add)*sizeof(unsigned int));
for(i=0;i<num_to_add;i++)
current->dense_indices[i+current->num_dense] = states_to_add[i];
current->num_dense += num_to_add;
merge_sort_1D(current->dense_indices,current->num_dense);
}
}
}
free(states_to_add);
//Make sure all procs know the number of dense states at each link
for(i=0;i<N;i++)
MPI_Bcast(&(system[i]->num_dense),1,MPI_UNSIGNED,assignments[i],MPI_COMM_WORLD);
return 0;
}
//Loads the initial conditions.
//!!!! This assumes what about the dimension??? Wow, I don't think it has to assume anything... !!!!
//Initial state (0 = .ini, 1 = .uini, 2 = .rec, 3 = .dbc)
int Load_Initial_Conditions(Link** system,unsigned int N,int* assignments,short int* getting,unsigned int** id_to_loc,UnivVars* GlobalVars,ConnData** db_connections,model* custom_model,void* external)
{
unsigned int i,j,id,loc,no_ini_start,diff_start = 0;
FILE* initdata = NULL;
short int *who_needs = NULL;
short int my_need;
VEC *y_0 = v_get(0);
PGresult *res;
if(GlobalVars->init_flag == 0) //.ini ******************************************************************************************
{
//Proc 0 reads the file and sends the data to the other procs
if(my_rank == 0)
{
initdata = fopen(GlobalVars->init_filename,"r");
if(!initdata)
{
printf("Error: file %s not found for .ini file.\n",GlobalVars->init_filename);
return 1;
}
if(CheckWinFormat(initdata))
{
printf("Error: File %s appears to be in Windows format. Try converting to unix format using 'dos2unix' at the command line.\n",GlobalVars->init_filename);
fclose(initdata);
return 1;
}
fscanf(initdata,"%*i %u %lf",&i,&(GlobalVars->t_0)); //Read model type, number of links, init time
if(i != N)
{
printf("Error: the number of links in %s differs from the number in the topology data. (Got %u, expected %u)\n",GlobalVars->init_filename,i,N);
return 1;
}
//Broadcast initial time
MPI_Bcast(&(GlobalVars->t_0),1,MPI_DOUBLE,0,MPI_COMM_WORLD);
//Read the .ini file
who_needs = (short int*) malloc(np*sizeof(short int));
for(i=0;i<N;i++)
{
//Send current location
fscanf(initdata,"%u",&id);
loc = find_link_by_idtoloc(id,id_to_loc,N);
if(loc > N)
{
printf("Error: link id %u in initial condition file, but not in network.\n",id);
return 1;
}
MPI_Bcast(&loc,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
//See who needs info about this link.
//0 means the proc doesn't need it, 1 means link is assigned to proc, 2 means the link is a ghost to the proc.
my_need = (assignments[loc] == my_rank) ? 1 : ((getting[loc]) ? 2 : 0);
MPI_Gather(&my_need,1,MPI_SHORT,who_needs,1,MPI_SHORT,0,MPI_COMM_WORLD);
if(my_need == 1)
{
no_ini_start = system[loc]->no_ini_start;
diff_start = system[loc]->diff_start;
y_0->dim = system[loc]->dim;
}
else
{
MPI_Recv(&no_ini_start,1,MPI_UNSIGNED,assignments[loc],1,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
MPI_Recv(&diff_start,1,MPI_UNSIGNED,assignments[loc],1,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
MPI_Recv(&(y_0->dim),1,MPI_UNSIGNED,assignments[loc],1,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
}
//Read init data
y_0->ve = (double*) realloc(y_0->ve,y_0->dim*sizeof(double));
for(j=diff_start;j<no_ini_start;j++)
{
if( 0 == fscanf(initdata,"%lf",&(y_0->ve[j])) )
{
printf("Error: not enough states in .ini file.\n");
return 1;
}
}
//Send data to assigned proc and getting proc
if(assignments[loc] == my_rank || getting[loc])
{
if(custom_model)
system[loc]->state = custom_model->InitializeEqs(GlobalVars->global_params,system[loc]->params,system[loc]->qvs,system[loc]->dam,y_0,GlobalVars->type,diff_start,no_ini_start,system[loc]->user,external);
else
system[loc]->state = ReadInitData(GlobalVars->global_params,system[loc]->params,system[loc]->qvs,system[loc]->dam,y_0,GlobalVars->type,diff_start,no_ini_start,system[loc]->user,external);
system[loc]->list = Create_List(y_0,GlobalVars->t_0,y_0->dim,system[loc]->num_dense,system[loc]->method->s,GlobalVars->iter_limit);
system[loc]->list->head->state = system[loc]->state;
system[loc]->last_t = GlobalVars->t_0;
}
if(assignments[loc] != my_rank)
MPI_Send(&(y_0->ve[diff_start]),no_ini_start-diff_start,MPI_DOUBLE,assignments[loc],2,MPI_COMM_WORLD);
if(!(getting[loc]))
{
for(j=0;j<np;j++) if(who_needs[j] == 2) break;
if(j < np)
MPI_Send(&(y_0->ve[diff_start]),no_ini_start-diff_start,MPI_DOUBLE,(int) j,2,MPI_COMM_WORLD);
}
}
//Clean up
fclose(initdata);
free(who_needs);
}
else
{
//Get initial time
MPI_Bcast(&(GlobalVars->t_0),1,MPI_DOUBLE,0,MPI_COMM_WORLD);
who_needs = (short int*) malloc(np*sizeof(short int));
for(i=0;i<N;i++)
{
//Get link location
MPI_Bcast(&loc,1,MPI_UNSIGNED,0,MPI_COMM_WORLD);
//Is data needed for this link assigned at this proc?
my_need = (assignments[loc] == my_rank) ? 1 : ((getting[loc]) ? 2 : 0);
MPI_Gather(&my_need,1,MPI_SHORT,who_needs,1,MPI_SHORT,0,MPI_COMM_WORLD);
if(my_need)
{
no_ini_start = system[loc]->no_ini_start;
diff_start = system[loc]->diff_start;
y_0->dim = system[loc]->dim;
if(assignments[loc] == my_rank)
{
MPI_Send(&no_ini_start,1,MPI_UNSIGNED,0,1,MPI_COMM_WORLD);
MPI_Send(&diff_start,1,MPI_UNSIGNED,0,1,MPI_COMM_WORLD);
MPI_Send(&(y_0->dim),1,MPI_UNSIGNED,0,1,MPI_COMM_WORLD); //!!!! Actually, this might be available everywhere now !!!!
}
y_0->ve = (double*) realloc(y_0->ve,y_0->dim*sizeof(double));
MPI_Recv(&(y_0->ve[diff_start]),no_ini_start-diff_start,MPI_DOUBLE,0,2,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
if(custom_model)
system[loc]->state = custom_model->InitializeEqs(GlobalVars->global_params,system[loc]->params,system[loc]->qvs,system[loc]->dam,y_0,GlobalVars->type,diff_start,no_ini_start,system[loc]->user,external);
else
system[loc]->state = ReadInitData(GlobalVars->global_params,system[loc]->params,system[loc]->qvs,system[loc]->dam,y_0,GlobalVars->type,diff_start,no_ini_start,system[loc]->user,external);
system[loc]->list = Create_List(y_0,GlobalVars->t_0,y_0->dim,system[loc]->num_dense,system[loc]->method->s,GlobalVars->iter_limit);
system[loc]->list->head->state = system[loc]->state;
system[loc]->last_t = GlobalVars->t_0;
}
}
free(who_needs);
}
//Clean up
v_free(y_0);
}
else if(GlobalVars->init_flag == 1) //.uini ******************************************************************************************
{
//Proc 0 reads the initial conds, and send them to the other procs
if(my_rank == 0)
{
initdata = fopen(GlobalVars->init_filename,"r");
if(!initdata)
{
printf("Error: file %s not found for .uini file.\n",GlobalVars->init_filename);
return 1;
}
if(CheckWinFormat(initdata))
{
printf("Error: File %s appears to be in Windows format. Try converting to unix format using 'dos2unix' at the command line.\n",GlobalVars->init_filename);
fclose(initdata);
return 1;
}
fscanf(initdata,"%*i %lf",&(GlobalVars->t_0)); //Read model type, init time
}
//Broadcast the initial time
MPI_Bcast(&(GlobalVars->t_0),1,MPI_DOUBLE,0,MPI_COMM_WORLD);
//Get number of values to read from disk (and error checking)
for(i=0;i<N;i++)
{