caminos-lib 0.2.0

A modular interconnection network simulator.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223

use crate::config_parser::ConfigurationValue;
use crate::routing::CandidateEgress;
use crate::router::Router;
use crate::topology::{Topology,Location};
use crate::Plugs;
use std::cell::{RefCell};
use ::rand::{Rng,StdRng};

///Extra information to be used by the policies of virtual channels.
pub struct RequestInfo<'a>
{
	///target_router_index: The index of the router to which the destination server is attached.
	pub target_router_index: usize,
	///entry_port: The port for which the packet has entered into the current router.
	pub entry_port: usize,
	///entry_virtual_channel: The virtual_channel the packet used when it entered into the current router.
	pub entry_virtual_channel: usize,
	///performed_hops: the amount of hops already made by the packet.
	pub performed_hops: usize,
	///server_ports: a list of which ports from the current router go to server.
	pub server_ports: Option<&'a Vec<usize>>,
	///port_average_neighbour_queue_length: for each port the average queue length in the queues of the port in the neighbour router.
	pub port_average_neighbour_queue_length: Option<&'a Vec<f32>>,
	///port_last_transmission: a timestamp for each port of the last time that it was used.
	pub port_last_transmission: Option<&'a Vec<usize>>,
	///Number of phits currently in the output space of the current router at the indexed port.
	pub port_occupied_output_space: Option<&'a Vec<usize>>,
	///Number of available phits in the output space of the current router at the indexed port.
	pub port_available_output_space: Option<&'a Vec<usize>>,
	///Number of phits currently in the output space allocated to a virtual channel. Index by [port_index][virtual_channel].
	pub virtual_channel_occupied_output_space: Option<&'a Vec<Vec<usize>>>,
	///Number of available phits in the output space allocated to a virtual channel. Index by [port_index][virtual_channel].
	pub virtual_channel_available_output_space: Option<&'a Vec<Vec<usize>>>,
	///Number of cycles at the front of input space,
	pub time_at_front: Option<usize>,
	///current_cycle: The current cycle of the simulation.
	pub current_cycle: usize,
}

///How virtual channels are selected for a packet
///They provide the function filter(Vec<CandidateEgress>) -> Vec<CandidateEgress>
///It needs:
///	rng, self.virtual_ports(credits and length), phit.packet.routing_info.borrow().hops, server_ports,
/// topology.{distance,neighbour}, port_average_neighbour_queue_length, port_last_transmission
///We could also provide functions to declare which aspects must be computed. Thus allowing to both share when necessary and to not computing ti when unnecessary.
pub trait VirtualChannelPolicy
{
	///Apply the policy over a list of candidates and return the candidates that fulfil the policy requirements.
	///candidates: the list to be filtered.
	///router: the router in which the decision is being made.
	///topology: The network topology.
	///rng: the global random number generator.
	fn filter(&self, candidates:Vec<CandidateEgress>, router:&dyn Router, info: &RequestInfo, topology:&dyn Topology, rng: &RefCell<StdRng>) -> Vec<CandidateEgress>;
	fn need_server_ports(&self)->bool;
	fn need_port_average_queue_length(&self)->bool;
	fn need_port_last_transmission(&self)->bool;
}

#[non_exhaustive]
#[derive(Debug)]
pub struct VCPolicyBuilderArgument<'a>
{
	///A ConfigurationValue::Object defining the policy.
	pub cv: &'a ConfigurationValue,
	///The user defined plugs. In case the policy needs to create elements.
	pub plugs: &'a Plugs,
}

//pub fn new_virtual_channel_policy(cv: &ConfigurationValue, plugs:&Plugs) -> Box<dyn VirtualChannelPolicy>
pub fn new_virtual_channel_policy(arg:VCPolicyBuilderArgument) -> Box<dyn VirtualChannelPolicy>
{
	if let &ConfigurationValue::Object(ref cv_name, ref _cv_pairs)=arg.cv
	{
		match arg.plugs.policies.get(cv_name)
		{
			Some(builder) => return builder(arg),
			_ => (),
		};
		match cv_name.as_ref()
		{
			"Random" => Box::new(Random::new(arg)),
			"Shortest" => Box::new(Shortest::new(arg)),
			"Hops" => Box::new(Hops::new(arg)),
			"EnforceFlowControl" => Box::new(EnforceFlowControl::new(arg)),
			"WideHops" => Box::new(WideHops::new(arg)),
			"LowestSinghWeight" => Box::new(LowestSinghWeight::new(arg)),
			"LowestLabel" => Box::new(LowestLabel::new(arg)),
			"LabelSaturate" => Box::new(LabelSaturate::new(arg)),
			"LabelTransform" => Box::new(LabelTransform::new(arg)),
			"OccupancyFunction" => Box::new(OccupancyFunction::new(arg)),
			"NegateLabel" => Box::new(NegateLabel::new(arg)),
			"VecLabel" => Box::new(VecLabel::new(arg)),
			_ => panic!("Unknown traffic {}",cv_name),
		}
	}
	else
	{
		panic!("Trying to create a traffic from a non-Object");
	}
}

