summaryrefslogtreecommitdiff
path: root/src/org/unitConverter/unit/Unit.java
blob: 737802ab5556f0f964b43688975c7766db31297d (plain)
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
/**
 * Copyright (C) 2019 Adrien Hopkins
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package org.unitConverter.unit;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.DoubleUnaryOperator;

import org.unitConverter.math.ObjectProduct;

/**
 * A unit that is composed of base units.
 * 
 * @author Adrien Hopkins
 * @since 2019-10-16
 */
public abstract class Unit {
	/**
	 * A class that can be used to specify names and a symbol for a unit.
	 * 
	 * @author Adrien Hopkins
	 * @since 2019-10-21
	 */
	public static final class NameSymbol {
		public static final NameSymbol EMPTY = new NameSymbol(Optional.empty(), Optional.empty(), new HashSet<>());

		/**
		 * Gets a {@code NameSymbol} with a primary name, a symbol and no other names.
		 * 
		 * @param name
		 *            name to use
		 * @param symbol
		 *            symbol to use
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if name or symbol is null
		 */
		public static final NameSymbol of(final String name, final String symbol) {
			return new NameSymbol(Optional.of(name), Optional.of(symbol), new HashSet<>());
		}

		/**
		 * Gets a {@code NameSymbol} with a primary name, a symbol and additional names.
		 * 
		 * @param name
		 *            name to use
		 * @param symbol
		 *            symbol to use
		 * @param otherNames
		 *            other names to use
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if any argument is null
		 */
		public static final NameSymbol of(final String name, final String symbol, final Set<String> otherNames) {
			return new NameSymbol(Optional.of(name), Optional.of(symbol),
					new HashSet<>(Objects.requireNonNull(otherNames, "otherNames must not be null.")));
		}

		/**
		 * h * Gets a {@code NameSymbol} with a primary name, a symbol and additional names.
		 * 
		 * @param name
		 *            name to use
		 * @param symbol
		 *            symbol to use
		 * @param otherNames
		 *            other names to use
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if any argument is null
		 */
		public static final NameSymbol of(final String name, final String symbol, final String... otherNames) {
			return new NameSymbol(Optional.of(name), Optional.of(symbol),
					new HashSet<>(Arrays.asList(Objects.requireNonNull(otherNames, "otherNames must not be null."))));
		}

		/**
		 * Gets a {@code NameSymbol} with a primary name, a symbol and an additional name.
		 * 
		 * @param name
		 *            name to use
		 * @param symbol
		 *            symbol to use
		 * @param otherNames
		 *            other names to use
		 * @param name2
		 *            alternate name
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if any argument is null
		 */
		public static final NameSymbol of(final String name, final String symbol, final String name2) {
			final Set<String> otherNames = new HashSet<>();
			otherNames.add(Objects.requireNonNull(name2, "name2 must not be null."));
			return new NameSymbol(Optional.of(name), Optional.of(symbol), otherNames);
		}

		/**
		 * Gets a {@code NameSymbol} with a primary name, a symbol and additional names.
		 * 
		 * @param name
		 *            name to use
		 * @param symbol
		 *            symbol to use
		 * @param otherNames
		 *            other names to use
		 * @param name2
		 *            alternate name
		 * @param name3
		 *            alternate name
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if any argument is null
		 */
		public static final NameSymbol of(final String name, final String symbol, final String name2,
				final String name3) {
			final Set<String> otherNames = new HashSet<>();
			otherNames.add(Objects.requireNonNull(name2, "name2 must not be null."));
			otherNames.add(Objects.requireNonNull(name3, "name3 must not be null."));
			return new NameSymbol(Optional.of(name), Optional.of(symbol), otherNames);
		}

