mirror of
https://github.com/DanilaFe/abacus
synced 2026-01-13 18:35:19 +00:00
Move the source files into a new default directory.
This commit is contained in:
77
src/main/java/org/nwapw/abacus/plugin/ClassFinder.java
Normal file
77
src/main/java/org/nwapw/abacus/plugin/ClassFinder.java
Normal file
@@ -0,0 +1,77 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Class that loads plugin classes from their jars.
|
||||
*/
|
||||
public class ClassFinder {
|
||||
|
||||
/**
|
||||
* Loads all the plugin classes from the given plugin folder.
|
||||
* @param filePath the path for the plugin folder.
|
||||
* @return the list of all loaded classes.
|
||||
* @throws IOException thrown if an error occurred scanning the plugin folder.
|
||||
* @throws ClassNotFoundException thrown if the class listed in the file doesn't get loaded.
|
||||
*/
|
||||
public static List<Class<?>> loadJars(String filePath) throws IOException, ClassNotFoundException {
|
||||
return loadJars(new File(filePath));
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads all the plugin classes from the given plugin folder.
|
||||
* @param pluginFolderPath the folder in which to look for plugins.
|
||||
* @return the list of all loaded classes.
|
||||
* @throws IOException thrown if an error occurred scanning the plugin folder.
|
||||
* @throws ClassNotFoundException thrown if the class listed in the file doesn't get loaded.
|
||||
*/
|
||||
public static List<Class<?>> loadJars(File pluginFolderPath) throws IOException, ClassNotFoundException {
|
||||
ArrayList<Class<?>> toReturn = new ArrayList<>();
|
||||
if(!pluginFolderPath.exists()) return toReturn;
|
||||
ArrayList<File> files = Files.walk(pluginFolderPath.toPath())
|
||||
.map(Path::toFile)
|
||||
.filter(f -> f.getName().endsWith(".jar"))
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
for (File file : files){
|
||||
toReturn.addAll(loadJar(file));
|
||||
}
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the classes from a single path, given by the file.
|
||||
* @param jarLocation the location of the jar to load.
|
||||
* @return the list of loaded classes loaded from the jar.
|
||||
* @throws IOException thrown if there was an error reading the file
|
||||
* @throws ClassNotFoundException thrown if the class could not be loaded.
|
||||
*/
|
||||
public static List<Class<?>> loadJar(File jarLocation) throws IOException, ClassNotFoundException {
|
||||
ArrayList<Class<?>> loadedClasses = new ArrayList<>();
|
||||
String path = jarLocation.getPath();
|
||||
URL[] urls = new URL[]{new URL("jar:file:" + path + "!/")};
|
||||
|
||||
URLClassLoader classLoader = URLClassLoader.newInstance(urls);
|
||||
JarFile jarFolder = new JarFile(jarLocation);
|
||||
Enumeration jarEntityList = jarFolder.entries();
|
||||
|
||||
while (jarEntityList.hasMoreElements()) {
|
||||
JarEntry jarEntity = (JarEntry) jarEntityList.nextElement();
|
||||
if (jarEntity.getName().endsWith(".class")) {
|
||||
loadedClasses.add(classLoader.loadClass(jarEntity.getName().replace('/', '.').substring(0, jarEntity.getName().length() - 6)));
|
||||
}
|
||||
}
|
||||
return loadedClasses;
|
||||
}
|
||||
|
||||
}
|
||||
197
src/main/java/org/nwapw/abacus/plugin/Plugin.java
Normal file
197
src/main/java/org/nwapw/abacus/plugin/Plugin.java
Normal file
@@ -0,0 +1,197 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
import org.nwapw.abacus.function.Function;
|
||||
import org.nwapw.abacus.function.Operator;
|
||||
import org.nwapw.abacus.number.NumberInterface;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A plugin class that can be externally implemented and loaded via the
|
||||
* plugin manager. Plugins provide functionality to the calculator
|
||||
* with the "hasFunction" and "getFunction" functions,
|
||||
* and can use "registerFunction" and "functionFor" for
|
||||
* loading internally.
|
||||
*/
|
||||
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;
|
||||
/**
|
||||
* A hash map of operators mapped to their string names.
|
||||
*/
|
||||
private Map<String, Class<? extends NumberInterface>> numbers;
|
||||
/**
|
||||
* The plugin manager in which to search for functions
|
||||
* not inside this package,
|
||||
*/
|
||||
private PluginManager manager;
|
||||
/**
|
||||
* Whether this plugin has been loaded.
|
||||
*/
|
||||
private boolean enabled;
|
||||
|
||||
private Plugin(){ }
|
||||
|
||||
/**
|
||||
* Creates a new plugin with the given PluginManager.
|
||||
* @param manager the manager controlling this plugin.
|
||||
*/
|
||||
public Plugin(PluginManager manager) {
|
||||
this.manager = manager;
|
||||
functions = new HashMap<>();
|
||||
operators = new HashMap<>();
|
||||
numbers = new HashMap<>();
|
||||
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 all numbers provided by this plugin.
|
||||
* @return the list of registered numbers.
|
||||
*/
|
||||
public final Set<String> providedNumbers(){
|
||||
return numbers.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 class under the given name.
|
||||
* @param numberName the name of the class.
|
||||
* @return the class, or null if the plugin doesn't provide it.
|
||||
*/
|
||||
public final Class<? extends NumberInterface> getNumber(String numberName){
|
||||
return numbers.get(numberName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the function, loading the necessary instances
|
||||
* of functions.
|
||||
*/
|
||||
public final void enable(){
|
||||
if(enabled) return;
|
||||
onEnable();
|
||||
enabled = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables the plugin, clearing loaded data store by default
|
||||
* and calling its disable() method.
|
||||
*/
|
||||
public final void disable(){
|
||||
if(!enabled) return;
|
||||
onDisable();
|
||||
functions.clear();
|
||||
operators.clear();
|
||||
enabled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* To be used in load(). Registers a function abstract class with the
|
||||
* plugin internally, which makes it accessible to the plugin manager.
|
||||
* @param name the name to register by.
|
||||
* @param toRegister the function implementation.
|
||||
*/
|
||||
protected final void registerFunction(String name, Function toRegister) {
|
||||
functions.put(name, toRegister);
|
||||
}
|
||||
|
||||
/**
|
||||
* To be used in load(). Registers an operator abstract class
|
||||
* with the plugin internally, which makes it accessible to
|
||||
* the plugin manager.
|
||||
* @param name the name of the operator.
|
||||
* @param operator the operator to register.
|
||||
*/
|
||||
protected final void registerOperator(String name, Operator operator) {
|
||||
operators.put(name, operator);
|
||||
}
|
||||
|
||||
/**
|
||||
* To be used in load(). Registers a number class
|
||||
* with the plugin internally, which makes it possible
|
||||
* for the user to select it as an "implementation" for the
|
||||
* number that they would like to use.
|
||||
* @param name the name to register it under.
|
||||
* @param toRegister the class to register.
|
||||
*/
|
||||
protected final void registerNumber(String name, Class<? extends NumberInterface> toRegister){
|
||||
numbers.put(name, toRegister);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the PluginManager for the given function name.
|
||||
* This can be used by the plugins internally in order to call functions
|
||||
* they do not provide.
|
||||
* @param name the name for which to search
|
||||
* @return the resulting function, or null if none was found for that name.
|
||||
*/
|
||||
protected final Function functionFor(String name) {
|
||||
return manager.functionFor(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the PluginManager for the given operator name.
|
||||
* This can be used by the plugins internally in order to call
|
||||
* operations they do not provide.
|
||||
* @param name the name for which to search
|
||||
* @return the resulting operator, or null if none was found for that name.
|
||||
*/
|
||||
protected final Operator operatorFor(String name) {
|
||||
return manager.operatorFor(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract method to be overridden by plugin implementation, in which the plugins
|
||||
* are supposed to register the functions they provide and do any other
|
||||
* necessary setup.
|
||||
*/
|
||||
public abstract void onEnable();
|
||||
|
||||
/**
|
||||
* Abstract method overridden by the plugin implementation, in which the plugins
|
||||
* are supposed to dispose of loaded functions, operators, and macros.
|
||||
*/
|
||||
public abstract void onDisable();
|
||||
|
||||
}
|
||||
20
src/main/java/org/nwapw/abacus/plugin/PluginListener.java
Normal file
20
src/main/java/org/nwapw/abacus/plugin/PluginListener.java
Normal file
@@ -0,0 +1,20 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
/**
|
||||
* A listener that responds to changes in the PluginManager.
|
||||
*/
|
||||
public interface PluginListener {
|
||||
|
||||
/**
|
||||
* Called when the PluginManager loads plugins.
|
||||
* @param manager the manager that fired the event.
|
||||
*/
|
||||
public void onLoad(PluginManager manager);
|
||||
|
||||
/**
|
||||
* Called when the PluginManager unloads all its plugins.
|
||||
* @param manager the manager that fired the event.
|
||||
*/
|
||||
public void onUnload(PluginManager manager);
|
||||
|
||||
}
|
||||
231
src/main/java/org/nwapw/abacus/plugin/PluginManager.java
Normal file
231
src/main/java/org/nwapw/abacus/plugin/PluginManager.java
Normal file
@@ -0,0 +1,231 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
import org.nwapw.abacus.Abacus;
|
||||
import org.nwapw.abacus.function.Function;
|
||||
import org.nwapw.abacus.function.Operator;
|
||||
import org.nwapw.abacus.number.NumberInterface;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A class that controls instances of plugins, allowing for them
|
||||
* to interact with each other and the calculator.
|
||||
*/
|
||||
public class PluginManager {
|
||||
|
||||
/**
|
||||
* List of classes loaded by this manager.
|
||||
*/
|
||||
private Set<Class<?>> loadedPluginClasses;
|
||||
/**
|
||||
* A list of loaded plugins.
|
||||
*/
|
||||
private Set<Plugin> plugins;
|
||||
/**
|
||||
* List of functions that have been cached,
|
||||
* that is, found in a plugin and returned.
|
||||
*/
|
||||
private Map<String, Function> cachedFunctions;
|
||||
/**
|
||||
* List of operators that have been cached,
|
||||
* that is, found in a plugin and returned.
|
||||
*/
|
||||
private Map<String, Operator> cachedOperators;
|
||||
/**
|
||||
* List of registered number implementations that have
|
||||
* been cached, that is, found in a plugin and returned.
|
||||
*/
|
||||
private Map<String, Class<? extends NumberInterface>> cachedNumbers;
|
||||
/**
|
||||
* 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 numbers loaded by the plugins.
|
||||
*/
|
||||
private Set<String> allNumbers;
|
||||
/**
|
||||
* The list of plugin listeners attached to this instance.
|
||||
*/
|
||||
private Set<PluginListener> listeners;
|
||||
/**
|
||||
* The instance of Abacus that is used to interact with its other
|
||||
* components.
|
||||
*/
|
||||
private Abacus abacus;
|
||||
|
||||
/**
|
||||
* Creates a new plugin manager.
|
||||
*/
|
||||
public PluginManager(Abacus abacus){
|
||||
this.abacus = abacus;
|
||||
loadedPluginClasses = new HashSet<>();
|
||||
plugins = new HashSet<>();
|
||||
cachedFunctions = new HashMap<>();
|
||||
cachedOperators = new HashMap<>();
|
||||
cachedNumbers = new HashMap<>();
|
||||
allFunctions = new HashSet<>();
|
||||
allOperators = new HashSet<>();
|
||||
allNumbers = new HashSet<>();
|
||||
listeners = new HashSet<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the plugin list for a certain value, retrieving the Plugin's
|
||||
* list of items of the type using the setFunction and getting the value
|
||||
* of it is available via getFunction. If the value is contained
|
||||
* 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
|
||||
* @return the retrieved element, or null if it was not found.
|
||||
*/
|
||||
private static <T> T searchCached(Collection<Plugin> plugins, Map<String, T> cache,
|
||||
java.util.function.Function<Plugin, Set<String>> setFunction,
|
||||
java.util.function.BiFunction<Plugin, String, T> getFunction,
|
||||
String 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.
|
||||
* @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.
|
||||
* @return the operator under the given name.
|
||||
*/
|
||||
public Operator operatorFor(String name){
|
||||
return searchCached(plugins, cachedOperators, Plugin::providedOperators, Plugin::getOperator, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a numer implementation under the given name.
|
||||
* @param name the name of the implementation.
|
||||
* @return the implementation class
|
||||
*/
|
||||
public Class<? extends NumberInterface> numberFor(String name){
|
||||
return searchCached(plugins, cachedNumbers, Plugin::providedNumbers, Plugin::getNumber, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an instance of Plugin that already has been instantiated.
|
||||
* @param plugin the plugin to add.
|
||||
*/
|
||||
public void addInstantiated(Plugin plugin){
|
||||
if(loadedPluginClasses.contains(plugin.getClass())) return;
|
||||
plugins.add(plugin);
|
||||
loadedPluginClasses.add(plugin.getClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a class of plugin, and adds it to this
|
||||
* plugin manager.
|
||||
* @param newClass the new class to instantiate.
|
||||
*/
|
||||
public void addClass(Class<?> newClass){
|
||||
if(!Plugin.class.isAssignableFrom(newClass) || newClass == Plugin.class) return;
|
||||
try {
|
||||
addInstantiated((Plugin) newClass.getConstructor(PluginManager.class).newInstance(this));
|
||||
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads all the plugins in the PluginManager.
|
||||
*/
|
||||
public void load(){
|
||||
for(Plugin plugin : plugins) plugin.enable();
|
||||
for(Plugin plugin : plugins){
|
||||
allFunctions.addAll(plugin.providedFunctions());
|
||||
allOperators.addAll(plugin.providedOperators());
|
||||
allNumbers.addAll(plugin.providedNumbers());
|
||||
}
|
||||
listeners.forEach(e -> e.onLoad(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Unloads all the plugins in the PluginManager.
|
||||
*/
|
||||
public void unload(){
|
||||
for(Plugin plugin : plugins) plugin.disable();
|
||||
allFunctions.clear();
|
||||
allOperators.clear();
|
||||
allNumbers.clear();
|
||||
listeners.forEach(e -> e.onUnload(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads all the plugins in the PluginManager.
|
||||
*/
|
||||
public void reload(){
|
||||
unload();
|
||||
reload();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the functions loaded by the Plugin Manager.
|
||||
* @return the set of all functions that were loaded.
|
||||
*/
|
||||
public Set<String> getAllFunctions() {
|
||||
return allFunctions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the operators loaded by the Plugin Manager.
|
||||
* @return the set of all operators that were loaded.
|
||||
*/
|
||||
public Set<String> getAllOperators() {
|
||||
return allOperators;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the number implementations loaded by the Plugin Manager
|
||||
* @return the set of all implementations that were loaded
|
||||
*/
|
||||
public Set<String> getAllNumbers() {
|
||||
return allNumbers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a plugin change listener to this plugin manager.
|
||||
* @param listener the listener to add.
|
||||
*/
|
||||
public void addListener(PluginListener listener){
|
||||
listeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the plugin change listener from this plugin manager.
|
||||
* @param listener the listener to remove.
|
||||
*/
|
||||
public void removeListener(PluginListener listener){
|
||||
listeners.remove(listener);
|
||||
}
|
||||
|
||||
}
|
||||
302
src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java
Executable file
302
src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java
Executable file
@@ -0,0 +1,302 @@
|
||||
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.NaiveNumber;
|
||||
import org.nwapw.abacus.number.NumberInterface;
|
||||
import org.nwapw.abacus.number.PreciseNumber;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
/**
|
||||
* The plugin providing standard functions such as addition and subtraction to
|
||||
* the calculator.
|
||||
*/
|
||||
public class StandardPlugin extends Plugin {
|
||||
|
||||
public StandardPlugin(PluginManager manager) {
|
||||
super(manager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
registerNumber("naive", NaiveNumber.class);
|
||||
registerNumber("precise", PreciseNumber.class);
|
||||
|
||||
registerOperator("+", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 0, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length >= 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
NumberInterface sum = params[0];
|
||||
for(int i = 1; i < params.length; i++){
|
||||
sum = sum.add(params[i]);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}));
|
||||
|
||||
registerOperator("-", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 0, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return params[0].subtract(params[1]);
|
||||
}
|
||||
}));
|
||||
|
||||
registerOperator("*", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX,1, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length >= 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
NumberInterface product = params[0];
|
||||
for(int i = 1; i < params.length; i++){
|
||||
product = product.multiply(params[i]);
|
||||
}
|
||||
return product;
|
||||
}
|
||||
}));
|
||||
|
||||
registerOperator("/", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX,1, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return params[0].divide(params[1]);
|
||||
}
|
||||
}));
|
||||
|
||||
registerOperator("^", new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 2, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return StandardPlugin.this.getFunction("exp").apply(StandardPlugin.this.getFunction("ln").apply(params[0]).multiply(params[1]));
|
||||
}
|
||||
}));
|
||||
|
||||
registerOperator("!", new Operator(OperatorAssociativity.RIGHT, OperatorType.UNARY_POSTFIX, 0, 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 == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
if(params[0].signum() == 0){
|
||||
return (new NaiveNumber(1)).promoteTo(params[0].getClass());
|
||||
}
|
||||
NumberInterface factorial = params[0];
|
||||
NumberInterface multiplier = params[0];
|
||||
//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){
|
||||
factorial = factorial.multiply(multiplier);
|
||||
}
|
||||
return factorial;
|
||||
/*if(!storedList.containsKey(params[0].getClass())){
|
||||
storedList.put(params[0].getClass(), new ArrayList<NumberInterface>());
|
||||
storedList.get(params[0].getClass()).add(NaiveNumber.ONE.promoteTo(params[0].getClass()));
|
||||
storedList.get(params[0].getClass()).add(NaiveNumber.ONE.promoteTo(params[0].getClass()));
|
||||
}*/
|
||||
}
|
||||
}));
|
||||
|
||||
registerFunction("abs", new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return params[0].multiply((new NaiveNumber(params[0].signum())).promoteTo(params[0].getClass()));
|
||||
}
|
||||
});
|
||||
|
||||
registerFunction("exp", new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
boolean takeReciprocal = params[0].signum() == -1;
|
||||
params[0] = StandardPlugin.this.getFunction("abs").apply(params[0]);
|
||||
NumberInterface sum = sumSeries(params[0], StandardPlugin.this::getExpSeriesTerm, getNTermsExp(getMaxError(params[0]), params[0]));
|
||||
if(takeReciprocal){
|
||||
sum = NaiveNumber.ONE.promoteTo(sum.getClass()).divide(sum);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
});
|
||||
|
||||
registerFunction("ln", new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
NumberInterface param = params[0];
|
||||
int powersOf2 = 0;
|
||||
while(StandardPlugin.this.getFunction("abs").apply(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass()))).compareTo((new NaiveNumber(0.1)).promoteTo(param.getClass())) >= 0){
|
||||
if(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() == 1) {
|
||||
param = param.divide(new NaiveNumber(2).promoteTo(param.getClass()));
|
||||
powersOf2++;
|
||||
if(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != 1) {
|
||||
break;
|
||||
//No infinite loop for you.
|
||||
}
|
||||
}
|
||||
else {
|
||||
param = param.multiply(new NaiveNumber(2).promoteTo(param.getClass()));
|
||||
powersOf2--;
|
||||
if(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != 1) {
|
||||
break;
|
||||
//No infinite loop for you.
|
||||
}
|
||||
}
|
||||
}
|
||||
return getLog2(param).multiply((new NaiveNumber(powersOf2)).promoteTo(param.getClass())).add(getLogPartialSum(param));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the partial sum of the Taylor series for logx (around x=1).
|
||||
* Automatically determines the number of terms needed based on the precision of x.
|
||||
* @param x value at which the series is evaluated. 0 < x < 2. (x=2 is convergent but impractical.)
|
||||
* @return the partial sum.
|
||||
*/
|
||||
private NumberInterface getLogPartialSum(NumberInterface x){
|
||||
NumberInterface maxError = StandardPlugin.this.getMaxError(x);
|
||||
x = x.subtract(NaiveNumber.ONE.promoteTo(x.getClass())); //Terms used are for log(x+1).
|
||||
NumberInterface currentTerm = x, sum = x;
|
||||
int n = 1;
|
||||
while(StandardPlugin.this.getFunction("abs").apply(currentTerm).compareTo(maxError) > 0){
|
||||
n++;
|
||||
currentTerm = currentTerm.multiply(x).multiply((new NaiveNumber(n-1)).promoteTo(x.getClass())).divide((new NaiveNumber(n)).promoteTo(x.getClass())).negate();
|
||||
sum = sum.add(currentTerm);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns natural log of 2 to the required precision of the class of number.
|
||||
* @param number a number of the same type as the return type. (Used for precision.)
|
||||
* @return the value of log(2) with the appropriate precision.
|
||||
*/
|
||||
private NumberInterface getLog2(NumberInterface number){
|
||||
NumberInterface maxError = StandardPlugin.this.getMaxError(number);
|
||||
//NumberInterface errorBound = (new NaiveNumber(1)).promoteTo(number.getClass());
|
||||
//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.
|
||||
//a is also an error bound.
|
||||
NumberInterface a = (new NaiveNumber(1)).promoteTo(number.getClass()), b = a, c = a;
|
||||
NumberInterface sum = NaiveNumber.ZERO.promoteTo(number.getClass());
|
||||
int n = 0;
|
||||
while(a.compareTo(maxError) >= 1){
|
||||
n++;
|
||||
a = a.divide((new NaiveNumber(3)).promoteTo(number.getClass()));
|
||||
b = b.divide((new NaiveNumber(4)).promoteTo(number.getClass()));
|
||||
c = NaiveNumber.ONE.promoteTo(number.getClass()).divide((new NaiveNumber(n)).promoteTo(number.getClass()));
|
||||
sum = sum.add(a.add(b).multiply(c));
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
});
|
||||
|
||||
registerFunction("sqrt", new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return StandardPlugin.this.getOperator("^").getFunction().apply(params[0], ((new NaiveNumber(0.5)).promoteTo(params[0].getClass())));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the nth term of the Taylor series (centered at 0) of e^x
|
||||
* @param n the term required (n >= 0).
|
||||
* @param x the real number at which the series is evaluated.
|
||||
* @return the nth term of the series.
|
||||
*/
|
||||
private NumberInterface getExpSeriesTerm(int n, NumberInterface x){
|
||||
return x.intPow(n).divide(this.getOperator("!").getFunction().apply((new NaiveNumber(n)).promoteTo(x.getClass())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of terms needed to evaluate the exponential function (at x)
|
||||
* such that the error is at most maxError.
|
||||
* @param maxError Maximum error permissible (This should probably be positive.)
|
||||
* @param x where the function is evaluated.
|
||||
* @return the number of terms needed to evaluated the exponential function.
|
||||
*/
|
||||
private int getNTermsExp(NumberInterface maxError, NumberInterface x) {
|
||||
//We need n such that |x^(n+1)| <= (n+1)! * maxError
|
||||
//The variables LHS and RHS refer to the above inequality.
|
||||
int n = 0;
|
||||
x = this.getFunction("abs").apply(x);
|
||||
NumberInterface LHS = x, RHS = maxError;
|
||||
while (LHS.compareTo(RHS) > 0) {
|
||||
n++;
|
||||
LHS = LHS.multiply(x);
|
||||
RHS = RHS.multiply(new NaiveNumber(n + 1).promoteTo(RHS.getClass()));
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a partial sum of a series whose terms are given by the nthTermFunction, evaluated at x.
|
||||
* @param x the value at which the series is evaluated.
|
||||
* @param nthTermFunction the function that returns the nth term of the series, in the format term(x, n).
|
||||
* @param n the number of terms in the partial sum.
|
||||
* @return the value of the partial sum that has the same class as x.
|
||||
*/
|
||||
private NumberInterface sumSeries(NumberInterface x, BiFunction<Integer, NumberInterface, NumberInterface> nthTermFunction, int n){
|
||||
NumberInterface sum = NaiveNumber.ZERO.promoteTo(x.getClass());
|
||||
for(int i = 0; i <= n; i++){
|
||||
sum = sum.add(nthTermFunction.apply(i, x));
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum error based on the precision of the class of number.
|
||||
* @param number Any instance of the NumberInterface in question (should return an appropriate precision).
|
||||
* @return the maximum error.
|
||||
*/
|
||||
private NumberInterface getMaxError(NumberInterface number){
|
||||
return (new NaiveNumber(10)).promoteTo(number.getClass()).intPow(-number.getMaxPrecision());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user