summaryrefslogtreecommitdiff
path: root/src/main/java/sevenUnits/utils/ObjectProduct.java
blob: 772ff5eabde9c152f7f2afb78e97537cab548c06 (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
/**
 * Copyright (C) 2018, 2021, 2024, 2025 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 sevenUnits.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;

/**
 * An immutable product of multiple objects of a type, such as base units. The
 * objects can be multiplied and exponentiated.
 * 
 * @author Adrien Hopkins
 * @param <T> type of object that is being multiplied
 * @since 2019-10-16
 */
public class ObjectProduct<T> implements Nameable {
	/**
	 * If {@link #toExponentRounded}'s rounding changes exponents by more than
	 * this value, a warning will be printed to standard error.
	 */
	private static final double ROUND_WARN_THRESHOLD = 1e-12;
	
	/**
	 * Returns an empty ObjectProduct of a certain type
	 * 
	 * @param <T> type of objects that can be multiplied
	 * @return empty product
	 * @since 2019-10-16
	 */
	public static final <T> ObjectProduct<T> empty() {
		return new ObjectProduct<>(new HashMap<>());
	}
	
	/**
	 * Gets an {@code ObjectProduct} from an object-to-integer mapping
	 * 
	 * @param <T> type of object in product
	 * @param map map mapping objects to exponents
	 * @return object product
	 * @since 2019-10-16
	 */
	public static final <T> ObjectProduct<T> fromExponentMapping(
			final Map<T, Integer> map) {
		return new ObjectProduct<>(new HashMap<>(map));
	}
	
	/**
	 * Gets an ObjectProduct that has one of the inputted argument, and nothing
	 * else.
	 * 
	 * @param object object that will be in the product
	 * @param <T> type of object contained in returned ObjectProduct
	 * @return product
	 * @since 2019-10-16
	 * @throws NullPointerException if object is null
	 */
	public static final <T> ObjectProduct<T> oneOf(final T object) {
		Objects.requireNonNull(object, "object must not be null.");
		final Map<T, Integer> map = new HashMap<>();
		map.put(object, 1);
		return new ObjectProduct<>(map);
	}
	
	/**
	 * The objects that make up the product, mapped to their exponents. This map
	 * treats zero as null, and is immutable.
	 * 
	 * @since 2019-10-16
	 */
	final Map<T, Integer> exponents;
	
	/**
	 * The object's name and symbol
	 */
	private final NameSymbol nameSymbol;
	
	/**
	 * Creates a {@code ObjectProduct} without a name/symbol.
	 * 
	 * @param exponents objects that make up this product
	 * @since 2019-10-16
	 */
	ObjectProduct(final Map<T, Integer> exponents) {
		this(exponents, NameSymbol.EMPTY);
	}
	
	/**
	 * Creates the {@code ObjectProduct}.
	 * 
	 * @param exponents  objects that make up this product
	 * @param nameSymbol name and symbol of object product
	 * @since 2019-10-16
	 */
	ObjectProduct(final Map<T, Integer> exponents, NameSymbol nameSymbol) {
		this.exponents = Collections.unmodifiableMap(
				ConditionalExistenceCollections.conditionalExistenceMap(exponents,
						e -> !Integer.valueOf(0).equals(e.getValue())));
		this.nameSymbol = nameSymbol;
	}
	
	/**
	 * Calculates the quotient of two products
	 *
	 * @param other other product
	 * @return quotient of two products
	 * @since 2019-10-16
	 * @throws NullPointerException if other is null
	 */
	public ObjectProduct<T> dividedBy(final ObjectProduct<T> other) {
		Objects.requireNonNull(other, "other must not be null.");
		// get a list of all objects in both sets
		final Set<T> objects = new HashSet<>();
		objects.addAll(this.getBaseSet());
		objects.addAll(other.getBaseSet());
		
		// get a list of all exponents
		final Map<T, Integer> map = new HashMap<>(objects.size());
		for (final T key : objects) {
			map.put(key, this.getExponent(key) - other.getExponent(key));
		}
		
		// create the product
		return new ObjectProduct<>(map);
	}
	
	// this method relies on the use of ZeroIsNullMap
	@Override
	public boolean equals(final Object obj) {
		if (this == obj)
			return true;
		if (!(obj instanceof ObjectProduct))
			return false;
		final ObjectProduct<?> other = (ObjectProduct<?>) obj;
		return Objects.equals(this.exponents, other.exponents);
	}
	
	/**
	 * @return immutable map mapping objects to exponents
	 * @since 2019-10-16
	 */
	public Map<T, Integer> exponentMap() {
		return this.exponents;
	}
	
	/**
	 * @return a set of all of the base objects with non-zero exponents that make
	 *         up this dimension.
	 * @since 2018-12-12
	 * @since v0.1.0
	 */
	public final Set<T> getBaseSet() {
		final Set<T> dimensions = new HashSet<>();
		
		// add all dimensions with a nonzero exponent - zero exponents shouldn't
		// be there in the first place
		for (final T dimension : this.exponents.keySet()) {
			if (!this.exponents.get(dimension).equals(0)) {
				dimensions.add(dimension);
			}
		}
		
		return dimensions;
	}
	
	/**
	 * Gets the exponent for a specific dimension.
	 * 
	 * @param dimension dimension to check
	 * @return exponent for that dimension
	 * @since 2018-12-12
	 * @since v0.1.0
	 */
	public int getExponent(final T dimension) {
		return this.exponents.getOrDefault(dimension, 0);
	}
	
	@Override
	public NameSymbol getNameSymbol() {
		return this.nameSymbol;
	}
	
	@Override
	public int hashCode() {
		return Objects.hash(this.exponents);
	}
	
	/**
	 * @return true if this product is a single object, i.e. it has one exponent
	 *         of one and no other nonzero exponents
	 * @since 2019-10-16
	 */
	public boolean isSingleObject() {
		int oneCount = 0;
		boolean twoOrMore = false; // has exponents of 2 or more
		for (final T b : this.getBaseSet()) {
			if (this.getExponent(b) == 1) {
				oneCount++;
			} else if (this.getExponent(b) != 0) {
				twoOrMore = true;
			}
		}
		return oneCount == 1 && !twoOrMore;
	}
	
	/**
	 * Multiplies this product by another
	 *
	 * @param other other product
	 * @return product of two products
	 * @since 2019-10-16
	 * @throws NullPointerException if other is null
	 */
	public ObjectProduct<T> times(final ObjectProduct<T> other) {
		Objects.requireNonNull(other, "other must not be null.");
		// get a list of all objects in both sets
		final Set<T> objects = new HashSet<>();
		objects.addAll(this.getBaseSet());
		objects.addAll(other.getBaseSet());
		
		// get a list of all exponents
		final Map<T, Integer> map = new HashMap<>(objects.size());
		for (final T key : objects) {
			map.put(key, this.getExponent(key) + other.getExponent(key));
		}
		
		// create the product
		return new ObjectProduct<>(map);
	}
	
	/**
	 * Returns this product, but to an exponent
	 * 
	 * @param exponent exponent
	 * @return result of exponentiation
	 * @since 2019-10-16
	 */
	public ObjectProduct<T> toExponent(final int exponent) {
		final Map<T, Integer> map = new HashMap<>(this.exponents);
		for (final T key : this.exponents.keySet()) {
			map.put(key, this.getExponent(key) * exponent);
		}
		return new ObjectProduct<>(map);
	}
	
	/**
	 * Returns this product to an exponent, where every dimension is rounded to
	 * the nearest integer.
	 * 
	 * This function will send a warning (via standard error) if the rounding
	 * significantly changes the value.
	 * 
	 * @param exponent exponent to raise this product to
	 * @return result of exponentiation
	 *
	 * @since 2024-08-22
	 */
	public ObjectProduct<T> toExponentRounded(final double exponent) {
		final Map<T, Integer> map = new HashMap<>(this.exponents);
		for (final T key : this.exponents.keySet()) {
			final double newExponent = this.getExponent(key) * exponent;
			if (Math.abs(
					newExponent - Math.round(newExponent)) > ROUND_WARN_THRESHOLD) {
				System.err.printf(
						"Exponent Rounding Warning: Dimension exponents must be integers, so %d ^ %g = %g was rounded to %d.\n",
						this.getExponent(key), exponent, newExponent,
						Math.round(newExponent));
			}
			map.put(key, (int) Math.round(newExponent));
		}
		return new ObjectProduct<>(map);
	}
	
	/**
	 * Converts this product to a string using the objects'
	 * {@link Object#toString()} method (or {@link Nameable#getShortName} if
	 * available). If objects have a long toString representation, it is
	 * recommended to use {@link #toString(Function)} instead to shorten the
	 * returned string.
	 * 
	 * <p>
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		return this
				.toString(o -> o instanceof Nameable ? ((Nameable) o).getShortName()
						: o.toString());
	}
	
	/**
	 * Converts this product to a string. The objects that make up this product
	 * are represented by {@code objectToString}
	 * 
	 * @param objectToString function to convert objects to strings
	 * @return string representation of product
	 * @since 2019-10-16
	 */
	public String toString(final Function<T, String> objectToString) {
		final List<String> positiveStringComponents = new ArrayList<>();
		final List<String> negativeStringComponents = new ArrayList<>();
		
		// for each base object that makes up this object, add it and its exponent
		for (final T object : this.getBaseSet()) {
			final int exponent = this.exponents.get(object);
			if (exponent > 1) {
				positiveStringComponents.add(String.format("%s^%d",
						objectToString.apply(object), exponent));
			} else if (exponent == 1) {
				positiveStringComponents.add(objectToString.apply(object));
			} else if (exponent < 0) {
				negativeStringComponents.add(String.format("%s^%d",
						objectToString.apply(object), -exponent));
			}
		}
		
		final String positiveString = positiveStringComponents.isEmpty() ? "1"
				: String.join(" * ", positiveStringComponents);
		final String negativeString = negativeStringComponents.isEmpty() ? ""
				: " / " + String.join(" * ", negativeStringComponents);
		
		return positiveString + negativeString;
	}
	
	/**
	 * @param nameSymbol name to add to this product
	 * @return named version of this {@code ObjectProduct}, using data from
	 *         {@code nameSymbol}
	 * @since 2021-12-15
	 */
	public ObjectProduct<T> withName(NameSymbol nameSymbol) {
		return new ObjectProduct<>(this.exponents, nameSymbol);
	}
}