1
0
mirror of https://github.com/DanilaFe/abacus synced 2026-01-26 08:35:20 +00:00

Compare commits

..

16 Commits

Author SHA1 Message Date
Riley Jones
18b252afb1 add macros 2017-08-09 15:05:39 -07:00
Riley Jones
b2a20226d3 add variables 2017-08-09 09:44:51 -07:00
Riley Jones
d67d498625 Add variables 2017-08-08 14:00:35 -07:00
Riley Jones
2e9c88c39e Merge branch 'variables' of https://github.com/DanilaFe/abacus into variables 2017-08-07 15:07:09 -07:00
Riley Jones
b9c88b9d24 recognise variables 2017-08-07 15:03:14 -07:00
c9e0d4f8d3 Fix broken documentation,. 2017-08-07 11:18:01 -07:00
213d7af10b Merge branch 'remove-caching'
# Conflicts:
#	src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java
2017-08-07 11:14:11 -07:00
585a3839c1 Merge branch 'time-limit' 2017-08-07 11:12:12 -07:00
205b73f62c Add missing comments. 2017-08-07 11:11:41 -07:00
1cd332b97d Remove output. 2017-08-07 10:58:07 -07:00
314552f95a Read delay input from input field, and kill delay thread. 2017-08-07 10:58:04 -07:00
c5ec521996 Fix tests to work with the configuration. 2017-08-07 10:57:51 -07:00
4712bbfded Add a setting to the timeout delay. 2017-08-07 10:57:48 -07:00
7ae7f6d9a5 Add a timer to the computation thread to stop it from running. 2017-08-07 10:57:04 -07:00
35254d3e99 Rename getPi to piFor. 2017-08-06 21:56:49 -07:00
44f018060d Remove the useless caching in the plugin manager and the maps in plugins 2017-08-06 21:55:09 -07:00
22 changed files with 550 additions and 265 deletions

View File

