These are a running webassembly demos using .
|
Note
|
This section is work in progress |
Calculator
java
This is the source code for the above.
@Getter
public enum FieldInformation {
rational(RationalNumbers.INSTANCE,
"1 + 2",
"1 + 3/5"
),
real(RealField.INSTANCE,
"1 + 2",
"1 + 3/5",
"sin(𝜋/2)",
"sqr(𝜑) - 𝜑"
),
bigdecimal(BigDecimalField.INSTANCE,
"1 + 2",
"1 + 3/5",
"sin(𝜋/2)"
),
gaussian(GaussianRationals.INSTANCE,
"1 + 2",
"1 + 3/5",
"\"1 + 2i\" ⋅ 8i"
),
complex(ComplexNumbers.INSTANCE,
"1 + 2",
"1 + 3/5",
"sin(𝜋/2)",
"exp(-i ⋅ 𝜋)",
"\"2 + 3i\" ⋅ i"
),
bigcomplex(BigComplexNumbers.INSTANCE,
"1 + 2",
"1 + 3/5",
"\"1 + 2i\" ⋅ 8i"
),
quaternions(Quaternions.of(RationalNumbers.INSTANCE),
"1 + 2",
"1 + 3/5",
"\"1 + 2i + 3j + 4k\" ⋅ 8i"
),
quaternions_bigdecimal(Quaternions.of(BigDecimalField.INSTANCE),
"1 + 2",
"1 + 3/5",
"\"1 + 2i + 3j + 4k\" ⋅ 8i"
),
integers(Integers.INSTANCE,
"4 ⋅ 7",
"9 - 3",
"69!"
),
modulo10(ModuloRing.of(10),
"4 ⋅ 7",
"9 - 3"
),
modulo13(ModuloField.of(13),
"10 ⋅ 7",
"10 - 3",
"12 ⋅ 6 / 4"
),
natural(NaturalNumbers.INSTANCE,
"10 ⋅ 7",
"10 + 3",
"12 ⋅ 6 + 0"
),
even(EvenIntegers.INSTANCE,
"10 ⋅ 8",
"10 - 4"
),
odd(OddIntegers.INSTANCE,
"1 ⋅ 9",
"13 ⋅ 5"
),
squares(Squares.INSTANCE,
"4 ⋅ 9"
),
klein(KleinGroup.INSTANCE,
"a * b * c * e",
"a * b"
),
quaterniongroup(QuaternionGroup.INSTANCE,
"i * j",
"j * i",
"e * k * i"
),
dihedral3(DihedralGroup.D3,
"r1 * r2",
"s0 * r1 * s0"
),
dihedral4(DihedralGroup.of(4),
"r1 * r2",
"s0 * r1 * s0 * s3"
),
padic5(PAdicNumbers.of(5),
"1 / 3",
"\"...4 \" + 1",
"\"...0 12\" ⋅ 5",
"1 / 50"
),
padic13(PAdicNumbers.of(13),
"1 / 3",
"\"...c \" + 1",
"\"...0 1a\" ⋅ 13",
"1 / 26"
),
polynomials(PolynomialRing.of(GaussianRationals.INSTANCE),
"\"7·x + 15·x² + 2·x³ + 7·x⁵ + x⁶\" ⋅ \"15·x² + 2·x³\"",
"\"x + 2x^2 + x^5\" + \"5 + 3/4x^2 - x^5\""
);
private final Magma<?> field;
private final String[] examples;
private final String[] binaryOperators;
private final String[] unaryOperators;
private final boolean finite;
FieldInformation(Magma<?> field, String... examples) {
this.field = field;
this.finite = field.isFinite();
this.examples = examples;
this.binaryOperators = field.getSupportedOperators()
.stream()
.map(AlgebraicBinaryOperator::getSymbol)
.toArray(String[]::new);
this.unaryOperators = field.getSupportedUnaryOperators()
.stream()
.map(AlgebraicUnaryOperator::getSymbol)
.toArray(String[]::new);
log.fine(() -> "Created %s, operators: %s, unary: %s examples: %s, elements: %s".formatted(field,
List.of(binaryOperators),
List.of(unaryOperators),
List.of(examples), List.of(elements())));
}
public String[] elements() {
return elements(this.field);
}
public static String[] elements(Magma<?> field) {
Set<String> elements = new LinkedHashSet<>(field.getConstants().keySet());
if (field.getCardinality().isCountable() && field instanceof Streamable<?> streamable) {
try {
streamable.stream().limit(100).map(Object::toString).forEach(elements::add);
} catch (NotStreamable ignored) {
}
}
return elements.toArray(new String[0]);
}
/**
* The keys of an on-screen keypad for this structure.
* <ul>
* <li>{@code element}: for finite structures all elements, otherwise digits, constants, imaginary units, the variable of polynomials,
* as far as the structure accepts them</li>
* <li>{@code overline}: if the structure accepts numbers with repeating digits, to overline the selected digits</li>
* <li>{@code binary}: the binary operators</li>
* <li>{@code unary}: the unary operators. {@link Key#insert()} is then a template, where {@link #SLOT} is to be replaced with the operand</li>
* </ul>
*/
public Key[] keys() {
if (keys == null) {
List<Key> result = new ArrayList<>();
elementKeys(result);
boolean hasMultiplication = field.getSupportedOperators().stream().anyMatch(op -> op.getSymbol().equals("⋅"));
for (AlgebraicBinaryOperator op : field.getSupportedOperators()) {
if (hasMultiplication && op.getSymbol().equals("*")) {
// '*' is the generic group operation, which here is the same as '⋅'
continue;
}
result.add(new Key(op.getSymbol(), op.getSymbol(), "binary", title(op.name())));
}
for (AlgebraicUnaryOperator op : field.getSupportedUnaryOperators()) {
String template = inputTemplate(op);
if (template != null) {
result.add(new Key(op.stringify(SLOT), template, "unary", title(op.name())));
}
}
keys = result.toArray(new Key[0]);
}
return keys;
}
private Key[] keys;
private void elementKeys(List<Key> result) {
if (finite && field instanceof Streamable<?> streamable) {
streamable.stream().limit(100).map(Object::toString).forEach(e ->
result.add(new Key(e, AST.asOperand(e), "element", null))
);
return;
}
for (int i = 0; i <= 9; i++) {
result.add(new Key(String.valueOf(i), String.valueOf(i), "element", null));
}
if (accepts("1.5")) {
result.add(new Key(".", ".", "element", "decimal point"));
}
if (accepts("0.3\u0305") || accepts("3\u0305")) {
// repeating digits, like 0.3̅ (rational numbers) or 1̅3̅2 (p-adic numbers)
result.add(new Key(TextUtils.overLine("x"), "\u0305", "overline", "overline: marks the selected digits as repeating (again to remove it)"));
}
Set<String> candidates = new LinkedHashSet<>();
for (String constant : field.getConstants().keySet()) {
// names like 'unity', 'zero', 'pi' are aliases, and not useful as keys
if (!constant.matches("[a-z]{2,}")) {
candidates.add(constant);
}
}
candidates.addAll(List.of("i", "j", "k"));
for (String candidate : candidates) {
if (accepts(candidate)) {
result.add(new Key(candidate, candidate, "element", null));
}
}
if (field instanceof PolynomialRing<?> polynomialRing) {
result.add(new Key(polynomialRing.getVariable(), "\"" + polynomialRing.getVariable() + "\"", "element", "the variable"));
}
}
/**
* Whether the given input is a valid expression for this structure (without logging, failure is normal here)
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private boolean accepts(String input) {
try {
AST.parse(input, (AlgebraicStructure) field).eval();
return true;
} catch (RuntimeException e) {
return false;
}
}
private static String title(String name) {
return name.toLowerCase().replace('_', ' ');
}
/**
* The names of the settings that are relevant for this field (see calculator.js), e.g. {@code maximalPrecision}
* only makes sense if the elements contain decimal numbers.
*/
public String[] settings() {
List<String> settings = new ArrayList<>();
if (mayBeExpensive(field)) {
settings.add("maximalDuration");
}
if (hasDecimals(field)) {
settings.add("maximalPrecision");
}
if (field instanceof PAdicNumbers) {
settings.add("padicNotation");
}
if (hasRationals(field)) {
settings.add("rationalNotation");
}
return settings.toArray(new String[0]);
}
/**
* Whether calculations in the given structure may take long. That is the case if its elements can become arbitrarily big (e.g. integers, rational numbers,
* polynomials), but not if the structure is finite, or its elements are (built from) doubles.
*/
static boolean mayBeExpensive(AlgebraicStructure<?> structure) {
if (structure.isFinite() || structure instanceof RealField) {
return false;
}
if (structure instanceof CompoundStructure<?> compound && compound.isFiniteDimensional()) {
return mayBeExpensive(compound.getElementStructure());
}
return true;
}
/**
* Where the repeating (overlined) digits are in numbers of this structure, so where they can be extended while typing:
* <ul>
* <li>{@code trailing}: at the end, like in {@code 0.16̅} (rational numbers, and structures built from them)</li>
* <li>{@code leading}: at the start, like in {@code 1̅3̅2₅} (p-adic numbers)</li>
* </ul>
* @return {@code trailing}, {@code leading} or {@code null} if there are no repeating digits
*/
public String repeatingDigits() {
if (field instanceof PAdicNumbers) {
return "leading";
}
if (hasRationals((AlgebraicStructure<?>) field)) {
return "trailing";
}
return null;
}
/**
* Whether elements of the given structure are (or are built from) rational numbers
*/
static boolean hasRationals(AlgebraicStructure<?> structure) {
if (structure instanceof RationalNumbers) {
return true;
}
if (structure instanceof CompoundStructure<?> compound) {
return hasRationals(compound.getElementStructure());
}
return false;
}
/**
* Whether elements of the given structure are (or are built from) decimal numbers (which may be shown rounded)
*/
static boolean hasDecimals(AlgebraicStructure<?> structure) {
if (structure instanceof CompleteScalarField<?>) {
return true;
}
if (structure instanceof CompoundStructure<?> compound) {
return hasDecimals(compound.getElementStructure());
}
return false;
}
public String description() {
return field.getClass().getSimpleName() + " " + field;
}
/**
* @return the text of the {@link AlgebraicStructure#getDescription() description} of the structure, or {@code null}
*/
public String help() {
return field.getDescription().map(Description::text).orElse(null);
}
/**
* @return a link to more information about the structure (e.g. a wikipedia page), or {@code null}
*/
public String helpUrl() {
return field.getDescription().flatMap(Description::getUrl).map(Object::toString).orElse(null);
}
}
/**
* In templates for unary operators, the place where the operand goes.
*/
public static final String SLOT = "□";
/**
* A key on the on-screen keypad.
* @param label what is shown on the key
* @param insert what is inserted in the expression (for unary operators a template containing {@link #SLOT})
* @param type 'element', 'binary' or 'unary'
* @param title a description, or {@code null}
*/
public record Key(String label, String insert, String type, String title) {
}
/**
* How a unary operator can be entered in the infix notation, with {@link #SLOT} for the operand. Or {@code null} if it can't (or there is no point, like for the identity '+').
*/
static String inputTemplate(AlgebraicUnaryOperator op) {
String symbol = op.getSymbol();
String x = TextUtils.PLACEHOLDER;
if (symbol.matches("[a-z][a-z0-9]*")) {
// function notation, like sqr(x), sin(x), inverse(x)
return symbol + "(" + SLOT + ")";
}
if (symbol.equals("-")) {
return "-(" + SLOT + ")";
}
if (symbol.equals("'")) {
return SLOT + "'";
}
if (symbol.length() > 1 && symbol.startsWith(x)) {
// postfix, like x!
return SLOT + symbol.substring(x.length());
}
if (symbol.length() > 1 && symbol.endsWith(x)) {
// prefix, like !x
return symbol.substring(0, symbol.length() - x.length()) + SLOT;
}
return null;
}
@With
private final F field;
@With
private final Configuration configuration;
private final @Nullable Duration maximalDuration;
/**
* @return the maximal duration of a calculation, or {@code null} if there is no limit
*/
public @Nullable Duration getMaximalDuration() {
return maximalDuration;
}
/**
* The maximal number of previous results that are remembered (see {@link #results})
*/
static final int REMEMBERED_RESULTS = 100;
/**
* Results are shown rounded (see {@link #withMaximalPrecision(int)}). When such a shown result is used in a next
* calculation, the actual value is used. This maps the shown strings of the most recent results to their values.
*/
private final Map<String, E> results = Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, E> eldest) {
return size() > REMEMBERED_RESULTS;
}
});
public E eval(String input) {
return withTimeout(() -> doEval(input));
}
private E doEval(String input) {
final String expression = input.strip();
return ConfigurationService.withConfiguration(evalConfiguration(), () -> {
try {
log.fine(() -> "Evaluating expression in %s: %s. Binary: %s, Unary: %s".formatted(field, expression, field.getSupportedOperators(), field.getSupportedUnaryOperators()));
if (field.getSupportedOperators().isEmpty()) {
log.log(Level.SEVERE, "Supported operators is empty for " + field);
}
// a literal that is exactly a previous result (as it was shown) is that result, with its full precision
var parsedExpression = AST.parse(expression, field, (literal) -> Optional.ofNullable(results.get(literal.strip())));
log.fine(() -> "Parsed expression: %s".formatted(parsedExpression));
return parsedExpression.eval();
} catch (Throwable ex) {
log.log(Level.SEVERE, ex.getClass() + " " + ex.getMessage(), ex);
throw ex;
} finally {
log.finer("Ready evaluation");
}
});
}
public String evalToString(String input) {
// presenting the result is limited in time too, since that may be expensive as well (e.g. a huge integer)
var evaluated = withTimeout(() -> {
E result = doEval(input);
return Map.entry(ConfigurationService.withConfiguration(formatConfiguration(), result::toString), result);
});
final String resultAsString = evaluated.getKey();
results.put(resultAsString, evaluated.getValue());
log.fine(() -> "Result: %s = %s".formatted(input.strip(), resultAsString));
return resultAsString;
}
/**
* Runs the calculation, and stops it if it takes longer than {@link #maximalDuration} (see {@link Utils#withMaximalDuration(Duration, java.util.function.Supplier)}).
* The calculation is performed in the current thread, since in cheerpj threads are not preemptive.
*
* @throws CancellationException if it took too long
*/
<T> T withTimeout(java.util.function.Supplier<T> calculation) {
if (maximalDuration == null) {
return calculation.get();
}
try {
return Utils.withMaximalDuration(maximalDuration, calculation);
} catch (CancellationException e) {
throw new CancellationException("Calculation took longer than " + format(maximalDuration));
}
}
/**
* Formats a duration in seconds, in the same way as it can be given (see {@link #parseMaximalDuration(String)}), e.g. {@code 10s} or {@code 0.5s}
*/
static String format(Duration duration) {
return java.math.BigDecimal.valueOf(duration.toMillis(), 3).stripTrailingZeros().toPlainString() + "s";
}
/**
* Evaluates, but never throws. Meant for the web app.
* @param result the result as a string, or {@code null} if evaluation failed
* @param operand the result in a form that can be used as an operand in a next expression (see {@link AST#asOperand(String)}), or {@code null}
* @param error a message describing why evaluation failed, or {@code null}
*/
public record Result(String input, String result, String operand, String error) {
}
public Result calculate(String input) {
try {
String result = evalToString(input);
return new Result(input, result, AST.asOperand(result), null);
} catch (RuntimeException e) {
String message = e.getMessage() == null || e.getMessage().isBlank() ? e.getClass().getSimpleName() : e.getMessage().strip();
return new Result(input, null, null, message);
}
}
javascript
This is the source code for the above.
constructor() {
super('#calculator', 'org.meeuw.math.demo.Calculator');
// the keypad buttons are in the form too, so be explicit about which one submits
this.button = this.form.querySelector('button[name=submit]');
this.input = this.form.querySelector('#calculator_toparse');
this.settingsElement = this.form.querySelector('details.settings');
this.settings = CalculatorClass.loadSettings();
this.field = this.form.querySelector('#calculator_field');
this.inputDataList= this.form.querySelector('datalist');
this.tape = this.form.querySelector('ol.tape');
this.help = this.form.querySelector('span.help');
this.keypad = document.querySelector('#calculator_keypad');
this.information = null;
this.calculators = {};
this.listenersSetUp = false;
// true when the input contains the result of the previous calculation (completely selected)
this.fresh = false;
this.previewTimer = null;
this.previewSequence = 0;
}
get fieldInformation() {
return this.information[this.field.value];
}
/**
* One Calculator instance per field (with the current settings applied)
*/
async calculator() {
const name = this.field.value;
if (!this.calculators[name]) {
const Calculator = this.Class;
let calculator = await new Calculator(this.fieldInformation.value);
for (const [setting, {apply}] of Object.entries(SETTINGS)) {
if (this.settings[setting] !== undefined) {
calculator = await apply(calculator, this.settings[setting]);
}
}
this.calculators[name] = calculator;
}
return this.calculators[name];
}
/**
* Settings are remembered in local storage. That may not be available (e.g. in private mode), in which case the defaults are used.
*/
static loadSettings() {
try {
const settings = JSON.parse(localStorage.getItem(SETTINGS_KEY));
if (settings && typeof settings === 'object') {
if (typeof settings.maximalDuration === 'number') {
// used to be a number of seconds
settings.maximalDuration = settings.maximalDuration + 's';
}
return settings;
}
} catch (e) {
console.log("Could not load calculator settings", e);
}
return {};
}
saveSettings() {
try {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings));
} catch (e) {
console.log("Could not save calculator settings", e);
}
}
/**
* Called when the input of a setting changes. An empty (or invalid) value means the default.
*/
async updateSetting(setting, input) {
const value = await SETTINGS[setting].value(input, this.Class);
if (value !== undefined) {
this.settings[setting] = value;
} else {
delete this.settings[setting];
if (input.tagName !== 'SELECT') {
input.value = '';
}
}
this.saveSettings();
// apply to the existing calculators, which remember the previous results (so they can be used with full precision)
for (const [name, calculator] of Object.entries(this.calculators)) {
this.calculators[name] = Promise.resolve(calculator).then(c => SETTINGS[setting].apply(c, this.settings[setting]));
}
if (this.input.value.trim() !== '') {
this.fresh = false;
this.schedulePreview();
}
}
/**
* Overlines the selected characters (marking repeating digits). If they are all overlined already, the overline is removed again.
*/
toggleOverline() {
const input = this.input;
const value = input.value;
const start = input.selectionStart;
let end = input.selectionEnd;
if (start === end) {
// nothing selected (the button should not even be visible then)
return;
}
if (value[end] === OVERLINE) {
// don't split a character from its overline
end++;
}
const characters = Array.from(value.slice(start, end).replaceAll(OVERLINE, '')).filter(c => c.trim() !== '');
const selected = value.slice(start, end);
const allOverlined = characters.length > 0 && selected.replaceAll(/\s/g, '') === characters.map(c => c + OVERLINE).join('');
const replacement = allOverlined ?
selected.replaceAll(OVERLINE, '') :
Array.from(selected.replaceAll(OVERLINE, '')).map(c => c.trim() === '' ? c : c + OVERLINE).join('');
input.value = value.slice(0, start) + replacement + value.slice(end);
input.setSelectionRange(start, start + replacement.length);
this.fresh = false;
input.focus();
this.schedulePreview();
}
/**
* A digit typed next to repeating (overlined) digits, on the side where they can continue, is overlined too: after them for rational numbers
* (0.16̅ → 0.16̅7̅), before them for p-adic numbers (1̅3̅2 → 4̅1̅3̅2). Anything else would be invalid anyway.
* @return the character, possibly with an OVERLINE
*/
withOverlineIfRepeating(character) {
const where = this.fieldInformation?.repeatingDigits;
if (!where || character.length !== 1) {
return character;
}
// p-adic numbers can have digits above 9 (letters)
const digit = where === 'leading' ? /^[0-9a-z]$/i : /^[0-9]$/;
if (!digit.test(character)) {
return character;
}
const value = this.input.value;
const continues = where === 'trailing' ?
value[this.input.selectionStart - 1] === OVERLINE :
value[this.input.selectionEnd + 1] === OVERLINE;
return continues ? character + OVERLINE : character;
}
/**
* The overline key (if the current field has one) only makes sense if something is selected, so it is only shown then
*/
updateOverlineKey() {
const key = this.keypad?.querySelector('button.overline');
if (key) {
key.hidden = this.input.selectionStart === this.input.selectionEnd;
}
}
/**
* Inserts the string at the cursor, replacing the selection (if any)
*/
insert(string, cursorOffset = string.length) {
const input = this.input;
const start = input.selectionStart;
const end = input.selectionEnd;
const value = input.value;
input.value = value.slice(0, start) + string + value.slice(end);
input.setSelectionRange(start + cursorOffset, start + cursorOffset);
this.fresh = false;
input.focus();
this.schedulePreview();
}
/**
* Inserts a binary operator. If the input contains a previous result, then the calculation continues with that.
*/
insertBinaryOperator(operator) {
const input = this.input;
if (this.fresh) {
input.setSelectionRange(input.value.length, input.value.length);
}
const before = input.value.slice(0, input.selectionStart);
const padded = (before === '' || before.endsWith(' ') ? '' : ' ') + operator + ' ';
this.insert(padded);
}
/**
* Applies a unary operator, given as a template like 'sqr(□)', '□!' or '-(□)'. If something is selected (e.g. the previous
* result), that becomes the operand. Otherwise the template is inserted with the cursor where the operand should go.
*/
insertUnaryOperator(template) {
const input = this.input;
const [before, after] = template.split(SLOT);
const selected = input.value.slice(input.selectionStart, input.selectionEnd).trim();
if (selected !== '') {
const bracketed = template.includes('(' + SLOT + ')');
const operand = bracketed || SIMPLE_OPERAND.test(selected) ? selected : '(' + selected + ')';
this.insert(before + operand + after);
} else {
// postfix operators (like □!) go after the cursor, others leave the cursor at the operand's place
this.insert(before + after, before === '' ? after.length : before.length);
}
}
backspace() {
const input = this.input;
let start = input.selectionStart;
const end = input.selectionEnd;
if (start === end && start > 0) {
start--;
}
input.value = input.value.slice(0, start) + input.value.slice(end);
input.setSelectionRange(start, start);
this.fresh = false;
input.focus();
this.schedulePreview();
}
/**
* Replaces the complete input (e.g. with an expression from the tape)
*/
setInput(value) {
this.input.value = value;
this.input.setSelectionRange(value.length, value.length);
this.fresh = false;
this.input.focus();
this.schedulePreview();
}
clear() {
this.input.value = '';
this.clearOutput();
this.fresh = false;
this.input.focus();
}
clearOutput() {
this.output.value = '';
this.output.classList.remove('error', 'preview');
}
/**
* Whether typing '*' should produce '⋅'. Only if this field has no '*' operator of its own (in groups '*' is the group operation)
*/
remapStar() {
const operators = this.fieldInformation.binaryOperators;
return operators.includes('⋅') && !operators.includes('*');
}
async setupForm() {
await super.setupForm();
if (this.listenersSetUp) {
// setupForm is called every time the form comes into view
return;
}
this.listenersSetUp = true;
for (const setting of Object.keys(SETTINGS)) {
const input = this.form.querySelector(`[name=${setting}]`);
if (!input) {
continue;
}
if (this.settings[setting] !== undefined) {
input.value = this.settings[setting];
}
input.addEventListener('change', () => this.updateSetting(setting, input));
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
// don't submit the form, just apply the setting
e.preventDefault();
this.updateSetting(setting, input);
}
});
}
this.input.addEventListener('beforeinput', async (e) => {
this.help.textContent = '';
if (!e.inputType.startsWith('insert') || !e.data || e.data.length !== 1) {
// deletions, pastes, etc.
this.fresh = false;
return;
}
let data = e.data;
if (data === '=') {
e.preventDefault();
await this.handleSubmit();
return;
}
if (data === ';') {
// shortcut for '*', which can be typed without shift
data = this.fieldInformation.binaryOperators.includes('*') ? '*' : '⋅';
} else if (data === '*' && this.remapStar()) {
data = '⋅';
this.help.textContent = "(* is ⋅ here)";
}
if (this.fresh && this.fieldInformation.binaryOperators.includes(data)) {
// continue with the previous result
e.preventDefault();
this.insertBinaryOperator(data);
return;
}
data = this.withOverlineIfRepeating(data);
if (data !== e.data) {
e.preventDefault();
this.insert(data);
} else {
// just typing, which replaces the previous result if that was there
this.fresh = false;
}
});
this.input.addEventListener('input', () => {
this.schedulePreview();
});
this.input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
e.preventDefault();
this.clear();
}
});
this.form.addEventListener('copy', copyWithOverlines);
// show the overline key only if something is selected
for (const type of ['select', 'selectionchange', 'input', 'keyup', 'mouseup', 'focus']) {
this.input.addEventListener(type, () => this.updateOverlineKey());
}
document.addEventListener('selectionchange', () => this.updateOverlineKey());
this.field.addEventListener('change', async () => {
this.fieldToUrl();
await this.updateField();
});
}
async onInView(Calculator){
await super.onInView(Calculator);
if (this.information === null) {
await this.loadInformation();
this.updateFieldList();
await this.updateField();
}
}
/**
* Called when the field changes. Everything that depends on the field is updated, and previous results are cleared, since
* they mean nothing in another field
*/
async updateField() {
this.updateExamples();
this.updateHelp();
this.updateSettings();
this.tape.innerHTML = '';
this.input.value = '';
this.clearOutput();
this.fresh = false;
await this.updateKeypad();
}
/**
* Shows only the settings that are relevant for the current field, and no settings at all if there are none
*/
updateSettings() {
if (!this.settingsElement) {
return;
}
const relevant = this.fieldInformation.settings || [];
let anyShown = false;
for (const setting of this.settingsElement.querySelectorAll('[data-setting]')) {
const show = relevant.includes(setting.dataset.setting);
setting.hidden = !show;
anyShown ||= show;
}
this.settingsElement.hidden = !anyShown;
}
updateFieldList() {
for (const [key, value] of Object.entries(this.information)) {
const option = document.createElement('option');
option.value = key;
option.text = value.description;
this.field.appendChild(option);
}
const fromUrl = new URLSearchParams(location.search).get(FIELD_PARAMETER);
if (fromUrl !== null && Object.hasOwn(this.information, fromUrl)) {
this.field.value = fromUrl;
}
}
/**
* Puts the selected field in the URL (replacing the current history entry), so it can be bookmarked
*/
fieldToUrl() {
const url = new URL(location.href);
url.searchParams.set(FIELD_PARAMETER, this.field.value);
history.replaceState(history.state, '', url);
}
/**
* Load all information about the supported fields. The keys of the keypad are loaded when needed (see loadKeys)
*/
async loadInformation() {
this.information = {};
const fi = await (await BaseClass.cj)['org.meeuw.math.demo.Calculator$FieldInformation'];
const values = await fi.values();
for (let i = 0; i < values.length; i++) {
const value = await values[i];
const elements = await BaseClass.awaitedArray(value.elements());
let elementsSpans = null;
if (elements) {
elementsSpans = [];
for (let j = 0; j < elements.length; j++) {
const span = document.createElement('span');
span.classList.add('element');
span.textContent = elements[j];
elementsSpans[j] = span;
}
}
this.information[await values[i].name()] = {
examples: await BaseClass.awaitedArray(value.examples()),
elements: elements,
elementsSpans: elementsSpans,
binaryOperators: await BaseClass.awaitedArray(value.binaryOperators()),
finite: await value.finite(),
description: await value.description(),
help: await value.help(),
helpUrl: await value.helpUrl(),
settings: await BaseClass.awaitedArray(value.settings()),
repeatingDigits: await value.repeatingDigits(),
keys: null,
value: value,
};
}
}
async loadKeys(information) {
if (information.keys === null) {
const keys = await BaseClass.awaitedArray(information.value.keys());
information.keys = [];
for (const key of keys) {
information.keys.push({
label: await key.label(),
insert: await key.insert(),
type: await key.type(),
title: await key.title(),
});
}
}
return information.keys;
}
updateExamples() {
this.inputDataList.innerHTML = '';
for (const example of this.fieldInformation.examples) {
const option = document.createElement('option');
option.value = example;
this.inputDataList.appendChild(option);
}
}
updateHelp() {
const fieldInformation = this.fieldInformation;
const div = this.field.parentNode.querySelector("div.help");
div.innerHTML = '';
let help = fieldInformation.help;
if (help) {
div.appendChild(document.createTextNode(help));
}
if (fieldInformation.helpUrl) {
const link = document.createElement('a');
link.href = fieldInformation.helpUrl;
link.target = '_blank';
link.rel = 'noopener';
link.textContent = 'more…';
link.title = fieldInformation.helpUrl;
if (help) {
div.appendChild(document.createTextNode(' '));
}
div.appendChild(link);
}
// for infinite structures just a sample, the keypad is for entering them
const elements = fieldInformation.finite ? fieldInformation.elementsSpans : fieldInformation.elementsSpans?.slice(0, 20);
if (elements && elements.length > 0) {
div.appendChild(document.createElement("br"));
div.appendChild(document.createTextNode("elements: "));
elements.forEach(element => {
div.appendChild(element);
})
if (!fieldInformation.finite) {
div.appendChild(document.createTextNode("... infinitely many more"));
}
}
}
keyButton(label, title, onclick, ...classes) {
const button = document.createElement('button');
button.type = 'button';
button.textContent = label;
if (title) {
button.title = title;
}
button.classList.add(...classes);
// don't take the focus from the input, so its selection stays
button.addEventListener('mousedown', e => e.preventDefault());
button.addEventListener('click', onclick);
return button;
}
/**
* (Re)builds the on-screen keypad for the current field
*/
async updateKeypad() {
if (!this.keypad) {
return;
}
const name = this.field.value;
const keys = await this.loadKeys(this.fieldInformation);
if (name !== this.field.value) {
// field changed again in the meantime
return;
}
const groups = {
element: this.keypad.querySelector('.elements'),
binary: this.keypad.querySelector('.binary'),
unary: this.keypad.querySelector('.unary'),
};
Object.values(groups).forEach(g => g.innerHTML = '');
for (const key of keys) {
let onclick;
switch (key.type) {
case 'binary':
onclick = () => this.insertBinaryOperator(key.insert);
break;
case 'unary':
onclick = () => this.insertUnaryOperator(key.insert);
break;
case 'overline':
onclick = () => this.toggleOverline();
break;
default:
onclick = () => this.insert(this.withOverlineIfRepeating(key.insert));
}
(groups[key.type] ?? groups.element).appendChild(this.keyButton(key.label, key.title, onclick, 'key', key.type));
}
const special = this.keypad.querySelector('.special');
if (special.childElementCount === 0) {
special.append(
this.keyButton('(', 'opening bracket', () => this.insert('(')),
this.keyButton(')', 'closing bracket', () => this.insert(')')),
this.keyButton('" "', 'quotes, for an element in its own notation, like "1 + 2i"', () => this.insert('""', 1)),
this.keyButton('⌫', 'backspace', () => this.backspace()),
this.keyButton('C', 'clear (Esc)', () => this.clear()),
);
special.querySelectorAll('button').forEach(b => b.classList.add('key', 'special'));
}
this.updateOverlineKey();
}
/**
* Evaluates while typing (a bit delayed), and shows the result as a preview
*/
schedulePreview() {
clearTimeout(this.previewTimer);
this.previewTimer = setTimeout(() => this.preview(), 400);
}
async preview() {
const expression = this.input.value.trim();
const sequence = ++this.previewSequence;
if (this.running || this.fresh || !this.Class || this.Class === "locked") {
return;
}
if (expression === '') {
this.clearOutput();
return;
}
const result = await (await this.calculator()).calculate(expression);
if (sequence !== this.previewSequence || this.running || this.input.value.trim() !== expression) {
// outdated
return;
}
const error = await result.error();
this.output.classList.remove('error');
if (error) {
// probably just not finished typing
this.output.classList.remove('preview');
this.output.value = '';
} else {
this.output.classList.add('preview');
showWithOverlines(this.output, '= ' + await result.result());
}
}
addToTape(expression, result, operand) {
const li = document.createElement('li');
const expressionSpan = document.createElement('span');
expressionSpan.classList.add('expression');
showWithOverlines(expressionSpan, expression);
expressionSpan.title = 'use this expression again';
expressionSpan.onclick = () => this.setInput(expression);
const resultSpan = document.createElement('span');
resultSpan.classList.add('result');
showWithOverlines(resultSpan, result);
resultSpan.title = 'use this result';
resultSpan.onclick = () => this.setInput(operand);
li.append(expressionSpan, ' = ', resultSpan);
this.tape.appendChild(li);
this.tape.scrollTop = this.tape.scrollHeight;
}
async onSubmit() {
clearTimeout(this.previewTimer);
this.previewSequence++;
const expression = this.input.value.trim();
this.clearOutput();
if (expression === '') {
return;
}
const result = await (await this.calculator()).calculate(expression);
const error = await result.error();
if (error) {
// leave the input, so it can be corrected
this.output.classList.add('error');
this.output.value = error;
this.input.focus();
return;
}
const value = await result.result();
const operand = await result.operand();
showWithOverlines(this.output, value);
this.addToTape(expression, value, operand);
// the result becomes the start of the next calculation. It is selected, so typing something new replaces it,
// and typing an operator continues with it
this.input.value = operand;
this.input.focus();
this.input.select();
this.fresh = true;
}
}
Solver
The same idea as my very first applet. Solving the '24 flippo game'.
Give the desired outcome number, and a few input numbers, and it will find the possible ways to get it using those input numbers.
|
Note
|
This combines several aspects of this project:
|
|
Note
|
This runs webassembly, so it is considerably slower than a pure java version. It is still fast enough for demo purposes. But e.g. the 175000 considerations to be made for 5 numbers '4 7 7 7 8' will cost several minutes in the browser. It runs in under 2 seconds in pure java. |
java source code
This is the source code for the above.
package org.meeuw.math.demo;
import lombok.Getter;
import lombok.extern.java.Log;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.meeuw.math.IntegerUtils;
import org.meeuw.math.abstractalgebra.Ring;
import org.meeuw.math.abstractalgebra.RingElement;
import org.meeuw.math.abstractalgebra.complex.GaussianRationals;
import org.meeuw.math.abstractalgebra.permutations.PermutationGroup;
import org.meeuw.math.abstractalgebra.quaternions.Quaternions;
import org.meeuw.math.abstractalgebra.rationalnumbers.RationalNumbers;
import org.meeuw.math.arithmetic.ast.*;
import org.meeuw.math.exceptions.MathException;
import org.meeuw.math.exceptions.NotParsable;
import org.meeuw.math.operators.AlgebraicBinaryOperator;
import static org.meeuw.math.CollectionUtils.navigableSet;
import static org.meeuw.math.operators.BasicAlgebraicBinaryOperator.*;
/**
* A tool to evaluate all possible expressions (of a certain number of rational numbers) (and check if it equals a certain value)
*/
@Log
public class Solver<E extends RingElement<E>> {
private static final NavigableSet<AlgebraicBinaryOperator> OPERATORS = navigableSet(
ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION
);
private final AtomicLong tries = new AtomicLong();
private final AtomicLong considered = new AtomicLong();
@Getter
private final Ring<E> structure;
public Solver(Ring<E> structure) {
this.structure = structure;
}
native void callBack(long considered, long tried, long total, Expression<E> expression);
native boolean cancelled();
@SafeVarargs
public final Stream<Expression<E>> stream(E... set) {
PermutationGroup permutations = PermutationGroup.ofDegree(set.length);
long streamSize = permutations.getCardinality().getValue().longValue() * AST.streamSize(set.length, OPERATORS.size()).longValue();
long dividor = Arrays.stream(set)
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
)).values().stream()
.map(count -> IntegerUtils.factorial(count.intValue()))
.reduce(1L, (a, b) -> a * b);
long total = streamSize / dividor;
return permutations.stream()
.map(permutation -> permutation.permute(set))
.map(List::of)
.distinct()
.flatMap(permuted ->
AST.stream(
permuted,
OPERATORS
)
)
.peek((p) -> {
if (cancelled()) {
throw new CancellationException("cancelled");
}
})
.map( e -> e.canonize(structure))
.peek(e -> {
considered.incrementAndGet();
})
.distinct()
.peek(e ->
callBack(considered.get(), tries.incrementAndGet(), total, e)
);
}
@SafeVarargs
public final Stream<EvaluatedExpression<E>> evaledStream(E... set) {
log.fine(() -> "evaling" + List.of(set));
return stream(set)
.map(e -> {
try {
log.fine(() -> "Evaling " + e);
E evaled = e.eval();
return new EvaluatedExpression<>(e, evaled);
} catch (MathException ex) {
return null;
}
})
.filter(Objects::nonNull);
}
/**
*
*/
public SolverResult solve(String outcomeString, String inputStrings) {
ParseResult<E> outcome = parseOutcome(outcomeString);
ParseResult<E[]> input = parseInput(inputStrings);
if (outcome.success() && input.success()) {
SolverResult result = solve(outcome.result(), input.result());
log.fine(() -> "solved: " + result);
return result;
} else {
throw new NotParsable(outcome.error() + "/" + input.error());
}
}
public SolverResult solve(E outcome, E[] input) {
AtomicLong matches = new AtomicLong();
log.fine(() -> "Solving input " + List.of(input) + " for " + outcome + " ( in field " + structure + ")");
return new SolverResult(
evaledStream(input)
.filter(e ->
e.result().eq(outcome)
).peek(e -> matches.getAndIncrement())
.map(EvaluatedExpression::toString),
tries, matches, structure
);
}
public static <F extends RingElement<F>> ParseResult<F> parseOutcome(Ring<F> structure, String outcomeString) {
log.fine(() -> "Parsing output " + outcomeString + " in field " + structure);
String resultError = null;
F result;
try {
result = structure.fromString(outcomeString);
} catch (NotParsable pe) {
result = null;
resultError = pe.getMessage();
}
return new ParseResult<>(outcomeString, result, resultError);
}
public ParseResult<E> parseOutcome(String outcomeString) {
return parseOutcome(this.structure, outcomeString);
}
public static <F extends RingElement<F>> ParseResult<F[]> parseInput(Ring<F> structure, String inputStrings) {
log.fine(() -> "Parsing input " + inputStrings + " in field " + structure);
String inputError = null;
String[] input = inputStrings.split("\\s+");
F[] set = structure.newArray(input.length);
try {
for (int i = 0; i < set.length; i++) {
set[i] = structure.fromString(input[i]);
}
} catch (NotParsable pe) {
inputError = pe.getMessage();
}
return new ParseResult<>(inputStrings, set, inputError);
}
public ParseResult<E[]> parseInput(String inputStrings) {
return parseInput(this.structure, inputStrings);
}
public static Ring<?> algebraicStructureFor(String outcomeString, String input) {
log.info(() -> "Determining algebraic structure for outcome " + outcomeString + " and input " + input);
if (outcomeString.matches(".*[jk].*") || input.matches(".*[jk].*")) {
return Quaternions.of(RationalNumbers.INSTANCE);
} else if (outcomeString.contains("i") || input.contains("i")) {
return GaussianRationals.INSTANCE;
} else {
return RationalNumbers.INSTANCE;
}
}
public record SolverResult(Stream<String> stream, AtomicLong tries, AtomicLong matches, Ring<?> field) {
/**
* Calling stream().iterator() in cheerpj doesn't seem to work. I don't get it either.
*/
public Iterator<String> iterator() {
return stream().iterator();
}
public List<String> list() {
return stream().toList();
}
}
/**
* The natives are meant to implement by CheerpJ
* This is a dummy implementation for use in main.
* @param <E>
*/
static class Impl<E extends RingElement<E>> extends Solver<E> {
private final Level level;
public Impl(Ring<E> structure, Level level) {
super(structure);
this.level = level;
}
@Override
void callBack(long considered, long tried, long total, Expression<E> expression) {
if (considered % 10000 == 0 || (considered < 10000 && considered % 100 == 0)) {
log.log(level,"Considered %d / %d , tried %d : %s".formatted(considered, total, tried, expression));
}
}
@Override
boolean cancelled() {
return false;
}
}
static void main(String[] integers) {
if (integers.length < 3) {
System.out.println();
System.exit(1);
}
String resultString = integers[0];
String inputStrings = String.join(" ", Arrays.copyOfRange(integers, 1, integers.length));
Ring<?> field = algebraicStructureFor(resultString, inputStrings);
long start = System.nanoTime();
Solver<?> solver = new Impl<>(field, Level.FINE);
SolverResult solverResult = solver.solve(resultString, inputStrings);
solverResult.stream().forEach(System.out::println);
System.out.println("ready, found " + solverResult.matches().get() + ", tried " + solverResult.tries.get() + ", field " + solverResult.field().toString() + ", took " + Duration.ofNanos(System.nanoTime() - start));
}
}
javascript
This is the source code for the above.
async onSubmit(Solver) {
this.output.value += "using: " + await (this.model.field).toString();
const solver = await new Solver(await this.model.field);
console.log(solver, this.outcome.value, this.input.value);
const solverResult = await solver.solve(
this.outcome.value, this.input.value
);
//console.log("solverResult", await (await solverResult.list()).toString());
// using iterator, because I can't figure out java lambda's here.
try {
const stream = await solverResult.iterator();
while(await stream.hasNext() && ! this.cancelled) {
const line = await stream.next();
this.output.value += "\n" + await line.toString();
this.output.scrollTop = this.output.scrollHeight;
}
} catch (e) {
if (! this.cancelled) {
throw e;
}
}
const matches = await (await solverResult.matches()).get();
this.output.value += `\nFound: ${matches}`;
const tries = await (await solverResult.tries()).get();
this.output.value += `\nTried: ${tries}`;
if (this.cancelled) {
this.output.value += `\nAnd cancelled`;
}
}
}
Dynamic date parsing
The mihxil-time module contains a 'dynamic date parser. I dusted this off from old mmbase code.
javascript
This is the source code for the above.
async onSubmit(DynamicDateTime){
try {
const parser = await new DynamicDateTime();
const parseResult = await parser.applyWithException(
this.form.querySelector("#dynamicdate_toparse").value
);
this.output.value = await parseResult.toString();
} catch (error) {
console.log(error);
this.output.value = await (await error.getMessage()).toString();
}
}