		/**
		 * Gets a {@code NameSymbol} with a primary name, a symbol and additional names.
		 * 
		 * @param name
		 *            name to use
		 * @param symbol
		 *            symbol to use
		 * @param otherNames
		 *            other names to use
		 * @param name2
		 *            alternate name
		 * @param name3
		 *            alternate name
		 * @param name4
		 *            alternate name
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if any argument is null
		 */
		public static final NameSymbol of(final String name, final String symbol, final String name2,
				final String name3, final String name4) {
			final Set<String> otherNames = new HashSet<>();
			otherNames.add(Objects.requireNonNull(name2, "name2 must not be null."));
			otherNames.add(Objects.requireNonNull(name3, "name3 must not be null."));
			otherNames.add(Objects.requireNonNull(name4, "name4 must not be null."));
			return new NameSymbol(Optional.of(name), Optional.of(symbol), otherNames);
		}

		/**
		 * Gets a {@code NameSymbol} with a primary name, no symbol, and no other names.
		 * 
		 * @param name
		 *            name to use
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if name is null
		 */
		public static final NameSymbol ofName(final String name) {
			return new NameSymbol(Optional.of(name), Optional.empty(), new HashSet<>());
		}

		/**
		 * Gets a {@code NameSymbol} with a symbol and no names.
		 * 
		 * @param symbol
		 *            symbol to use
		 * @return NameSymbol instance
		 * @since 2019-10-21
		 * @throws NullPointerException
		 *             if symbol is null
		 */
		public static final NameSymbol ofSymbol(final String symbol) {
			return new NameSymbol(Optional.empty(), Optional.of(symbol), new HashSet<>());
		}

		private final Optional<String> primaryName;
		private final Optional<String> symbol;

		private final Set<String> otherNames;

		/**
		 * Creates the {@code NameSymbol}.
		 * 
		 * @param primaryName
		 *            primary name of unit
		 * @param symbol
		 *            symbol used to represent unit
		 * @param otherNames
		 *            other names and/or spellings
		 * @since 2019-10-21
		 */
		private NameSymbol(final Optional<String> primaryName, final Optional<String> symbol,
				final Set<String> otherNames) {
			this.primaryName = primaryName;
			this.symbol = symbol;
			this.otherNames = Collections.unmodifiableSet(otherNames);
		}

		/**
		 * @return otherNames
		 * @since 2019-10-21
		 */
		public final Set<String> getOtherNames() {
			return this.otherNames;
		}

		/**
		 * @return primaryName
		 * @since 2019-10-21
		 */
		public final Optional<String> getPrimaryName() {
			return this.primaryName;
		}

		/**
		 * @return symbol
		 * @since 2019-10-21
		 */
		public final Optional<String> getSymbol() {
			return this.symbol;
		}
	}

	/**
	 * Returns a unit from its base and the functions it uses to convert to and from its base.
	 * 
	 * <p>
	 * For example, to get a unit representing the degree Celsius, the following code can be used:
	 * 
	 * {@code Unit.fromConversionFunctions(SI.KELVIN, tempK -> tempK - 273.15, tempC -> tempC + 273.15);}
	 * </p>
	 * 
	 * @param base
	 *            unit's base
	 * @param converterFrom
	 *            function that accepts a value expressed in the unit's base and returns that value expressed in this
	 *            unit.
	 * @param converterTo
	 *            function that accepts a value expressed in the unit and returns that value expressed in the unit's
	 *            base.
	 * @return a unit that uses the provided functions to convert.
	 * @since 2019-05-22
	 * @throws NullPointerException
	 *             if any argument is null
	 */
	public static final Unit fromConversionFunctions(final ObjectProduct<BaseUnit> base,
			final DoubleUnaryOperator converterFrom, final DoubleUnaryOperator converterTo) {
		return new FunctionalUnit(base, converterFrom, converterTo);
	}

