复选框工具8.7——Needleman Wusch算法全局比对

Needleman-Wunsch算法是一种经典的全局序列比对方法,用于比较DNA或蛋白质序列的同源性。它通过二维表格计算最佳比对,考虑匹配、不匹配和空格的情况。算法初始填充第二行和第二列,然后逐个填充其余单元格,选择得分最高的路径。最终从右下角单元格回溯得到比对字符串和得分。

Needleman Wusch算法

是经典的全局比对算法,用于比对两条DNA序列或者蛋白质序列的同源性或者说相似性;

 全局序列比对:  尝试找到两个完整的序列 S1 和 S2 之间的最佳比对。如S1=GCCCTAGCG S2=GCGCAATG 如果设定每个匹配字符为1分,每个空格为-2分,每个不匹配为-1分,则下面的比对就是全局最优比对:S1'=GCCCTAGCG S2'=GCGC_AATG,连字符“_”代表空格。在 S2' 中有五个匹配字符,一个空格(或者反过来说,在 S1' 中有一个插入项),有三个不匹配字符。这样得到的分数是 (5×1) + (1×-2) + (3×-1) = 0,这是能够实现的最佳结果。

  局部序列比对: 不必对两个完整的序列进行比对;可以在每个序列中使用某些部分来获得最大得分。使用同样的序列 S1 和 S2,以及同样的得分方案,可以得到以下局部最优比对 S1'' 和 S2'':S1=GCCCTAGCG S2=GCGCAATG   S1''=GCG S2''=GCG,虽然这个局部比对恰好没有不匹配字符或空格,但是一般情况下,局部比对可能存在不匹配字符或空格。这个局部比对的得分是 (3×1) + (0×-2) + (0×-1) = 3。(最佳局部比对的得分要大于或等于最佳全局比对的得分,这是因为全局比对也属于局部比对)

百度经验:https://jingyan.baidu.com/article/358570f6b545cace4724fcbb.html

Needleman Wusch算法全局比对(Java)

 

  该算法用来计算全局比对。它的思路与 LCS 算法相似。这个算法也使用二维表格,一个序列沿顶部展开,一个序列沿左侧展开。而且也能通过以下三个途径到达每个单元格:1.来自上面的单元格,代表将左侧的字符与空格比对。2.来自左侧的单元格,代表将上面的字符与空格比对。3.来自左上侧的单元格,代表与左侧和上面的字符比对(可能匹配也可能不匹配)。该单元格的值来自于一下3个中的最大值:(1)上方的值-2 (2)左边的值-2 (3)如果该单元格所在的行于所在的列对应的字符相等,则为左上值加1,否则为左上值-1。

 

       首先,必须初始化表格。这意味着填充第二行和第二列的分数和指针。填充第二行的操作意味着使用位于顶部的第一个序列中的字符,并使用空格,而不是使用左侧从上到下的序列中的第一个字符。空格的扣分是 -2,所以每次使用空格的时候,就给以前的单元格加了 -2 分。以前的单元格是左侧的单元格。这就说明了在第二行中为什么得到了 0, -2, -4, -6, ... 这样的序列。用相似的方式得到第二列的得分和指针.

       接下来,需要填充余下的单元格。同 LCS 算法一样,对于每个单元格,都有三个选择,要从中选择最大的。可以从上面、左侧、左上侧到达每个单元格。假设 S1 和 S2 是要比对的字符串,S1' 和 S2' 是生成的比对中的字符串。从上面到达单元格相当于将左面的字符从 S2 加入 S2',跳过上面的 S1 中的当前字符,并在 S1'中加入一个空格。因为一个空格的分数是 -2,所以当前单元格的得分要从上面的单元格得分减 2 得到。类似的,将左边的单元格得分减 2,可以从左侧到达空单元格。

       最后,可以将上面的字符加入到 S1' 中,将左边的字符加入到 S2' 中。这就相当于从左上侧进入空白单元格。这两个字符将会匹配,在这种情况下,新的得分就是左上侧单元格的得分减 1。在这三种可能性当中,选择得分最大的一个(如果得分相等,可以从得分高的单元格中从任选一个)。接下来,需要得到实际的比对字符串S1' 和S2'以及比对的得分。右下角单元格中的得分包含 S1 和 S2 的最大比对得分,就像在 LCS 算法中包含 LCS 的长度一样。而且,与 LCS 算法类似,要获得 S1' 和 S2',要从右下角单元格开始沿着指针回溯,反向构建 S1' 和 S2'。从表格的构建过程可知,从上向下对应着将左侧字符从 S2 加入到 S2' 中,将空格加入 S1' 中;从左向右对应着将上面的字符从 S1 加入到 S1' 中,将空格加入 S2' 中;而向下和向右移动意味着分别将来自S1 和 S2 的字符加入 S1' 和 S2'

 

