editablebayesnet.java
来自「Weka」· Java 代码 · 共 1,981 行 · 第 1/5 页
JAVA
1,981 行
parentset.deleteParent(nTargetNode, m_Instances); for (int iParent = 0; iParent < parentset.getNrOfParents(); iParent++) { int nParent = parentset.getParent(iParent); if (nParent > nTargetNode) { parentset.SetParent(iParent, nParent - 1); } } parentSets[iParentSet] = parentset; } m_ParentSets = parentSets; // update instances m_Instances.setClassIndex(-1); m_Instances.deleteAttributeAt(nTargetNode); m_Instances.setClassIndex(nAtts - 1); // update positions m_nPositionX.removeElementAt(nTargetNode); m_nPositionY.removeElementAt(nTargetNode); // update evidence & margins m_nEvidence.removeElementAt(nTargetNode); m_fMarginP.removeElementAt(nTargetNode); } // deleteNode /** * Delete nodes with indexes in selection from the network, updating instances, parentsets, * distributions Conditional distributions are condensed by taking the * values for the target node to be its first value. Used for manual * manipulation of the Bayesian network. * * @param nodes * array of indexes of nodes to delete. * @throws Exception */ public void deleteSelection(FastVector nodes) { // sort before proceeding for (int i = 0; i < nodes.size(); i++) { for (int j = i + 1; j < nodes.size(); j++) { if ((Integer) nodes.elementAt(i) > (Integer) nodes.elementAt(j)) { int h = (Integer) nodes.elementAt(i); nodes.setElementAt(nodes.elementAt(j), i); nodes.setElementAt(h, j); } } } // update undo stack if (m_bNeedsUndoAction) { addUndoAction(new DeleteSelectionAction(nodes)); } boolean bNeedsUndoAction = m_bNeedsUndoAction; m_bNeedsUndoAction = false; try { for (int iNode = nodes.size() - 1; iNode >= 0; iNode--) { deleteNode((Integer) nodes.elementAt(iNode)); } } catch (Exception e) { e.printStackTrace(); } m_bNeedsUndoAction = bNeedsUndoAction; } // deleteSelection /** XML helper function for selecting elements under a node with a given name * @param item XMLNode to select items from * @param sElement name of the element to return */ FastVector selectElements(Node item, String sElement) throws Exception { NodeList children = item.getChildNodes(); FastVector nodelist = new FastVector(); for (int iNode = 0; iNode < children.getLength(); iNode++) { Node node = children.item(iNode); if ((node.getNodeType() == Node.ELEMENT_NODE) && node.getNodeName().equals(sElement)) { nodelist.addElement(node); } } return nodelist; } // selectElements /** * XML helper function. Returns all TEXT children of the given node in one string. Between the * node values new lines are inserted. * * @param node * the node to return the content for * @return the content of the node */ public String getContent(Element node) { NodeList list; Node item; int i; String result; result = ""; list = node.getChildNodes(); for (i = 0; i < list.getLength(); i++) { item = list.item(i); if (item.getNodeType() == Node.TEXT_NODE) result += "\n" + item.getNodeValue(); } return result; } /** XML helper function that returns DEFINITION element from a XMLBIF document * for a node with a given name. * @param doc XMLBIF document * @param sName name of the node to get the definition for */ Element getDefinition(Document doc, String sName) throws Exception { NodeList nodelist = doc.getElementsByTagName("DEFINITION"); for (int iNode = 0; iNode < nodelist.getLength(); iNode++) { Node node = nodelist.item(iNode); FastVector list = selectElements(node, "FOR"); if (list.size() > 0) { Node forNode = (Node) list.elementAt(0); if (getContent((Element) forNode).trim().equals(sName)) { return (Element) node; } } } throw new Exception("Could not find definition for ((" + sName + "))"); } // getDefinition /** Paste modes. This allows for verifying that a past action does not cause * any problems before actually performing the paste operation. */ final static int TEST = 0; final static int EXECUTE = 1; /** Apply paste operation with XMLBIF fragment. This adds nodes in the XMLBIF fragment * to the network, together with its parents. First, paste in test mode to verify * no problems occur, then execute paste operation. If a problem occurs (e.g. parent * does not exist) then a exception is thrown. * @param sXML XMLBIF fragment to paste into the network */ public void paste(String sXML) throws Exception { try { paste(sXML, TEST); } catch (Exception e) { throw e; } paste(sXML, EXECUTE); } // paste /** Apply paste operation with XMLBIF fragment. Depending on the paste mode, the * nodes are actually added to the network or it is just tested that the nodes can * be added to the network. * @param sXML XMLBIF fragment to paste into the network * @param mode paste mode TEST or EXECUTE */ void paste(String sXML, int mode) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); Document doc = factory.newDocumentBuilder().parse(new org.xml.sax.InputSource(new StringReader(sXML))); doc.normalize(); // create nodes first NodeList nodelist = doc.getElementsByTagName("VARIABLE"); FastVector sBaseNames = new FastVector(); Instances instances = new Instances(m_Instances, 0); int nBase = instances.numAttributes(); for (int iNode = 0; iNode < nodelist.getLength(); iNode++) { // Get element FastVector valueslist; // Get the name of the node valueslist = selectElements(nodelist.item(iNode), "OUTCOME"); int nValues = valueslist.size(); // generate value strings FastVector nomStrings = new FastVector(nValues + 1); for (int iValue = 0; iValue < nValues; iValue++) { Node node = ((Node) valueslist.elementAt(iValue)).getFirstChild(); String sValue = ((CharacterData) (node)).getData(); if (sValue == null) { sValue = "Value" + (iValue + 1); } nomStrings.addElement(sValue); } FastVector nodelist2; // Get the name of the network nodelist2 = selectElements(nodelist.item(iNode), "NAME"); if (nodelist2.size() == 0) { throw new Exception("No name specified for variable"); } String sBaseName = ((CharacterData) (((Node) nodelist2.elementAt(0)).getFirstChild())).getData(); sBaseNames.addElement(sBaseName); String sNodeName = sBaseName; if (getNode2(sNodeName) >= 0) { sNodeName = "Copy of " + sBaseName; } int iAttempt = 2; while (getNode2(sNodeName) >= 0) { sNodeName = "Copy (" + iAttempt + ") of " + sBaseName; iAttempt++; } Attribute att = new Attribute(sNodeName, nomStrings); instances.insertAttributeAt(att, instances.numAttributes()); valueslist = selectElements(nodelist.item(iNode), "PROPERTY"); nValues = valueslist.size(); // generate value strings int nPosX = iAttempt * 10; int nPosY = iAttempt * 10; for (int iValue = 0; iValue < nValues; iValue++) { // parsing for strings of the form "position = (73, 165)" Node node = ((Node) valueslist.elementAt(iValue)).getFirstChild(); String sValue = ((CharacterData) (node)).getData(); if (sValue.startsWith("position")) { int i0 = sValue.indexOf('('); int i1 = sValue.indexOf(','); int i2 = sValue.indexOf(')'); String sX = sValue.substring(i0 + 1, i1).trim(); String sY = sValue.substring(i1 + 1, i2).trim(); try { nPosX = (Integer.parseInt(sX) + iAttempt * 10); nPosY = (Integer.parseInt(sY) + iAttempt * 10); } catch (NumberFormatException e) { System.err.println("Wrong number format in position :(" + sX + "," + sY + ")"); } } } if (mode == EXECUTE) { m_nPositionX.addElement(nPosX); m_nPositionY.addElement(nPosY); } } FastVector nodelist2; Estimator[][] distributions = new Estimator[nBase + sBaseNames.size()][]; ParentSet[] parentsets = new ParentSet[nBase + sBaseNames.size()]; for (int iNode = 0; iNode < nBase; iNode++) { distributions[iNode] = m_Distributions[iNode]; parentsets[iNode] = m_ParentSets[iNode]; } if (mode == EXECUTE) { m_Instances = instances; } // create arrows & create distributions for (int iNode = 0; iNode < sBaseNames.size(); iNode++) { // find definition that goes with this node String sName = (String) sBaseNames.elementAt(iNode); Element definition = getDefinition(doc, sName); parentsets[nBase + iNode] = new ParentSet(); // get the parents for this node // resolve structure nodelist2 = selectElements(definition, "GIVEN"); for (int iParent = 0; iParent < nodelist2.size(); iParent++) { Node parentName = ((Node) nodelist2.elementAt(iParent)).getFirstChild(); String sParentName = ((CharacterData) (parentName)).getData(); int nParent = -1; for (int iBase = 0; iBase < sBaseNames.size(); iBase++) { if (sParentName.equals((String) sBaseNames.elementAt(iBase))) { nParent = nBase + iBase; } } if (nParent < 0) { nParent = getNode(sParentName); } parentsets[nBase + iNode].addParent(nParent, instances); } // resolve conditional probability table int nCardinality = parentsets[nBase + iNode].getCardinalityOfParents(); int nValues = instances.attribute(nBase + iNode).numValues(); distributions[nBase + iNode] = new Estimator[nCardinality]; for (int i = 0; i < nCardinality; i++) { distributions[nBase + iNode][i] = new DiscreteEstimatorBayes(nValues, 0.0f); } String sTable = getContent((Element) selectElements(definition, "TABLE").elementAt(0)); sTable = sTable.replaceAll("\\n", " "); StringTokenizer st = new StringTokenizer(sTable.toString()); for (int i = 0; i < nCardinality; i++) { DiscreteEstimatorBayes d = (DiscreteEstimatorBayes) distributions[nBase + iNode][i]; for (int iValue = 0; iValue < nValues; iValue++) { String sWeight = st.nextToken(); d.addValue(iValue, new Double(sWeight).doubleValue()); } } if (mode == EXECUTE) { m_nEvidence.insertElementAt(-1, nBase + iNode); m_fMarginP.insertElementAt(new double[getCardinality(nBase + iNode)], nBase + iNode); } } if (mode == EXECUTE) { m_Distributions = distributions; m_ParentSets = parentsets; } // update undo stack if (mode == EXECUTE && m_bNeedsUndoAction) { addUndoAction(new PasteAction(sXML, nBase)); } } // paste /** * Add arc between two nodes Distributions are updated by duplication for * every value of the parent node. * * @param sParent * name of the parent node * @param sChild * name of the child node * @throws Exception * if parent or child cannot be found in network */ public void addArc(String sParent, String sChild) throws Exception { int nParent = getNode(sParent); int nChild = getNode(sChild); addArc(nParent, nChild); } // addArc /** * Add arc between two nodes Distributions are updated by duplication for * every value of the parent node. * * @param nParent * index of the parent node * @param nChild * index of the child node * @throws Exception */ public void addArc(int nParent, int nChild) throws Exception { // update undo stack if (m_bNeedsUndoAction) { addUndoAction(new AddArcAction(nParent, nChild)); } int nOldCard = m_ParentSets[nChild].getCardinalityOfParents(); // update parentsets m_ParentSets[nChild].addParent(nParent, m_Instances); // update distributions int nNewCard = m_ParentSets[nChild].getCardinalityOfParents(); Estimator[] ds = new Estimator[nNewCard]; for (int iParent = 0; iParent < nNewCard; iParent++) { ds[iParent] = Estimator.clone(m_Distributions[nChild][iParent % nOldCard]); } m_Distributions[nChild] = ds; } // addArc /** * Add arc between parent node and each of the nodes in a given list. * Distributions are updated as above. * * @param sParent * name of the parent node * @param nodes * array of indexes of child nodes * @throws Exception */ public void addArc(String sParent, FastVector nodes) throws Exception { int nParent = getNode(sParent); // update undo stack if (m_bNeedsUndoAction) { addUndoAction(new AddArcAction(nParent, nodes)); } boolean bNeedsUndoAction = m_bNeedsUndoAction; m_bNeedsUndoAction = false; for (int iNode = 0; iNode < nodes.size(); iNode++) { int nNode = (Integer) nodes.elementAt(iNode); addArc(nParent, nNode); } m_bNeedsUndoAction = bNeedsUndoAction; } // addArc /** * Delete arc between two nodes. Distributions are updated by condensing for * the parent node taking its first value. * * @param sParent * name of the parent node * @param sChild * name of the child node * @throws Exception * if parent or child cannot be found in network */ public void deleteArc(String sParent, String sChild) throws Exception { int nParent = getNode(sParent); int nChild = getNode(sChild); deleteArc(nParent, nChild); } // deleteArc /** * Delete arc between two nodes. Distributions are updated by condensing for * the parent node taking its first value. * * @param nParent * index of the parent node * @param nChild * index of the child node * @throws Exception */ public void deleteArc(int nParent, int nChild) throws Exception { // update undo stack if (m_bNeedsUndoAction) { addUndoAction(new DeleteArcAction(nParent, nChild));
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?