	/**
	 * Returns a unit from its base and the functions it uses to convert to and from its base.
	 * 
	 * <p>
	 * For example, to get a unit representing the degree Celsius, the following code can be used:
	 * 
	 * {@code Unit.fromConversionFunctions(SI.KELVIN, tempK -> tempK - 273.15, tempC -> tempC + 273.15);}
	 * </p>
	 * 
	 * @param base
	 *            unit's base
	 * @param converterFrom
	 *            function that accepts a value expressed in the unit's base and returns that value expressed in this
	 *            unit.
	 * @param converterTo
	 *            function that accepts a value expressed in the unit and returns that value expressed in the unit's
	 *            base.
	 * @param ns
	 *            names and symbol of unit
	 * @return a unit that uses the provided functions to convert.
	 * @since 2019-05-22
	 * @throws NullPointerException
	 *             if any argument is null
	 */
	public static final Unit fromConversionFunctions(final ObjectProduct<BaseUnit> base,
			final DoubleUnaryOperator converterFrom, final DoubleUnaryOperator converterTo, final NameSymbol ns) {
		return new FunctionalUnit(base, converterFrom, converterTo, ns);
	}

	/**
	 * The combination of units that this unit is based on.
	 * 
	 * @since 2019-10-16
	 */
	private final ObjectProduct<BaseUnit> unitBase;

	/**
	 * The primary name used by this unit.
	 */
	private final Optional<String> primaryName;

	/**
	 * A short symbol used to represent this unit.
	 */
	private final Optional<String> symbol;

	/**
	 * A set of any additional names and/or spellings that the unit uses.
	 */
	private final Set<String> otherNames;

	/**
	 * Cache storing the result of getDimension()
	 *
	 * @since 2019-10-16
	 */
	private transient ObjectProduct<BaseDimension> dimension = null;

	/**
	 * Creates the {@code AbstractUnit}.
	 * 
	 * @param unitBase
	 *            base of unit
	 * @param ns
	 *            names and symbol of unit
	 * @since 2019-10-16
	 * @throws NullPointerException
	 *             if unitBase or ns is null
	 */
	protected Unit(final ObjectProduct<BaseUnit> unitBase, final NameSymbol ns) {
		this.unitBase = Objects.requireNonNull(unitBase, "unitBase must not be null.");
		this.primaryName = Objects.requireNonNull(ns, "ns must not be null.").getPrimaryName();
		this.symbol = ns.getSymbol();
		this.otherNames = ns.getOtherNames();
	}

	/**
	 * A constructor that constructs {@code BaseUnit} instances.
	 * 
	 * @since 2019-10-16
	 */
	Unit(final String primaryName, final String symbol, final Set<String> otherNames) {
		if (this instanceof BaseUnit) {
			this.unitBase = ObjectProduct.oneOf((BaseUnit) this);
		} else
			throw new AssertionError();
		this.primaryName = Optional.of(primaryName);
		this.symbol = Optional.of(symbol);
		this.otherNames = Collections.unmodifiableSet(
				new HashSet<>(Objects.requireNonNull(otherNames, "additionalNames must not be null.")));
	}

	/**
	 * Checks if a value expressed in this unit can be converted to a value expressed in {@code other}
	 * 
	 * @param other
	 *            unit to test with
	 * @return true if the units are compatible
	 * @since 2019-01-13
	 * @since v0.1.0
	 * @throws NullPointerException
	 *             if other is null
	 */
	public final boolean canConvertTo(final Unit other) {
		Objects.requireNonNull(other, "other must not be null.");
		return Objects.equals(this.getBase(), other.getBase());
	}

	/**
	 * Converts from a value expressed in this unit's base unit to a value expressed in this unit.
	 * <p>
	 * This must be the inverse of {@code convertToBase}, so {@code convertFromBase(convertToBase(value))} must be equal
	 * to {@code value} for any value, ignoring precision loss by roundoff error.
	 * </p>
	 * <p>
	 * If this unit <i>is</i> a base unit, this method should return {@code value}.
	 * </p>
	 * 
	 * @implSpec This method is used by {@link #convertTo}, and its behaviour affects the behaviour of
	 *           {@code convertTo}.
	 * 
	 * @param value
	 *            value expressed in <b>base</b> unit
	 * @return value expressed in <b>this</b> unit
	 * @since 2018-12-22
	 * @since v0.1.0
	 */
	protected abstract double convertFromBase(double value);