@@ -2,6 +2,8 @@ package org.nwapw.abacus;
import org.nwapw.abacus.config.Configuration; import org.nwapw.abacus.config.Configuration;
import org.nwapw.abacus.fx.AbacusApplication; import org.nwapw.abacus.fx.AbacusApplication;
import org.nwapw.abacus.fx.AbacusController;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface; import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.parsing.LexerTokenizer; import org.nwapw.abacus.parsing.LexerTokenizer;
import org.nwapw.abacus.parsing.ShuntingYardParser; import org.nwapw.abacus.parsing.ShuntingYardParser;
@@ -12,6 +14,8 @@ import org.nwapw.abacus.plugin.StandardPlugin;
import org.nwapw.abacus.tree.NumberReducer; import org.nwapw.abacus.tree.NumberReducer;
import org.nwapw.abacus.tree.TreeNode; import org.nwapw.abacus.tree.TreeNode;
import java.util.HashMap;
/** /**
* The main calculator class. This is responsible * The main calculator class. This is responsible
* for piecing together all of the components, allowing * for piecing together all of the components, allowing
@@ -43,13 +47,13 @@ public class Abacus {
* from a string. * from a string.
*/ */
private TreeBuilder treeBuilder; private TreeBuilder treeBuilder;
private AbacusController controller;
/** /**
* Creates a new instance of the Abacus calculator. * Creates a new instance of the Abacus calculator.
* *
* @param configuration the configuration object for this Abacus instance. * @param configuration the configuration object for this Abacus instance.
*/ */
public Abacus(Configuration configuration) { public Abacus(Configuration configuration,AbacusController controller) {
pluginManager = new PluginManager(this); pluginManager = new PluginManager(this);
numberReducer = new NumberReducer(this); numberReducer = new NumberReducer(this);
this.configuration = new Configuration(configuration); this.configuration = new Configuration(configuration);
@@ -59,8 +63,12 @@ public class Abacus {
pluginManager.addListener(shuntingYardParser); pluginManager.addListener(shuntingYardParser);
pluginManager.addListener(lexerTokenizer); pluginManager.addListener(lexerTokenizer);
} this.controller =controller;
}
public NumberInterface getVar(String variable){
return controller.getVar(variable);
}
public static void main(String[] args) { public static void main(String[] args) {
AbacusApplication.launch(AbacusApplication.class, args); AbacusApplication.launch(AbacusApplication.class, args);
} }

View File

@@ -30,6 +30,10 @@ public class Configuration {
*/ */
private static final TomlWriter TOML_WRITER = new TomlWriter(); private static final TomlWriter TOML_WRITER = new TomlWriter();
/**
* The computation delay for which the thread can run without interruption.
*/
private double computationDelay = 0;
/** /**
* The implementation of the number that should be used. * The implementation of the number that should be used.
*/ */
@@ -51,10 +55,12 @@ public class Configuration {
/** /**
* Creates a new configuration with the given values. * Creates a new configuration with the given values.
* *
* @param computationDelay the delay before the computation gets killed.
* @param numberImplementation the number implementation, like "naive" or "precise" * @param numberImplementation the number implementation, like "naive" or "precise"
* @param disabledPlugins the list of disabled plugins. * @param disabledPlugins the list of disabled plugins.
*/ */
public Configuration(String numberImplementation, String[] disabledPlugins) { public Configuration(double computationDelay, String numberImplementation, String[] disabledPlugins) {
this.computationDelay = computationDelay;
this.numberImplementation = numberImplementation; this.numberImplementation = numberImplementation;
this.disabledPlugins.addAll(Arrays.asList(disabledPlugins)); this.disabledPlugins.addAll(Arrays.asList(disabledPlugins));
} }
@@ -75,6 +81,7 @@ public class Configuration {
* @param otherConfiguration the configuration to copy from. * @param otherConfiguration the configuration to copy from.
*/ */
public void copyFrom(Configuration otherConfiguration) { public void copyFrom(Configuration otherConfiguration) {
this.computationDelay = otherConfiguration.computationDelay;
this.numberImplementation = otherConfiguration.numberImplementation; this.numberImplementation = otherConfiguration.numberImplementation;
this.disabledPlugins.addAll(otherConfiguration.disabledPlugins); this.disabledPlugins.addAll(otherConfiguration.disabledPlugins);
} }
@@ -130,4 +137,23 @@ public class Configuration {
return disabledPlugins; return disabledPlugins;
} }
/**
* Gets the computation delay specified in the configuration.
*
* @return the computaton delay.
*/
public double getComputationDelay() {
return computationDelay;
}
/**
* Sets the computation delay.
*
* @param computationDelay the new computation delay.
*/
public void setComputationDelay(double computationDelay) {
this.computationDelay = computationDelay;
}
} }

View File

@@ -12,13 +12,25 @@ import javafx.stage.Stage;
*/ */
public class AbacusApplication extends Application { public class AbacusApplication extends Application {
/**
* The controller currently managing the application.
*/
private AbacusController controller;
@Override @Override
public void start(Stage primaryStage) throws Exception { public void start(Stage primaryStage) throws Exception {
Parent parent = FXMLLoader.load(getClass().getResource("/abacus.fxml")); FXMLLoader loader = new FXMLLoader(getClass().getResource("/abacus.fxml"));
Parent parent = loader.load();
controller = loader.getController();
Scene mainScene = new Scene(parent, 320, 480); Scene mainScene = new Scene(parent, 320, 480);
primaryStage.setScene(mainScene); primaryStage.setScene(mainScene);
primaryStage.setTitle("Abacus"); primaryStage.setTitle("Abacus");
primaryStage.show(); primaryStage.show();
} }
@Override
public void stop() throws Exception {
super.stop();
controller.performStop();
}
} }

View File

@@ -12,15 +12,15 @@ import javafx.util.StringConverter;
import org.nwapw.abacus.Abacus; import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.config.Configuration; import org.nwapw.abacus.config.Configuration;
import org.nwapw.abacus.number.ComputationInterruptedException; import org.nwapw.abacus.number.ComputationInterruptedException;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface; import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.plugin.ClassFinder; import org.nwapw.abacus.plugin.*;
import org.nwapw.abacus.plugin.PluginListener;
import org.nwapw.abacus.plugin.PluginManager;
import org.nwapw.abacus.plugin.StandardPlugin;
import org.nwapw.abacus.tree.TreeNode; import org.nwapw.abacus.tree.TreeNode;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Set; import java.util.Set;
@@ -64,6 +64,16 @@ public class AbacusController implements PluginListener {
*/ */
private static final String ERR_EXCEPTION = "Exception Thrown"; private static final String ERR_EXCEPTION = "Exception Thrown";
@FXML @FXML
private TextArea macroOutputField;
@FXML
private Tab macroTab;
@FXML
private TextArea macroField;
@FXML
private Button inputButtonMacro;
@FXML
private Button stopButtonMacro;
@FXML
private TabPane coreTabPane; private TabPane coreTabPane;
@FXML @FXML
private Tab calculateTab; private Tab calculateTab;
@@ -89,7 +99,9 @@ public class AbacusController implements PluginListener {
private ComboBox<String> numberImplementationBox; private ComboBox<String> numberImplementationBox;
@FXML @FXML
private ListView<ToggleablePlugin> enabledPluginView; private ListView<ToggleablePlugin> enabledPluginView;
@FXML
private TextField computationLimitField;
private String macroOutputText;
/** /**
* The list of history entries, created by the users. * The list of history entries, created by the users.
*/ */
@@ -111,7 +123,7 @@ public class AbacusController implements PluginListener {
* The abacus instance used for changing the plugin configuration. * The abacus instance used for changing the plugin configuration.
*/ */
private Abacus abacus; private Abacus abacus;
private boolean stop;
/** /**
* Boolean which represents whether changes were made to the configuration. * Boolean which represents whether changes were made to the configuration.
*/ */
@@ -124,6 +136,28 @@ public class AbacusController implements PluginListener {
* The alert shown when a press to "apply" is needed. * The alert shown when a press to "apply" is needed.
*/ */
private Alert reloadAlert; private Alert reloadAlert;
private ArrayList<Plugin> plugins;
public NumberInterface getVar(String variable){
for(Plugin plugin:plugins){
if(plugin instanceof VariablePlugin){
if(((VariablePlugin)plugin).getValue(variable)!=null)
return ((VariablePlugin)plugin).getValue(variable);
return NaiveNumber.ZERO;
}
}
return null;
}
/**
* The runnable that takes care of killing computations that take too long.
*/
private final Runnable TIMER_RUNNABLE = () -> {
try {
Configuration abacusConfig = abacus.getConfiguration();
if(abacusConfig.getComputationDelay() == 0) return;
Thread.sleep((long) (abacusConfig.getComputationDelay() * 1000));
performStop();
} catch (InterruptedException e) { }
};
/** /**
* The runnable used to perform the calculation. * The runnable used to perform the calculation.
*/ */
@@ -161,6 +195,10 @@ public class AbacusController implements PluginListener {
}); });
} }
}; };
/**
* The thread that is waiting to pause the calculation.
*/
private Thread computationLimitThread;
/** /**
* The thread in which the computation runs. * The thread in which the computation runs.
*/ */
@@ -213,10 +251,15 @@ public class AbacusController implements PluginListener {
if (oldValue.equals(settingsTab)) alertIfApplyNeeded(true); if (oldValue.equals(settingsTab)) alertIfApplyNeeded(true);
}); });
abacus = new Abacus(new Configuration(CONFIG_FILE)); abacus = new Abacus(new Configuration(CONFIG_FILE),this);
PluginManager abacusPluginManager = abacus.getPluginManager(); PluginManager abacusPluginManager = abacus.getPluginManager();
abacusPluginManager.addListener(this); abacusPluginManager.addListener(this);
abacusPluginManager.addInstantiated(new StandardPlugin(abacus.getPluginManager())); plugins = new ArrayList<>();
plugins.add(new StandardPlugin(abacus.getPluginManager()));
plugins.add(new VariablePlugin(abacus.getPluginManager()));
for(Plugin plugin: plugins){
abacusPluginManager.addInstantiated(plugin);
}
try { try {
ClassFinder.loadJars("plugins").forEach(abacusPluginManager::addClass); ClassFinder.loadJars("plugins").forEach(abacusPluginManager::addClass);
} catch (IOException | ClassNotFoundException e) { } catch (IOException | ClassNotFoundException e) {
@@ -224,6 +267,15 @@ public class AbacusController implements PluginListener {
} }
abacusPluginManager.reload(); abacusPluginManager.reload();
computationLimitField.setText(Double.toString(abacus.getConfiguration().getComputationDelay()));
computationLimitField.textProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue.matches("(\\d+(\\.\\d*)?)?")) {
computationLimitField.setText(oldValue);
} else {
changesMade = true;
}
});
changesMade = false; changesMade = false;
reloadAlertShown = false; reloadAlertShown = false;
@@ -234,21 +286,64 @@ public class AbacusController implements PluginListener {
} }
@FXML @FXML
private void performCalculation() { public void performCalculation() {
stop=false;
inputButton.setDisable(true); inputButton.setDisable(true);
stopButton.setDisable(false); stopButton.setDisable(false);
calculationThread = new Thread(CALCULATION_RUNNABLE); calculationThread = new Thread(CALCULATION_RUNNABLE);
calculationThread.start(); calculationThread.start();
computationLimitThread = new Thread(TIMER_RUNNABLE);
computationLimitThread.start();
} }
Runnable macroCalculate = new Runnable(){
@Override
public void run() {
stop=false;
inputButtonMacro.setDisable(true);
stopButtonMacro.setDisable(false);
Scanner macroScanner = new Scanner(macroField.getText());
String next = "!";
macroOutputText="";
while(!stop&&macroScanner.hasNextLine()) {
next = macroScanner.nextLine().trim();
if(next.equals(""))
break;
inputField.setText(next);
calculationThread = new Thread(CALCULATION_RUNNABLE);
calculationThread.start();
computationLimitThread = new Thread(TIMER_RUNNABLE);
computationLimitThread.start();
while(calculationThread.isAlive()){}
//long b = System.currentTimeMillis();
//while(System.currentTimeMillis()-b<10000){}
macroOutputText +=outputText.getText()+"\n";
//next = macroScanner.nextLine().trim();
}
Platform.runLater(() -> {
macroOutputField.setText(macroOutputText);
inputButtonMacro.setDisable(false);
stopButtonMacro.setDisable(true);
});
}
};
@FXML @FXML
private void performStop(){ public void macroCalculation(){
if(calculationThread != null) Thread macroThread = new Thread(macroCalculate);
macroThread.start();
}
@FXML
public void performStop(){
if(calculationThread != null) {
calculationThread.interrupt(); calculationThread.interrupt();
calculationThread = null;
stop = true;
}
} }
@FXML @FXML
private void performSaveAndReload() { public void performSaveAndReload() {
performSave(); performSave();
performReload(); performReload();
changesMade = false; changesMade = false;
@@ -256,13 +351,13 @@ public class AbacusController implements PluginListener {
} }
@FXML @FXML
private void performReload() { public void performReload() {
alertIfApplyNeeded(true); alertIfApplyNeeded(true);
abacus.getPluginManager().reload(); abacus.getPluginManager().reload();
} }
@FXML @FXML
private void performSave() { public void performSave() {
Configuration configuration = abacus.getConfiguration(); Configuration configuration = abacus.getConfiguration();
configuration.setNumberImplementation(numberImplementationBox.getSelectionModel().getSelectedItem()); configuration.setNumberImplementation(numberImplementationBox.getSelectionModel().getSelectedItem());
Set<String> disabledPlugins = configuration.getDisabledPlugins(); Set<String> disabledPlugins = configuration.getDisabledPlugins();
@@ -270,6 +365,8 @@ public class AbacusController implements PluginListener {
for (ToggleablePlugin pluginEntry : enabledPlugins) { for (ToggleablePlugin pluginEntry : enabledPlugins) {
if (!pluginEntry.isEnabled()) disabledPlugins.add(pluginEntry.getClassName()); if (!pluginEntry.isEnabled()) disabledPlugins.add(pluginEntry.getClassName());
} }
if(computationLimitField.getText().matches("\\d*(\\.\\d+)?") && computationLimitField.getText().length() != 0)
configuration.setComputationDelay(Double.parseDouble(computationLimitField.getText()));
configuration.saveTo(CONFIG_FILE); configuration.saveTo(CONFIG_FILE);
changesMade = false; changesMade = false;
reloadAlertShown = false; reloadAlertShown = false;
@@ -296,4 +393,5 @@ public class AbacusController implements PluginListener {
enabledPlugins.clear(); enabledPlugins.clear();
numberImplementationOptions.clear(); numberImplementationOptions.clear();
} }
} }

View File

@@ -57,6 +57,7 @@ public class Lexer<T> {
* @return the best match. * @return the best match.
*/ */
public Match<T> lexOne(String from, int startAt, Comparator<T> compare) { public Match<T> lexOne(String from, int startAt, Comparator<T> compare) {
//boolean variable = true;
ArrayList<Match<T>> matches = new ArrayList<>(); ArrayList<Match<T>> matches = new ArrayList<>();
HashSet<PatternNode<T>> currentSet = new HashSet<>(); HashSet<PatternNode<T>> currentSet = new HashSet<>();
HashSet<PatternNode<T>> futureSet = new HashSet<>(); HashSet<PatternNode<T>> futureSet = new HashSet<>();
@@ -70,6 +71,7 @@ public class Lexer<T> {
node.addOutputsInto(futureSet); node.addOutputsInto(futureSet);
} else if (node instanceof EndNode) { } else if (node instanceof EndNode) {
matches.add(new Match<>(from.substring(startAt, index), ((EndNode<T>) node).getPatternId())); matches.add(new Match<>(from.substring(startAt, index), ((EndNode<T>) node).getPatternId()));
//variable = false;
} }
} }
@@ -84,6 +86,9 @@ public class Lexer<T> {
if (compare != null) { if (compare != null) {
matches.sort(Comparator.comparingInt(a -> a.getContent().length())); matches.sort(Comparator.comparingInt(a -> a.getContent().length()));
} }
//if(variable&&) {
// matches.add(new Match<>(from.substring(startAt, index), ((EndNode<T>) node).getPatternId()));
//}
return matches.isEmpty() ? null : matches.get(matches.size() - 1); return matches.isEmpty() ? null : matches.get(matches.size() - 1);
} }

