1 package org.opentrafficsim.simulationengine;
2
3
4
5
6
7
8
9
10
11
12
13 public class ProbabilityDistributionProperty extends AbstractProperty<Double[]>
14 {
15
16 private Double[] value;
17
18
19 private String[] names;
20
21
22 private String shortName;
23
24
25 private String description;
26
27
28 private final Boolean readOnly;
29
30
31
32
33
34
35
36
37
38
39
40
41 public ProbabilityDistributionProperty(final String shortName, final String description,
42 final String[] elementNames, final Double[] initialValue, final boolean readOnly, final int displayPriority)
43 throws PropertyException
44 {
45 super(displayPriority);
46 this.shortName = shortName;
47 this.description = description;
48 this.names = new String[elementNames.length];
49 for (int i = 0; i < elementNames.length; i++)
50 {
51 this.names[i] = elementNames[i];
52 }
53 verifyProposedValues(initialValue);
54 copyValue(initialValue);
55 this.readOnly = readOnly;
56 }
57
58
59
60
61
62
63
64 private void verifyProposedValues(final Double[] values) throws PropertyException
65 {
66 if (values.length < 1)
67 {
68 throw new PropertyException("Array of probability values may not be empty");
69 }
70 double sum = 0.0;
71 for (double v : values)
72 {
73 if (v < 0.0 || v > 1.0)
74 {
75 throw new PropertyException("Probability value " + v + " is invalid (valid range is 0.0..1.0)");
76 }
77 sum += v;
78 }
79 double maximumError = Math.ulp(1.0) * values.length;
80 if (sum < 1.0 - maximumError || sum > 1.0 + maximumError)
81 {
82 throw new PropertyException("Probabilities do not add up to 1.0 (actual sum is " + sum + ")");
83 }
84
85 }
86
87
88 @Override
89 public final Double[] getValue()
90 {
91
92
93 return this.value.clone();
94 }
95
96
97
98
99
100
101 final Double getValue(final int index)
102 {
103 return this.value[index];
104 }
105
106
107
108
109
110
111 final String getElementName(final int index)
112 {
113 return this.names[index];
114 }
115
116
117 @Override
118 public final String getShortName()
119 {
120 return this.shortName;
121 }
122
123
124 @Override
125 public final String getDescription()
126 {
127 return this.description;
128 }
129
130
131 @Override
132 public final void setValue(final Double[] newValue) throws PropertyException
133 {
134 if (this.readOnly)
135 {
136 throw new PropertyException("This property is read-only");
137 }
138 updateValue(newValue);
139 }
140
141
142
143
144
145 private void copyValue(final Double[] newValue)
146 {
147
148 this.value = new Double[newValue.length];
149 for (int i = 0; i < newValue.length; i++)
150 {
151 this.value[i] = newValue[i];
152 }
153 }
154
155
156
157
158
159 private void updateValue(final Double[] newValue) throws PropertyException
160 {
161 verifyProposedValues(newValue);
162 copyValue(newValue);
163 }
164
165
166
167
168
169 public final String[] getElementNames()
170 {
171 return this.names.clone();
172 }
173
174
175 @Override
176 public final boolean isReadOnly()
177 {
178 return this.readOnly;
179 }
180
181 }