index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/IGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; public interface IGUIPlugin { public IGUIPluginController getController(); public IGUIPluginModel getModel(); public IGUIPluginView getView(); public void setAlgorithmEventSource(AlgorithmEventSource graphEventSource); public void setGUIEventSource(GUIEventSource guiEventSource); }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/IGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventListener; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventListener; public interface IGUIPluginController extends AlgorithmEventListener, GUIEventListener { }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/IGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin; public interface IGUIPluginModel { }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/IGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin; import javafx.scene.Node; public interface IGUIPluginView { public Node getNode(); public void update(); public String getTitle(); }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; public class ControlBarGUIPlugin implements IGUIPlugin { private ControlBarGUIPluginController controller; private ControlBarGUIPluginView view; public ControlBarGUIPlugin() { view = new ControlBarGUIPluginView(); controller = new ControlBarGUIPluginController(view.getModel()); } @Override public IGUIPluginController getController() { return controller; } @Override public IGUIPluginModel getModel() { return view.getModel(); } @Override public IGUIPluginView getView() { return view; } @Override public void setAlgorithmEventSource(AlgorithmEventSource graphEventSource) { graphEventSource.registerListener(controller); } @Override public void setGUIEventSource(GUIEventSource guiEventSource) { guiEventSource.registerListener(controller); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; public class ControlBarGUIPluginController implements IGUIPluginController { private ControlBarGUIPluginModel model; public ControlBarGUIPluginController(ControlBarGUIPluginModel model) { this.model = model; } @Override public void handleAlgorithmEvent(AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { // nothing to do here as the control bar does not need to handle any algorithm event } @Override public void handleGUIEvent(GUIEvent guiEvent) { if (guiEvent instanceof PauseEvent || guiEvent instanceof ResetEvent) { model.setPaused(); } else if (guiEvent instanceof PlayEvent) { model.setUnpaused(); } } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; public class ControlBarGUIPluginModel implements IGUIPluginModel { private ControlBarGUIPluginView view; private boolean visualizationPaused; public ControlBarGUIPluginModel(ControlBarGUIPluginView view) { this.view = view; } public void setPaused() { visualizationPaused = true; view.update(); } public void setUnpaused() { visualizationPaused = false; view.update(); } public boolean isPaused() { return visualizationPaused; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Separator; import javafx.scene.control.ToolBar; public class ControlBarGUIPluginView implements IGUIPluginView { private ControlBarGUIPluginModel model; private Button startButton; public ControlBarGUIPluginView() { this.model = new ControlBarGUIPluginModel(this); } @Override public Node getNode() { ToolBar topButtonToolBar = new ToolBar(); this.startButton = new Button("Play"); this.startButton.setOnMouseClicked(event -> this.handleStartButtonClick()); topButtonToolBar.getItems().add(this.startButton); Button pauseButton = new Button("Pause"); pauseButton.setOnMouseClicked(event -> this.handlePauseButtonClick()); topButtonToolBar.getItems().add(pauseButton); Button resetButton = new Button("Reset"); resetButton.setOnMouseClicked(event -> this.handleResetButtonClick()); topButtonToolBar.getItems().add(resetButton); topButtonToolBar.getItems().add(new Separator()); return topButtonToolBar; } public void handleStartButtonClick() { DefaultGUIEventBus.getInstance().postEvent(new PlayEvent()); } public void handlePauseButtonClick() { DefaultGUIEventBus.getInstance().postEvent(new PauseEvent()); } public void handleResetButtonClick() { DefaultGUIEventBus.getInstance().postEvent(new ResetEvent()); } @Override public void update() { if (this.model.isPaused()) { this.startButton.setText("Resume"); this.startButton.setDisable(false); } else { this.startButton.setText("Play"); this.startButton.setDisable(true); } } @Override public String getTitle() { return "Control Bar"; } public ControlBarGUIPluginModel getModel() { return this.model; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphMouseListener.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import org.graphstream.graph.Node; import org.graphstream.ui.view.ViewerListener; import org.graphstream.ui.view.ViewerPipe; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; public class GraphMouseListener implements ViewerListener, Runnable { private boolean active; private GraphViewPluginModel viewModel; private ViewerPipe viewerPipe; public GraphMouseListener(GraphViewPluginModel viewModel, ViewerPipe viewerPipe) { this.viewModel = viewModel; this.viewerPipe = viewerPipe; this.active = true; } @Override public void buttonPushed(String id) { Node viewGraphNode = viewModel.getGraph().getNode(id); Object searchGraphNode = viewModel.getSearchGraphNodeMappedToViewGraphNode(viewGraphNode); DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(viewGraphNode, searchGraphNode)); } @Override public void buttonReleased(String id) { // nothing to do here } @Override public void mouseLeft(String id) { // nothing to do here } @Override public void mouseOver(String id) { // nothing to do here } @Override public void viewClosed(String id) { active = false; } @Override public void run() { while (active) { viewerPipe.pump(); } } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; public class GraphViewPlugin implements IGUIPlugin { private GraphViewPluginController controller; private GraphViewPluginView view; public GraphViewPlugin() { this.view = new GraphViewPluginView(); this.controller = new GraphViewPluginController(view.getModel()); } @Override public IGUIPluginController getController() { return controller; } @Override public IGUIPluginModel getModel() { return view.getModel(); } @Override public IGUIPluginView getView() { return view; } @Override public void setAlgorithmEventSource(AlgorithmEventSource graphEventSource) { graphEventSource.registerListener(controller); } @Override public void setGUIEventSource(GUIEventSource guiEventSource) { guiEventSource.registerListener(controller); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import java.util.Arrays; import java.util.Collections; import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeRemovedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeTypeSwitchEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; public class GraphViewPluginController implements IGUIPluginController { private GraphViewPluginModel model; public GraphViewPluginController(GraphViewPluginModel model) { this.model = model; } @Override public void handleAlgorithmEvent(AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { try { if (GraphInitializedEvent.class.isInstance(algorithmEvent)) { GraphInitializedEvent<?> graphInitializedEvent = (GraphInitializedEvent<?>) algorithmEvent; handleGraphInitializedEvent(graphInitializedEvent); } else if (NodeAddedEvent.class.isInstance(algorithmEvent)) { NodeAddedEvent<?> nodeAddedEvent = (NodeAddedEvent<?>) algorithmEvent; handleNodeAddedEvent(nodeAddedEvent); } else if (NodeRemovedEvent.class.isInstance(algorithmEvent)) { NodeRemovedEvent<?> nodeRemovedEvent = (NodeRemovedEvent<?>) algorithmEvent; handleNodeRemovedEvent(nodeRemovedEvent); } else if (NodeTypeSwitchEvent.class.isInstance(algorithmEvent)) { NodeTypeSwitchEvent<?> nodeTypeSwitchEvent = (NodeTypeSwitchEvent<?>) algorithmEvent; handleNodeTypeSwitchEvent(nodeTypeSwitchEvent); } } catch (ViewGraphManipulationException exception) { throw new HandleAlgorithmEventException("Encountered a problem while handling graph event " + algorithmEvent + " .", exception); } } private void handleGraphInitializedEvent(GraphInitializedEvent<?> graphInitializedEvent) throws ViewGraphManipulationException { model.addNode(graphInitializedEvent.getRoot(), Collections.emptyList(), "root"); } private void handleNodeAddedEvent(NodeAddedEvent<?> nodeReachedEvent) throws ViewGraphManipulationException { model.addNode(nodeReachedEvent.getNode(), Arrays.asList(nodeReachedEvent.getParent()), nodeReachedEvent.getType()); } private void handleNodeTypeSwitchEvent(NodeTypeSwitchEvent<?> nodeTypeSwitchEvent) throws ViewGraphManipulationException { model.switchNodeType(nodeTypeSwitchEvent.getNode(), nodeTypeSwitchEvent.getType()); } private void handleNodeRemovedEvent(NodeRemovedEvent<?> nodeRemovedEvent) throws ViewGraphManipulationException { model.removeNode(nodeRemovedEvent.getNode()); } @Override public void handleGUIEvent(GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent) { model.reset(); } else if (guiEvent instanceof GoToTimeStepEvent) { model.reset(); } } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.graphstream.graph.Edge; import org.graphstream.graph.Graph; import org.graphstream.graph.IdAlreadyInUseException; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.SingleGraph; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.FileUtil; import ai.libs.jaicore.basic.ResourceUtil; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; public class GraphViewPluginModel implements IGUIPluginModel { private static final Logger LOGGER = LoggerFactory.getLogger(GraphViewPluginModel.class); private static final String DEF_RES_STYLESHEET_PATH = "searchgraph.css"; private static final String STYLESHEET_PATH = "conf/searchgraph.css"; private static final File DEF_STYLESHEET = FileUtil.getExistingFileWithHighestPriority(DEF_RES_STYLESHEET_PATH, STYLESHEET_PATH); private int nodeIdCounter; private GraphViewPluginView view; private Graph graph; private ConcurrentMap<Object, Node> searchGraphNodesToViewGraphNodesMap; private ConcurrentMap<Node, Object> viewGraphNodesToSearchGraphNodesMap; private ConcurrentMap<Node, Set<Edge>> nodeToConnectedEdgesMap; public GraphViewPluginModel(final GraphViewPluginView view) { this(view, DEF_STYLESHEET); } public GraphViewPluginModel(final GraphViewPluginView view, final File searchGraphCSSPath) { this.view = view; this.searchGraphNodesToViewGraphNodesMap = new ConcurrentHashMap<>(); this.viewGraphNodesToSearchGraphNodesMap = new ConcurrentHashMap<>(); this.nodeToConnectedEdgesMap = new ConcurrentHashMap<>(); this.nodeIdCounter = 0; this.initializeGraph(searchGraphCSSPath); } private void initializeGraph(final File searchGraphCSSPath) { this.graph = new SingleGraph("Search Graph"); try { this.graph.setAttribute("ui.stylesheet", ResourceUtil.readResourceFileToString(searchGraphCSSPath.getPath())); } catch (IOException e) { LOGGER.warn("Could not load css stylesheet for graph view plugin. Continue without stylesheet", e); } } public void addNode(final Object node, final List<Object> predecessorNodes, final String typeOfNode) throws ViewGraphManipulationException { try { Node viewNode = this.graph.addNode(String.valueOf(this.nodeIdCounter)); this.registerNodeMapping(node, viewNode); for (Object predecessorNode : predecessorNodes) { this.createEdge(node, predecessorNode); } this.switchNodeType(viewNode, typeOfNode); this.view.update(); this.nodeIdCounter++; } catch (IdAlreadyInUseException exception) { throw new ViewGraphManipulationException("Cannot add node " + node + " as the id " + this.nodeIdCounter + " is already in use."); } } private void createEdge(final Object node, final Object predecessorNode) throws ViewGraphManipulationException { Node viewNode = this.searchGraphNodesToViewGraphNodesMap.get(node); Node viewPredecessorNode = this.searchGraphNodesToViewGraphNodesMap.get(predecessorNode); if (viewPredecessorNode == null) { throw new ViewGraphManipulationException("Cannot add edge from node " + predecessorNode + " to node " + viewNode + " due to missing view node of predecessor."); } String edgeId = viewPredecessorNode.getId() + "-" + viewNode.getId(); Edge edge = this.graph.addEdge(edgeId, viewPredecessorNode, viewNode, true); this.registerEdgeConnectedToNodesInMap(edge); } private void registerNodeMapping(final Object node, final Node viewNode) { this.searchGraphNodesToViewGraphNodesMap.put(node, viewNode); this.viewGraphNodesToSearchGraphNodesMap.put(viewNode, node); } private void registerEdgeConnectedToNodesInMap(final Edge edge) { if (!this.nodeToConnectedEdgesMap.containsKey(edge.getNode0())) { this.nodeToConnectedEdgesMap.put(edge.getNode0(), new HashSet<>()); } this.nodeToConnectedEdgesMap.get(edge.getNode0()).add(edge); if (!this.nodeToConnectedEdgesMap.containsKey(edge.getNode1())) { this.nodeToConnectedEdgesMap.put(edge.getNode1(), new HashSet<>()); } this.nodeToConnectedEdgesMap.get(edge.getNode1()).add(edge); } public void switchNodeType(final Object node, final String newType) throws ViewGraphManipulationException { if (node == null) { throw new ViewGraphManipulationException("Cannot switch type of null node."); } Node viewNode = this.searchGraphNodesToViewGraphNodesMap.get(node); if (viewNode == null) { throw new ViewGraphManipulationException("Cannot switch type of node " + node + " without corresponding view node."); } this.switchNodeType(viewNode, newType); this.view.update(); } private void switchNodeType(final Node node, final String newType) { if (!this.isLabeledAsRootNode(node)) { node.setAttribute("ui.class", newType); } } private boolean isLabeledAsRootNode(final Node node) { return node.getAttribute("ui.class") != null && node.getAttribute("ui.class").equals("root"); } public void removeNode(final Object node) throws ViewGraphManipulationException { if (node == null) { throw new ViewGraphManipulationException("Cannot remove null node."); } Node viewNode = this.searchGraphNodesToViewGraphNodesMap.remove(node); if (viewNode == null) { throw new ViewGraphManipulationException("Cannot remove node " + node + " without corresponding view node."); } this.viewGraphNodesToSearchGraphNodesMap.remove(viewNode); Set<Edge> connectedEdges = this.nodeToConnectedEdgesMap.remove(viewNode); this.graph.removeNode(viewNode); for (Edge edge : connectedEdges) { Node otherNode = edge.getNode0().equals(viewNode) ? edge.getNode1() : edge.getNode0(); Set<Edge> connectedEdgesOfOtherNode = this.nodeToConnectedEdgesMap.get(otherNode); connectedEdgesOfOtherNode.remove(edge); this.graph.removeEdge(edge); } } public void reset() { this.graph.clear(); this.graph.setAttribute("ui.stylesheet", "url('conf/searchgraph.css')"); this.searchGraphNodesToViewGraphNodesMap.clear(); this.viewGraphNodesToSearchGraphNodesMap.clear(); this.nodeToConnectedEdgesMap.clear(); this.view.update(); } public Graph getGraph() { return this.graph; } public Object getSearchGraphNodeMappedToViewGraphNode(final Object searchGraphNode) { return this.viewGraphNodesToSearchGraphNodesMap.get(searchGraphNode); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import org.graphstream.ui.fx_viewer.FxViewPanel; import org.graphstream.ui.fx_viewer.FxViewer; import org.graphstream.ui.view.Viewer.ThreadingModel; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; import org.graphstream.ui.view.ViewerPipe; import javafx.scene.Node; import javafx.scene.layout.BorderPane; public class GraphViewPluginView implements IGUIPluginView { private GraphViewPluginModel model; private FxViewer fxViewer; private BorderPane graphParentLayout; public GraphViewPluginView() { this.model = new GraphViewPluginModel(this); this.fxViewer = new FxViewer(model.getGraph(), ThreadingModel.GRAPH_IN_ANOTHER_THREAD); this.fxViewer.enableAutoLayout(); this.graphParentLayout = new BorderPane(); initializeGraphMouseListener(); } private void initializeGraphMouseListener() { ViewerPipe viewerPipe = fxViewer.newViewerPipe(); GraphMouseListener graphMouseListener = new GraphMouseListener(model, viewerPipe); viewerPipe.addViewerListener(graphMouseListener); viewerPipe.addSink(model.getGraph()); Thread listenerThread = new Thread(graphMouseListener); listenerThread.start(); } @Override public Node getNode() { FxViewPanel fxViewPanel = (FxViewPanel) fxViewer.addDefaultView(false); graphParentLayout.setCenter(fxViewPanel); return graphParentLayout; } @Override public void update() { // No need for code here as the update happens automatically via the graphstream graph } @Override public String getTitle() { return "Search Graph Viewer"; } public GraphViewPluginModel getModel() { return model; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/graphview/NodeClickedEvent.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import org.graphstream.graph.Node; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; public class NodeClickedEvent implements GUIEvent { private Node viewerNode; private Object searchGraphNode; public NodeClickedEvent(Node viewerNode, Object searchGraphNode) { this.viewerNode = viewerNode; this.searchGraphNode = searchGraphNode; } public Node getViewerNode() { return viewerNode; } public Object getSearchGraphNode() { return searchGraphNode; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; public class NodeInfoGUIPlugin<N> implements IGUIPlugin { private NodeInfoGUIPluginController<N> controller; private NodeInfoGUIPluginView<N> view; public NodeInfoGUIPlugin(NodeInfoGenerator<N> nodeInfoGenerator, String viewTitle) { view = new NodeInfoGUIPluginView<>(nodeInfoGenerator, viewTitle); controller = new NodeInfoGUIPluginController<>(view.getModel()); } public NodeInfoGUIPlugin(NodeInfoGenerator<N> nodeInfoGenerator) { this(nodeInfoGenerator, "Node Info View"); } @Override public IGUIPluginController getController() { return controller; } @Override public IGUIPluginModel getModel() { return view.getModel(); } @Override public IGUIPluginView getView() { return view; } @Override public void setAlgorithmEventSource(AlgorithmEventSource graphEventSource) { graphEventSource.registerListener(controller); } @Override public void setGUIEventSource(GUIEventSource guiEventSource) { guiEventSource.registerListener(controller); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; public class NodeInfoGUIPluginController<N> implements IGUIPluginController { private NodeInfoGUIPluginModel<N> model; public NodeInfoGUIPluginController(final NodeInfoGUIPluginModel<N> model) { this.model = model; } @Override public void handleAlgorithmEvent(final AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { /* no updates required */ } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (NodeClickedEvent.class.isInstance(guiEvent)) { NodeClickedEvent nodeClickedEvent = (NodeClickedEvent) guiEvent; Object searchGraphNodeCorrespondingToClickedViewGraphNode = nodeClickedEvent.getSearchGraphNode(); this.model.setCurrentlySelectedNode((N) searchGraphNodeCorrespondingToClickedViewGraphNode); } } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; /** * * @author hetzer * * @param <N> * The node type class. */ public class NodeInfoGUIPluginModel<N> implements IGUIPluginModel { private NodeInfoGUIPluginView<N> view; private N currentlySelectedNode; public NodeInfoGUIPluginModel(NodeInfoGUIPluginView<N> view) { this.view = view; } public void setCurrentlySelectedNode(N currentlySelectedNode) { this.currentlySelectedNode = currentlySelectedNode; view.update(); } public N getCurrentlySelectedNode() { return currentlySelectedNode; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; import javafx.application.Platform; import javafx.scene.Node; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; /** * * @author hetzer * * @param <N> * The node class */ public class NodeInfoGUIPluginView<N> implements IGUIPluginView { private NodeInfoGUIPluginModel<N> model; private NodeInfoGenerator<N> nodeInfoGenerator; private String title; private WebEngine webViewEngine; public NodeInfoGUIPluginView(NodeInfoGenerator<N> nodeInfoGenerator, String title) { this.model = new NodeInfoGUIPluginModel<>(this); this.nodeInfoGenerator = nodeInfoGenerator; this.title = title; } public NodeInfoGUIPluginView(NodeInfoGenerator<N> nodeInfoGenerator) { this(nodeInfoGenerator, "Node Info View"); } @Override public Node getNode() { WebView htmlView = new WebView(); webViewEngine = htmlView.getEngine(); webViewEngine.loadContent("<i>No node selected</i>"); return htmlView; } @Override public void update() { N currentlySelectedNode = model.getCurrentlySelectedNode(); String nodeInfoOfCurrentlySelectedNode = nodeInfoGenerator.generateInfoForNode(currentlySelectedNode); Platform.runLater(() -> { webViewEngine.loadContent(nodeInfoOfCurrentlySelectedNode); }); } public NodeInfoGUIPluginModel<N> getModel() { return model; } @Override public String getTitle() { return title; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGenerator.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; /** * * @author hetzer * * @param <N> * The node class for which information is provided */ public interface NodeInfoGenerator<N> { public String generateInfoForNode(N node); }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; public class SolutionPerformanceTimelinePlugin extends ASimpleMVCPlugin<SolutionPerformanceTimelinePluginModel, SolutionPerformanceTimelinePluginView, SolutionPerformanceTimelinePluginController> { public SolutionPerformanceTimelinePlugin() { super(); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent; import ai.libs.jaicore.basic.algorithm.events.ScoredSolutionCandidateFoundEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; public class SolutionPerformanceTimelinePluginController extends ASimpleMVCPluginController<SolutionPerformanceTimelinePluginModel, SolutionPerformanceTimelinePluginView> { private Logger logger = LoggerFactory.getLogger(SolutionPerformanceTimelinePluginController.class); public SolutionPerformanceTimelinePluginController(final SolutionPerformanceTimelinePluginModel model, final SolutionPerformanceTimelinePluginView view) { super(model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); } } @SuppressWarnings("unchecked") @Override public void handleAlgorithmEventInternally(final AlgorithmEvent algorithmEvent) { if (algorithmEvent instanceof ScoredSolutionCandidateFoundEvent) { this.logger.debug("Received solution event {}", algorithmEvent); ScoredSolutionCandidateFoundEvent<?,?> event = (ScoredSolutionCandidateFoundEvent<?,?>)algorithmEvent; if (!(event.getScore() instanceof Number)) { this.logger.warn("Received SolutionCandidateFoundEvent, but the score is of type {}, which is not a number.", event.getScore().getClass().getName()); return; } this.logger.debug("Adding solution to model and updating view."); this.getModel().addEntry((ScoredSolutionCandidateFoundEvent<?, ? extends Number>)event); } else { this.logger.trace("Received and ignored irrelevant event {}", algorithmEvent); } } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.util.Pair; import ai.libs.jaicore.basic.algorithm.events.ScoredSolutionCandidateFoundEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; public class SolutionPerformanceTimelinePluginModel extends ASimpleMVCPluginModel<SolutionPerformanceTimelinePluginView, SolutionPerformanceTimelinePluginController> { private final List<Pair<Integer, Double>> timedPerformances = new ArrayList<>(); private long timestampOfFirstEvent = -1; public final void addEntry(ScoredSolutionCandidateFoundEvent<?, ? extends Number> solutionEvent) { int offset = 0; if (timestampOfFirstEvent == -1) { timestampOfFirstEvent = solutionEvent.getTimestamp(); } else { offset = (int) (solutionEvent.getTimestamp() - timestampOfFirstEvent); } timedPerformances.add(new Pair<>(offset, (Double) solutionEvent.getScore())); getView().update(); } public long getTimestampOfFirstEvent() { return timestampOfFirstEvent; } public List<Pair<Integer, Double>> getTimedPerformances() { return timedPerformances; } public void clear() { timedPerformances.clear(); timestampOfFirstEvent = -1; getView().clear(); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.application.Platform; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart.Data; import javafx.scene.chart.XYChart.Series; /** * * @author fmohr * */ public class SolutionPerformanceTimelinePluginView extends ASimpleMVCPluginView<SolutionPerformanceTimelinePluginModel, SolutionPerformanceTimelinePluginController, LineChart<Number, Number>> { private Logger logger = LoggerFactory.getLogger(SolutionPerformanceTimelinePluginView.class); private final Series<Number, Number> performanceSeries; private int nextIndexToDisplay = 0; public SolutionPerformanceTimelinePluginView(SolutionPerformanceTimelinePluginModel model) { super(model, new LineChart<>(new NumberAxis(), new NumberAxis())); // defining the axes getNode().getXAxis().setLabel("elapsed time (s)"); // creating the chart getNode().setTitle(getTitle()); // defining a series performanceSeries = new Series<>(); getNode().getData().add(performanceSeries); } @Override public void update() { /* compute data to add */ List<Pair<Integer, Double>> events = getModel().getTimedPerformances(); List<Data<Number, Number>> values = new ArrayList<>(); for (; nextIndexToDisplay < events.size(); nextIndexToDisplay++) { Pair<Integer, Double> entry = events.get(nextIndexToDisplay); values.add(new Data<>(entry.getKey() / 1000, entry.getValue())); } logger.info("Adding {} values to chart.", values.size()); Platform.runLater(() -> { performanceSeries.getData().addAll(values); }); } @Override public String getTitle() { return "Solution Performance Timeline"; } public void clear() { nextIndexToDisplay = 0; performanceSeries.getData().clear(); } public int getNextIndexToDisplay() { return nextIndexToDisplay; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; public class SpeedSliderGUIPlugin implements IGUIPlugin { private SpeedSliderGUIPluginController controller; private SpeedSliderGUIPluginView view; public SpeedSliderGUIPlugin() { view = new SpeedSliderGUIPluginView(); controller = new SpeedSliderGUIPluginController(view.getModel()); } @Override public IGUIPluginController getController() { return controller; } @Override public IGUIPluginModel getModel() { return view.getModel(); } @Override public IGUIPluginView getView() { return view; } @Override public void setAlgorithmEventSource(AlgorithmEventSource graphEventSource) { graphEventSource.registerListener(controller); } @Override public void setGUIEventSource(GUIEventSource guiEventSource) { guiEventSource.registerListener(controller); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; public class SpeedSliderGUIPluginController implements IGUIPluginController { private SpeedSliderGUIPluginModel model; public SpeedSliderGUIPluginController(SpeedSliderGUIPluginModel model) { this.model = model; } @Override public void handleAlgorithmEvent(AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { // no need to handle any algorithm events } @Override public void handleGUIEvent(GUIEvent guiEvent) { if (guiEvent instanceof ChangeSpeedEvent) { ChangeSpeedEvent changeSpeedEvent = (ChangeSpeedEvent) guiEvent; model.setCurrentSpeedPercentage(changeSpeedEvent.getNewSpeedPercentage()); } } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; public class SpeedSliderGUIPluginModel implements IGUIPluginModel { private SpeedSliderGUIPluginView view; private int currentSpeedPercentage; public SpeedSliderGUIPluginModel(SpeedSliderGUIPluginView view) { this.view = view; currentSpeedPercentage = 85; } public int getCurrentSpeedPercentage() { return currentSpeedPercentage; } public void setCurrentSpeedPercentage(int currentSpeedPercentage) { this.currentSpeedPercentage = currentSpeedPercentage; view.update(); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.VBox; public class SpeedSliderGUIPluginView implements IGUIPluginView { private SpeedSliderGUIPluginModel model; private Slider visualizationSpeedSlider; public SpeedSliderGUIPluginView() { this.model = new SpeedSliderGUIPluginModel(this); } @Override public Node getNode() { VBox visualizationSpeedSliderLayout = new VBox(); visualizationSpeedSliderLayout.setAlignment(Pos.CENTER); this.visualizationSpeedSlider = new Slider(1, 100, this.model.getCurrentSpeedPercentage()); this.visualizationSpeedSlider.setShowTickLabels(true); this.visualizationSpeedSlider.setShowTickMarks(true); this.visualizationSpeedSlider.setMajorTickUnit(5); this.visualizationSpeedSlider.setMinorTickCount(1); this.visualizationSpeedSlider.setOnMouseReleased(event -> this.handleInputEvent()); this.visualizationSpeedSlider.setOnKeyPressed(event -> this.handleInputEvent()); this.visualizationSpeedSlider.setOnKeyReleased(event -> this.handleInputEvent()); visualizationSpeedSliderLayout.getChildren().add(this.visualizationSpeedSlider); Label visualizationSpeedSliderLabel = new Label("Visualization Speed (%)"); visualizationSpeedSliderLayout.getChildren().add(visualizationSpeedSliderLabel); return visualizationSpeedSliderLayout; } private void handleInputEvent() { ChangeSpeedEvent changeSpeedEvent = new ChangeSpeedEvent((int) this.visualizationSpeedSlider.getValue()); DefaultGUIEventBus.getInstance().postEvent(changeSpeedEvent); } @Override public void update() { this.visualizationSpeedSlider.setValue(this.model.getCurrentSpeedPercentage()); } @Override public String getTitle() { return "Speed Slider"; } public SpeedSliderGUIPluginModel getModel() { return this.model; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; public class TimeSliderGUIPlugin implements IGUIPlugin { private TimeSliderGUIPluginController controller; private TimeSliderGUIPluginView view; public TimeSliderGUIPlugin() { view = new TimeSliderGUIPluginView(); controller = new TimeSliderGUIPluginController(view.getModel()); } @Override public IGUIPluginController getController() { return controller; } @Override public IGUIPluginModel getModel() { return view.getModel(); } @Override public IGUIPluginView getView() { return view; } @Override public void setAlgorithmEventSource(AlgorithmEventSource graphEventSource) { graphEventSource.registerListener(controller); } @Override public void setGUIEventSource(GUIEventSource guiEventSource) { guiEventSource.registerListener(controller); } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PauseEvent; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PlayEvent; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; public class TimeSliderGUIPluginController implements IGUIPluginController { private TimeSliderGUIPluginModel model; private int amountOfEventsToIgnore; public TimeSliderGUIPluginController(TimeSliderGUIPluginModel model) { this.model = model; this.amountOfEventsToIgnore = 0; } @Override public void handleAlgorithmEvent(AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { if (amountOfEventsToIgnore <= 0) { model.increaseCurrentTimeStep(); model.increaseMaximumTimeStep(); } else { amountOfEventsToIgnore--; } } @Override public void handleGUIEvent(GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent) { model.reset(); } else if (guiEvent instanceof PauseEvent) { model.pause(); } else if (guiEvent instanceof PlayEvent) { model.unpause(); } else if (guiEvent instanceof GoToTimeStepEvent) { int newTimeStep = ((GoToTimeStepEvent) guiEvent).getNewTimeStep(); amountOfEventsToIgnore = newTimeStep; model.setCurrentTimeStep(newTimeStep); } } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginModel; public class TimeSliderGUIPluginModel implements IGUIPluginModel { private TimeSliderGUIPluginView view; private int currentTimeStep; private int maximumTimeStep; private boolean paused; public TimeSliderGUIPluginModel(TimeSliderGUIPluginView view) { this.view = view; currentTimeStep = 0; maximumTimeStep = 0; paused = true; } public void increaseMaximumTimeStep() { maximumTimeStep++; view.update(); } public void reset() { currentTimeStep = 0; maximumTimeStep = 0; view.update(); } public int getCurrentTimeStep() { return currentTimeStep; } public int getMaximumTimeStep() { return maximumTimeStep; } public void pause() { paused = true; view.update(); } public void unpause() { paused = false; view.update(); } public void increaseCurrentTimeStep() { currentTimeStep++; view.update(); } public void setCurrentTimeStep(int currentTimeStep) { this.currentTimeStep = currentTimeStep; view.update(); } public boolean isPaused() { return paused; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPluginView; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.VBox; public class TimeSliderGUIPluginView implements IGUIPluginView { private TimeSliderGUIPluginModel model; private Slider timestepSlider; public TimeSliderGUIPluginView() { this.model = new TimeSliderGUIPluginModel(this); } @Override public Node getNode() { VBox timestepSliderLayout = new VBox(); timestepSliderLayout.setAlignment(Pos.CENTER); timestepSlider = new Slider(0, 1, 0); timestepSlider.setShowTickLabels(true); timestepSlider.setShowTickMarks(true); timestepSlider.setMajorTickUnit(25); timestepSlider.setMinorTickCount(5); timestepSlider.setOnMouseReleased(event -> { handleInputEvent(); }); timestepSlider.setOnKeyPressed(event -> { handleInputEvent(); }); timestepSlider.setOnKeyReleased(event -> { handleInputEvent(); }); timestepSliderLayout.getChildren().add(timestepSlider); Label timestepSliderLabel = new Label("Timestep"); timestepSliderLayout.getChildren().add(timestepSliderLabel); return timestepSliderLayout; } public synchronized void handleInputEvent() { DefaultGUIEventBus.getInstance().postEvent(new GoToTimeStepEvent((int) timestepSlider.getValue())); } @Override public void update() { timestepSlider.setValue(model.getCurrentTimeStep()); timestepSlider.setMax(model.getMaximumTimeStep()); if (model.isPaused() && timestepSlider.isDisabled()) { timestepSlider.setDisable(false); } else if (!model.isPaused() && !timestepSlider.isDisabled()) { timestepSlider.setDisable(true); } } @Override public String getTitle() { return "Time Slider"; } public TimeSliderGUIPluginModel getModel() { return model; } }
0
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/window/AlgorithmVisualizationWindow.java
package ai.libs.jaicore.graphvisualizer.window; import java.util.ArrayList; import java.util.List; import ai.libs.jaicore.basic.algorithm.IAlgorithm; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistory; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistoryEntryDeliverer; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistoryRecorder; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ControlBarGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.speedslider.SpeedSliderGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.TimeSliderGUIPlugin; import javafx.scene.Scene; import javafx.scene.control.SplitPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class AlgorithmVisualizationWindow implements Runnable { private AlgorithmEventSource algorithmEventSource; private AlgorithmEventHistoryEntryDeliverer algorithmEventHistoryPuller; private List<IGUIPlugin> visualizationPlugins; private IGUIPlugin mainPlugin; private TimeSliderGUIPlugin timeSliderGUIPlugin; private ControlBarGUIPlugin controlBarGUIPlugin; private SpeedSliderGUIPlugin speedSliderGUIPlugin; private String title = "MLPlan Graph Search Visualization"; private Stage stage; private BorderPane rootLayout; private BorderPane topLayout; private TabPane pluginTabPane; public AlgorithmVisualizationWindow(AlgorithmEventHistory algorithmEventHistory, IGUIPlugin mainPlugin, IGUIPlugin... visualizationPlugins) { this.mainPlugin = mainPlugin; algorithmEventHistoryPuller = new AlgorithmEventHistoryEntryDeliverer(algorithmEventHistory); this.algorithmEventSource = algorithmEventHistoryPuller; initializePlugins(visualizationPlugins); // it is important to register the history puller as a last listener! DefaultGUIEventBus.getInstance().registerListener(algorithmEventHistoryPuller); } public AlgorithmVisualizationWindow(IAlgorithm<?, ?> algorithm, IGUIPlugin mainPlugin, IGUIPlugin... visualizationPlugins) { this.mainPlugin = mainPlugin; AlgorithmEventHistoryRecorder historyRecorder = new AlgorithmEventHistoryRecorder(); algorithm.registerListener(historyRecorder); algorithmEventHistoryPuller = new AlgorithmEventHistoryEntryDeliverer(historyRecorder.getHistory()); this.algorithmEventSource = algorithmEventHistoryPuller; initializePlugins(visualizationPlugins); // it is important to register the history puller as a last listener! DefaultGUIEventBus.getInstance().registerListener(algorithmEventHistoryPuller); } private void initializePlugins(IGUIPlugin... visualizationPlugins) { mainPlugin.setAlgorithmEventSource(algorithmEventSource); mainPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); timeSliderGUIPlugin = new TimeSliderGUIPlugin(); timeSliderGUIPlugin.setAlgorithmEventSource(algorithmEventSource); timeSliderGUIPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); controlBarGUIPlugin = new ControlBarGUIPlugin(); controlBarGUIPlugin.setAlgorithmEventSource(algorithmEventSource); controlBarGUIPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); speedSliderGUIPlugin = new SpeedSliderGUIPlugin(); speedSliderGUIPlugin.setAlgorithmEventSource(algorithmEventSource); speedSliderGUIPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); this.visualizationPlugins = new ArrayList<>(visualizationPlugins.length); for (IGUIPlugin graphVisualizationPlugin : visualizationPlugins) { this.visualizationPlugins.add(graphVisualizationPlugin); graphVisualizationPlugin.setAlgorithmEventSource(algorithmEventSource); graphVisualizationPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); } } @Override public void run() { rootLayout = new BorderPane(); initializeTopLayout(); initializeCenterLayout(); initializeBottomLayout(); initializePluginTabs(); Scene scene = new Scene(rootLayout, 800, 300); stage = new Stage(); stage.setScene(scene); stage.setTitle(title); stage.setMaximized(true); stage.show(); algorithmEventHistoryPuller.start(); } private void initializeTopLayout() { topLayout = new BorderPane(); initializeTopButtonToolBar(); initializeVisualizationSpeedSlider(); rootLayout.setTop(topLayout); } private void initializeTopButtonToolBar() { topLayout.setTop(controlBarGUIPlugin.getView().getNode()); } private void initializeVisualizationSpeedSlider() { topLayout.setBottom(speedSliderGUIPlugin.getView().getNode()); } private void initializeCenterLayout() { SplitPane centerSplitLayout = new SplitPane(); centerSplitLayout.setDividerPosition(0, 0.25); pluginTabPane = new TabPane(); centerSplitLayout.getItems().add(this.pluginTabPane); centerSplitLayout.getItems().add(mainPlugin.getView().getNode()); rootLayout.setCenter(centerSplitLayout); } private void initializeBottomLayout() { rootLayout.setBottom(timeSliderGUIPlugin.getView().getNode()); } private void initializePluginTabs() { for (IGUIPlugin plugin : visualizationPlugins) { Tab pluginTab = new Tab(plugin.getView().getTitle(), plugin.getView().getNode()); pluginTabPane.getTabs().add(pluginTab); } } public void setTitle(String title) { this.title = title; stage.setTitle(title); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms/resolution/ResolutionPair.java
package ai.libs.jaicore.logic.fol.algorithms.resolution; import ai.libs.jaicore.logic.fol.structure.Clause; import ai.libs.jaicore.logic.fol.structure.Literal; public class ResolutionPair { private Clause c1; private Clause c2; private Literal l1; private Literal l2; public ResolutionPair(final Clause c1, final Clause c2, final Literal l1, final Literal l2) { super(); this.c1 = c1; this.c2 = c2; this.l1 = l1; this.l2 = l2; } public Clause getC1() { return this.c1; } public Clause getC2() { return this.c2; } public Literal getL1() { return this.l1; } public Literal getL2() { return this.l2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.c1 == null) ? 0 : this.c1.hashCode()); result = prime * result + ((this.c2 == null) ? 0 : this.c2.hashCode()); result = prime * result + ((this.l1 == null) ? 0 : this.l1.hashCode()); result = prime * result + ((this.l2 == null) ? 0 : this.l2.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } ResolutionPair other = (ResolutionPair) obj; if (this.c1 == null) { if (other.c1 != null) { return false; } } else if (!this.c1.equals(other.c1)) { return false; } if (this.c2 == null) { if (other.c2 != null) { return false; } } else if (!this.c2.equals(other.c2)) { return false; } if (this.l1 == null) { if (other.l1 != null) { return false; } } else if (!this.l1.equals(other.l1)) { return false; } if (this.l2 == null) { if (other.l2 != null) { return false; } } else if (!this.l2.equals(other.l2)) { return false; } return true; } @Override public String toString() { return "PL1ResolutionPair [c1=" + this.c1 + ", c2=" + this.c2 + ", l1=" + this.l1 + ", l2=" + this.l2 + "]"; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms/resolution/ResolutionStep.java
package ai.libs.jaicore.logic.fol.algorithms.resolution; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.Clause; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.VariableParam; public class ResolutionStep { private ResolutionPair pair; private Clause r; private Map<VariableParam, LiteralParam> unificator; public ResolutionStep(ResolutionPair pair, Clause r, Map<VariableParam, LiteralParam> unificator) { super(); this.pair = pair; this.r = r; this.unificator = unificator; } public ResolutionPair getPair() { return pair; } public Clause getR() { return r; } public Map<VariableParam, LiteralParam> getUnificator() { return unificator; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms/resolution/ResolutionTree.java
package ai.libs.jaicore.logic.fol.algorithms.resolution; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import ai.libs.jaicore.logic.fol.structure.Clause; public class ResolutionTree { private Set<Clause> baseClauses; private Set<ResolutionPair> resolvedPairs = new HashSet<>(); private Map<Clause, ResolutionStep> resolventsWithTheirSteps = new HashMap<>(); public ResolutionTree(final Set<Clause> baseClauses) { super(); this.baseClauses = baseClauses; } public void addResolutionStep(final ResolutionStep step) { this.resolventsWithTheirSteps.put(step.getR(), step); this.resolvedPairs.add(step.getPair()); } public Set<Clause> getBaseClauses() { return this.baseClauses; } public Map<Clause, ResolutionStep> getResolventsWithTheirSteps() { return this.resolventsWithTheirSteps; } public boolean isClausePairAdmissible(final ResolutionPair pair) { if (this.resolvedPairs.contains(pair)) { return false; } Clause c1 = pair.getC1(); Clause c2 = pair.getC2(); if (this.baseClauses.contains(c1) && this.baseClauses.contains(c2)) { return false; } Set<Clause> parentsOfC1 = this.getAllClausesUsedToObtainResolvent(c1); if (parentsOfC1.contains(c2)) { return false; } Set<Clause> parentsOfC2 = this.getAllClausesUsedToObtainResolvent(c2); return !parentsOfC2.contains(c1); } public Set<Clause> getAllClausesUsedToObtainResolvent(final Clause resolvent) { Set<Clause> clauses = new HashSet<>(); for (ResolutionStep step : this.getAllStepsUsedToObtainResolvent(resolvent)) { clauses.add(step.getPair().getC1()); clauses.add(step.getPair().getC2()); } return clauses; } public boolean containsResolvent(final Clause resolvent) { return this.baseClauses.contains(resolvent) || this.resolventsWithTheirSteps.containsKey(resolvent); } public boolean containsEmptyClause() { return this.containsResolvent(new Clause()); } public Set<ResolutionStep> getAllStepsUsedToObtainResolvent(final Clause resolvent) { if (this.baseClauses.contains(resolvent)) { return new HashSet<>(); } Set<ResolutionStep> steps = new HashSet<>(); ResolutionStep step = this.resolventsWithTheirSteps.get(resolvent); steps.add(step); steps.addAll(this.getAllStepsUsedToObtainResolvent(step.getPair().getC1())); steps.addAll(this.getAllStepsUsedToObtainResolvent(step.getPair().getC2())); return steps; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms/resolution/Solver.java
package ai.libs.jaicore.logic.fol.algorithms.resolution; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Clause; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.VariableParam; /** * This solver tries to solver PL1 formulas in CNF where all variables are existentially quantified * * @author Felix * */ public abstract class Solver { private static final Logger logger = LoggerFactory.getLogger(Solver.class); private final Set<CNFFormula> formulas = new HashSet<>(); private final Map<CNFFormula, CNFFormula> internalRepresentationOfFormulas = new HashMap<>(); private ResolutionTree tree; // stores the resolution tree private int varCounter = 1; public Set<CNFFormula> getFormulas() { return this.formulas; } public Map<CNFFormula, CNFFormula> getInternalRepresentationOfFormulas() { return this.internalRepresentationOfFormulas; } public void addFormula(final CNFFormula formula) { this.formulas.add(formula); /* make variable names in all clauses disjoint */ CNFFormula disAmbFormula = new CNFFormula(); for (Clause c : formula) { Set<VariableParam> paramsInC = c.getVariableParams(); Map<VariableParam, LiteralParam> substitution = new HashMap<>(); for (VariableParam p : paramsInC) { substitution.put(p, new VariableParam("c" + this.varCounter + "_" + p.getName())); } disAmbFormula.add(new Clause(c, substitution)); this.varCounter++; } this.internalRepresentationOfFormulas.put(formula, disAmbFormula); } public void removeFormula(final CNFFormula formula) { this.formulas.remove(formula); this.internalRepresentationOfFormulas.remove(formula); } public boolean isSatisfiable(final CNFFormula formula) throws InterruptedException { CNFFormula internalRepresentation = this.internalRepresentationOfFormulas.get(formula); CNFFormula resultOfResolution = this.performResolutionUntilEmptyClauseIsFound(internalRepresentation, internalRepresentation); this.internalRepresentationOfFormulas.put(formula, resultOfResolution); return !resultOfResolution.contains(new HashSet<>()); } /** * is f & g satisfiable if resolution must take in each step at least one clause from g (and resolvents produced)? * * @param formula * @param formulaToChooseAtLeastOneLiteralFrom * @return */ public boolean isSatisfiable(final CNFFormula formula, final CNFFormula formulaToChooseAtLeastOneLiteralFrom) throws InterruptedException { CNFFormula internalRepresentationOfFormula1 = this.internalRepresentationOfFormulas.get(formula); CNFFormula internalRepresentationOfFormula2 = this.internalRepresentationOfFormulas.get(formulaToChooseAtLeastOneLiteralFrom); CNFFormula joint = new CNFFormula(); joint.addAll(internalRepresentationOfFormula1); joint.addAll(internalRepresentationOfFormula2); CNFFormula resultOfResolution = this.performResolutionUntilEmptyClauseIsFound(joint, internalRepresentationOfFormula2); return !resultOfResolution.contains(new HashSet<>()); } public boolean isSatisfiable() throws InterruptedException { CNFFormula jointFormula = new CNFFormula(); for (CNFFormula formula : this.formulas) { jointFormula.addAll(this.internalRepresentationOfFormulas.get(formula)); } CNFFormula resultOfResolution = this.performResolutionUntilEmptyClauseIsFound(jointFormula, jointFormula); return !resultOfResolution.contains(new HashSet<>()); } protected CNFFormula performResolutionUntilEmptyClauseIsFound(final CNFFormula formula, final CNFFormula formulaToChooseAtLeastOneLiteralFrom) throws InterruptedException { /* create start state with substituted formula */ Set<ResolutionPair> candidates = new HashSet<>(); candidates.addAll(this.getPossibleResolutionPairs(formulaToChooseAtLeastOneLiteralFrom)); for (Clause c : formula) { candidates.addAll(this.getPossibleResolutionPairs(formulaToChooseAtLeastOneLiteralFrom, c)); } /* create memory */ this.tree = new ResolutionTree(formula); CNFFormula currentFormula = new CNFFormula(formula); ResolutionPair nextPair; logger.info("Starting resolution for formula {} using in each iteration literals from {}", formula, formulaToChooseAtLeastOneLiteralFrom); logger.info("The initial set of candidates is {}", candidates); while ((nextPair = this.getNextPair(candidates)) != null) { ResolutionStep step = this.performResolutionStepForPair(nextPair); if (step == null) { continue; } Clause resolvent = step.getR(); logger.debug("Size is {}: Resolving {} with {} on literal {} with unifier {}. Resolvent is: {}", candidates.size(), nextPair.getC1(), nextPair.getC2(), nextPair.getL1().getProperty(), step.getUnificator(), resolvent); if (nextPair.getC1().isTautological() || nextPair.getC2().isTautological()) { logger.error("Resolved tautological clause!"); } if (resolvent.isEmpty()) { // cancel if we deduced the empty clause logger.debug("Found empty clause, canceling process."); currentFormula.add(resolvent); this.tree.addResolutionStep(step); return currentFormula; } if (this.isClauseAlreadyContainedInFormula(currentFormula, resolvent)) { logger.debug("Ignoring resolvent, because it is already contained in the known formula."); continue; } this.tree.addResolutionStep(step); // memorize this step if (resolvent.isTautological()) { logger.debug("Not considering any clauses producible with this resolvent, because it is tautological."); continue; } logger.debug("Added resolvent {} to formula, which has now size {}.", resolvent, currentFormula.size()); currentFormula.add(resolvent); /* * if this resolvent is not tautological, create new candidates that have become available by this resolvent */ List<ResolutionPair> successors = this.getPossibleResolutionPairs(currentFormula, resolvent); candidates.addAll(this.getAdmissiblePairs(successors)); } return currentFormula; } public ResolutionTree getTree() { return this.tree; } protected ResolutionPair getNextPair(final Set<ResolutionPair> candidates) { /* try to find a pair with unit clause */ List<ResolutionPair> pairsWithUnitClause = candidates.stream().filter(p -> (p.getC1().size() == 1 || p.getC2().size() == 1)).collect(Collectors.toList()); if (!pairsWithUnitClause.isEmpty()) { ResolutionPair pair = pairsWithUnitClause.get(0); candidates.remove(pair); return pair; } /* now minimize for s.th. */ Optional<ResolutionPair> min = candidates.stream().min((p1, p2) -> (p1.getC1().size() + p1.getC2().size()) - (p2.getC1().size() + p2.getC2().size())); if (!min.isPresent()) { return null; } ResolutionPair pair = min.get(); candidates.remove(pair); return pair; } protected List<ResolutionPair> getPossibleResolutionPairs(final CNFFormula formula) { List<ResolutionPair> pairs = new LinkedList<>(); Set<List<Clause>> candidates = SetUtil.getAllPossibleSubsetsWithSize(formula, 2).stream().map(ArrayList::new).collect(Collectors.toSet()); for (List<Clause> pair : candidates) { Clause c1 = pair.get(0); Clause c2 = pair.get(1); boolean invert = c1.size() > c2.size(); pairs.addAll(this.getPossibleResolutionsPairsOfClauses(invert ? c2 : c1, invert ? c1 : c2)); } return pairs; } protected abstract List<ResolutionPair> getAdmissiblePairs(List<ResolutionPair> pairs); protected List<ResolutionPair> getPossibleResolutionPairs(final CNFFormula formula, final Clause c2) { logger.debug("Computing all resolution pairs between formula {} and clause {}", formula, c2); List<ResolutionPair> pairs = new LinkedList<>(); for (Clause c1 : formula) { boolean invert = c1.size() > c2.size(); pairs.addAll(this.getPossibleResolutionsPairsOfClauses(invert ? c2 : c1, invert ? c1 : c2)); } return pairs; } protected Set<Clause> getClausesWithSamePredicates(final CNFFormula formula, final Clause c2) { Set<Clause> clausesWithSamePredicates = new HashSet<>(); Set<String> predicatesInC2 = c2.toPropositionalSet(); for (Clause c1 : formula) { if (c1.size() != c2.size()) { continue; } if (c1.toPropositionalSet().equals(predicatesInC2)) { clausesWithSamePredicates.add(c1); } } return clausesWithSamePredicates; } protected boolean isClauseAlreadyContainedInFormula(final CNFFormula formula, final Clause c) throws InterruptedException { if (formula.contains(c)) { return true; } Set<Clause> possibleMatchings = this.getClausesWithSamePredicates(formula, c); int numberOfVarsInC = c.getVariableParams().size(); for (Clause candidate : possibleMatchings) { Set<VariableParam> paramsOfCandidate = candidate.getVariableParams(); Clause clauseWithLessParams = ((numberOfVarsInC < paramsOfCandidate.size()) ? c : candidate); Clause clauseWithMoreParams = clauseWithLessParams == c ? candidate : c; for (Map<VariableParam, VariableParam> map : SetUtil.allTotalMappings(clauseWithMoreParams.getVariableParams(), clauseWithLessParams.getVariableParams())) { Clause clauseWithMoreParamsMapped = new Clause(clauseWithMoreParams, map); if (clauseWithMoreParamsMapped.equals(clauseWithLessParams)) { return true; } } } return false; } /** * * @param c1 * Note that c1 MUST be the smaller clause by convention * @param c2 * @return */ protected List<ResolutionPair> getPossibleResolutionsPairsOfClauses(final Clause c1, final Clause c2) { List<ResolutionPair> pairs = new ArrayList<>(); if (c1.size() > c2.size()) { logger.error("Error, first clause bigger than second!"); } /* * for each of the literals in c1, find literals in c2 that can be used for resolution */ for (Literal l1 : c1) { for (Literal l2 : c2) { if ((l1.getPropertyName().equals(l2.getPropertyName()) && l1.isPositive() != l2.isPositive())) { pairs.add(new ResolutionPair(c1, c2, l1, l2)); } } } logger.debug("Possible resolution pairs for clauses {} and {} are {}", c1, c2, pairs); return pairs; } protected ResolutionStep performResolutionStepForPair(final ResolutionPair pair) { /* get unifier for the two clauses */ Map<VariableParam, LiteralParam> unifier = this.getUnificatorForLiterals(pair.getL1(), pair.getL2()); if (unifier == null) { return null; } /* literals are unifiable, now compute resulting resolvent */ Clause basicResolvent = new Clause(); for (Literal l : pair.getC1()) { if (l == pair.getL1()) { continue; } basicResolvent.add(new Literal(l, unifier)); } for (Literal l : pair.getC2()) { if (l == pair.getL2()) { continue; } basicResolvent.add(new Literal(l, unifier)); } /* * now make variables in this new resolve unique by adding an underscore to each of the variables */ Map<VariableParam, LiteralParam> substitution = new HashMap<>(); for (VariableParam variable : basicResolvent.getVariableParams()) { substitution.put(variable, new VariableParam("_" + variable.getName())); } Clause resolvent = new Clause(basicResolvent, substitution); /* add this resolution step to the possible steps */ return new ResolutionStep(pair, resolvent, unifier); } /** * Performs Robinsons's unification * * @param l1 * @param l2 * @return */ protected Map<VariableParam, LiteralParam> getUnificatorForLiterals(final Literal l1, final Literal l2) { List<LiteralParam> p1 = new LinkedList<>(l1.getParameters()); List<LiteralParam> p2 = new LinkedList<>(l2.getParameters()); if (p1.size() != p2.size()) { return null; } Map<VariableParam, LiteralParam> unifier = new HashMap<>(); for (int i = 0; i < p1.size(); i++) { LiteralParam v1 = p1.get(i); LiteralParam v2 = p2.get(i); /* not unifiable if two different constants must be unified */ if (v1 instanceof ConstantParam && v2 instanceof ConstantParam && !v1.equals(v2)) { return null; } else if (v1 instanceof VariableParam && v2 instanceof ConstantParam) { unifier.put((VariableParam) v1, v2); for (Entry<VariableParam, LiteralParam> unificationEntry : unifier.entrySet()) { if (unificationEntry.getValue().equals(v1)) { unifier.put(unificationEntry.getKey(), v2); } } } else if (v2 instanceof VariableParam && v1 instanceof ConstantParam) { unifier.put((VariableParam) v2, v1); for (Entry<VariableParam, LiteralParam> entry : unifier.entrySet()) { if (entry.getValue().equals(v2)) { unifier.put(entry.getKey(), v1); } } } else { if (!v1.equals(v2)) { unifier.put((VariableParam) v2, v1); } for (Entry<VariableParam, LiteralParam> entry : unifier.entrySet()) { if (entry.getValue().equals(v2)) { unifier.put(entry.getKey(), v1); } } } } return unifier; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms/resolution/SolverFactory.java
package ai.libs.jaicore.logic.fol.algorithms.resolution; import java.util.stream.Collectors; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Clause; import ai.libs.jaicore.logic.fol.structure.Literal; public class SolverFactory { private static SolverFactory singleton = new SolverFactory(); private SolverFactory() { } public static SolverFactory getInstance() { return singleton; } public Solver getSolver(final CNFFormula formula) { /* check if formula is in horn */ boolean isHorn = true; for (Clause c : formula) { if (c.stream().filter(Literal::isPositive).limit(2).collect(Collectors.toList()).size() > 1) { isHorn = false; break; } } if (isHorn) { Solver solver = new UnitResolutionSolver(); solver.addFormula(formula); return solver; } throw new IllegalArgumentException("Formula " + formula + " is not in HORN!"); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/algorithms/resolution/UnitResolutionSolver.java
package ai.libs.jaicore.logic.fol.algorithms.resolution; import java.util.List; import java.util.stream.Collectors; public class UnitResolutionSolver extends Solver { @Override protected List<ResolutionPair> getAdmissiblePairs(List<ResolutionPair> pairs) { return pairs.stream().filter(p -> p.getC1().size() == 1 || p.getC2().size() == 1).collect(Collectors.toList()); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/CNFFormula.java
package ai.libs.jaicore.logic.fol.structure; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import ai.libs.jaicore.logic.fol.util.LogicUtil; @SuppressWarnings("serial") public class CNFFormula extends HashSet<Clause> { public CNFFormula() { super(); } public CNFFormula(final Clause c) { super(); this.add(c); } public CNFFormula(final Monom m) { super(); for (Literal l : m) { this.add(new Clause(l)); } } public CNFFormula(final Collection<Clause> c) { super(); this.addAll(c); } public CNFFormula(final Set<Clause> clauses, final Map<VariableParam, ? extends LiteralParam> mapping) { super(); for (Clause c : clauses) { Clause replacedClause = new Clause(c, mapping); /* if the clause is empty, it is false */ if (replacedClause.isEmpty()) { this.clear(); this.add(new Clause("A")); this.add(new Clause("!A")); return; } /* if the clause is tautological, we also do not need to add it */ if (!replacedClause.isTautological()) { this.add(replacedClause); } } } public Set<VariableParam> getVariableParams() { Set<VariableParam> vars = new HashSet<>(); for (Clause c : this) { vars.addAll(c.getVariableParams()); } return vars; } public Set<ConstantParam> getConstantParams() { Set<ConstantParam> constants = new HashSet<>(); for (Clause c : this) { constants.addAll(c.getConstantParams()); } return constants; } public boolean hasDisjunctions() { for (Clause c : this) { if (c.size() > 1) { return true; } } return false; } public Monom extractMonom() { if (this.hasDisjunctions()) { throw new IllegalArgumentException("Cannot extract a monom from a non-monom CNF"); } Monom m = new Monom(); for (Clause c : this) { m.add(c.iterator().next()); } return m; } public boolean isObviouslyContradictory() { return this.contains(new Clause("A")) && this.contains(new Clause("!A")); } public boolean entailedBy(final Monom m) { for (Clause c : this) { boolean clauseSatisfied = false; for (Literal l : c) { if (l.getPropertyName().equals("=")) { if (LogicUtil.evalEquality(l)) { clauseSatisfied = true; break; } } else if (l.isPositive() && m.contains(l) || l.isNegated() && !m.contains(l.clone().toggleNegation())) { clauseSatisfied = true; break; } } if (!clauseSatisfied) { return false; } } return true; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/Clause.java
package ai.libs.jaicore.logic.fol.structure; import java.util.Map; import ai.libs.jaicore.logic.fol.util.LogicUtil; public class Clause extends LiteralSet { public static Clause getByNegatingMonom(final Monom m) { Clause c = new Clause(); for (Literal l : m) { c.add(new Literal(l.getProperty(), l.getParameters(), !l.isPositive())); } return c; } public Clause() { super(); } public Clause(final Literal l) { super(l); } public Clause(final LiteralSet literals, final Map<VariableParam, ? extends LiteralParam> m) { super(); for (Literal l : literals) { Literal lCopy = l.clone(m); if (lCopy.getPropertyName().equals("=") && lCopy.isGround()) { if (LogicUtil.evalEquality(lCopy)) { this.clear(); this.add(new Literal("A")); this.add(new Literal("!A")); return; } } else { this.add(lCopy); } } } public Clause(final String literals) { super(literals, "\\|"); } /** * */ private static final long serialVersionUID = 3915423297171319761L; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); boolean firstElement = true; for (Literal l : this) { if (firstElement) { firstElement = false; } else { sb.append("|"); } sb.append(l); } sb.append("]"); return sb.toString(); } public boolean isTautological() { return this.containsPositiveAndNegativeVersionOfLiteral(); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/ConstantParam.java
package ai.libs.jaicore.logic.fol.structure; /** * The constant parameter of a literal. * * @author mbunse */ @SuppressWarnings("serial") public class ConstantParam extends LiteralParam { private boolean variablesMayBeUnifiedWithThisConstant; public ConstantParam(final String name, final boolean pVariablesMayBeUnifiedWithThisConstant) { super(name); this.variablesMayBeUnifiedWithThisConstant = pVariablesMayBeUnifiedWithThisConstant; } public ConstantParam(final String name) { this(name, true); } public ConstantParam(final String name, final Type type) { this(name); this.type = type; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { if (!(obj instanceof ConstantParam)) { return false; } return super.equals(obj); } @Override public String toString() { return this.getName(); } public boolean variablesMayBeUnifiedWithThisConstant() { return this.variablesMayBeUnifiedWithThisConstant; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/DNFFormula.java
package ai.libs.jaicore.logic.fol.structure; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import ai.libs.jaicore.logic.fol.util.LogicUtil; @SuppressWarnings("serial") public class DNFFormula extends HashSet<Monom> { public DNFFormula() { super(); } public DNFFormula(final Monom m) { super(); this.add(m); } public DNFFormula(final Clause m) { super(); for (Literal l : m) { this.add(new Monom(l)); } } public DNFFormula(final Collection<Monom> m) { super(); this.addAll(m); } public DNFFormula(final Set<Monom> monoms, final Map<VariableParam, ? extends LiteralParam> mapping) { super(); for (Monom c : monoms) { Monom replacedMonom = new Monom(c, mapping); /* if the monom is empty, it is false */ if (replacedMonom.isEmpty()) { this.clear(); this.add(new Monom("A")); this.add(new Monom("!A")); return; } /* if the monom is contradictory, we also do not need to add it */ if (!replacedMonom.isContradictory()) { this.add(replacedMonom); } } } public Set<VariableParam> getVariableParams() { Set<VariableParam> vars = new HashSet<>(); for (Monom m : this) { vars.addAll(m.getVariableParams()); } return vars; } public Set<ConstantParam> getConstantParams() { Set<ConstantParam> constants = new HashSet<>(); for (Monom m : this) { constants.addAll(m.getConstantParams()); } return constants; } public boolean hasConjunctions() { for (Monom m : this) { if (m.size() > 1) { return true; } } return false; } public Clause extractClause() { if (this.hasConjunctions()) { throw new IllegalArgumentException("Cannot extract a clause from a non-monom DNF"); } Clause c = new Clause(); for (Monom m : this) { c.add(m.iterator().next()); } return c; } public boolean entailedBy(final Monom m) { for (Monom m2 : this) { boolean monomSatisfied = true; for (Literal l : m2) { if (l.getPropertyName().equals("=")) { if (!LogicUtil.evalEquality(l)) { monomSatisfied = false; break; } } else if (!(l.isPositive() && m.contains(l) || l.isNegated() && !m.contains(l.clone().toggleNegation()))) { monomSatisfied = false; break; } } if (monomSatisfied) { return true; } } return false; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/HornFormula.java
package ai.libs.jaicore.logic.fol.structure; import java.util.HashSet; import java.util.Set; @SuppressWarnings("serial") public class HornFormula extends HashSet<HornRule> { public Set<ConstantParam> getConstantParams() { Set<ConstantParam> constants = new HashSet<>(); for (HornRule r : this) { constants.addAll(r.getPremise().getConstantParams()); constants.addAll(r.getConclusion().getConstantParams()); } return constants; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/HornRule.java
package ai.libs.jaicore.logic.fol.structure; public class HornRule { private Monom premise; private Literal conclusion; public HornRule(Monom premise, Literal conclusion) { super(); this.premise = premise; this.conclusion = conclusion; } public Monom getPremise() { return premise; } public Literal getConclusion() { return conclusion; } @Override public String toString() { return premise + " -> " + conclusion; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/InterpretedLiteral.java
package ai.libs.jaicore.logic.fol.structure; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings("serial") public class InterpretedLiteral extends Literal { private static final Logger logger = LoggerFactory.getLogger(InterpretedLiteral.class); /** * Copy constructor for an existing literal under giving mapping. * * @param l * Literal to be copied * @param map * Mapping for projecting existing literal to a new literal. */ public InterpretedLiteral(final Literal l, final Map<VariableParam, ? extends LiteralParam> map) { super(l, map); } /** * Creates a monadic literal (with only one parameter). * * @param property * The property defined by this literal. * @param parameter * The parameter of this literal. */ public InterpretedLiteral(final String property, final LiteralParam parameter) { super(property, parameter); } /** * Creates a literal with a list of parameters. * * @param property * The property defined by this literal. * @param parameter * The parameters of this literal defined as a list. */ public InterpretedLiteral(final String property, final List<LiteralParam> parameters) { super(property, parameters); } /** * Protected helper constructor. Ensure the literal gets parameters!! */ public InterpretedLiteral(final String property) { super(property); } public InterpretedLiteral(final String predicateName, final List<LiteralParam> params, final boolean b) { super(predicateName, params, b); } @Override public Literal clone() { return new InterpretedLiteral(this.getProperty(), this.getParameters()); } /** * Creates a copy of this literal on which the given parameter mapping is * applied. * * @param mapping * A mapping of parameters. * @return A copy of this literal on which the given parameter mapping is * applied. */ @Override public Literal clone(final Map<? extends VariableParam, ? extends LiteralParam> mapping) { logger.debug("start cloning"); Literal clone = new InterpretedLiteral(this.getProperty()); // add parameters corresponding to mapping for (LiteralParam v : this.getParameters()) { if (v instanceof VariableParam) { if (mapping != null && mapping.containsKey(v)) { logger.trace("Params: {}", clone.getParameters()); } clone.getParameters().add((mapping != null && mapping.containsKey(v)) ? mapping.get(v) : v); } else { clone.getParameters().add(v); } } logger.debug("finished cloning"); return clone; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("i*"); sb.append(super.toString()); return sb.toString(); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/Literal.java
package ai.libs.jaicore.logic.fol.structure; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.logic.fol.util.LogicUtil; /** * A literal defines a property over parameters. Note that literals can be cloned using the clone() methods. * * @author Felix Mohr */ @SuppressWarnings("serial") public class Literal implements Serializable, Comparable<Literal> { private static Logger logger = LoggerFactory.getLogger(Literal.class); private String property; private List<LiteralParam> parameters; public Literal(final Literal l, final Map<? extends LiteralParam, ? extends LiteralParam> map) { this(l.getProperty()); for (LiteralParam p : l.getParameters()) { this.parameters.add(map.containsKey(p) ? map.get(p) : p); } } /** * Creates a monadic literal (with only one parameter). * * @param property * The property defined by this literal. * @param parameter * The parameter of this literal. */ public Literal(final String property, final LiteralParam parameter) { this(property); this.parameters.add(parameter); } /** * Creates a literal with a list of parameters. * * @param property * The property defined by this literal. * @param parameter * The parameters of this literal defined as a list. */ public Literal(final String property, final List<? extends LiteralParam> parameters) { this(property); this.parameters.addAll(parameters); } /** * Protected helper constructor. Ensure the literal gets parameters!! */ public Literal(final String pPropertyWithParams) { super(); this.parameters = new ArrayList<>(); /* detect special predicates = or != */ if (pPropertyWithParams.contains("=")) { String[] params = StringUtil.explode(pPropertyWithParams, "="); boolean isNegated = params.length > 0 && params[0].endsWith("!"); this.property = isNegated ? "!=" : "="; if (params.length == 2) { int p1Length = isNegated ? params[0].length() - 1 : params[0].length(); this.parameters.add(LogicUtil.parseParamName(params[0].substring(0, p1Length).trim())); this.parameters.add(LogicUtil.parseParamName(params[1].trim())); } } /* otherwise, if this is a normal predicate */ else { boolean isPositive = true; String propertyWithParams = "" + pPropertyWithParams; if (pPropertyWithParams.startsWith("!")) { isPositive = false; propertyWithParams = pPropertyWithParams.substring(1); } /* add parameters if given in the string */ if (propertyWithParams.contains("(")) { if (propertyWithParams.contains(")")) { int index = propertyWithParams.indexOf('('); this.property = propertyWithParams.substring(0, index); if (index < propertyWithParams.length() - 2) { this.parameters.addAll(Arrays.asList(StringUtil.explode(propertyWithParams.substring(index + 1, propertyWithParams.length() - 1), ",")).stream().map(s -> LogicUtil.parseParamName(s.trim())).collect(Collectors.toList())); } } } else { this.property = propertyWithParams; } if (!isPositive) { this.property = "!" + this.property; } } if (this.property == null) { throw new IllegalArgumentException("Given string \"" + pPropertyWithParams + "\" causes a NULL property!"); } } public Literal(final String property2, final boolean isPositive) { this(property2); if (isPositive && this.isNegated() || !isPositive && this.isPositive()) { this.toggleNegation(); } } public Literal(final String property2, final List<? extends LiteralParam> parameters, final boolean isPositive) { this(property2, parameters); if (isPositive && this.isNegated() || !isPositive && this.isPositive()) { this.toggleNegation(); } } /** * Returns a String representation of the property stated by this literal. */ public final String getProperty() { return (this.isNegated() ? "!" : "") + this.getPropertyName(); } /** * Returns only the property name of this literal. */ public final String getPropertyName() { return this.isNegated() ? this.property.substring(1) : this.property; } /** * @return The parameters of this literal in an unmodifiable list. */ public final List<LiteralParam> getParameters() { return Collections.unmodifiableList(this.parameters); } public final boolean isNegated() { return this.property.startsWith("!"); } public Literal toggleNegation() { this.property = this.isNegated() ? this.getPropertyName() : "!" + this.getPropertyName(); return this; } /** * @return The variable parameters of this literal in an unmodifiable list. */ public final List<VariableParam> getVariableParams() { List<VariableParam> vars = new LinkedList<>(); for (LiteralParam param : this.parameters) { if (param instanceof VariableParam) { vars.add((VariableParam) param); } } return Collections.unmodifiableList(vars); } public final List<ConstantParam> getConstantParams() { List<ConstantParam> constants = new ArrayList<>(); for (LiteralParam param : this.parameters) { if (param instanceof ConstantParam) { constants.add((ConstantParam) param); } } return Collections.unmodifiableList(constants); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.parameters == null) ? 0 : this.parameters.hashCode()); result = prime * result + ((this.property == null) ? 0 : this.property.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Literal other = (Literal) obj; if (this.parameters == null) { if (other.parameters != null) { return false; } } else if (!this.parameters.equals(other.parameters)) { return false; } if (this.property == null) { if (other.property != null) { return false; } } else if (!this.property.equals(other.property)) { return false; } return true; } @Override public Literal clone() { return new Literal(this.property, this.parameters); } /** * Creates a copy of this literal on which the given parameter mapping is applied. * * @param mapping * A mapping of parameters. * @return A copy of this literal on which the given parameter mapping is applied. */ public Literal clone(final Map<? extends VariableParam, ? extends LiteralParam> mapping) { logger.debug("start cloning"); Literal clone = new Literal(this.property); // add parameters corresponding to mapping for (LiteralParam v : this.getParameters()) { if (v instanceof VariableParam && mapping != null && mapping.containsKey(v)) { logger.trace("Params: {}", clone.parameters); if (mapping.get(v) == null) { throw new IllegalArgumentException("Mapping " + mapping + " assigns null to a parameter, which must not be the case!"); } clone.parameters.add(mapping.get(v)); } else { clone.parameters.add(v); } } logger.debug("finished cloning"); return clone; } @Override public String toString() { return this.toString(true); } public String toString(final boolean printTypesOfParams) { StringBuilder sb = new StringBuilder(); sb.append(this.property + "("); // iterate through parameter list int params = this.parameters.size(); int i = 1; for (LiteralParam p : this.parameters) { sb.append(printTypesOfParams ? p.toString() : p.getName()); if (i++ < params) { sb.append(", "); } } sb.append(")"); return sb.toString(); } public boolean isNegationOf(final Literal l) { return l.getPropertyName().equals(this.getPropertyName()) && l.getParameters().equals(this.parameters) && l.isNegated() != this.isNegated(); } public boolean isPositive() { return !this.isNegated(); } public boolean hasVariableParams() { return !this.getVariableParams().isEmpty(); } public final boolean isGround() { return !this.hasVariableParams(); } @Override public int compareTo(final Literal l) { return this.property.compareTo(l.property); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/LiteralParam.java
package ai.libs.jaicore.logic.fol.structure; import java.io.Serializable; /** * The parameter of a literal. * * @author mbunse */ @SuppressWarnings("serial") public abstract class LiteralParam implements Serializable { private String name; protected Type type; /** * @param name * The name of this parameter; */ protected LiteralParam(final String name) { this.name = name; } /** * @param name * The name of this parameter; */ protected LiteralParam(final String name, final Type type) { this(name); this.setType(type); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); return result; } /** * It is with intention that the equals method does NOT check the type. * We assume that the name of a parameter is sufficient to identify it. * The type is rather optional to enable efficient processing in some contexts. * */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } LiteralParam other = (LiteralParam) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } return true; } public String getName() { return this.name; } public Type getType() { return this.type; } public void setType(final Type type) { this.type = type; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/LiteralSet.java
package ai.libs.jaicore.logic.fol.structure; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.basic.sets.SetUtil; /** * A set of literals. * * @author mbunse */ public class LiteralSet extends HashSet<Literal> { /** * */ private static final long serialVersionUID = 6767454041686262363L; private static Logger logger = LoggerFactory.getLogger(LiteralSet.class); /** * Creates an empty literal set. Literals can be added later. */ public LiteralSet() { super(); } public LiteralSet(final String literals, final String delimiter) { this(Arrays.asList(StringUtil.explode(literals, delimiter)).stream().map(s -> new Literal(s.trim())).collect(Collectors.toList())); } /** * Creates a literal set that only contains the given literal. Other literals can be added later. * * @param literal * A literal. */ public LiteralSet(final Literal literal) { super(); this.add(literal.clone()); } /** * Creates a copy of the given collection. The created literal set will contain all the elements from the given collection. * * @param literals * A collection of literals. */ public LiteralSet(final Collection<Literal> literals, final boolean deep) { super(); if (literals != null) { if (deep) { for (Literal l : literals) { this.add(l.clone()); } } else { this.addAll(literals); } } } public LiteralSet(final Collection<Literal> literals) { this(literals, true); } /** * Creates a copy of the given collection under the given parameter mapping. * * @param literals * A collection of literals. * @param mapping * A mapping of literals. */ public LiteralSet(final Collection<Literal> literals, final Map<? extends LiteralParam, ? extends LiteralParam> mapping) { super(); logger.debug("init with: {}", literals); for (Literal l : literals) { logger.debug("call clone for literal {}, which is of class {}, on literal set {}", l, l.getClass(), this); this.add(new Literal(l, mapping)); logger.debug("finished clone for literal {}, which is of class {}, on literal set {}", l, l.getClass(), this); } } public boolean add(final String literalDescriptor) { return this.add(new Literal(literalDescriptor)); } /** * @param conclusion * Another literal set that may be concluded by this literal set. * @return True, if this literal set logically implies the conclusion literal set under any partial mapping. */ public boolean implies(final LiteralSet conclusion) throws InterruptedException { if (this.containsAll(conclusion)) { return true; } // check all partial mappings for implication for (Map<VariableParam, VariableParam> mapping : SetUtil.allMappings(this.getVariableParams(), conclusion.getVariableParams(), false, false, false)) { if (new LiteralSet(this, mapping).containsAll(conclusion)) { return true; // implication mapping found } } return false; // no implying mapping } public boolean isConsistent() { for (Literal l : this) { String prop = l.getProperty(); String negProp = prop.startsWith("!") ? prop.substring(1) : ("!" + prop); if (this.contains(new Literal(negProp, l.getParameters()))) { return false; } } return true; } public Map<VariableParam, VariableParam> getImplyingMappingThatMapsFromConclusionVarsToPremiseVars(final LiteralSet conclusion) throws InterruptedException { for (Map<VariableParam, VariableParam> mapping : SetUtil.allMappings(conclusion.getVariableParams(), this.getVariableParams(), false, false, false)) { if (this.containsAll(new LiteralSet(conclusion, mapping))) { return mapping; // implication mapping found } } return null; // no implying mapping } public LiteralSet getPositiveLiterals() { LiteralSet ls = new LiteralSet(); for (Literal l : this) { if (l.isPositive()) { ls.add(l); } } return ls; } public LiteralSet getNegativeLiterals() { LiteralSet ls = new LiteralSet(); for (Literal l : this) { if (l.isNegated()) { ls.add(l); } } return ls; } /** * @return All the parameters (variable and constant) from the contained literals. */ public Set<LiteralParam> getParameters() { Set<LiteralParam> params = new HashSet<>(); for (Literal literal : this) { params.addAll(literal.getParameters()); } return params; } /** * @return All the variable parameters from the contained literals. */ public Set<VariableParam> getVariableParams() { Set<VariableParam> vars = new HashSet<>(); for (Literal literal : this) { vars.addAll(literal.getVariableParams()); } return vars; } public Set<ConstantParam> getConstantParams() { Set<ConstantParam> constants = new HashSet<>(); for (Literal literal : this) { constants.addAll(literal.getConstantParams()); } return constants; } /** * @return All interpreted literals that could be used as branching or looping condition */ public Set<InterpretedLiteral> getInterpretedLiterals() { Set<InterpretedLiteral> interpretedLiteralSet = new HashSet<>(); for (Literal l : this) { if (l instanceof InterpretedLiteral) { interpretedLiteralSet.add((InterpretedLiteral) l); } } return interpretedLiteralSet; } /** * This method converts the LiteralSet into a PropositionalSet meaning that the resulting set only contains properties of the literals contained in this LiteralSet. * * @return A set of property name strings. */ public Set<String> toPropositionalSet() { Set<String> propositionalSet = new HashSet<>(); for (Literal l : this) { propositionalSet.add(l.getProperty()); } return propositionalSet; } public boolean containsPositiveAndNegativeVersionOfLiteral() { for (Literal l1 : this) { for (Literal l2 : this) { if (l1.isNegationOf(l2)) { return true; } } } return false; } public boolean containsGroundEqualityPredicateThatEvaluatesTo(final boolean eval) { for (Literal l : this) { if (l.getPropertyName().equals("=") && l.isGround()) { List<ConstantParam> params = l.getConstantParams(); if ((l.isPositive() == params.get(0).equals(params.get(1))) == eval) { return true; } } } return false; } public boolean containsLiteralWithPredicatename(final String predicateName) { for (Literal l : this) { if (l.getPropertyName().equals(predicateName)) { return true; } } return false; } public boolean hasVariables() { return !this.getVariableParams().isEmpty(); } public Set<Literal> getLiteralsWithPropertyName(final String propertyName) { Set<Literal> literalsWithPropertyName = new HashSet<>(); for (Literal lit : this) { if (lit.getPropertyName().equals(propertyName)) { literalsWithPropertyName.add(lit); } } return literalsWithPropertyName; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/Monom.java
package ai.libs.jaicore.logic.fol.structure; import java.util.Collection; import java.util.HashMap; import java.util.Map; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logging.ToJSONStringUtil; public class Monom extends LiteralSet { public static Monom fromCNFFormula(final CNFFormula formula) { Monom m = new Monom(); for (Clause c : formula) { if (c.size() > 1) { throw new IllegalArgumentException("Monom constructor says: Cannot create monom from CNF with disjunctions " + formula); } m.addAll(c); } return m; } public Monom() { super(); } public Monom(final Literal l) { super(l); } public Monom(final String literals) { super(literals, "&"); } public Monom(final Collection<Literal> set) { this(set, true); } public Monom(final Collection<Literal> set, final boolean deep) { super(set, deep); } public Monom(final Collection<Literal> literals, final Map<? extends LiteralParam, ? extends LiteralParam> mapping) { super(literals, mapping); } /** * */ private static final long serialVersionUID = 1279300062766067057L; @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("literals", this); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } public boolean isContradictory() { return this.containsPositiveAndNegativeVersionOfLiteral() || this.containsGroundEqualityPredicateThatEvaluatesTo(false); } @Override public boolean isConsistent() { return !this.isContradictory(); } /** * @param conclusion * Another literal set that may be concluded by this literal set. * @return True, if this literal set logically implies the conclusion literal set under any partial mapping. */ @Override public boolean implies(final LiteralSet conclusion) throws InterruptedException { // check all partial mappings for implication for (Map<VariableParam, VariableParam> mapping : SetUtil.allMappings(this.getVariableParams(), conclusion.getVariableParams(), false, false, false)) { if (new LiteralSet(this, mapping).containsAll(conclusion)) { return true; // implication mapping found } } return false; // no implying mapping } @Override public Map<VariableParam, VariableParam> getImplyingMappingThatMapsFromConclusionVarsToPremiseVars(final LiteralSet conclusion) throws InterruptedException { for (Map<VariableParam, VariableParam> mapping : SetUtil.allMappings(conclusion.getVariableParams(), this.getVariableParams(), false, false, false)) { if (this.containsAll(new LiteralSet(conclusion, mapping))) { return mapping; // implication mapping found } } return null; // no implying mapping } public CNFFormula asCNF() { CNFFormula formula = new CNFFormula(); for (Literal l : this) { formula.add(new Clause(l)); } return formula; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/Rule.java
package ai.libs.jaicore.logic.fol.structure; import java.util.HashSet; import java.util.Set; /** * @author wever * */ public class Rule { private final CNFFormula premise; private final CNFFormula conclusion; public Rule(final CNFFormula pPremise, final CNFFormula pConclusion) { this.premise = pPremise; this.conclusion = pConclusion; } public CNFFormula getPremise() { return this.premise; } public CNFFormula getConclusion() { return this.conclusion; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.premise); sb.append(" => "); sb.append(this.conclusion); return sb.toString(); } public Set<ConstantParam> getConstantParams() { Set<ConstantParam> constants = new HashSet<>(); constants.addAll(this.premise.getConstantParams()); constants.addAll(this.conclusion.getConstantParams()); return constants; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/Type.java
package ai.libs.jaicore.logic.fol.structure; import java.io.Serializable; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Set; @SuppressWarnings("serial") public class Type implements Serializable { private final String name; private final List<Type> superTypeList; private final List<Type> subTypeList; private final List<Type> subTypeOfBuffer; private final List<Type> supTypeOfBuffer; Type(final String name, final Collection<Type> parentTypeList) { // call plain constructor this(name); if (parentTypeList != null) { this.superTypeList.addAll(parentTypeList); for (Type parentType : parentTypeList) { parentType.subTypeList.add(this); } } } Type(final String name, final Type parentType) { // call plain constructor this(name); if (parentType != null) { this.superTypeList.add(parentType); parentType.subTypeList.add(this); } } public Type(final String name) { // no legal type definition if (name.trim().isEmpty()) { throw new IllegalArgumentException(); } // assign type definition this.name = name; // initialize lists this.subTypeList = new LinkedList<>(); this.superTypeList = new LinkedList<>(); this.supTypeOfBuffer = new LinkedList<>(); this.subTypeOfBuffer = new LinkedList<>(); } public String getName() { return this.name; } public void addSubType(final Type newSubType) { if (this.isSubTypeOf(newSubType)) { throw new IllegalArgumentException("Cannot add " + newSubType + " as a sub-type of " + this + ", because the relation already exists the other way around."); } newSubType.superTypeList.add(this); this.subTypeList.add(newSubType); } public void removeSubType(final Type removeSubType) { removeSubType.superTypeList.remove(this); this.subTypeList.remove(removeSubType); } public List<Type> getDirectSubTypes() { return this.subTypeList; } public List<Type> getAllSubTypes() { List<Type> allSubTypeList = new LinkedList<>(this.getDirectSubTypes()); for (Type subType : this.getDirectSubTypes()) { allSubTypeList.addAll(subType.getAllSubTypes()); } return allSubTypeList; } public List<Type> getAllSubTypesIncl() { List<Type> allSubTypeInclList = this.getAllSubTypes(); allSubTypeInclList.add(this); return allSubTypeInclList; } public void addSuperType(final Type newSuperType) { if (this.isSuperTypeOf(newSuperType)) { throw new IllegalArgumentException("Cannot add " + newSuperType + " as a super-type of " + this + ", because the relation already exists the other way around."); } newSuperType.subTypeList.add(this); this.superTypeList.add(newSuperType); } public void removeSuperType(final Type removeSuperType) { removeSuperType.subTypeList.remove(this); this.superTypeList.remove(removeSuperType); } public List<Type> getDirectSuperTypes() { return this.superTypeList; } public boolean isRootType() { return this.superTypeList.isEmpty(); } /** * Given the parameter typeToCheck, this method checks whether typeToCheck is actually a sub type of the current object. Thus, it checks whether this is a super type of typeToCheck. * * @param typeToCheck * A DataType to check whether it is a sub-type of this DataType. * * @return It returns true iff the given DataType typeToCheck is a sub-type of this DataType. */ public boolean isSuperTypeOf(final Type typeToCheck) { // robustness check if (typeToCheck == null) { throw new IllegalArgumentException("Null is not a feasible type for this function"); } if (typeToCheck == this || this.subTypeOfBuffer.indexOf(typeToCheck) >= 0) { return true; } assert !this.subTypeList.contains(this) : ("Type " + this.getName() + " contains itself as a sub-type!"); for (Type subType : this.subTypeList) { if (subType.isSuperTypeOf(typeToCheck)) { this.subTypeOfBuffer.add(typeToCheck); return true; } } return false; } /** * Given the parameter typeToCheck, this method checks whether typeToCheck is actually a super type of the current object. Thus, it checks whether this is a sub type of typeToCheck. * * @param typeToCheck * A DataType to check whether it is a super type of this DataType * * @return It returns true iff the given DataType typeToCheck is a super type of this DataType. */ public boolean isSubTypeOf(final Type typeToCheck) { if (typeToCheck == this || this.supTypeOfBuffer.indexOf(typeToCheck) >= 0) { return true; } if (!this.superTypeList.isEmpty() && typeToCheck.isSuperTypeOf(this)) { this.supTypeOfBuffer.add(typeToCheck); return true; } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.name + ";"); for (Type superType : this.superTypeList) { sb.append(superType.name); if (this.superTypeList.indexOf(superType) < this.superTypeList.size() - 1) { sb.append('&'); } } return sb.toString(); } public void addSuperType(final Set<Type> parentTypeCollection) { for (Type superType : parentTypeCollection) { this.addSuperType(superType); } } /** * Searches in data type DAG for a greatest sub type of the given two types. * * @param type * Type to check for sub type relation. * @param type2 * Type to check for sub type relation. * @return Returns the concreter type if the two types are related to each other. Otherwise, it returns null. */ public static Type getGreatestSubType(final Type type, final Type type2) { if (type.isSubTypeOf(type2)) { return type; } else { if (type2.isSubTypeOf(type)) { return type2; } else { return null; } } } public List<Type> getInheritanceHierarchyIncludingType() { List<Type> inheritanceList = new LinkedList<>(); inheritanceList.add(this); for (Type superType : this.superTypeList) { inheritanceList.addAll(superType.getInheritanceHierarchyIncludingType()); } return inheritanceList; } public List<Type> getConcretesHierarchyIncludingType() { List<Type> concretesList = new LinkedList<>(); concretesList.add(this); for (Type subType : this.subTypeList) { concretesList.addAll(subType.getConcretesHierarchyIncludingType()); } return concretesList; } @Override public int hashCode() { return this.name.hashCode(); } @Override public boolean equals(final Object o) { if (!(o instanceof Type)) { return false; } Type other = (Type) o; return this.name.equals(other.name); } public List<Type> getAllSuperTypes() { List<Type> superTypes = new LinkedList<>(this.getDirectSuperTypes()); for(Type superType : this.getDirectSuperTypes()) { superTypes.addAll(superType.getAllSuperTypesIncl()); } return superTypes; } public List<Type> getAllSuperTypesIncl() { List<Type> superTypes = new LinkedList<>(this.getAllSuperTypes()); superTypes.add(this); return superTypes; } public String serialize() { StringBuilder sb = new StringBuilder(); sb.append(this.getName()); sb.append(";"); if (!this.isRootType()) { for (Type superType : this.getDirectSuperTypes()) { sb.append(superType.getName()); if (this.getDirectSuperTypes().indexOf(superType) < this.getDirectSuperTypes().size() - 1) { sb.append("&"); } } } return sb.toString(); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/TypeModule.java
package ai.libs.jaicore.logic.fol.structure; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class TypeModule { private final Map<String, Type> typeMap = new HashMap<>(); private final Map<String,ConstantParam> constants = new HashMap<>(); public TypeModule() {} public TypeModule(final Collection<Type> types) { for (Type type : types) { this.typeMap.put(type.getName(), type); } } public Type getType(final String nameOfType) { if (nameOfType.trim().isEmpty()) { throw new IllegalArgumentException("Empty string is no valid name for a datatype."); } return this.typeMap.computeIfAbsent(nameOfType, Type::new); } public int size() { return this.typeMap.size(); } public Collection<Type> getAllTypes() { return this.typeMap.values(); } public List<Type> getListOfAllTypes() { List<Type> result = new LinkedList<>(); result.addAll(this.typeMap.values()); return result; } public void merge(final TypeModule typeModule) { for (Type otherType : typeModule.getAllTypes()) { this.getType(otherType.getName()); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Type type : this.typeMap.values()) { sb.append(type); sb.append("\n"); } return sb.toString(); } public void setConstantType(final String constant, final Type type) { this.constants.put(constant, new ConstantParam(constant, type)); } public Type getConstantType(final String constant) { if (!this.constants.containsKey(constant)) { throw new IllegalArgumentException("Constant " + constant + " not found!"); } return this.constants.get(constant).getType(); } public Collection<ConstantParam> getConstants() { return this.constants.values(); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/structure/VariableParam.java
package ai.libs.jaicore.logic.fol.structure; /** * A variable parameter of a literal. * * @author mbunse, wever */ @SuppressWarnings("serial") public class VariableParam extends LiteralParam { public VariableParam(final String name, final Type type) { super(name, type); } public VariableParam(final String name) { super(name); } public VariableParam(final VariableParam toBeCopied) { super(toBeCopied.getName(), toBeCopied.type); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.type == null) ? 0 : this.type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (!(obj instanceof VariableParam)) { return false; } return super.equals(obj); } @Override public String toString() { if (this.getType() != null) { return "<" + this.getName() + ":" + this.getType().getName() + ">"; } else { return "<" + this.getName() + ":undefined>"; } } @Override public Type getType() { return this.type; } @Override public void setType(final Type type) { this.type = type; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories/EvaluablePredicate.java
package ai.libs.jaicore.logic.fol.theories; import java.util.Collection; import java.util.List; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; public interface EvaluablePredicate { public Collection<List<ConstantParam>> getParamsForPositiveEvaluation(Monom state, ConstantParam... partialGrounding); public boolean isOracable(); public Collection<List<ConstantParam>> getParamsForNegativeEvaluation(Monom state, ConstantParam... partialGrounding); public boolean test(Monom state, ConstantParam... params); // usually we would evaluate ONLY the predicate with terms, but there may be terms that are described indirectly in the state. }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories/set/ContainsPredicate.java
package ai.libs.jaicore.logic.fol.theories.set; import java.util.Collection; import java.util.List; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.theories.EvaluablePredicate; public class ContainsPredicate implements EvaluablePredicate { @Override public boolean test(Monom state, ConstantParam... params) { String cluster = params[1].getName(); List<String> itemsInSet = SetTheoryUtil.getObjectsInSet(state, cluster); return itemsInSet.contains(params[0].getName()); } @Override public Collection<List<ConstantParam>> getParamsForPositiveEvaluation(Monom state, ConstantParam... partialGrounding) { throw new UnsupportedOperationException("NOT ORACABLE"); } @Override public Collection<List<ConstantParam>> getParamsForNegativeEvaluation(Monom state, ConstantParam... partialGrounding) { throw new UnsupportedOperationException("NOT ORACABLE"); } @Override public boolean isOracable() { return false; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories/set/NotEmptyPredicate.java
package ai.libs.jaicore.logic.fol.theories.set; import java.util.Collection; import java.util.List; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.theories.EvaluablePredicate; public class NotEmptyPredicate implements EvaluablePredicate { @Override public boolean test(Monom state, ConstantParam... params) { String cluster = params[0].getName(); long count = SetTheoryUtil.getObjectsInSet(state, cluster).size(); return count > 0; } @Override public Collection<List<ConstantParam>> getParamsForPositiveEvaluation(Monom state, ConstantParam... partialGrounding) { throw new UnsupportedOperationException("NOT ORACABLE"); } @Override public Collection<List<ConstantParam>> getParamsForNegativeEvaluation(Monom state, ConstantParam... partialGrounding) { throw new UnsupportedOperationException("NOT ORACABLE"); } @Override public boolean isOracable() { return false; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories/set/OneItemPredicate.java
package ai.libs.jaicore.logic.fol.theories.set; import java.util.Collection; import java.util.List; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.theories.EvaluablePredicate; public class OneItemPredicate implements EvaluablePredicate { @Override public boolean test(Monom state, ConstantParam... params) { String cluster = params[0].getName(); long count = SetTheoryUtil.getObjectsInSet(state, cluster).size(); return count == 1; } @Override public Collection<List<ConstantParam>> getParamsForPositiveEvaluation(Monom state, ConstantParam... partialGrounding) { throw new UnsupportedOperationException("NOT ORACABLE"); } @Override public Collection<List<ConstantParam>> getParamsForNegativeEvaluation(Monom state, ConstantParam... partialGrounding) { throw new UnsupportedOperationException("NOT ORACABLE"); } @Override public boolean isOracable() { return false; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories/set/PartitionPredicate.java
package ai.libs.jaicore.logic.fol.theories.set; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.theories.EvaluablePredicate; public class PartitionPredicate implements EvaluablePredicate { @Override public boolean test(final Monom state, final ConstantParam... params) { List<String> union = SetTheoryUtil.getObjectsInSet(state, params[0].getName()); List<String> p1 = SetTheoryUtil.getObjectsInSet(state, params[1].getName()); List<String> p2 = SetTheoryUtil.getObjectsInSet(state, params[2].getName()); return SetUtil.union(p1,p2).equals(union); } @Override public Collection<List<ConstantParam>> getParamsForPositiveEvaluation(final Monom state, final ConstantParam... partialGrounding) { List<String> p1 = partialGrounding[1] != null ? SetTheoryUtil.getObjectsInSet(state, partialGrounding[1].getName()) : null; List<String> p2 = partialGrounding[2] != null ? SetTheoryUtil.getObjectsInSet(state, partialGrounding[2].getName()) : null; if (p1 == null && p2 == null) { throw new IllegalArgumentException("At most one of the two last parameters must be null!"); } Collection<List<ConstantParam>> validGroundings = new ArrayList<>(); List<String> union = SetTheoryUtil.getObjectsInSet(state, partialGrounding[0].getName()); if (p1 == null) { validGroundings.add(Arrays.asList(partialGrounding[0], new ConstantParam(SetUtil.serializeAsSet(SetUtil.difference(union, p2))), partialGrounding[2])); } if (p2 == null) { validGroundings.add(Arrays.asList(partialGrounding[0], partialGrounding[1], new ConstantParam(SetUtil.serializeAsSet(SetUtil.difference(union, p1))))); } return validGroundings; } @Override public Collection<List<ConstantParam>> getParamsForNegativeEvaluation(final Monom state, final ConstantParam... partialGrounding) { return new ArrayList<>(); } @Override public boolean isOracable() { return true; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/theories/set/SetTheoryUtil.java
package ai.libs.jaicore.logic.fol.theories.set; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.Monom; public class SetTheoryUtil { private SetTheoryUtil() { // prevent instantiation of static util class. } public static List<String> getObjectsInSet(final Monom state, final String setDescriptor) { if (setDescriptor.startsWith("{") && setDescriptor.endsWith("}")) { return new ArrayList<>(SetUtil.unserializeSet(setDescriptor)); } return state.stream().filter(l -> l.getPropertyName().equals("in") && l.getParameters().get(1).getName().equals(setDescriptor)).map(l -> l.getConstantParams().get(0).getName()).collect(Collectors.toList()); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/ForwardChainer.java
package ai.libs.jaicore.logic.fol.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.algorithm.AAlgorithm; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.LiteralSet; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; /** * This algorithm answers the question for which groundings G of the variables * in $premise, G[$premise] follows from $factbase. This method does NOT adopt * the closed world assumption, i.e. !L in the premise can only be followed if L * is provably wrong in the factbase. * * @param factbase * @param conclusion * @return */ public class ForwardChainer extends AAlgorithm<ForwardChainingProblem, Collection<Map<VariableParam, LiteralParam>>> { private Logger logger = LoggerFactory.getLogger(ForwardChainer.class); private Monom conclusion; private Monom cwaRelevantNegativeLiterals; // contains the negative part of the conclusion IF CWA is active! private Monom factbase; private Literal chosenLiteral; private List<Map<VariableParam, LiteralParam>> possibleChoicesForLocalLiteral; private Monom remainingConclusion; private Map<VariableParam, LiteralParam> currentGroundingOfLocalLiteral; private Monom currentGroundRemainingConclusion; private ForwardChainer currentlyActiveSubFC; public ForwardChainer(final ForwardChainingProblem problem) { super(problem); if (problem.getConclusion().isEmpty()) { throw new IllegalArgumentException("Ill-defined forward chaining problem with empty conclusion!"); } } @Override /** * This is a recursive algorithm. It will only identify solutions for one of the * literals in the conclusion and invoke a new instance of ForwardChainer on the * rest. */ public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException { long start = System.currentTimeMillis(); switch (this.getState()) { /* initialize the algorithm for the most promising literal */ case CREATED: this.conclusion = this.getInput().getConclusion(); assert !this.conclusion.isEmpty() : "The algorithm should not be invoked with an empty conclusion"; this.factbase = this.getInput().getFactbase(); this.logger.info("Computing substitution for {}-conclusion that enable forward chaining from factbase of size {}. Enable trace for more detailed output.", this.conclusion.size(), this.factbase.size()); this.logger.trace("Conclusion is {}", this.conclusion); this.logger.trace("Factbase is {}", this.factbase); /* if CWA is active, store away all negative literals */ if (this.getInput().isCwa()) { /* decompose conclusion in positive and negative literals */ Monom positiveLiterals = new Monom(); Monom negativeLiterals = new Monom(); for (Literal l : this.conclusion) { if (l.isPositive()) { positiveLiterals.add(l); } else { negativeLiterals.add(l); } } this.conclusion = positiveLiterals; this.cwaRelevantNegativeLiterals = negativeLiterals; } /* select the literal that has the least options to be ground */ int currentlyFewestOptions = Integer.MAX_VALUE; long timeToPrepareCWAVersion = System.currentTimeMillis(); for (Literal nextLitealCandidate : this.conclusion) { this.checkAndConductTermination(); this.logger.debug("Considering {} as next literal for grounding.", nextLitealCandidate); long candidateGroundingStart = System.currentTimeMillis(); List<Map<VariableParam, LiteralParam>> choicesTmp = this.getGroundingsUnderWhichALiteralAppearsInFactBase(this.factbase, nextLitealCandidate, currentlyFewestOptions); this.logger.debug("Computation of {} groundings took {}ms.", choicesTmp.size(), System.currentTimeMillis() - candidateGroundingStart); if (choicesTmp.size() < currentlyFewestOptions) { this.chosenLiteral = nextLitealCandidate; this.possibleChoicesForLocalLiteral = choicesTmp; currentlyFewestOptions = choicesTmp.size(); if (currentlyFewestOptions == 0) { break; } } } assert this.chosenLiteral != null : "No literal has been chosen"; assert this.possibleChoicesForLocalLiteral != null : "List of possible choices for literal must not be null"; this.remainingConclusion = new Monom(); for (Literal l : this.conclusion) { if (!l.equals(this.chosenLiteral)) { this.remainingConclusion.add(l); } } long end = System.currentTimeMillis(); this.logger.debug("Selected literal {} with still unbound params {} that can be ground in {} ways in {}ms.", this.chosenLiteral, this.chosenLiteral.getVariableParams(), this.possibleChoicesForLocalLiteral.size(), end - timeToPrepareCWAVersion); this.logger.info("Initialized FC algorithm within {}ms.", end - start); return this.activate(); case ACTIVE: this.checkAndConductTermination(); /* if a sub-process is running, get its result and combine it with our current grounding for the local literal */ if (this.currentlyActiveSubFC != null) { this.logger.trace("Reuse currently active recursive FC as it may still have solutions ..."); NextBindingFoundEvent event = this.currentlyActiveSubFC.nextBinding(); if (event == null) { this.currentlyActiveSubFC = null; } else { Map<VariableParam, LiteralParam> subsolution = event.getGrounding(); this.logger.debug("Identified recursively determined sub-solution {}", subsolution); Map<VariableParam, LiteralParam> solutionToReturn = new HashMap<>(subsolution); solutionToReturn.putAll(this.currentGroundingOfLocalLiteral); assert this.verifyThatGroundingEnablesConclusion(this.factbase, this.currentGroundRemainingConclusion, solutionToReturn); /* if CWA is activated, we have to recheck whether the negative literals are ok */ if (this.getInput().isCwa() && this.doesCWADeductionFail(this.factbase, new LiteralSet(this.cwaRelevantNegativeLiterals, solutionToReturn))) { return new ForwardChainingFailedCWABindingEvent(this); } this.logger.info("Computed binding {} for {}-conclusion within {}ms", solutionToReturn, this.conclusion.size(), System.currentTimeMillis() - start); return new NextBindingFoundEvent(this, solutionToReturn); } } /* if we reach this part, we need to determine the next grounding of the local predicate, which we want to check (and for which we may want to recurse) */ this.logger.debug("Determine a new out of {} remaining groundings for {} to be analyzed.", this.possibleChoicesForLocalLiteral.size(), this.chosenLiteral); boolean foundAChoiceThatMightBeFeasible = false; while (!foundAChoiceThatMightBeFeasible && !this.possibleChoicesForLocalLiteral.isEmpty()) { this.checkAndConductTermination(); this.currentGroundingOfLocalLiteral = this.possibleChoicesForLocalLiteral.get(0); this.possibleChoicesForLocalLiteral.remove(0); this.logger.debug("Considering choice {}", this.currentGroundingOfLocalLiteral); Monom modifiedRemainingConclusion = new Monom(this.remainingConclusion, this.currentGroundingOfLocalLiteral); this.logger.trace("Checking whether one of the ground remaining conclusion {} is not in the state.", modifiedRemainingConclusion); if (!this.doesConclusionContainAGroundLiteralThatIsNotInFactBase(this.factbase, modifiedRemainingConclusion)) { foundAChoiceThatMightBeFeasible = true; this.currentGroundRemainingConclusion = modifiedRemainingConclusion; break; } } this.logger.debug("Selected grounding {}. {} possible other groundings remain.", this.currentGroundingOfLocalLiteral, this.possibleChoicesForLocalLiteral.size()); /* if no (more) groundings are possible for this literal and no feasible grounding was detected, return the algorithm finished event */ if (!foundAChoiceThatMightBeFeasible) { assert this.possibleChoicesForLocalLiteral.isEmpty() : "Collection of possible choices should be empty when no grounding was chosen!"; this.logger.debug("Finishing process for {}-conclusion since no (more) grounding is avilable for predicate {}.", this.conclusion.size(), this.chosenLiteral); return this.terminate(); } /* if the conclusion has size 1, return the current candidate. Otherwise recurse */ if (this.currentGroundRemainingConclusion.isEmpty()) { return new NextBindingFoundEvent(this, this.currentGroundingOfLocalLiteral); } else { this.logger.debug("Recurse to {}-conclusion", this.currentGroundRemainingConclusion.size()); ForwardChainingProblem subProblem = new ForwardChainingProblem(this.factbase, this.currentGroundRemainingConclusion, this.getInput().isCwa()); long startRecursiveCall = System.currentTimeMillis(); this.logger.debug("Finished recursion of {}-conclusion. Computation took {}ms", this.currentGroundRemainingConclusion.size(), System.currentTimeMillis() - startRecursiveCall); this.currentlyActiveSubFC = new ForwardChainer(subProblem); return new ForwardChainerRecursionEvent(this, this.chosenLiteral, this.currentGroundRemainingConclusion); } default: throw new IllegalStateException("Don't know how to behave in state " + this.getState()); } } @Override public Collection<Map<VariableParam, LiteralParam>> call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException { Collection<Map<VariableParam, LiteralParam>> mappings = new ArrayList<>(); NextBindingFoundEvent e; while ((e = this.nextBinding()) != null) { this.logger.info("Adding solution grounding {} to output set.", e.getGrounding()); mappings.add(e.getGrounding()); } return mappings; } public NextBindingFoundEvent nextBinding() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException { while (this.hasNext()) { IAlgorithmEvent e = this.nextWithException(); if (e instanceof NextBindingFoundEvent) { return (NextBindingFoundEvent) e; } } return null; } public Collection<Map<VariableParam, LiteralParam>> getSubstitutionsThatEnableForwardChaining(final Collection<Literal> factbase, final Collection<Literal> conclusion) { return this.getSubstitutionsThatEnableForwardChaining(factbase, new ArrayList<>(conclusion)); } public boolean doesConclusionContainAGroundLiteralThatIsNotInFactBase(final Collection<Literal> factbase, final Collection<Literal> conclusion) { for (Literal l : conclusion) { if (l.isGround() && !factbase.contains(l)) { return true; } } return false; } /** * * @param factbase * @param conclusion * @return true iff the conclusion contains a positive ground literal that is * NOT in the factbase or a negative ground literal that positively * occurs in the factbase */ public boolean doesCWADeductionFail(final Collection<Literal> factbase, final Collection<Literal> conclusion) { for (Literal l : conclusion) { if (!l.isGround()) { continue; } if (l.isPositive()) { if (!factbase.contains(l)) { return true; } } else { if (factbase.contains(l.clone().toggleNegation())) { return true; } } } return false; } public List<Map<VariableParam, LiteralParam>> getGroundingsUnderWhichALiteralAppearsInFactBase(final Collection<Literal> factbase, final Literal l, final int maxSubstitutions) { List<VariableParam> openParams = l.getVariableParams(); /* * if there are no open params, we do not need to make decisions here, so just * compute subsolutions */ this.logger.debug("Compute possible sub-groundings of the open parameters."); long start = System.currentTimeMillis(); List<Map<VariableParam, LiteralParam>> choices = new ArrayList<>(); if (openParams.isEmpty()) { choices.add(new HashMap<>()); } /* * otherwise, select literal from the factbase that could be used for * unification */ else { for (Literal fact : factbase) { if (!fact.getPropertyName().equals(l.getPropertyName()) || fact.isPositive() != l.isPositive()) { continue; } this.logger.trace("Considering known literal {} as a literal that can be used for grounding", fact); List<LiteralParam> factParams = fact.getParameters(); // should only contain constant params List<LiteralParam> nextLiteralParams = l.getParameters(); Map<VariableParam, LiteralParam> submap = new HashMap<>(); /* create a substitution that grounds the rest of the literal */ boolean paramsCanBeMatched = true; for (int i = 0; i < factParams.size(); i++) { if (nextLiteralParams.get(i) instanceof VariableParam) { submap.put((VariableParam) nextLiteralParams.get(i), factParams.get(i)); } else if (!nextLiteralParams.get(i).equals(factParams.get(i))) { paramsCanBeMatched = false; break; } } if (!paramsCanBeMatched) { continue; } this.logger.trace("Adding {} as a possible such grounding.", submap); choices.add(submap); if (choices.size() >= maxSubstitutions) { this.logger.debug("Reached maximum number {} of required substitutions. Returning what we have so far.", maxSubstitutions); return choices; } } } this.logger.debug("Done. Computation of {} groundings took {}ms", choices.size(), System.currentTimeMillis() - start); return choices; } public boolean verifyThatGroundingEnablesConclusion(final Collection<Literal> factbase, final Collection<Literal> conclusion, final Map<VariableParam, LiteralParam> grounding) { for (Literal l : conclusion) { Literal lg = new Literal(l, grounding); if (factbase.contains(lg) != l.isPositive()) { this.logger.error("Literal {} in conclusion ground to {} does not follow from state: ", l, lg); factbase.stream().sorted((l1, l2) -> l1.toString().compareTo(l2.toString())).forEach(lit -> this.logger.info("\t{}", lit)); return false; } } return true; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/ForwardChainerRecursionEvent.java
package ai.libs.jaicore.logic.fol.util; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; public class ForwardChainerRecursionEvent extends AAlgorithmEvent { private Literal local; private Monom remainingConclusion; public ForwardChainerRecursionEvent(final IAlgorithm<?, ?> algorithm, final Literal local, final Monom remainingConclusion) { super(algorithm); this.local = local; this.remainingConclusion = remainingConclusion; } public Literal getLocal() { return this.local; } public void setLocal(final Literal local) { this.local = local; } public Monom getRemainingConclusion() { return this.remainingConclusion; } public void setRemainingConclusion(final Monom remainingConclusion) { this.remainingConclusion = remainingConclusion; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/ForwardChainingFailedCWABindingEvent.java
package ai.libs.jaicore.logic.fol.util; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; /** * This is used if a binding is found that is ok for positive literals, but negative literals of the conclusions are in the factbase. * */ public class ForwardChainingFailedCWABindingEvent extends AAlgorithmEvent { public ForwardChainingFailedCWABindingEvent(final IAlgorithm<?, ?> algorithm) { super(algorithm); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/ForwardChainingProblem.java
package ai.libs.jaicore.logic.fol.util; import ai.libs.jaicore.logic.fol.structure.Monom; public class ForwardChainingProblem { private final Monom factbase; private final Monom conclusion; private final boolean cwa; public ForwardChainingProblem(Monom factbase, Monom conclusion, boolean cwa) { super(); this.factbase = factbase; this.conclusion = conclusion; this.cwa = cwa; } public Monom getFactbase() { return factbase; } public Monom getConclusion() { return conclusion; } public boolean isCwa() { return cwa; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/LiteralStringParser.java
package ai.libs.jaicore.logic.fol.util; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.InterpretedLiteral; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.LiteralSet; import ai.libs.jaicore.logic.fol.structure.VariableParam; public class LiteralStringParser { private static Pattern basicPattern = Pattern.compile("(!|~)?(.*)\\(([^\\)]*)\\)"); private LiteralStringParser() { /* do nothing */ } public static LiteralSet convertStringToLiteralSetWithConst(final String literalSetString, final Set<String> evaluablePredicates) { LiteralSet literalSet = new LiteralSet(); String[] literals = literalSetString.split("&"); if (!(literals.length == 1 && literals[0].isEmpty())) { for (int i = 0; i < literals.length; i++) { literalSet.add(convertStringToLiteralWithConst(literals[i], evaluablePredicates)); } } return literalSet; } public static Literal convertStringToLiteralWithConst(final String literalString, final Set<String> evaluablePredicates) { String string = literalString.replace(" ", ""); string = string.trim(); Matcher matcher = basicPattern.matcher(string); if (!matcher.find()) { return null; } MatchResult results = matcher.toMatchResult(); String predicateName = results.group(2); // position 2 is predicate name String[] paramsAsStrings = results.group(3).split(","); // position 3 are the variables List<LiteralParam> params = new LinkedList<>(); for (int i = 0; i < paramsAsStrings.length; i++) { String param = paramsAsStrings[i].trim(); params.add(param.startsWith("'") ? new ConstantParam(param.replace("'", "")) : new VariableParam(param)); } /* try to match suffix of predicate name */ if (evaluablePredicates.contains(predicateName)) { return new InterpretedLiteral(predicateName, params, results.group(1) == null); } else { return new Literal(predicateName, params, results.group(1) == null); } } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/LogicUtil.java
package ai.libs.jaicore.logic.fol.util; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Clause; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.LiteralSet; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.Type; import ai.libs.jaicore.logic.fol.structure.VariableParam; /** * Utility class for the logic package. * * @author fmohr, mbunse */ public class LogicUtil { private static final Logger logger = LoggerFactory.getLogger(LogicUtil.class); private LogicUtil() { /* do nothing */ } /** * @param a * The literal set A. * @param b * The literal set B. * @return The intersection of A and B. */ public static LiteralSet intersectionOfLiteralSets(final LiteralSet a, final LiteralSet b) { return new LiteralSet(SetUtil.intersection(a, b)); } /** * @param a * The literal set A. * @param b * The literal set B. * @return The difference A \ B. */ public static LiteralSet differenceOfLiteralSets(final LiteralSet a, final LiteralSet b) { return new LiteralSet(SetUtil.difference(a, b)); } public static boolean doesPremiseContainAGroundLiteralThatIsNotInFactBase(final Collection<Literal> factbase, final Collection<Literal> premise) { for (Literal l : premise) { if (l.isGround() && !factbase.contains(l)) { return true; } } return false; } public static boolean doesPremiseContainAGroundLiteralThatIsNotInFactBaseCWA(final Collection<Literal> factbase, final Collection<Literal> premise) { for (Literal l : premise) { if (!l.isGround()) { continue; } if (l.isPositive()) { if (!factbase.contains(l)) { return true; } } else { if (factbase.contains(l.clone().toggleNegation())) { return true; } } } return false; } public static boolean verifyThatGroundingEnablesPremise(final Collection<Literal> factbase, final Collection<Literal> premise, final Map<VariableParam, LiteralParam> grounding) { for (Literal l : premise) { Literal lg = new Literal(l, grounding); if (factbase.contains(lg) != l.isPositive()) { logger.error("Literal {} in premise ground to {} does not follow from state: ", l, lg); factbase.stream().sorted((l1, l2) -> l1.toString().compareTo(l2.toString())).forEach(lit -> logger.info("\t{}", lit)); return false; } } return true; } public static boolean canLiteralBeUnifiedWithLiteralFromDatabase(final Collection<Literal> set, final Literal literal) { for (Literal candidate : set) { if (areLiteralsUnifiable(candidate, literal)) { return true; } } return false; } public static boolean areLiteralsUnifiable(final Literal l1, final Literal l2) { if (!l1.getPropertyName().equals(l2.getPropertyName())) { return false; } List<LiteralParam> paramsOfL1 = l1.getParameters(); List<LiteralParam> paramsOfL2 = l2.getParameters(); for (int i = 0; i < paramsOfL1.size(); i++) { if (paramsOfL1.get(i) instanceof ConstantParam && paramsOfL2.get(i) instanceof ConstantParam && !paramsOfL1.get(i).equals(paramsOfL2.get(i))) { return false; } } return true; } public static LiteralParam parseParamName(String name) { boolean isConstant = false; if (name.contains("'")) { if (!name.startsWith("'") || !name.endsWith("'") || name.substring(1, name.length() - 1).contains("'")) { throw new IllegalArgumentException("A parameter that contains simple quotes must contain EXACTLY two such quotes (one in the beginning, one in the end). Such a name indicates a constant!"); } name = name.substring(1, name.length() - 1); isConstant = true; } Type type = null; if (name.contains(":")) { String[] parts = name.split(":"); if (parts.length != 2) { throw new IllegalArgumentException("The name of a parameter must contain at most one colon! A colon is used to separate the name from the type!"); } name = parts[0]; type = new Type(parts[1]); } return isConstant ? new ConstantParam(name, type) : new VariableParam(name, type); } public static boolean evalEquality(final Literal l) { List<LiteralParam> params = l.getParameters(); if (!(params.get(0) instanceof ConstantParam) || !(params.get(1) instanceof ConstantParam)) { throw new IllegalArgumentException("Equality cannot be evaluated for non-constants!"); } return params.get(0).equals(params.get(1)) == l.isPositive(); } public static CNFFormula evalEqualityLiteralsUnderUNA(final CNFFormula set) { CNFFormula newFormula = new CNFFormula(); for (Clause c : set) { Clause cNew = new Clause(); for (Literal l : c) { if (l.getPropertyName().equals("=")) { List<LiteralParam> params = l.getParameters(); if (params.get(0) instanceof ConstantParam && params.get(1) instanceof ConstantParam) { if (params.get(0).equals(params.get(1)) != l.isPositive()) { return new CNFFormula(new Monom("A & !A")); } } else { cNew.add(l); } } else { cNew.add(l); } } if (!cNew.isEmpty()) { newFormula.add(cNew); } } return newFormula; } public static String getSortedLiteralSetDescription(final Collection<? extends Literal> collection) { return collection.stream().sorted((l1, l2) -> l1.toString().compareTo(l2.toString() )).map(l -> "\n\t- " + l).collect(Collectors.joining()); } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/NextBindingFoundEvent.java
package ai.libs.jaicore.logic.fol.util; import java.util.Map; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.VariableParam; public class NextBindingFoundEvent extends AAlgorithmEvent { private final Map<VariableParam, LiteralParam> grounding; public NextBindingFoundEvent(final IAlgorithm<?, ?> algorithm, final Map<VariableParam, LiteralParam> grounding) { super(algorithm); this.grounding = grounding; } public Map<VariableParam, LiteralParam> getGrounding() { return this.grounding; } }
0
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol
java-sources/ai/libs/jaicore-logic/0.2.7/ai/libs/jaicore/logic/fol/util/TypeUtil.java
package ai.libs.jaicore.logic.fol.util; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.TypeModule; public class TypeUtil { private TypeUtil() { /* avoid instantiation */ } private static final Logger LOGGER = LoggerFactory.getLogger(TypeUtil.class); public static final String GODFATHER_TYPE = "Thing"; private static TypeModule typeMod; public static void setTypeModule(final TypeModule typeModule) { TypeUtil.typeMod = typeModule; } public static void defineGodfatherDataTypes(final Literal l) { checkTypeModule(); for (LiteralParam p : l.getParameters()) { if (p.getType() == null) { p.setType(typeMod.getType(GODFATHER_TYPE)); } } } public static void defineGodfatherDataTypes(final Set<? extends Literal> m) { for (Literal l : m) { defineGodfatherDataTypes(l); } } public static void defineGodfatherDataTypes(final List<? extends Literal> m) { for (Literal l : m) { defineGodfatherDataTypes(l); } } private static void checkTypeModule() { if (typeMod == null) { typeMod = new TypeModule(); LOGGER.warn("TypeModule in DataTypeUtil has not been set. Now, operating on own TypeModule"); } } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/bayesianinference/ABayesianInferenceAlgorithm.java
package ai.libs.jaicore.math.bayesianinference; import java.util.Collection; import java.util.Map; import java.util.Set; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import ai.libs.jaicore.basic.algorithm.AAlgorithm; import ai.libs.jaicore.basic.sets.SetUtil; public abstract class ABayesianInferenceAlgorithm extends AAlgorithm<BayesianInferenceProblem, DiscreteProbabilityDistribution> { protected final BayesNet net = this.getInput().getNetwork(); protected final Collection<String> queryVariables = this.getInput().getQueryVariables(); protected final Map<String, Boolean> evidence = this.getInput().getEvidenceVariables(); protected final Set<String> allModelVariables = this.net.getMap().keySet(); protected final Collection<String> hiddenVariables = SetUtil.difference(this.allModelVariables, SetUtil.union(this.queryVariables, this.evidence.keySet())); private DiscreteProbabilityDistribution distribution = new DiscreteProbabilityDistribution(); protected ABayesianInferenceAlgorithm(final BayesianInferenceProblem input) { super(input); } public BayesNet getNet() { return this.net; } public Collection<String> getQueryVariables() { return this.queryVariables; } public Map<String, Boolean> getEvidence() { return this.evidence; } public Set<String> getAllModelVariables() { return this.allModelVariables; } public Collection<String> getHiddenVariables() { return this.hiddenVariables; } public DiscreteProbabilityDistribution getDistribution() { return this.distribution; } protected void setDistribution(final DiscreteProbabilityDistribution distribution) { this.distribution = distribution; } @Override public DiscreteProbabilityDistribution call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { this.nextWithException(); this.distribution = this.distribution.getNormalizedCopy(); return this.distribution; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/bayesianinference/BayesNet.java
package ai.libs.jaicore.math.bayesianinference; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.graph.Graph; public class BayesNet implements ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(BayesNet.class); private Map<String, Map<Set<String>, Double>> map = new HashMap<>(); private Graph<String> net = new Graph<>(); public void addNode(final String name) { this.net.addItem(name); } public void addDependency(final String child, final String parent) { this.net.addEdge(parent, child); } public void addProbability(final String node, final Collection<String> parentsThatAreTrue, final double probability) { if (!this.net.hasItem(node)) { throw new IllegalArgumentException("Cannot add probability for unknown node " + node); } this.map.computeIfAbsent(node, n -> new HashMap<>()).put(new HashSet<>(parentsThatAreTrue), probability); } public void addProbability(final String node, final double probability) { if (!this.net.getPredecessors(node).isEmpty()) { throw new IllegalArgumentException("Cannot define prior on non-root node " + node); } this.addProbability(node, new HashSet<>(), probability); } public boolean isWellDefined() throws InterruptedException { for (String node : this.net.getItems()) { if (!this.isProbabilityTableOfNodeWellDefined(node)) { return false; } } return true; } public boolean isProbabilityTableOfNodeWellDefined(final String node) throws InterruptedException { /* compute cartesian product of parent values */ Collection<String> parents = this.net.getPredecessors(node); if (parents.isEmpty()) { if (!this.map.containsKey(node) || this.map.get(node).size() != 1) { this.logger.error("{} has no probability map associated", node); return false; } double prob = this.map.get(node).get(new HashSet<>()); return prob >= 0 && prob <= 1; } else { Collection<Collection<String>> powerset = SetUtil.powerset(parents); /* for each tuple, check whether the probability is defined */ if (!this.map.containsKey(node)) { this.logger.error("{} has no probability map associated", node); return false; } Map<Set<String>, Double> tableOfNode = this.map.get(node); for (Collection<String> activeParents : powerset) { Set<String> activeParentsAsSet = new HashSet<>(activeParents); if (!tableOfNode.containsKey(activeParentsAsSet)) { this.logger.error("Entry {} not contained.", activeParents); return false; } double prob = tableOfNode.get(activeParentsAsSet); if (prob < 0 || prob > 1) { this.logger.error("Invalid probability {}", prob); return false; } } return true; } } public Map<String, Map<Set<String>, Double>> getMap() { return this.map; } public Graph<String> getNet() { return this.net; } public double getProbabilityOfPositiveEvent(final String node, final Set<String> event) { Set<String> relevantSubset = new HashSet<>(SetUtil.intersection(event, this.net.getPredecessors(node))); return this.map.get(node).get(relevantSubset); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/bayesianinference/BayesianInferenceProblem.java
package ai.libs.jaicore.math.bayesianinference; import java.util.Collection; import java.util.Map; public class BayesianInferenceProblem { private final BayesNet network; private final Map<String, Boolean> evidenceVariables; private final Collection<String> queryVariables; public BayesianInferenceProblem(final BayesNet network, final Map<String, Boolean> evidenceVariables, final Collection<String> queryVariables) { super(); this.network = network; this.evidenceVariables = evidenceVariables; this.queryVariables = queryVariables; } public BayesNet getNetwork() { return this.network; } public Map<String, Boolean> getEvidenceVariables() { return this.evidenceVariables; } public Collection<String> getQueryVariables() { return this.queryVariables; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/bayesianinference/DiscreteProbabilityDistribution.java
package ai.libs.jaicore.math.bayesianinference; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import ai.libs.jaicore.basic.sets.SetUtil; public class DiscreteProbabilityDistribution { private final List<String> variables = new ArrayList<>(); private final Map<Set<String>, Double> probabilities = new HashMap<>(); public DiscreteProbabilityDistribution() { super(); } public void addProbability(final Collection<String> variablesThatAreTrue, final double probability) { for (String newVar : SetUtil.difference(variablesThatAreTrue, this.variables)) { this.variables.add(newVar); } this.probabilities.put(variablesThatAreTrue instanceof Set ? (Set<String>)variablesThatAreTrue : new HashSet<>(variablesThatAreTrue), probability); } public Map<Set<String>, Double> getProbabilities() { return this.probabilities; } public List<String> getVariables() { return this.variables; } public DiscreteProbabilityDistribution getNormalizedCopy() { /* prepare coefficients for linear equation system (with one constraint) */ double sum = 0; List<Set<String>> assignments = new ArrayList<>(); for (Entry<Set<String>, Double> prob : this.probabilities.entrySet()) { sum += prob.getValue(); assignments.add(prob.getKey()); } if (sum == 0) { throw new IllegalStateException("Cannot normalize a distribution with zero mass."); } /* compute alpha */ double alpha = 1.0 / sum; DiscreteProbabilityDistribution newDist = new DiscreteProbabilityDistribution(); for (Set<String> assignment : assignments) { newDist.addProbability(assignment, this.probabilities.get(assignment) * alpha); } return newDist; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/bayesianinference/DiscreteProbabilityDistributionPrinter.java
package ai.libs.jaicore.math.bayesianinference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import ai.libs.jaicore.basic.sets.LDSRelationComputer; import ai.libs.jaicore.basic.sets.RelationComputationProblem; import ai.libs.jaicore.logging.LoggerUtil; public class DiscreteProbabilityDistributionPrinter { public String getTable(final DiscreteProbabilityDistribution d) { StringBuilder sb = new StringBuilder(); /* create header */ List<String> vars = new ArrayList<>(d.getVariables()); for (String var : vars) { sb.append(var); sb.append(" | "); } sb.append(" P "); int len = sb.length(); sb.append("\n"); for (int i = 0; i < len; i++) { sb.append("-"); } sb.append("\n"); /* create one line for every combo */ List<List<Integer>> binaryVector = new ArrayList<>(); int n = vars.size(); for (int i = 0; i < n; i++) { binaryVector.add(Arrays.asList(0, 1)); } RelationComputationProblem<Integer> prob = new RelationComputationProblem<>(binaryVector); List<List<Integer>> combos; try { combos = new LDSRelationComputer<>(prob).call(); for (List<Integer> truthVector : combos) { Set<String> activeVariables = new HashSet<>(); for (int i = 0; i < n; i++) { int val = truthVector.get(i); if (val == 1) { activeVariables.add(vars.get(i)); } sb.append(val + " | "); } sb.append(d.getProbabilities().get(activeVariables)); sb.append("\n"); } return sb.toString(); } catch (AlgorithmTimeoutedException | AlgorithmExecutionCanceledException e) { return LoggerUtil.getExceptionInfo(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return LoggerUtil.getExceptionInfo(e); } } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/bayesianinference/EnumerationBasedBayesianInferenceSolver.java
package ai.libs.jaicore.math.bayesianinference; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import ai.libs.jaicore.basic.sets.SetUtil; public class EnumerationBasedBayesianInferenceSolver extends ABayesianInferenceAlgorithm { public EnumerationBasedBayesianInferenceSolver(final BayesianInferenceProblem input) { super(input); } @Override public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { /* get hidden variables */ List<String> hiddenVariableOrder = new ArrayList<>(this.hiddenVariables); Map<String, Boolean> evidenceAssignment = new HashMap<>(this.evidence); /* create all combinations for query variables */ Collection<Collection<String>> entries = SetUtil.powerset(this.queryVariables); for (Collection<String> positiveQueryVariables : entries) { Map<String, Boolean> initAssignment = new HashMap<>(evidenceAssignment); for (String var : this.queryVariables) { initAssignment.put(var, positiveQueryVariables.contains(var)); } double prob = this.sumProbability(hiddenVariableOrder, 0, initAssignment); this.getDistribution().addProbability(positiveQueryVariables, prob); } return null; } public double sumProbability(final List<String> hiddenVariables, final int indexOfHiddenVariableToSum, final Map<String, Boolean> partialAssignment) { /* if the assignment is complete, calculate the prob from the network */ Set<String> event = partialAssignment.keySet().stream().filter(partialAssignment::get).collect(Collectors.toSet()); if (indexOfHiddenVariableToSum == hiddenVariables.size()) { double product = 1; for (String var : this.allModelVariables) { double factor = this.net.getProbabilityOfPositiveEvent(var, event); if (!event.contains(var)) { factor = 1 - factor; } product *= factor; } return product; } /* otherwise branch over the hidden variables */ String branchVariable = hiddenVariables.get(indexOfHiddenVariableToSum); partialAssignment.put(branchVariable, false); double sum = 0; sum += this.sumProbability(hiddenVariables, indexOfHiddenVariableToSum + 1, partialAssignment); partialAssignment.put(branchVariable, true); sum += this.sumProbability(hiddenVariables, indexOfHiddenVariableToSum + 1, partialAssignment); return sum; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/bayesianinference/VariableElimination.java
package ai.libs.jaicore.math.bayesianinference; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.graph.Graph; public class VariableElimination extends ABayesianInferenceAlgorithm { private class Factor { private DiscreteProbabilityDistribution subDistribution; public Factor(final DiscreteProbabilityDistribution subDistribution) { super(); this.subDistribution = subDistribution; } } private List<Factor> factors = new ArrayList<>(); public VariableElimination(final BayesianInferenceProblem input) { super(input); } public List<String> preprocessVariables() { /* create a copy of the BN with which we want to work */ Graph<String> reducedGraph = new Graph<>(this.net.getNet()); /* remove irrelevant vars */ boolean variableRemoved; do { variableRemoved = false; Collection<String> sinks = reducedGraph.getSinks(); for (String sink : sinks) { if (!this.queryVariables.contains(sink) && !this.evidence.containsKey(sink)) { reducedGraph.removeItem(sink); variableRemoved = true; } } } while (variableRemoved); /* sort variables by order in network */ List<String> vars = new ArrayList<>(); while (!reducedGraph.isEmpty()) { Collection<String> sinks = reducedGraph.getSinks(); for (String var : sinks) { vars.add(var); reducedGraph.removeItem(var); } } return vars; } @Override public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { List<String> relevantAndOrderedVariables = this.preprocessVariables(); for (String var : relevantAndOrderedVariables) { this.factors.add(this.makeFactor(var, this.evidence)); if (this.hiddenVariables.contains(var)) { this.factors = this.sumOut(var, this.factors); } } this.setDistribution(this.multiply(this.factors).getNormalizedCopy()); return null; } private Factor makeFactor(final String var, final Map<String, Boolean> evidence) throws InterruptedException { /* determine variables that are inputs for this factor (all non-evident parents and the variable itself if it is not evidence) */ Collection<String> inputVariables = SetUtil.difference(this.net.getNet().getPredecessors(var), evidence.keySet()); Set<String> trueEvidenceVariables = this.net.getNet().getPredecessors(var).stream().filter(k -> evidence.containsKey(k) && evidence.get(k)).collect(Collectors.toSet()); boolean branchOverQueryVar = !evidence.keySet().contains(var); /* now compute the probabilities for all possible input combinations */ DiscreteProbabilityDistribution factorDistribution = new DiscreteProbabilityDistribution(); Collection<Collection<String>> factorEntries = SetUtil.powerset(inputVariables); for (Collection<String> event : factorEntries) { Set<String> eventWithEvidence = new HashSet<>(event); eventWithEvidence.addAll(trueEvidenceVariables); /* if the var is not part of the evidence */ if (branchOverQueryVar) { double probWithPosVal = this.net.getProbabilityOfPositiveEvent(var, eventWithEvidence); double probWithNegVal = 1 - probWithPosVal; factorDistribution.addProbability(event, probWithNegVal); Set<String> eventWithPositiveVar = new HashSet<>(event); eventWithPositiveVar.add(var); factorDistribution.addProbability(eventWithPositiveVar, probWithPosVal); } /* the var is part of the evidence */ else { double prob = -1; boolean wantPositiveProb = evidence.get(var); if (wantPositiveProb) { prob = this.net.getProbabilityOfPositiveEvent(var, eventWithEvidence); } else { prob = 1 - this.net.getProbabilityOfPositiveEvent(var, eventWithEvidence); } factorDistribution.addProbability(event, prob); } } return new Factor(factorDistribution); } private List<Factor> sumOut(final String var, final List<Factor> factors) throws InterruptedException { /* determine which factors will be eliminated and which stay */ List<Factor> newFactors = new ArrayList<>(); List<Factor> eliminatedFactors = new ArrayList<>(); for (Factor f : factors) { if (!f.subDistribution.getVariables().contains(var)) { newFactors.add(f); } else { eliminatedFactors.add(f); } } /* first build point-wise product of distributions */ DiscreteProbabilityDistribution productDistribution = eliminatedFactors.size() > 1 ? this.multiply(eliminatedFactors) : eliminatedFactors.get(0).subDistribution; /* compute distribution for elimination factor */ DiscreteProbabilityDistribution distOfNewFactor = new DiscreteProbabilityDistribution(); Collection<String> remainingVariablesInFactor = productDistribution.getVariables(); remainingVariablesInFactor.remove(var); Collection<Collection<String>> entriesInReducedFactor = SetUtil.powerset(remainingVariablesInFactor); for (Collection<String> entry : entriesInReducedFactor) { Set<String> event = new HashSet<>(entry); double probForEventWithVariableIsNegative = productDistribution.getProbabilities().get(event); event.add(var); double probForEventWithVariableIsPositive = productDistribution.getProbabilities().get(event); event.remove(var); distOfNewFactor.addProbability(event, probForEventWithVariableIsNegative + probForEventWithVariableIsPositive); } newFactors.add(new Factor(distOfNewFactor)); return newFactors; } public DiscreteProbabilityDistribution multiply(final Collection<Factor> factors) throws InterruptedException { DiscreteProbabilityDistribution current = null; for (Factor f : factors) { if (current != null) { current = this.multiply(current, f.subDistribution); } else { current = f.subDistribution; } } return current; } public DiscreteProbabilityDistribution multiply(final DiscreteProbabilityDistribution f1, final DiscreteProbabilityDistribution f2) throws InterruptedException { /* first determine variables that occur in the product */ Set<String> variables = new HashSet<>(); variables.addAll(f1.getVariables()); variables.addAll(f2.getVariables()); /* now compute the possible combinations of variables in the intersection (these will be the patterns to match each of the two tables) */ List<String> intersectionVariables = new ArrayList<>(SetUtil.intersection(f1.getVariables(), f2.getVariables())); Collection<Collection<String>> commonVariableCombinations = SetUtil.powerset(intersectionVariables); Collection<String> otherVariables = SetUtil.difference(variables, intersectionVariables); Collection<Collection<String>> disjointVariableCombinations = SetUtil.powerset(otherVariables); /* for each combination of elements in the intersection, compute the set of matches in the first and in the second distribution */ DiscreteProbabilityDistribution newDist = new DiscreteProbabilityDistribution(); for (Collection<String> intersectionVarCombo : commonVariableCombinations) { for (Collection<String> differenceVarCombo : disjointVariableCombinations) { Set<String> eventInFirst = new HashSet<>(SetUtil.union(intersectionVarCombo, SetUtil.intersection(differenceVarCombo, f1.getVariables()))); Set<String> eventInSecond = new HashSet<>(SetUtil.union(intersectionVarCombo, SetUtil.intersection(differenceVarCombo, f2.getVariables()))); double p1 = f1.getProbabilities().get(eventInFirst); double p2 = f2.getProbabilities().get(eventInSecond); double p = p1 * p2; Set<String> jointEvent = new HashSet<>(); jointEvent.addAll(intersectionVarCombo); jointEvent.addAll(differenceVarCombo); newDist.addProbability(jointEvent, p); } } return newDist; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/gradientdescent/BlackBoxGradient.java
package ai.libs.jaicore.math.gradientdescent; import org.api4.java.common.math.IVector; import ai.libs.jaicore.math.linearalgebra.DenseDoubleVector; /** * Difference quotient based gradient estimation. This class will give a * black-box gradient estimation by simply calculating * * (f(x + h) - f(x))/h * * where x is the provided point and x' is a point that slightly differs, * specified by the parameter <code>precision</code>. (Obviously it holds that * in lim_{precision -> 0} this yields the exact gradient.) * * If x is a vector (a_o, ..., a_n), then, instead we calculate each partial * derivative i by: * * (f(a_o, ... a_i +h, ... , a_n) - f((a_o, ..., a_n)))/h * * Obviously, this is a highly inefficient approach for estimating the gradient * (if we have n partial derivatives, we need 2 *n estimations). * * @author Mirko Jürgens * */ public class BlackBoxGradient implements IGradientFunction { private final double precision; private final IGradientDescendableFunction function; /** * Sets up a gradient-estimator for the given function. The estimation of the gradient can be tuned by the precision parameter. * * @param underlyingFunction the function for which the gradient shall be estimated * @param precision the precision of the estimation, the close this value is to zero the better is the estimation */ public BlackBoxGradient(final IGradientDescendableFunction underlyingFunction, final double precision) { this.precision = precision; this.function = underlyingFunction; } @Override public IVector apply(final IVector xVec) { IVector gradient = new DenseDoubleVector(xVec.length()); double fX = this.function.apply(xVec); IVector xPrime = new DenseDoubleVector(xVec.asArray()); for (int i = 0; i < xVec.length(); i++) { if (i > 0) { xPrime.setValue(i - 1, xPrime.getValue(i - 1) - this.precision); } xPrime.setValue(i, xPrime.getValue(i) + this.precision); // now compute f(x') - f(x) double fXPrime = this.function.apply(xPrime); double partial = fXPrime - fX; gradient.setValue(i, partial); } return gradient; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/gradientdescent/GradientDescentOptimizer.java
package ai.libs.jaicore.math.gradientdescent; import org.aeonbits.owner.ConfigFactory; import org.api4.java.common.math.IVector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An optimizer based on the gradient descent method [1]. This optimizer is the * naive implementation that calculates the gradient in every step and makes an * update into the negative direction of the gradient. * * This method is known to find the optimum, if the underlying function is convex. * * At some point in the future, we should probably implement faster methods, * like for example http://www.seas.ucla.edu/~vandenbe/236C/lectures/fgrad.pdf * * [1] Jonathan Barzilai and Jonathan M. Borwein, "Two-point step size gradient * methods", in: IMA journal of numerical analysis, 8.1 (1998), pp. 141-148. * * @author Mirko Jürgens * */ public class GradientDescentOptimizer implements IGradientBasedOptimizer { private double learningRate; private final double gradientThreshold; private final int maxIterations; private static final Logger log = LoggerFactory.getLogger(GradientDescentOptimizer.class); /** * * @param config */ public GradientDescentOptimizer(final IGradientDescentOptimizerConfig config) { this.learningRate = config.learningRate(); this.gradientThreshold = config.gradientThreshold(); this.maxIterations = config.maxIterations(); } public GradientDescentOptimizer() { this(ConfigFactory.create(IGradientDescentOptimizerConfig.class)); } @Override public IVector optimize(final IGradientDescendableFunction descendableFunction, final IGradientFunction gradient, final IVector initialGuess) { int iterations = 0; IVector gradients; do { gradients = gradient.apply(initialGuess); iterations++; this.updatePredictions(initialGuess, gradients); log.warn("iteration {}:\n weights \t{} \n gradients \t{}", iterations, initialGuess, gradients); } while (!this.allGradientsAreBelowThreshold(gradients) && iterations < this.maxIterations); log.warn("Gradient descent based optimization took {} iterations.", iterations); return initialGuess; } private boolean allGradientsAreBelowThreshold(final IVector gradients) { return gradients.stream().allMatch(grad -> Math.abs(grad) < this.gradientThreshold || !Double.isFinite(grad)); } private void updatePredictions(final IVector initialGuess, final IVector gradients) { for (int i = 0; i < initialGuess.length(); i++) { double weight = initialGuess.getValue(i); double gradient = gradients.getValue(i); // don't further optimize if we meet the threshold if (Math.abs(gradient) < this.gradientThreshold) { continue; } // we want to minimize gradient = gradient * -1.0; weight = weight + gradient * this.learningRate; initialGuess.setValue(i, weight); } } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/gradientdescent/IGradientBasedOptimizer.java
package ai.libs.jaicore.math.gradientdescent; import org.api4.java.common.math.IVector; /** * Interface for an optimizer that is based on a gradient descent and gets a * differentiable function and the derivation of said function to solve an * optimization problem. * * @author Helena Graf, Mirko Jürgens * */ public interface IGradientBasedOptimizer { /** * Optimize the given function based on its derivation. * * @param descendableFunction * the function to optimize * @param gradient * the first order derivate of the function * @param initialGuess * the initial guess for the parameters that shall be optimized * @return the optimized vector */ public IVector optimize(IGradientDescendableFunction descendableFunction, IGradientFunction gradient, IVector initialGuess); }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/gradientdescent/IGradientDescendableFunction.java
package ai.libs.jaicore.math.gradientdescent; import org.api4.java.common.math.IVector; /** * This interface represents a function that is differentiable and thus can be * used by gradient descent algorithms. * * In particular, if a function implements this interface, we assume that the * underlying space is convex. * * @author Helena Graf, Mirko Jürgens * */ public interface IGradientDescendableFunction { /** * Applies the function for the point represented by the given vector. * * @param vector * the point to which to apply the function * @return the function value at the applied point */ double apply(IVector vector); }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/gradientdescent/IGradientDescentOptimizerConfig.java
package ai.libs.jaicore.math.gradientdescent; import org.aeonbits.owner.Config.Sources; import org.aeonbits.owner.Mutable; @Sources({ "file:conf/opt/graddesc.properties" }) public interface IGradientDescentOptimizerConfig extends Mutable { /** * Specifies the maximum of gradient update steps. Can be set to -1 to specify * no threshold (the algorithm may not terminate in this case). */ public static final String GRAD_DESC_MAX_ITERATIONS = "graddesc.max_iterations"; /** * The learning rate in the update step (i.e. how much of the gradient should be * added to the parameter) */ public static final String GRAD_DESC_LEARNING_RATE = "gradedesc.learning_rate"; /** * Specifies a threshold for the gradient (i.e. if the gradient is below this * value no update will be done; if all gradients are below this value, the * algorithm will terminate) */ public static final String GRAD_DESC_GRADIENT_THRESHOLD = "graddesc.gradient_threshold"; @Key(GRAD_DESC_MAX_ITERATIONS) @DefaultValue("20") public int maxIterations(); @Key(GRAD_DESC_LEARNING_RATE) @DefaultValue("0.01") public double learningRate(); @Key(GRAD_DESC_GRADIENT_THRESHOLD) @DefaultValue("0.001") public double gradientThreshold(); }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/gradientdescent/IGradientFunction.java
package ai.libs.jaicore.math.gradientdescent; import org.api4.java.common.math.IVector; /** * Represents the gradient of a function that is differentiable. * * @author Helena Graf, Mirko Jürgens * */ public interface IGradientFunction { /** * Returns the result of applying the gradient to the point represented by the * given vector. * * @param vector * the vector the gradient is applied to * @return the new vector resulting from applying the gradient to the given * vector */ IVector apply(IVector vector); }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/gradientdescent/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.math.gradientdescent;
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/linearalgebra/AbstractVector.java
package ai.libs.jaicore.math.linearalgebra; import org.api4.java.common.math.IVector; /** * An abstract vector class, implementing several common methods for different vector implementations. All vector implementations should subclass this class. * * @author Alexander Tornede */ public abstract class AbstractVector implements IVector { @Override public void squareRoot() { for (int i = 0; i < length(); i++) { setValue(i, Math.sqrt(getValue(i))); } } @Override public IVector squareRootToCopy() { IVector copy = this.duplicate(); for (int i = 0; i < length(); i++) { copy.setValue(i, Math.sqrt(getValue(i))); } return copy; } @Override public void incrementValueAt(int index, double amount) { setValue(index, amount + getValue(index)); } @Override public double sum() { double sum = 0; for (int i = 0; i < length(); i++) { sum += getValue(i); } return sum; } @Override public double mean() { return sum() / length(); } @Override public double standardDeviation() { double mean = mean(); double std = 0.0; for (int i = 0; i < length(); i++) { std += Math.pow(mean - getValue(i), 2); } std = std / length(); return Math.sqrt(std); } @Override public String toString() { StringBuilder sb = new StringBuilder("("); sb.append(getValue(0)); for (int i = 1; i < length(); i++) { sb.append(",").append(getValue(i)); } sb.append(")"); return sb.toString(); } protected double[] kroneckerProductInternal(double[] vectorAsArray) { double[] kroneckerProduct = new double[this.length() * vectorAsArray.length]; int counter = 0; for (int i = 0; i < this.length(); i++) { for (int j = 0; j < vectorAsArray.length; j++) { kroneckerProduct[counter++] = this.getValue(i) * vectorAsArray[j]; } } return kroneckerProduct; } @Override public void zeroAllDimensions() { for (int i = 0; i < length(); i++) { setValue(i, 0); } } @Override public double euclideanNorm() { return Math.sqrt(this.dotProduct(this)); } @Override public IVector addVectorToCopy(double[] vectorAsArray) { IVector vector = duplicate(); vector.addVector(vectorAsArray); return vector; } @Override public IVector subtractVectorFromCopy(double[] vectorAsArray) { IVector vector = duplicate(); vector.subtractVector(vectorAsArray); return vector; } @Override public IVector multiplyByVectorPairwiseToCopy(double[] vectorAsArray) { IVector vector = duplicate(); vector.multiplyByVectorPairwise(vectorAsArray); return vector; } @Override public IVector divideByVectorPairwiseToCopy(double[] vectorAsArray) { IVector vector = duplicate(); vector.divideByVectorPairwise(vectorAsArray); return vector; } @Override public IVector addConstantToCopy(double constant) { IVector vector = duplicate(); vector.addConstant(constant); return vector; } @Override public IVector addVectorToCopy(IVector vector) { IVector vectorCopy = duplicate(); vectorCopy.addVector(vector); return vectorCopy; } @Override public IVector subtractConstantFromCopy(double constant) { IVector vectorCopy = duplicate(); vectorCopy.subtractConstant(constant); return vectorCopy; } @Override public IVector subtractVectorFromCopy(IVector vector) { IVector vectorCopy = duplicate(); vectorCopy.subtractVector(vector); return vectorCopy; } @Override public IVector multiplyByVectorPairwiseToCopy(IVector vector) { IVector vectorCopy = duplicate(); vectorCopy.multiplyByVectorPairwise(vector); return vectorCopy; } @Override public IVector multiplyByConstantToCopy(double constant) { IVector vectorCopy = duplicate(); vectorCopy.multiplyByConstant(constant); return vectorCopy; } @Override public IVector divideByVectorPairwiseToCopy(IVector vector) { IVector vectorCopy = duplicate(); vectorCopy.divideByVectorPairwise(vector); return vectorCopy; } @Override public IVector divideByConstantToCopy(double constant) { IVector vectorCopy = duplicate(); vectorCopy.divideByConstant(constant); return vectorCopy; } @Override public Double average() { double basisAverage = 0; for (int i = 0; i < this.length(); i++) { basisAverage += this.getValue(i); } basisAverage = basisAverage / this.length(); return basisAverage; } @Override public boolean equals(Object obj) { if (obj instanceof AbstractVector) { AbstractVector vector = (AbstractVector) obj; for (int i = 0; i < vector.length(); i++) { if (Math.abs(vector.getValue(i) - this.getValue(i)) > 0.00000000000000001) { return false; } } return true; } return super.equals(obj); } @Override public int hashCode() { int hashCode = 1; for (int i = 0; i < length(); i++) { hashCode = 31 * hashCode + (Double.valueOf(getValue(i)).hashCode()); } return hashCode; } public abstract DenseDoubleVector toDenseVector(); public abstract SparseDoubleVector toSparseVector(); }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/linearalgebra/AffineFunction.java
package ai.libs.jaicore.math.linearalgebra; import java.math.BigDecimal; import java.math.BigInteger; import java.util.function.ToDoubleFunction; public class AffineFunction implements ToDoubleFunction<Number> { private final double a; private final double b; public AffineFunction(final double a, final double b) { super(); this.a = a; this.b = b; } public AffineFunction(final BigDecimal x1, final BigDecimal y1, final BigDecimal x2, final BigDecimal y2) { this.a = y1.subtract(y2).doubleValue() / x1.subtract(x2).doubleValue(); this.b = y1.subtract(x1.multiply(BigDecimal.valueOf(this.a))).doubleValue(); } public AffineFunction(final double x1, final double y1, final double x2, final double y2) { if (x1 == x2) { throw new IllegalArgumentException("Cannot create an affine function from two points with the same x-choordinate " + x1 + "."); } this.a = (y1 - y2) / (x1 - x2); this.b = y1 - this.a * x1; } public double getA() { return this.a; } public double getB() { return this.b; } @Override public double applyAsDouble(final Number t) { if (t instanceof BigDecimal) { return ((BigDecimal) t).multiply(BigDecimal.valueOf(this.a)).add(BigDecimal.valueOf(this.b)).doubleValue(); } else if (t instanceof BigInteger) { return new BigDecimal((BigInteger) t).multiply(BigDecimal.valueOf(this.a)).add(BigDecimal.valueOf(this.b)).doubleValue(); } else if (t instanceof Integer) { return this.a * (Integer)t + this.b; } else { return this.a * (double)t + this.b; } } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/linearalgebra/DenseDoubleVector.java
package ai.libs.jaicore.math.linearalgebra; import java.util.Arrays; import org.api4.java.common.math.IVector; import ai.libs.jaicore.math.random.RandomGenerator; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Vector.Norm; /** * Dense vector implementation wrapping the MTJ implementation of a dense vector. * * @author Alexander Tornede */ public class DenseDoubleVector extends AbstractVector { private no.uib.cipr.matrix.Vector internalVector; /** * Creates a dense vector with the given amount of dimensions, initialized with zeros. * * @param numberOfDimensions * The number of dimensions of this vector. */ public DenseDoubleVector(final int numberOfDimensions) { this.internalVector = new DenseVector(numberOfDimensions); } /** * Creates a dense vector from the given data. * * @param data * A double array, which can be interpreted as a vector. */ public DenseDoubleVector(final double[] data) { this.internalVector = new DenseVector(Arrays.copyOf(data, data.length)); } /** * Creates a dense vector from an MTJ vector. * * @param vector * The MTJ vector. */ public DenseDoubleVector(final no.uib.cipr.matrix.Vector vector) { this.internalVector = vector; } /** * Creates a new dense vector with the given size and paste for each entry the given value. * * @param size * The size of the dense vector. * @param value * The value for each entry. */ public DenseDoubleVector(final int size, final double value) { this.internalVector = new DenseVector(size); for (int index = 0; index < this.internalVector.size(); index++) { this.internalVector.set(index, value); } } @Override public int length() { return this.internalVector.size(); } @Override public double getValue(final int index) { return this.internalVector.get(index); } @Override public void setValue(final int index, final double value) { this.internalVector.set(index, value); } @Override public void addConstant(final double constant) { double[] contantAsVector = new double[this.internalVector.size()]; for (int i = 0; i < contantAsVector.length; i++) { contantAsVector[i] = constant; } this.addVector(contantAsVector); } @Override public void addVector(final IVector vector) { if (!(vector instanceof AbstractVector)) { throw new UnsupportedOperationException("Not implemented for non-AbstractVector vectors."); } this.internalVector = this.internalVector.add(((AbstractVector) vector).toDenseVector().internalVector); } @Override public void subtractConstant(final double constant) { this.addConstant(-1 * constant); } @Override public void subtractVector(final IVector vector) { this.internalVector = this.internalVector.add(-1, ((AbstractVector) vector).toDenseVector().internalVector); } @Override public void multiplyByVectorPairwise(final IVector secondVector) { for (int i = 0; i < this.internalVector.size(); i++) { this.internalVector.set(i, this.internalVector.get(i) * secondVector.getValue(i)); } } @Override public void multiplyByConstant(final double constant) { this.internalVector = this.internalVector.scale(constant); } @Override public void divideByVectorPairwise(final IVector secondVector) { for (int i = 0; i < this.internalVector.size(); i++) { this.internalVector.set(i, this.internalVector.get(i) / secondVector.getValue(i)); } } @Override public void divideByConstant(final double constant) { this.internalVector = this.internalVector.scale(1 / constant); } @Override public double dotProduct(final IVector vector) { return this.internalVector.dot(((AbstractVector) vector).toDenseVector().internalVector); } @Override public boolean isSparse() { return false; } @Override public double[] asArray() { double[] result = new double[this.internalVector.size()]; for (int i = 0; i < result.length; i++) { result[i] = this.internalVector.get(i); } return result; } @Override public void addVector(final double[] vectorAsArray) { this.addVector(new DenseDoubleVector(vectorAsArray)); } @Override public void subtractVector(final double[] vectorAsArray) { this.subtractVector(new DenseDoubleVector(vectorAsArray)); } @Override public void multiplyByVectorPairwise(final double[] vectorAsArray) { this.multiplyByVectorPairwise(new DenseDoubleVector(vectorAsArray)); } @Override public void divideByVectorPairwise(final double[] vectorAsArray) { this.divideByVectorPairwise(new DenseDoubleVector(vectorAsArray)); } @Override public double dotProduct(final double[] vectorAsArray) { return this.dotProduct(new DenseDoubleVector(vectorAsArray)); } @Override public IVector duplicate() { return new DenseDoubleVector(this.asArray()); } @Override public void normalize() { this.internalVector = this.internalVector.scale(1 / this.internalVector.norm(Norm.Two)); } @Override public void fillRandomly() { for (int numberOfAddedValues = 0; numberOfAddedValues < this.internalVector.size(); numberOfAddedValues++) { double fillValue = RandomGenerator.getRNG().nextDouble(); this.internalVector.set(numberOfAddedValues, fillValue); } } @Override public DenseDoubleVector toDenseVector() { return this; } @Override public SparseDoubleVector toSparseVector() { return new SparseDoubleVector(this.asArray()); } @Override public IVector kroneckerProduct(final double[] vectorAsArray) { return new DenseDoubleVector(this.kroneckerProductInternal(vectorAsArray)); } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/linearalgebra/LinearlyScaledFunction.java
package ai.libs.jaicore.math.linearalgebra; import java.util.function.DoubleFunction; public class LinearlyScaledFunction implements DoubleFunction<Double> { private final DoubleFunction<Double> baseFunction; private final AffineFunction mapping; public LinearlyScaledFunction(final DoubleFunction<Double> baseFunction, final double x1, final double y1, final double x2, final double y2) { super(); this.baseFunction = baseFunction; this.mapping = new AffineFunction(baseFunction.apply(x1), y1, baseFunction.apply(x2), y2); } @Override public Double apply(final double arg0) { double intermediate = this.baseFunction.apply(arg0); return this.mapping.applyAsDouble(intermediate); } public AffineFunction getMapping() { return this.mapping; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/linearalgebra/SparseDoubleVector.java
package ai.libs.jaicore.math.linearalgebra; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.api4.java.common.math.IVector; import ai.libs.jaicore.math.random.RandomGenerator; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Vector.Norm; import no.uib.cipr.matrix.sparse.SparseVector; /** * Sparse vector implementation wrapping the MTJ implementation of a sparse vector. * * @author Alexander Tornede */ public class SparseDoubleVector extends AbstractVector { protected SparseVector internalVector; private boolean isChanged = true; /** * Creates a new SparseDoubleVector which contains the given values. * * @param indices * An array which includes all indices for which there exists a value. * @param values * An array which contains all values. * @param dimension * The total dimension of the vector. */ public SparseDoubleVector(final int[] indices, final double[] values, final int dimension) { this.internalVector = new SparseVector(dimension, indices, values); this.setIsChanged(); } /** * Creates a new SparseDoubleVector which contains only zero values. * * @param dimension * The dimension of the vector. */ public SparseDoubleVector(final int dimension) { this.internalVector = new SparseVector(dimension); } /** * Creates a new SparseDoubleVector which contains the given values. * * @param data * A double array, which can be interpreted as a vector. */ public SparseDoubleVector(final double[] data) { List<Integer> indicesWithNonZeroEntry = new ArrayList<>(); List<Double> nonZeroEntries = new ArrayList<>(); for (int i = 0; i < data.length; i++) { if (Double.compare(data[i], 0.0) != 0) { indicesWithNonZeroEntry.add(i); nonZeroEntries.add(data[i]); } } this.internalVector = new SparseVector(data.length, indicesWithNonZeroEntry.stream().mapToInt(i -> i).toArray(), nonZeroEntries.stream().mapToDouble(d -> d).toArray()); this.setIsChanged(); } /** * Creates a new SparseDoubleVector from an MTJ {@link SparseVector}. * * @param mtjVector * The MTJ vector. */ public SparseDoubleVector(final SparseVector mtjVector) { this.internalVector = mtjVector; this.setIsChanged(); } @Override public void addVector(final double[] vectorAsArray) { this.setIsChanged(); this.addVector(new SparseDoubleVector(vectorAsArray)); } @Override public void subtractVector(final double[] vectorAsArray) { this.setIsChanged(); this.internalVector = (SparseVector) this.internalVector.add(-1, new SparseDoubleVector(vectorAsArray).internalVector); } @Override public void multiplyByVectorPairwise(final double[] vectorAsArray) { this.setIsChanged(); SparseVector vector = this.internalVector; int[] indexes = vector.getIndex(); for (int i = 0; i < indexes.length; i++) { vector.set(indexes[i], vector.get(indexes[i]) * vectorAsArray[indexes[i]]); } } @Override public void divideByVectorPairwise(final double[] vectorAsArray) { this.setIsChanged(); SparseVector vector = this.internalVector; int[] indexes = vector.getIndex(); for (int i = 0; i < indexes.length; i++) { vector.set(indexes[i], vector.get(indexes[i]) / vectorAsArray[indexes[i]]); } } @Override public double dotProduct(final double[] vectorAsArray) { return this.internalVector.dot(new DenseVector(vectorAsArray)); } @Override public int length() { return this.internalVector.size(); } @Override public double getValue(final int index) { return this.internalVector.get(index); } @Override public void setValue(final int index, final double value) { this.setIsChanged(); this.internalVector.set(index, value); } @Override public void addVector(final IVector vector) { this.setIsChanged(); this.internalVector = (SparseVector) this.internalVector.add(((AbstractVector) vector).toSparseVector().internalVector); } @Override public void subtractVector(final IVector vector) { this.setIsChanged(); this.internalVector = (SparseVector) this.internalVector.add(-1, ((AbstractVector) vector).toSparseVector().internalVector); } @Override public void multiplyByVectorPairwise(final IVector secondVector) { this.setIsChanged(); SparseVector sparseVector = this.internalVector; int[] indexes = sparseVector.getIndex(); for (int i = 0; i < indexes.length; i++) { sparseVector.set(indexes[i], sparseVector.get(indexes[i]) * secondVector.getValue(indexes[i])); } } @Override public void multiplyByConstant(final double constant) { this.setIsChanged(); this.internalVector = this.internalVector.scale(constant); } @Override public void divideByVectorPairwise(final IVector secondVector) { this.setIsChanged(); SparseVector sparseVector = this.internalVector; int[] indexes = sparseVector.getIndex(); for (int i = 0; i < indexes.length; i++) { sparseVector.set(indexes[i], sparseVector.get(indexes[i]) / secondVector.getValue(indexes[i])); } } @Override public void divideByConstant(final double constant) { this.setIsChanged(); this.internalVector = this.internalVector.scale(1 / constant); } @Override public double dotProduct(final IVector vector) { return this.internalVector.dot(((AbstractVector) vector).toSparseVector().internalVector); } @Override public boolean isSparse() { return true; } @Override public double[] asArray() { double[] result = new double[this.internalVector.size()]; for (int i = 0; i < result.length; i++) { result[i] = this.internalVector.get(i); } return result; } @Override public DenseDoubleVector toDenseVector() { return new DenseDoubleVector(this.asArray()); } @Override public SparseDoubleVector toSparseVector() { return this; } @Override public IVector duplicate() { return new SparseDoubleVector(this.asArray()); } @Override public void normalize() { this.setIsChanged(); this.internalVector = this.internalVector.scale(this.internalVector.norm(Norm.Two)); } @Override public void addConstant(final double constant) { this.setIsChanged(); double[] contantAsVector = new double[this.internalVector.size()]; for (int i = 0; i < contantAsVector.length; i++) { contantAsVector[i] = constant; } this.addVector(contantAsVector); } @Override public void subtractConstant(final double constant) { this.setIsChanged(); this.addConstant(-1 * constant); } @Override public void fillRandomly() { this.setIsChanged(); Random random = RandomGenerator.getRNG(); int numberToAdd = random.nextInt(this.internalVector.size()); List<Integer> unfilledIndexes = IntStream.range(0, this.internalVector.size()).mapToObj(x -> x).collect(Collectors.toList()); for (int numberOfAddedValues = 0; numberOfAddedValues < numberToAdd; numberOfAddedValues++) { int randomIndex = random.nextInt(unfilledIndexes.size()); int toBeFilledIndex = unfilledIndexes.get(randomIndex); double fillValue = random.nextDouble(); this.internalVector.set(toBeFilledIndex, fillValue); unfilledIndexes.remove(0); } } /** * Returns an array containing the non-zero indices of this sparse vector. * * @return an integer array containing the non-zero indices of this sparse vector */ public int[] getNonZeroIndices() { if (this.isChanged) { List<Integer> indicesWithNonZeroEntry = new ArrayList<>(this.length()); List<Double> nonZeroEntries = new ArrayList<>(this.length()); for (int i = 0; i < this.length(); i++) { double value = this.internalVector.get(i); if (Double.compare(value, 0.0) != 0) { indicesWithNonZeroEntry.add(i); nonZeroEntries.add(value); } } // do we need to recopy? if (indicesWithNonZeroEntry.size() != this.internalVector.getIndex().length) { this.internalVector = new SparseVector(indicesWithNonZeroEntry.size(), indicesWithNonZeroEntry.stream().mapToInt(i -> i).toArray(), nonZeroEntries.stream().mapToDouble(d -> d).toArray()); } this.setUnchanged(); } return this.internalVector.getIndex(); } /** * Changes the status of this vector to changed. */ private void setIsChanged() { this.isChanged = true; } /** * Changes the status of this vector to unchanged. */ private void setUnchanged() { this.isChanged = false; } @Override public IVector kroneckerProduct(final double[] vectorAsArray) { return new SparseDoubleVector(this.kroneckerProductInternal(vectorAsArray)); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.internalVector == null) ? 0 : this.internalVector.hashCode()); result = prime * result + (this.isChanged ? 1231 : 1237); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } SparseDoubleVector other = (SparseDoubleVector) obj; // we cannot compare the internal vector if (this.isChanged != other.isChanged) { return false; } return Arrays.equals(this.asArray(), other.asArray()); } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/numopt/IRealFunction.java
package ai.libs.jaicore.math.numopt; public interface IRealFunction { public double eval(double[] x); }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/numopt/ISingleMinimumComputer.java
package ai.libs.jaicore.math.numopt; /** * Interface to compute the place of a function f where f is locally minimal * * @author fmohr * */ public interface ISingleMinimumComputer { public double[] getMinimum(); }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability/pl/PLInferenceProblem.java
package ai.libs.jaicore.math.probability.pl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import it.unimi.dsi.fastutil.shorts.ShortArraySet; import it.unimi.dsi.fastutil.shorts.ShortList; import it.unimi.dsi.fastutil.shorts.ShortSet; public class PLInferenceProblem { private final List<ShortList> rankings; private final int n; public PLInferenceProblem(final Collection<ShortList> rankings) { this(new ArrayList<>(rankings)); } public PLInferenceProblem(final List<ShortList> rankings) { super(); this.rankings = rankings; ShortSet comparedObjects = new ShortArraySet(); for (ShortList ranking : rankings) { comparedObjects.addAll(ranking); } this.n = comparedObjects.size(); } public List<ShortList> getRankings() { return this.rankings; } public int getNumObjects() { return this.n; } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability/pl/PLInferenceProblemEncoder.java
package ai.libs.jaicore.math.probability.pl; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import it.unimi.dsi.fastutil.shorts.ShortArrayList; import it.unimi.dsi.fastutil.shorts.ShortList; public class PLInferenceProblemEncoder { private Map<Object, Short> ext2int; private List<Object> items; public PLInferenceProblem encode(final Collection<? extends List<?>> rankings) { if (this.ext2int != null) { throw new IllegalStateException(); } this.ext2int = new HashMap<>(); List<ShortList> encodedRankings = new ArrayList<>(rankings.size()); this.items = new ArrayList<>(); for (List<?> ranking : rankings) { ShortList encodedRanking = new ShortArrayList(); for (Object o : ranking) { short index = this.ext2int.computeIfAbsent(o, obj -> (short)this.ext2int.size()); if (!this.items.contains(o)) { this.items.add(o); } encodedRanking.add(index); } encodedRankings.add(encodedRanking); } return new PLInferenceProblem(encodedRankings); } public short getIndexOfObject(final Object o) { return this.ext2int.get(o); } public Object getObjectAtIndex(final int index) { return this.items.get(index); } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability/pl/PLMMAlgorithm.java
package ai.libs.jaicore.math.probability.pl; import java.util.List; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig; import ai.libs.jaicore.basic.algorithm.AAlgorithm; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleList; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.shorts.ShortList; /** * This is the MM algorithm for Plackett-Luce as described in * * @article{hunter2004, title={MM algorithms for generalized Bradley-Terry models}, author={Hunter, David R and others}, journal={The annals of statistics}, volume={32}, number={1}, pages={384--406}, year={2004}, publisher={Institute of Mathematical Statistics} } * * @author felix * */ public class PLMMAlgorithm extends AAlgorithm<PLInferenceProblem, DoubleList> { private final List<ShortList> rankings; private final int numRankings; private final int numObjects; private final IntList winVector; private DoubleList skillVector; private Logger logger = LoggerFactory.getLogger(PLMMAlgorithm.class); public PLMMAlgorithm(final PLInferenceProblem input) { this(input, null, null); } public PLMMAlgorithm(final PLInferenceProblem input, final IOwnerBasedAlgorithmConfig config) { this(input, null, config); } public PLMMAlgorithm(final PLInferenceProblem input, final DoubleList skillVector, final IOwnerBasedAlgorithmConfig config) { super(config, input); this.numRankings = this.getInput().getRankings().size(); this.numObjects = this.getInput().getNumObjects(); if (this.numObjects < 2) { throw new IllegalArgumentException("Cannot create PL-Algorithm for choice problems with only one option."); } this.rankings = input.getRankings(); for (ShortList ranking : this.rankings) { if (ranking.size() != this.numObjects) { throw new UnsupportedOperationException("This MM implementation only supports full rankings!"); } } this.skillVector = skillVector != null ? skillVector : getDefaultSkillVector(this.numObjects); this.winVector = this.getWinVector(); } public static DoubleList getDefaultSkillVector(final int n) { DoubleList skillVector = new DoubleArrayList(); double p = 1.0 / n; for (int i = 0; i < n; i++) { skillVector.add(p); } return skillVector; } @Override public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { DoubleList lastSkillVector = null; double epsilon = 0.00001; double diffToLast = 0; do { this.skillVector = this.normalizeSkillVector(this.getUpdatedSkillVectorImproved(this.skillVector)); if (lastSkillVector != null) { diffToLast = 0; for (int i = 0; i < this.numObjects; i++) { diffToLast += Math.abs(this.skillVector.getDouble(i) - lastSkillVector.getDouble(i)); } } else { diffToLast = Double.MAX_VALUE; } lastSkillVector = this.skillVector; } while (diffToLast > epsilon); return null; } private DoubleList normalizeSkillVector(final DoubleList skillVector) { double sum = 0; for (double d : skillVector) { if (Double.isNaN(d)) { throw new IllegalArgumentException("Skill vector has NaN entry: " + skillVector); } sum += d; } if (sum < 0) { sum *= -1; } if (sum == 0) { throw new IllegalArgumentException("Cannot normalize null skill vector: " + skillVector); } DoubleList copy = new DoubleArrayList(); for (double d : skillVector) { copy.add(d / sum); } return copy; } private double getSkillOfRankedObject(final ShortList ranking, final int indexOfObjectInRanking, final DoubleList skillVector) { return skillVector.getDouble(ranking.getShort(indexOfObjectInRanking)); } private DoubleList getUpdatedSkillVectorImproved(final DoubleList skillVector) { DoubleList updatedVector = new DoubleArrayList(); /* first create tree of accumulated skills (stored in 2D-array (not a matrix)) */ double[][] accumulatedSkills = new double[this.numRankings][]; for (int j = 0; j < this.numRankings; j++) { ShortList ranking = this.rankings.get(j); double[] accumulatedSkillsForThisRanking = new double[ranking.size() - 1]; int numNodes = accumulatedSkillsForThisRanking.length; accumulatedSkills[j] = accumulatedSkillsForThisRanking; /* compute the delta-conditioned sums of the denominator in (30) */ accumulatedSkillsForThisRanking[numNodes - 1] = this.getSkillOfRankedObject(ranking, this.numObjects - 1, skillVector) + this.getSkillOfRankedObject(ranking, this.numObjects - 2, skillVector); for (int i = this.numObjects - 3; i >= 0; i--) { accumulatedSkillsForThisRanking[i] = accumulatedSkillsForThisRanking[i + 1] + this.getSkillOfRankedObject(ranking, i, skillVector); } for (int i = 0; i < numNodes; i++) { accumulatedSkillsForThisRanking[i] = 1 / accumulatedSkillsForThisRanking[i]; } } /* now compute the updated skill values for each t base on the accumulated skills structure */ for (short t = 0; t < this.numObjects; t++) { double denominator = 0; for (int j = 0; j < this.numRankings; j++) { ShortList ranking = this.rankings.get(j); double[] accumulatedSkillsForThisRanking = accumulatedSkills[j]; for (int i = 0; i < accumulatedSkillsForThisRanking.length; i++) { denominator += accumulatedSkillsForThisRanking[i]; if (ranking.getShort(i) == t) { break; } } } if (denominator == 0) { throw new IllegalStateException("Denominator in PL-model must not be null."); } updatedVector.add(this.winVector.getInt(t) / denominator); } this.logger.debug("Updated vector: {}", updatedVector); return updatedVector; } private IntList getWinVector() { IntList wins = new IntArrayList(); for (short t = 0; t < this.numObjects; t ++) { int w = 0; for (ShortList ranking : this.getInput().getRankings()) { if (ranking.indexOf(t) < ranking.size() - 1) { w ++; } } wins.add(w); } return wins; } @Override public DoubleList call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { this.next(); if (this.skillVector.size() != this.numObjects) { throw new IllegalStateException("Have " + this.skillVector.size() + " skills (" + this.skillVector + ") for " + this.numObjects + " objects."); } for (double d : this.skillVector) { if (Double.isNaN(d)) { throw new IllegalStateException("Illegal skill return value: " + this.skillVector); } } return this.skillVector; } public DoubleList getSkillVector() { return this.skillVector; } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } @Override public String getLoggerName() { return this.logger.getName(); } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/probability/pl/PLSkillMap.java
package ai.libs.jaicore.math.probability.pl; import java.util.HashMap; public class PLSkillMap extends HashMap<Object, Double> { public Object getObjectWithHighestSkill() { return this.keySet().stream().max((k1,k2) -> Double.compare(this.get(k1), this.get(k2))).get(); } }
0
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math
java-sources/ai/libs/jaicore-math/0.2.7/ai/libs/jaicore/math/random/RandomGenerator.java
package ai.libs.jaicore.math.random; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class serves as a way to obtain a globally synchronized random variable. Any part of the system requiring a random number should make use of the random variable provided by this class in order to assure a repeatability of * experiments. * * @author Alexander Hetzer * */ public class RandomGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(RandomGenerator.class); private static final String INITIALIZING_THE_RANDOM_GENERATOR_TO_SEED = "Initializing the random generator to seed: %d ."; private static final String INITIALIZING_RANDOM_GENERATOR = "Random number generator not initialized; initializing to 1234."; /** The default value for the random value seed. */ public static final int DEFAULT_SEED = 1234; private static Random randomVariable = null; private static long seed = -1; /** * Hides the public constructor. */ private RandomGenerator() { throw new IllegalAccessError("Utility class"); } /** * Initializes the random generator with the given seed. * * @param seed * The random seed to use for initialization. */ public static void initializeRNG(final long seed) { RandomGenerator.seed = seed; randomVariable = new Random(seed); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format(INITIALIZING_THE_RANDOM_GENERATOR_TO_SEED, seed)); } } /** * Returns the random variable of this class. * * @return The random variable of this class. */ public static Random getRNG() { if (randomVariable == null) { LOGGER.warn(INITIALIZING_RANDOM_GENERATOR); initializeRNG(DEFAULT_SEED); } return randomVariable; } /** * Returns the seed of the random variable singleton. * * @return The seed of the random variable singleton. */ public static long getSeed() { return seed; } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/package-info.java
package ai.libs.jaicore.ml.classification;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/ConfusionMatrix.java
package ai.libs.jaicore.ml.classification.loss; import static ai.libs.jaicore.basic.StringUtil.postpaddedString; import static ai.libs.jaicore.basic.StringUtil.prepaddedString; import static ai.libs.jaicore.basic.StringUtil.spaces; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Given two equal-length lists/vectors of values, this class computes a confusion matrix * @author mwever * */ public class ConfusionMatrix { private static final String COL_SEP = " | "; private final List<Object> objectIndex; private int[][] matrixEntries; /** * Constructor computing the confusion matrix based on the given equal-length lists expected and actual. * @param expected The list of expected values. * @param actual The list of actual values. */ public ConfusionMatrix(final List<?> expected, final List<?> actual) { if (expected.size() != actual.size()) { throw new IllegalArgumentException("The proivded lists must be of the same length."); } Set<Object> distinctClasses = new HashSet<>(expected); distinctClasses.addAll(actual); this.objectIndex = new ArrayList<>(distinctClasses); this.matrixEntries = new int[this.objectIndex.size()][this.objectIndex.size()]; for (int i = 0; i < expected.size(); i++) { this.matrixEntries[this.objectIndex.indexOf(expected.get(i))][this.objectIndex.indexOf(actual.get(i))] += 1; } } /** * Gets the order of all the occurring elements which also defines the index of an element. * @return The index list of objects. */ public List<Object> getObjectIndex() { return this.objectIndex; } /** * Returns the index of an object in the confusion matrix. * @param object The object for which to retrieve the index. * @return The index of the given object. */ public int getIndexOfObject(final Object object) { return this.objectIndex.indexOf(object); } /** * Returns an integer matrix with counts of the confusions. * @return The integer matrix counting all occurring confusions. */ public int[][] getConfusionMatrix() { return this.matrixEntries; } @Override public String toString() { StringBuilder sb = new StringBuilder(); // determine maximum cell width int cellWidth = Math.max(this.objectIndex.stream().mapToInt(x -> x.toString().length()).max().getAsInt(), Arrays.stream(this.matrixEntries).mapToInt(x -> Arrays.stream(x).map(y -> (y + "").length()).max().getAsInt()).max().getAsInt()); // write table head row sb.append(spaces(cellWidth)); this.objectIndex.stream().map(x -> COL_SEP + postpaddedString(x.toString(), cellWidth)).forEach(sb::append); sb.append("\n"); sb.append(IntStream.range(0, cellWidth + (cellWidth + COL_SEP.length()) * this.objectIndex.size()).mapToObj(x -> "-").collect(Collectors.joining())).append("\n"); // write content of the table for (int i = 0; i < this.objectIndex.size(); i++) { sb.append(postpaddedString(this.objectIndex.get(i).toString(), cellWidth)); for (int j = 0; j < this.objectIndex.size(); j++) { sb.append(COL_SEP).append(prepaddedString(this.matrixEntries[i][j] + "", cellWidth)); } sb.append("\n"); } return sb.toString(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/package-info.java
package ai.libs.jaicore.ml.classification.loss;
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/AAreaUnderCurvePerformanceMeasure.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.IntStream; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import ai.libs.jaicore.basic.sets.Pair; public abstract class AAreaUnderCurvePerformanceMeasure extends ASingleLabelClassificationPerformanceMeasure { private final int positiveClass; public AAreaUnderCurvePerformanceMeasure(final int positiveClass) { super(); this.positiveClass = positiveClass; } public AAreaUnderCurvePerformanceMeasure() { this(0); } public Object getPositiveClass() { return this.positiveClass; } public List<Pair<Double, Integer>> getPredictionList(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { List<Pair<Double, Integer>> predictionsList = new ArrayList<>(expected.size()); IntStream.range(0, expected.size()).mapToObj(x -> new Pair<>(predicted.get(x).getProbabilityOfLabel(this.positiveClass), (int) expected.get(x))).forEach(predictionsList::add); Collections.sort(predictionsList, (o1, o2) -> o2.getX().compareTo(o1.getX())); return predictionsList; } /** * Computes the area under the curve coordinates, assuming a linear interpolation between the coordinates. * * @param curveCoordinates The points of the curve in ascending order (according to x-axis). * @return The area under the curve. */ protected double getAreaUnderCurve(final List<Pair<Double, Double>> curveCoordinates) { double area = 0.0; for (int i = 1; i < curveCoordinates.size(); i++) { Pair<Double, Double> prev = curveCoordinates.get(i - 1); Pair<Double, Double> cur = curveCoordinates.get(i); double deltaX = cur.getX() - prev.getX(); double deltaY = cur.getY() - prev.getY(); area += prev.getY() * deltaX + deltaX * deltaY / 2; } return area; } @Override public double score(final List<? extends Integer> expected, final List<? extends ISingleLabelClassification> predicted) { this.checkConsistency(expected, predicted); // parse predictions into a handy format List<Pair<Double, Integer>> predictionsList = this.getPredictionList(expected, predicted); // Compute roc curve coordinates List<Pair<Double, Double>> curveCoordinates = new ArrayList<>(predictionsList.size()); int tp = 0; int fp = 0; int fn = (int) predictionsList.stream().filter(x -> x.getY() == this.getPositiveClass()).count(); int tn = predictionsList.size() - fn; curveCoordinates.add(new Pair<>(this.getXValue(tp, fp, tn, fn), this.getYValue(tp, fp, tn, fn))); double currentThreshold = 1.0; int currentIndex = 0; while (currentIndex < predictionsList.size()) { while (currentIndex < predictionsList.size() && currentThreshold <= predictionsList.get(currentIndex).getX()) { Pair<Double, Integer> pred = predictionsList.get(currentIndex); if (pred.getY() == this.getPositiveClass()) { tp++; fn--; } else { fp++; tn--; } currentIndex++; } curveCoordinates.add(new Pair<>(this.getXValue(tp, fp, tn, fn), this.getYValue(tp, fp, tn, fn))); if (currentIndex >= predictionsList.size()) { break; } currentThreshold = predictionsList.get(currentIndex).getX(); } // compute area under the curve return this.getAreaUnderCurve(curveCoordinates); } public abstract double getXValue(int tp, int fp, int tn, int fn); public abstract double getYValue(int tp, int fp, int tn, int fn); }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/APredictionPerformanceMeasure.java
package ai.libs.jaicore.ml.classification.loss.dataset; import java.util.List; import java.util.OptionalDouble; import java.util.stream.IntStream; import org.api4.java.ai.ml.core.evaluation.IPredictionAndGroundTruthTable; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicInstancePredictionPerformanceMeasure; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; public abstract class APredictionPerformanceMeasure<E, P> implements IDeterministicPredictionPerformanceMeasure<E, P> { public APredictionPerformanceMeasure() { super(); } protected void checkConsistency(final List<? extends E> expected, final List<? extends P> predicted) { if (expected.size() != predicted.size()) { throw new IllegalArgumentException("The expected and predicted classification lists must be of the same length."); } } @Override public double loss(final IPredictionAndGroundTruthTable<? extends E, ? extends P> pairTable) { return this.loss(pairTable.getGroundTruthAsList(), pairTable.getPredictionsAsList()); } /** * If this performance measure is originally a score function its score is transformed into a loss by multiplying the score with -1. (loss=-score). */ @Override public double loss(final List<? extends E> expected, final List<? extends P> predicted) { return -this.score(expected, predicted); } /** * If this performance measure is originally a loss function its loss is transformed into a score by multiplying the loss with -1. (score=-loss). */ @Override public double score(final List<? extends E> expected, final List<? extends P> predicted) { return -this.loss(expected, predicted); } @Override public double score(final IPredictionAndGroundTruthTable<? extends E, ? extends P> pairTable) { return this.score(pairTable.getGroundTruthAsList(), pairTable.getPredictionsAsList()); } protected double averageInstanceWiseLoss(final List<? extends E> expected, final List<? extends P> predicted, final IDeterministicInstancePredictionPerformanceMeasure<P, E> subMeasure) { OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> subMeasure.loss(expected.get(x), predicted.get(x))).average(); if (res.isPresent()) { return res.getAsDouble(); } else { throw new IllegalStateException("The submeasure could not be aggregated."); } } protected double averageInstanceWiseScore(final List<? extends E> expected, final List<? extends P> predicted, final IDeterministicInstancePredictionPerformanceMeasure<P, E> subMeasure) { OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> subMeasure.score(expected.get(x), predicted.get(x))).average(); if (res.isPresent()) { return res.getAsDouble(); } else { throw new IllegalStateException("The submeasure could not be aggregated."); } } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/ASingleLabelClassificationPerformanceMeasure.java
package ai.libs.jaicore.ml.classification.loss.dataset; import org.api4.java.ai.ml.classification.singlelabel.evaluation.ISingleLabelClassification; import org.api4.java.ai.ml.core.evaluation.supervised.loss.IDeterministicPredictionPerformanceMeasure; public abstract class ASingleLabelClassificationPerformanceMeasure extends APredictionPerformanceMeasure<Integer, ISingleLabelClassification> implements IDeterministicPredictionPerformanceMeasure<Integer, ISingleLabelClassification> { public ASingleLabelClassificationPerformanceMeasure() { super(); } }
0
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss
java-sources/ai/libs/jaicore-ml/0.2.7/ai/libs/jaicore/ml/classification/loss/dataset/AreaUnderPrecisionRecallCurve.java
package ai.libs.jaicore.ml.classification.loss.dataset; public class AreaUnderPrecisionRecallCurve extends AAreaUnderCurvePerformanceMeasure { public AreaUnderPrecisionRecallCurve(final int positiveClass) { super(positiveClass); } @Override public double getXValue(final int tp, final int fp, final int tn, final int fn) { // true positive rate / recall return (double) tp / (tp + fn); } @Override public double getYValue(final int tp, final int fp, final int tn, final int fn) { // precision if (tp + fp == 0) { return 1.0; } return (double) tp / (tp + fp); } }