///Request a port+virtual channel at random from all available.
#[derive(Debug)]
pub struct Random{}

impl VirtualChannelPolicy for Random
{
	//fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, _target_router_index:usize, _entry_port:usize, _entry_virtual_channel:usize, _performed_hops:usize, _server_ports:&Option<Vec<usize>>, _port_average_neighbour_queue_length:&Option<Vec<f32>>, _port_last_transmission:&Option<Vec<usize>>, _port_occuped_output_space:&Option<Vec<usize>>, _port_available_output_space:&Option<Vec<usize>>, _current_cycle:usize, _topology:&dyn Topology, rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, _info: &RequestInfo, _topology:&dyn Topology, rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		vec![candidates[rng.borrow_mut().gen_range(0,candidates.len())].clone()]
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl Random
{
	pub fn new(_arg:VCPolicyBuilderArgument) -> Random
	{
		//let mut servers=None;
		//let mut load=None;
		//let mut pattern=None;
		//let mut message_size=None;
		//if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=cv
		//{
		//	if cv_name!="Random"
		//	{
		//		panic!("A Random must be created from a `Random` object not `{}`",cv_name);
		//	}
		//	for &(ref name,ref value) in cv_pairs
		//	{
		//		//match name.as_ref()
		//		match name.as_ref()
		//		{
		//			//"pattern" => pattern=Some(new_pattern(value)),
		//			//"servers" => match value
		//			//{
		//			//	&ConfigurationValue::Number(f) => servers=Some(f as usize),
		//			//	_ => panic!("bad value for servers"),
		//			//}
		//			//"load" => match value
		//			//{
		//			//	&ConfigurationValue::Number(f) => load=Some(f as f32),
		//			//	_ => panic!("bad value for load ({:?})",value),
		//			//}
		//			//"message_size" => match value
		//			//{
		//			//	&ConfigurationValue::Number(f) => message_size=Some(f as usize),
		//			//	_ => panic!("bad value for message_size"),
		//			//}
		//			_ => panic!("Nothing to do with field {} in Random",name),
		//		}
		//	}
		//}
		//else
		//{
		//	panic!("Trying to create a Random from a non-Object");
		//}
		//let servers=servers.expect("There were no servers");
		//let message_size=message_size.expect("There were no message_size");
		//let load=load.expect("There were no load");
		//let mut pattern=pattern.expect("There were no pattern");
		Random{}
	}
}

///Request the port+virtual channel with more credits. Does not solve ties, so it needs to be followed by Random or something.
#[derive(Debug)]
pub struct Shortest{}

impl VirtualChannelPolicy for Shortest
{
	fn filter(&self, candidates:Vec<CandidateEgress>, router:&dyn Router, _info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		let mut best=vec![];
		let mut best_credits=0;
		//for i in 1..vps.len()
		for i in 0..candidates.len()
		{
			let CandidateEgress{port:p,virtual_channel:vc,..}=candidates[i];
			//let next_credits=router.virtual_ports[p][vc].neighbour_credits;
			//let next_credits=router.get_virtual_port(p,vc).expect("This router does not have virtual ports (and not credits therefore)").neighbour_credits;
			let next_credits=router.get_status_at_emisor(p).expect("This router does not have transmission status").known_available_space_for_virtual_channel(vc).expect("remote available space is not known");
			if next_credits>best_credits
			{
				best_credits=next_credits;
				//best=vec![CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops}];
				best=vec![candidates[i].clone()];
			}
			else if next_credits==best_credits
			{
				//best.push(CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops});
				best.push(candidates[i].clone());
			}
		}
		best
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl Shortest
{
	pub fn new(_arg:VCPolicyBuilderArgument) -> Shortest
	{
		Shortest{}
	}
}


///Select virtual channel=packet.hops.
#[derive(Debug)]
pub struct Hops{}

impl VirtualChannelPolicy for Hops
{
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		let server_ports=info.server_ports.expect("server_ports have not been computed for policy Hops");
		let filtered=candidates.into_iter().filter(|&CandidateEgress{port,virtual_channel,label:_label,estimated_remaining_hops:_,..}|virtual_channel==info.performed_hops|| server_ports.contains(&port)).collect::<Vec<_>>();
		//let filtered=candidates.iter().filter_map(|e|if e.1==performed_hops{Some(*e)}else {None}).collect::<Vec<_>>();
		//if filtered.len()==0
		//{
		//	//panic!("There is no route from router {} to server {} increasing on virtual channels",self.router_index,phit.packet.message.destination);
		//	continue;
		//}
		//filtered[simulation.rng.borrow_mut().gen_range(0,filtered.len())]
		filtered
	}

	fn need_server_ports(&self)->bool
	{
		true
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl Hops
{
	pub fn new(_arg:VCPolicyBuilderArgument) -> Hops
	{
		Hops{}
	}
}

///
#[derive(Debug)]
pub struct EnforceFlowControl{}

impl VirtualChannelPolicy for EnforceFlowControl
{
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, _info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		let filtered=candidates.into_iter().filter(|candidate|candidate.router_allows.unwrap_or(true)).collect::<Vec<_>>();
		filtered
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl EnforceFlowControl
{
	pub fn new(_arg:VCPolicyBuilderArgument) -> EnforceFlowControl
	{
		EnforceFlowControl{}
	}
}


///Select virtual channel in (width*packet.hops..width*(packet.hops+1)).
#[derive(Debug)]
pub struct WideHops{
	width:usize,
}

impl VirtualChannelPolicy for WideHops
{
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		let server_ports=info.server_ports.expect("server_ports have not been computed for policy WideHops");
		let lower_limit = self.width*info.performed_hops;
		let upper_limit = self.width*(info.performed_hops+1);
		let filtered=candidates.into_iter().filter(
			|&CandidateEgress{port,virtual_channel,label:_,estimated_remaining_hops:_,..}| (lower_limit<=virtual_channel && virtual_channel<upper_limit) || server_ports.contains(&port)
		).collect::<Vec<_>>();
		//let filtered=candidates.iter().filter_map(|e|if e.1==info.performed_hops{Some(*e)}else {None}).collect::<Vec<_>>();
		//if filtered.len()==0
		//{
		//	//panic!("There is no route from router {} to server {} increasing on virtual channels",self.router_index,phit.packet.message.destination);
		//	continue;
		//}
		//filtered[simulation.rng.borrow_mut().gen_range(0,filtered.len())]
		filtered
	}

	fn need_server_ports(&self)->bool
	{
		true
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl WideHops
{
	pub fn new(arg:VCPolicyBuilderArgument) -> WideHops
	{
		let mut width=None;
		if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=arg.cv
		{
			if cv_name!="WideHops"
			{
				panic!("A WideHops must be created from a `WideHops` object not `{}`",cv_name);
			}
			for &(ref name,ref value) in cv_pairs
			{
				match AsRef::<str>::as_ref(&name)
				{
					"width" => match value
					{
						&ConfigurationValue::Number(f) => width=Some(f as usize),
						_ => panic!("bad value for width"),
					}
					_ => panic!("Nothing to do with field {} in WideHops",name),
				}
			}
		}
		else
		{
			panic!("Trying to create a WideHops from a non-Object");
		}
		let width=width.expect("There were no width");
		WideHops{
			width
		}
	}
}

///Select the lowest value of the product of the queue length (that is, consumed credits) times the estimated hop count (usually 1 plus the distance from next router to target router)
///This was initially proposed for the UGAL routing.
///parameters=(extra_congestion,extra_distance,aggregate_buffers), which are added in the formula to allow tuning. Firth two default to 0.
///aggregate_buffers indicates to use all buffers instead of just the selected one.
#[derive(Debug)]
pub struct LowestSinghWeight
{
	///constant added to the occupied space
	extra_congestion: usize,
	///constant added to the distance to target
	extra_distance: usize,
	///Whether we consider all the space in each port (when true) or we segregate by virtual channels (when false).
	///defaults to false
	aggregate_buffers: bool,
	///Whether to use internal output space in the calculations instead of the counters relative to the next router.
	///defaults to false
	use_internal_space: bool,
}

impl VirtualChannelPolicy for LowestSinghWeight
{
	fn filter(&self, candidates:Vec<CandidateEgress>, router:&dyn Router, info: &RequestInfo, topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		let port_average_neighbour_queue_length=info.port_average_neighbour_queue_length.expect("port_average_neighbour_queue_length have not been computed for policy LowestSinghWeight");
		let dist=topology.distance(router.get_index().expect("we need routers with index"),info.target_router_index);
		if dist==0
		{
			//do nothing
			candidates
		}
		else
		{
			let mut best=vec![];
			//let mut best_weight=<usize>::max_value();
			let mut best_weight=::std::f32::MAX;
			//for i in 0..candidates.len()
			//for CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops} in candidates
			for candidate in candidates
			{
				let CandidateEgress{port:p,virtual_channel:vc, ..} = candidate;
				//let (p,vc)=candidates[i];
				//let next_credits=self.virtual_ports[p][vc].neighbour_credits;
				//let next_consumed_credits=extra_congestion + self.buffer_size - next_credits;
				let next_consumed_credits:f32=(self.extra_congestion as f32)+if self.aggregate_buffers
				{
					if self.use_internal_space
					{
						let port_occupied_output_space=info.port_occupied_output_space.expect("port_occupied_output_space have not been computed for policy LowestSinghWeight");
						port_occupied_output_space[p] as f32
					}
					else
					{
						port_average_neighbour_queue_length[p]
					}
				}
				else
				{
					if self.use_internal_space
					{
						unimplemented!()
					}
					else
					{
						//(router.buffer_size - router.virtual_ports[p][vc].neighbour_credits) as f32
						let next_credits=router.get_status_at_emisor(p).expect("This router does not have transmission status").known_available_space_for_virtual_channel(vc).expect("remote available space is not known");
						(router.get_maximum_credits_towards(p,vc).expect("we need routers with maximum credits") - next_credits) as f32
					}
				};
				let next_router=if let (Location::RouterPort{router_index, router_port:_},_link_class)=topology.neighbour(router.get_index().expect("we need routers with index"),p)
				{
					router_index
				}
				else
				{
					panic!("We trying to go to the server when we are at distance {} greater than 0.",dist);
				};
				let distance=self.extra_distance + 1+topology.distance(next_router,info.target_router_index);
				let next_weight= next_consumed_credits * (distance as f32);
				if next_weight<best_weight
				{
					best_weight=next_weight;
					//best=vec![CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops}];
					best=vec![candidate];
				}
				else if next_weight==best_weight
				{
					//best.push(CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops});
					best.push(candidate);
				}
			}
			best
		}
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		true
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl LowestSinghWeight
{
	pub fn new(arg:VCPolicyBuilderArgument) -> LowestSinghWeight
	{
		let mut extra_congestion=None;
		let mut extra_distance=None;
		let mut aggregate_buffers=false;
		let mut use_internal_space=false;
		if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=arg.cv
		{
			if cv_name!="LowestSinghWeight"
			{
				panic!("A LowestSinghWeight must be created from a `LowestSinghWeight` object not `{}`",cv_name);
			}
			for &(ref name,ref value) in cv_pairs
			{
				match AsRef::<str>::as_ref(&name)
				{
 					"extra_congestion" => match value
 					{
 						&ConfigurationValue::Number(f) => extra_congestion=Some(f as usize),
 						_ => panic!("bad value for extra_congestion"),
 					}
 					"extra_distance" => match value
 					{
 						&ConfigurationValue::Number(f) => extra_distance=Some(f as usize),
 						_ => panic!("bad value for extra_distance"),
 					}
 					"aggregate_buffers" => match value
 					{
 						&ConfigurationValue::True => aggregate_buffers=true,
 						&ConfigurationValue::False => aggregate_buffers=false,
 						_ => panic!("bad value for aggregate_buffers"),
 					}
 					"use_internal_space" => match value
 					{
 						&ConfigurationValue::True => use_internal_space=true,
 						&ConfigurationValue::False => use_internal_space=false,
 						_ => panic!("bad value for use_internal_space"),
 					}
					_ => panic!("Nothing to do with field {} in LowestSinghWeight",name),
				}
			}
		}
		else
		{
			panic!("Trying to create a LowestSinghWeight from a non-Object");
		}
		let extra_congestion=extra_congestion.unwrap_or(0);
		let extra_distance=extra_distance.unwrap_or(0);
		LowestSinghWeight{
			extra_congestion,
			extra_distance,
			aggregate_buffers,
			use_internal_space,
		}
	}
}


///Select the egresses with lowest label.
#[derive(Debug)]
pub struct LowestLabel{}

impl VirtualChannelPolicy for LowestLabel
{
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, _info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		let mut best=vec![];
		let mut best_label=<i32>::max_value();
		//for CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops} in candidates
		for candidate in candidates
		{
			let label = candidate.label;
			if label<best_label
			{
				best_label=label;
				//best=vec![CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops}];
				best=vec![candidate];
			}
			else if label==best_label
			{
				//best.push(CandidateEgress{port:p,virtual_channel:vc,label,estimated_remaining_hops});
				best.push(candidate);
			}
		}
		best
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl LowestLabel
{
	pub fn new(_arg:VCPolicyBuilderArgument) -> LowestLabel
	{
		LowestLabel{}
	}
}












///New label = min{old_label,value} or max{old_label,value}
///(value,bottom)
#[derive(Debug)]
pub struct LabelSaturate
{
	value:i32,
	bottom:bool,
}

impl VirtualChannelPolicy for LabelSaturate
{
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, _info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		if self.bottom
		{
			candidates.into_iter().map(
				//|CandidateEgress{port,virtual_channel,label,estimated_remaining_hops}|
				|candidate|{
				let label= candidate.label;
				//label as usize <= simulation.cycle -1 - self.virtual_ports[port][virtual_channel].last_transmission
				let new_label = ::std::cmp::max(label,self.value);
				CandidateEgress{label:new_label,..candidate}
			}).collect::<Vec<_>>()
		}
		else
		{
			candidates.into_iter().map(
				|candidate|{
				let label= candidate.label;
				//label as usize <= simulation.cycle -1 - self.virtual_ports[port][virtual_channel].last_transmission
				let new_label = ::std::cmp::min(label,self.value);
				CandidateEgress{label:new_label,..candidate}
			}).collect::<Vec<_>>()
		}
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl LabelSaturate
{
	pub fn new(arg:VCPolicyBuilderArgument) -> LabelSaturate
	{
		let mut xvalue=None;
		let mut bottom=None;
		if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=arg.cv
		{
			if cv_name!="LabelSaturate"
			{
				panic!("A LabelSaturate must be created from a `LabelSaturate` object not `{}`",cv_name);
			}
			for &(ref name,ref value) in cv_pairs
			{
				match AsRef::<str>::as_ref(&name)
				{
					"value" => match value
					{
						&ConfigurationValue::Number(f) => xvalue=Some(f as i32),
						_ => panic!("bad value for value"),
					}
					"bottom" => match value
					{
						&ConfigurationValue::True => bottom=Some(true),
						&ConfigurationValue::False => bottom=Some(false),
						_ => panic!("bad value for bottom"),
					}
					_ => panic!("Nothing to do with field {} in LabelSaturate",name),
				}
			}
		}
		else
		{
			panic!("Trying to create a LabelSaturate from a non-Object");
		}
		let value=xvalue.expect("There were no value");
		let bottom=bottom.expect("There were no bottom");
		LabelSaturate{
			value,
			bottom,
		}
	}
}


///New label = old_label*multplier+summand.
///(multiplier,summand,saturate_bottom,saturate_top,minimum,maximum)
#[derive(Debug)]
pub struct LabelTransform
{
	multiplier:i32,
	summand:i32,
	saturate_bottom: Option<i32>,
	saturate_top: Option<i32>,
	minimum: Option<i32>,
	maximum: Option<i32>,
}

impl VirtualChannelPolicy for LabelTransform
{
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, _info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		candidates.into_iter().filter_map(
			//|CandidateEgress{port,virtual_channel,label,estimated_remaining_hops}|
			|candidate|{
			let mut new_label = candidate.label*self.multiplier + self.summand;
			//let new_label = ::std::cmp::min(::std::cmp::max(label*self.multiplier + self.summand, saturate_bottom),saturate_top);
			if let Some(value)=self.saturate_bottom
			{
				if value>new_label
				{
					new_label=value;
				}
			}
			if let Some(value)=self.saturate_top
			{
				if value<new_label
				{
					new_label=value;
				}
			}
			//if new_label>=minimum && new_label<=maximum;
			let mut good=true;
			if let Some(value)=self.minimum
			{
				if value>new_label
				{
					good=false;
				}
			}
			if let Some(value)=self.maximum
			{
				if value<new_label
				{
					good=false;
				}
			}
			if good
			{
				Some(CandidateEgress{label:new_label,..candidate})
			}
			else
			{
				None
			}
		}).collect::<Vec<_>>()
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		true
	}

}

impl LabelTransform
{
	pub fn new(arg:VCPolicyBuilderArgument) -> LabelTransform
	{
		let mut multiplier=None;
		let mut summand=None;
		let mut saturate_bottom=None;
		let mut saturate_top=None;
		let mut minimum=None;
		let mut maximum=None;
		if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=arg.cv
		{
			if cv_name!="LabelTransform"
			{
				panic!("A LabelTransform must be created from a `LabelTransform` object not `{}`",cv_name);
			}
			for &(ref name,ref value) in cv_pairs
			{
				match AsRef::<str>::as_ref(&name)
				{
					"multiplier" => match value
					{
						&ConfigurationValue::Number(f) => multiplier=Some(f as i32),
						_ => panic!("bad value for multiplier"),
					}
					"summand" => match value
					{
						&ConfigurationValue::Number(f) => summand=Some(f as i32),
						_ => panic!("bad value for summand"),
					}
					"saturate_bottom" => match value
					{
						&ConfigurationValue::Number(f) => saturate_bottom=Some(f as i32),
						_ => panic!("bad value for saturate_bottom"),
					}
					"saturate_top" => match value
					{
						&ConfigurationValue::Number(f) => saturate_top=Some(f as i32),
						_ => panic!("bad value for saturate_top"),
					}
					"minimum" => match value
					{
						&ConfigurationValue::Number(f) => minimum=Some(f as i32),
						_ => panic!("bad value for minimum"),
					}
					"maximum" => match value
					{
						&ConfigurationValue::Number(f) => maximum=Some(f as i32),
						_ => panic!("bad value for maximum"),
					}
					_ => panic!("Nothing to do with field {} in LabelTransform",name),
				}
			}
		}
		else
		{
			panic!("Trying to create a LabelTransform from a non-Object");
		}
		let multiplier=multiplier.expect("There were no multiplier");
		let summand=summand.expect("There were no summand");
		LabelTransform{
			multiplier,
			summand,
			saturate_bottom,
			saturate_top,
			minimum,
			maximum,
		}
	}
}




///Transform (l,q) into new label a*l+b*q+c*l*q+d
///where l is the label and q is the occupancy.
#[derive(Debug)]
pub struct OccupancyFunction
{
	///Which multiplies the label.
	label_coefficient: i32,
	///Which multiplies the occupancy.
	occupancy_coefficient: i32,
	///Which multiplies the product of label and occupancy.
	product_coefficient: i32,
	///Just added.
	constant_coefficient: i32,
	///Whether to include the own router buffers in the calculation.
	use_internal_space: bool,
	///Whether to include the known state of the next router buffers in the calculation.
	use_neighbour_space: bool,
	///Whether to aggregate all virtual channels associated to the port.
	///Defaults to true.
	aggregate: bool,
}

impl VirtualChannelPolicy for OccupancyFunction
{
	fn filter(&self, candidates:Vec<CandidateEgress>, router:&dyn Router, info: &RequestInfo, topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		//let port_average_neighbour_queue_length=port_average_neighbour_queue_length.as_ref().expect("port_average_neighbour_queue_length have not been computed for policy OccupancyFunction");
		let dist=topology.distance(router.get_index().expect("we need routers with index"),info.target_router_index);
		if dist==0
		{
			//do nothing
			candidates
		}
		else
		{
			candidates.into_iter().filter_map(
				//|CandidateEgress{port,virtual_channel,label,estimated_remaining_hops}|
				|candidate|{
				let CandidateEgress{port,virtual_channel,label,..} = candidate;
				let q=if self.use_internal_space
				{
					if self.aggregate
					{
						let port_occupied_output_space=info.port_occupied_output_space.expect("port_occupied_output_space have not been computed for policy OccupancyFunction");
						port_occupied_output_space[port] as i32
					}
					else
					{
						let virtual_channel_occupied_output_space=info.virtual_channel_occupied_output_space.expect("virtual_channel_occupied_output_space have not been computed for OccupancyFunction");
						virtual_channel_occupied_output_space[port][virtual_channel] as i32
					}
				}
				else {0} + if self.use_neighbour_space
				{
					if self.aggregate
					{
						//port_average_neighbour_queue_length[port]
						let status=router.get_status_at_emisor(port).expect("This router does not have transmission status");
						//FIXME: this could be different than the whole occuped space if using a DAMQ or something, although they are yet to be implemented.
						(0..status.num_virtual_channels()).map(|c|router.get_maximum_credits_towards(port,c).expect("we need routers with maximum credits") as i32 - status.known_available_space_for_virtual_channel(c).expect("remote available space is not known.") as i32).sum()
					}
					else
					{
						//port_average_neighbour_queue_length[port]
						let status=router.get_status_at_emisor(port).expect("This router does not have transmission status");
						router.get_maximum_credits_towards(port,virtual_channel).expect("we need routers with maximum credits") as i32 - status.known_available_space_for_virtual_channel(virtual_channel).expect("remote available space is not known.") as i32
					}
				}
				else {0};
				let new_label = self.label_coefficient*label + self.occupancy_coefficient*q + self.product_coefficient*label*q + self.constant_coefficient;
				Some(CandidateEgress{label:new_label,..candidate})
			}).collect::<Vec<_>>()
		}
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl OccupancyFunction
{
	pub fn new(arg:VCPolicyBuilderArgument) -> OccupancyFunction
	{
		let mut label_coefficient=None;
		let mut occupancy_coefficient=None;
		let mut product_coefficient=None;
		let mut constant_coefficient=None;
		let mut use_internal_space=false;
		let mut use_neighbour_space=false;
		let mut aggregate=true;
		if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=arg.cv
		{
			if cv_name!="OccupancyFunction"
			{
				panic!("A OccupancyFunction must be created from a `OccupancyFunction` object not `{}`",cv_name);
			}
			for &(ref name,ref value) in cv_pairs
			{
				match AsRef::<str>::as_ref(&name)
				{
					"label_coefficient" => match value
					{
						&ConfigurationValue::Number(f) => label_coefficient=Some(f as i32),
						_ => panic!("bad value for label_coefficient"),
					}
					"occupancy_coefficient" => match value
					{
						&ConfigurationValue::Number(f) => occupancy_coefficient=Some(f as i32),
						_ => panic!("bad value for occupancy_coefficient"),
					}
					"product_coefficient" => match value
					{
						&ConfigurationValue::Number(f) => product_coefficient=Some(f as i32),
						_ => panic!("bad value for product_coefficient"),
					}
					"constant_coefficient" => match value
					{
						&ConfigurationValue::Number(f) => constant_coefficient=Some(f as i32),
						_ => panic!("bad value for constant_coefficient"),
					}
 					"use_neighbour_space" => match value
 					{
 						&ConfigurationValue::True => use_neighbour_space=true,
 						&ConfigurationValue::False => use_neighbour_space=false,
 						_ => panic!("bad value for use_neighbour_space"),
 					}
 					"use_internal_space" => match value
 					{
 						&ConfigurationValue::True => use_internal_space=true,
 						&ConfigurationValue::False => use_internal_space=false,
 						_ => panic!("bad value for use_internal_space"),
 					}
 					"aggregate" => match value
 					{
 						&ConfigurationValue::True => aggregate=true,
 						&ConfigurationValue::False => aggregate=false,
 						_ => panic!("bad value for aggregate"),
 					}
					_ => panic!("Nothing to do with field {} in OccupancyFunction",name),
				}
			}
		}
		else
		{
			panic!("Trying to create a OccupancyFunction from a non-Object");
		}
		let label_coefficient=label_coefficient.expect("There were no multiplier");
		let occupancy_coefficient=occupancy_coefficient.expect("There were no multiplier");
		let product_coefficient=product_coefficient.expect("There were no multiplier");
		let constant_coefficient=constant_coefficient.expect("There were no multiplier");
		OccupancyFunction{
			label_coefficient,
			occupancy_coefficient,
			product_coefficient,
			constant_coefficient,
			use_internal_space,
			use_neighbour_space,
			aggregate,
		}
	}
}


///New label = -old_label
///Just until I fix the grammar to accept preceding minuses.
#[derive(Debug)]
pub struct NegateLabel
{
}

impl VirtualChannelPolicy for NegateLabel
{
	fn filter(&self, candidates:Vec<CandidateEgress>, _router:&dyn Router, _info: &RequestInfo, _topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		candidates.into_iter().filter_map(
			//|CandidateEgress{port,virtual_channel,label,estimated_remaining_hops}|
			|candidate|Some(CandidateEgress{label:-candidate.label,..candidate})
		).collect::<Vec<_>>()
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl NegateLabel
{
	pub fn new(arg:VCPolicyBuilderArgument) -> NegateLabel
	{
		if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=arg.cv
		{
			if cv_name!="NegateLabel"
			{
				panic!("A NegateLabel must be created from a `NegateLabel` object not `{}`",cv_name);
			}
			for &(ref name,ref _value) in cv_pairs
			{
				match AsRef::<str>::as_ref(&name)
				{
					//"multiplier" => match value
					//{
					//	&ConfigurationValue::Number(f) => multiplier=Some(f as i32),
					//	_ => panic!("bad value for multiplier"),
					//}
					_ => panic!("Nothing to do with field {} in NegateLabel",name),
				}
			}
		}
		else
		{
			panic!("Trying to create a NegateLabel from a non-Object");
		}
		NegateLabel{}
	}
}




///Vector of labels
///new_label = vector[old_label]
#[derive(Debug)]
pub struct VecLabel
{
	label_vector: Vec<i32>,
}

impl VirtualChannelPolicy for VecLabel
{
	fn filter(&self, candidates:Vec<CandidateEgress>, router:&dyn Router, info: &RequestInfo, topology:&dyn Topology, _rng: &RefCell<StdRng>) -> Vec<CandidateEgress>
	{
		//let port_average_neighbour_queue_length=port_average_neighbour_queue_length.as_ref().expect("port_average_neighbour_queue_length have not been computed for policy VecLabel");
		let dist=topology.distance(router.get_index().expect("we need routers with index"),info.target_router_index);
		if dist==0
		{
			//do nothing
			candidates
		}
		else
		{
			candidates.into_iter().filter_map(
				//|CandidateEgress{port,virtual_channel,label,estimated_remaining_hops}|
				|candidate|{
				let label = candidate.label;
				if label<0 || label>=self.label_vector.len() as i32
				{
					panic!("label={} is out of range 0..{}",label,self.label_vector.len());
				}
				let new_label = self.label_vector[label as usize];
				Some(CandidateEgress{label:new_label,..candidate})
			}).collect::<Vec<_>>()
		}
	}

	fn need_server_ports(&self)->bool
	{
		false
	}

	fn need_port_average_queue_length(&self)->bool
	{
		false
	}

	fn need_port_last_transmission(&self)->bool
	{
		false
	}

}

impl VecLabel
{
	pub fn new(arg:VCPolicyBuilderArgument) -> VecLabel
	{
		let mut label_vector=None;
		if let &ConfigurationValue::Object(ref cv_name, ref cv_pairs)=arg.cv
		{
			if cv_name!="VecLabel"
			{
				panic!("A VecLabel must be created from a `VecLabel` object not `{}`",cv_name);
			}
			for &(ref name,ref value) in cv_pairs
			{
				match AsRef::<str>::as_ref(&name)
				{
 					"label_vector" => match value
 					{
						&ConfigurationValue::Array(ref l) => label_vector=Some(l.iter().map(|v| match v{
							ConfigurationValue::Number(f) => *f as i32,
							_ => panic!("bad value for label_vector"),
						}).collect()),
 						_ => panic!("bad value for label_vector"),
 					}
					_ => panic!("Nothing to do with field {} in VecLabel",name),
				}
			}
		}
		else
		{
			panic!("Trying to create a VecLabel from a non-Object");
		}
		let label_vector=label_vector.expect("There were no label_vector");
		VecLabel{
			label_vector,
		}
	}
}