View File

@@ -1,5 +1,7 @@
package org.nwapw.abacus.lexing.pattern; package org.nwapw.abacus.lexing.pattern;
import org.nwapw.abacus.tree.TokenType;
/** /**
* A match that has been generated by the lexer. * A match that has been generated by the lexer.
* *

View File

@@ -35,7 +35,6 @@ public class NaiveNumber extends NumberInterface {
public NaiveNumber(double value) { public NaiveNumber(double value) {
this.value = value; this.value = value;
} }
@Override @Override
public int getMaxPrecision() { public int getMaxPrecision() {
return 18; return 18;
@@ -43,22 +42,22 @@ public class NaiveNumber extends NumberInterface {
@Override @Override
public NumberInterface multiplyInternal(NumberInterface multiplier) { public NumberInterface multiplyInternal(NumberInterface multiplier) {
return new NaiveNumber(value * ((NaiveNumber) multiplier).value); return new NaiveNumber(value * ((NaiveNumber) multiplier.number()).value);
} }
@Override @Override
public NumberInterface divideInternal(NumberInterface divisor) { public NumberInterface divideInternal(NumberInterface divisor) {
return new NaiveNumber(value / ((NaiveNumber) divisor).value); return new NaiveNumber(value / ((NaiveNumber) divisor.number()).value);
} }
@Override @Override
public NumberInterface addInternal(NumberInterface summand) { public NumberInterface addInternal(NumberInterface summand) {
return new NaiveNumber(value + ((NaiveNumber) summand).value); return new NaiveNumber(value + ((NaiveNumber) summand.number()).value);
} }
@Override @Override
public NumberInterface subtractInternal(NumberInterface subtrahend) { public NumberInterface subtractInternal(NumberInterface subtrahend) {
return new NaiveNumber(value - ((NaiveNumber) subtrahend).value); return new NaiveNumber(value - ((NaiveNumber) subtrahend.number()).value);
} }
@Override @Override
@@ -85,7 +84,7 @@ public class NaiveNumber extends NumberInterface {
@Override @Override
public int compareTo(NumberInterface number) { public int compareTo(NumberInterface number) {
NaiveNumber num = (NaiveNumber) number; NaiveNumber num = (NaiveNumber) number.number();
return Double.compare(value, num.value); return Double.compare(value, num.value);
} }
@@ -119,6 +118,8 @@ public class NaiveNumber extends NumberInterface {
if (toClass == this.getClass()) return this; if (toClass == this.getClass()) return this;
else if (toClass == PreciseNumber.class) { else if (toClass == PreciseNumber.class) {
return new PreciseNumber(Double.toString(value)); return new PreciseNumber(Double.toString(value));
}else if(toClass == Variable.class){
return this;
} }
return null; return null;
} }

View File

@@ -13,6 +13,12 @@ public abstract class NumberInterface {
if(Thread.currentThread().isInterrupted()) if(Thread.currentThread().isInterrupted())
throw new ComputationInterruptedException(); throw new ComputationInterruptedException();
} }
public NumberInterface number(){
return this;
}
public Class<? extends NumberInterface> getClassVal(){
return this.getClass();
}
/** /**
* The maximum precision to which this number operates. * The maximum precision to which this number operates.
* *
@@ -173,7 +179,7 @@ public abstract class NumberInterface {
/** /**
* Returns the least integer greater than or equal to the number. * Returns the least integer greater than or equal to the number.
* *
* @return the least integer >= the number, if int can hold the value. * @return the least integer greater or equal to the number, if int can hold the value.
*/ */
protected abstract NumberInterface ceilingInternal(); protected abstract NumberInterface ceilingInternal();
@@ -201,7 +207,7 @@ public abstract class NumberInterface {
* Also, checks if the thread has been interrupted, and if so, throws * Also, checks if the thread has been interrupted, and if so, throws
* an exception. * an exception.
* *
* @return the greatest int >= the number, if int can hold the value. * @return the greatest int smaller or equal to the number, if int can hold the value.
*/ */
public final NumberInterface floor(){ public final NumberInterface floor(){
checkInterrupted(); checkInterrupted();

View File

@@ -53,22 +53,22 @@ public class PreciseNumber extends NumberInterface {
@Override @Override
public NumberInterface multiplyInternal(NumberInterface multiplier) { public NumberInterface multiplyInternal(NumberInterface multiplier) {
return new PreciseNumber(this.value.multiply(((PreciseNumber) multiplier).value)); return new PreciseNumber(this.value.multiply(((PreciseNumber) multiplier.number()).value));
} }
@Override @Override
public NumberInterface divideInternal(NumberInterface divisor) { public NumberInterface divideInternal(NumberInterface divisor) {
return new PreciseNumber(value.divide(((PreciseNumber) divisor).value, this.getMaxPrecision(), RoundingMode.HALF_UP)); return new PreciseNumber(value.divide(((PreciseNumber) divisor.number()).value, this.getMaxPrecision(), RoundingMode.HALF_UP));
} }
@Override @Override
public NumberInterface addInternal(NumberInterface summand) { public NumberInterface addInternal(NumberInterface summand) {
return new PreciseNumber(value.add(((PreciseNumber) summand).value)); return new PreciseNumber(value.add(((PreciseNumber) summand.number()).value));
} }
@Override @Override
public NumberInterface subtractInternal(NumberInterface subtrahend) { public NumberInterface subtractInternal(NumberInterface subtrahend) {
return new PreciseNumber(value.subtract(((PreciseNumber) subtrahend).value)); return new PreciseNumber(value.subtract(((PreciseNumber) subtrahend.number()).value));
} }
@Override @Override
@@ -90,7 +90,7 @@ public class PreciseNumber extends NumberInterface {
@Override @Override
public int compareTo(NumberInterface number) { public int compareTo(NumberInterface number) {
return value.compareTo(((PreciseNumber) number).value); return value.compareTo(((PreciseNumber) number.number()).value);
} }
@Override @Override

View File

@@ -0,0 +1,102 @@
package org.nwapw.abacus.number;
public class Variable extends NumberInterface{
public NumberInterface value;
public String variable;
public Variable(NumberInterface value,String variable){
this.value = value;
this.variable = variable;
}
public String getVariable(){
return variable;
}
@Override
public NumberInterface number(){
return value.number();
}
@Override
public Class<? extends NumberInterface> getClassVal(){
return value.getClassVal();
}
@Override
public int getMaxPrecision() {
return value.getMaxPrecision();
}
@Override
protected NumberInterface multiplyInternal(NumberInterface multiplier) {
value = value.promoteToInternal(multiplier.number().getClass());
return value.multiplyInternal(multiplier.number());
}
@Override
protected NumberInterface divideInternal(NumberInterface divisor) {
value = value.promoteToInternal(divisor.number().getClass());
return value.divideInternal(divisor.number());
}
@Override
protected NumberInterface addInternal(NumberInterface summand) {
value = value.promoteToInternal(summand.number().getClass());
return value.addInternal(summand.number());
}
@Override
protected NumberInterface subtractInternal(NumberInterface subtrahend) {
value = value.promoteToInternal(subtrahend.number().getClass());
return value.subtractInternal(subtrahend.number());
}
@Override
protected NumberInterface negateInternal() {
return value.negateInternal();
}
@Override
protected NumberInterface intPowInternal(int exponent) {
return value.intPowInternal(exponent);
}
@Override
public int compareTo(NumberInterface number) {
value = value.promoteToInternal(number.number().getClass());
return value.compareTo(number.number());
}
@Override
public int signum() {
return value.signum();
}
@Override
protected NumberInterface ceilingInternal() {
return value.ceilingInternal();
}
@Override
protected NumberInterface floorInternal() {
return value.floorInternal();
}
@Override
protected NumberInterface fractionalPartInternal() {
return value.fractionalPartInternal();
}
@Override
public int intValue() {
return value.intValue();
}
@Override
protected NumberInterface promoteToInternal(Class<? extends NumberInterface> toClass) {
return value.promoteToInternal(toClass);
}
public String toString(){
return value.toString();
}
}

View File

@@ -36,6 +36,7 @@ public class LexerTokenizer implements Tokenizer<Match<TokenType>>, PluginListen
register("[0-9]*(\\.[0-9]+)?", TokenType.NUM); register("[0-9]*(\\.[0-9]+)?", TokenType.NUM);
register("\\(", TokenType.OPEN_PARENTH); register("\\(", TokenType.OPEN_PARENTH);
register("\\)", TokenType.CLOSE_PARENTH); register("\\)", TokenType.CLOSE_PARENTH);
register("[a-zA-Z]+",TokenType.VARIABLE);
}}; }};
} }

