Completed
Pull Request — master (#66)
by Daniel
06:11 queued 03:53
created

QuantityValue::getLowerBound()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace DataValues;
4
5
use InvalidArgumentException;
6
7
/**
8
 * Class representing a quantity with associated unit and uncertainty interval.
9
 * The amount is stored as a @see DecimalValue object.
10
 *
11
 * @see UnboundedQuantityValue For quantities with no known uncertainty interval.
12
 * For simple numeric amounts use @see NumberValue.
13
 *
14
 * @note UnboundedQuantityValue and QuantityValue both use the value type ID "quantity".
15
 * The fact that we use subclassing to model the bounded vs the unbounded case should be
16
 * considered an implementation detail.
17
 *
18
 * @since 0.1
19
 *
20
 * @license GPL-2.0+
21
 * @author Daniel Kinzler
22
 */
23
class QuantityValue extends UnboundedQuantityValue {
24
25
	/**
26
	 * The quantity's upper bound
27
	 *
28
	 * @var DecimalValue
29
	 */
30
	private $upperBound;
31
32
	/**
33
	 * The quantity's lower bound
34
	 *
35
	 * @var DecimalValue
36
	 */
37
	private $lowerBound;
38
39
	/**
40
	 * @param DecimalValue $amount
41
	 * @param string $unit A unit identifier. Must not be empty, use "1" for unit-less quantities.
42
	 * @param DecimalValue $upperBound The upper bound of the quantity, inclusive.
43
	 * @param DecimalValue $lowerBound The lower bound of the quantity, inclusive.
44
	 *
45
	 * @throws IllegalValueException
46
	 */
47
	public function __construct( DecimalValue $amount, $unit, DecimalValue $upperBound, DecimalValue $lowerBound ) {
48
		parent::__construct( $amount, $unit );
49
50
		if ( $lowerBound->compare( $amount ) > 0 ) {
0 ignored issues
show
Documentation introduced by
$amount is of type object<DataValues\DecimalValue>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
51
			throw new IllegalValueException( '$lowerBound ' . $lowerBound->getValue() . ' must be <= $amount ' . $amount->getValue() );
52
		}
53
54
		if ( $upperBound->compare( $amount ) < 0 ) {
0 ignored issues
show
Documentation introduced by
$amount is of type object<DataValues\DecimalValue>, but the function expects a object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
55
			throw new IllegalValueException( '$upperBound ' . $upperBound->getValue() . ' must be >= $amount ' . $amount->getValue() );
56
		}
57
58
		$this->upperBound = $upperBound;
59
		$this->lowerBound = $lowerBound;
60
	}
61
62
	/**
63
	 * Returns a QuantityValue representing the given amount.
64
	 * If no upper or lower bound is given, the amount is assumed to be absolutely exact,
65
	 * that is, the amount itself will be used as the upper and lower bound.
66
	 *
67
	 * This is a convenience wrapper around the constructor that accepts native values
68
	 * instead of DecimalValue objects.
69
	 *
70
	 * @note: if the amount or a bound is given as a string, the string must conform
71
	 * to the rules defined by @see DecimalValue.
72
	 *
73
	 * @since 0.1
74
	 *
75
	 * @param string|int|float|DecimalValue $amount
76
	 * @param string $unit A unit identifier. Must not be empty, use "1" for unit-less quantities.
77
	 * @param string|int|float|DecimalValue|null $upperBound
78
	 * @param string|int|float|DecimalValue|null $lowerBound
79
	 *
80
	 * @return self
81
	 * @throws IllegalValueException
82
	 */
83
	public static function newFromNumber( $amount, $unit = '1', $upperBound = null, $lowerBound = null ) {
84
		$amount = self::asDecimalValue( 'amount', $amount );
85
		$upperBound = self::asDecimalValue( 'upperBound', $upperBound, $amount );
86
		$lowerBound = self::asDecimalValue( 'lowerBound', $lowerBound, $amount );
87
88
		return new self( $amount, $unit, $upperBound, $lowerBound );
89
	}
90
91
	/**
92
	 * @see newFromNumber
93
	 *
94
	 * @deprecated since 0.1, use newFromNumber instead
95
	 *
96
	 * @param string|int|float|DecimalValue $amount
97
	 * @param string $unit
98
	 * @param string|int|float|DecimalValue|null $upperBound
99
	 * @param string|int|float|DecimalValue|null $lowerBound
100
	 *
101
	 * @return self
102
	 */
103
	public static function newFromDecimal( $amount, $unit = '1', $upperBound = null, $lowerBound = null ) {
104
		return self::newFromNumber( $amount, $unit, $upperBound, $lowerBound );
105
	}
106
107
	/**
108
	 * @see Serializable::serialize
109
	 *
110
	 * @since 0.1
111
	 *
112
	 * @return string
113
	 */
114
	public function serialize() {
115
		return serialize( array(
116
			$this->amount,
117
			$this->unit,
118
			$this->upperBound,
119
			$this->lowerBound,
120
		) );
121
	}
122
123
	/**
124
	 * @see Serializable::unserialize
125
	 *
126
	 * @since 0.1
127
	 *
128
	 * @param string $data
129
	 */
130
	public function unserialize( $data ) {
131
		list( $amount, $unit, $upperBound, $lowerBound ) = unserialize( $data );
132
		$this->__construct( $amount, $unit, $upperBound, $lowerBound );
133
	}
134
135
	/**
136
	 * Returns this quantity's upper bound.
137
	 *
138
	 * @since 0.1
139
	 *
140
	 * @return DecimalValue
141
	 */
142
	public function getUpperBound() {
143
		return $this->upperBound;
144
	}
145
146
	/**
147
	 * Returns this quantity's lower bound.
148
	 *
149
	 * @since 0.1
150
	 *
151
	 * @return DecimalValue
152
	 */
153
	public function getLowerBound() {
154
		return $this->lowerBound;
155
	}
156
157
	/**
158
	 * Returns the size of the uncertainty interval.
159
	 * This can roughly be interpreted as "amount +/- uncertainty/2".
160
	 *
161
	 * The exact interpretation of the uncertainty interval is left to the concrete application or
162
	 * data point. For example, the uncertainty interval may be defined to be that part of a
163
	 * normal distribution that is required to cover the 95th percentile.
164
	 *
165
	 * @since 0.1
166
	 *
167
	 * @return float
168
	 */
169
	public function getUncertainty() {
170
		return $this->upperBound->getValueFloat() - $this->lowerBound->getValueFloat();
171
	}
172
173
	/**
174
	 * Returns a DecimalValue representing the symmetrical offset to be applied
175
	 * to the raw amount for a rough representation of the uncertainty interval,
176
	 * as in "amount +/- offset".
177
	 *
178
	 * The offset is calculated as max( amount - lowerBound, upperBound - amount ).
179
	 *
180
	 * @todo Should be factored out into a separate QuantityMath class.
181
	 *
182
	 * @since 0.1
183
	 *
184
	 * @return DecimalValue
185
	 */
186
	public function getUncertaintyMargin() {
187
		$math = new DecimalMath();
188
189
		$lowerMargin = $math->sum( $this->amount, $this->lowerBound->computeComplement() );
190
		$upperMargin = $math->sum( $this->upperBound, $this->amount->computeComplement() );
191
192
		$margin = $math->max( $lowerMargin, $upperMargin );
193
		return $margin;
194
	}
195
196
	/**
197
	 * Returns the order of magnitude of the uncertainty as the exponent of
198
	 * last significant digit in the amount-string. The value returned by this
199
	 * is suitable for use with @see DecimalMath::roundToExponent().
200
	 *
201
	 * @example: if two digits after the decimal point are significant, this
202
	 * returns -2.
203
	 *
204
	 * @example: if the last two digits before the decimal point are insignificant,
205
	 * this returns 2.
206
	 *
207
	 * Note that this calculation assumes a symmetric uncertainty interval,
208
	 * and can be misleading.
209
	 *
210
	 * @todo Should be factored out into a separate QuantityMath class.
211
	 *
212
	 * @since 0.1
213
	 *
214
	 * @return int
215
	 */
216
	public function getOrderOfUncertainty() {
217
		// the desired precision is given by the distance between the amount and
218
		// whatever is closer, the upper or lower bound.
219
		//TODO: use DecimalMath to avoid floating point errors!
220
		$amount = $this->amount->getValueFloat();
221
		$upperBound = $this->upperBound->getValueFloat();
222
		$lowerBound = $this->lowerBound->getValueFloat();
223
		$precision = min( $amount - $lowerBound, $upperBound - $amount );
224
225
		if ( $precision === 0.0 ) {
226
			// If there is no uncertainty, the order of uncertainty is a bit more than what we have digits for.
227
			return -strlen( $this->amount->getFractionalPart() );
228
		}
229
230
		// e.g. +/- 200 -> 2; +/- 0.02 -> -2
231
		// note: we really want floor( log10( $precision ) ), but have to account for
232
		// small errors made in the floating point operations above.
233
		// @todo: use bcmath (via DecimalMath) to avoid this if possible
234
		$orderOfUncertainty = floor( log10( $precision + 0.0000000005 ) );
235
236
		return (int)$orderOfUncertainty;
237
	}
238
239
	/**
240
	 * Returns a transformed value derived from this QuantityValue by applying
241
	 * the given transformation to the amount and the upper and lower bounds.
242
	 * The resulting amount and bounds are rounded to the significant number of
243
	 * digits. Note that for exact quantities (with at least one bound equal to
244
	 * the amount), no rounding is applied (since they are considered to have
245
	 * infinite precision).
246
	 *
247
	 * The transformation is provided as a callback, which must implement a
248
	 * monotonously increasing, fully differentiable function mapping a DecimalValue
249
	 * to a DecimalValue. Typically, it will be a linear transformation applying a
250
	 * factor and an offset.
251
	 *
252
	 * @param string $newUnit The unit of the transformed quantity.
253
	 *
254
	 * @param callable $transformation A callback that implements the desired transformation.
255
	 *        The transformation will be called three times, once for the amount, once
256
	 *        for the lower bound, and once for the upper bound. It must return a DecimalValue.
257
	 *        The first parameter passed to $transformation is the DecimalValue to transform
258
	 *        In addition, any extra parameters passed to transform() will be passed through
259
	 *        to the transformation callback.
260
	 *
261
	 * @param mixed ... Any extra parameters will be passed to the $transformation function.
262
	 *
263
	 * @todo share more code with UnboundQuantityValue::transform.
264
	 * @todo Should be factored out into a separate QuantityMath class.
265
	 *
266
	 * @throws InvalidArgumentException
267
	 * @return self
268
	 */
269
	public function transform( $newUnit, $transformation ) {
270
		if ( !is_callable( $transformation ) ) {
271
			throw new InvalidArgumentException( '$transformation must be callable.' );
272
		}
273
274
		if ( !is_string( $newUnit ) ) {
275
			throw new InvalidArgumentException( '$newUnit must be a string. Use "1" as the unit for unit-less quantities.' );
276
		}
277
278
		if ( $newUnit === '' ) {
279
			throw new InvalidArgumentException( '$newUnit must not be empty. Use "1" as the unit for unit-less quantities.' );
280
		}
281
282
		$oldUnit = $this->unit;
283
284
		if ( $newUnit === null ) {
285
			$newUnit = $oldUnit;
286
		}
287
288
		// Apply transformation by calling the $transform callback.
289
		// The first argument for the callback is the DataValue to transform. In addition,
290
		// any extra arguments given for transform() are passed through.
291
		$args = func_get_args();
292
		array_shift( $args );
293
294
		$args[0] = $this->amount;
295
		$amount = call_user_func_array( $transformation, $args );
296
297
		$args[0] = $this->upperBound;
298
		$upperBound = call_user_func_array( $transformation, $args );
299
300
		$args[0] = $this->lowerBound;
301
		$lowerBound = call_user_func_array( $transformation, $args );
302
303
		// use a preliminary QuantityValue to determine the significant number of digits
304
		$transformed = new self( $amount, $newUnit, $upperBound, $lowerBound );
305
		$roundingExponent = $transformed->getOrderOfUncertainty();
306
307
		// apply rounding to the significant digits
308
		$math = new DecimalMath();
309
310
		$amount = $math->roundToExponent( $amount, $roundingExponent );
311
		$upperBound = $math->roundToExponent( $upperBound, $roundingExponent );
312
		$lowerBound = $math->roundToExponent( $lowerBound, $roundingExponent );
313
314
		return new self( $amount, $newUnit, $upperBound, $lowerBound );
315
	}
316
317
	public function __toString() {
318
		return $this->amount->getValue()
319
			. '[' . $this->lowerBound->getValue()
320
			. '..' . $this->upperBound->getValue()
321
			. ']'
322
			. ( $this->unit === '1' ? '' : $this->unit );
323
	}
324
325
	/**
326
	 * @see DataValue::getArrayValue
327
	 *
328
	 * @since 0.1
329
	 *
330
	 * @return array
331
	 */
332
	public function getArrayValue() {
333
		return array(
334
			'amount' => $this->amount->getArrayValue(),
335
			'unit' => $this->unit,
336
			'upperBound' => $this->upperBound->getArrayValue(),
337
			'lowerBound' => $this->lowerBound->getArrayValue(),
338
		);
339
	}
340
341
	/**
342
	 * Constructs a new instance of the DataValue from the provided data.
343
	 * This can round-trip with @see getArrayValue
344
	 *
345
	 * @note: if the upperBound or lowerBound field is missing from $data,
346
	 * this returns an UnboundedQuantityValue, not a QuantityValue!
347
	 *
348
	 * @since 0.1
349
	 *
350
	 * @param mixed $data
351
	 *
352
	 * @return UnboundedQuantityValue
353
	 * @throws IllegalValueException
354
	 */
355
	public static function newFromArray( $data ) {
356
		if ( !isset( $data['upperBound'] ) || !isset( $data['lowerBound'] ) ) {
357
			// No bounds given, so construct an unbounded QuantityValue.
358
			return parent::newFromArray( $data );
359
		}
360
361
		self::requireArrayFields( $data, array( 'amount', 'unit', 'upperBound', 'lowerBound' ) );
362
363
		return new static(
364
			DecimalValue::newFromArray( $data['amount'] ),
365
			$data['unit'],
366
			DecimalValue::newFromArray( $data['upperBound'] ),
367
			DecimalValue::newFromArray( $data['lowerBound'] )
368
		);
369
	}
370
371
}
372