代码:


import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.highgo.Test.XMLDemo1;

import java.io.InputStream;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Highgo
 */



public class CheckboxSwing extends javax.swing.JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Creates new form CheckboxSwing
	 * 
	 * @throws IOException
	 */
	public CheckboxSwing() throws IOException {
		this.setTitle("CheckboxSwing");
		initComponents();
		inittable();
		this.setLocationRelativeTo(null);

	}

	private CheckboxSwing getThis() {
		return this;
	}



	private String filepath = null;
	private String comppath = null;
	private String resultpath = null;
	private void dathinit()  {

		jTabcheckbox.getModel();

		getXml();

		jTextArea1.append(filepath);

		if (filepath == null || filepath.trim().equals("")) {
		} 
		else {
			traverseFolder(filepath,0);
		}
	}

	private void getXml() {

		SAXReader reader = new SAXReader();

		try {
			InputStream is = new FileInputStream("../filedath.xml");

			Document doc= null;
			doc = reader.read(is);

			Element root = doc.getRootElement();
			int i = 0;
			Iterator<Element> it = root.elementIterator();
			while(it.hasNext()){
				Element e = it.next();//获取子元素

				//Attribute idAttr = e.attribute("id");
				//String id = idAttr.getValue();
				//System.out.println(id);

				//通过元素对象获取子元素对象
				Element nameElement = e.element("name");
				//获取元素中的文本内容
				if(i == 0) {
					filepath = nameElement.getText();
					//System.out.println(filepath);
				}
				if(i == 1) {
					comppath = nameElement.getText();
				}
				if(i == 2) {
					resultpath = nameElement.getText();
				}
				i++;
			}   
			
		} catch (DocumentException | FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 

	}


	private   DefaultMutableTreeNode traverseFolder(String path,int n) {
		DefaultMutableTreeNode temp;


		DefaultTableModel model = (DefaultTableModel) jTabcheckbox.getModel();
		DefaultMutableTreeNode fujiedian = new DefaultMutableTreeNode(new File(path).getName());
		File file = new File(path);
		if (file.exists()) {
			if(file.isDirectory()) {
				File[] files = file.listFiles();
				if (files.length == 0) {
					if(file.isDirectory()) {//如果是空文件夹
						DefaultMutableTreeNode dn = new DefaultMutableTreeNode(file.getName(), false);
						return dn;
					}
				}else{
					for (File file2 : files) {
						if (file2.isDirectory()) {
							//是目录的话,生成节点,并添加里面的节点
							if( n < 5) {
								n++;
								fujiedian.add(traverseFolder(file2.getAbsolutePath(),n));
							}
						}else{
							//是文件的话直接生成节点,并把该节点加到对应父节点上

							try {
								String fileName = file2.getName();
								String fapat = file2.getCanonicalPath();

								model.addRow(new Object[] { true, model.getRowCount() + 1 ,fileName,fapat});
								temp = new DefaultMutableTreeNode(file2.getName());
								fujiedian.add(temp);	
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}	

						}
						javax.swing.tree.DefaultTreeModel dm = new DefaultTreeModel(fujiedian);
						// 将模型设给树,树上显示的将上前面所加载的节点
						jTree.setModel(dm);
					}
				}
			} else {
				//model.addRow(new Object[] { true, model.getRowCount() + 1 ,file.getName()});
			}
		} else {//文件不存在
			return null;
		}
		return fujiedian;

	}

	private void inittable()  {

		DefaultTableModel model = (DefaultTableModel) jTabcheckbox.getModel();




		jTree.setModel(null);
		jBAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				for (int i = 0; i < model.getRowCount(); i++) {
					model.setValueAt(Boolean.valueOf(true), i, 0);
				}

			}
		});

		jBAllNot.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				for (int i = 0; i < model.getRowCount(); i++) {
					model.setValueAt(Boolean.valueOf(false), i, 0);
				}
			}
		});

		jBClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				model.setRowCount(0);
			}
		});

		jBDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int sum = model.getRowCount();

				for(int i = sum - 1; i >=0; i--) {
					if((boolean) model.getValueAt(i, 0) == true) {
						model.removeRow(i);
					}
				}
			}



		});

		getRootPane().setDefaultButton(jBOK);
		jBOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Boolean str = null;
				String[] mojdlogName =  new String[model.getRowCount()];
				String[] mojdlogPath =  new String[model.getRowCount()];
				int mi = 0;
				for (int i = 0; i < model.getRowCount(); i++) {
					str =  (Boolean) model.getValueAt(i, 0);
					if (str.equals(true)) {
						mojdlogName[mi] = (String) model.getValueAt(i, 2);
						mojdlogPath[mi] = (String) model.getValueAt(i, 3);
						System.out.println(mojdlogName[mi]);
						System.out.println(mojdlogPath[mi]);
						mi++;
						System.out.println("true" + (i + 1));
					} else {
						System.out.println("false" + (i + 1));
					}
				}
				System.out.println(mojdlogName);
				
				new NewJDialog(getThis(), true, mojdlogName,mojdlogPath,comppath,resultpath);
			}
		});

		jBDath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dathinit();
			}
		});




	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jBAllNot = new javax.swing.JButton();
		jBAll = new javax.swing.JButton();
		jSPTabel = new javax.swing.JScrollPane();
		jTabcheckbox = new javax.swing.JTable();
		jBOK = new javax.swing.JButton();
		jSPArea = new javax.swing.JScrollPane();
		jTextArea1 = new javax.swing.JTextArea();
		jBDath = new javax.swing.JButton();
		jBClear = new javax.swing.JButton();
		jBDelete = new javax.swing.JButton();
		jSPTree = new javax.swing.JScrollPane();
		jTree = new javax.swing.JTree();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jBAllNot.setText("ANOT");

		jBAll.setText("ALL");

		jTabcheckbox.setModel(new javax.swing.table.DefaultTableModel(
				new Object [][] {

				},
				new String [] {
						"Choose", "line", "Name", "path"
				}
				) {
			Class[] types = new Class [] {
					java.lang.Boolean.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class
			};

			public Class getColumnClass(int columnIndex) {
				return types [columnIndex];
			}
		});
		jSPTabel.setViewportView(jTabcheckbox);
		if (jTabcheckbox.getColumnModel().getColumnCount() > 0) {
			jTabcheckbox.getColumnModel().getColumn(0).setMinWidth(30);
			jTabcheckbox.getColumnModel().getColumn(0).setPreferredWidth(60);
			jTabcheckbox.getColumnModel().getColumn(0).setMaxWidth(200);
			jTabcheckbox.getColumnModel().getColumn(1).setMinWidth(30);
			jTabcheckbox.getColumnModel().getColumn(1).setPreferredWidth(50);
			jTabcheckbox.getColumnModel().getColumn(1).setMaxWidth(200);
			jTabcheckbox.getColumnModel().getColumn(3).setMinWidth(30);
			jTabcheckbox.getColumnModel().getColumn(3).setPreferredWidth(30);
		}

		jBOK.setText("OK");

		jTextArea1.setColumns(20);
		jTextArea1.setRows(5);
		jSPArea.setViewportView(jTextArea1);

		jBDath.setText("Dath");

		jBClear.setText("Clear");

		jBDelete.setText("Delete");

		jSPTree.setViewportView(jTree);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addGap(39, 39, 39)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
								.addComponent(jBAllNot, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(jBAll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
						.addGap(18, 18, 18)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
								.addComponent(jBDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(jBClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 66, Short.MAX_VALUE)
						.addComponent(jSPArea, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jBDath, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(26, 26, 26))
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addGap(162, 162, 162)
						.addComponent(jBOK, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addGap(169, 169, 169))
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addComponent(jSPTabel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jSPTree)
						.addContainerGap())
				);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addComponent(jSPArea, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGroup(layout.createSequentialGroup()
										.addContainerGap()
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jBAll)
												.addComponent(jBClear))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jBAllNot)
												.addComponent(jBDelete)))
								.addComponent(jBDath))
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(layout.createSequentialGroup()
										.addComponent(jSPTabel, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
										.addGap(3, 3, 3))
								.addGroup(layout.createSequentialGroup()
										.addGap(6, 6, 6)
										.addComponent(jSPTree)
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
						.addComponent(jBOK)
						.addGap(6, 6, 6))
				);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
		// (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the default
		 * look and feel. For details see
		 * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
					ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
					ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
					ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(CheckboxSwing.class.getName()).log(java.util.logging.Level.SEVERE, null,
					ex);
		}
		// </editor-fold>
		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					new CheckboxSwing().setVisible(true);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton jBAll;
	private javax.swing.JButton jBAllNot;
	private javax.swing.JButton jBClear;
	private javax.swing.JButton jBDath;
	private javax.swing.JButton jBDelete;
	private javax.swing.JButton jBOK;
	private javax.swing.JScrollPane jSPArea;
	private javax.swing.JScrollPane jSPTabel;
	private javax.swing.JScrollPane jSPTree;
	private javax.swing.JTable jTabcheckbox;
	private javax.swing.JTextArea jTextArea1;
	private javax.swing.JTree jTree;
	// End of variables declaration//GEN-END:variables
}

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.BadLocationException;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Highgo
 */