View File

@@ -63,7 +63,9 @@ public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListe
matchType = match.getType(); matchType = match.getType();
if (matchType == TokenType.NUM) { if (matchType == TokenType.NUM) {
output.add(match); output.add(match);
} else if (matchType == TokenType.FUNCTION) { }else if(matchType == TokenType.VARIABLE) {
output.add(match);
}else if (matchType == TokenType.FUNCTION) {
output.add(new Match<>("", TokenType.INTERNAL_FUNCTION_END)); output.add(new Match<>("", TokenType.INTERNAL_FUNCTION_END));
tokenStack.push(match); tokenStack.push(match);
} else if (matchType == TokenType.OP) { } else if (matchType == TokenType.OP) {
@@ -144,6 +146,8 @@ public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListe
} }
} else if (matchType == TokenType.NUM) { } else if (matchType == TokenType.NUM) {
return new NumberNode(abacus.numberFromString(match.getContent())); return new NumberNode(abacus.numberFromString(match.getContent()));
} else if (matchType == TokenType.VARIABLE){
return new VariableNode(match.getContent());
} else if (matchType == TokenType.FUNCTION) { } else if (matchType == TokenType.FUNCTION) {
String functionName = match.getContent(); String functionName = match.getContent();
FunctionNode node = new FunctionNode(functionName); FunctionNode node = new FunctionNode(functionName);

View File

@@ -17,18 +17,6 @@ import java.util.Set;
*/ */
public abstract class Plugin { public abstract class Plugin {
/**
* A hash map of functions mapped to their string names.
*/
private Map<String, Function> functions;
/**
* A hash map of operators mapped to their string names.
*/
private Map<String, Operator> operators;
/**
* The map of the number implementations this plugin provides.
*/
private Map<String, NumberImplementation> numberImplementations;
/** /**
* The plugin manager in which to search for functions * The plugin manager in which to search for functions
* not inside this package, * not inside this package,
@@ -49,69 +37,9 @@ public abstract class Plugin {
*/ */
public Plugin(PluginManager manager) { public Plugin(PluginManager manager) {
this.manager = manager; this.manager = manager;
functions = new HashMap<>();
operators = new HashMap<>();
numberImplementations = new HashMap<>();
enabled = false; enabled = false;
} }
/**
* Gets the list of functions provided by this plugin.
*
* @return the list of registered functions.
*/
public final Set<String> providedFunctions() {
return functions.keySet();
}
/**
* Gets the list of functions provided by this plugin.
*
* @return the list of registered functions.
*/
public final Set<String> providedOperators() {
return operators.keySet();
}
/**
* Gets the list of number implementations provided by this plugin.
*
* @return the list of registered number implementations.
*/
public final Set<String> providedNumberImplementations() {
return numberImplementations.keySet();
}
/**
* Gets a function under the given function name.
*
* @param functionName the name of the function to get
* @return the function, or null if this plugin doesn't provide it.
*/
public final Function getFunction(String functionName) {
return functions.get(functionName);
}
/**
* Gets an operator under the given operator name.
*
* @param operatorName the name of the operator to get.
* @return the operator, or null if this plugin doesn't provide it.
*/
public final Operator getOperator(String operatorName) {
return operators.get(operatorName);
}
/**
* Gets the number implementation under the given name.
*
* @param name the name of the number implementation to look up.
* @return the number implementation associated with that name, or null if the plugin doesn't provide it.
*/
public final NumberImplementation getNumberImplementation(String name) {
return numberImplementations.get(name);
}
/** /**
* Enables the function, loading the necessary instances * Enables the function, loading the necessary instances
* of functions. * of functions.
@@ -129,8 +57,6 @@ public abstract class Plugin {
public final void disable() { public final void disable() {
if (!enabled) return; if (!enabled) return;
onDisable(); onDisable();
functions.clear();
operators.clear();
enabled = false; enabled = false;
} }
@@ -142,7 +68,7 @@ public abstract class Plugin {
* @param toRegister the function implementation. * @param toRegister the function implementation.
*/ */
protected final void registerFunction(String name, Function toRegister) { protected final void registerFunction(String name, Function toRegister) {
functions.put(name, toRegister); manager.registerFunction(name, toRegister);
} }
/** /**
@@ -154,7 +80,7 @@ public abstract class Plugin {
* @param operator the operator to register. * @param operator the operator to register.
*/ */
protected final void registerOperator(String name, Operator operator) { protected final void registerOperator(String name, Operator operator) {
operators.put(name, operator); manager.registerOperator(name, operator);
} }
/** /**
@@ -165,7 +91,7 @@ public abstract class Plugin {
* @param implementation the actual implementation class to register. * @param implementation the actual implementation class to register.
*/ */
protected final void registerNumberImplementation(String name, NumberImplementation implementation) { protected final void registerNumberImplementation(String name, NumberImplementation implementation) {
numberImplementations.put(name, implementation); manager.registerNumberImplementation(name, implementation);
} }
/** /**
@@ -213,7 +139,7 @@ public abstract class Plugin {
* @param forClass the class to which to find the pi instance. * @param forClass the class to which to find the pi instance.
* @return the pi value for the given class. * @return the pi value for the given class.
*/ */
protected final NumberInterface getPi(Class<? extends NumberInterface> forClass) { protected final NumberInterface piFor(Class<? extends NumberInterface> forClass) {
return manager.piFor(forClass); return manager.piFor(forClass);
} }

View File

@@ -23,20 +23,17 @@ public class PluginManager {
*/ */
private Set<Plugin> plugins; private Set<Plugin> plugins;
/** /**
* List of functions that have been cached, * The map of functions registered by the plugins.
* that is, found in a plugin and returned.
*/ */
private Map<String, Function> cachedFunctions; private Map<String, Function> registeredFunctions;
/** /**
* List of operators that have been cached, * The map of operators registered by the plugins
* that is, found in a plugin and returned.
*/ */
private Map<String, Operator> cachedOperators; private Map<String, Operator> registeredOperators;
/** /**
* The list of number implementations that have * The map of number implementations registered by the plugins.
* been cached, that is, found in a plugin and returned.
*/ */
private Map<String, NumberImplementation> cachedNumberImplementations; private Map<String, NumberImplementation> registeredNumberImplementations;
/** /**
* The list of number implementations that have been * The list of number implementations that have been
* found by their implementation class. * found by their implementation class.
@@ -46,18 +43,6 @@ public class PluginManager {
* The pi values for each implementation class that have already been computer. * The pi values for each implementation class that have already been computer.
*/ */
private Map<Class<? extends NumberInterface>, NumberInterface> cachedPi; private Map<Class<? extends NumberInterface>, NumberInterface> cachedPi;
/**
* List of all functions loaded by the plugins.
*/
private Set<String> allFunctions;
/**
* List of all operators loaded by the plugins.
*/
private Set<String> allOperators;
/**
* List of all the number implementations loaded by the plugins.
*/
private Set<String> allNumberImplementations;
/** /**
* The list of plugin listeners attached to this instance. * The list of plugin listeners attached to this instance.
*/ */
@@ -77,79 +62,66 @@ public class PluginManager {
this.abacus = abacus; this.abacus = abacus;
loadedPluginClasses = new HashSet<>(); loadedPluginClasses = new HashSet<>();
plugins = new HashSet<>(); plugins = new HashSet<>();
cachedFunctions = new HashMap<>(); registeredFunctions = new HashMap<>();
cachedOperators = new HashMap<>(); registeredOperators = new HashMap<>();
cachedNumberImplementations = new HashMap<>(); registeredNumberImplementations = new HashMap<>();
cachedInterfaceImplementations = new HashMap<>(); cachedInterfaceImplementations = new HashMap<>();
cachedPi = new HashMap<>(); cachedPi = new HashMap<>();
allFunctions = new HashSet<>();
allOperators = new HashSet<>();
allNumberImplementations = new HashSet<>();
listeners = new HashSet<>(); listeners = new HashSet<>();
} }
/** /**
* Searches the plugin list for a certain value, retrieving the Plugin's * Registers a function under the given name.
* list of items of the type using the setFunction and getting the value * @param name the name of the function.
* of it is available via getFunction. If the value is contained * @param function the function to register.
* in the cache, it returns the cached value instead.
*
* @param plugins the plugin list to search.
* @param cache the cache to use
* @param setFunction the function to retrieve a set of available T's from the plugin
* @param getFunction the function to get the T value under the given name
* @param name the name to search for
* @param <T> the type of element being search
* @param <K> the type of key that the cache is indexed by.
* @return the retrieved element, or null if it was not found.
*/ */
private static <T, K> T searchCached(Collection<Plugin> plugins, Map<K, T> cache, public void registerFunction(String name, Function function){
java.util.function.Function<Plugin, Set<K>> setFunction, registeredFunctions.put(name, function);
java.util.function.BiFunction<Plugin, K, T> getFunction,
K name) {
if (cache.containsKey(name)) return cache.get(name);
T loadedValue = null;
for (Plugin plugin : plugins) {
if (setFunction.apply(plugin).contains(name)) {
loadedValue = getFunction.apply(plugin, name);
break;
}
}
cache.put(name, loadedValue);
return loadedValue;
} }
/** /**
* Gets a function under the given name. * Registers an operator under the given name.
*
* @param name the name of the function
* @return the function under the given name.
*/
public Function functionFor(String name) {
return searchCached(plugins, cachedFunctions, Plugin::providedFunctions, Plugin::getFunction, name);
}
/**
* Gets an operator under the given name.
*
* @param name the name of the operator. * @param name the name of the operator.
* @return the operator under the given name. * @param operator the operator to register.
*/ */
public Operator operatorFor(String name) { public void registerOperator(String name, Operator operator){
return searchCached(plugins, cachedOperators, Plugin::providedOperators, Plugin::getOperator, name); registeredOperators.put(name, operator);
} }
/** /**
* Gets the number implementation under the given name. * Registers a number implementation under the given name.
* * @param name the name of the number implementation.
* @param name the name of the implementation. * @param implementation the number implementation to register.
* @return the implementation.
*/ */
public NumberImplementation numberImplementationFor(String name) { public void registerNumberImplementation(String name, NumberImplementation implementation){
return searchCached(plugins, cachedNumberImplementations, Plugin::providedNumberImplementations, registeredNumberImplementations.put(name, implementation);
Plugin::getNumberImplementation, name); }
/**
* Gets the function registered under the given name.
* @param name the name of the function.
* @return the function, or null if it was not found.
*/
public Function functionFor(String name){
return registeredFunctions.get(name);
}
/**
* Gets the operator registered under the given name.
* @param name the name of the operator.
* @return the operator, or null if it was not found.
*/
public Operator operatorFor(String name){
return registeredOperators.get(name);
}
/**
* Gets the number implementation registered under the given name.
* @param name the name of the number implementation.
* @return the number implementation, or null if it was not found.
*/
public NumberImplementation numberImplementationFor(String name){
return registeredNumberImplementations.get(name);
} }
/** /**
@@ -161,14 +133,11 @@ public class PluginManager {
public NumberImplementation interfaceImplementationFor(Class<? extends NumberInterface> name) { public NumberImplementation interfaceImplementationFor(Class<? extends NumberInterface> name) {
if (cachedInterfaceImplementations.containsKey(name)) return cachedInterfaceImplementations.get(name); if (cachedInterfaceImplementations.containsKey(name)) return cachedInterfaceImplementations.get(name);
NumberImplementation toReturn = null; NumberImplementation toReturn = null;
outside: for(String key : registeredNumberImplementations.keySet()){
for (Plugin plugin : plugins) { NumberImplementation implementation = registeredNumberImplementations.get(key);
for (String implementationName : plugin.providedNumberImplementations()) { if(implementation.getImplementation() == name) {
NumberImplementation implementation = plugin.getNumberImplementation(implementationName);
if (implementation.getImplementation().equals(name)) {
toReturn = implementation; toReturn = implementation;
break outside; break;
}
} }
} }
cachedInterfaceImplementations.put(name, toReturn); cachedInterfaceImplementations.put(name, toReturn);
@@ -227,12 +196,6 @@ public class PluginManager {
if (disabledPlugins.contains(plugin.getClass().getName())) continue; if (disabledPlugins.contains(plugin.getClass().getName())) continue;
plugin.enable(); plugin.enable();
} }
for (Plugin plugin : plugins) {
if (disabledPlugins.contains(plugin.getClass().getName())) continue;
allFunctions.addAll(plugin.providedFunctions());
allOperators.addAll(plugin.providedOperators());
allNumberImplementations.addAll(plugin.providedNumberImplementations());
}
listeners.forEach(e -> e.onLoad(this)); listeners.forEach(e -> e.onLoad(this));
} }
@@ -246,14 +209,8 @@ public class PluginManager {
if (disabledPlugins.contains(plugin.getClass().getName())) continue; if (disabledPlugins.contains(plugin.getClass().getName())) continue;
plugin.disable(); plugin.disable();
} }
cachedFunctions.clear();
cachedOperators.clear();
cachedNumberImplementations.clear();
cachedInterfaceImplementations.clear(); cachedInterfaceImplementations.clear();
cachedPi.clear(); cachedPi.clear();
allFunctions.clear();
allOperators.clear();
allNumberImplementations.clear();
listeners.forEach(e -> e.onUnload(this)); listeners.forEach(e -> e.onUnload(this));
} }
@@ -271,7 +228,7 @@ public class PluginManager {
* @return the set of all functions that were loaded. * @return the set of all functions that were loaded.
*/ */
public Set<String> getAllFunctions() { public Set<String> getAllFunctions() {
return allFunctions; return registeredFunctions.keySet();
} }
/** /**
@@ -280,7 +237,7 @@ public class PluginManager {
* @return the set of all operators that were loaded. * @return the set of all operators that were loaded.
*/ */
public Set<String> getAllOperators() { public Set<String> getAllOperators() {
return allOperators; return registeredOperators.keySet();
} }
/** /**
@@ -289,7 +246,7 @@ public class PluginManager {
* @return the set of all implementations that were loaded. * @return the set of all implementations that were loaded.
*/ */
public Set<String> getAllNumberImplementations() { public Set<String> getAllNumberImplementations() {
return allNumberImplementations; return registeredNumberImplementations.keySet();
} }
/** /**

View File

@@ -94,7 +94,7 @@ public class StandardPlugin extends Plugin {
public static final Operator OP_DIVIDE = new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 1, new Function() { public static final Operator OP_DIVIDE = new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 1, new Function() {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2 && params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClass())) != 0; return params.length == 2 && params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClassVal())) != 0;
} }
@Override @Override
@@ -110,26 +110,26 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1 return params.length == 1
&& params[0].fractionalPart().compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0 && params[0].fractionalPart().compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClassVal())) == 0
&& params[0].signum() >= 0; && params[0].signum() >= 0;
} }
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
if (params[0].signum() == 0) { if (params[0].signum() == 0) {
return fromInt(params[0].getClass(), 1); return fromInt(params[0].getClassVal(), 1);
} }
NumberInterface factorial = params[0]; NumberInterface factorial = params[0];
NumberInterface multiplier = params[0]; NumberInterface multiplier = params[0];
//It is necessary to later prevent calls of factorial on anything but non-negative integers. //It is necessary to later prevent calls of factorial on anything but non-negative integers.
while ((multiplier = multiplier.subtract(NaiveNumber.ONE.promoteTo(multiplier.getClass()))).signum() == 1) { while ((multiplier = multiplier.subtract(NaiveNumber.ONE.promoteTo(multiplier.getClassVal()))).signum() == 1) {
factorial = factorial.multiply(multiplier); factorial = factorial.multiply(multiplier);
} }
return factorial; return factorial;
/*if(!storedList.containsKey(params[0].getClass())){ /*if(!storedList.containsKey(params[0].getClassVal())){
storedList.put(params[0].getClass(), new ArrayList<NumberInterface>()); storedList.put(params[0].getClassVal(), new ArrayList<NumberInterface>());
storedList.get(params[0].getClass()).add(NaiveNumber.ONE.promoteTo(params[0].getClass())); storedList.get(params[0].getClassVal()).add(NaiveNumber.ONE.promoteTo(params[0].getClassVal()));
storedList.get(params[0].getClass()).add(NaiveNumber.ONE.promoteTo(params[0].getClass())); storedList.get(params[0].getClassVal()).add(NaiveNumber.ONE.promoteTo(params[0].getClassVal()));
}*/ }*/
} }
}); });
@@ -144,7 +144,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return params[0].multiply((new NaiveNumber(params[0].signum())).promoteTo(params[0].getClass())); return params[0].multiply((new NaiveNumber(params[0].signum())).promoteTo(params[0].getClassVal()));
} }
}; };
/** /**
@@ -153,31 +153,31 @@ public class StandardPlugin extends Plugin {
public static final Function FUNCTION_LN = new Function() { public static final Function FUNCTION_LN = new Function() {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1 && params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) > 0; return params.length == 1 && params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClassVal())) > 0;
} }
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface param = params[0]; NumberInterface param = params[0];
int powersOf2 = 0; int powersOf2 = 0;
while (FUNCTION_ABS.apply(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass()))).compareTo(new NaiveNumber(0.1).promoteTo(param.getClass())) >= 0) { while (FUNCTION_ABS.apply(param.subtract(NaiveNumber.ONE.promoteTo(param.getClassVal()))).compareTo(new NaiveNumber(0.1).promoteTo(param.getClassVal())) >= 0) {
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() == 1) { if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClassVal())).signum() == 1) {
param = param.divide(fromInt(param.getClass(), 2)); param = param.divide(fromInt(param.getClassVal(), 2));
powersOf2++; powersOf2++;
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != 1) { if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClassVal())).signum() != 1) {
break; break;
//No infinite loop for you. //No infinite loop for you.
} }
} else { } else {
param = param.multiply(fromInt(param.getClass(), 2)); param = param.multiply(fromInt(param.getClassVal(), 2));
powersOf2--; powersOf2--;
if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != -1) { if (param.subtract(NaiveNumber.ONE.promoteTo(param.getClassVal())).signum() != -1) {
break; break;
//No infinite loop for you. //No infinite loop for you.
} }
} }
} }
return getLog2(param).multiply((new NaiveNumber(powersOf2)).promoteTo(param.getClass())).add(getLogPartialSum(param)); return getLog2(param).multiply((new NaiveNumber(powersOf2)).promoteTo(param.getClassVal())).add(getLogPartialSum(param));
} }
/** /**
@@ -189,13 +189,13 @@ public class StandardPlugin extends Plugin {
private NumberInterface getLogPartialSum(NumberInterface x) { private NumberInterface getLogPartialSum(NumberInterface x) {
NumberInterface maxError = getMaxError(x); NumberInterface maxError = getMaxError(x);
x = x.subtract(NaiveNumber.ONE.promoteTo(x.getClass())); //Terms used are for log(x+1). x = x.subtract(NaiveNumber.ONE.promoteTo(x.getClassVal())); //Terms used are for log(x+1).
NumberInterface currentNumerator = x, currentTerm = x, sum = x; NumberInterface currentNumerator = x, currentTerm = x, sum = x;
int n = 1; int n = 1;
while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) { while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) {
n++; n++;
currentNumerator = currentNumerator.multiply(x).negate(); currentNumerator = currentNumerator.multiply(x).negate();
currentTerm = currentNumerator.divide(new NaiveNumber(n).promoteTo(x.getClass())); currentTerm = currentNumerator.divide(new NaiveNumber(n).promoteTo(x.getClassVal()));
sum = sum.add(currentTerm); sum = sum.add(currentTerm);
} }
return sum; return sum;
@@ -208,18 +208,18 @@ public class StandardPlugin extends Plugin {
*/ */
private NumberInterface getLog2(NumberInterface number) { private NumberInterface getLog2(NumberInterface number) {
NumberInterface maxError = getMaxError(number); NumberInterface maxError = getMaxError(number);
//NumberInterface errorBound = fromInt(number.getClass(), 1); //NumberInterface errorBound = fromInt(number.getClassVal(), 1);
//We'll use the series \sigma_{n >= 1) ((1/3^n + 1/4^n) * 1/n) //We'll use the series \sigma_{n >= 1) ((1/3^n + 1/4^n) * 1/n)
//In the following, a=1/3^n, b=1/4^n, c = 1/n. //In the following, a=1/3^n, b=1/4^n, c = 1/n.
//a is also an error bound. //a is also an error bound.
NumberInterface a = fromInt(number.getClass(), 1), b = a, c = a; NumberInterface a = fromInt(number.getClassVal(), 1), b = a, c = a;
NumberInterface sum = NaiveNumber.ZERO.promoteTo(number.getClass()); NumberInterface sum = NaiveNumber.ZERO.promoteTo(number.getClassVal());
int n = 0; int n = 0;
while (a.compareTo(maxError) >= 1) { while (a.compareTo(maxError) >= 1) {
n++; n++;
a = a.divide(fromInt(number.getClass(), 3)); a = a.divide(fromInt(number.getClassVal(), 3));
b = b.divide(fromInt(number.getClass(), 4)); b = b.divide(fromInt(number.getClassVal(), 4));
c = NaiveNumber.ONE.promoteTo(number.getClass()).divide((new NaiveNumber(n)).promoteTo(number.getClass())); c = NaiveNumber.ONE.promoteTo(number.getClassVal()).divide((new NaiveNumber(n)).promoteTo(number.getClassVal()));
sum = sum.add(a.add(b).multiply(c)); sum = sum.add(a.add(b).multiply(c));
} }
return sum; return sum;
@@ -236,7 +236,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return OP_CARET.getFunction().apply(params[0], ((new NaiveNumber(0.5)).promoteTo(params[0].getClass()))); return OP_CARET.getFunction().apply(params[0], ((new NaiveNumber(0.5)).promoteTo(params[0].getClassVal())));
} }
}; };
/** /**
@@ -304,25 +304,25 @@ public class StandardPlugin extends Plugin {
NumberInterface maxError = getMaxError(params[0]); NumberInterface maxError = getMaxError(params[0]);
int n = 0; int n = 0;
if (params[0].signum() <= 0) { if (params[0].signum() <= 0) {
NumberInterface currentTerm = NaiveNumber.ONE.promoteTo(params[0].getClass()), sum = currentTerm; NumberInterface currentTerm = NaiveNumber.ONE.promoteTo(params[0].getClassVal()), sum = currentTerm;
while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) { while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0) {
n++; n++;
currentTerm = currentTerm.multiply(params[0]).divide((new NaiveNumber(n)).promoteTo(params[0].getClass())); currentTerm = currentTerm.multiply(params[0]).divide((new NaiveNumber(n)).promoteTo(params[0].getClassVal()));
sum = sum.add(currentTerm); sum = sum.add(currentTerm);
} }
return sum; return sum;
} else { } else {
//We need n such that x^(n+1) * 3^ceil(x) <= maxError * (n+1)!. //We need n such that x^(n+1) * 3^ceil(x) <= maxError * (n+1)!.
//right and left refer to lhs and rhs in the above inequality. //right and left refer to lhs and rhs in the above inequality.
NumberInterface sum = NaiveNumber.ONE.promoteTo(params[0].getClass()); NumberInterface sum = NaiveNumber.ONE.promoteTo(params[0].getClassVal());
NumberInterface nextNumerator = params[0]; NumberInterface nextNumerator = params[0];
NumberInterface left = params[0].multiply(fromInt(params[0].getClass(), 3).intPow(params[0].ceiling().intValue())), right = maxError; NumberInterface left = params[0].multiply(fromInt(params[0].getClassVal(), 3).intPow(params[0].ceiling().intValue())), right = maxError;
do { do {
sum = sum.add(nextNumerator.divide(factorial(params[0].getClass(), n + 1))); sum = sum.add(nextNumerator.divide(factorial(params[0].getClassVal(), n + 1)));
n++; n++;
nextNumerator = nextNumerator.multiply(params[0]); nextNumerator = nextNumerator.multiply(params[0]);
left = left.multiply(params[0]); left = left.multiply(params[0]);
NumberInterface nextN = (new NaiveNumber(n + 1)).promoteTo(params[0].getClass()); NumberInterface nextN = (new NaiveNumber(n + 1)).promoteTo(params[0].getClassVal());
right = right.multiply(nextN); right = right.multiply(nextN);
//System.out.println(left + ", " + right); //System.out.println(left + ", " + right);
} }
@@ -339,16 +339,16 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected boolean matchesParams(NumberInterface[] params) { protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2 return params.length == 2
&& !(params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0 && !(params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClassVal())) == 0
&& params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClass())) == 0); && params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[1].getClassVal())) == 0);
} }
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
if (params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0) if (params[0].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClassVal())) == 0)
return NaiveNumber.ZERO.promoteTo(params[0].getClass()); return NaiveNumber.ZERO.promoteTo(params[0].getClassVal());
else if (params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClass())) == 0) else if (params[1].compareTo(NaiveNumber.ZERO.promoteTo(params[0].getClassVal())) == 0)
return NaiveNumber.ONE.promoteTo(params[1].getClass()); return NaiveNumber.ONE.promoteTo(params[1].getClassVal());
return FUNCTION_EXP.apply(FUNCTION_LN.apply(FUNCTION_ABS.apply(params[0])).multiply(params[1])); return FUNCTION_EXP.apply(FUNCTION_LN.apply(FUNCTION_ABS.apply(params[0])).multiply(params[1]));
} }
}); });
@@ -363,13 +363,13 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface pi = getPi(params[0].getClass()); NumberInterface pi = piFor(params[0].getClassVal());
NumberInterface twoPi = pi.multiply(fromInt(pi.getClass(), 2)); NumberInterface twoPi = pi.multiply(fromInt(pi.getClassVal(), 2));
NumberInterface theta = getSmallAngle(params[0], pi); NumberInterface theta = getSmallAngle(params[0], pi);
//System.out.println(theta); //System.out.println(theta);
if (theta.compareTo(pi.multiply(new NaiveNumber(1.5).promoteTo(twoPi.getClass()))) >= 0) { if (theta.compareTo(pi.multiply(new NaiveNumber(1.5).promoteTo(twoPi.getClassVal()))) >= 0) {
theta = theta.subtract(twoPi); theta = theta.subtract(twoPi);
} else if (theta.compareTo(pi.divide(fromInt(pi.getClass(), 2))) > 0) { } else if (theta.compareTo(pi.divide(fromInt(pi.getClassVal(), 2))) > 0) {
theta = pi.subtract(theta); theta = pi.subtract(theta);
} }
//System.out.println(theta); //System.out.println(theta);
@@ -387,7 +387,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return functionSin.apply(getPi(params[0].getClass()).divide(fromInt(params[0].getClass(), 2)) return functionSin.apply(piFor(params[0].getClassVal()).divide(fromInt(params[0].getClassVal(), 2))
.subtract(params[0])); .subtract(params[0]));
} }
}; };
@@ -416,7 +416,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return NaiveNumber.ONE.promoteTo(params[0].getClass()).divide(functionCos.apply(params[0])); return NaiveNumber.ONE.promoteTo(params[0].getClassVal()).divide(functionCos.apply(params[0]));
} }
}; };
/** /**
@@ -430,7 +430,7 @@ public class StandardPlugin extends Plugin {
@Override @Override
protected NumberInterface applyInternal(NumberInterface[] params) { protected NumberInterface applyInternal(NumberInterface[] params) {
return NaiveNumber.ONE.promoteTo(params[0].getClass()).divide(functionSin.apply(params[0])); return NaiveNumber.ONE.promoteTo(params[0].getClassVal()).divide(functionSin.apply(params[0]));
} }
}; };
/** /**
@@ -461,7 +461,7 @@ public class StandardPlugin extends Plugin {
* @return the value of the partial sum that has the same class as x. * @return the value of the partial sum that has the same class as x.
*/ */
private static NumberInterface sumSeries(NumberInterface x, BiFunction<Integer, NumberInterface, NumberInterface> nthTermFunction, int n) { private static NumberInterface sumSeries(NumberInterface x, BiFunction<Integer, NumberInterface, NumberInterface> nthTermFunction, int n) {
NumberInterface sum = NaiveNumber.ZERO.promoteTo(x.getClass()); NumberInterface sum = NaiveNumber.ZERO.promoteTo(x.getClassVal());
for (int i = 0; i <= n; i++) { for (int i = 0; i <= n; i++) {
sum = sum.add(nthTermFunction.apply(i, x)); sum = sum.add(nthTermFunction.apply(i, x));
} }
@@ -475,7 +475,7 @@ public class StandardPlugin extends Plugin {
* @return the maximum error. * @return the maximum error.
*/ */
private static NumberInterface getMaxError(NumberInterface number) { private static NumberInterface getMaxError(NumberInterface number) {
return fromInt(number.getClass(), 10).intPow(-number.getMaxPrecision()); return fromInt(number.getClassVal(), 10).intPow(-number.getMaxPrecision());
} }
/** /**
@@ -514,7 +514,7 @@ public class StandardPlugin extends Plugin {
do { do {
n += 2; n += 2;
power = power.multiply(multiplier); power = power.multiply(multiplier);
currentTerm = power.divide(factorial(x.getClass(), n)); currentTerm = power.divide(factorial(x.getClassVal(), n));
sum = sum.add(currentTerm); sum = sum.add(currentTerm);
} while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0); } while (FUNCTION_ABS.apply(currentTerm).compareTo(maxError) > 0);
return sum; return sum;
@@ -527,7 +527,7 @@ public class StandardPlugin extends Plugin {
* @return theta in [0, 2pi) that differs from phi by a multiple of 2pi. * @return theta in [0, 2pi) that differs from phi by a multiple of 2pi.
*/ */
private static NumberInterface getSmallAngle(NumberInterface phi, NumberInterface pi) { private static NumberInterface getSmallAngle(NumberInterface phi, NumberInterface pi) {
NumberInterface twoPi = pi.multiply(new NaiveNumber("2").promoteTo(phi.getClass())); NumberInterface twoPi = pi.multiply(new NaiveNumber("2").promoteTo(phi.getClassVal()));
NumberInterface theta = FUNCTION_ABS.apply(phi).subtract(twoPi NumberInterface theta = FUNCTION_ABS.apply(phi).subtract(twoPi
.multiply(FUNCTION_ABS.apply(phi).divide(twoPi).floor())); //Now theta is in [0, 2pi). .multiply(FUNCTION_ABS.apply(phi).divide(twoPi).floor())); //Now theta is in [0, 2pi).
if (phi.signum() < 0) { if (phi.signum() < 0) {

View File

@@ -0,0 +1,52 @@
package org.nwapw.abacus.plugin;
import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.function.OperatorAssociativity;
import org.nwapw.abacus.function.OperatorType;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.number.Variable;
import java.lang.reflect.Method;
import java.util.HashMap;
public class VariablePlugin extends Plugin {
private HashMap<String,NumberInterface> variableMap;
public final Operator OP_EQUALS = new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, -1, new Function() {
//private HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>> storedList = new HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>>();
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
//System.out.println((char)Double.parseDouble(params[1].toString()));
//System.out.println(params[0].toString());
if (params[0] instanceof Variable){
variableMap.put(((Variable) params[0]).getVariable(), params[1]);
}
return params[1];
}
});
public NumberInterface getValue(String variable){
return variableMap.get(variable);
}
public VariablePlugin(PluginManager manager) {
super(manager);
//variables = new ArrayList<>();
variableMap=new HashMap<>();
}
@Override
public void onEnable(){
//variables = new ArrayList<>();
variableMap=new HashMap<>();
registerOperator("=",OP_EQUALS);
}
@Override
public void onDisable(){
}
};

View File

@@ -3,6 +3,7 @@ package org.nwapw.abacus.tree;
import org.nwapw.abacus.Abacus; import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.function.Function; import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.number.NumberInterface; import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.number.Variable;
/** /**
* A reducer implementation that turns a tree into a single number. * A reducer implementation that turns a tree into a single number.
@@ -47,6 +48,8 @@ public class NumberReducer implements Reducer<NumberInterface> {
Function function = abacus.getPluginManager().functionFor(((FunctionNode) node).getFunction()); Function function = abacus.getPluginManager().functionFor(((FunctionNode) node).getFunction());
if (function == null) return null; if (function == null) return null;
return function.apply(convertedChildren); return function.apply(convertedChildren);
} else if (node instanceof VariableNode){
return (NumberInterface)new Variable(abacus.getVar(((VariableNode)node).getVariable()),((VariableNode)node).getVariable());
} }
return null; return null;
} }

View File

@@ -7,7 +7,7 @@ package org.nwapw.abacus.tree;
public enum TokenType { public enum TokenType {
INTERNAL_FUNCTION_END(-1), INTERNAL_FUNCTION_END(-1),
ANY(0), WHITESPACE(1), COMMA(2), OP(3), NUM(4), FUNCTION(5), OPEN_PARENTH(6), CLOSE_PARENTH(7); ANY(0), WHITESPACE(1), COMMA(2), OP(3), NUM(4), VARIABLE(5), FUNCTION(6), OPEN_PARENTH(7), CLOSE_PARENTH(8);
/** /**
* The priority by which this token gets sorted. * The priority by which this token gets sorted.

View File

@@ -0,0 +1,24 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.number.NumberInterface;
public class VariableNode extends TreeNode{
private String variable;
public VariableNode() {
variable = null;
}
public VariableNode(String name){
this.variable = name;
}
public String getVariable() {
return variable;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
return reducer.reduceNode(this);
}
@Override
public String toString() {
return variable;
}
}

View File

@@ -50,7 +50,9 @@
<ListView fx:id="enabledPluginView" <ListView fx:id="enabledPluginView"
GridPane.rowIndex="1" GridPane.columnIndex="0" GridPane.rowIndex="1" GridPane.columnIndex="0"
GridPane.columnSpan="2" maxHeight="100"/> GridPane.columnSpan="2" maxHeight="100"/>
<FlowPane GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="2" hgap="10" <Text GridPane.columnIndex="0" GridPane.rowIndex="2" text="Computation Limit"/>
<TextField fx:id="computationLimitField" GridPane.columnIndex="1" GridPane.rowIndex="2"/>
<FlowPane GridPane.columnIndex="0" GridPane.columnSpan="2" GridPane.rowIndex="3" hgap="10"
vgap="10"> vgap="10">
<Button text="Apply" onAction="#performSave"/> <Button text="Apply" onAction="#performSave"/>
<Button text="Reload Plugins" onAction="#performReload"/> <Button text="Reload Plugins" onAction="#performReload"/>
@@ -58,6 +60,62 @@
</FlowPane> </FlowPane>
</GridPane> </GridPane>
</Tab> </Tab>
<Tab fx:id="macroTab" text="Macros" closable="false">
<BorderPane>
<padding>
<Insets top="10" bottom="10" left="10" right="10"/>
</padding>
<center>
<BorderPane>
<center>
<ScrollPane hbarPolicy="NEVER" vbarPolicy="NEVER" prefWidth="50" fitToWidth="true">
<SplitPane prefHeight="Infinity" >
<BorderPane prefHeight="Infinity">
<center>
<TextArea fx:id="macroField" wrapText="false" prefHeight="Infinity"/>
</center>
</BorderPane>
<BorderPane prefHeight="Infinity">
<center>
<TextArea fx:id="macroOutputField" wrapText="false" text="aaa&#xA;aaaaa" editable="false" prefHeight="Infinity"/>
</center>
</BorderPane>
</SplitPane>
</ScrollPane>
</center>
</BorderPane>
</center>
<bottom>
<VBox>
<Button fx:id="inputButtonMacro" text="Calculate"
onAction="#macroCalculation" maxWidth="Infinity"/>
<Button fx:id="stopButtonMacro" text="Stop" onAction="#performStop" maxWidth="Infinity"/>
</VBox>
</bottom>
</BorderPane>
<!--
<GridPane>
<padding>
<Insets top="10" bottom="10" left="10" right="10"/>
</padding>
<columnConstraints>
<ColumnConstraints percentWidth="100.0"/>
</columnConstraints>
<rowConstraints>
<RowConstraints percentHeight="85.0"/>
<RowConstraints/>
<RowConstraints/>
</rowConstraints>
<TextArea fx:id="macroField" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
<Button fx:id="inputButtonMacro" text="Calculate" maxWidth="Infinity"
onAction="#macroCalculation" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
<Button fx:id="stopButtonMacro" text="Stop" onAction="#performStop" maxWidth="Infinity"
disable="true" GridPane.columnIndex="0" GridPane.rowIndex="2"/>
</GridPane>
-->
</Tab>
</TabPane> </TabPane>
</center> </center>

View File

@@ -11,7 +11,7 @@ import org.nwapw.abacus.tree.TreeNode;
public class CalculationTests { public class CalculationTests {
private static Abacus abacus = new Abacus(new Configuration("precise", new String[]{})); private static Abacus abacus = new Abacus(new Configuration(0, "precise", new String[]{}),null);
@BeforeClass @BeforeClass
public static void prepareTests(){ public static void prepareTests(){

View File

@@ -19,7 +19,7 @@ import java.util.List;
public class TokenizerTests { public class TokenizerTests {
private static Abacus abacus = new Abacus(new Configuration("precise", new String[]{})); private static Abacus abacus = new Abacus(new Configuration(0, "precise", new String[]{}),null);
private static LexerTokenizer lexerTokenizer = new LexerTokenizer(); private static LexerTokenizer lexerTokenizer = new LexerTokenizer();
private static Function subtractFunction = new Function() { private static Function subtractFunction = new Function() {
@Override @Override