	/**
	 * Converts a value expressed in this unit to a value expressed in {@code other}.
	 * 
	 * @implSpec If unit conversion is possible, this implementation returns
	 *           {@code other.convertFromBase(this.convertToBase(value))}. Therefore, overriding either of those methods
	 *           will change the output of this method.
	 * 
	 * @param other
	 *            unit to convert to
	 * @param value
	 *            value to convert
	 * @return converted value
	 * @since 2019-05-22
	 * @throws IllegalArgumentException
	 *             if {@code other} is incompatible for conversion with this unit (as tested by
	 *             {@link Unit#canConvertTo}).
	 * @throws NullPointerException
	 *             if other is null
	 */
	public final double convertTo(final Unit other, final double value) {
		Objects.requireNonNull(other, "other must not be null.");
		if (this.canConvertTo(other))
			return other.convertFromBase(this.convertToBase(value));
		else
			throw new IllegalArgumentException(String.format("Cannot convert from %s to %s.", this, other));
	}

	/**
	 * Converts from a value expressed in this unit to a value expressed in this unit's base unit.
	 * <p>
	 * This must be the inverse of {@code convertFromBase}, so {@code convertToBase(convertFromBase(value))} must be
	 * equal to {@code value} for any value, ignoring precision loss by roundoff error.
	 * </p>
	 * <p>
	 * If this unit <i>is</i> a base unit, this method should return {@code value}.
	 * </p>
	 * 
	 * @implSpec This method is used by {@link #convertTo}, and its behaviour affects the behaviour of
	 *           {@code convertTo}.
	 * 
	 * @param value
	 *            value expressed in <b>this</b> unit
	 * @return value expressed in <b>base</b> unit
	 * @since 2018-12-22
	 * @since v0.1.0
	 */
	protected abstract double convertToBase(double value);

	/**
	 * @return combination of units that this unit is based on
	 * @since 2018-12-22
	 * @since v0.1.0
	 */
	public final ObjectProduct<BaseUnit> getBase() {
		return this.unitBase;
	}

	/**
	 * @return dimension measured by this unit
	 * @since 2018-12-22
	 * @since v0.1.0
	 */
	public final ObjectProduct<BaseDimension> getDimension() {
		if (this.dimension == null) {
			final Map<BaseUnit, Integer> mapping = this.unitBase.exponentMap();
			final Map<BaseDimension, Integer> dimensionMap = new HashMap<>();

			for (final BaseUnit key : mapping.keySet()) {
				dimensionMap.put(key.getBaseDimension(), mapping.get(key));
			}

			this.dimension = ObjectProduct.fromExponentMapping(dimensionMap);
		}
		return this.dimension;
	}

	/**
	 * @return additionalNames
	 * @since 2019-10-21
	 */
	public final Set<String> getOtherNames() {
		return this.otherNames;
	}

	/**
	 * @return primaryName
	 * @since 2019-10-21
	 */
	public final Optional<String> getPrimaryName() {
		return this.primaryName;
	}

	/**
	 * @return symbol
	 * @since 2019-10-21
	 */
	public final Optional<String> getSymbol() {
		return this.symbol;
	}

	@Override
	public String toString() {
		return this.getPrimaryName().orElse("Unnamed unit")
				+ (this.getSymbol().isPresent() ? String.format(" (%s)", this.getSymbol().get()) : "")
				+ ", derived from " + this.getBase().toString(u -> u.getSymbol().get())
				+ (this.getOtherNames().isEmpty() ? "" : ", also called " + String.join(", ", this.getOtherNames()));
	}

	/**
	 * @param ns
	 *            name(s) and symbol to use
	 * @return a copy of this unit with provided name(s) and symbol
	 * @since 2019-10-21
	 * @throws NullPointerException
	 *             if ns is null
	 */
	public Unit withName(final NameSymbol ns) {
		return fromConversionFunctions(this.getBase(), this::convertFromBase, this::convertToBase,
				Objects.requireNonNull(ns, "ns must not be null."));
	}
}