public class NewJDialog extends javax.swing.JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean compbl;
	//	private  String RESULT_FILE_PATH = "src/result.txt";




	private String[] path;
	
	private String comppath;
	private String resultpath;
	public NewJDialog(java.awt.Frame parent, boolean modal, String[] mojdlogName, String[] mojdlogPath, String comp_path, String result_path) {
		super(parent, modal);
		initComponents();
		path = mojdlogPath;
		comppath = comp_path;
		resultpath = result_path;
		String file_path = null;
		
		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		for(int i = 0 ; i < mojdlogName.length; i++) {
			if(mojdlogName[i] != null) {
				file_path = mojdlogPath[i];
				
				compare(file_path,comp_path);
				model.addRow(new Object[] { model.getRowCount() + 1 ,mojdlogName[i], compbl});
			}
			
		}
	//	System.out.println(path);
		initAction();

		this.setTitle("NewjDialog");
		this.setLocationRelativeTo(null);
		this.setVisible(true);



	}

	private void compare(String file_path,String comp_path) {
		try {
			BufferedReader	br = new BufferedReader(new FileReader(file_path));
			BufferedReader  cbr = new BufferedReader(new FileReader(comp_path));

			compbl = false;
			String brStr = null;
			String cbrStr = null;
			while((brStr = br.readLine()) != null  && (cbrStr = cbr.readLine()) != null) {
				if (brStr.equals(cbrStr)) {
					compbl = true;
				} else {
					compbl = false;
					break;
				}
			}
			if(compbl = true) {
				while ((cbrStr = cbr.readLine()) != null)
				{
					compbl = false;
				}
				while((brStr = br.readLine()) != null )
				{
					compbl = false;
				}
			}
			try {
				br.close();
				cbr.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initAction() {
		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		jTable1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int clickCount = e.getClickCount();
				if ( clickCount == 2 ) {
					int numac = jTable1.getSelectedRow();
					System.out.println(numac);
					if (model.getValueAt(numac, 2).equals(false)) {
						String file_name = (String)model.getValueAt(numac, 1);
						new JDiaComp( null, true, numac, path,comppath,resultpath,file_name);
					}
				}		
			}
		});
	}


	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		jTable1 = new javax.swing.JTable();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

		jTable1.setModel(new javax.swing.table.DefaultTableModel(
				new Object [][] {

				},
				new String [] {
						"Line", "Name", "Boolean"
				}
				) {
			boolean[] canEdit = new boolean [] {
					false, false, false
			};

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit [columnIndex];
			}
		});
		jScrollPane1.setViewportView(jTable1);
		if (jTable1.getColumnModel().getColumnCount() > 0) {
			jTable1.getColumnModel().getColumn(0).setMinWidth(30);
			jTable1.getColumnModel().getColumn(0).setPreferredWidth(60);
			jTable1.getColumnModel().getColumn(0).setMaxWidth(150);
		}

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jScrollPane1)
						.addContainerGap())
				);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jScrollPane1)
						.addContainerGap())
				);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
		/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(NewJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/* Create and display the dialog */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				NewJDialog dialog = new NewJDialog(new javax.swing.JFrame(), true, null,null,null,null);
				dialog.addWindowListener(new java.awt.event.WindowAdapter() {
					@Override
					public void windowClosing(java.awt.event.WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTable jTable1;
	// End of variables declaration//GEN-END:variables
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import com.highgo.Test.*;

import java.awt.Color;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

/**
 *
 * @author Highgo
 */
public class JDiaComp extends javax.swing.JDialog {

	/**
	 * Creates new form JDiaComp
	 *   
	 * 
	 */


	public JDiaComp(java.awt.Frame parent, boolean modal, int num,Object[] Path,String comppath,String resultpath,String file_name)   {
		super(parent, modal);
		initComponents();
	
		//compare(filepath,comppath,resultpath,num);
		String result = resultpath + "//result_" + (num + 1) + file_name+ ".txt";
		compareDNA(num, Path, comppath, result);
		

		this.setTitle("JDiaComp");
		this.setLocationRelativeTo(null);
		this.setVisible(true);

	}


	private void compareDNA(int num,Object[] Path,String comppath,String resultpath) {
		String filepath ;
		String dnas1,dnas2;
		filepath = (String) Path[num];
		//String result = resultpath + "//result_" + (num + 1) + file_name+ ".txt";
		try {
			BufferedWriter rbw = new BufferedWriter(new FileWriter(resultpath));

			new Read_File(filepath);
			
			String File1= Read_File.getFile();
			new Read_File(comppath);
			String File2= Read_File.getFile();
			DNASequence dna = new DNASequence(File1,File2);
			dna.runAnalysis();
			dna.traceback();
			dnas1=dna.getString1();//获取处理后的字符串
			dnas2=dna.getString2();

			Document docs1=jTextPane1.getDocument();
			Document docs2=jTextPane2.getDocument();

			char[] s = dnas1.toCharArray();//字符串转Char数组
			char[] p = dnas2.toCharArray();
			int len=dnas1.length();
			SimpleAttributeSet set2 = new SimpleAttributeSet();//设置一个属性
			StyleConstants.setFontSize(set2,16);//设置字号
			for(int i=0;i<len;i++){
				if(s[i]=='~'){
					StyleConstants.setForeground(set2,Color.BLUE);//设置文字颜色
					docs2.insertString(docs2.getLength(),String.valueOf(p[i]), set2);
				}else if(p[i]=='~'){
					StyleConstants.setForeground(set2,Color.BLUE);//设置文字颜色
					docs1.insertString(docs1.getLength(),String.valueOf(s[i]), set2);
				}else if(s[i]==p[i]){
					StyleConstants.setForeground(set2,Color.black);//设置文字颜色
					docs1.insertString(docs1.getLength(),String.valueOf(s[i]), set2);
					docs2.insertString(docs2.getLength(),String.valueOf(p[i]), set2);
				}else if(s[i]!=p[i]){                                
					StyleConstants.setForeground(set2,Color.red);//设置文字颜色
					docs1.insertString(docs1.getLength(),String.valueOf(s[i]), set2);
					docs2.insertString(docs2.getLength(),String.valueOf(p[i]), set2);
				}else{
					System.out.print("考虑更多颜色");
				}
			}
			
			rbw.write(dnas1 + "\r\n" + dnas2);
		
			rbw.close();
			//jTextPane1.setText(dnas1);
			// jTextPane2.setText(dnas2);
		} catch (IOException | BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

	private void compare(String file_path, String comp_path,String result_path,int num) { 
		try {
			String result = result_path + "//result_" + (num + 1) + ".txt";
			BufferedReader	br = new BufferedReader(new FileReader(file_path));
			BufferedReader  cbr = new BufferedReader(new FileReader(comp_path));
			BufferedWriter  rbw = new BufferedWriter(new FileWriter(result));
			try {
				int lineNum = 0;
				String lineStr = null;
				String TlineStr = null;
				String brStr = null;
				String cbrStr = null;


				while((brStr = br.readLine()) != null  &&(cbrStr = cbr.readLine()) != null) 
				{
					lineNum++;
					if (brStr.equals(cbrStr)) {
						lineStr = brStr + "\n";
						setDocs(brStr, Color.black,true,13);
						rbw.write("  EQUAL   Line  " + lineNum + "  :  " + lineStr);

					} else
					{
						lineStr = brStr + "\n";
						//jTextPane1.setText(jTextPane1.getText() + lineStr);
						setDocs(brStr, Color.red,true,13);
						rbw.write("NOT EQUAL Line  " + lineNum + "  :  " + lineStr);
					}
					TlineStr = cbrStr + "\n";	
					//	jTextPane2.setText(jTextPane2.getText() + TlineStr);
					setDocs2(cbrStr, Color.black,true,13);

				}
				while ((cbrStr = cbr.readLine()) != null )
				{
					lineStr = cbrStr + "\n";
					//	jTextPane2.setText(jTextPane2.getText() + lineStr);
					//	jTextPane1.setText(jTextPane1.getText() + "       NULL       " + "\n");
					setDocs("       NULL       ", Color.black,true,13);
					setDocs2(cbrStr, Color.black,true,13);
					lineNum++;	
					rbw.write("br NULL Line:  " + lineNum + "\n");
				}
				while ((brStr = br.readLine()) != null )
				{
					lineStr = brStr  + "\n";
					//	jTextPane1.setText(jTextPane1.getText() + lineStr);
					//	jTextPane2.setText(jTextPane2.getText() + "       NULL       " + "\n");
					setDocs(brStr, Color.black,true,13);
					setDocs2("       NULL       ", Color.black,true,13);
					lineNum++;		
					rbw.write("Cbr NULL Line:  " + lineNum + "\n");
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				br.close();
				cbr.close();
				rbw.close();		
			}

		} catch (IOException e) {
			e.printStackTrace();
		} 

	}

	private void insert(String str, AttributeSet attrSet) { 
		Document doc = jTextPane1.getDocument(); 
		str = "\n " + str; 
		try { 
			doc.insertString(doc.getLength(), str, attrSet); 
		} 
		catch (BadLocationException e) { 
			System.out.println( "BadLocationException:   " + e); 
		} 
	} 
	private void setDocs(String str,Color col,boolean bold,int fontSize) { 

		SimpleAttributeSet attrSet = new SimpleAttributeSet(); 
		StyleConstants.setForeground(attrSet, col); 
		if(bold==true){ 
			StyleConstants.setBold(attrSet, true); 
		}
		StyleConstants.setFontSize(attrSet, fontSize); 
		insert(str, attrSet); 

	} 
	private void insert2(String str, AttributeSet attrSet) { 
		Document doc = jTextPane2.getDocument(); 
		str = "\n " + str; 
		try { 
			doc.insertString(doc.getLength(), str, attrSet); 
		} 
		catch (BadLocationException e) { 
			System.out.println( "BadLocationException:   " + e); 
		} 
	} 
	private void setDocs2(String str,Color col,boolean bold,int fontSize) { 

		SimpleAttributeSet attrSet = new SimpleAttributeSet(); 
		StyleConstants.setForeground(attrSet, col); 
		if(bold==true){ 
			StyleConstants.setBold(attrSet, true); 
		}
		StyleConstants.setFontSize(attrSet, fontSize); 
		insert2(str, attrSet); 

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		jTextPane1 = new javax.swing.JTextPane();
		jScrollPane3 = new javax.swing.JScrollPane();
		jTextPane2 = new javax.swing.JTextPane();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

		jScrollPane1.setViewportView(jTextPane1);

		jScrollPane3.setViewportView(jTextPane2);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
						.addContainerGap())
				);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addComponent(jScrollPane3)
								.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
						.addContainerGap())
				);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
		/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(JDiaComp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(JDiaComp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(JDiaComp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(JDiaComp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/* Create and display the dialog */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				JDiaComp dialog;
				try {
					dialog = new JDiaComp(new javax.swing.JFrame(), true, 0, null,null,null,null);

					dialog.addWindowListener(new java.awt.event.WindowAdapter() {
						@Override
						public void windowClosing(java.awt.event.WindowEvent e) {
							System.exit(0);
						}
					});
					dialog.setVisible(true);
				} catch (HeadlessException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JTextPane jTextPane1;
	private javax.swing.JTextPane jTextPane2;
	// End of variables declaration//GEN-END:variables
}


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Read_File {
     static  String fileName;
    
    public  Read_File(String str){
            fileName=str;    
    }
    public static String getFile(){
        BufferedReader br = null;
        StringBuffer sb = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"utf-8")); //这里可以控制编码
            sb = new StringBuffer();
            String line = null;
            while((line = br.readLine()) != null) {
                sb.append(line + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
        String data = new String(sb); //StringBuffer ==> String
        System.out.println("数据为==> " + data);
        return data;
    }
    
//    public static void main(String[] args) {
//        new Read_File("1");
//    }
}


//https://codereview.stackexchange.com/questions/182601/optimizing-needleman-wunsch-algorithm-in-java

public class DNASequence {
  protected final String seq_1, seq_2;    //要分析的两个序列
  public int alignmentScore;              //使用Needleman-Wunsch算法
  protected Node[][] matrix;              //存储分数和缩进
  protected final int matchScore, mismatchScore, indel;

  //用于打印DNA序列分析的字符串
  String top = "";        // Sequence 1
  String bottom = "";     // Sequence 2

  public DNASequence(String s1, String s2) {
      //我使用一个■作为缓冲,这样序列字符串正确对齐
      // 在矩阵中使用缩进和分数。
      ScoreScheme s = new ScoreScheme(2, -1, -2);  
      seq_1 = "\u25A0" + s1;
      seq_2 = "\u25A0" + s2;
      matchScore = s.matchScore;
      mismatchScore = s.mismatchScore;
      indel = s.indel;

      matrix = new Node[seq_1.length()][seq_2.length()];
      for (int i = 0; i < seq_1.length(); i++)
          matrix[i][0] = new Node(i * indel, i, 0);

      for (int i = 0; i < seq_2.length(); i++)
          matrix[0][i] = new Node(i * indel, 0, i);
  }

  //辅助方法,帮助决定使用哪种匹配/不匹配得分。
  protected int score(int i, int j) {
      if (seq_1.charAt(i) == seq_2.charAt(j))
          return matchScore;
      else
          return mismatchScore;
  }

  //在本地级别上实现Needleman-Wunsch algo的Helper方法。
  protected Node match(int i, int j) {
      Node s1,s2,s3;
      s1 = new Node(matrix[i-1][j-1].score + score(i, j), i, j);
      s2 = new Node(matrix[i-1][j].score + indel, i, j);
      s3 = new Node(matrix[i][j-1].score + indel, i, j);

      Node largest = new Node(Math.max(s1.score, Math.max(s2.score, s3.score)), i, j);
      if (s1.compareTo(largest) == 0)
          largest.prev = matrix[i-1][j-1];
      else if(s2.compareTo(largest) == 0)
          largest.prev = matrix[i-1][j];
      else
          largest.prev = matrix[i][j-1];
      return largest;
  }

  public Node runAnalysis() {
      for (int i = 1; i < seq_1.length(); i++) {
          for (int j = 1; j < seq_2.length(); j++){
              matrix[i][j] = match(i, j);
          }
      }
      alignmentScore = matrix[seq_1.length()-1][seq_2.length()-1].score;
      return matrix[seq_1.length()-1][seq_2.length()-1];
  }

  //辅助方法,逐步构建分析结果。它将返回
  //“尾巴”,因为我们可能还需要做一些工作。
  protected Node traceHelper(Node curr) {
      while (curr.prev != null) {
          if (curr.i - curr.prev.i == 1 && curr.j - curr.prev.j == 1){    // If the path leads diagonal
              boolean x = seq_1.charAt(curr.i) == seq_2.charAt(curr.j) ? true : false;
              if(x){
                  top = seq_1.charAt(curr.i) +top;
                  bottom = seq_2.charAt(curr.j) +bottom;
              }else{
                  top = seq_1.charAt(curr.i) + top;
                  bottom = seq_2.charAt(curr.j) + bottom;
              }
          }else if (curr.i - curr.prev.i == 1){               //如果这条路通向山顶
              top = seq_1.charAt(curr.i) + top;
              bottom = "~" +  bottom;                     //如果这条路通向左边
          }else if (curr.j - curr.prev.j == 1){
              top = " " + top;
              bottom = seq_2.charAt(curr.j) +  bottom;
          }
          curr = curr.prev;
      }
      return curr;
  }

//从矩阵的最后一个节点回溯到第一个索引节点。
  public void traceback() {
      Node curr = matrix[seq_1.length()-1][seq_2.length()-1];
      curr = traceHelper(curr);
      while (curr.i != 0 || curr.j != 0) {
          if (curr.i != 0 && curr.j == 0){
              curr.prev = matrix[curr.i-1][curr.j];
              curr = traceHelper(curr);
          }else if (curr.i == 0 && curr.j != 0) {
              curr.prev = matrix[curr.i][curr.j-1];
              curr = traceHelper(curr);
          }
      }

  //打印DNA序列分析
      System.out.println(top);
      System.out.println(bottom);
  }
  public String getString1(){
      return top;
  }
  public String getString2(){
      return bottom;
  }    

}
class Node implements Comparable<Node>{
  int i, j;
  int score;
  Node prev;

  public Node(int score, int x, int y) {
      this.i = x;
      this.j = y;
      this.score = score;
      this.prev = null;
  }
  public int compareTo(Node n) {
      return this.score - n.score;
  }
  public String toString() {
      return ""+score;
  }
}

class ScoreScheme {
  int matchScore, mismatchScore, indel;
  public ScoreScheme(int m1, int m2, int i) {
      matchScore = m1;
      mismatchScore = m2;
      indel = i;
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<companys>
    <company id="1001">
        <name>D:\\测试目录</name> 
    </company>
	 <company id="1002">
        <name>../File101.txt</name> 
    </company>
	 <company id="1003">
        <name>../result101</name> 
    </company>
</companys>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值