Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Logic Familiar Hierarchy - ObjectPanel.java

ObjectPanel.java

Caricato da: Nophiq
Scarica il programma completo

  1. /************************************************************************
  2.  * Copyright (C) 19aa Claudio Reggiani alias Nophiq                     *
  3.  * Questo programma è software libero; è lecito ridistribuirlo e/o      *
  4.  * modificarlo secondo i termini della Licenza Pubblica Generica GNU    *
  5.  * come pubblicata dalla Free Software Foundation; o la versione 2      *
  6.  * della licenza o (a scelta) una versione successiva.                  *
  7.  *                                                                      *
  8.  * Questo programma è distribuito  nella speranza che sia utile, ma     *
  9.  * SENZA ALCUNA GARANZIA; senza neppure la garanzia implicita di        *
  10.  * COMMERCIABILITÀ o di APPLICABILITÀ PER UN PARTICOLARE SCOPO. Si      *
  11.  * veda la Licenza Pubblica Generica GNU per avere maggiori dettagli.   *
  12.  *                                                                      *
  13.  * Ognuno dovrebbe avere ricevuto una copia  della Licenza Pubblica     *
  14.  * Generica GNU insieme a questo programma; in caso contrario, la si    *
  15.  * può ottenere dalla Free Software Foundation, Inc., 675 Mass Ave,     *
  16.  * Cambridge, MA 02139, Stati Uniti.                                    *
  17.  *                                                                      *
  18.  * Per contattarmi attraverso posta elettronica: nophiq@virgilio.it     *
  19.  ************************************************************************/
  20.  
  21. package albero;
  22.  
  23. import java.awt.*;
  24. import java.awt.event.*;
  25. import java.awt.geom.*;
  26. import javax.swing.*;
  27. import java.util.*;
  28. import java.io.*;
  29.  
  30. import alice.tuprolog.*;
  31.  
  32. /**
  33.  *
  34.  * @author nophiq
  35.  */
  36.  
  37. public class ObjectPanel extends JPanel implements AdjustmentListener {
  38.   private Prolog engine;
  39.   private Theory t = null;
  40.   private Struct query = null;
  41.   private SolveInfo info = null;
  42.   private Term resultTerm = null;
  43.   private GridBagConstraints c;
  44.  
  45.   private Graph gr;
  46.  
  47.   /** Creates a new instance of ObjectId */
  48.   public ObjectPanel(Graph gr) {
  49.     this.gr = gr;
  50.     this.setLayout(new GridBagLayout());
  51.     c = new GridBagConstraints();
  52.    
  53.     engine = new Prolog();
  54.    
  55.     try {
  56.       t = new Theory(new FileInputStream("db/base.pl"));
  57.       engine.setTheory(t);
  58.     }
  59.     catch(InvalidTheoryException e) {
  60.       System.out.println("Teoria non valida: "+e);
  61.       System.exit(1);
  62.     }
  63.     catch(IOException ioe) {
  64.       System.out.println("Errore nella lettura della teoria");
  65.       System.exit(1);
  66.     }
  67.   }
  68.  
  69.   public void getHierarchy() {
  70.     gr.clearAll();
  71.     this.drawPanel();
  72.   }
  73.  
  74.   private void setObjectSetting(GridBagConstraints c, int gridx, int gridy, int gridheight, int gridwidth) {
  75.     c.gridx = gridx;  // Posizionamento Orizzontale
  76.     c.gridy = gridy;  // Posizionamento Verticale
  77.     c.gridheight = gridheight;
  78.     c.gridwidth = gridwidth;
  79.     c.insets = new Insets (20, 20, 20, 20);
  80.   }
  81.  
  82.   public void drawPanel() {
  83.       // TODO: da spostare in getHierarchy()
  84.     this.getMember();
  85.     this.getRelation();
  86.    
  87.     this.removeAll();
  88.    
  89.     if (gr.getLengthVectorArcs() > 0 && gr.getLengthVectorNodes() > 0) {
  90.    
  91.         // Utilizzo un vettore per ricordarmi le generazioni e settare coordX
  92.       Vector tmpGener = new Vector();
  93.  
  94.         // Disegno i nodi
  95.       for (int i=0; i<gr.getLengthVectorNodes(); i++) {
  96.         if (gr.getNode(i).getPointX() != -1 && gr.getNode(i).getPointY() != -1) {} // Coordinate già settate
  97.         else { // Assegno le coordinate se non sono già state calcolate
  98.           this.assegnaCoordinate(this, i, tmpGener);
  99.  
  100.             // Vado alla ricerca della possibile moglie, marito
  101.           for (int j=0; j<gr.getLengthVectorRelation(); j++) {
  102.             Vector v = gr.giveMeRelation(gr.getRelation(j).toString());
  103.  
  104.             if (v.elementAt(0).toString().equals(gr.getNode(i).getNodeName()) && v.elementAt(1).equals("=_") &&
  105.                 gr.getNodeAtThisName(v.elementAt(2).toString()).getPointX() == -1 && gr.getNodeAtThisName(v.elementAt(2).toString()).getPointY() == -1) {
  106.               int pos = gr.getNodeAtThisName(v.elementAt(2).toString()).getNumNode();
  107.               this.assegnaCoordinate(this, pos, tmpGener);
  108.             }
  109.             else if (v.elementAt(2).toString().equals(gr.getNode(i).getNodeName()) && v.elementAt(1).equals("=_") &&
  110.                 gr.getNodeAtThisName(v.elementAt(0).toString()).getPointX() == -1 && gr.getNodeAtThisName(v.elementAt(0).toString()).getPointY() == -1) {
  111.               int pos = gr.getNodeAtThisName(v.elementAt(0).toString()).getNumNode();
  112.               this.assegnaCoordinate(this, pos, tmpGener);
  113.             }
  114.           }
  115.  
  116.         }
  117.       }
  118.     }
  119.    
  120.     this.repaint();
  121.     this.revalidate();
  122.   }
  123.  
  124.   public void paintComponent(Graphics g) {
  125.     super.paintComponent(g);
  126.  
  127.     Component[] comp = this.getComponents();
  128.  
  129.     for (int k=0; k<gr.getLengthVectorArcs(); k++) {
  130.       int a = gr.getArc(k).getPosStart();
  131.       int b = gr.getArc(k).getPosEnd();
  132.  
  133.       int x1 = -1;
  134.       int y1 = -1;
  135.       for (int m=0; m<comp.length; m++) {
  136.         if (((JLabel) comp[m]).getText().equals(gr.getNodeAtThisId(a).getNodeName())) {
  137.           x1 = (int) ((JLabel) comp[m]).getLocation().getX();
  138.           y1 = (int) ((JLabel) comp[m]).getLocation().getY();
  139.         }
  140.       }
  141.  
  142.       int x2 = -1;
  143.       int y2 = -1;
  144.       for (int m=0; m<comp.length; m++) {
  145.         if (((JLabel) comp[m]).getText().equals(gr.getNodeAtThisId(b).getNodeName())) {
  146.           x2 = (int) ((JLabel) comp[m]).getLocation().getX();
  147.           y2 = (int) ((JLabel) comp[m]).getLocation().getY();
  148.         }
  149.       }
  150.       g.setColor(Color.WHITE);
  151.       g.drawLine(x1+10, y1+10, x2+10, y2+10);
  152.     }
  153.   }
  154.  
  155.   private void assegnaCoordinate(JPanel jp, int i, Vector tmpGener) {
  156.     int gener = (gr.getNode(i).getGeneration()-1000)/10;
  157.     int coordX = 10;
  158.     int coordY = 10;
  159.  
  160.     coordX = coordX+70*this.countSameGeneration(tmpGener, new Integer(gener).toString());
  161.    
  162.     if (gener < 0) coordY = coordY+(gener*2);
  163.     else if (gener > 0) coordY = coordY+(gener*2);
  164.    
  165.     JLabel l = new JLabel(gr.getNode(i).getNodeName());
  166.       if (gr.getNode(i).getGender().equals("male")) l.setForeground(Color.blue);
  167.       else if (gr.getNode(i).getGender().equals("female")) l.setForeground(Color.magenta);
  168.     this.setObjectSetting(c, coordX, coordY, 1, 1);
  169.     jp.add(l, c);
  170.    
  171.     gr.getNode(i).setPointX(coordX);
  172.     gr.getNode(i).setPointY(coordY);
  173.  
  174.     tmpGener.addElement(new Integer(gener).toString());
  175.   }
  176.  
  177.     /*
  178.      * Funzione non utilizzata
  179.      */
  180.   public boolean controlMemberAndRelation() {
  181.       // True => Tutti i membri hanno una relazione
  182.       // False => Alcuni membri non hanno una relazione
  183.     boolean b = true;
  184.    
  185.     for (int i=0; i<gr.getLengthVectorNodes(); i++) {
  186.      
  187.       b = false;
  188.       for (int j=0; j<gr.getLengthVectorRelation(); j++) {
  189.         Vector v = gr.giveMeRelation(gr.getRelation(j).toString());
  190.        
  191.         if (v.elementAt(0).toString().equals(gr.getNode(i).getNodeName()) ||
  192.             v.elementAt(2).toString().equals(gr.getNode(i).getNodeName())) b = true;
  193.       }
  194.       if (!b) return false;      
  195.     }
  196.    
  197.     return b;
  198.   }
  199.  
  200.   private int countSameGeneration(Vector v, String gen) {
  201.     int total = v.size();
  202.     int count = 0;
  203.     for (int i=0; i<total; i++) {
  204.       if (v.elementAt(i).equals(gen)) count++;
  205.     }
  206.     return count;
  207.   }
  208.  
  209.   public void getMember() {
  210.     try {
  211.       query = new Struct("getMember", new Var("Result"), new Var("Gender"));
  212.       info = engine.solve(query);
  213.  
  214.       while(info.isSuccess()) {
  215.           // Operazione riuscita, riporto i risultati.
  216.         gr.addNode(info.getTerm("Result").toString(), info.getTerm("Gender").toString());
  217.         info = engine.solveNext();
  218.       }
  219.     }
  220.     catch(InvalidVarNameException e) {
  221.       System.err.println("L'espressione non è valida in Prolog");
  222.       System.exit(1);
  223.     }
  224.     catch(NoMoreSolutionException e) {
  225.       System.err.println("# NoMoreSolutionException");
  226.       //System.exit(1);
  227.     }
  228.     catch(NoSolutionException e) {
  229.       System.err.println("NoSolutionException");
  230.       //System.exit(1);
  231.     }
  232.     catch(UnknownVarException e) {
  233.       System.err.println("UnknownVarException");
  234.       System.exit(1);
  235.     }
  236.   }
  237.  
  238.   public void getRelation() {
  239.     try {
  240.       query = new Struct("getRelation", new Var("Result1"), new Var("Result2"), new Var("Result3"));
  241.       info = engine.solve(query);
  242.  
  243.       while(info.isSuccess()) {
  244.           // Operazione riuscita, riporto i risultati.
  245.         String s1 = info.getTerm("Result1").toString();
  246.         String s2 = info.getTerm("Result2").toString();
  247.         String s3 = info.getTerm("Result3").toString();
  248.        
  249.           // Costruisco un vettore di relazioni
  250.         gr.getVectorRelation().addElement(s1+s2+s3);
  251.        
  252.         info = engine.solveNext();
  253.       }
  254.     }
  255.     catch(InvalidVarNameException e) {
  256.       System.err.println("L'espressione non è valida in Prolog");
  257.       System.exit(1);
  258.     }
  259.     catch(NoMoreSolutionException e) {
  260.       System.err.println("NoMoreSolutionException");
  261.       //System.exit(1);
  262.     }
  263.     catch(NoSolutionException e) {
  264.       System.err.println("NoSolutionException");
  265.       //System.exit(1);
  266.     }
  267.     catch(UnknownVarException e) {
  268.       System.err.println("UnknownVarException");
  269.       System.exit(1);
  270.     }
  271.    
  272.     gr.setRelation();
  273.   }
  274.  
  275.   public void addTheory(String s) {
  276.     try {
  277.       this.engine.addTheory(new Theory(s));
  278.     }
  279.     catch(InvalidTheoryException e) {
  280.       System.out.println("Teoria non valida");
  281.       System.exit(1);
  282.     }
  283.   }
  284.  
  285.   public void newTheory(String name, String atom1, String atom2) {
  286.     try {
  287.       query = new Struct("bestTrack", Term.parse(atom1), Term.parse(atom2), new Var("L"), Term.parse("[]"));
  288.       info = engine.solve(query);
  289.  
  290.       if (info.isSuccess()) {
  291.           // Operazione riuscita, riporto i risultati.
  292.         query = new Struct("makeRelation", info.getTerm("L"), new Var("L1"));
  293.         info = engine.solve(query);
  294.        
  295.         if (info.isSuccess()) {
  296.             // Elaboro la nuova Teoria
  297.           String elab = info.getTerm("L1").toString().substring(1, (info.getTerm("L1").toString().length()-1));
  298.           elab = elab.replace("'", "");
  299.           elab = elab.replace("[", "");
  300.           elab = elab.replace("]", "");
  301.           elab = elab.replace(",", "");
  302.          
  303.           elab = elab.replace("-", ",-");
  304.           elab = elab.replace("))", ")),");
  305.           elab = elab.replace(")person", "),person");
  306.           elab = elab.replace(") person", "),person");
  307.           elab = elab.replace("-", "_");
  308.           elab = elab.replace(" ", "");
  309.          
  310.           elab = elab.replace(atom1, "X");
  311.           elab = elab.replace(atom2, "Y");
  312.          
  313.           System.out.println("## "+elab);
  314.          
  315.           this.getMember();
  316.           for (int i=0; i<gr.getLengthVectorNodes(); i++) {
  317.             elab = elab.replace(gr.getNode(i).getNodeName(), ("Q"+i));
  318.           }
  319.          
  320.           this.addTheory("relation('"+name+"', 'X, Y', '"+elab.substring(0, elab.length()-1)+"').");
  321.          
  322.           elab = elab + " L = [X,Y,";
  323.           for (int i=0; i<gr.getLengthVectorNodes(); i++) {
  324.             String s = "Q"+i;
  325.             if (elab.contains(s)) elab = elab + "Q" + i + ",";
  326.           }
  327.           elab = elab.substring(0, elab.length()-1);
  328.           elab = elab + "], diseguali(L).";
  329.          
  330.           String newStringTheory = name + "(person(X, _), person(Y, _)) :- " + elab;
  331.           System.out.println("## "+newStringTheory);
  332.           this.addTheory(newStringTheory);
  333.          
  334.         }
  335.       }
  336.     }
  337.     catch(InvalidVarNameException e) {
  338.       System.err.println("L'espressione non è valida in Prolog");
  339.       System.exit(1);
  340.     }
  341.     catch(NoSolutionException e) {
  342.       System.err.println("NoSolutionException");
  343.       //System.exit(1);
  344.     }
  345.     catch(UnknownVarException e) {
  346.       System.err.println("UnknownVarException");
  347.       System.exit(1);
  348.     }
  349.     catch (InvalidTermException e) {
  350.       System.err.println("L'espressione non è valida in Prolog");
  351.       System.exit(1);
  352.     }
  353.   }
  354.  
  355.   public void setTheory(File f) {
  356.     try {
  357.       this.engine.setTheory(new Theory(new FileInputStream(f.getPath())));
  358.     }
  359.     catch(InvalidTheoryException e) {
  360.       System.out.println("Teoria non valida");
  361.       System.exit(1);
  362.     }
  363.     catch(IOException ioe) {}
  364.   }
  365.  
  366.   public String getTheory() {return this.engine.getTheory().toString();}
  367.   public void newFile() {
  368.     try {
  369.       t = new Theory(new FileInputStream("db/base.pl"));
  370.       engine.setTheory(t);
  371.     }
  372.     catch(InvalidTheoryException e) {
  373.       System.out.println("Teoria non valida");
  374.       System.exit(1);
  375.     }
  376.     catch(IOException ioe) {
  377.       System.out.println("Errore nella lettura della teoria");
  378.       System.exit(1);
  379.     }
  380.     gr.clearAll();
  381.     this.repaint();
  382.   }
  383.  
  384.   public void doQuery(JTextArea console, String name, String a, String b) {
  385.     try {
  386.         // Controllo se a e b sono variabili o dati
  387.       String c = name+"(person("+a+", _), person("+b+", _)).";
  388.       System.out.println(c);
  389.       info = engine.solve(c);
  390.       console.append("?- "+name+"("+a+", "+b+").\n");
  391.      
  392.       boolean flag = false;
  393.       while(info.isSuccess()) {
  394.           // Operazione riuscita, riporto i risultati.
  395.         flag = true;
  396.        
  397.         // Controllo se a e b è una variabile oppure un dato
  398.         String s1 = a;
  399.         String s2 = b;
  400.         if (Term.parse(a).isVar()) s1 = info.getTerm(a).toString();
  401.         if (Term.parse(b).isVar()) s2 = info.getTerm(b).toString();
  402.        
  403.         console.append(s1+" è "+name+" di "+s2+"\n");
  404.        
  405.         info = engine.solveNext();
  406.       }
  407.       if (!flag) console.append("L'operazione non è riuscita\n");
  408.     }
  409.     catch(InvalidTermException e) {
  410.       System.err.println("L'espressione non è valida in Prolog");
  411.       System.exit(1);
  412.     }
  413.     catch(NoSolutionException e) {
  414.       System.err.println("NoSolutionException");
  415.       //System.exit(1);
  416.     }
  417.     catch(NoMoreSolutionException e) {
  418.       System.err.println("NoSolutionException");
  419.       //System.exit(1);
  420.     }
  421.     catch(UnknownVarException e) {
  422.       System.err.println("UnknownVarException");
  423.       System.exit(1);
  424.     }
  425.     catch (MalformedGoalException e) {
  426.       System.err.println("L'espressione non è valida in Prolog");
  427.       System.exit(1);
  428.     }
  429.     console.append("-----------------\n");
  430.   }
  431.  
  432.   public String viewRelation() {
  433.     String allRelation = "";
  434.    
  435.     try {
  436.       query = new Struct("sendMeAllRelation", new Var("A"), new Var("B"), new Var("C"));
  437.       info = engine.solve(query);
  438.  
  439.       while(info.isSuccess()) {
  440.           // Operazione riuscita, riporto i risultati.
  441.         String name = info.getTerm("A").toString();
  442.         String var = info.getTerm("B").toString();
  443.         String desc = info.getTerm("C").toString();
  444.        
  445.         allRelation = allRelation+name+"("+var+")|"+desc+"{}";
  446.         allRelation = allRelation.replace("'", "");
  447.        
  448.         info = engine.solveNext();
  449.       }
  450.     }
  451.     catch(InvalidVarNameException e) {
  452.       System.err.println("L'espressione non è valida in Prolog");
  453.       System.exit(1);
  454.     }
  455.     catch(NoMoreSolutionException e) {
  456.       System.err.println("NoMoreSolutionException");
  457.       //System.exit(1);
  458.     }
  459.     catch(NoSolutionException e) {
  460.       System.err.println("NoSolutionException");
  461.       //System.exit(1);
  462.     }
  463.     catch(UnknownVarException e) {
  464.       System.err.println("UnknownVarException");
  465.       System.exit(1);
  466.     }
  467.     return allRelation;
  468.   }
  469.  
  470.   public boolean isMemberPresent(String s) {
  471.     try {
  472.       info = engine.solve("person("+s+", _).");
  473.       if (info.isSuccess()) return true;
  474.     }
  475.     catch(MalformedGoalException e) {
  476.       System.err.println("L'espressione non è valida in Prolog");
  477.       System.exit(1);
  478.     }
  479.     return false;
  480.   }
  481.  
  482.   public boolean isRulePresent(String s) {
  483.     try {
  484.       info = engine.solve("relation("+s+", _, _).");
  485.       if (info.isSuccess()) return true;
  486.     }
  487.     catch(MalformedGoalException e) {
  488.       System.err.println("L'espressione non è valida in Prolog");
  489.       System.exit(1);
  490.     }
  491.     return false;
  492.   }
  493.  
  494.   public void adjustmentValueChanged(AdjustmentEvent e) {this.drawPanel();}
  495. }