Advertisement
Guest User

codigo

a guest
Dec 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.58 KB | None | 0 0
  1. package analise.redes.sociais;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.text.DateFormat;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8. import java.util.Formatter;
  9. import java.util.Scanner;
  10. import org.la4j.Matrix;
  11. import org.la4j.decomposition.EigenDecompositor;
  12. import org.la4j.matrix.dense.Basic2DMatrix;
  13.  
  14. public class ANALISEREDESSOCIAIS {
  15.  
  16. private final static String SEPARADOR_DADOS_FICH = ",";
  17.  
  18. private static final Scanner input = new Scanner(System.in);
  19. private static final Formatter output = new Formatter(System.out);
  20.  
  21. public static void main(String[] args) throws FileNotFoundException {
  22. if (args[0].equals("-n")) {
  23. String nomeFicheiroNos = args[1];
  24. String nomeFicheiroRamos = args[2];
  25. //Contagem do número de elementos
  26. int nElems = contagemEntidades(nomeFicheiroNos);
  27.  
  28. if (nElems == 0) {
  29. System.out.println("Ficheiro de entrada com erros");
  30. System.out.println("(Erro: O ficheiro de entrada contém menos de 1 ou mais de 200 nós)");
  31. } else {
  32. //Criação da Matriz de Adjacência
  33. double matrizAdjacencia[][] = new double[nElems][nElems];
  34. //Criação do vetor de Id's
  35. String vetorIds[] = new String[nElems];
  36. double valoresProprios[] = new double[nElems];
  37. double vetorProprio[] = new double[nElems];
  38. double matrizB[][] = new double[nElems][nElems];
  39. double matrizC[][] = new double[nElems][nElems];
  40. preenchimentoVetorIds(vetorIds, nomeFicheiroNos);
  41. int erro = preenchimentoMatrizAdjacencia(matrizAdjacencia, vetorIds, nomeFicheiroRamos);
  42. if (erro == 1) {
  43. System.out.println("O ficheiro de entrada continha um erro que foi corrigido");
  44. System.out.println("(Erro: Estabelecer uma relação entre o mesmo Id)");
  45. }
  46. int op;
  47. do {
  48. op = menu();
  49. switch (op) {
  50. case 1:
  51. System.out.println("");
  52. impressaoMatrizAdjacencia(matrizAdjacencia, nElems);
  53. System.out.println("");
  54. break;
  55. case 2:
  56. System.out.println("");
  57. for (int indice = 0; indice < nElems; indice++) {
  58. float grau = calculoDoGrauDeUmNo(indice, nElems, matrizAdjacencia);
  59. System.out.println("O nó de Id " + vetorIds[indice] + " tem grau " + grau);
  60. }
  61. System.out.println("");
  62. break;
  63. case 3:
  64. System.out.println("");
  65. obterValoresProprios(matrizAdjacencia, nElems, valoresProprios, vetorProprio);
  66. output.format("%s%.3f%n","A centralidade tem valor ", descobrirCentralidadeVetor(vetorProprio));
  67. System.out.println("");
  68. break;
  69. case 4:
  70. System.out.println("");
  71. output.format("%s%.3f%n","O grau médio é ", grauMedio(nElems, matrizAdjacencia));
  72. System.out.println("");
  73. break;
  74. case 5:
  75. System.out.println("");
  76. float densidade = densidadeRede(nElems, matrizAdjacencia);
  77. output.format("%s%.3f%n","A densidade da rede tem valor ", densidade);
  78. System.out.println("");
  79. break;
  80. case 6:
  81. System.out.println("");
  82. clonarMatriz(matrizAdjacencia, matrizB);
  83. int comprimento = pedirComprimento();
  84. System.out.println("k=1:");
  85. impressaoMatrizAdjacencia(matrizAdjacencia, nElems);
  86. for (int k = 2; k <= comprimento; k++) {
  87. System.out.println("k=" + k + ":");
  88. produtoMatrizes(matrizAdjacencia, matrizB, matrizC);
  89. clonarMatriz(matrizC, matrizB);
  90. impressaoMatrizAdjacencia(matrizB, nElems);
  91. }
  92. System.out.println("");
  93. break;
  94. case 0:
  95. System.out.println("");
  96. System.out.println("Já fez todas as gravações necessárias? Confirma terminar (s/n)?");
  97. char resp = (input.next()).charAt(0);
  98. if ((resp != 's') && (resp != 'S')) {
  99. op = 1;
  100. }
  101. break;
  102. default:
  103. System.out.println("");
  104. System.out.println("Opção incorreta. Repita");
  105. System.out.println("");
  106. break;
  107. }
  108. } while (op != 0);
  109. }
  110.  
  111. } else if (args[0].equals("-t")) {
  112. int k = Integer.parseInt(args[2]);
  113. String nomeFicheiroNos = args[3];
  114. //String nomeFicheiroNos = "rs_media_nos.csv";
  115. String nomeFicheiroRamos = args[4];
  116. String[] temp = nomeFicheiroNos.split("_");
  117. String dataSist = getDateTime();
  118. Formatter outfile = new Formatter(new File("out_" + temp[1] + "_" + dataSist + ".txt"));
  119. int nElems = contagemEntidades(nomeFicheiroNos);
  120.  
  121. if (nElems == 0) {
  122. outfile.format("%n%s%n%n%s%n", "Ficheiro de entrada com erros", "(Erro: O ficheiro de entrada contém menos de 1 ou mais de 200 nós)");
  123. } else {
  124. double matrizAdjacencia[][] = new double[nElems][nElems];
  125. String vetorIds[] = new String[nElems];
  126. double valoresProprios[] = new double[nElems];
  127. double vetorProprio[] = new double[nElems];
  128. double matrizB[][] = new double[nElems][nElems];
  129. double matrizC[][] = new double[nElems][nElems];
  130. preenchimentoVetorIds(vetorIds, nomeFicheiroNos);
  131. int erro = preenchimentoMatrizAdjacencia(matrizAdjacencia, vetorIds, nomeFicheiroRamos);
  132. if (erro == 1) {
  133. outfile.format("%n%s%n%n%s%n", "O ficheiro de entrada continha um erro que foi corrigido", "(Erro: Estabelecer uma relação entre o mesmo Id)");
  134. }
  135.  
  136. outfile.format("%s%n%n", "1 - Impressão da matriz de adjacências (com relações):");
  137. impressaoMatrizAdjacenciaFicheiro(matrizAdjacencia, nElems, outfile);
  138. outfile.format("%s%n%n", "2 - Cálculo do grau de todos os nós:");
  139. for (int indice = 0; indice < nElems; indice++) {
  140. float grau = calculoDoGrauDeUmNo(indice, nElems, matrizAdjacencia);
  141. outfile.format("%s%n", "O nó de Id " + vetorIds[indice] + " tem grau " + grau);
  142. }
  143. outfile.format("%n%s%n", "3 - Centralidade do vetor próprio:");
  144. obterValoresProprios(matrizAdjacencia, nElems, valoresProprios, vetorProprio);
  145. outfile.format("%n%s%.3f%s%n", "A centralidade tem valor ", descobrirCentralidadeVetor(vetorProprio), ".");
  146. outfile.format("%n%s%n", "4 - Cálculo do grau médio:");
  147. outfile.format("%n%s%.3f%s%n", "O grau médio é ", grauMedio(nElems, matrizAdjacencia), ".");
  148. outfile.format("%n%s%n", "5 - Cálculo da densidade da rede:");
  149. float densidade = densidadeRede(nElems, matrizAdjacencia);
  150. outfile.format("%n%s%.3f%s%n", "A densidade da rede tem valor ", densidade, ".");
  151. outfile.format("%n%s%n", "6 - Cálculo de uma potência da matriz de adjacências:");
  152. outfile.format("%n%s%n", "k=1:");
  153. clonarMatriz(matrizAdjacencia, matrizB);
  154. impressaoMatrizAdjacenciaFicheiro(matrizAdjacencia, nElems, outfile);
  155. for (int i = 2; i <= k; i++) {
  156. outfile.format("%n%s%n", "k=" + i + ":");
  157. produtoMatrizes(matrizAdjacencia, matrizB, matrizC);
  158. clonarMatriz(matrizC, matrizB);
  159. impressaoMatrizAdjacenciaFicheiro(matrizB, nElems, outfile);
  160. }
  161. }
  162. outfile.close();
  163.  
  164. }
  165.  
  166. }
  167.  
  168. public static int menu() {
  169. int op;
  170. String menu = " MENU:"
  171. + "\n"
  172. + "\n 1 - Impressão da matriz de adjacências (com relações)"
  173. + "\n 2 - Cálculo do grau de todos os nós"
  174. + "\n 3 - Centralidade do vetor próprio"
  175. + "\n 4 - Cálculo do grau médio"
  176. + "\n 5 - Cálculo da densidade da rede"
  177. + "\n 6 - Cálculo de uma potência da matriz de adjacências"
  178. + "\n 0 - Terminar"
  179. + "\n"
  180. + "\n Digite a sua opção: ";
  181. output.format("%s", menu);
  182. op = input.nextInt();
  183. input.nextLine();
  184. return op;
  185. }
  186.  
  187. public static int contagemEntidades(String nomeFicheiroNos) throws FileNotFoundException {
  188. int contagem = 0;
  189. Scanner inputFile = new Scanner(new File(nomeFicheiroNos));
  190. while (inputFile.hasNextLine()) {
  191. String linha = inputFile.nextLine();
  192. if ((linha.trim()).length() > 0) {
  193. contagem = contagem + 1;
  194. }
  195. }
  196. if ((contagem - 1) <= 0 || (contagem - 1) > 200) {
  197. return 0;
  198. }
  199. return (contagem - 1);
  200. }
  201.  
  202. public static void preenchimentoVetorIds(String vetorIds[], String nomeFicheiroNos) throws FileNotFoundException {
  203. Scanner inputFile = new Scanner(new File(nomeFicheiroNos));
  204. int i = 0;
  205. inputFile.nextLine();
  206. while (inputFile.hasNextLine()) {
  207. String linha = inputFile.nextLine();
  208. if (linha.trim().length() > 0) {
  209. String[] temp = linha.split(SEPARADOR_DADOS_FICH);
  210. vetorIds[i] = temp[0];
  211. i++;
  212. }
  213. }
  214. }
  215.  
  216. public static void impressaoMatrizAdjacencia(double matrizAdjacencia[][], int nElems) {
  217. for (int i = 0; i < nElems; i++) {
  218. for (int j = 0; j < nElems; j++) {
  219. output.format("%5s", matrizAdjacencia[i][j]);
  220. }
  221. output.format("%n%n", "");
  222. }
  223. }
  224.  
  225. public static void impressaoMatrizAdjacenciaFicheiro(double matrizAdjacencia[][], int nElems, Formatter outfile) {
  226. for (int i = 0; i < nElems; i++) {
  227. for (int j = 0; j < nElems; j++) {
  228. outfile.format("%5s", matrizAdjacencia[i][j]);
  229. }
  230. outfile.format("%n%n", "");
  231. }
  232. }
  233.  
  234. public static int procurarPosicaoVetor(String vetor[], String elemento) {
  235. for (int i = 0; i < vetor.length; i++) {
  236. if (elemento.equals(vetor[i])) {
  237. return i;
  238. }
  239. }
  240. return 0;
  241. }
  242.  
  243. public static int preenchimentoMatrizAdjacencia(double matrizAdjacencia[][], String vetorIds[], String nomeFicheiroRamos) throws FileNotFoundException {
  244. Scanner inputFile = new Scanner(new File(nomeFicheiroRamos));
  245. int flag = 0;
  246. int pos1, pos2;
  247. inputFile.nextLine();
  248. while (inputFile.hasNextLine()) {
  249. String linha = inputFile.nextLine();
  250. if (linha.trim().length() > 0) {
  251. String[] temp = linha.split(SEPARADOR_DADOS_FICH);
  252. pos1 = procurarPosicaoVetor(vetorIds, temp[0].trim());
  253. pos2 = procurarPosicaoVetor(vetorIds, temp[1].trim());
  254. if (pos1 == pos2) {
  255. flag = 1;
  256. }
  257. if (!(pos1 == pos2)) {
  258. matrizAdjacencia[pos1][pos2] = 1;
  259. matrizAdjacencia[pos2][pos1] = 1;
  260. }
  261. }
  262. }
  263. return flag;
  264. }
  265.  
  266. public static float calculoDoGrauDeUmNo(int no, int nElems, double matrizAdjacencia[][]) {
  267. float grau = 0;
  268. for (int i = 0; i < nElems; i++) {
  269. if (matrizAdjacencia[no][i] != 0) {
  270. grau = grau + 1;
  271. }
  272. }
  273. return grau;
  274. }
  275.  
  276. public static void obterValoresProprios(double matrizAdjacencia[][], int nElems, double valoresProprios[], double vetorProprio[]) {
  277. Matrix a = new Basic2DMatrix(matrizAdjacencia);
  278. EigenDecompositor eigenD = new EigenDecompositor(a);
  279. Matrix[] mattD = eigenD.decompose();
  280. double matA[][] = mattD[0].toDenseMatrix().toArray();
  281. double matB[][] = mattD[1].toDenseMatrix().toArray();
  282. for (int i = 0; i < nElems; i++) {
  283. for (int j = 0; j < nElems; j++) {
  284. if (i == j) {
  285. valoresProprios[i] = matB[i][j];
  286. }
  287. }
  288. }
  289. int indice = verIndiceDoMaiorElementoNumVetor(valoresProprios);
  290. for (int c = 0; c < nElems; c++) {
  291. vetorProprio[c] = matA[c][indice];
  292. }
  293. }
  294.  
  295. public static int verIndiceDoMaiorElementoNumVetor(double vetor[]) {
  296. double valor = vetor[0];
  297. int indice = 0;
  298. for (int i = 1; i < vetor.length; i++) {
  299. if (vetor[i] > valor) {
  300. valor = vetor[i];
  301. indice = i;
  302. }
  303. }
  304. return indice;
  305. }
  306.  
  307. public static double descobrirCentralidadeVetor(double vetorProprio[]) {
  308. int indice = verIndiceDoMaiorElementoNumVetor(vetorProprio);
  309. double centralidade = vetorProprio[indice];
  310. return centralidade;
  311. }
  312.  
  313. public static float grauMedio(int nElems, double matrizAdjacencia[][]) {
  314. float grauMedio = 0;
  315. for (int j = 0; j < nElems; j++) {
  316. grauMedio = grauMedio + calculoDoGrauDeUmNo(j, nElems, matrizAdjacencia);
  317. }
  318. return grauMedio / nElems;
  319. }
  320.  
  321. public static float densidadeRede(int nElem, double matrizAdjacencia[][]) {
  322. float maxRamos = (nElem * nElem - nElem) / 2;
  323. float numRamos = numRamos(matrizAdjacencia, nElem);
  324. return numRamos / maxRamos;
  325. }
  326.  
  327. public static float numRamos(double matrizAdjacencia[][], int nElem) {
  328. int numRamos = 0;
  329. for (int i = 0; i < nElem - 1; i++) {
  330. for (int j = i + 1; j < nElem; j++) {
  331. if (matrizAdjacencia[i][j] == 1) {
  332. numRamos++;
  333. }
  334. }
  335. }
  336. return numRamos;
  337. }
  338.  
  339. public static int pedirComprimento() {
  340. int comprimento;
  341. do {
  342. System.out.print("Digite o comprimento das ligações desejado: ");
  343. comprimento = input.nextInt();
  344. System.out.println("");
  345. input.nextLine();
  346. } while (comprimento < 1);
  347. return comprimento;
  348. }
  349.  
  350. public static void clonarMatriz(double[][] matrizAdjacencias, double[][] matrizB) {
  351. for (int i = 0; i < matrizAdjacencias.length; i++) {
  352. matrizB[i] = matrizAdjacencias[i].clone();
  353. }
  354. }
  355.  
  356. public static void produtoMatrizes(double[][] matrizAdjacencias, double[][] matrizB, double[][] matrizC) {
  357. double soma = 0;
  358. for (int j = 0; j < matrizAdjacencias.length; j++) {
  359. for (int i = 0; i < matrizAdjacencias[j].length; i++) {
  360. soma = 0;
  361. for (int k = 0; k < matrizAdjacencias.length; k++) {
  362. soma = soma + matrizAdjacencias[j][k] * matrizB[k][i];
  363. }
  364. matrizC[j][i] = soma;
  365. }
  366. }
  367. }
  368.  
  369. private static String getDateTime() {
  370. DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  371. Date date = new Date();
  372. String data = dateFormat.format(date);
  373. String[] temp = data.split(" ");
  374. String[] temp1 = temp[0].split("/");
  375. String dataFinal = temp1[0] + temp1[1] + temp1[2];
  376. return dataFinal;
  377. }
  378. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement