Changeset 32404 in osm


Ignore:
Timestamp:
2016-06-25T14:41:52+02:00 (8 years ago)
Author:
donvip
Message:

checkstyle

Location:
applications/editors/josm/plugins/OSMRecPlugin
Files:
2 added
1 deleted
25 edited
5 moved

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/OSMRecPlugin/.project

    r32278 r32404  
    1616                        </arguments>
    1717                </buildCommand>
     18                <buildCommand>
     19                        <name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
     20                        <arguments>
     21                        </arguments>
     22                </buildCommand>
    1823        </buildSpec>
    1924        <natures>
    2025                <nature>org.eclipse.jdt.core.javanature</nature>
     26                <nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
    2127        </natures>
    2228</projectDescription>
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/MenuExportAction.java

    r32278 r32404  
     1// License: GPL. For details, see LICENSE file.
    12package org.openstreetmap.josm.plugins.osmrec;
    23
    34import static org.openstreetmap.josm.tools.I18n.tr;
     5
    46import java.awt.event.ActionEvent;
     7
    58import org.openstreetmap.josm.actions.JosmAction;
    69
    710/**
    811 * Exports the OSMRec toggle dialog.
    9  * 
     12 *
    1013 * @author imis-nkarag
    1114 *
     
    1619     * Constructs a new {@code MenuExportAction}.
    1720     */
    18     public MenuExportAction(){
    19         super(tr("OSM Recommendation"), "dialogs/logo-osmrec.png", 
    20               tr("Recommend categories to your newly created instances."), null, false);
     21    public MenuExportAction() {
     22        super(tr("OSM Recommendation"), "dialogs/logo-osmrec.png",
     23                tr("Recommend categories to your newly created instances."), null, false);
    2124    }
    22        
     25
    2326    @Override
    2427    public void actionPerformed(ActionEvent arg0) {
     
    2629            OSMRecToggleDialog pro = new OSMRecToggleDialog();
    2730            OSMRecPlugin.getCurrentMapFrame().addToggleDialog(pro);
    28         }       
     31        }
    2932    }
    3033}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecPlugin.java

    r31554 r32404  
    1 
     1// License: GPL. For details, see LICENSE file.
    22package org.openstreetmap.josm.plugins.osmrec;
    33
     
    66import org.openstreetmap.josm.plugins.Plugin;
    77import org.openstreetmap.josm.plugins.PluginInformation;
    8 //import org.openstreetmap.josm.gui.dialogs.properties.PropertiesDialog;
    98
    10 /** 
    11  * 
     9/**
     10 *
    1211 * @author imis-nkarag
    1312 */
     13public class OSMRecPlugin extends Plugin {
    1414
    15 public class OSMRecPlugin extends Plugin{
    16    
    1715    private final MenuExportAction menuExportAction;
    1816    private static MapFrame mapFrame;
    1917    public OSMRecPlugin plugin;
    20    
    21    
    22     public OSMRecPlugin(PluginInformation info) {       
     18
     19    public OSMRecPlugin(PluginInformation info) { // NO_UCD (unused code)
    2320        super(info);
    24         System.out.println(getPluginDir());
    2521        menuExportAction = new MenuExportAction();
    2622        Main.main.menu.toolsMenu.add(menuExportAction);
    2723    }
    28    
    29     /**
    30      * Called when the JOSM map frame is created or destroyed.
    31      * @param oldFrame
    32      * @param newFrame
    33      */
     24
    3425    @Override
    35     public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {             
     26    public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
    3627        if (oldFrame == null && newFrame != null) { // map frame added
    37             System.out.println("mapFrameInitialized");
    3828            setCurrentMapFrame(newFrame);
    3929            setState(this);
    4030        }
    4131    }
    42    
    43     private void setCurrentMapFrame(MapFrame newFrame){
     32
     33    private void setCurrentMapFrame(MapFrame newFrame) {
    4434        OSMRecPlugin.mapFrame = newFrame;
    4535    }
    46    
     36
    4737    public static MapFrame getCurrentMapFrame() {
    4838        return mapFrame;
    4939    }
    50    
    51     private void setState(OSMRecPlugin plugin){
     40
     41    private void setState(OSMRecPlugin plugin) {
    5242        this.plugin = plugin;
    5343    }
    54    
    55     public OSMRecPlugin getState(){
     44
     45    public OSMRecPlugin getState() {
    5646        return plugin;
    5747    }
    58    
    59 //    @Override
    60 //    public PreferenceSetting getPreferenceSetting() {
    61 //        return new PreferenceEditor();
    62 //    }
     48
     49    //    @Override
     50    //    public PreferenceSetting getPreferenceSetting() {
     51    //        return new PreferenceEditor();
     52    //    }
    6353}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecPluginHelper.java

    r31627 r32404  
     1// License: GPL. For details, see LICENSE file.
    12package org.openstreetmap.josm.plugins.osmrec;
    23
    3 import com.vividsolutions.jts.geom.Coordinate;
    4 import com.vividsolutions.jts.geom.Geometry;
    5 import com.vividsolutions.jts.geom.GeometryFactory;
    6 import com.vividsolutions.jts.geom.LineString;
    7 import com.vividsolutions.jts.geom.LinearRing;
    8 import com.vividsolutions.jts.geom.Point;
    9 import com.vividsolutions.jts.geom.Polygon;
    10 import de.bwaldvogel.liblinear.FeatureNode;
    11 import de.bwaldvogel.liblinear.Linear;
    12 import de.bwaldvogel.liblinear.Model;
    134import static org.openstreetmap.josm.tools.I18n.tr;
    145import static org.openstreetmap.josm.tools.I18n.trn;
     
    1910import java.awt.Cursor;
    2011import java.awt.Dimension;
     12import java.awt.EventQueue;
    2113import java.awt.FlowLayout;
    22 import java.awt.Font;
    2314import java.awt.GridBagConstraints;
    2415import java.awt.GridBagLayout;
    25 import java.awt.Toolkit;
    26 import java.awt.datatransfer.Clipboard;
    27 import java.awt.datatransfer.Transferable;
    2816import java.awt.event.ActionEvent;
    2917import java.awt.event.FocusAdapter;
     
    3220import java.awt.event.MouseAdapter;
    3321import java.awt.event.MouseEvent;
    34 import java.awt.event.WindowAdapter;
    35 import java.awt.event.WindowEvent;
    3622import java.awt.image.BufferedImage;
    3723import java.beans.PropertyChangeEvent;
     
    6854import javax.swing.BoxLayout;
    6955import javax.swing.ButtonGroup;
    70 import javax.swing.DefaultListCellRenderer;
    7156import javax.swing.DefaultListModel;
    7257import javax.swing.GroupLayout;
     
    8873import javax.swing.JScrollPane;
    8974import javax.swing.JTextField;
    90 import javax.swing.ListCellRenderer;
    9175import javax.swing.SwingConstants;
    9276import javax.swing.border.EtchedBorder;
     
    9680import javax.swing.table.DefaultTableModel;
    9781import javax.swing.text.JTextComponent;
     82
    9883import org.geotools.geometry.jts.JTS;
    9984import org.geotools.referencing.CRS;
     
    10590import org.opengis.referencing.operation.MathTransform;
    10691import org.opengis.referencing.operation.TransformException;
    107 
    10892import org.openstreetmap.josm.Main;
    10993import org.openstreetmap.josm.actions.JosmAction;
     
    124108import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
    125109import org.openstreetmap.josm.io.XmlWriter;
    126 import org.openstreetmap.josm.plugins.container.OSMWay;
    127 import org.openstreetmap.josm.plugins.core.TrainWorker;
    128 import org.openstreetmap.josm.plugins.extractor.LanguageDetector;
    129 import org.openstreetmap.josm.plugins.extractor.SampleModelsExtractor;
    130 import org.openstreetmap.josm.plugins.features.ClassFeatures;
    131 import org.openstreetmap.josm.plugins.features.GeometryFeatures;
    132 import org.openstreetmap.josm.plugins.features.OSMClassification;
    133 import org.openstreetmap.josm.plugins.features.TextualFeatures;
     110import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
     111import org.openstreetmap.josm.plugins.osmrec.core.TrainWorker;
     112import org.openstreetmap.josm.plugins.osmrec.extractor.LanguageDetector;
     113import org.openstreetmap.josm.plugins.osmrec.extractor.SampleModelsExtractor;
     114import org.openstreetmap.josm.plugins.osmrec.features.ClassFeatures;
     115import org.openstreetmap.josm.plugins.osmrec.features.GeometryFeatures;
     116import org.openstreetmap.josm.plugins.osmrec.features.OSMClassification;
     117import org.openstreetmap.josm.plugins.osmrec.features.TextualFeatures;
     118import org.openstreetmap.josm.plugins.osmrec.parsers.Mapper;
     119import org.openstreetmap.josm.plugins.osmrec.parsers.OSMParser;
     120import org.openstreetmap.josm.plugins.osmrec.parsers.Ontology;
     121import org.openstreetmap.josm.plugins.osmrec.parsers.TextualStatistics;
    134122import org.openstreetmap.josm.plugins.osmrec.personalization.UserDataExtractAndTrainWorker;
    135 import org.openstreetmap.josm.plugins.parsers.Mapper;
    136 import org.openstreetmap.josm.plugins.parsers.OSMParser;
    137 import org.openstreetmap.josm.plugins.parsers.Ontology;
    138 import org.openstreetmap.josm.plugins.parsers.TextualStatistics;
    139123import org.openstreetmap.josm.tools.GBC;
    140124import org.openstreetmap.josm.tools.Shortcut;
    141125import org.openstreetmap.josm.tools.WindowGeometry;
    142126
     127import com.vividsolutions.jts.geom.Coordinate;
     128import com.vividsolutions.jts.geom.Geometry;
     129import com.vividsolutions.jts.geom.GeometryFactory;
     130import com.vividsolutions.jts.geom.LineString;
     131import com.vividsolutions.jts.geom.LinearRing;
     132import com.vividsolutions.jts.geom.Point;
     133import com.vividsolutions.jts.geom.Polygon;
     134
     135import de.bwaldvogel.liblinear.FeatureNode;
     136import de.bwaldvogel.liblinear.Linear;
     137import de.bwaldvogel.liblinear.Model;
     138
    143139/**
    144140 * Modified PropertiesDialog(since 5633) to serve the plugin functionality.
    145  * 
     141 *
    146142 * @author imis-nkarag
    147143 */
    148 
    149144class OSMRecPluginHelper {
    150    
     145
    151146    private final DefaultTableModel tagData;
    152     private final Map<String, Map<String, Integer>> valueCount;
    153147    private static Collection<String> fileHistory;
    154148    private Map<File, Double> filesAndWeights = new HashMap<>();
    155     private boolean useCombinedModel = false;
    156    
    157     //the most recent file from history. 
     149    private boolean useCombinedModel;
     150
     151    //the most recent file from history.
    158152    //all necessary files will reside in a directory of this file
    159153    private static String MAIN_PATH;
    160     //private static final String MODEL_PATH = MAIN_PATH.substring(0, MAIN_PATH.lastIndexOf("/")) + "OSMRec_models/";
    161154    private static String MODEL_PATH;
    162155    private static String TEXTUAL_LIST_PATH;
     
    165158    private static LanguageDetector languageDetector;
    166159    private static String bestModelPath;
    167     private boolean modelWithClasses;// = false;
     160    private boolean modelWithClasses;
    168161    private final String modelWithClassesPath;
    169162    private boolean useCustomSVMModel = false;
     
    171164    private final String combinedModelClasses;
    172165    private final String combinedModel;
    173        
     166
    174167    // Selection that we are editing by using both dialogs
    175168    Collection<OsmPrimitive> sel;
    176169
    177170    private String changedKey;
    178     private String objKey;
    179171
    180172    Comparator<AutoCompletionListItem> defaultACItemComparator = new Comparator<AutoCompletionListItem>() {
     
    199191    };
    200192
    201    
    202193    OSMRecPluginHelper(DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
    203194        this.tagData = propertyData;
    204         this.valueCount = valueCount;
    205195        fileHistory = Main.pref.getCollection("file-open.history");
    206         if(!fileHistory.isEmpty()){           
    207             MAIN_PATH = (String) fileHistory.toArray()[0];
    208         }
    209         else{
     196        if (!fileHistory.isEmpty()) {
     197            MAIN_PATH = (String) fileHistory.toArray()[0];
     198        } else {
    210199            MAIN_PATH = System.getProperty("user.home");
    211200        }
     
    220209
    221210        SampleModelsExtractor sampleModelsExtractor = new SampleModelsExtractor();
    222                
     211
    223212        sampleModelsExtractor.extractSampleSVMmodel("best_model", bestModelPath);
    224213        sampleModelsExtractor.extractSampleSVMmodel("model_with_classes", modelWithClassesPath);
    225        
    226214    }
    227215
    228216    /**
    229      * Open the add selection dialog and add a new key/value to the table (and
    230      * to the dataset, of course).
     217     * Open the add selection dialog and add a new key/value to the table (and to the dataset, of course).
    231218     */
    232219    public void addTag() {
     
    236223
    237224        final AddTagsDialog addDialog = new AddTagsDialog();
    238        
     225
    239226        addDialog.showDialog();
    240227
     
    247234
    248235    /**
    249     * Edit the value in the tags table row.
    250     * @param row The row of the table from which the value is edited.
    251     * @param focusOnKey Determines if the initial focus should be set on key instead of value
    252     * @since 5653
    253     */
     236     * Edit the value in the tags table row.
     237     * @param row The row of the table from which the value is edited.
     238     * @param focusOnKey Determines if the initial focus should be set on key instead of value
     239     * @since 5653
     240     */
    254241    public void editTag(final int row, boolean focusOnKey) {
    255242        changedKey = null;
    256243        sel = Main.main.getInProgressSelection();
    257         //if (sel == null || sel.isEmpty()) return;
    258 //        String key = tagData.getValueAt(row, 0).toString();
    259244        String key = "";
    260 //        objKey=key;
    261245
    262246        @SuppressWarnings("unchecked")
     
    264248        dumPar.put(" ", -1);
    265249        final TrainingDialog editDialog = new TrainingDialog(key, row,
    266                 dumPar, focusOnKey);               
     250                dumPar, focusOnKey);
    267251        editDialog.showDialog();
    268         //if (editDialog.getValue() !=1 ) return;
    269         //editDialog.performTagEdit();
    270252    }
    271253
     
    277259    public String getChangedKey() {
    278260        return changedKey;
    279     }
    280 
    281     public void resetChangedKey() {
    282         changedKey = null;
    283261    }
    284262
     
    318296    public void saveTagsIfNeeded() {
    319297        if (PROPERTY_REMEMBER_TAGS.get() && !recentTags.isEmpty()) {
    320             List<String> c = new ArrayList<>( recentTags.size()*2 );
     298            List<String> c = new ArrayList<>(recentTags.size()*2);
    321299            for (Tag t: recentTags.keySet()) {
    322300                c.add(t.getKey());
     
    349327    public final class TrainingDialog extends AbstractTagsDialog {
    350328
    351         ListCellRenderer<AutoCompletionListItem> cellRenderer = new ListCellRenderer<AutoCompletionListItem>() {
    352             final DefaultListCellRenderer def = new DefaultListCellRenderer();
    353             @Override
    354             public Component getListCellRendererComponent(JList<? extends AutoCompletionListItem> list,
    355                     AutoCompletionListItem value, int index, boolean isSelected,  boolean cellHasFocus){
    356                 Component c = def.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    357                 if (c instanceof JLabel) {
    358                     String str = value.getValue();
    359                     if (valueCount.containsKey(objKey)) {
    360                         Map<String, Integer> m = valueCount.get(objKey);
    361                         if (m.containsKey(str)) {
    362                             str = tr("{0} ({1})", str, m.get(str));
    363                             c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD));
    364                         }
    365                     }
    366                     ((JLabel) c).setText(str);
    367                 }
    368                 return c;
    369             }
    370         };
    371329        private static final int FIELD_COLUMNS = 4;
    372330        private final JTextField inputFileField;
     
    375333        private final JTextField cParameterField;
    376334        private final JTextField frequencyField;
    377        
     335
    378336        private final JButton fileBrowseButton;
    379337        private final JButton acceptConfigButton;
     
    393351        private final JLabel frequencyErrorMessageLabel;
    394352        private final JProgressBar trainingProgressBar;
    395         //private final JLabel userHistoryLabel;
    396353        private final JRadioButton byAreaRadioButton;
    397354        private final JRadioButton byTimeRadioButton;
     
    406363        private TrainWorker trainWorker;
    407364        private UserDataExtractAndTrainWorker userDataExtractAndTrainWorker;
    408        
     365
    409366        private TrainingDialog(String key, int row, Map<String, Integer> map, final boolean initialFocusOnKey) {
    410             //super(Main.parent, tr("Training process configuration"), new String[] {tr("Start Training"),tr("Cancel")});
    411             super(Main.parent, tr("Training process configuration"),
    412                     new String[] {tr("Cancel")});
    413 
    414             setButtonIcons(new String[] {"ok","cancel"});
     367            super(Main.parent, tr("Training process configuration"), new String[] {tr("Cancel")});
     368
     369            setButtonIcons(new String[] {"ok", "cancel"});
    415370            setCancelButton(2);
    416            
    417             JPanel mainPanel = new JPanel(new BorderLayout(10,10));   //6,6
    418             JPanel configPanel = new JPanel(new BorderLayout(10,10));  //6,6    //at NORTH of mainPanel
     371
     372            JPanel mainPanel = new JPanel(new BorderLayout(10, 10));   //6,6
     373            JPanel configPanel = new JPanel(new BorderLayout(10, 10));  //6,6    //at NORTH of mainPanel
    419374            JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));    //NORTH at config panel
    420             JPanel paramPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));    //WEST at config panel //config panel has EAST free                                                                               
    421                                          
     375            JPanel paramPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));    //WEST at config panel //config panel has EAST free
     376
    422377            JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));    //SOUTH at config panel
    423378            userHistoryPanel = new JPanel(); //CENTER of config
    424            
    425             trainingProgressBar = new javax.swing.JProgressBar(0,100);
     379
     380            trainingProgressBar = new JProgressBar(0, 100);
    426381
    427382            ButtonGroup paramGroup = new ButtonGroup();
    428383            ButtonGroup userGroup = new ButtonGroup();
    429             inputFileLabel = new javax.swing.JLabel();
    430             inputFileField = new javax.swing.JTextField();
    431             cParameterField = new javax.swing.JTextField(); 
    432             topKField = new javax.swing.JTextField();
    433             frequencyField = new javax.swing.JTextField();           
    434            
     384            inputFileLabel = new JLabel();
     385            inputFileField = new JTextField();
     386            cParameterField = new JTextField();
     387            topKField = new JTextField();
     388            frequencyField = new JTextField();
     389
    435390            cParameterCheckBox = new JCheckBox("Define C parameter");
    436391            topKButton = new JRadioButton("Top-K terms");
    437392            frequencyButton = new JRadioButton("Max-Frequency");
    438             fileBrowseButton = new javax.swing.JButton();
    439             acceptConfigButton = new javax.swing.JButton("Accept Configuration");                       
    440             resetConfigButton = new javax.swing.JButton("Reset Configuration/Cancel training");
    441             startTrainingButton = new javax.swing.JButton("Train Model");
    442            
    443             inputFileErrorMessageLabel = new javax.swing.JLabel("");
    444             cErrorMessageLabel = new javax.swing.JLabel("");
    445             topKErrorMessageLabel = new javax.swing.JLabel("");
    446             frequencyErrorMessageLabel = new javax.swing.JLabel("");
    447          
     393            fileBrowseButton = new JButton();
     394            acceptConfigButton = new JButton("Accept Configuration");
     395            resetConfigButton = new JButton("Reset Configuration/Cancel training");
     396            startTrainingButton = new JButton("Train Model");
     397
     398            inputFileErrorMessageLabel = new JLabel("");
     399            cErrorMessageLabel = new JLabel("");
     400            topKErrorMessageLabel = new JLabel("");
     401            frequencyErrorMessageLabel = new JLabel("");
     402
    448403            trainFromUserCheckBox = new JCheckBox("Train Model From User");
    449404            byAreaRadioButton = new JRadioButton("By Area");
    450405            byTimeRadioButton = new JRadioButton("By Time");
    451             userNameLabel = new javax.swing.JLabel("Username:");
    452             userNameField = new javax.swing.JTextField();
    453            
    454             daysLabel = new javax.swing.JLabel("Days: ");
    455             daysField = new javax.swing.JTextField();
    456            
     406            userNameLabel = new JLabel("Username:");
     407            userNameField = new JTextField();
     408
     409            daysLabel = new JLabel("Days: ");
     410            daysField = new JTextField();
     411
    457412            cParameterCheckBox.setSelected(true);
    458413            userHistoryPanel.setEnabled(false);
     
    465420            daysField.setEnabled(false);
    466421            userNameField.setColumns(FIELD_COLUMNS);
    467             daysField.setColumns(FIELD_COLUMNS);           
    468            
     422            daysField.setColumns(FIELD_COLUMNS);
     423
    469424            Collection<String> fileHistory = Main.pref.getCollection("file-open.history");
    470             if(!fileHistory.isEmpty()){               
    471                 //System.out.println(fileName);
     425            if (!fileHistory.isEmpty()) {
    472426                inputFileField.setText(MAIN_PATH);
    473427            }
    474                
     428
    475429            fileBrowseButton.setText("...");
    476430            inputFileLabel.setText("OSM filepath: ");
     
    480434            frequencyField.setText("200");
    481435            cParameterField.setText("0.01");
    482            
     436
    483437            cParameterField.setColumns(FIELD_COLUMNS);
    484438            cParameterField.setEditable(false);
    485439            cParameterField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    486440            cErrorMessageLabel.setForeground(Color.RED);
    487             cErrorMessageLabel.setMinimumSize(new Dimension(150,10));
    488            
    489             topKButton.setSelected(true);       
     441            cErrorMessageLabel.setMinimumSize(new Dimension(150, 10));
     442
     443            topKButton.setSelected(true);
    490444            topKField.setColumns(FIELD_COLUMNS);
    491445            topKField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    492446            topKErrorMessageLabel.setForeground(Color.RED);
    493                    
     447
    494448            frequencyField.setEditable(false);
    495449            frequencyField.setColumns(FIELD_COLUMNS);
    496450            frequencyField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    497451            frequencyErrorMessageLabel.setForeground(Color.RED);
    498          
     452
    499453            fileBrowseButton.addActionListener(new java.awt.event.ActionListener() {
    500454                @Override
     
    506460                @Override
    507461                public void actionPerformed(java.awt.event.ActionEvent evt) {
    508                     if(topKButton.isSelected()){                       
     462                    if (topKButton.isSelected()) {
    509463                        frequencyField.setEditable(false);
    510464                        topKField.setEditable(true);
    511                     }
    512                     else{
     465                    } else {
    513466                        frequencyField.setEditable(true);
    514467                        topKField.setEditable(false);
     
    519472                @Override
    520473                public void actionPerformed(java.awt.event.ActionEvent evt) {
    521                     if(frequencyButton.isSelected()){
     474                    if (frequencyButton.isSelected()) {
    522475                        topKField.setEditable(false);
    523476                        frequencyField.setEditable(true);
    524                     }
    525                     else{
     477                    } else {
    526478                        topKField.setEditable(true);
    527479                        frequencyField.setEditable(false);
    528480                    }
    529481                }
    530             });           
     482            });
    531483            cParameterCheckBox.addActionListener(new java.awt.event.ActionListener() {
    532484                @Override
    533485                public void actionPerformed(java.awt.event.ActionEvent evt) {
    534                     if(cParameterCheckBox.isSelected()){                       
    535                         cParameterField.setEditable(true);                       
    536                     }
    537                     else{
     486                    if (cParameterCheckBox.isSelected()) {
     487                        cParameterField.setEditable(true);
     488                    } else {
    538489                        cParameterField.setEditable(false);
    539490                    }
     
    550501                public void actionPerformed(java.awt.event.ActionEvent evt) {
    551502                    resetConfigButtonActionPerformed();
    552                    
    553503                }
    554504            });
    555                
     505
    556506            startTrainingButton.addActionListener(new java.awt.event.ActionListener() {
    557507                @Override
    558508                public void actionPerformed(java.awt.event.ActionEvent evt) {
    559                     if(!acceptConfigButton.isEnabled()){
     509                    if (!acceptConfigButton.isEnabled()) {
    560510                        startTraining();
    561                     }
    562                     else{
     511                    } else {
    563512                        System.out.println("Set values first!");
    564513                    }
    565514                }
    566515            });
    567            
     516
    568517            trainFromUserCheckBox.addActionListener(new java.awt.event.ActionListener() {
    569518                @Override
    570519                public void actionPerformed(java.awt.event.ActionEvent evt) {
    571                     if(trainFromUserCheckBox.isSelected()){
     520                    if (trainFromUserCheckBox.isSelected()) {
    572521                        userHistoryPanel.setEnabled(true);
    573522                        byAreaRadioButton.setEnabled(true);
     
    577526                        daysLabel.setEnabled(true);
    578527                        daysField.setEnabled(true);
    579                     }
    580                     else{
     528                    } else {
    581529                        userHistoryPanel.setEnabled(false);
    582530                        byAreaRadioButton.setEnabled(false);
     
    585533                        userNameField.setEnabled(false);
    586534                        daysLabel.setEnabled(false);
    587                         daysField.setEnabled(false);   
    588                     }
    589                 }
    590             }); 
    591            
     535                        daysField.setEnabled(false);
     536                    }
     537                }
     538            });
     539
    592540            byAreaRadioButton.addActionListener(new java.awt.event.ActionListener() {
    593541                @Override
    594542                public void actionPerformed(java.awt.event.ActionEvent evt) {
    595                     if(byAreaRadioButton.isSelected()){
    596                         daysField.setEditable(false);                       
    597                     }
    598                     else{
    599                         daysField.setEditable(true);                       
    600                     }
    601                 }
    602             });   
    603            
     543                    if (byAreaRadioButton.isSelected()) {
     544                        daysField.setEditable(false);
     545                    } else {
     546                        daysField.setEditable(true);
     547                    }
     548                }
     549            });
     550
    604551            byTimeRadioButton.addActionListener(new java.awt.event.ActionListener() {
    605552                @Override
    606553                public void actionPerformed(java.awt.event.ActionEvent evt) {
    607                     if(byTimeRadioButton.isSelected()){
    608                         daysField.setEditable(true);                       
    609                     }
    610                     else{
    611                         daysField.setEditable(false);                       
    612                     }
    613                 }
    614             });
    615            
     554                    if (byTimeRadioButton.isSelected()) {
     555                        daysField.setEditable(true);
     556                    } else {
     557                        daysField.setEditable(false);
     558                    }
     559                }
     560            });
     561
    616562            //grouplayout for input panel
     563            buildInputPanelGroupLayout(inputPanel);
     564
     565            //grouplayout for param panel
     566            buildParamPanelGroupLayout(paramPanel);
     567
     568            inputPanel.add(inputFileLabel);
     569            inputPanel.add(inputFileField);
     570            inputPanel.add(fileBrowseButton);
     571            inputPanel.add(inputFileErrorMessageLabel);
     572
     573            paramGroup.add(topKButton);
     574            paramGroup.add(frequencyButton);
     575
     576            paramPanel.add(cParameterCheckBox);
     577            paramPanel.add(cParameterField);
     578            paramPanel.add(cErrorMessageLabel);
     579            paramPanel.add(topKButton);
     580            paramPanel.add(topKField);
     581            paramPanel.add(topKErrorMessageLabel);
     582            paramPanel.add(frequencyButton);
     583            paramPanel.add(frequencyField);
     584            paramPanel.add(frequencyErrorMessageLabel);
     585
     586            southPanel.add(acceptConfigButton);
     587            southPanel.add(resetConfigButton);
     588            southPanel.add(trainFromUserCheckBox);
     589
     590            userGroup.add(byAreaRadioButton);
     591            userGroup.add(byTimeRadioButton);
     592            userHistoryPanel.add(byAreaRadioButton);
     593            userHistoryPanel.add(byTimeRadioButton);
     594            userHistoryPanel.add(daysLabel);
     595            userHistoryPanel.add(daysField);
     596            userHistoryPanel.add(userNameLabel);
     597            userHistoryPanel.add(userNameField);
     598
     599            //grouplayout for user history panel
     600            /*
     601                userNameLabel       userField
     602                arearadiobutton
     603                timeradiobutton     daysLabel   daysField
     604             */
     605            buildUserHistoryPanelGroupLayout();
     606
     607            configPanel.add(inputPanel, BorderLayout.NORTH);
     608            configPanel.add(userHistoryPanel, BorderLayout.EAST);
     609            configPanel.add(paramPanel, BorderLayout.WEST);
     610            configPanel.add(southPanel, BorderLayout.SOUTH);
     611
     612            userHistoryPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
     613                    .createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE), "Train by user History"));
     614            paramPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
     615                    .createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE), "SVM Configuration"));
     616            inputPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));
     617            configPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));
     618
     619            mainPanel.add(configPanel, BorderLayout.NORTH);
     620            mainPanel.add(startTrainingButton, BorderLayout.CENTER);
     621            mainPanel.add(trainingProgressBar, BorderLayout.SOUTH);
     622
     623            AutoCompletionManager autocomplete = Main.getLayerManager().getEditLayer().data.getAutoCompletionManager();
     624            List<AutoCompletionListItem> keyList = autocomplete.getKeys();
     625            Collections.sort(keyList, defaultACItemComparator);
     626
     627            setContent(mainPanel, false);
     628        }
     629
     630        private void buildInputPanelGroupLayout(JPanel inputPanel) {
    617631            GroupLayout inputGroupLayout = new GroupLayout(inputPanel);
    618632            inputPanel.setLayout(inputGroupLayout);
    619633            inputGroupLayout.setAutoCreateGaps(true);
    620634            inputGroupLayout.setAutoCreateContainerGaps(true);
    621            
     635
    622636            GroupLayout.SequentialGroup inputHorGroup = inputGroupLayout.createSequentialGroup();
    623637            inputHorGroup.addGroup(inputGroupLayout.createParallelGroup().addComponent(inputFileLabel).
     
    626640            inputHorGroup.addGroup(inputGroupLayout.createParallelGroup().addComponent(fileBrowseButton));
    627641            inputGroupLayout.setHorizontalGroup(inputHorGroup);
    628            
     642
    629643            GroupLayout.SequentialGroup inputVerGroup = inputGroupLayout.createSequentialGroup();
    630644            inputVerGroup.addGroup(inputGroupLayout.createParallelGroup(Alignment.LEADING).addComponent(inputFileLabel).
     
    633647                    addComponent(inputFileErrorMessageLabel));
    634648            inputGroupLayout.setVerticalGroup(inputVerGroup);
    635            
    636            
    637             //grouplayout for param panel
     649        }
     650
     651        private void buildParamPanelGroupLayout(JPanel paramPanel) {
    638652            GroupLayout paramGroupLayout = new GroupLayout(paramPanel);
    639653            paramPanel.setLayout(paramGroupLayout);
    640654            paramGroupLayout.setAutoCreateGaps(true);
    641655            paramGroupLayout.setAutoCreateContainerGaps(true);
    642            
     656
    643657            GroupLayout.SequentialGroup paramHorGroup = paramGroupLayout.createSequentialGroup();
    644658            paramHorGroup.addGroup(paramGroupLayout.createParallelGroup().addComponent(topKButton).
    645659                    addComponent(frequencyButton).addComponent(cParameterCheckBox));
    646660            paramHorGroup.addGroup(paramGroupLayout.createParallelGroup().addComponent(cParameterField).
    647                     addComponent(topKField).addComponent(frequencyField));           
     661                    addComponent(topKField).addComponent(frequencyField));
    648662            paramHorGroup.addGroup(paramGroupLayout.createParallelGroup().addComponent(cErrorMessageLabel).
    649663                    addComponent(topKErrorMessageLabel).addComponent(frequencyErrorMessageLabel));
    650664            paramGroupLayout.setHorizontalGroup(paramHorGroup);
    651                        
     665
    652666            GroupLayout.SequentialGroup paramVerGroup = paramGroupLayout.createSequentialGroup();
    653667            paramVerGroup.addGroup(paramGroupLayout.createParallelGroup(Alignment.BASELINE).
     
    657671            paramVerGroup.addGroup(paramGroupLayout.createParallelGroup(Alignment.BASELINE).
    658672                    addComponent(frequencyButton).addComponent(frequencyField).addComponent(frequencyErrorMessageLabel));
    659             paramGroupLayout.setVerticalGroup(paramVerGroup);     
    660            
    661             inputPanel.add(inputFileLabel);
    662             inputPanel.add(inputFileField);           
    663             inputPanel.add(fileBrowseButton);   
    664             inputPanel.add(inputFileErrorMessageLabel);
    665            
    666             paramGroup.add(topKButton);
    667             paramGroup.add(frequencyButton);
    668            
    669             paramPanel.add(cParameterCheckBox);
    670             paramPanel.add(cParameterField);
    671             paramPanel.add(cErrorMessageLabel);
    672             paramPanel.add(topKButton);
    673             paramPanel.add(topKField); 
    674             paramPanel.add(topKErrorMessageLabel);
    675             paramPanel.add(frequencyButton);
    676             paramPanel.add(frequencyField);
    677             paramPanel.add(frequencyErrorMessageLabel);
    678            
    679             southPanel.add(acceptConfigButton);
    680             southPanel.add(resetConfigButton);
    681             southPanel.add(trainFromUserCheckBox);
    682 
    683             userGroup.add(byAreaRadioButton);
    684             userGroup.add(byTimeRadioButton);
    685             userHistoryPanel.add(byAreaRadioButton);
    686             userHistoryPanel.add(byTimeRadioButton);
    687             userHistoryPanel.add(daysLabel);
    688             userHistoryPanel.add(daysField);
    689             userHistoryPanel.add(userNameLabel);
    690             userHistoryPanel.add(userNameField);   
    691             //userHistoryPanel.add(trainFromUserCheckBox);   
    692            
    693             //grouplayout for user history panel
    694             /*
    695                 userNameLabel       userField
    696                 arearadiobutton
    697                 timeradiobutton     daysLabel   daysField
    698             */
     673            paramGroupLayout.setVerticalGroup(paramVerGroup);
     674        }
     675
     676        private void buildUserHistoryPanelGroupLayout() {
    699677            GroupLayout userHistoryGroupLayout = new GroupLayout(userHistoryPanel);
    700             //userHistoryGroupLayout.se
    701678            userHistoryPanel.setLayout(userHistoryGroupLayout);
    702679            userHistoryGroupLayout.setAutoCreateGaps(true);
    703             userHistoryGroupLayout.setAutoCreateContainerGaps(true); 
    704             userHistoryGroupLayout.linkSize(SwingConstants.HORIZONTAL, userNameField, daysLabel,daysField);
    705            
     680            userHistoryGroupLayout.setAutoCreateContainerGaps(true);
     681            userHistoryGroupLayout.linkSize(SwingConstants.HORIZONTAL, userNameField, daysLabel, daysField);
     682
    706683            GroupLayout.SequentialGroup userHistoryHorGroup = userHistoryGroupLayout.createSequentialGroup();
    707            
     684
    708685            userHistoryHorGroup.addGroup(userHistoryGroupLayout.createParallelGroup().addComponent(userNameLabel)
    709             .addComponent(byAreaRadioButton).addComponent(byTimeRadioButton));                       
     686                    .addComponent(byAreaRadioButton).addComponent(byTimeRadioButton));
    710687            userHistoryHorGroup.addGroup(userHistoryGroupLayout.createParallelGroup().addComponent(userNameField)
    711                     .addComponent(daysLabel));       
     688                    .addComponent(daysLabel));
    712689            userHistoryHorGroup.addGroup(userHistoryGroupLayout.createParallelGroup().addComponent(daysField));
    713690            userHistoryGroupLayout.setHorizontalGroup(userHistoryHorGroup);
    714            
     691
    715692            GroupLayout.SequentialGroup userHistoryVerGroup = userHistoryGroupLayout.createSequentialGroup();
    716693            userHistoryVerGroup.addGroup(userHistoryGroupLayout.createParallelGroup(Alignment.BASELINE).
    717                     addComponent(userNameLabel).addComponent(userNameField));           
     694                    addComponent(userNameLabel).addComponent(userNameField));
    718695            userHistoryVerGroup.addGroup(userHistoryGroupLayout.createParallelGroup(Alignment.BASELINE).
    719                     addComponent(byAreaRadioButton));           
     696                    addComponent(byAreaRadioButton));
    720697            userHistoryVerGroup.addGroup(userHistoryGroupLayout.createParallelGroup(Alignment.BASELINE).
    721                     addComponent(byTimeRadioButton).addComponent(daysLabel).addComponent(daysField)); 
     698                    addComponent(byTimeRadioButton).addComponent(daysLabel).addComponent(daysField));
    722699            userHistoryGroupLayout.setVerticalGroup(userHistoryVerGroup);
    723            
    724             configPanel.add(inputPanel, BorderLayout.NORTH);
    725             configPanel.add(userHistoryPanel, BorderLayout.EAST);
    726             configPanel.add(paramPanel, BorderLayout.WEST);
    727             configPanel.add(southPanel, BorderLayout.SOUTH);           
    728 
    729             userHistoryPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
    730                     .createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE), "Train by user History"));           
    731             paramPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory
    732                     .createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE), "SVM Configuration"));           
    733             inputPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));
    734             configPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));           
    735            
    736             mainPanel.add(configPanel, BorderLayout.NORTH);
    737             mainPanel.add(startTrainingButton, BorderLayout.CENTER);
    738             mainPanel.add(trainingProgressBar, BorderLayout.SOUTH);
    739            
    740             AutoCompletionManager autocomplete = Main.main.getEditLayer().data.getAutoCompletionManager();
    741             List<AutoCompletionListItem> keyList = autocomplete.getKeys();
    742             Collections.sort(keyList, defaultACItemComparator);
    743 
    744             setContent(mainPanel, false);
    745 
    746             addWindowListener(new WindowAdapter() {
    747                 @Override
    748                 public void windowOpened(WindowEvent e) {
    749                     if (initialFocusOnKey) {
    750                         selectKeysComboBox();
    751                     } else {
    752                         selectValuesCombobox();
    753                     }
    754                 }
    755             });
    756         }
    757        
    758         private void inputFileChooserButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                     
     700        }
     701
     702        private void inputFileChooserButtonActionPerformed(ActionEvent evt) {
    759703            try {
    760704                final File file = new File(inputFileField.getText());
     
    762706
    763707                final int returnVal = fileChooser.showOpenDialog(this);
    764                 if(returnVal == JFileChooser.APPROVE_OPTION) {
     708                if (returnVal == JFileChooser.APPROVE_OPTION) {
    765709                    inputFileField.setText(fileChooser.getSelectedFile().getAbsolutePath());
    766710                }
    767             }
    768             catch (RuntimeException ex) {
     711            } catch (RuntimeException ex) {
    769712                Main.warn(ex);
    770                 //ex.printStackTrace();
    771             }
    772         }
    773        
    774         private void acceptConfigButtonActionPerformed(java.awt.event.ActionEvent evt) {
     713            }
     714        }
     715
     716        private void acceptConfigButtonActionPerformed(ActionEvent evt) {
    775717            //parse values
    776718            inputFileValue = inputFileField.getText();
    777            
    778             if(!new File(inputFileValue).exists()){
     719
     720            if (!new File(inputFileValue).exists()) {
    779721                inputFileErrorMessageLabel.setText("OSM file does not exist");
    780722                resetConfigButtonActionPerformed();
    781723                return;
    782724            }
    783            
    784             if(cParameterCheckBox.isSelected()){
     725
     726            if (cParameterCheckBox.isSelected()) {
    785727                String c = cParameterField.getText();
    786728                try {
    787                     cParameterValue = Double.parseDouble(c.replace(",","."));
     729                    cParameterValue = Double.parseDouble(c.replace(",", "."));
    788730                    cErrorMessageLabel.setText("");
    789                 }
    790                 catch(NumberFormatException ex){
    791                    
     731                } catch (NumberFormatException ex) {
    792732                    cErrorMessageLabel.setText("Must be a number!");
    793                     System.out.println("c must be a number!" + ex); //make empty textLabel beside c param to notify errors 
     733                    System.out.println("c must be a number!" + ex); //make empty textLabel beside c param to notify errors
    794734                    resetConfigButtonActionPerformed();
    795                     return;
    796                 }
    797                 crossValidateFlag = false;               
    798             }
    799             else{
     735                    return;
     736                }
     737                crossValidateFlag = false;
     738            } else {
    800739                crossValidateFlag = true;
    801740            }
    802            
    803             if(topKButton.isSelected()){
     741
     742            if (topKButton.isSelected()) {
    804743                String k = topKField.getText();
    805744                try {
    806                     topKvalue = Integer.parseInt(k); 
     745                    topKvalue = Integer.parseInt(k);
    807746                    topKErrorMessageLabel.setText("");
    808                 }
    809                 catch(NumberFormatException ex){
    810                     topKErrorMessageLabel.setText("Must be an Integer!");
    811                     resetConfigButtonActionPerformed();
    812                     return;
    813                 }
    814             }
    815             else{
    816                 String f = frequencyField.getText();
    817                 try{
    818                     frequencyValue = Integer.parseInt(f);
    819                     frequencyErrorMessageLabel.setText("");
    820                 }
    821                 catch(NumberFormatException ex){
    822                     frequencyErrorMessageLabel.setText("Must be an Integer!");
     747                } catch (NumberFormatException ex) {
     748                    topKErrorMessageLabel.setText("Must be an Integer!");
    823749                    resetConfigButtonActionPerformed();
    824750                    return;
    825751                }
    826             }
    827            
    828             if(trainFromUserCheckBox.isSelected()){
     752            } else {
     753                String f = frequencyField.getText();
     754                try {
     755                    frequencyValue = Integer.parseInt(f);
     756                    frequencyErrorMessageLabel.setText("");
     757                } catch (NumberFormatException ex) {
     758                    frequencyErrorMessageLabel.setText("Must be an Integer!");
     759                    resetConfigButtonActionPerformed();
     760                    return;
     761                }
     762            }
     763
     764            if (trainFromUserCheckBox.isSelected()) {
    829765                usernameValue = userNameField.getText();
    830                 if(byTimeRadioButton.isSelected()){
    831                     try{
     766                if (byTimeRadioButton.isSelected()) {
     767                    try {
    832768                        daysValue = Integer.parseInt(daysField.getText());
    833                     }
    834                     catch (NumberFormatException ex){
     769                    } catch (NumberFormatException ex) {
    835770                        daysField.setText("Integer!");
    836771                        Main.warn(ex);
    837                     } 
    838                 }
    839                
     772                    }
     773                }
     774
    840775                userHistoryPanel.setEnabled(false);
    841776                byAreaRadioButton.setEnabled(false);
     
    844779                userNameField.setEnabled(false);
    845780                daysLabel.setEnabled(false);
    846                 daysField.setEnabled(false);               
    847             }
    848 
    849             System.out.println("Running configuration:" + "\nC parameter: " + cParameterValue +" \ntopK: " + topKvalue 
    850                     + "\nMax Frequency: " + frequencyValue + "\nCross Validate?: " + crossValidateFlag);                       
    851            
     781                daysField.setEnabled(false);
     782            }
     783
     784            System.out.println("Running configuration:" + "\nC parameter: " + cParameterValue +" \ntopK: " + topKvalue
     785                    + "\nMax Frequency: " + frequencyValue + "\nCross Validate?: " + crossValidateFlag);
     786
    852787            trainFromUserCheckBox.setEnabled(false);
    853788            inputFileField.setEditable(false);
    854             cParameterField.setEditable(false); 
     789            cParameterField.setEditable(false);
    855790            topKField.setEditable(false);
    856             frequencyField.setEditable(false);                               
    857             cParameterCheckBox.setEnabled(false); 
     791            frequencyField.setEditable(false);
     792            cParameterCheckBox.setEnabled(false);
    858793            topKButton.setEnabled(false);
    859794            frequencyButton.setEnabled(false);
    860             acceptConfigButton.setEnabled(false);         
    861             fileBrowseButton.setEnabled(false); 
    862         }
    863 
    864         private void resetConfigButtonActionPerformed() { 
    865             if(trainWorker != null){
     795            acceptConfigButton.setEnabled(false);
     796            fileBrowseButton.setEnabled(false);
     797        }
     798
     799        private void resetConfigButtonActionPerformed() {
     800            if (trainWorker != null) {
    866801                try {
    867802                    trainWorker.cancel(true);
    868                 }
    869                 catch(CancellationException ex){
    870                    startTrainingButton.setEnabled(true);
    871                    System.out.println(ex);
    872                 }
    873             }
    874             if(userDataExtractAndTrainWorker != null){
     803                } catch (CancellationException ex) {
     804                    startTrainingButton.setEnabled(true);
     805                    System.out.println(ex);
     806                }
     807            }
     808            if (userDataExtractAndTrainWorker != null) {
    875809                try {
    876810                    userDataExtractAndTrainWorker.cancel(true);
    877                 }
    878                 catch(CancellationException ex){
    879                    startTrainingButton.setEnabled(true);
    880                    System.out.println(ex);
    881                 }               
     811                } catch (CancellationException ex) {
     812                    startTrainingButton.setEnabled(true);
     813                    System.out.println(ex);
     814                }
    882815            }
    883816            inputFileField.setEditable(true);
    884             cParameterField.setEditable(true); 
     817            cParameterField.setEditable(true);
    885818            topKField.setEditable(true);
    886             frequencyField.setEditable(true);                               
    887             cParameterCheckBox.setEnabled(true); 
     819            frequencyField.setEditable(true);
     820            cParameterCheckBox.setEnabled(true);
    888821            topKButton.setEnabled(true);
    889822            frequencyButton.setEnabled(true);
    890             acceptConfigButton.setEnabled(true);         
     823            acceptConfigButton.setEnabled(true);
    891824            fileBrowseButton.setEnabled(true);
    892825            trainFromUserCheckBox.setEnabled(true);
    893            
    894             if(trainFromUserCheckBox.isSelected()){
     826
     827            if (trainFromUserCheckBox.isSelected()) {
    895828                userHistoryPanel.setEnabled(true);
    896829                byAreaRadioButton.setEnabled(true);
     
    899832                userNameField.setEnabled(true);
    900833                daysLabel.setEnabled(true);
    901                 daysField.setEnabled(true); 
    902             }   
    903         }       
    904        
     834                daysField.setEnabled(true);
     835            }
     836        }
     837
    905838        private void startTraining() {
    906839            startTrainingButton.setEnabled(false);
    907            
    908             if(trainFromUserCheckBox.isSelected()){ //if user training. train by area or days
    909  
    910                 java.awt.EventQueue.invokeLater(new Runnable() {                   
     840
     841            if (trainFromUserCheckBox.isSelected()) { //if user training. train by area or days
     842                EventQueue.invokeLater(new Runnable() {
    911843                    @Override
    912844                    public void run() {
    913845
    914                     userDataExtractAndTrainWorker = new UserDataExtractAndTrainWorker
    915                       (inputFileValue, usernameValue, daysValue, byAreaRadioButton.isSelected(),
    916                          crossValidateFlag, cParameterValue, topKvalue, frequencyValue,
    917                               topKButton.isSelected(), languageDetector);               
    918                
     846                        userDataExtractAndTrainWorker = new UserDataExtractAndTrainWorker(inputFileValue, usernameValue, daysValue,
     847                                byAreaRadioButton.isSelected(), crossValidateFlag, cParameterValue, topKvalue, frequencyValue,
     848                                topKButton.isSelected(), languageDetector);
     849
    919850                        userDataExtractAndTrainWorker.addPropertyChangeListener(new PropertyChangeListener() {
    920                            
    921                             @Override
     851                            @Override
    922852                            public void propertyChange(PropertyChangeEvent evt) {
    923                                 if("progress".equals(evt.getPropertyName())) {
     853                                if ("progress".equals(evt.getPropertyName())) {
    924854                                    int progress = (Integer) evt.getNewValue();
    925855                                    trainingProgressBar.setValue(progress);
    926                                     if(progress == 100){
     856                                    if (progress == 100) {
    927857                                        startTrainingButton.setEnabled(true);
    928858                                    }
    929859                                }
    930                             }                                                 
    931                         });                                                 
     860                            }
     861                        });
    932862
    933863                        try {
     
    936866                        } catch (Exception ex) {
    937867                            Logger.getLogger(OSMRecPluginHelper.class.getName()).log(Level.SEVERE, null, ex);
    938                         }                   
    939                     }
    940                 });                         
    941             }
    942             else {
    943 
    944                 java.awt.EventQueue.invokeLater(new Runnable() {
    945                     //private TrainWorker trainWorker;
     868                        }
     869                    }
     870                });
     871            } else {
     872                EventQueue.invokeLater(new Runnable() {
    946873                    @Override
    947874                    public void run() {
    948 
    949                         trainWorker = new TrainWorker
    950                                     (inputFileValue, crossValidateFlag, cParameterValue, topKvalue, frequencyValue,
    951                                             topKButton.isSelected(), languageDetector);
    952                        
     875                        trainWorker = new TrainWorker(inputFileValue, crossValidateFlag, cParameterValue, topKvalue, frequencyValue,
     876                                topKButton.isSelected(), languageDetector);
     877
    953878                        trainWorker.addPropertyChangeListener(new PropertyChangeListener() {
    954                             @Override 
     879                            @Override
    955880                            public void propertyChange(PropertyChangeEvent evt) {
    956                                 if("progress".equals(evt.getPropertyName())) {
     881                                if ("progress".equals(evt.getPropertyName())) {
    957882                                    int progress = (Integer) evt.getNewValue();
    958883                                    trainingProgressBar.setValue(progress);
    959                                     if(progress == 100){
     884                                    if (progress == 100) {
    960885                                        startTrainingButton.setEnabled(true);
    961886                                    }
    962887                                }
    963     //                            if(cancelled){
    964     //                                trainWorker.cancel(true);
    965     //                            }
    966                             }                                                 
    967                         });                                                 
     888                            }
     889                        });
    968890
    969891                        try {
     
    971893                        } catch (Exception ex) {
    972894                            Logger.getLogger(OSMRecPluginHelper.class.getName()).log(Level.SEVERE, null, ex);
    973                         }                   
    974                     }
    975                 }); 
     895                        }
     896                    }
     897                });
    976898            }
    977899        }
    978900    }
    979901
    980     public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE = new BooleanProperty("properties.fix-tag-combobox-locale", false);
    981     public static final BooleanProperty PROPERTY_REMEMBER_TAGS = new BooleanProperty("properties.remember-recently-added-tags", true);
    982     public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER = new IntegerProperty("properties.recently-added-tags", DEFAULT_LRU_TAGS_NUMBER);
    983 
    984     abstract class AbstractTagsDialog extends ExtendedDialog {
     902    public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE =
     903            new BooleanProperty("properties.fix-tag-combobox-locale", false);
     904    public static final BooleanProperty PROPERTY_REMEMBER_TAGS =
     905            new BooleanProperty("properties.remember-recently-added-tags", true);
     906    public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER =
     907            new IntegerProperty("properties.recently-added-tags", DEFAULT_LRU_TAGS_NUMBER);
     908
     909    abstract static class AbstractTagsDialog extends ExtendedDialog {
    985910        AutoCompletingComboBox keys;
    986911        AutoCompletingComboBox values;
    987         Component componentUnderMouse;
    988 
    989         public AbstractTagsDialog(Component parent, String title, String[] buttonTexts) {
     912
     913        AbstractTagsDialog(Component parent, String title, String[] buttonTexts) {
    990914            super(parent, title, buttonTexts);
    991915            addMouseListener(new PopupMenuLauncher(popupMenu));
     
    1004928
    1005929            setRememberWindowGeometry(getClass().getName() + ".geometry",
    1006                 WindowGeometry.centerInWindow(Main.parent, size));
     930                    WindowGeometry.centerInWindow(Main.parent, size));
    1007931        }
    1008932
     
    1024948                    rememberWindowGeometry(geometry);
    1025949                }
    1026                 if(keys != null){
    1027                    keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
    1028                 }               
     950                if (keys != null) {
     951                    keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
     952                }
    1029953            }
    1030954            super.setVisible(visible);
    1031955        }
    1032956
    1033         private void selectACComboBoxSavingUnixBuffer(AutoCompletingComboBox cb) {
    1034             // select combobox with saving unix system selection (middle mouse paste)
    1035             Clipboard sysSel = Toolkit.getDefaultToolkit().getSystemSelection();
    1036             if(sysSel != null) {
    1037                 Transferable old = sysSel.getContents(null);
    1038                 cb.requestFocusInWindow();
    1039                 cb.getEditor().selectAll();
    1040                 sysSel.setContents(old, null);
    1041             } else {
    1042                 cb.requestFocusInWindow();
    1043                 cb.getEditor().selectAll();
    1044             }
    1045         }
    1046 
    1047         public void selectKeysComboBox() {
    1048             //selectACComboBoxSavingUnixBuffer(keys);
    1049         }
    1050 
    1051         public void selectValuesCombobox()   {
    1052             //selectACComboBoxSavingUnixBuffer(values);
    1053         }
    1054 
    1055957        /**
    1056         * Create a focus handling adapter and apply in to the editor component of value
    1057         * autocompletion box.
    1058         * @param autocomplete Manager handling the autocompletion
    1059         * @param comparator Class to decide what values are offered on autocompletion
    1060         * @return The created adapter
    1061         */
     958         * Create a focus handling adapter and apply in to the editor component of value
     959         * autocompletion box.
     960         * @param autocomplete Manager handling the autocompletion
     961         * @param comparator Class to decide what values are offered on autocompletion
     962         * @return The created adapter
     963         */
    1062964        protected FocusAdapter addFocusAdapter(final AutoCompletionManager autocomplete, final Comparator<AutoCompletionListItem> comparator) {
    1063            // get the combo box' editor component
    1064            JTextComponent editor = (JTextComponent)values.getEditor().getEditorComponent();
    1065            // Refresh the values model when focus is gained
    1066            FocusAdapter focus = new FocusAdapter() {
    1067                @Override
    1068                public void focusGained(FocusEvent e) {
    1069                    String key = keys.getEditor().getItem().toString();
    1070 
    1071                    List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
    1072                    Collections.sort(valueList, comparator);
    1073 
    1074                    values.setPossibleACItems(valueList);
    1075                    values.getEditor().selectAll();
    1076                    objKey=key;
    1077                }
    1078            };
    1079            editor.addFocusListener(focus);
    1080            return focus;
     965            // get the combo box' editor component
     966            JTextComponent editor = (JTextComponent) values.getEditor().getEditorComponent();
     967            // Refresh the values model when focus is gained
     968            FocusAdapter focus = new FocusAdapter() {
     969                @Override
     970                public void focusGained(FocusEvent e) {
     971                    String key = keys.getEditor().getItem().toString();
     972
     973                    List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
     974                    Collections.sort(valueList, comparator);
     975
     976                    values.setPossibleACItems(valueList);
     977                    values.getEditor().selectAll();
     978                }
     979            };
     980            editor.addFocusListener(focus);
     981            return focus;
    1081982        }
    1082983
    1083984        protected JPopupMenu popupMenu = new JPopupMenu() {
    1084985            JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem(
    1085                 new AbstractAction(tr("Use English language for tag by default")){
    1086                 @Override
    1087                 public void actionPerformed(ActionEvent e) {
    1088                     boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
    1089                     PROPERTY_FIX_TAG_LOCALE.put(sel);
    1090                 }
    1091             });
     986                    new AbstractAction(tr("Use English language for tag by default")) {
     987                        @Override
     988                        public void actionPerformed(ActionEvent e) {
     989                            boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
     990                            PROPERTY_FIX_TAG_LOCALE.put(sel);
     991                        }
     992                    });
    1092993            {
    1093994                add(fixTagLanguageCb);
     
    1097998    }
    1098999
    1099     class ModelSettingsDialog extends JPanel{
    1100        
     1000    class ModelSettingsDialog extends JPanel {
     1001
    11011002        private final JLabel chooseModelLabel;
    11021003        private final JButton chooseModelButton;
    11031004        private final JTextField chooseModelTextField;
    1104        
     1005
    11051006        private final DefaultListModel<String> combinationDefaultListModel = new DefaultListModel<>();
    1106         private final JList<String> modelCombinationList = new javax.swing.JList<>(combinationDefaultListModel);
     1007        private final JList<String> modelCombinationList = new JList<>(combinationDefaultListModel);
    11071008        private final JPanel modelCombinationPanel;
    1108         //private final JTextField weightTextField;
    11091009        private final JPanel weightsPanel;
    1110         //private final int hei;
    1111         //private final int wi;
    11121010        private final JCheckBox useModelCombinationCheckbox;
    11131011        private final JButton acceptWeightsButton;
     
    11261024        private final TitledBorder weightTitle;
    11271025        private final TitledBorder combineTitle;
    1128         //private final BorderLayout mainBorderLayout;
    1129         //private final BorderLayout mainBorderLayoutDefault;
    1130         //private final Dimension combinationPanelDimension;
    11311026        private final Dimension singleSelectionDimension;
    11321027        private final Dimension modelCombinationDimension;
    11331028        private final Dimension mainPanelDimension;
    1134        
    1135        
    1136         public ModelSettingsDialog(Collection<OsmPrimitive> sel1, final AddTagsDialog addDialog){
    1137            
     1029
     1030        ModelSettingsDialog(Collection<OsmPrimitive> sel1, final AddTagsDialog addDialog) {
     1031
    11381032            loadPreviousCombinedSVMModel();
    1139             singleSelectionDimension = new Dimension(470,70);
    1140             modelCombinationDimension = new Dimension(450,250);
    1141             mainPanelDimension = new Dimension(600,350);
    1142            
     1033            singleSelectionDimension = new Dimension(470, 70);
     1034            modelCombinationDimension = new Dimension(450, 250);
     1035            mainPanelDimension = new Dimension(600, 350);
     1036
    11431037            //------- <NORTH of main> ---------//
    1144             mainPanel = new JPanel(new BorderLayout(10,10));
    1145             singleSelectionPanel = new JPanel(new BorderLayout(10,10));
     1038            mainPanel = new JPanel(new BorderLayout(10, 10));
     1039            singleSelectionPanel = new JPanel(new BorderLayout(10, 10));
    11461040            setResetWeightsPanel = new JPanel();
    1147            
    1148             chooseModelLabel = new javax.swing.JLabel("Choose a Model:");
    1149             chooseModelTextField = new javax.swing.JTextField();
    1150             chooseModelButton = new javax.swing.JButton("...");
    1151             chooseModelTextField.setText(MODEL_PATH);                       
    1152            
    1153             singleSelectionPanel.add(chooseModelLabel, BorderLayout.NORTH); 
     1041
     1042            chooseModelLabel = new JLabel("Choose a Model:");
     1043            chooseModelTextField = new JTextField();
     1044            chooseModelButton = new JButton("...");
     1045            chooseModelTextField.setText(MODEL_PATH);
     1046
     1047            singleSelectionPanel.add(chooseModelLabel, BorderLayout.NORTH);
    11541048            singleSelectionPanel.add(chooseModelTextField, BorderLayout.WEST);
    1155             singleSelectionPanel.add(chooseModelButton, BorderLayout.EAST); 
    1156            
     1049            singleSelectionPanel.add(chooseModelButton, BorderLayout.EAST);
     1050
    11571051            singleSelectionScrollPane = new JScrollPane(singleSelectionPanel);
    11581052            singleSelectionScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    11591053            singleSelectionScrollPane.setPreferredSize(singleSelectionDimension);
    1160            
     1054
    11611055            //------- </NORTH of main> ---------//
    11621056
    11631057            //------- <WEST of main> ---------//
    1164             //modelCombinationList = new javax.swing.JList<>(combinationDefaultListModel);
    1165             modelCombinationList.setFixedCellHeight(20); 
     1058            modelCombinationList.setFixedCellHeight(20);
    11661059            modelCombinationList.setEnabled(false);
    1167             modelCombinationPanel = new JPanel(new BorderLayout(10,10)); //new BorderLayout()
     1060            modelCombinationPanel = new JPanel(new BorderLayout(10, 10));
    11681061
    11691062            weightsPanel = new JPanel();
    1170             weightsPanel.setLayout(new BoxLayout(weightsPanel, BoxLayout.Y_AXIS)); 
     1063            weightsPanel.setLayout(new BoxLayout(weightsPanel, BoxLayout.Y_AXIS));
    11711064            weightsPanel.setEnabled(false);
    1172            
    1173            
    1174             acceptWeightsButton = new javax.swing.JButton("Set Weights/Normalize");
    1175             resetWeightsButton = new javax.swing.JButton("Reset Weights");
    1176             removeSelectedModelButton = new javax.swing.JButton("Remove Selected");
     1065
     1066
     1067            acceptWeightsButton = new JButton("Set Weights/Normalize");
     1068            resetWeightsButton = new JButton("Reset Weights");
     1069            removeSelectedModelButton = new JButton("Remove Selected");
    11771070            setResetWeightsPanel.add(acceptWeightsButton);
    11781071            setResetWeightsPanel.add(resetWeightsButton);
     
    11811074            acceptWeightsButton.setEnabled(false);
    11821075            resetWeightsButton.setEnabled(false);
    1183            
     1076
    11841077            modelCombinationPanel.add(modelCombinationList, BorderLayout.CENTER);
    11851078            modelCombinationPanel.add(weightsPanel, BorderLayout.EAST);
    1186             modelCombinationPanel.add(setResetWeightsPanel, BorderLayout.SOUTH); 
     1079            modelCombinationPanel.add(setResetWeightsPanel, BorderLayout.SOUTH);
    11871080
    11881081            combinationScrollPane = new JScrollPane(modelCombinationPanel);
    1189            
     1082
    11901083            combinationScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    1191             combinationScrollPane.setPreferredSize(modelCombinationDimension);   //new Dimension(450,250) // w/h 
     1084            combinationScrollPane.setPreferredSize(modelCombinationDimension);   //new Dimension(450, 250) // w/h
    11921085
    11931086            //------- </WEST of main> ---------//
     
    11951088            //------- <SOUTH of main> ---------//
    11961089            useModelCombinationCheckbox = new JCheckBox("Combine different models?");
    1197            
     1090
    11981091            //------- </SOUTH of main> ---------//
    1199            
     1092
    12001093            //------- <Borders> ---------//
    12011094            modelTitle = BorderFactory.createTitledBorder("Models");
     
    12041097            modelCombinationList.setBorder(modelTitle);
    12051098            weightsPanel.setBorder(weightTitle);
    1206            
    1207             for(Entry<JTextField, String> entry : weightFieldsAndPaths.entrySet()){
    1208                 //modelCombinationList.add(entry.getValue());
     1099
     1100            for (Entry<JTextField, String> entry : weightFieldsAndPaths.entrySet()) {
    12091101                combinationDefaultListModel.addElement(entry.getValue());
    1210                
    1211                 JTextField weightTextField = new javax.swing.JTextField("0.00");                   
    1212                 weightTextField.setMaximumSize(new Dimension(80,20));
    1213                 weightsPanel.add(entry.getKey());               
    1214 
    1215                 //entry.getKey().setText("0.00");
    1216             }           
    1217            
     1102
     1103                JTextField weightTextField = new JTextField("0.00");
     1104                weightTextField.setMaximumSize(new Dimension(80, 20));
     1105                weightsPanel.add(entry.getKey());
     1106            }
     1107
    12181108            //modelCombinationPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));
    12191109            modelCombinationPanel.setBorder(combineTitle);
     
    12261116                    modelChooserButtonActionPerformed(evt);
    12271117                }
    1228             }); 
    1229            
     1118            });
     1119
    12301120            useModelCombinationCheckbox.addActionListener(new java.awt.event.ActionListener() {
    12311121                @Override
     
    12341124                }
    12351125            });
    1236            
     1126
    12371127            acceptWeightsButton.addActionListener(new java.awt.event.ActionListener() {
    12381128                @Override
     
    12401130                    acceptWeightsButtonActionPerformed(evt);
    12411131                }
    1242             }); 
    1243            
     1132            });
     1133
    12441134            resetWeightsButton.addActionListener(new java.awt.event.ActionListener() {
    12451135                @Override
     
    12471137                    resetWeightsButtonActionPerformed(evt);
    12481138                }
    1249             }); 
    1250            
     1139            });
     1140
    12511141            removeSelectedModelButton.addActionListener(new java.awt.event.ActionListener() {
    12521142                @Override
     
    12541144                    removeSelectedModelButtonActionPerformed(evt);
    12551145                }
    1256             });           
     1146            });
    12571147            mainPanel.add(singleSelectionScrollPane, BorderLayout.NORTH);
    1258             mainPanel.add(combinationScrollPane, BorderLayout.CENTER); 
    1259             mainPanel.add(useModelCombinationCheckbox,BorderLayout.SOUTH);
     1148            mainPanel.add(combinationScrollPane, BorderLayout.CENTER);
     1149            mainPanel.add(useModelCombinationCheckbox, BorderLayout.SOUTH);
    12601150
    12611151            mainPanel.setPreferredSize(mainPanelDimension);
    1262            
     1152
    12631153            this.add(mainPanel);
    1264             //pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    1265            
    1266             //final JFrame frame = new JFrame();
     1154
    12671155            pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
    12681156                @Override
    12691157                public void setValue(Object newValue) {
    12701158                    super.setValue(newValue);
    1271                     if(newValue instanceof Integer && (int) newValue == 0 && useModelCombinationCheckbox.isSelected()){
     1159                    if (newValue instanceof Integer && (int) newValue == 0 && useModelCombinationCheckbox.isSelected()) {
    12721160                        System.out.println("model settings button value: " + newValue);
    12731161                        System.out.println("\nUSE COMBINED MODEL\n");
    12741162                        useCombinedModel = true;
    12751163                        useCustomSVMModel = false;
    1276                        
    1277                         addDialog.loadSVMmodel(); 
    1278                         addDialog.createOSMObject(sel);                             
     1164
     1165                        addDialog.loadSVMmodel();
     1166                        addDialog.createOSMObject(sel);
    12791167                        saveCombinedModel();
    12801168                        dlg.setVisible(false);
    1281                         //this.setVisible(false);
    1282                     }
    1283                     else if(newValue instanceof Integer && (int) newValue == -1 && useModelCombinationCheckbox.isSelected()){
     1169                    } else if (newValue instanceof Integer && (int) newValue == -1 && useModelCombinationCheckbox.isSelected()) {
    12841170                        System.out.println("model settings button value: " + newValue);
    12851171                        useCombinedModel = false;
     
    12901176                        addDialog.createOSMObject(sel);
    12911177                        dlg.setVisible(false);
    1292                     }
    1293                     else if(newValue instanceof Integer && (int) newValue == 0 && !useModelCombinationCheckbox.isSelected() ){
     1178                    } else if (newValue instanceof Integer && (int) newValue == 0 && !useModelCombinationCheckbox.isSelected()) {
    12941179                        System.out.println("model settings button value: " + newValue);
    12951180                        System.out.println("Don t use combined model, use custom model");
     
    12991184                        addDialog.createOSMObject(sel);
    13001185                        dlg.setVisible(false);
    1301                     }
    1302                     else if(newValue instanceof Integer && (int) newValue == -1 && !useModelCombinationCheckbox.isSelected() ){
     1186                    } else if (newValue instanceof Integer && (int) newValue == -1 && !useModelCombinationCheckbox.isSelected()) {
    13031187                        System.out.println("model settings button value: " + newValue);
    13041188                        System.out.println("Don t use combined model, use custom model");
     
    13081192                        addDialog.createOSMObject(sel);
    13091193                        dlg.setVisible(false);
    1310                     }     
    1311                     else if(newValue == null || newValue.equals("uninitializedValue")){
     1194                    } else if (newValue == null || newValue.equals("uninitializedValue")) {
    13121195                        System.out.println("uninitializedValue, do nothing");
    13131196                    }
    1314                     //JOptionPane.showMessageDialog(frame.getContentPane(), "You have hit " + newValue);
    1315                 }
    1316             };           
     1197                }
     1198            };
    13171199
    13181200            dlg = pane.createDialog(Main.parent, tr("Model Settings"));
    1319             dlg.setVisible(true); 
    1320            
    1321         }
    1322        
    1323         public void makeVisible(boolean visible){
    13241201            dlg.setVisible(true);
    13251202        }
    1326        
    1327         private void modelChooserButtonActionPerformed(java.awt.event.ActionEvent evt) {   
    1328            
     1203
     1204        public void makeVisible(boolean visible) {
     1205            dlg.setVisible(true);
     1206        }
     1207
     1208        private void modelChooserButtonActionPerformed(ActionEvent evt) {
     1209
    13291210            try {
    13301211                final File file = new File(chooseModelTextField.getText());
    13311212                final JFileChooser fileChooser = new JFileChooser(file);
    1332            
     1213
    13331214                final int returnVal = fileChooser.showOpenDialog(this);
    1334                 if(returnVal == JFileChooser.APPROVE_OPTION) {
     1215                if (returnVal == JFileChooser.APPROVE_OPTION) {
    13351216                    chooseModelTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
    13361217                    useCustomSVMModel = true;
    13371218                    customSVMModelPath = fileChooser.getSelectedFile().getAbsolutePath();
    13381219                }
    1339                                
    1340                 if(useModelCombinationCheckbox.isSelected()){
     1220
     1221                if (useModelCombinationCheckbox.isSelected()) {
    13411222                    String svmModelPath = fileChooser.getSelectedFile().getAbsolutePath();
    13421223                    String svmModelText;
    1343                     if(System.getProperty("os.name").contains("ux")){
    1344                         if(svmModelPath.contains("/")){
     1224                    if (System.getProperty("os.name").contains("ux")) {
     1225                        if (svmModelPath.contains("/")) {
    13451226                            svmModelText = svmModelPath.substring(svmModelPath.lastIndexOf("/"));
    1346                         }
    1347                         else{
     1227                        } else {
    13481228                            svmModelText = svmModelPath;
    13491229                        }
    1350                     }
    1351                     else{
    1352                          if(svmModelPath.contains("\\")){
     1230                    } else {
     1231                        if (svmModelPath.contains("\\")) {
    13531232                            svmModelText = svmModelPath.substring(svmModelPath.lastIndexOf("\\"));
    1354                         }
    1355                         else{
     1233                        } else {
    13561234                            svmModelText = svmModelPath;
    1357                         }                       
     1235                        }
    13581236                    }
    13591237                    combinationDefaultListModel.addElement(svmModelText);
    1360                     JTextField weightTextField = new javax.swing.JTextField("0.00");
     1238                    JTextField weightTextField = new JTextField("0.00");
    13611239                    weightFieldsAndPaths.put(weightTextField, svmModelPath);
    13621240                    System.out.println("weights size: " + weightFieldsAndPaths.size());
    1363                    
    1364                     weightTextField.setMaximumSize(new Dimension(80,20));
     1241
     1242                    weightTextField.setMaximumSize(new Dimension(80, 20));
    13651243                    weightsPanel.add(weightTextField);
    13661244                    //add additional textbox
    1367                 }                 
    1368             }
    1369             catch (RuntimeException ex) {
     1245                }
     1246            } catch (RuntimeException ex) {
    13701247                Main.warn(ex);
    1371                 //ex.printStackTrace();
    1372             }
    1373         }
    1374        
     1248            }
     1249        }
     1250
    13751251        private void userCombinationCheckboxActionPerformed(java.awt.event.ActionEvent evt) {
    13761252
    1377             if(useModelCombinationCheckbox.isSelected()){
     1253            if (useModelCombinationCheckbox.isSelected()) {
    13781254                useCombinedModel = true;
    13791255                useCustomSVMModel = false; //reseting the selected custom SVM model only here
     
    13811257                acceptWeightsButton.setEnabled(true);
    13821258                resetWeightsButton.setEnabled(true);
    1383                
     1259
    13841260                chooseModelTextField.setEnabled(false);
    13851261                modelCombinationList.setEnabled(true);
     
    13891265                    weightPanelComponent.setEnabled(true);
    13901266                }
    1391                
    1392             }
    1393             else{
     1267            } else {
    13941268                useCombinedModel = false;
    13951269                useCustomSVMModel = true;
     
    13971271                acceptWeightsButton.setEnabled(false);
    13981272                resetWeightsButton.setEnabled(false);
    1399                
     1273
    14001274                chooseModelTextField.setEnabled(true);
    14011275                modelCombinationList.setEnabled(false);
     
    14071281            }
    14081282        }
    1409        
     1283
    14101284        private void acceptWeightsButtonActionPerformed(ActionEvent evt) {
    14111285            int weightsCount = 0;
    14121286            removeSelectedModelButton.setEnabled(false);
    1413             double weightSum = 0;           
    1414             for(JTextField weightField : weightFieldsAndPaths.keySet()){
    1415                 if(weightField.getText().equals("")){
     1287            double weightSum = 0;
     1288            for (JTextField weightField : weightFieldsAndPaths.keySet()) {
     1289                if (weightField.getText().equals("")) {
    14161290                    weightField.setText("0.00");
    14171291                }
    1418                
    1419                 try{
     1292
     1293                try {
    14201294                    //TODO replace "," with "." to parse doubles with commas
    14211295                    Double weightValue = Double.parseDouble(weightField.getText());
     
    14231297                    weightValue = Math.abs(weightValue);
    14241298                    weightSum += weightValue;
    1425                 }   
    1426                 catch (NumberFormatException ex){
     1299                } catch (NumberFormatException ex) {
    14271300                    Main.warn(ex);
    14281301                }
    14291302                weightsCount++;
    1430             } 
    1431            
    1432             if(!filesAndWeights.isEmpty()){
     1303            }
     1304
     1305            if (!filesAndWeights.isEmpty()) {
    14331306                filesAndWeights.clear();
    14341307            }
    1435            
    1436             for(JTextField weightField : weightFieldsAndPaths.keySet()){
    1437                 try{
     1308
     1309            for (JTextField weightField : weightFieldsAndPaths.keySet()) {
     1310                try {
    14381311                    Double weightValue = Double.parseDouble(weightField.getText());
    14391312
    14401313                    weightValue = Math.abs(weightValue)/weightSum; //normalize
    1441                    
    1442                     if(weightSum == 0){
    1443                         //System.out.println("Zero weights");
     1314
     1315                    if (weightSum == 0) {
    14441316                        weightValue = 1.0/weightsCount;
    1445                     }                   
    1446                    
     1317                    }
     1318
    14471319                    weightField.setText(new DecimalFormat("#.##").format(weightValue));
    1448                     normalizedPathsAndWeights.put(weightFieldsAndPaths.get(weightField), weightValue);                   
     1320                    normalizedPathsAndWeights.put(weightFieldsAndPaths.get(weightField), weightValue);
    14491321                    filesAndWeights.put(new File(weightFieldsAndPaths.get(weightField)), weightValue);
    1450                     System.out.println("normalized: " + weightFieldsAndPaths.get(weightField) + "->"  + weightValue);
     1322                    System.out.println("normalized: " + weightFieldsAndPaths.get(weightField) + "->" + weightValue);
    14511323                    weightField.setEnabled(false);
    14521324
    1453                 }   
    1454                 catch (NumberFormatException ex){
     1325                } catch (NumberFormatException ex) {
    14551326                    Main.warn(ex);
    1456                 }     
     1327                }
    14571328            }
    14581329
    14591330            useCombinedModel = true;
    14601331            useCustomSVMModel = false;
    1461            
    1462             //filesAndWeights.putAll(normalizedPathsAndWeights);
    1463         }
    1464        
     1332        }
     1333
    14651334        private void resetWeightsButtonActionPerformed(ActionEvent evt) {
    14661335            removeSelectedModelButton.setEnabled(true);
    1467             for(JTextField weightField : weightFieldsAndPaths.keySet()){
     1336            for (JTextField weightField : weightFieldsAndPaths.keySet()) {
    14681337                weightField.setEnabled(true);
    14691338            }
    14701339        }
    1471        
     1340
    14721341        private void removeSelectedModelButtonActionPerformed(ActionEvent evt) {
    1473             int index  = modelCombinationList.getSelectedIndex();
     1342            int index = modelCombinationList.getSelectedIndex();
    14741343            String modelToBeRemoved = combinationDefaultListModel.get(index);
    1475             combinationDefaultListModel.remove(index); 
     1344            combinationDefaultListModel.remove(index);
    14761345            System.out.println("model to be removed: " + modelToBeRemoved);
    14771346
    1478             Iterator<Entry<JTextField, String>> it = weightFieldsAndPaths.entrySet().iterator();               
     1347            Iterator<Entry<JTextField, String>> it = weightFieldsAndPaths.entrySet().iterator();
    14791348            while (it.hasNext()) {
    14801349                Entry<JTextField, String> en = it.next();
    1481                 if(en.getValue().equals(modelToBeRemoved)){
     1350                if (en.getValue().equals(modelToBeRemoved)) {
    14821351                    it.remove();
    14831352                }
     
    14851354            System.out.println("model to be removed: " + modelToBeRemoved);
    14861355
    1487             weightsPanel.remove(index); 
     1356            weightsPanel.remove(index);
    14881357            weightsPanel.revalidate();
    14891358            weightsPanel.repaint();
     
    15071376                } finally {
    15081377                    try {
    1509                         if(in!=null){
     1378                        if (in != null) {
    15101379                            in.close();
    15111380                        }
    1512                         if(fileIn!=null){
     1381                        if (fileIn != null) {
    15131382                            fileIn.close();
    15141383                        }
    1515                        
     1384
    15161385                    } catch (IOException ex) {
    15171386                        Logger.getLogger(OSMRecPluginHelper.class.getName()).log(Level.SEVERE, null, ex);
     
    15291398        private void saveCombinedModel() {
    15301399            try (FileOutputStream fileOut = new FileOutputStream(combinedModelClasses);
    1531                 ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
     1400                    ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
    15321401                out.writeObject(weightFieldsAndPaths);
    15331402            } catch (IOException e) {
     
    15361405        }
    15371406    }
    1538    
    1539     class AddTagsDialog extends  AbstractTagsDialog {
     1407
     1408    class AddTagsDialog extends AbstractTagsDialog {
    15401409        List<JosmAction> recentTagsActions = new ArrayList<>();
    15411410
     
    15541423        private Map<Integer, String> idsWithMappings;
    15551424        private List<String> textualList = new ArrayList<>();
    1556         //private boolean useClassFeatures = false;
    1557         private final JCheckBox useTagsCheckBox; 
     1425        private final JCheckBox useTagsCheckBox;
    15581426        private ModelSettingsDialog modelSettingsDialog;
    15591427        private static final int RECOMMENDATIONS_SIZE = 10;
    15601428
    1561         public AddTagsDialog() {
    1562             super(Main.parent, tr("Add value?"), new String[] {tr("OK"),tr("Cancel")});
    1563             setButtonIcons(new String[] {"ok","cancel"});
     1429        AddTagsDialog() {
     1430            super(Main.parent, tr("Add value?"), new String[] {tr("OK"), tr("Cancel")});
     1431            setButtonIcons(new String[] {"ok", "cancel"});
    15641432            setCancelButton(2);
    15651433            configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */);
    15661434            final AddTagsDialog addTagsDialog = this;
    1567            
     1435
    15681436            loadOntology();
    15691437            //if the user did not train a model by running the training process
     
    15721440            System.out.println("path for textual: " + TEXTUAL_LIST_PATH);
    15731441            File textualListFile = new File(TEXTUAL_LIST_PATH);
    1574             if(textualListFile.exists()){
     1442            if (textualListFile.exists()) {
    15751443                loadTextualList(textualListFile);
    1576             }
    1577             else{
    1578                 loadDefaultTextualList();
    1579             }
    1580            
     1444            } else {
     1445                loadDefaultTextualList();
     1446            }
     1447
    15811448            //if training process has not been performed, we use two sample SVM models, extracted from the jar
    1582             //File bestModelFile = new File(bestModelPath);
    1583             //File bestModelWithClassesFile = new File(modelWithClassesPath);
    1584 
    1585             JPanel splitPanel = new JPanel(new BorderLayout(10,10));           
    1586             JPanel mainPanel = new JPanel(new GridBagLayout()); //original panel, will be wrapped by the splitPanel                   
    1587             JPanel recommendPanel = new JPanel(new BorderLayout(10,10));   //will contain listPanel, action panel           
    1588             JPanel listPanel = new JPanel(new BorderLayout(10,10)); //class recommend label, recommendation list
     1449
     1450            JPanel splitPanel = new JPanel(new BorderLayout(10, 10));
     1451            JPanel mainPanel = new JPanel(new GridBagLayout()); //original panel, will be wrapped by the splitPanel
     1452            JPanel recommendPanel = new JPanel(new BorderLayout(10, 10));   //will contain listPanel, action panel
     1453            JPanel listPanel = new JPanel(new BorderLayout(10, 10)); //class recommend label, recommendation list
    15891454            JPanel actionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); //model selection buttons or configuration
    1590            
    1591             addAndContinueButton = new javax.swing.JButton("Add and continue");
    1592             modelSettingsButton = new javax.swing.JButton("Model Settings");
    1593             useTagsCheckBox = new javax.swing.JCheckBox("Predict using tags");
    1594             recommendedClassesLabel = new javax.swing.JLabel("Recommended Classes:");           
    1595            
     1455
     1456            addAndContinueButton = new JButton("Add and continue");
     1457            modelSettingsButton = new JButton("Model Settings");
     1458            useTagsCheckBox = new JCheckBox("Predict using tags");
     1459            recommendedClassesLabel = new JLabel("Recommended Classes:");
     1460
    15961461            addAndContinueButton.addActionListener(new java.awt.event.ActionListener() {
    15971462                @Override
    1598                 public void actionPerformed(java.awt.event.ActionEvent evt) {                   
     1463                public void actionPerformed(java.awt.event.ActionEvent evt) {
    15991464                    String selectedClass = categoryList.getSelectedValue();
    16001465                    addAndContinueButtonActionPerformed(evt, selectedClass);
    1601                    
     1466
    16021467                    //reconstruct vector for instance and use the model that was trained with classes here
    1603                    
     1468
    16041469                    List<OsmPrimitive> osmPrimitiveSelection = new ArrayList<>(sel);
    16051470                    OsmPrimitive s;
    16061471
    1607                    
    16081472                    //get a simple selection
    1609                     if(!osmPrimitiveSelection.isEmpty()){
    1610                         s = osmPrimitiveSelection.get(0);                       
    1611                         if(s.getInterestingTags().isEmpty()){
     1473                    if (!osmPrimitiveSelection.isEmpty()) {
     1474                        s = osmPrimitiveSelection.get(0);
     1475                        if (s.getInterestingTags().isEmpty()) {
    16121476                            //load original model
    16131477                            modelWithClasses = false;
    16141478                            loadSVMmodel();
    16151479                            createOSMObject(sel); //create object without class features
    1616                         }
    1617                         else{
     1480                        } else {
    16181481                            //recommend using tags: set the checkbox selected to avoid confusing the user
    16191482                            useTagsCheckBox.setSelected(true);
    1620                            
    1621                             if(useTagsCheckBox.isSelected()){
     1483
     1484                            if (useTagsCheckBox.isSelected()) {
    16221485                                //load model with classes
    16231486                                modelWithClasses = true;
    16241487                                loadSVMmodel();
    1625                                 createOSMObject(sel); //create object including class features                             
    1626                             }
    1627                             else{
     1488                                createOSMObject(sel); //create object including class features
     1489                            } else {
    16281490                                modelWithClasses = false;
    16291491                                loadSVMmodel();
    1630                                 createOSMObject(sel); //create object including class features   
     1492                                createOSMObject(sel); //create object including class features
    16311493                            }
    1632                         }                       
     1494                        }
    16331495                    }
    16341496                }
    16351497            });
    1636            
     1498
    16371499            modelSettingsButton.addActionListener(new java.awt.event.ActionListener() {
    16381500                @Override
    16391501                public void actionPerformed(java.awt.event.ActionEvent evt) {
    1640                     if(modelSettingsDialog == null){
     1502                    if (modelSettingsDialog == null) {
    16411503                        System.out.println("new modelSettingsDialog");
    1642                         modelSettingsDialog = new ModelSettingsDialog(sel, addTagsDialog); 
    1643                        
    1644                         //modelSettingsDialog.makeVisible(true);
    1645                         //modelSettingsDialog.setVisible(true);
    1646                     }
    1647                     else{
     1504                        modelSettingsDialog = new ModelSettingsDialog(sel, addTagsDialog);
     1505                    } else {
    16481506                        System.out.println("set modelSettingsDialog visible");
    16491507                        modelSettingsDialog.makeVisible(true);
    1650                         //modelSettingsDialog.setVisible(true);
    1651                     }
    1652                 }
    1653             });         
    1654 
    1655             useTagsCheckBox.addActionListener(new java.awt.event.ActionListener() {               
     1508                    }
     1509                }
     1510            });
     1511
     1512            useTagsCheckBox.addActionListener(new java.awt.event.ActionListener() {
    16561513                @Override
    16571514                public void actionPerformed(java.awt.event.ActionEvent evt) {
    16581515                    List<OsmPrimitive> osmPrimitiveSelection = new ArrayList<>(sel);
    16591516                    OsmPrimitive s;
    1660                     if(!osmPrimitiveSelection.isEmpty()){
    1661                         s = osmPrimitiveSelection.get(0);                       
    1662                         if(s.getInterestingTags().isEmpty()){
     1517                    if (!osmPrimitiveSelection.isEmpty()) {
     1518                        s = osmPrimitiveSelection.get(0);
     1519                        if (s.getInterestingTags().isEmpty()) {
    16631520                            //load original model
    16641521                            modelWithClasses = false;
    16651522                            loadSVMmodel();
    16661523                            createOSMObject(sel); //create object without class features
    1667                         }
    1668                         else{
     1524                        } else {
    16691525                            //useTagsCheckBox
    1670                             if(useTagsCheckBox.isSelected()){
     1526                            if (useTagsCheckBox.isSelected()) {
    16711527                                //load model with classes
    16721528                                modelWithClasses = true;
    16731529                                loadSVMmodel();
    1674                                 createOSMObject(sel); //create object including class features                               
    1675                             }
    1676                             else{
     1530                                createOSMObject(sel); //create object including class features
     1531                            } else {
    16771532                                modelWithClasses = false;
    16781533                                loadSVMmodel();
    1679                                 createOSMObject(sel); //create object including class features   
     1534                                createOSMObject(sel); //create object including class features
    16801535                            }
    1681                         }                       
    1682                     }                   
     1536                        }
     1537                    }
    16831538                }
    16841539            });
    1685            
     1540
    16861541            keys = new AutoCompletingComboBox();
    16871542            values = new AutoCompletingComboBox();
    16881543
    16891544            mainPanel.add(new JLabel("<html>"+trn("This will change up to {0} object.",
    1690                 "This will change up to {0} objects.", sel.size(),sel.size())
    1691                 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL));
    1692 
    1693             AutoCompletionManager autocomplete = Main.main.getEditLayer().data.getAutoCompletionManager();
     1545                    "This will change up to {0} objects.", sel.size(), sel.size())
     1546            +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL));
     1547
     1548            AutoCompletionManager autocomplete = Main.getLayerManager().getEditLayer().data.getAutoCompletionManager();
    16941549            List<AutoCompletionListItem> keyList = autocomplete.getKeys();
    16951550
     
    17181573
    17191574            mainPanel.add(keys, GBC.eop().fill());
    1720             mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol());           
    1721  
     1575            mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol());
     1576
    17221577            model = new DefaultListModel<>();
    1723            
    1724             parseTagsMappedToClasses(); 
    1725            
     1578
     1579            parseTagsMappedToClasses();
     1580
    17261581            List<OsmPrimitive> osmPrimitiveSelection = new ArrayList<>(sel);
    17271582            OsmPrimitive s;
    17281583            //get a simple selection
    1729             if(!osmPrimitiveSelection.isEmpty()){
    1730                 s = osmPrimitiveSelection.get(0);     
     1584            if (!osmPrimitiveSelection.isEmpty()) {
     1585                s = osmPrimitiveSelection.get(0);
    17311586                File modelDirectory = new File(MODEL_PATH);
    17321587                String modelWithClassesPath = modelDirectory.getAbsolutePath() + "/model_with_classes";
    1733                 File modelWithClassesFile = new File(modelWithClassesPath); 
    1734                 if(s.getInterestingTags().isEmpty() || !modelWithClassesFile.exists()){
     1588                File modelWithClassesFile = new File(modelWithClassesPath);
     1589                if (s.getInterestingTags().isEmpty() || !modelWithClassesFile.exists()) {
    17351590                    modelWithClasses = false;
    1736                     loadSVMmodel();//load original model
    1737                     createOSMObject(sel); //create object without class features                                   
    1738                 }
    1739                 else{
     1591                    loadSVMmodel(); //load original model
     1592                    createOSMObject(sel); //create object without class features
     1593                } else {
    17401594                    //recommend using tags: set the checkbox selected to avoid confusing the user
    1741                     useTagsCheckBox.setSelected(true);                   
     1595                    useTagsCheckBox.setSelected(true);
    17421596                    modelWithClasses = true;
    1743                     loadSVMmodel();//load model with classes         
    1744                     createOSMObject(sel); //create object including class features                             
    1745                 }                       
    1746             } 
    1747            
     1597                    loadSVMmodel(); //load model with classes
     1598                    createOSMObject(sel); //create object including class features
     1599                }
     1600            }
     1601
    17481602            categoryList = new JList<>(model);
    17491603
    1750             ListSelectionListener listSelectionListener = new ListSelectionListener() {       
     1604            ListSelectionListener listSelectionListener = new ListSelectionListener() {
    17511605                @Override
    17521606                public void valueChanged(ListSelectionEvent listSelectionEvent) {
    1753                     if (!listSelectionEvent.getValueIsAdjusting()) {//This prevents double events
    1754                         //System.out.println("tag selected: " + categoryList.getSelectedValue());
    1755                        
     1607                    if (!listSelectionEvent.getValueIsAdjusting()) { //This prevents double events
     1608
    17561609                        String selectedClass = categoryList.getSelectedValue();
    17571610
    1758                         if(selectedClass != null){ //null check, because the model is cleared after a new recommendation
    1759                                                    //tags become unselected
    1760                             if((selectedClass.indexOf(" ")+1) > 0){
     1611                        if (selectedClass != null) { //null check, because the model is cleared after a new recommendation
     1612                            //tags become unselected
     1613                            if ((selectedClass.indexOf(" ")+1) > 0) {
    17611614                                //add both key + value in tags
    17621615                                String keyTag = selectedClass.substring(0, selectedClass.indexOf(" "));
     
    17641617                                keys.setSelectedItem(keyTag); //adding selected tags to textBoxes
    17651618                                values.setSelectedItem(valueTag);
    1766                             }
    1767                             else{
     1619                            } else {
    17681620                                //value does not have a value, add the key tag only
    17691621                                String keyTag = selectedClass; //test it
     
    17721624                            }
    17731625                        }
    1774                     }                   
     1626                    }
    17751627                }
    17761628            };
    1777            
     1629
    17781630            categoryList.addListSelectionListener(listSelectionListener);
    17791631            categoryList.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));
     
    17981650            }
    17991651
    1800             // Add tag on Shift-Enter
    1801 //            mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    1802 //                        KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK), "addAndContinue");
    1803 //                mainPanel.getActionMap().put("addAndContinue", new AbstractAction() {
    1804 //                    @Override
    1805 //                    public void actionPerformed(ActionEvent e) {
    1806 //                        performTagAdding();
    1807 //                        selectKeysComboBox();
    1808 //                    }
    1809 //                });
    1810 
    18111652            suggestRecentlyAddedTags(mainPanel, recentTagsToShow, focus);
    18121653
     
    18141655            listPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));
    18151656            splitPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED, Color.GRAY, Color.WHITE));
    1816            
     1657
    18171658            listPanel.add(recommendedClassesLabel, BorderLayout.NORTH);
    18181659            listPanel.add(categoryList, BorderLayout.SOUTH);
     
    18201661            actionsPanel.add(modelSettingsButton);
    18211662            actionsPanel.add(useTagsCheckBox);
    1822            
     1663
    18231664            recommendPanel.add(actionsPanel, BorderLayout.WEST);
    18241665            recommendPanel.add(listPanel, BorderLayout.NORTH);
    1825            
     1666
    18261667            splitPanel.add(mainPanel, BorderLayout.WEST);
    18271668            splitPanel.add(recommendPanel, BorderLayout.EAST);
    1828            
     1669
    18291670            setContent(splitPanel, false);
    1830 
    1831             selectKeysComboBox();
    18321671
    18331672            popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) {
     
    18381677            });
    18391678            JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem(
    1840                 new AbstractAction(tr("Remember last used tags after a restart")){
    1841                 @Override
    1842                 public void actionPerformed(ActionEvent e) {
    1843                     boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
    1844                     PROPERTY_REMEMBER_TAGS.put(sel);
    1845                     if (sel) saveTagsIfNeeded();
    1846                 }
    1847             });
     1679                    new AbstractAction(tr("Remember last used tags after a restart")) {
     1680                        @Override
     1681                        public void actionPerformed(ActionEvent e) {
     1682                            boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
     1683                            PROPERTY_REMEMBER_TAGS.put(sel);
     1684                            if (sel) saveTagsIfNeeded();
     1685                        }
     1686                    });
    18481687            rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get());
    18491688            popupMenu.add(rememberLastTags);
    1850 
    1851         }
    1852        
     1689        }
     1690
    18531691        private void addAndContinueButtonActionPerformed(ActionEvent evt, String selectedClass) {
    18541692            performTagAdding();
    1855             selectKeysComboBox();
    1856         }
    1857        
     1693        }
     1694
    18581695        private void selectNumberOfTags() {
    18591696            String s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"));
    1860             if (s!=null) try {
     1697            if (s != null) try {
    18611698                int v = Integer.parseInt(s);
    1862                 if (v>=0 && v<=MAX_LRU_TAGS_NUMBER) {
     1699                if (v >= 0 && v <= MAX_LRU_TAGS_NUMBER) {
    18631700                    PROPERTY_RECENT_TAGS_NUMBER.put(v);
    18641701                    return;
     
    18781715            int count = 1;
    18791716            // We store the maximum number (9) of recent tags to allow dynamic change of number of tags shown in the preferences.
    1880             // This implies to iterate in descending order, as the oldest elements will only be removed after we reach the maximum numbern and not the number of tags to show.
    1881             // However, as Set does not allow to iterate in descending order, we need to copy its elements into a List we can access in reverse order.
     1717            // This implies to iterate in descending order,
     1718            // as the oldest elements will only be removed after we reach the maximum numbern and not the number of tags to show.
     1719            // However, as Set does not allow to iterate in descending order,
     1720            // we need to copy its elements into a List we can access in reverse order.
    18821721            List<Tag> tags = new LinkedList<>(recentTags.keySet());
    18831722            for (int i = tags.size()-1; i >= 0 && count <= tagsToShow; i--, count++) {
    18841723                final Tag t = tags.get(i);
    18851724                // Create action for reusing the tag, with keyboard shortcut Ctrl+(1-5)
    1886                 String actionShortcutKey = "properties:recent:"+count;
    1887                 String actionShortcutShiftKey = "properties:recent:shift:"+count;
    1888                 Shortcut sc = Shortcut.registerShortcut(actionShortcutKey, tr("Choose recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL);
    1889                 final JosmAction action = new JosmAction(actionShortcutKey, null, tr("Use this tag again"), sc, false) {
     1725                String scKey = "properties:recent:"+count;
     1726                String scsKey = "properties:recent:shift:"+count;
     1727                Shortcut sc = Shortcut.registerShortcut(scKey, tr("Choose recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL);
     1728                final JosmAction action = new JosmAction(scKey, null, tr("Use this tag again"), sc, false) {
    18901729                    @Override
    18911730                    public void actionPerformed(ActionEvent e) {
     
    18941733                        focus.focusGained(null);
    18951734                        values.setSelectedItem(t.getValue());
    1896                         selectValuesCombobox();
    18971735                    }
    18981736                };
    1899                 Shortcut scShift = Shortcut.registerShortcut(actionShortcutShiftKey, tr("Apply recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL_SHIFT);
    1900                 final JosmAction actionShift = new JosmAction(actionShortcutShiftKey, null, tr("Use this tag again"), scShift, false) {
     1737                Shortcut scs = Shortcut.registerShortcut(scsKey, tr("Apply recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL_SHIFT);
     1738                final JosmAction actionShift = new JosmAction(scsKey, null, tr("Use this tag again"), scs, false) {
    19011739                    @Override
    19021740                    public void actionPerformed(ActionEvent e) {
    19031741                        action.actionPerformed(null);
    19041742                        performTagAdding();
    1905                         selectKeysComboBox();
    19061743                    }
    19071744                };
     
    19151752                    Map<String, String> map = new HashMap<>();
    19161753                    map.put(t.getKey(), t.getValue());
    1917 //                    for (TaggingPreset tp : TaggingPreset.getMatchingPresets(null, map, false)) {
    1918 //                        icon = tp.getIcon();
    1919 //                        if (icon != null) {
    1920 //                            break;
    1921 //                        }
    1922 //                    }
    19231754                    // If still nothing display an empty icon
    19241755                    if (icon == null) {
     
    19321763                final String color = action.isEnabled() ? "" : "; color:gray";
    19331764                final JLabel tagLabel = new JLabel("<html>"
    1934                     + "<style>td{border:1px solid gray; font-weight:normal"+color+"}</style>"
    1935                     + "<table><tr><td>" + XmlWriter.encode(t.toString(), true) + "</td></tr></table></html>");
     1765                        + "<style>td{border:1px solid gray; font-weight:normal"+color+"}</style>"
     1766                        + "<table><tr><td>" + XmlWriter.encode(t.toString(), true) + "</td></tr></table></html>");
    19361767                if (action.isEnabled()) {
    19371768                    // Register action
    1938                     mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), actionShortcutKey);
    1939                     mainPanel.getActionMap().put(actionShortcutKey, action);
    1940                     mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), actionShortcutShiftKey);
    1941                     mainPanel.getActionMap().put(actionShortcutShiftKey, actionShift);
     1769                    mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), scKey);
     1770                    mainPanel.getActionMap().put(scKey, action);
     1771                    mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scs.getKeyStroke(), scsKey);
     1772                    mainPanel.getActionMap().put(scsKey, actionShift);
    19421773                    // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut)
    19431774                    tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
     
    19481779                            action.actionPerformed(null);
    19491780                            // add tags and close window on double-click
    1950                            
    1951                             if (e.getClickCount()>1) {
     1781
     1782                            if (e.getClickCount() > 1) {
    19521783                                buttonAction(0, null); // emulate OK click and close the dialog
    19531784                            }
     
    19551786                            if (e.isShiftDown()) {
    19561787                                performTagAdding();
    1957                                 selectKeysComboBox();
    19581788                            }
    19591789                        }
     
    20211851            File modelDirectory = new File(MODEL_PATH);
    20221852            File modelFile;
    2023             if(useCombinedModel){
    2024                 if(filesAndWeights.isEmpty()){
     1853            if (useCombinedModel) {
     1854                if (filesAndWeights.isEmpty()) {
    20251855                    System.out.println("No models selected! Loading defaults..");
    2026                     if(modelWithClasses){
     1856                    if (modelWithClasses) {
    20271857                        System.out.println("Using default/last model with classes: " + modelDirectory.getAbsolutePath() + "/model_with_classes");
    20281858                        modelFile = new File(modelDirectory.getAbsolutePath() + "/model_with_classes");
     
    20371867                        modelSVMLabelSize = modelSVM.getLabels().length;
    20381868                        modelSVMLabels = modelSVM.getLabels();
    2039                     }
    2040                     else{
     1869                    } else {
    20411870                        System.out.println("Using default/last model without classes: " + modelDirectory.getAbsolutePath() + "/best_model");
    20421871                        modelFile = new File(modelDirectory.getAbsolutePath() + "/best_model");
     
    20511880                        modelSVMLabelSize = modelSVM.getLabels().length;
    20521881                        modelSVMLabels = modelSVM.getLabels();
    2053                     } 
    2054                 }               
    2055                 if(modelWithClasses){ //check filenames to define if model with classes is selected
     1882                    }
     1883                }
     1884                if (modelWithClasses) { //check filenames to define if model with classes is selected
    20561885                    System.out.println("Using combined model with classes");
    20571886                    useCombinedSVMmodels(sel, true);
    2058                 }
    2059                 else{
     1887                } else {
    20601888                    System.out.println("Using combined model without classes");
    20611889                    useCombinedSVMmodels(sel, false);
    2062                 }               
    2063                                
    2064             }
    2065             else if(useCustomSVMModel){
     1890                }
     1891            } else if (useCustomSVMModel) {
    20661892                System.out.println("custom path: " + customSVMModelPath);
    2067                 File checkExistance = new File(customSVMModelPath);             
    2068                 if(checkExistance.exists() && checkExistance.isFile()){
     1893                File checkExistance = new File(customSVMModelPath);
     1894                if (checkExistance.exists() && checkExistance.isFile()) {
    20691895                    if (modelWithClasses) {
    20701896                        System.out.println("Using custom model with classes: ");
    20711897                        if (customSVMModelPath.endsWith(".0")) {
    2072                             //String customSVMModelPathWithClasses = customSVMModelPath.replace(".0", ".1");
    20731898                            String customSVMModelPathWithClasses = customSVMModelPath.substring(0, customSVMModelPath.length() - 2) + ".1";
    20741899
    20751900                            modelFile = new File(customSVMModelPathWithClasses);
    20761901                            System.out.println(customSVMModelPathWithClasses);
    2077                         }
    2078                         else {
     1902                        } else {
    20791903                            modelFile = new File(customSVMModelPath);
    20801904                        }
     
    20981922                    }
    20991923                    modelSVMLabelSize = modelSVM.getLabels().length;
    2100                     modelSVMLabels = modelSVM.getLabels();                   
    2101 
    2102                 }
    2103                 else {
     1924                    modelSVMLabels = modelSVM.getLabels();
     1925
     1926                } else {
    21041927                    //user chose to use a custom model, but did not provide a path to a model:
    2105                     if(modelWithClasses){
     1928                    if (modelWithClasses) {
    21061929                        System.out.println("Using default/last model with classes");
    21071930                        modelFile = new File(modelDirectory.getAbsolutePath() + "/model_with_classes");
    2108                     }
    2109                     else{
     1931                    } else {
    21101932                        System.out.println("Using default/last model without classes");
    21111933                        modelFile = new File(modelDirectory.getAbsolutePath() + "/best_model");
     
    21211943                    }
    21221944                    modelSVMLabelSize = modelSVM.getLabels().length;
    2123                     modelSVMLabels = modelSVM.getLabels();                   
    2124                    
    2125                 }
    2126             }
    2127             else {
    2128                 if(modelWithClasses){
     1945                    modelSVMLabels = modelSVM.getLabels();
     1946
     1947                }
     1948            } else {
     1949                if (modelWithClasses) {
    21291950                    System.out.println("Using default/last model with classes");
    21301951                    modelFile = new File(modelDirectory.getAbsolutePath() + "/model_with_classes");
    2131                 }
    2132                 else{
     1952                } else {
    21331953                    System.out.println("Using default/last model without classes");
    21341954                    modelFile = new File(modelDirectory.getAbsolutePath() + "/best_model");
    2135                 } 
    2136                
     1955                }
     1956
    21371957                try {
    21381958                    System.out.println("try to load model: " + modelFile.getAbsolutePath());
     
    21441964                }
    21451965                modelSVMLabelSize = modelSVM.getLabels().length;
    2146                 modelSVMLabels = modelSVM.getLabels();               
    2147             }                   
    2148         }
    2149        
    2150         private void useCombinedSVMmodels(Collection<OsmPrimitive> sel, boolean useClassFeatures){
    2151             System.out.println("The system will combine " + filesAndWeights.size() + " SVM models.");           
    2152            
     1966                modelSVMLabels = modelSVM.getLabels();
     1967            }
     1968        }
     1969
     1970        private void useCombinedSVMmodels(Collection<OsmPrimitive> sel, boolean useClassFeatures) {
     1971            System.out.println("The system will combine " + filesAndWeights.size() + " SVM models.");
     1972
    21531973            MathTransform transform = null;
    21541974            GeometryFactory geometryFactory = new GeometryFactory();
     
    21571977            try {
    21581978                transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
    2159                
     1979
    21601980            } catch (FactoryException ex) {
    21611981                Logger.getLogger(OSMRecPluginHelper.class.getName()).log(Level.SEVERE, null, ex);
     
    21651985            List<OsmPrimitive> osmPrimitiveSelection = new ArrayList<>(sel);
    21661986            OsmPrimitive s;
    2167            
     1987
    21681988            //get a simple selection
    2169             if(!osmPrimitiveSelection.isEmpty()){
     1989            if (!osmPrimitiveSelection.isEmpty()) {
    21701990                s = osmPrimitiveSelection.get(0);
    2171             }
    2172             else {
     1991            } else {
    21731992                return;
    21741993            }
    21751994
    21761995            selectedInstance = new OSMWay();
    2177             for(Way selectedWay : s.getDataSet().getSelectedWays()){   
    2178                // System.out.println(nod.getNodes());
     1996            for (Way selectedWay : s.getDataSet().getSelectedWays()) {
    21791997                List<Node> selectedWayNodes = selectedWay.getNodes();
    2180                 for(Node node : selectedWayNodes){
     1998                for (Node node : selectedWayNodes) {
    21811999                    node.getCoor();
    2182                     //System.out.println(node.getCoor());
    2183                     if(node.isLatLonKnown()){
     2000                    if (node.isLatLonKnown()) {
    21842001                        double lat = node.getCoor().lat();
    21852002                        double lon = node.getCoor().lon();
     
    21872004                        Coordinate sourceCoordinate = new Coordinate(lon, lat);
    21882005                        Coordinate targetGeometry = null;
    2189                         try {   
     2006                        try {
    21902007                            targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    21912008                        } catch (MismatchedDimensionException | TransformException ex) {
    21922009                            Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
    2193                         }                   
    2194 
    2195                         Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));   
     2010                        }
     2011
     2012                        Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
    21962013                        selectedInstance.addNodeGeometry(geom);
    21972014                    }
     
    21992016            }
    22002017            Geometry fullGeom = geometryFactory.buildGeometry(selectedInstance.getNodeGeometries());
    2201             if((selectedInstance.getNodeGeometries().size() > 3) &&
    2202                 selectedInstance.getNodeGeometries().get(0).equals(selectedInstance.getNodeGeometries()
    2203                 .get(selectedInstance.getNodeGeometries().size()-1)))
    2204             {
    2205                 //checks if the beginning and ending node are the same and the number of nodes are more than 3.
    2206                 //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.                   
     2018            if ((selectedInstance.getNodeGeometries().size() > 3) &&
     2019                    selectedInstance.getNodeGeometries().get(0).equals(selectedInstance.getNodeGeometries()
     2020                            .get(selectedInstance.getNodeGeometries().size()-1))) {
     2021                //checks if the beginning and ending node are the same and the number of nodes are more than 3.
     2022                //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
    22072023                LinearRing linear = geometryFactory.createLinearRing(fullGeom.getCoordinates());
    22082024                Polygon poly = new Polygon(linear, null, geometryFactory);
     
    22102026
    22112027                System.out.println("\n\npolygon");
    2212             }
    2213             else if (selectedInstance.getNodeGeometries().size()>1){
    2214             //it is an open geometry with more than one nodes, make it linestring
     2028            } else if (selectedInstance.getNodeGeometries().size() > 1) {
     2029                //it is an open geometry with more than one nodes, make it linestring
    22152030                System.out.println("\n\nlinestring");
    2216                 LineString lineString =  geometryFactory.createLineString(fullGeom.getCoordinates());
    2217                 selectedInstance.setGeometry(lineString);               
    2218             }
    2219             else{ //we assume all the rest geometries are points
     2031                LineString lineString = geometryFactory.createLineString(fullGeom.getCoordinates());
     2032                selectedInstance.setGeometry(lineString);
     2033            } else { //we assume all the rest geometries are points
    22202034                System.out.println("\n\npoint");
    22212035                Point point = geometryFactory.createPoint(fullGeom.getCoordinate());
     
    22242038
    22252039            Map<String, String> selectedTags = s.getInterestingTags();
    2226             selectedInstance.setAllTags(selectedTags);             
    2227  
     2040            selectedInstance.setAllTags(selectedTags);
     2041
    22282042            //construct vector
    2229             if(selectedInstance != null){
     2043            if (selectedInstance != null) {
    22302044                int id;
    2231                
     2045
    22322046                OSMClassification classifier = new OSMClassification();
    22332047                classifier.calculateClasses(selectedInstance, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    2234                
    2235                 if(useClassFeatures){
     2048
     2049                if (useClassFeatures) {
    22362050                    ClassFeatures classFeatures = new ClassFeatures();
    22372051                    classFeatures.createClassFeatures(selectedInstance, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    22382052                    id = 1422;
    2239                 }
    2240                 else{
     2053                } else {
    22412054                    id = 1;
    22422055                }
    2243                
     2056
    22442057                GeometryFeatures geometryFeatures = new GeometryFeatures(id);
    22452058                geometryFeatures.createGeometryFeatures(selectedInstance);
    2246                 id=geometryFeatures.getLastID();
     2059                id = geometryFeatures.getLastID();
    22472060                TextualFeatures textualFeatures = new TextualFeatures(id, textualList, languageDetector);
    2248                 textualFeatures.createTextualFeatures(selectedInstance);               
    2249                
     2061                textualFeatures.createTextualFeatures(selectedInstance);
     2062
    22502063                List<FeatureNode> featureNodeList = selectedInstance.getFeatureNodeList();
    2251                 //System.out.println(featureNodeList);
    2252                
     2064
    22532065                FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    22542066
    22552067                int i = 0;
    2256                 for(FeatureNode featureNode : featureNodeList){
    2257 
     2068                for (FeatureNode featureNode : featureNodeList) {
    22582069                    featureNodeArray[i] = featureNode;
    2259                     //System.out.println("i: " + i + " array:" + featureNodeArray[i]);
    22602070                    i++;
    2261 
    2262                 }                   
    2263                 FeatureNode[] testInstance2 = featureNodeArray;                                           
    2264                
     2071                }
     2072                FeatureNode[] testInstance2 = featureNodeArray;
     2073
    22652074                //compute prediction list for every model
    22662075                int[] ranks = new int[10];
    2267                
    2268                 for(int l=0; l<10; l++){
     2076
     2077                for (int l = 0; l < 10; l++) {
    22692078                    ranks[l] = 10-l; //init from 10 to 1
    22702079                }
    2271                
     2080
    22722081                Map<String, Double> scoreMap = new HashMap<>();
    22732082
    22742083                Map<File, Double> alignedFilesAndWeights = getAlignedModels(filesAndWeights);
    2275                
    2276                 for(File modelFile : alignedFilesAndWeights.keySet()){
    2277                    
     2084
     2085                for (File modelFile : alignedFilesAndWeights.keySet()) {
    22782086
    22792087                    try {
    22802088                        modelSVM = Model.load(modelFile);
    2281                         //System.out.println("model loaded: " + modelFile.getAbsolutePath());
    22822089                    } catch (IOException ex) {
    22832090                        Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
    22842091                    }
    22852092                    modelSVMLabelSize = modelSVM.getLabels().length;
    2286                     modelSVMLabels = modelSVM.getLabels();           
    2287                                                                
    2288                
     2093                    modelSVMLabels = modelSVM.getLabels();
     2094
    22892095                    Map<Integer, Integer> mapLabelsToIDs = new HashMap<>();
    2290                     for(int h =0; h < modelSVMLabelSize; h++){
    2291 
     2096                    for (int h = 0; h < modelSVMLabelSize; h++) {
    22922097                        mapLabelsToIDs.put(modelSVMLabels[h], h);
    2293                         //System.out.println(h + "   <->    " + modelSVMLabels[h]);
    2294 
    2295                     }
     2098                    }
    22962099                    double[] scores = new double[modelSVMLabelSize];
    22972100                    Linear.predictValues(modelSVM, testInstance2, scores);
    22982101
    22992102                    Map<Double, Integer> scoresValues = new HashMap<>();
    2300                     for(int h = 0; h < scores.length; h++){
     2103                    for (int h = 0; h < scores.length; h++) {
    23012104                        scoresValues.put(scores[h], h);
    2302                         //System.out.println(h + "   <->    " + scores[h]);
    2303                     }               
     2105                    }
    23042106
    23052107                    Arrays.sort(scores);
    2306                     int predicted1 = modelSVMLabels[scoresValues.get(scores[scores.length-1])]; 
     2108                    int predicted1 = modelSVMLabels[scoresValues.get(scores[scores.length-1])];
    23072109                    int predicted2 = modelSVMLabels[scoresValues.get(scores[scores.length-2])];
    23082110                    int predicted3 = modelSVMLabels[scoresValues.get(scores[scores.length-3])];
    2309                     int predicted4 = modelSVMLabels[scoresValues.get(scores[scores.length-4])]; 
     2111                    int predicted4 = modelSVMLabels[scoresValues.get(scores[scores.length-4])];
    23102112                    int predicted5 = modelSVMLabels[scoresValues.get(scores[scores.length-5])];
    23112113                    int predicted6 = modelSVMLabels[scoresValues.get(scores[scores.length-6])];
    2312                     int predicted7 = modelSVMLabels[scoresValues.get(scores[scores.length-7])]; 
     2114                    int predicted7 = modelSVMLabels[scoresValues.get(scores[scores.length-7])];
    23132115                    int predicted8 = modelSVMLabels[scoresValues.get(scores[scores.length-8])];
    23142116                    int predicted9 = modelSVMLabels[scoresValues.get(scores[scores.length-9])];
    2315                     int predicted10 = modelSVMLabels[scoresValues.get(scores[scores.length-10])];                 
     2117                    int predicted10 = modelSVMLabels[scoresValues.get(scores[scores.length-10])];
    23162118
    23172119                    String[] predictedTags = new String[10];
    2318                     for( Map.Entry<String, Integer> entry : mapperWithIDs.entrySet()){
    2319 
    2320                         if(entry.getValue().equals(predicted1)){
    2321                             //System.out.println("1st predicted class: " +entry.getKey());                     
     2120                    for (Map.Entry<String, Integer> entry : mapperWithIDs.entrySet()) {
     2121
     2122                        if (entry.getValue().equals(predicted1)) {
    23222123                            predictedTags[0] = entry.getKey();
    2323                         }
    2324                         else if(entry.getValue().equals(predicted2)){
     2124                        } else if (entry.getValue().equals(predicted2)) {
    23252125                            predictedTags[1] = entry.getKey();
    2326                             //System.out.println("2nd predicted class: " +entry.getKey());
    2327                         }
    2328                         else if(entry.getValue().equals(predicted3)){
     2126                        } else if (entry.getValue().equals(predicted3)) {
    23292127                            predictedTags[2] = entry.getKey();
    2330                             //System.out.println("3rd predicted class: " +entry.getKey());
    2331                         }
    2332                         else if(entry.getValue().equals(predicted4)){
     2128                        } else if (entry.getValue().equals(predicted4)) {
    23332129                            predictedTags[3] = entry.getKey();
    2334                             //System.out.println("2nd predicted class: " +entry.getKey());
    2335                         }
    2336                         else if(entry.getValue().equals(predicted5)){
     2130                        } else if (entry.getValue().equals(predicted5)) {
    23372131                            predictedTags[4] = entry.getKey();
    2338                             //System.out.println("3rd predicted class: " +entry.getKey());
    2339                         }                   
    2340                         else if(entry.getValue().equals(predicted6)){
     2132                        } else if (entry.getValue().equals(predicted6)) {
    23412133                            predictedTags[5] = entry.getKey();
    2342                             //System.out.println("2nd predicted class: " +entry.getKey());
    2343                         }
    2344                         else if(entry.getValue().equals(predicted7)){
     2134                        } else if (entry.getValue().equals(predicted7)) {
    23452135                            predictedTags[6] = entry.getKey();
    2346                             //System.out.println("3rd predicted class: " +entry.getKey());
    2347                         }
    2348                         else if(entry.getValue().equals(predicted8)){
     2136                        } else if (entry.getValue().equals(predicted8)) {
    23492137                            predictedTags[7] = entry.getKey();
    2350                             //System.out.println("2nd predicted class: " +entry.getKey());
    2351                         }
    2352                         else if(entry.getValue().equals(predicted9)){
     2138                        } else if (entry.getValue().equals(predicted9)) {
    23532139                            predictedTags[8] = entry.getKey();
    2354                             //System.out.println("3rd predicted class: " +entry.getKey());
    2355                         }     
    2356                         else if(entry.getValue().equals(predicted10)){
     2140                        } else if (entry.getValue().equals(predicted10)) {
    23572141                            predictedTags[9] = entry.getKey();
    2358                             //System.out.println("3rd predicted class: " +entry.getKey());
    2359                         }                     
     2142                        }
    23602143                    }
    23612144                    //clearing model, to add the new computed classes in jlist
    23622145                    model.clear();
    2363                     for(Map.Entry<String, String> tag : mappings.entrySet()){
    2364 
    2365                         for(int k=0; k<10; k++){
    2366                             if(tag.getValue().equals(predictedTags[k])){
     2146                    for (Map.Entry<String, String> tag : mappings.entrySet()) {
     2147
     2148                        for (int k = 0; k < 10; k++) {
     2149                            if (tag.getValue().equals(predictedTags[k])) {
    23672150                                predictedTags[k] = tag.getKey();
    23682151                                model.addElement(tag.getKey());
     
    23712154                    }
    23722155                    System.out.println("combined, predicted classes: " + Arrays.toString(predictedTags));
    2373                    
    2374                     for(int r = 0; r<ranks.length; r++){
     2156
     2157                    for (int r = 0; r < ranks.length; r++) {
    23752158                        String predictedTag = predictedTags[r];
    23762159                        Double currentWeight = alignedFilesAndWeights.get(modelFile);
    23772160                        double finalRank = ranks[r]*currentWeight;
    2378                         //String roundedWeight = new DecimalFormat("##.###").format(finalRank);
    2379                         //double finalRounded = Double.parseDouble(roundedWeight);
    2380                         //System.out.println("rank: " + ranks[r] + ", weight: " + currentWeight
    2381                                // + ", final rank: " + finalRounded + " " + predictedTags[r]);
    2382                        
    2383                         if(scoreMap.containsKey(predictedTag)){
     2161
     2162                        if (scoreMap.containsKey(predictedTag)) {
    23842163                            Double scoreToAdd = scoreMap.get(predictedTag);
    23852164                            scoreMap.put(predictedTag, finalRank+scoreToAdd);
    2386                         }
    2387                         else{
     2165                        } else {
    23882166                            scoreMap.put(predictedTag, finalRank);
    2389                         }                     
     2167                        }
    23902168                        //add final weight - predicted tag
    2391                     }                   
    2392                 } //files iter 
     2169                    }
     2170                } //files iter
    23932171                model.clear();
    23942172                List<Double> scoresList = new ArrayList<>(scoreMap.values());
    2395                 Collections.sort(scoresList ,Collections.reverseOrder());
    2396                
    2397                 for(Double sco : scoresList){
    2398                     if(model.size()>9){
     2173                Collections.sort(scoresList, Collections.reverseOrder());
     2174
     2175                for (Double sco : scoresList) {
     2176                    if (model.size() > 9) {
    23992177                        break;
    24002178                    }
    2401                     for(Map.Entry<String, Double> scoreEntry : scoreMap.entrySet()){
    2402                    
    2403                         if(scoreEntry.getValue().equals(sco)){
    2404                             //model.addElement(scoreEntry.toString()); //displaying score                           
     2179                    for (Map.Entry<String, Double> scoreEntry : scoreMap.entrySet()) {
     2180                        if (scoreEntry.getValue().equals(sco)) {
    24052181                            model.addElement(scoreEntry.getKey());
    24062182                        }
    24072183                    }
    24082184                }
    2409                 //System.out.println("final list:" + scoreMap);
    2410             }           
     2185            }
    24112186        }
    24122187
    24132188        private void createOSMObject(Collection<OsmPrimitive> sel) {
    2414                        
     2189
    24152190            MathTransform transform = null;
    24162191            GeometryFactory geometryFactory = new GeometryFactory();
     
    24192194            try {
    24202195                transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
    2421                
     2196
    24222197            } catch (FactoryException ex) {
    24232198                Logger.getLogger(OSMRecPluginHelper.class.getName()).log(Level.SEVERE, null, ex);
    24242199            }
    2425            
     2200
    24262201            //fire an error to the user if he has multiple selection from map
    2427            
     2202
    24282203            //we consider simple (one instance) selection, so we get the first of the sel list
    2429             //int singleSelectionCount = 0;
    2430             //Collection<OsmPrimitive> paa = Main.main.getInProgressSelection();
    2431            
     2204
    24322205            OSMWay selectedInstance;
    24332206            List<OsmPrimitive> osmPrimitiveSelection = new ArrayList<>(sel);
    24342207            OsmPrimitive s;
    2435            
     2208
    24362209            //get a simple selection
    2437             if(!osmPrimitiveSelection.isEmpty()){
     2210            if (!osmPrimitiveSelection.isEmpty()) {
    24382211                s = osmPrimitiveSelection.get(0);
    2439             }
    2440             else {
     2212            } else {
    24412213                return;
    24422214            }
    24432215
    24442216            selectedInstance = new OSMWay();
    2445             for(Way selectedWay : s.getDataSet().getSelectedWays()){   
    2446                // System.out.println(nod.getNodes());
     2217            for (Way selectedWay : s.getDataSet().getSelectedWays()) {
    24472218                List<Node> selectedWayNodes = selectedWay.getNodes();
    2448                 for(Node node : selectedWayNodes){
     2219                for (Node node : selectedWayNodes) {
    24492220                    node.getCoor();
    2450                     //System.out.println(node.getCoor());
    2451                     if(node.isLatLonKnown()){
    2452                         //LatLon coord = nod.getCoor();
     2221                    if (node.isLatLonKnown()) {
    24532222                        double lat = node.getCoor().lat();
    24542223                        double lon = node.getCoor().lon();
     
    24562225                        Coordinate sourceCoordinate = new Coordinate(lon, lat);
    24572226                        Coordinate targetGeometry = null;
    2458                         try {   
     2227                        try {
    24592228                            targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    24602229                        } catch (MismatchedDimensionException | TransformException ex) {
    24612230                            Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
    2462                         }                   
    2463 
    2464                         Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));   
     2231                        }
     2232
     2233                        Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
    24652234                        selectedInstance.addNodeGeometry(geom);
    24662235                    }
     
    24682237            }
    24692238            Geometry fullGeom = geometryFactory.buildGeometry(selectedInstance.getNodeGeometries());
    2470             //System.out.println("full geom: " + fullGeom.toText());
    24712239
    24722240            System.out.println("number of nodes: " + selectedInstance.getNodeGeometries().size());
    24732241
    2474             if((selectedInstance.getNodeGeometries().size() > 3) &&
    2475                 selectedInstance.getNodeGeometries().get(0).equals(selectedInstance.getNodeGeometries()
    2476                 .get(selectedInstance.getNodeGeometries().size()-1)))
    2477             {
    2478                 //checks if the beginning and ending node are the same and the number of nodes are more than 3.
    2479                 //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.                   
     2242            if ((selectedInstance.getNodeGeometries().size() > 3) &&
     2243                    selectedInstance.getNodeGeometries().get(0).equals(selectedInstance.getNodeGeometries()
     2244                            .get(selectedInstance.getNodeGeometries().size()-1))) {
     2245                //checks if the beginning and ending node are the same and the number of nodes are more than 3.
     2246                //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
    24802247                LinearRing linear = geometryFactory.createLinearRing(fullGeom.getCoordinates());
    24812248                Polygon poly = new Polygon(linear, null, geometryFactory);
     
    24832250
    24842251                System.out.println("\n\npolygon");
    2485             }
    2486             else if (selectedInstance.getNodeGeometries().size()>1){
    2487             //it is an open geometry with more than one nodes, make it linestring
     2252            } else if (selectedInstance.getNodeGeometries().size() > 1) {
     2253                //it is an open geometry with more than one nodes, make it linestring
    24882254                System.out.println("\n\nlinestring");
    2489                 LineString lineString =  geometryFactory.createLineString(fullGeom.getCoordinates());
    2490                 selectedInstance.setGeometry(lineString);               
    2491             }
    2492             else{ //we assume all the rest geometries are points
     2255                LineString lineString = geometryFactory.createLineString(fullGeom.getCoordinates());
     2256                selectedInstance.setGeometry(lineString);
     2257            } else { //we assume all the rest geometries are points
    24932258                System.out.println("\n\npoint");
    24942259                Point point = geometryFactory.createPoint(fullGeom.getCoordinate());
     
    24962261            }
    24972262
    2498             //System.out.println(tt + "  " + s.getDataSet().getNodes());
    2499             //Collection<Node> nodes = s.getDataSet().getNodes();
    2500             //nodeTmp.setGeometry(geom);
    2501 
    25022263            Map<String, String> selectedTags = s.getInterestingTags();
    25032264            selectedInstance.setAllTags(selectedTags);
    2504             //System.out.println("selected instance interested tags: " + s.getInterestingTags());
    2505             //selectedInstance.setTagKeyValue(selectedTags);
    2506 
    2507             //singleSelectionCount++;               
    2508  
     2265
    25092266            //construct vector here
    2510             if(selectedInstance != null){
     2267            if (selectedInstance != null) {
    25112268                int id;
    2512                 if(mappings == null){
    2513                    System.out.println("null mappings ERROR");
    2514                 }
    2515                
     2269                if (mappings == null) {
     2270                    System.out.println("null mappings ERROR");
     2271                }
     2272
    25162273                OSMClassification classifier = new OSMClassification();
    25172274                classifier.calculateClasses(selectedInstance, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    2518                
    2519                 if(modelWithClasses){
     2275
     2276                if (modelWithClasses) {
    25202277                    ClassFeatures classFeatures = new ClassFeatures();
    25212278                    classFeatures.createClassFeatures(selectedInstance, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    25222279                    id = 1422;
    2523                 }
    2524                 else{
     2280                } else {
    25252281                    id = 1;
    25262282                }
    2527                
     2283
    25282284                GeometryFeatures geometryFeatures = new GeometryFeatures(id);
    25292285                geometryFeatures.createGeometryFeatures(selectedInstance);
    2530                 id=geometryFeatures.getLastID();
     2286                id = geometryFeatures.getLastID();
    25312287                TextualFeatures textualFeatures = new TextualFeatures(id, textualList, languageDetector);
    2532                 textualFeatures.createTextualFeatures(selectedInstance);               
    2533                
     2288                textualFeatures.createTextualFeatures(selectedInstance);
     2289
    25342290                List<FeatureNode> featureNodeList = selectedInstance.getFeatureNodeList();
    25352291                System.out.println(featureNodeList);
    2536                
     2292
    25372293                FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    25382294
    25392295                int i = 0;
    2540                 for(FeatureNode featureNode : featureNodeList){
    2541 
     2296                for (FeatureNode featureNode : featureNodeList) {
    25422297                    featureNodeArray[i] = featureNode;
    2543                     //System.out.println("i: " + i + " array:" + featureNodeArray[i]);
    25442298                    i++;
    2545 
    2546                 }                   
    2547                 FeatureNode[] testInstance2 = featureNodeArray;                                           
    2548                
     2299                }
     2300                FeatureNode[] testInstance2 = featureNodeArray;
     2301
    25492302                Map<Integer, Integer> mapLabelsToIDs = new HashMap<>();
    2550                 for(int h =0; h < modelSVMLabelSize; h++){
    2551                    
     2303                for (int h = 0; h < modelSVMLabelSize; h++) {
    25522304                    mapLabelsToIDs.put(modelSVMLabels[h], h);
    2553                     //System.out.println(h + "   <->    " + modelSVMLabels[h]);
    2554                    
    2555                 }               
    2556                
     2305                }
     2306
    25572307                double[] scores = new double[modelSVMLabelSize];
    25582308                Linear.predictValues(modelSVM, testInstance2, scores);
    2559                        
     2309
    25602310                Map<Double, Integer> scoresValues = new HashMap<>();
    2561                 for(int h = 0; h < scores.length; h++){
     2311                for (int h = 0; h < scores.length; h++) {
    25622312                    scoresValues.put(scores[h], h);
    2563                     //System.out.println(h + "   <->    " + scores[h]);
    25642313                }
    25652314
    25662315                Arrays.sort(scores);
    2567                
     2316
    25682317                int[] preds = new int[RECOMMENDATIONS_SIZE];
    2569                 for(int p=0; p < RECOMMENDATIONS_SIZE; p++){
     2318                for (int p = 0; p < RECOMMENDATIONS_SIZE; p++) {
    25702319                    preds[p] = modelSVMLabels[scoresValues.get(scores[scores.length-(p+1)])];
    25712320                }
    25722321                String[] predictedTags2 = new String[RECOMMENDATIONS_SIZE];
    2573                
    2574                 for(int p=0; p<RECOMMENDATIONS_SIZE; p++){
    2575                     if(idsWithMappings.containsKey(preds[p])){
     2322
     2323                for (int p = 0; p < RECOMMENDATIONS_SIZE; p++) {
     2324                    if (idsWithMappings.containsKey(preds[p])) {
    25762325                        predictedTags2[p] = idsWithMappings.get(preds[p]);
    25772326                    }
    2578 
    2579                 }               
    2580                
     2327                }
     2328
    25812329                //clearing model, to add the new computed classes in jlist
    25822330                model.clear();
    2583                 for(Map.Entry<String, String> tag : mappings.entrySet()){
    2584                    
    2585                     for(int k=0; k<10; k++){
    2586                         if(tag.getValue().equals(predictedTags2[k])){
     2331                for (Map.Entry<String, String> tag : mappings.entrySet()) {
     2332                    for (int k = 0; k < 10; k++) {
     2333                        if (tag.getValue().equals(predictedTags2[k])) {
    25872334                            predictedTags2[k] = tag.getKey();
    25882335                            model.addElement(tag.getKey());
     
    25902337                    }
    25912338                }
    2592                 //System.out.println("createdOSM object, predicted classes: " + Arrays.toString(predictedTags));
    25932339                System.out.println("Optimized - create OSMObject, predicted classes: " + Arrays.toString(predictedTags2));
    25942340            }
     
    25992345            InputStream tagsToClassesMapping = TrainWorker.class.getResourceAsStream("/resources/files/Map");
    26002346            Mapper mapper = new Mapper();
    2601             try {   
     2347            try {
    26022348                mapper.parseFile(tagsToClassesMapping);
    26032349
     
    26062352            }
    26072353            mappings = mapper.getMappings();
    2608             mapperWithIDs = mapper.getMappingsWithIDs(); 
     2354            mapperWithIDs = mapper.getMappingsWithIDs();
    26092355            idsWithMappings = mapper.getIDsWithMappings();
    2610             //System.out.println("mappings " + mappings);
    2611             //System.out.println("mapperWithIDs " + mapperWithIDs);
    26122356        }
    26132357
    26142358        private void loadTextualList(File textualListFile) {
    2615          
     2359
    26162360            Scanner input = null;
    2617            
     2361
    26182362            try {
    26192363                input = new Scanner(textualListFile);
    2620             }
    2621             catch (FileNotFoundException ex) {
    2622                 //Logger.getLogger(Statistics.class.getName()).log(Level.SEVERE, null, ex);
    2623             }
    2624             while(input.hasNext()) {
     2364            } catch (FileNotFoundException ex) {
     2365                Main.warn(ex);
     2366            }
     2367            while (input.hasNext()) {
    26252368                String nextLine = input.nextLine();
    26262369                textualList.add(nextLine);
    26272370            }
    2628             System.out.println("Textual List parsed from file successfully." + textualList); 
     2371            System.out.println("Textual List parsed from file successfully." + textualList);
    26292372        }
    26302373
     
    26472390        private Map<File, Double> getAlignedModels(Map<File, Double> filesAndWeights) {
    26482391            Map<File, Double> alignedFilesAndWeights = new HashMap<>();
    2649             if(modelWithClasses){
    2650                 for(Entry<File, Double> entry : filesAndWeights.entrySet()){
     2392            if (modelWithClasses) {
     2393                for (Entry<File, Double> entry : filesAndWeights.entrySet()) {
    26512394                    String absolutePath = entry.getKey().getAbsolutePath();
    2652                     if(absolutePath.endsWith(".0")){
     2395                    if (absolutePath.endsWith(".0")) {
    26532396                        String newPath = absolutePath.substring(0, absolutePath.length()-2) + ".1";
    26542397                        File alignedFile = new File(newPath);
    2655                         if(alignedFile.exists()){
     2398                        if (alignedFile.exists()) {
    26562399                            alignedFilesAndWeights.put(alignedFile, entry.getValue());
    2657                         }                       
    2658                     }                   
    2659                     else{
     2400                        }
     2401                    } else {
    26602402                        alignedFilesAndWeights.put(entry.getKey(), entry.getValue());
    2661                     }                   
    2662                 }
    2663             }
    2664             else{
    2665                 for(Entry<File, Double> entry : filesAndWeights.entrySet()){
     2403                    }
     2404                }
     2405            } else {
     2406                for (Entry<File, Double> entry : filesAndWeights.entrySet()) {
    26662407                    String absolutePath = entry.getKey().getAbsolutePath();
    2667                     if(absolutePath.endsWith(".1")){
     2408                    if (absolutePath.endsWith(".1")) {
    26682409                        String newPath = absolutePath.substring(0, absolutePath.length()-2) + ".0";
    26692410                        File alignedFile = new File(newPath);
    2670                         if(alignedFile.exists()){
     2411                        if (alignedFile.exists()) {
    26712412                            alignedFilesAndWeights.put(alignedFile, entry.getValue());
    2672                         }                       
    2673                     }
    2674                     else{
     2413                        }
     2414                    } else {
    26752415                        alignedFilesAndWeights.put(entry.getKey(), entry.getValue());
    2676                     }                   
    2677                 }               
     2416                    }
     2417                }
    26782418            }
    26792419            return alignedFilesAndWeights;
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecToggleDialog.java

    r31697 r32404  
    1 
     1// License: GPL. For details, see LICENSE file.
    22package org.openstreetmap.josm.plugins.osmrec;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    35
    46import java.awt.GridBagLayout;
     
    1921import java.util.Set;
    2022import java.util.TreeMap;
     23
    2124import javax.swing.JLabel;
    2225import javax.swing.JPanel;
     
    4144import org.openstreetmap.josm.gui.SideButton;
    4245import org.openstreetmap.josm.gui.dialogs.ToggleDialog;
    43 import static org.openstreetmap.josm.tools.I18n.tr;
    44 import org.openstreetmap.josm.tools.Predicates;
     46import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
    4547import org.openstreetmap.josm.tools.Shortcut;
    46 import org.openstreetmap.josm.tools.Utils;
    4748
    4849/**
    4950 * This class is a modification of the PropertiesDialog for the OSMRec.
    50  * 
    51  * 
     51 *
     52 *
    5253 * This dialog displays the tags of the current selected primitives.
    5354 *
     
    101102    private final AddAction addAction = new AddAction();
    102103    private final EditActionTrain editAction = new EditActionTrain();
    103 //    private final DeleteAction deleteAction = new DeleteAction();
    104 //    private final JosmAction[] josmActions = new JosmAction[]{addAction, editAction, deleteAction};
     104    //    private final DeleteAction deleteAction = new DeleteAction();
     105    //    private final JosmAction[] josmActions = new JosmAction[]{addAction, editAction, deleteAction};
    105106
    106107    /**
     
    143144        membershipTable.addMouseListener(mouseClickWatch);
    144145        scrollPane.addMouseListener(mouseClickWatch);
    145         editHelper.loadTagsIfNeeded(); 
    146 
    147     }
    148 
    149      /**
     146        editHelper.loadTagsIfNeeded();
     147
     148    }
     149
     150    /**
    150151     * This simply fires up an {@link RelationEditor} for the relation shown; everything else
    151152     * is the editor's business.
     
    154155     */
    155156    private void editMembership(int row) {
    156         Relation relation = (Relation)membershipData.getValueAt(row, 0);
     157        Relation relation = (Relation) membershipData.getValueAt(row, 0);
    157158        Main.map.relationListDialog.selectRelation(relation);
    158159    }
    159160
    160161    private int findRow(TableModel model, Object value) {
    161         for (int i=0; i<model.getRowCount(); i++) {
     162        for (int i = 0; i < model.getRowCount(); i++) {
    162163            if (model.getValueAt(i, 0).equals(value))
    163164                return i;
     
    174175    }
    175176
    176    // </editor-fold>
     177    // </editor-fold>
    177178
    178179    // <editor-fold defaultstate="collapsed" desc="Event listeners methods">
     
    196197        selectedTag = editHelper.getChangedKey(); // select last added or last edited key by default
    197198        if (selectedTag == null && tagTable.getSelectedRowCount() == 1) {
    198             selectedTag = (String)tagData.getValueAt(tagTable.getSelectedRow(), 0);
     199            selectedTag = (String) tagData.getValueAt(tagTable.getSelectedRow(), 0);
    199200        }
    200201        if (membershipTable.getSelectedRowCount() == 1) {
    201             selectedRelation = (Relation)membershipData.getValueAt(membershipTable.getSelectedRow(), 0);
     202            selectedRelation = (Relation) membershipData.getValueAt(membershipTable.getSelectedRow(), 0);
    202203        }
    203204
     
    228229                    Relation r = (Relation) ref;
    229230                    MemberInfo mi = roles.get(r);
    230                     if(mi == null) {
     231                    if (mi == null) {
    231232                        mi = new MemberInfo(newSel);
    232233                    }
     
    248249                int comp = Boolean.valueOf(o1.isDisabledAndHidden()).compareTo(o2.isDisabledAndHidden());
    249250                return comp != 0 ? comp : DefaultNameFormatter.getInstance().getRelationComparator().compare(o1, o2);
    250             }}
    251                 );
     251            } });
    252252
    253253        for (Relation r: sortedRelations) {
     
    261261        boolean hasTags = hasSelection && tagData.getRowCount() > 0;
    262262        boolean hasMemberships = hasSelection && membershipData.getRowCount() > 0;
    263          
     263
    264264        addAction.setEnabled(hasSelection);
    265265        //editAction.setEnabled(hasTags || hasMemberships);
     
    268268        tagTable.getTableHeader().setVisible(hasTags);
    269269        selectSth.setVisible(!hasSelection);
    270        
     270
    271271        int selectedIndex;
    272272        if (selectedTag != null && (selectedIndex = findRow(tagData, selectedTag)) != -1) {
     
    274274        } else if (selectedRelation != null && (selectedIndex = findRow(membershipData, selectedRelation)) != -1) {
    275275            membershipTable.changeSelection(selectedIndex, 0, false, false);
    276         } else if(hasTags) {
     276        } else if (hasTags) {
    277277            tagTable.changeSelection(0, 0, false, false);
    278         } else if(hasMemberships) {
     278        } else if (hasMemberships) {
    279279            membershipTable.changeSelection(0, 0, false, false);
    280280        }
     
    316316    // </editor-fold>
    317317
    318      /**
     318    /**
    319319     * Class that watches for mouse clicks
    320320     * @author imi
     
    330330                    tagTable.clearSelection();
    331331                }
    332             } else if (e.getSource() == tagTable ) {
     332            } else if (e.getSource() == tagTable) {
    333333                // double click, edit or add tag
    334334                int row = tagTable.rowAtPoint(e.getPoint());
     
    338338                } else {
    339339                    editHelper.addTag();
    340                     //btnAdd.requestFocusInWindow();
    341340                }
    342341            } else if (e.getSource() == membershipTable) {
     
    347346            } else {
    348347                editHelper.addTag();
    349                 //btnAdd.requestFocusInWindow();
    350348            }
    351349        }
     
    379377        }
    380378
    381         String getPositionString() {
    382             if (positionString == null) {
    383                 positionString = Utils.getPositionListString(position);
    384                 // if not all objects from the selection are member of this relation
    385                 if (Utils.exists(selection, Predicates.not(Predicates.inCollection(members)))) {
    386                     positionString += ",\u2717";
    387                 }
    388                 members = null;
    389                 position = null;
    390                 selection = null;
    391             }
    392             return Utils.shortenString(positionString, 20);
    393         }
    394 
    395         String getRoleString() {
    396             if (roleString == null) {
    397                 for (RelationMember r : role) {
    398                     if (roleString == null) {
    399                         roleString = r.getRole();
    400                     } else if (!roleString.equals(r.getRole())) {
    401                         roleString = tr("<different>");
    402                         break;
    403                     }
    404                 }
    405             }
    406             return roleString;
    407         }
    408 
    409379        @Override
    410380        public String toString() {
     
    424394            return false;
    425395        }
     396
    426397        @Override
    427398        public Class<?> getColumnClass(int columnIndex) {
     
    443414        public void actionPerformed(ActionEvent e) {
    444415            editHelper.addTag();
    445             btnAdd.requestFocusInWindow();           
     416            btnAdd.requestFocusInWindow();
    446417        }
    447418    }
     
    452423     */
    453424    class EditActionTrain extends JosmAction implements ListSelectionListener {
    454         EditActionTrain() {           
     425        EditActionTrain() {
    455426            super(tr("Train a Model"), /* ICON() */ "dialogs/fix", tr("Start the training engine!"),
    456427                    Shortcut.registerShortcut("properties:edit", tr("Edit Tags"), KeyEvent.VK_S,
    457428                            Shortcut.ALT), false);
    458429            setEnabled(true);
    459             updateEnabledState(); 
     430            updateEnabledState();
    460431        }
    461432
     
    470441                int row = membershipTable.getSelectedRow();
    471442                editHelper.editTag(row, false);
    472                 //editMembership(row);
    473             }
    474             else{
     443            } else {
    475444                editHelper.editTag(1, false);
    476445            }
     
    480449        protected void updateEnabledState() {
    481450            setEnabled(true);
    482 //            setEnabled(
    483 //                    (tagTable != null && tagTable.getSelectedRowCount() == 1)
    484 //                    ^ (membershipTable != null && membershipTable.getSelectedRowCount() == 1)
    485 //                    );           
    486451        }
    487452
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/container/OSMNode.java

    r31106 r32404  
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.container;
    13
    2 package org.openstreetmap.josm.plugins.container;
     4import java.util.HashMap;
     5import java.util.Map;
    36
    47import com.vividsolutions.jts.geom.Geometry;
    5 import java.util.HashMap;
    6 import java.util.Map;
    78
    89/**
     
    1011 * @author imis-nkarag
    1112 */
    12 
    13 public class OSMNode {   
     13public class OSMNode {
    1414
    1515    private String id;
    16     private String lang;
    1716    private String action; //e.g modify
    18     private String visible; 
     17    private String visible;
    1918    private Geometry geometry;
    2019    private String timestamp;
     
    2322    private String version;
    2423    private String changeset;
    25     private final Map<String, String> tags = new HashMap<>(); 
    26    
     24    private final Map<String, String> tags = new HashMap<>();
     25
    2726    //attribute getters
    28     public String getID(){
     27    public String getID() {
    2928        return id;
    3029    }
    31    
    32     public String getlang(){
    33         return lang;
     30
     31    public String getAction() {
     32        return action;
    3433    }
    3534
    36     public String getAction(){
    37         return action;
     35    public String getVisible() {
     36        return visible;
    3837    }
    39    
    40     public String getVisible(){
    41         return visible;
    42     }
    4338
    44     public Geometry getGeometry(){
     39    public Geometry getGeometry() {
    4540        return this.geometry;
    4641    }
    47    
    48     public String getTimestamp(){
     42
     43    public String getTimestamp() {
    4944        return timestamp;
    5045    }
    51    
    52     public String getUid(){
     46
     47    public String getUid() {
    5348        return uid;
    54     }   
    55    
    56     public String getUser(){
     49    }
     50
     51    public String getUser() {
    5752        return user;
    5853    }
    59  
    60     public String getVersion(){
     54
     55    public String getVersion() {
    6156        return version;
    62     }   
     57    }
    6358
    64     public String getChangeset(){
     59    public String getChangeset() {
    6560        return changeset;
    66     }   
    67    
    68     public Map<String,String> getTagKeyValue(){
     61    }
     62
     63    public Map<String, String> getTagKeyValue() {
    6964        return tags;
    70     }     
    71    
     65    }
     66
    7267    //attributes setters
    73     public void setID(String id){
     68    public void setID(String id) {
    7469        this.id = id;
    7570    }
    76    
    77     public void setLang(String lang){
    78         this.lang = lang;
    79     }
    80    
    81     public void setAction(String action){
     71
     72    public void setAction(String action) {
    8273        this.action = action;
    8374    }
    84    
    85     public void setVisible(String visible){
     75
     76    public void setVisible(String visible) {
    8677        this.visible = visible;
    8778    }
    88    
    89     public void setGeometry(Geometry geometry){
     79
     80    public void setGeometry(Geometry geometry) {
    9081        this.geometry = geometry;
    9182    }
    92    
    93     public void setTimestamp(String timestamp){
     83
     84    public void setTimestamp(String timestamp) {
    9485        this.timestamp = timestamp;
    9586    }
    96    
    97     public void setUid(String uid){
     87
     88    public void setUid(String uid) {
    9889        this.uid = uid;
    99     }   
    100    
    101     public void setUser(String user){
     90    }
     91
     92    public void setUser(String user) {
    10293        this.user = user;
    10394    }
    10495
    105     public void setVersion(String version){
     96    public void setVersion(String version) {
    10697        this.version = version;
    107     }   
    108  
    109     public void setChangeset(String changeset){
     98    }
     99
     100    public void setChangeset(String changeset) {
    110101        this.changeset = changeset;
    111     }   
    112    
    113     public void setTagKeyValue(String tagKey, String tagValue){
     102    }
     103
     104    public void setTagKeyValue(String tagKey, String tagValue) {
    114105        this.tags.put(tagKey, tagValue);
    115106    }
    116    
     107
    117108}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/container/OSMRelation.java

    r31106 r32404  
    1 package org.openstreetmap.josm.plugins.container;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.container;
    23
    34import java.io.Serializable;
     
    1011/**
    1112 * Class containing information about the OSM relations.
    12  * 
     13 *
    1314 * @author imis-nkarag
    1415 */
    1516
    16 public class OSMRelation implements Serializable{
    17    
     17public class OSMRelation implements Serializable {
     18
    1819    private String id;
    1920    private Set<Integer> classIDs;
    2021    private final List<String> memberReferences = new ArrayList<>();
    2122    private final Map<String, String> tags = new HashMap<>();
    22    
    23     public String getID(){
     23
     24    public String getID() {
    2425        return id;
    2526    }
    26    
    27     public List<String> getMemberReferences(){
     27
     28    public List<String> getMemberReferences() {
    2829        return memberReferences;
    2930    }
    30    
    31     public Set<Integer> getClassIDs(){
     31
     32    public Set<Integer> getClassIDs() {
    3233        return this.classIDs;
    3334    }
    34    
    35     public Map<String, String> getTagKeyValue(){
     35
     36    public Map<String, String> getTagKeyValue() {
    3637        return tags;
    3738    }
    38    
    39     public void setID(String id){
     39
     40    public void setID(String id) {
    4041        this.id = id;
    4142    }
    42    
    43     public void setClassIDs(Set<Integer> classIDs){
     43
     44    public void setClassIDs(Set<Integer> classIDs) {
    4445        this.classIDs = classIDs;
    45     }   
    46    
    47     public void addMemberReference(String memberReference){
     46    }
     47
     48    public void addMemberReference(String memberReference) {
    4849        memberReferences.add(memberReference);
    49     }   
    50    
    51     public void setTagKeyValue(String tagKey, String tagValue){
     50    }
     51
     52    public void setTagKeyValue(String tagKey, String tagValue) {
    5253        this.tags.put(tagKey, tagValue);
    5354    }
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/container/OSMWay.java

    r32358 r32404  
    1 package org.openstreetmap.josm.plugins.container;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.container;
    23
    34import java.io.Serializable;
     
    1920 * @author imis-nkarag
    2021 */
    21 public class OSMWay implements Serializable{
     22public class OSMWay implements Serializable {
    2223
    2324    private String id;
     
    3031    private Map<String, String> tags = new HashMap<>();
    3132    private Geometry geometry;
    32     private TreeMap<Integer,Double> indexVector = new TreeMap<>();
     33    private TreeMap<Integer, Double> indexVector = new TreeMap<>();
    3334    private ArrayList<FeatureNode> featureNodeList = new ArrayList<>();
    34     //private Map<String, String> tags;
    3535
    3636    //way attributes getters
    37     public String getID(){
     37    public String getID() {
    3838        return id;
    3939    }
    4040
    41     public String getUser(){
     41    public String getUser() {
    4242        return user;
    4343    }
    4444
    45     public List<Geometry> getNodeGeometries(){
     45    public List<Geometry> getNodeGeometries() {
    4646        return nodeGeometries;
    4747    }
    4848
    49     public Coordinate[] getCoordinateList(){
     49    public Coordinate[] getCoordinateList() {
    5050        coordinateList = nodeGeometries.toArray(new Coordinate[0]);
    5151        return coordinateList;
    5252    }
    5353
    54     public Geometry getGeometry(){
     54    public Geometry getGeometry() {
    5555        return geometry;
    5656    }
    5757
    58     public List<String> getNodeReferences(){
     58    public List<String> getNodeReferences() {
    5959        return nodeReferences;
    6060    }
    6161
    62     public int getNumberOfNodes(){
     62    public int getNumberOfNodes() {
    6363        return nodeReferences.size();
    6464    }
    6565
    66     public Map<String, String> getTagKeyValue(){
     66    public Map<String, String> getTagKeyValue() {
    6767        return tags;
    6868    }
    6969
    70     public int getClassID(){
     70    public int getClassID() {
    7171        return classID;
    7272    }
    7373
    74     public Set<Integer> getClassIDs(){
     74    public Set<Integer> getClassIDs() {
    7575        return classIDs;
    7676    }
    7777
    78     public TreeMap<Integer, Double> getIndexVector(){
     78    public TreeMap<Integer, Double> getIndexVector() {
    7979        return indexVector;
    8080    }
    8181
    82     public void setIndexVector(TreeMap<Integer, Double> indexVector){
     82    public void setIndexVector(TreeMap<Integer, Double> indexVector) {
    8383        this.indexVector = indexVector;
    8484    }
    8585
    8686    //way attributes setters
    87     public void setID(String id){
     87    public void setID(String id) {
    8888        this.id = id;
    8989    }
    9090
    91     public void setUser(String user){
     91    public void setUser(String user) {
    9292        this.user = user;
    9393    }
    9494
    95     public void setTagKeyValue(String tagKey, String tagValue){
     95    public void setTagKeyValue(String tagKey, String tagValue) {
    9696        this.tags.put(tagKey, tagValue);
    9797    }
    9898
    99     public void addNodeReference(String nodeReference){
     99    public void addNodeReference(String nodeReference) {
    100100        nodeReferences.add(nodeReference);
    101101    }
    102102
    103     public void addNodeGeometry(Geometry geometry){
     103    public void addNodeGeometry(Geometry geometry) {
    104104        nodeGeometries.add(geometry);
    105105    }
    106106
    107     public void setGeometry(Geometry geometry){
     107    public void setGeometry(Geometry geometry) {
    108108        this.geometry = geometry;
    109109    }
    110110
    111     public void setClassID(int classID){
     111    public void setClassID(int classID) {
    112112        this.classID = classID;
    113113    }
    114114
    115     public void setClassIDs(Set<Integer> classIDs){
     115    public void setClassIDs(Set<Integer> classIDs) {
    116116        this.classIDs = classIDs;
    117117    }
    118118
    119     public void setFeature(FeatureNode featureNode){
     119    public void setFeature(FeatureNode featureNode) {
    120120        this.featureNodeList.add(featureNode);
    121121    }
    122122
    123     public List<FeatureNode> getFeatureNodeList(){
     123    public List<FeatureNode> getFeatureNodeList() {
    124124        return featureNodeList;
    125125    }
    126126
    127     public void setAllTags(Map<String, String> selectedTags){
     127    public void setAllTags(Map<String, String> selectedTags) {
    128128        tags.putAll(selectedTags);
    129129    }
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/core/TrainWorker.java

    r31564 r32404  
    1 package org.openstreetmap.josm.plugins.core;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.core;
    23
    34import static java.util.concurrent.TimeUnit.NANOSECONDS;
    4 import de.bwaldvogel.liblinear.FeatureNode;
    5 import de.bwaldvogel.liblinear.Linear;
    6 import de.bwaldvogel.liblinear.Model;
    7 import de.bwaldvogel.liblinear.Parameter;
    8 import de.bwaldvogel.liblinear.Problem;
    9 import de.bwaldvogel.liblinear.SolverType;
     5
    106import java.awt.event.ActionEvent;
    117import java.awt.event.ActionListener;
     
    2925import java.util.logging.Level;
    3026import java.util.logging.Logger;
     27
    3128import javax.swing.SwingWorker;
    32 import org.openstreetmap.josm.plugins.container.OSMRelation;
    33 import org.openstreetmap.josm.plugins.container.OSMWay;
    34 import org.openstreetmap.josm.plugins.extractor.Analyzer;
    35 import org.openstreetmap.josm.plugins.extractor.LanguageDetector;
    36 import org.openstreetmap.josm.plugins.features.ClassFeatures;
    37 import org.openstreetmap.josm.plugins.features.GeometryFeatures;
    38 import org.openstreetmap.josm.plugins.features.OSMClassification;
    39 import org.openstreetmap.josm.plugins.features.RelationFeatures;
    40 import org.openstreetmap.josm.plugins.features.TextualFeatures;
    41 import org.openstreetmap.josm.plugins.parsers.Mapper;
    42 import org.openstreetmap.josm.plugins.parsers.OSMParser;
    43 import org.openstreetmap.josm.plugins.parsers.Ontology;
    44 import org.openstreetmap.josm.plugins.parsers.TextualStatistics;
     29
     30import org.openstreetmap.josm.plugins.osmrec.container.OSMRelation;
     31import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
     32import org.openstreetmap.josm.plugins.osmrec.extractor.Analyzer;
     33import org.openstreetmap.josm.plugins.osmrec.extractor.LanguageDetector;
     34import org.openstreetmap.josm.plugins.osmrec.features.ClassFeatures;
     35import org.openstreetmap.josm.plugins.osmrec.features.GeometryFeatures;
     36import org.openstreetmap.josm.plugins.osmrec.features.OSMClassification;
     37import org.openstreetmap.josm.plugins.osmrec.features.RelationFeatures;
     38import org.openstreetmap.josm.plugins.osmrec.features.TextualFeatures;
     39import org.openstreetmap.josm.plugins.osmrec.parsers.Mapper;
     40import org.openstreetmap.josm.plugins.osmrec.parsers.OSMParser;
     41import org.openstreetmap.josm.plugins.osmrec.parsers.Ontology;
     42import org.openstreetmap.josm.plugins.osmrec.parsers.TextualStatistics;
     43
     44import de.bwaldvogel.liblinear.FeatureNode;
     45import de.bwaldvogel.liblinear.Linear;
     46import de.bwaldvogel.liblinear.Model;
     47import de.bwaldvogel.liblinear.Parameter;
     48import de.bwaldvogel.liblinear.Problem;
     49import de.bwaldvogel.liblinear.SolverType;
    4550
    4651/**
    4752 * Provides the necessary functionality for cross validating and training of SVM models.
    48  * 
     53 *
    4954 * @author imis-nkarag
    5055 */
    51 
    5256public class TrainWorker extends SwingWorker<Void, Void> implements ActionListener {
    53    
     57
    5458    private final String inputFilePath;
    55     //private final String tagsToClassesFilePath;
    56     private static Map<String,String> mappings;
    57     private static Map<String,Integer> mapperWithIDs;
    58     //private static final String PATH = Paths.get("").toAbsolutePath().toString();
    59    
     59    private static Map<String, String> mappings;
     60    private static Map<String, Integer> mapperWithIDs;
     61
    6062    private static List<OSMWay> wayList;
    6163    private static List<OSMRelation> relationList;
    62    
     64
    6365    private static Map<String, List<String>> indirectClasses;
    6466    private static Map<String, Integer> indirectClassesWithIDs;
    65     //private static List<OntClass> listHierarchy;
    66     private static List<String> namesList;       
    67     //private static Properties osmRecProperties = new Properties();
     67    private static List<String> namesList;
    6868    private int numberOfTrainingInstances;
    6969    private final String modelDirectoryPath;
    70     //private final String textualDirectoryPath;
    7170    private final File modelDirectory;
    7271    private static double score1 = 0;
     
    8584    private final boolean topKIsSelected;
    8685    private String textualListFilePath;
    87    
     86
    8887    private static final boolean USE_CLASS_FEATURES = false;
    8988    private static final boolean USE_RELATION_FEATURES = false;
     
    9291    private static LanguageDetector languageDetector;
    9392    private final String inputFileName;
    94    
    95    
    96    
    97     public TrainWorker(String inputFilePath, boolean validateFlag, double cParameterFromUser,
     93
     94    public TrainWorker(String inputFilePath, boolean validateFlag, double cParameterFromUser,
    9895            int topK, int frequency, boolean topKIsSelected, LanguageDetector languageDetector) {
    99         super();
    10096        TrainWorker.languageDetector = languageDetector;
    101         this.inputFilePath = inputFilePath; 
     97        this.inputFilePath = inputFilePath;
    10298        this.validateFlag = validateFlag;
    10399        this.cParameterFromUser = cParameterFromUser;
     
    105101        this.frequency = frequency;
    106102        this.topKIsSelected = topKIsSelected;
    107         if(System.getProperty("os.name").contains("ux")){
     103        if (System.getProperty("os.name").contains("ux")) {
    108104            inputFileName = inputFilePath.substring(inputFilePath.lastIndexOf("/"));
    109         }
    110         else{
     105        } else {
    111106            inputFileName = inputFilePath.substring(inputFilePath.lastIndexOf("\\"));
    112107        }
    113108        System.out.println("find parent directory, create osmrec dir for models: " + new File(inputFilePath).getParentFile());
    114109        modelDirectoryPath = new File(inputFilePath).getParentFile() + "/OSMRec_models";
    115         //textualDirectoryPath = new File(inputFilePath).getParentFile() + "/OSMRec_models/textualList.txt";
    116        
     110
    117111        modelDirectory = new File(modelDirectoryPath);
    118        
     112
    119113        if (!modelDirectory.exists()) {
    120114            modelDirectory.mkdir();
    121115            System.out.println("model directory created!");
    122         }
    123         else {
     116        } else {
    124117            System.out.println("directory already exists!");
    125         }             
    126     }
    127    
     118        }
     119    }
     120
    128121    @Override
    129     public Void doInBackground() throws Exception {       
     122    public Void doInBackground() throws Exception {
    130123        extractTextualList();
    131124        parseFiles();
    132         if(validateFlag){           
     125        if (validateFlag) {
    133126            validateLoop();
    134127            System.out.println("Training model with the best c: " + bestConfParam);
     
    137130            clearDataset();
    138131            trainModelWithClasses(bestConfParam);
    139            
    140         }
    141         else{
     132        } else {
    142133            clearDataset();
    143134            trainModel(cParameterFromUser);
     
    148139        return null;
    149140    }
    150    
    151     private void extractTextualList(){
     141
     142    private void extractTextualList() {
    152143        System.out.println("Running analysis..");
    153144        //provide top-K
     
    155146        //Keep terms with frequency higher than N
    156147        //Use the remaining terms as training features
    157        
     148
    158149        Analyzer anal = new Analyzer(inputFilePath, languageDetector);
    159150        anal.runAnalysis();
    160         //System.out.println(anal.getFrequencies());
    161         //System.out.println(anal.getTopKMostFrequent(15));
    162         //System.out.println(anal.getWithFrequency(100));       
    163151
    164152        textualListFilePath = modelDirectory.getAbsolutePath()+"/textualList.txt";
    165153        File textualFile = new File(textualListFilePath); //decide path of models
    166         if(textualFile.exists()){
     154        if (textualFile.exists()) {
    167155            textualFile.delete();
    168         }       
     156        }
    169157        try {
    170158            textualFile.createNewFile();
    171159        } catch (IOException ex) {
    172160            Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
    173         }         
    174        
    175         //writeTextualListToFile(textualFilePath, anal.getTopKMostFrequent(15));
     161        }
     162
    176163        List<Map.Entry<String, Integer>> textualList;
    177         if(topKIsSelected){
     164        if (topKIsSelected) {
    178165            textualList = anal.getTopKMostFrequent(topK);
    179             //System.out.println(textualList);
    180         }
    181         else{
     166        } else {
    182167            textualList = anal.getWithFrequency(frequency);
    183             //System.out.println(textualList);
    184168        }
    185169
     
    187171        System.out.println("textual list saved at location:\n" + textualListFilePath);
    188172        //write list to file and let parser do the loading from the names file
    189        
     173
    190174        //method read default list
    191175        //method extract textual list - > the list will be already in memory, so the names parser doesn t have to be called
    192         if(USE_CLASS_FEATURES){
     176        if (USE_CLASS_FEATURES) {
    193177            numberOfFeatures = 1422 + 105 + textualList.size(); //105 is number of geometry features
    194         }
    195         else{         
     178        } else {
    196179            numberOfFeatures = 105 + textualList.size();
    197180        }
    198181    }
    199    
    200    
     182
    201183    private void parseFiles() {
    202        // File tagsToClassesFile = new File(tagsToClassesFilePath);       
    203 
    204         //osmRecProperties.load(Train.class.getResourceAsStream("/resources/properties/osmRec.properties"));
    205184        InputStream tagsToClassesMapping = TrainWorker.class.getResourceAsStream("/resources/files/Map");
    206185
    207186        Mapper mapper = new Mapper();
    208         try {   
     187        try {
    209188            mapper.parseFile(tagsToClassesMapping);
    210189        } catch (FileNotFoundException ex) {
     
    212191        }
    213192        mappings = mapper.getMappings();
    214         mapperWithIDs = mapper.getMappingsWithIDs();
    215         //System.out.println("success. mappings empty? " + mappings.isEmpty());
    216        
     193        mapperWithIDs = mapper.getMappingsWithIDs();
     194
    217195        InputStream ontologyStream = TrainWorker.class.getResourceAsStream("/resources/files/owl.xml");
    218         Ontology ontology = new Ontology(ontologyStream);           
     196        Ontology ontology = new Ontology(ontologyStream);
    219197
    220198        ontology.parseOntology();
     
    222200        indirectClasses = ontology.getIndirectClasses();
    223201        indirectClassesWithIDs = ontology.getIndirectClassesIDs();
    224         //listHierarchy = ontology.getListHierarchy();       
    225 
    226         //InputStream textualFileStream = TrainWorker.class.getResourceAsStream("/resources/files/names");     
    227         InputStream textualFileStream = null; 
     202
     203        InputStream textualFileStream = null;
    228204        try {
    229205            textualFileStream = new FileInputStream(new File(textualListFilePath));
     
    231207            Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
    232208        }
    233        
     209
    234210        readTextualFromDefaultList(textualFileStream);
    235      
    236         OSMParser osmParser = new OSMParser(inputFilePath);     
    237        
     211
     212        OSMParser osmParser = new OSMParser(inputFilePath);
     213
    238214        osmParser.parseDocument();
    239215        relationList = osmParser.getRelationList();
    240216        wayList = osmParser.getWayList();
    241217        numberOfTrainingInstances = osmParser.getWayList().size();
    242         System.out.println("number of instances: " + numberOfTrainingInstances);   
    243         System.out.println("end of parsing files.");
    244        
    245     }
    246 
    247     public void validateLoop(){
    248 //        Double[] confParams = new Double[] {Math.pow(2, -10), Math.pow(2, -5),Math.pow(2, -3),Math.pow(2, -1),
    249 //            Math.pow(2, 0),Math.pow(2, 1),Math.pow(2, 2),Math.pow(2, 3),Math.pow(2, 4),Math.pow(2, 5),Math.pow(2, 6),
    250 //            Math.pow(2, 8),Math.pow(2, 10),Math.pow(2, 12),Math.pow(2, 14),Math.pow(2, 15),Math.pow(2, 16),Math.pow(2, 17)};
    251        
    252         Double[] confParams = new Double[] {Math.pow(2, -3),Math.pow(2, 1),Math.pow(2, -10),Math.pow(2, -10), Math.pow(2, -5),Math.pow(2, -3)};       
    253                
     218        System.out.println("number of instances: " + numberOfTrainingInstances);
     219        System.out.println("end of parsing files.");
     220
     221    }
     222
     223    public void validateLoop() {
     224        Double[] confParams = new Double[] {Math.pow(2, -3), Math.pow(2, 1),
     225                Math.pow(2, -10), Math.pow(2, -10), Math.pow(2, -5), Math.pow(2, -3)};
     226
    254227        double bestC = Math.pow(2, -10);
    255        
    256         for(Double param : confParams){
    257            
    258 //            if(this.isCancelled()){
    259 //                break;
    260 //            }
     228
     229        for (Double param : confParams) {
     230
    261231            foldScore1 = 0;
    262232            foldScore5 = 0;
     
    265235            clearDataset();
    266236            System.out.println("fold1");
    267             //crossValidateFold(0, 3, 3, 4, false, param);
    268237            crossValidateFold(0, 4, 4, 5, false, param); //4-1
    269             setProgress(4*((5*(trainProgress++))/confParams.length));
    270             //System.out.println((5*trainProgress)/confParams.length);
    271            
     238            setProgress(4*((5*(trainProgress++))/confParams.length));
     239
    272240            foldScore1 = foldScore1 + score1;
    273241            foldScore5 = foldScore5 + score5;
     
    275243            clearDataset();
    276244            System.out.println("fold2");
    277             //crossValidateFold(1, 4, 4, 5, false, param);
    278245            crossValidateFold(1, 5, 0, 1, false, param);
    279246            setProgress(4*((5*(trainProgress++))/confParams.length));
    280             //System.out.println((5*trainProgress)/confParams.length);
    281            
     247
    282248            foldScore1 = foldScore1 + score1;
    283249            foldScore5 = foldScore5 + score5;
     
    285251            clearDataset();
    286252            System.out.println("fold3");
    287             //crossValidateFold(2, 5, 0, 1, false, param);
    288253            crossValidateFold(0, 5, 1, 2, true, param);
    289254            setProgress(4*((5*(trainProgress++))/confParams.length));
    290             //System.out.println((5*trainProgress)/confParams.length);
    291            
     255
    292256            foldScore1 = foldScore1 + score1;
    293257            foldScore5 = foldScore5 + score5;
     
    295259            clearDataset();
    296260            System.out.println("fold4");
    297             //crossValidateFold(0, 5, 1, 2, true, param); 
     261            //crossValidateFold(0, 5, 1, 2, true, param);
    298262            crossValidateFold(0, 5, 2, 3, true, param);
    299263            setProgress(4*((5*(trainProgress++))/confParams.length));
    300264            //System.out.println((5*trainProgress)/confParams.length);
    301            
     265
    302266            foldScore1 = foldScore1 + score1;
    303267            foldScore5 = foldScore5 + score5;
     
    305269            clearDataset();
    306270            System.out.println("fold5");
    307             //crossValidateFold(0, 5, 2, 3, true, param);
    308271            crossValidateFold(0, 5, 3, 4, true, param);
    309272            setProgress(4*((5*(trainProgress++))/confParams.length));
    310             //System.out.println((5*trainProgress)/confParams.length);
    311            
     273
    312274            foldScore1 = foldScore1 + score1;
    313275            foldScore5 = foldScore5 + score5;
    314276            foldScore10 = foldScore10 + score10;
    315277            System.out.println("\n\nC=" + param + ", average score 1-5-10: " + foldScore1/5 +" "+ foldScore5/5 + " "+ foldScore10/5);
    316             if(bestScore < foldScore1 ){
     278            if (bestScore < foldScore1) {
    317279                bestScore = foldScore1;
    318280                bestC = param;
    319281            }
    320            
     282
    321283        }
    322284        System.out.println(4*((5*(trainProgress++))/confParams.length));
    323         //setProgress(100);
    324285        bestConfParam = bestC;
    325         System.out.println("best c param= " + bestC + ", score: " + bestScore/5 );
    326     }
    327    
    328     public void crossValidateFold(int a, int b, int c, int d, boolean skip, double param){
     286        System.out.println("best c param= " + bestC + ", score: " + bestScore/5);
     287    }
     288
     289    public void crossValidateFold(int a, int b, int c, int d, boolean skip, double param) {
    329290        System.out.println("Starting cross validation");
    330291        int testSize = wayList.size()/5;
    331292
    332         List<OSMWay> trainList= new ArrayList<>();
    333         for(int g = a*testSize; g<b*testSize; g++){  // 0~~1~~2~~3~~4~~5
    334             if(skip){
    335                 if(g == (c)*testSize){g=(c+1)*testSize;}
    336            
    337             }
    338             trainList.add(wayList.get(g));
    339         } 
     293        List<OSMWay> trainList = new ArrayList<>();
     294        for (int g = a*testSize; g < b*testSize; g++) {  // 0~~1~~2~~3~~4~~5
     295            if (skip) {
     296                if (g == (c)*testSize) {
     297                    g = (c+1)*testSize;
     298                }
     299            }
     300            trainList.add(wayList.get(g));
     301        }
    340302
    341303        int wayListSizeWithoutUnclassified = trainList.size();
    342         int u = 0;
    343304        System.out.println("trainList size: " + wayListSizeWithoutUnclassified);
    344        
     305
    345306        //set classes for each osm instance
    346         int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
    347         int lalala = 0;
    348         for(OSMWay way : trainList){
     307        int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
     308        for (OSMWay way : trainList) {
    349309
    350310            OSMClassification classifyInstances = new OSMClassification();
    351311            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    352312
    353             if(way.getClassIDs().isEmpty()){
     313            if (way.getClassIDs().isEmpty()) {
    354314                wayListSizeWithoutUnclassified -= 1;
    355                 u++;
    356             }
    357             else {
     315            } else {
    358316                sizeToBeAddedToArray = sizeToBeAddedToArray + way.getClassIDs().size()-1;
    359             }               
    360         } 
    361         double C = param;       
     317            }
     318        }
     319        double C = param;
    362320        double eps = 0.001;
    363         double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];//new double[117558];//               
    364         FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures]; //working[3812];
    365         int k =0;   
    366        
    367         for(OSMWay way : trainList){
    368             //adding multiple vectors                     
    369             int id;           
    370             if(USE_CLASS_FEATURES){               
     321        double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];
     322        FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures];
     323        int k = 0;
     324
     325        for (OSMWay way : trainList) {
     326            //adding multiple vectors
     327            int id;
     328            if (USE_CLASS_FEATURES) {
    371329                ClassFeatures class_vector = new ClassFeatures();
    372330                class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    373331                id = 1422;
    374             }
    375             else{
     332            } else {
    376333                id = 1;
    377334            }
     
    382339            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    383340            //id = 1526
    384             if(USE_RELATION_FEATURES){
     341            if (USE_RELATION_FEATURES) {
    385342                RelationFeatures relationFeatures = new RelationFeatures(id);
    386                 relationFeatures.createRelationFeatures(way, relationList);   
     343                relationFeatures.createRelationFeatures(way, relationList);
    387344                id = relationFeatures.getLastID();
    388             }
    389             else {
     345            } else {
    390346                id = geometryFeatures.getLastID();
    391347            }
    392348            //id 1531
    393            
     349
    394350            TextualFeatures textualFeatures;
    395             if(USE_TEXTUAL_FEATURES){
     351            if (USE_TEXTUAL_FEATURES) {
    396352                textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    397353                textualFeatures.createTextualFeatures(way);
    398354            }
    399            
     355
    400356            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
    401357            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    402                        
    403             if(!way.getClassIDs().isEmpty()){
    404                 int i =0;
    405                 for(FeatureNode featureNode : featureNodeList){
     358
     359            if (!way.getClassIDs().isEmpty()) {
     360                int i = 0;
     361                for (FeatureNode featureNode : featureNodeList) {
    406362                    featureNodeArray[i] = featureNode;
    407363                    i++;
    408                 }               
    409                 for(int classID : way.getClassIDs()){
    410                     lalala++;
     364                }
     365                for (int classID : way.getClassIDs()) {
    411366                    trainingSetWithUnknown2[k] = featureNodeArray;
    412367                    GROUPS_ARRAY2[k] = classID;
    413                     k++;                   
    414                 }                               
    415             }           
    416         }
    417        
    418         //Linear.enableDebugOutput();
    419         Problem problem = new Problem(); 
    420         problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;//wayListSizeWithoutUnclassified;//wayList.size();
    421         problem.n = numberOfFeatures; //(geometry 105 + textual        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
     368                    k++;
     369                }
     370            }
     371        }
     372
     373        Problem problem = new Problem();
     374        problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;
     375        problem.n = numberOfFeatures;
     376        //(geometry 105 + textual        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
    422377        problem.x = trainingSetWithUnknown2; // feature nodes
    423378        problem.y = GROUPS_ARRAY2; // target values
    424379        //SolverType solver = SolverType.MCSVM_CS; //Cramer and Singer for multiclass classification - equivalent of SVMlight
    425380        SolverType solver2 = SolverType.getById(2); //2 -- L2-regularized L2-loss support vector classification (primal)
    426  
     381
    427382        Parameter parameter = new Parameter(solver2, C, eps);
    428         //System.out.println("param set ok");
    429         //System.out.println("number of features: " + vc.getNumOfFeatures());       
    430        
     383
    431384        long start = System.nanoTime();
    432385        System.out.println("training...");
    433386        PrintStream original = System.out;
    434387        System.setOut(new PrintStream(new OutputStream() {
    435            @Override
    436            public void write(int arg0) throws IOException {
    437                
    438            }
     388            @Override
     389            public void write(int arg0) throws IOException {
     390
     391            }
    439392        }));
    440          
     393
    441394        Model model = Linear.train(problem, parameter);
    442395        long end = System.nanoTime();
     
    444397        System.setOut(original);
    445398        System.out.println("training process completed in: " + NANOSECONDS.toSeconds(elapsedTime) + " seconds.");
    446         //System.out.println("trained");
    447        
    448         //decide model path and naming and/or way of deleting/creating 1 or more models.
    449         //File inFile = new File(inputFilePath).getParentFile();
    450        
     399
     400        //decide model path and naming and/or way of deleting/creating 1 or more models.
     401
    451402        File modelFile;
    452         if(USE_CLASS_FEATURES){
     403        if (USE_CLASS_FEATURES) {
    453404            modelFile = new File(modelDirectory.getAbsolutePath()+"/model_with_classes_c=" + param);
    454         }
    455         else{
     405        } else {
    456406            modelFile = new File(modelDirectory.getAbsolutePath()+"/model_geometries_textual_c=" + param);
    457407        }
    458  
    459         if(modelFile.exists()){
     408
     409        if (modelFile.exists()) {
    460410            modelFile.delete();
    461         }       
     411        }
    462412        try {
    463             //System.out.println("file created");
    464413            model.save(modelFile);
    465             System.out.println("model saved at: " + modelFile); 
     414            System.out.println("model saved at: " + modelFile);
    466415        } catch (IOException ex) {
    467416            Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
    468417        }
    469        
    470         //end of evaluation training           
    471 
    472        
    473         //test set
    474         List<OSMWay> testList= new ArrayList<>();
    475         for(int g = c*testSize; g<d*testSize; g++){
     418
     419        //end of evaluation training
     420
     421        //test set
     422        List<OSMWay> testList = new ArrayList<>();
     423        for (int g = c*testSize; g < d*testSize; g++) {
    476424            testList.add(wayList.get(g));
    477             //liblinear test                       
     425            //liblinear test
    478426        }
    479427        System.out.println("testList size: " + testList.size());
    480         int succededInstances=0;
    481         int succededInstances5=0;
    482         int succededInstances10=0;
     428        int succededInstances = 0;
     429        int succededInstances5 = 0;
     430        int succededInstances10 = 0;
    483431        try {
    484432            model = Model.load(modelFile);
     
    489437        int[] labels = model.getLabels();
    490438        Map<Integer, Integer> mapLabelsToIDs = new HashMap<>();
    491         for(int h =0; h < model.getLabels().length; h++){
     439        for (int h = 0; h < model.getLabels().length; h++) {
    492440            mapLabelsToIDs.put(labels[h], h);
    493 
    494             //System.out.println(h + "   <->    " + labels[h]);
    495         }
    496        
     441        }
     442
    497443        int wayListSizeWithoutUnclassified2 = testList.size();
    498         for(OSMWay way : testList){
     444        for (OSMWay way : testList) {
    499445
    500446            OSMClassification classifyInstances = new OSMClassification();
    501447            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    502             if(way.getClassIDs().isEmpty()){
    503                 //System.out.println("found unclassified" + way.getClassIDs() + "class: " +way.getClassID());
     448            if (way.getClassIDs().isEmpty()) {
    504449                wayListSizeWithoutUnclassified2 -= 1;
    505                 //u++;
    506             }
    507         }         
    508        
     450            }
     451        }
     452
    509453        FeatureNode[] testInstance2;
    510         for(OSMWay way : testList){
    511            
     454        for (OSMWay way : testList) {
     455
    512456            int id;
    513            
    514             if(USE_CLASS_FEATURES){               
     457
     458            if (USE_CLASS_FEATURES) {
    515459                ClassFeatures class_vector = new ClassFeatures();
    516460                class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    517461                id = 1422;
    518             }
    519             else{
     462            } else {
    520463                id = 1;
    521464            }
    522            
     465
    523466            //pass id also: 1422 if using classes, 1 if not
    524467            GeometryFeatures geometryFeatures = new GeometryFeatures(id);
     
    527470            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    528471            //id = 1526
    529             //System.out.println("id 1526 -> " + geometryFeatures.getLastID());
    530             if(USE_RELATION_FEATURES){
     472            if (USE_RELATION_FEATURES) {
    531473                RelationFeatures relationFeatures = new RelationFeatures(id);
    532                 relationFeatures.createRelationFeatures(way, relationList);       
     474                relationFeatures.createRelationFeatures(way, relationList);
    533475                id = relationFeatures.getLastID();
    534             }
    535             else {
     476            } else {
    536477                id = geometryFeatures.getLastID();
    537                 //System.out.println("geom feat " + id);
    538478            }
    539479            //id 1531
    540             //System.out.println("id 1532 -> " + relationFeatures.getLastID());
    541             if(USE_TEXTUAL_FEATURES){
     480            if (USE_TEXTUAL_FEATURES) {
    542481                TextualFeatures textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    543482                textualFeatures.createTextualFeatures(way);
    544                 //System.out.println("last textual id: " + textualFeatures.getLastID());
    545                 //System.out.println("full:  " + way.getFeatureNodeList());
    546             }
    547             else{
    548                
    549483            }
    550484            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
     
    552486            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    553487
    554             int i =0;
    555             for(FeatureNode featureNode : featureNodeList){
     488            int i = 0;
     489            for (FeatureNode featureNode : featureNodeList) {
    556490                featureNodeArray[i] = featureNode;
    557491                i++;
     
    559493
    560494            testInstance2 = featureNodeArray;
    561             //double prediction = Linear.predict(model, testInstance2);
    562             //System.out.println("test prediction: " + prediction);
    563495            double[] scores = new double[modelLabelSize];
    564496            Linear.predictValues(model, testInstance2, scores);
     
    567499            //iter scores and find 10 max values with their indexes first. then ask those indexes from model.getlabels
    568500            Map<Double, Integer> scoresValues = new HashMap<>();
    569             for(int h = 0; h < scores.length; h++){
    570                 scoresValues.put(scores[h], h);               
     501            for (int h = 0; h < scores.length; h++) {
     502                scoresValues.put(scores[h], h);
    571503                //System.out.println(h + "   <->    " + scores[h]);
    572             }         
     504            }
    573505
    574506            Arrays.sort(scores);
    575             //System.out.println("max value: " + scores[scores.length-1] + " second max: " + scores[scores.length-2]);
    576             //System.out.println("ask this index from labels: " + scoresValues.get(scores[scores.length-1]));
    577             //System.out.println("got from labels: " +  labels[scoresValues.get(scores[scores.length-1])]);
    578             //System.out.println("next prediction: " +  labels[scoresValues.get(scores[scores.length-2])]);
    579             //System.out.println("way labels: " + way.getClassIDs());
    580             //System.out.println("test prediction: " + prediction);
    581             if(way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])])){
    582                 succededInstances++;             
    583             }
    584             if(
    585                    
    586                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
    587                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
    588                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
    589                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
    590                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])])
    591               ){
     507            if (way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])])) {
     508                succededInstances++;
     509            }
     510            if (
     511                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
     512                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
     513                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
     514                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
     515                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])])
     516                    ) {
    592517                succededInstances5++;
    593518            }
    594             if(
    595                    
    596                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
    597                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
    598                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
    599                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
    600                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])]) ||
    601                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-6])]) ||
    602                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-7])]) ||
    603                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-8])]) ||
    604                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-9])]) ||
    605                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-10])])
    606               ){
     519            if (
     520
     521                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
     522                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
     523                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
     524                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
     525                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])]) ||
     526                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-6])]) ||
     527                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-7])]) ||
     528                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-8])]) ||
     529                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-9])]) ||
     530                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-10])])
     531                    ) {
    607532                succededInstances10++;
    608             }
    609             //System.out.println("labels: " + Arrays.toString(model.getLabels()));
    610             //System.out.println("label[0]: " + model.getLabels()[0]);           
    611         }       
    612        
     533            }
     534        }
     535
    613536        System.out.println("Succeeded " + succededInstances + " of " + testList.size() + " total (1 class prediction)");
    614         double precision1 = succededInstances/(double)wayListSizeWithoutUnclassified2;
     537        double precision1 = succededInstances/(double) wayListSizeWithoutUnclassified2;
    615538        score1 = precision1;
    616539        System.out.println(precision1);
    617        
     540
    618541        System.out.println("Succeeded " + succededInstances5 + " of " + testList.size()+ " total (5 class prediction)");
    619         double precision5 = succededInstances5/(double)wayListSizeWithoutUnclassified2;
     542        double precision5 = succededInstances5/(double) wayListSizeWithoutUnclassified2;
    620543        score5 = precision5;
    621544        System.out.println(precision5);
    622        
     545
    623546        System.out.println("Succeeded " + succededInstances10 + " of " + testList.size()+ " total (10 class prediction)");
    624         double precision10 = succededInstances10/(double)wayListSizeWithoutUnclassified2;
     547        double precision10 = succededInstances10/(double) wayListSizeWithoutUnclassified2;
    625548        score10 = precision10;
    626         System.out.println(precision10);               
    627     } 
    628    
    629     private void trainModel(double param){
    630        
     549        System.out.println(precision10);
     550    }
     551
     552    private void trainModel(double param) {
     553
    631554        int wayListSizeWithoutUnclassified = wayList.size();
    632         int u = 0;
    633555        System.out.println("trainList size: " + wayListSizeWithoutUnclassified);
    634        
     556
    635557        //set classes for each osm instance
    636         int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
    637         int lalala = 0;
    638         if(trainProgress>11){
     558        int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
     559        if (trainProgress > 11) {
    639560            setProgress(trainProgress-10);
    640         }
    641         else{
     561        } else {
    642562            setProgress(trainProgress+10);
    643563        }
    644         //System.out.println("starting classify instances");
    645         for(OSMWay way : wayList){
    646             //setProgress(trainProgress++);
     564        for (OSMWay way : wayList) {
    647565            OSMClassification classifyInstances = new OSMClassification();
    648566            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    649567
    650             if(way.getClassIDs().isEmpty()){
     568            if (way.getClassIDs().isEmpty()) {
    651569                wayListSizeWithoutUnclassified -= 1;
    652                 u++;
    653             }
    654             else {
     570            } else {
    655571                sizeToBeAddedToArray = sizeToBeAddedToArray + way.getClassIDs().size()-1;
    656             }               
    657         }
    658         //System.out.println("end classify instances");
    659         double C = param;       
     572            }
     573        }
     574        double C = param;
    660575        double eps = 0.001;
    661         double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];//new double[117558];//               
    662         FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures]; //working[3812];
    663         int k =0;
    664        
    665         //setProgress(trainProgress+5);
    666         for(OSMWay way : wayList){
    667             //adding multiple vectors                     
    668             int id;           
    669             if(USE_CLASS_FEATURES){               
     576        double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];
     577        FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures];
     578        int k = 0;
     579
     580        for (OSMWay way : wayList) {
     581            //adding multiple vectors
     582            int id;
     583            if (USE_CLASS_FEATURES) {
    670584                ClassFeatures class_vector = new ClassFeatures();
    671585                class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    672586                id = 1422;
    673             }
    674             else{
     587            } else {
    675588                id = 1;
    676589            }
     
    681594            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    682595            //id = 1526
    683             if(USE_RELATION_FEATURES){
     596            if (USE_RELATION_FEATURES) {
    684597                RelationFeatures relationFeatures = new RelationFeatures(id);
    685                 relationFeatures.createRelationFeatures(way, relationList);   
     598                relationFeatures.createRelationFeatures(way, relationList);
    686599                id = relationFeatures.getLastID();
    687             }
    688             else {
     600            } else {
    689601                id = geometryFeatures.getLastID();
    690602            }
    691603            //id 1531
    692            
     604
    693605            TextualFeatures textualFeatures;
    694             if(USE_TEXTUAL_FEATURES){
    695                 textualFeatures = new TextualFeatures(id, namesList,languageDetector);
     606            if (USE_TEXTUAL_FEATURES) {
     607                textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    696608                textualFeatures.createTextualFeatures(way);
    697609            }
    698            
     610
    699611            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
    700612            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    701                        
    702             if(!way.getClassIDs().isEmpty()){
    703                 int i =0;
    704                 for(FeatureNode featureNode : featureNodeList){
     613
     614            if (!way.getClassIDs().isEmpty()) {
     615                int i = 0;
     616                for (FeatureNode featureNode : featureNodeList) {
    705617                    featureNodeArray[i] = featureNode;
    706618                    i++;
    707                 }               
    708                 for(int classID : way.getClassIDs()){
    709                     lalala++;
     619                }
     620                for (int classID : way.getClassIDs()) {
    710621                    trainingSetWithUnknown2[k] = featureNodeArray;
    711622                    GROUPS_ARRAY2[k] = classID;
    712                     k++;                   
    713                 }                               
    714             }           
    715         }
    716         //System.out.println("feature construction completed.");
    717         //Linear.enableDebugOutput();
    718         Problem problem = new Problem(); 
    719         problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;//wayListSizeWithoutUnclassified;//wayList.size();
    720         problem.n = numberOfFeatures;//3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
     623                    k++;
     624                }
     625            }
     626        }
     627        Problem problem = new Problem();
     628        problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;
     629        problem.n = numberOfFeatures;
     630        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
    721631        problem.x = trainingSetWithUnknown2; // feature nodes
    722632        problem.y = GROUPS_ARRAY2; // target values
    723         //SolverType solver = SolverType.MCSVM_CS; //Cramer and Singer for multiclass classification - equivalent of SVMlight
    724633        SolverType solver2 = SolverType.getById(2); //2 -- L2-regularized L2-loss support vector classification (primal)
    725  
     634
    726635        Parameter parameter = new Parameter(solver2, C, eps);
    727         //System.out.println("param set ok");
    728         //System.out.println("number of features: " + vc.getNumOfFeatures());       
    729        
     636
    730637        long start = System.nanoTime();
    731638        System.out.println("training...");
    732639        PrintStream original = System.out;
    733640        System.setOut(new PrintStream(new OutputStream() {
    734 
    735            @Override
    736            public void write(int arg0) throws IOException {
    737 
    738            }
    739         }));     
    740        
    741        
     641            @Override
     642            public void write(int arg0) throws IOException {
     643
     644            }
     645        }));
     646
    742647        Model model = Linear.train(problem, parameter);
    743648        long end = System.nanoTime();
     
    745650        System.setOut(original);
    746651        System.out.println("training process completed in: " + NANOSECONDS.toSeconds(elapsedTime) + " seconds.");
    747         //System.out.println("trained");
    748        
    749         //decide model path and naming and/or way of deleting/creating 1 or more models.
    750         //File inFile = new File(inputFilePath).getParentFile();
    751        
     652
     653        //decide model path and naming and/or way of deleting/creating 1 or more models.
     654
    752655        File modelFile = new File(modelDirectory.getAbsolutePath()+"/best_model"); //decide path of models
    753        
     656
    754657        File customModelFile;
    755         if(topKIsSelected){
     658        if (topKIsSelected) {
    756659            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model_c" + param + "_topK" + topK + ".0");
    757         }
    758         else{
     660        } else {
    759661            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model_c" + param + "_maxF" + frequency + ".0");
    760662        }
    761        
    762        
    763         if(modelFile.exists()){
     663
     664
     665        if (modelFile.exists()) {
    764666            modelFile.delete();
    765         }       
    766         if(customModelFile.exists()){
     667        }
     668        if (customModelFile.exists()) {
    767669            customModelFile.delete();
    768         }         
    769        
     670        }
     671
    770672        try {
    771673            //System.out.println("file created");
    772674            model.save(modelFile);
    773675            model.save(customModelFile);
    774             System.out.println("best model saved at: " + modelFile); 
     676            System.out.println("best model saved at: " + modelFile);
    775677            System.out.println("custom model saved at: " + customModelFile);
    776678        } catch (IOException ex) {
    777679            Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
    778         }       
    779     }
    780    
    781     private void trainModelWithClasses(double param){
    782        
     680        }
     681    }
     682
     683    private void trainModelWithClasses(double param) {
     684
    783685        int wayListSizeWithoutUnclassified = wayList.size();
    784         int u = 0;
    785686        System.out.println("trainList size: " + wayListSizeWithoutUnclassified);
    786        
     687
    787688        //set classes for each osm instance
    788         int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
    789         //int lalala = 0;
    790         //setProgress(trainProgress-10);
    791         for(OSMWay way : wayList){
    792             //setProgress(trainProgress++);
     689        int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
     690        for (OSMWay way : wayList) {
    793691            OSMClassification classifyInstances = new OSMClassification();
    794692            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    795693
    796             if(way.getClassIDs().isEmpty()){
     694            if (way.getClassIDs().isEmpty()) {
    797695                wayListSizeWithoutUnclassified -= 1;
    798                 u++;
    799             }
    800             else {
     696            } else {
    801697                sizeToBeAddedToArray = sizeToBeAddedToArray + way.getClassIDs().size()-1;
    802             }               
    803         } 
    804         double C = param;       
     698            }
     699        }
     700        double C = param;
    805701        double eps = 0.001;
    806         double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];//new double[117558];//               
    807         FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures+1422]; //working[3812];
    808         int k =0;
    809        
    810         //setProgress(trainProgress+5);
    811         for(OSMWay way : wayList){
    812             //adding multiple vectors                     
    813             int id;           
    814             //if(USE_CLASS_FEATURES){               
    815                 ClassFeatures class_vector = new ClassFeatures();
    816                 class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    817                 id = 1422;
    818 //            }
    819 //            else{
    820 //                id = 1;
    821 //            }
     702        double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];
     703        FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures+1422];
     704        int k = 0;
     705
     706        for (OSMWay way : wayList) {
     707            //adding multiple vectors
     708            int id;
     709            ClassFeatures class_vector = new ClassFeatures();
     710            class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
     711            id = 1422;
    822712            //pass id also: 1422 if using classes, 1 if not
    823713            GeometryFeatures geometryFeatures = new GeometryFeatures(id);
     
    826716            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    827717            //id = 1526
    828             if(USE_RELATION_FEATURES){
     718            if (USE_RELATION_FEATURES) {
    829719                RelationFeatures relationFeatures = new RelationFeatures(id);
    830                 relationFeatures.createRelationFeatures(way, relationList);   
     720                relationFeatures.createRelationFeatures(way, relationList);
    831721                id = relationFeatures.getLastID();
    832             }
    833             else {
     722            } else {
    834723                id = geometryFeatures.getLastID();
    835724            }
    836725            //id 1531
    837            
     726
    838727            TextualFeatures textualFeatures;
    839             if(USE_TEXTUAL_FEATURES){
    840                 textualFeatures = new TextualFeatures(id, namesList,languageDetector);
     728            if (USE_TEXTUAL_FEATURES) {
     729                textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    841730                textualFeatures.createTextualFeatures(way);
    842731            }
    843            
     732
    844733            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
    845734            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    846                        
    847             if(!way.getClassIDs().isEmpty()){
    848                 int i =0;
    849                 for(FeatureNode featureNode : featureNodeList){
     735
     736            if (!way.getClassIDs().isEmpty()) {
     737                int i = 0;
     738                for (FeatureNode featureNode : featureNodeList) {
    850739                    featureNodeArray[i] = featureNode;
    851740                    i++;
    852                 }               
    853                 for(int classID : way.getClassIDs()){
    854                     //lalala++;
     741                }
     742                for (int classID : way.getClassIDs()) {
    855743                    trainingSetWithUnknown2[k] = featureNodeArray;
    856744                    GROUPS_ARRAY2[k] = classID;
    857                     k++;                   
    858                 }                               
    859             }           
    860         } 
    861        
    862         //Linear.enableDebugOutput();
    863         Problem problem = new Problem(); 
    864         problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;//wayListSizeWithoutUnclassified;//wayList.size();
    865         problem.n = numberOfFeatures+1422;//3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
     745                    k++;
     746                }
     747            }
     748        }
     749
     750        Problem problem = new Problem();
     751        problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;
     752        problem.n = numberOfFeatures+1422;
     753        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
    866754        problem.x = trainingSetWithUnknown2; // feature nodes
    867755        problem.y = GROUPS_ARRAY2; // target values
    868         //SolverType solver = SolverType.MCSVM_CS; //Cramer and Singer for multiclass classification - equivalent of SVMlight
    869756        SolverType solver2 = SolverType.getById(2); //2 -- L2-regularized L2-loss support vector classification (primal)
    870  
     757
    871758        Parameter parameter = new Parameter(solver2, C, eps);
    872         //System.out.println("param set ok");
    873         //System.out.println("number of features: " + vc.getNumOfFeatures());       
    874        
     759
    875760        long start = System.nanoTime();
    876761        System.out.println("training...");
    877762        PrintStream original = System.out;
    878763        System.setOut(new PrintStream(new OutputStream() {
    879 
    880            @Override
    881            public void write(int arg0) throws IOException {
    882 
    883            }
    884         }));     
    885        
    886        
     764            @Override
     765            public void write(int arg0) throws IOException {
     766
     767            }
     768        }));
     769
     770
    887771        Model model = Linear.train(problem, parameter);
    888772        long end = System.nanoTime();
     
    890774        System.setOut(original);
    891775        System.out.println("training process completed in: " + NANOSECONDS.toSeconds(elapsedTime) + " seconds.");
    892         //System.out.println("trained");
    893        
    894         //decide model path and naming and/or way of deleting/creating 1 or more models.
    895         //File inFile = new File(inputFilePath).getParentFile();
    896        
    897         File modelFile = new File(modelDirectory.getAbsolutePath()+"/model_with_classes");
    898        
    899                
     776
     777        //decide model path and naming and/or way of deleting/creating 1 or more models.
     778
     779        File modelFile = new File(modelDirectory.getAbsolutePath()+"/model_with_classes");
     780
     781
    900782        File customModelFile;
    901         if(topKIsSelected){
     783        if (topKIsSelected) {
    902784            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model" + "_c" + param + "_topK" + topK + ".1");
    903         }
    904         else{
     785        } else {
    905786            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model_c" + param + "_maxF" + frequency + ".1");
    906         }               
    907              
    908         if(customModelFile.exists()){
     787        }
     788
     789        if (customModelFile.exists()) {
    909790            customModelFile.delete();
    910         }                 
    911                
    912         if(modelFile.exists()){
     791        }
     792
     793        if (modelFile.exists()) {
    913794            modelFile.delete();
    914         } 
    915    
     795        }
     796
    916797        try {
    917             //System.out.println("file created");
    918798            model.save(modelFile);
    919799            model.save(customModelFile);
    920             System.out.println("model with classes saved at: " + modelFile); 
     800            System.out.println("model with classes saved at: " + modelFile);
    921801            System.out.println("custom model with classes saved at: " + modelFile);
    922802        } catch (IOException ex) {
    923803            Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
    924         } 
    925     }
    926    
    927     private static void clearDataset(){
    928         for(OSMWay way : wayList){
     804        }
     805    }
     806
     807    private static void clearDataset() {
     808        for (OSMWay way : wayList) {
    929809            way.getFeatureNodeList().clear();
    930810        }
    931     } 
    932    
     811    }
     812
    933813    private void readTextualFromDefaultList(InputStream textualFileStream) {
    934                  
     814
    935815        TextualStatistics textualStatistics = new TextualStatistics();
    936816        textualStatistics.parseTextualList(textualFileStream);
    937817        namesList = textualStatistics.getTextualList();
    938  
    939     }
    940    
     818    }
     819
    941820    @Override
    942821    protected void done() {
     
    944823            System.out.println("Training process complete! - > " + get());
    945824            setProgress(100);
    946         }
    947         catch (InterruptedException | ExecutionException ignore) {
     825        } catch (InterruptedException | ExecutionException ignore) {
    948826            System.out.println("Exception: " + ignore);
    949827        }
    950     } 
     828    }
    951829
    952830    @Override
     
    954832        //cancel button, end process after clearing Dataset
    955833    }
    956    
    957    
    958     private static void writeTextualListToFile(String filePath, List<Map.Entry<String, Integer>> textualList) {       
    959         try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"))) {           
    960             for(Map.Entry<String, Integer> entry : textualList){
     834
     835    private static void writeTextualListToFile(String filePath, List<Map.Entry<String, Integer>> textualList) {
     836        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"))) {
     837            for (Map.Entry<String, Integer> entry : textualList) {
    961838                writer.write(entry.getKey());
    962839                writer.newLine();
    963                 //System.out.println(entry.getKey());
    964840            }
    965841        } catch (UnsupportedEncodingException ex) {
     
    969845        } catch (IOException ex) {
    970846            Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex);
    971         }       
     847        }
    972848    }
    973849}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/extractor/Analyzer.java

    r31461 r32404  
    1 package org.openstreetmap.josm.plugins.extractor;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.extractor;
    23
    34import java.io.BufferedReader;
     
    1819import java.util.logging.Level;
    1920import java.util.logging.Logger;
     21
    2022import org.apache.lucene.analysis.de.GermanAnalyzer;
    2123import org.apache.lucene.analysis.el.GreekAnalyzer;
     
    3840
    3941public class Analyzer {
    40    
     42
    4143    private final String osmFilePath;
    4244    private static final HashSet<String> stopWordsList = new HashSet<>(); //add greek list to same file
    4345    private ArrayList<Entry<String, Integer>> frequencies;
    4446    private final LanguageDetector languageDetector;
    45    
    46     public Analyzer(String osmFilePath, LanguageDetector languageDetector){
     47
     48    public Analyzer(String osmFilePath, LanguageDetector languageDetector) {
    4749        this.osmFilePath = osmFilePath;
    4850        this.languageDetector = languageDetector;
    4951    }
    50    
     52
    5153    public void runAnalysis() {
    5254        //textual list
     
    5456        frequenceExtractor.parseDocument();
    5557        Set<Map.Entry<String, Integer>> frequencyEntries = frequenceExtractor.getFrequency().entrySet();
    56        
     58
    5759        //parse stop words
    5860        loadStopWords();
    59        
     61
    6062        //send some samples
    6163        ArrayList<Map.Entry<String, Integer>> normalizedList = new ArrayList<>();
    6264        ArrayList<String> sampleList = new ArrayList<>();
    63         int iters = 0; 
    64         for(Map.Entry<String, Integer> frequencyEntry : frequencyEntries){
    65             if(iters <10){
     65        int iters = 0;
     66        for (Map.Entry<String, Integer> frequencyEntry : frequencyEntries) {
     67            if (iters < 10) {
    6668                sampleList.add(frequencyEntry.getKey());
    6769                iters++;
    6870            }
    6971            //remove parenthesis etc here
    70             if(!stopWordsList.contains(frequencyEntry.getKey())){//stopwords
     72            if (!stopWordsList.contains(frequencyEntry.getKey())) {
    7173                String normalizedName = frequencyEntry.getKey().toLowerCase();
    7274                normalizedName = normalizedName.replaceAll("[-+.^:,?;'{}\"!()\\[\\]]", "");
    7375
    74                 AbstractMap.SimpleEntry<String, Integer> normalizedEntry = new AbstractMap.SimpleEntry<>(normalizedName,frequencyEntry.getValue());                       
    75                 normalizedList.add(normalizedEntry);
     76                normalizedList.add(new AbstractMap.SimpleEntry<>(normalizedName, frequencyEntry.getValue()));
    7677            }
    7778        }
     
    8889        langs.put("fr", 0);
    8990
    90         for(String word : sampleList){
     91        for (String word : sampleList) {
    9192            //System.out.println("to be detected: " + word);
    92             if(!word.isEmpty()){
     93            if (!word.isEmpty()) {
    9394                String lang;
    9495                lang = languageDetector.detect(word);
    9596                switch (lang) {
    96                     case "en":
    97                         //en++;
    98                         langs.put("en", langs.get("en")+1);                       
    99                         break;
    100                     case "el":
    101                         //el++;
    102                         langs.put("el", langs.get("el")+1);
    103                         break;                       
    104                     case "de":
    105                         //de++;
    106                         langs.put("de", langs.get("de")+1);
    107                         break;
    108                     case "es":
    109                         //es++;
    110                         langs.put("es", langs.get("es")+1);
    111                         break;
    112                     case "ru":                       
    113                         //ru++;
    114                         langs.put("ru", langs.get("ru")+1);
    115                         break;
    116                     case "fr":
    117                         //fr++;
    118                         langs.put("fr", langs.get("fr")+1);
    119                         break;                         
    120                     case "zh":
    121                         //zh++;
    122                         langs.put("zh", langs.get("zh")+1);
    123                         break;
    124                     case "tr":
    125                         //tr++;
    126                         langs.put("tr", langs.get("tr")+1);
    127                         break;                         
    128                     case "hi":
    129                         //hi++;
    130                         langs.put("hi", langs.get("hi")+1);
    131                         break;
    132                         //other lang, no support yet
    133                         //System.out.println("found other language, no support yet :(");
    134                     default:
    135                         break;
    136                 }
    137             }
    138         }
    139        
     97                case "en":
     98                    //en++;
     99                    langs.put("en", langs.get("en")+1);
     100                    break;
     101                case "el":
     102                    //el++;
     103                    langs.put("el", langs.get("el")+1);
     104                    break;
     105                case "de":
     106                    //de++;
     107                    langs.put("de", langs.get("de")+1);
     108                    break;
     109                case "es":
     110                    //es++;
     111                    langs.put("es", langs.get("es")+1);
     112                    break;
     113                case "ru":
     114                    //ru++;
     115                    langs.put("ru", langs.get("ru")+1);
     116                    break;
     117                case "fr":
     118                    //fr++;
     119                    langs.put("fr", langs.get("fr")+1);
     120                    break;
     121                case "zh":
     122                    //zh++;
     123                    langs.put("zh", langs.get("zh")+1);
     124                    break;
     125                case "tr":
     126                    //tr++;
     127                    langs.put("tr", langs.get("tr")+1);
     128                    break;
     129                case "hi":
     130                    //hi++;
     131                    langs.put("hi", langs.get("hi")+1);
     132                    break;
     133                    //other lang, no support yet
     134                    //System.out.println("found other language, no support yet :(");
     135                default:
     136                    break;
     137                }
     138            }
     139        }
     140
    140141        int maxLangFreq = langs.get("en");
    141142        String dominantLanguage = "en";
    142         for(Entry<String,Integer> lang : langs.entrySet()){
    143             if(lang.getValue()> maxLangFreq){
     143        for (Entry<String, Integer> lang : langs.entrySet()) {
     144            if (lang.getValue() > maxLangFreq) {
    144145                maxLangFreq = lang.getValue();
    145146                dominantLanguage = lang.getKey();
    146             }         
    147         }
    148        
     147            }
     148        }
     149
    149150        switch (dominantLanguage) {
    150             case "en":
    151                 normalizedList = stemEnglish(normalizedList);
    152                 break;
    153             case "el":
    154                 normalizedList = stemGreek(normalizedList);
    155                 break;
    156             case "de":
    157                 normalizedList = stemGerman(normalizedList);
    158                 break;
    159             case "es":
    160                 normalizedList = stemSpanish(normalizedList);
    161                 break;
    162             case "ru":
    163                 normalizedList = stemRussian(normalizedList);
    164                 break;
    165             case "fr":
    166                 normalizedList = stemFrench(normalizedList);
    167                 break;
    168             case "zh":
    169                 normalizedList = stemChinese(normalizedList);
    170                 break;
    171             case "tr":
    172                 normalizedList = stemTurkish(normalizedList);
    173                 break;
    174             case "hi":
    175                 normalizedList = stemHindi(normalizedList);
    176                 break;
    177             default:
    178                 normalizedList = stemEnglish(normalizedList);
    179                 break;
    180         }
    181 
    182         Collections.sort(normalizedList, new Comparator<Map.Entry<String, Integer>>()
    183         {
     151        case "en":
     152            normalizedList = stemEnglish(normalizedList);
     153            break;
     154        case "el":
     155            normalizedList = stemGreek(normalizedList);
     156            break;
     157        case "de":
     158            normalizedList = stemGerman(normalizedList);
     159            break;
     160        case "es":
     161            normalizedList = stemSpanish(normalizedList);
     162            break;
     163        case "ru":
     164            normalizedList = stemRussian(normalizedList);
     165            break;
     166        case "fr":
     167            normalizedList = stemFrench(normalizedList);
     168            break;
     169        case "zh":
     170            normalizedList = stemChinese(normalizedList);
     171            break;
     172        case "tr":
     173            normalizedList = stemTurkish(normalizedList);
     174            break;
     175        case "hi":
     176            normalizedList = stemHindi(normalizedList);
     177            break;
     178        default:
     179            normalizedList = stemEnglish(normalizedList);
     180            break;
     181        }
     182
     183        Collections.sort(normalizedList, new Comparator<Map.Entry<String, Integer>>() {
    184184            @Override
    185             public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
    186             {
    187                 return (o2.getValue()).compareTo( o1.getValue() );
    188             }
    189         } );       
     185            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
     186                return (o2.getValue()).compareTo(o1.getValue());
     187            }
     188        });
    190189        setFrequencies(normalizedList);
    191190    }
    192    
     191
    193192    private static ArrayList<Map.Entry<String, Integer>> stemGreek(List<Map.Entry<String, Integer>> normalizedList) {
    194193        org.apache.lucene.analysis.Analyzer greekAnalyzer = new GreekAnalyzer(Version.LUCENE_36);
    195194        QueryParser greekParser = new QueryParser(Version.LUCENE_36, "", greekAnalyzer);
    196195        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    197         for(Map.Entry<String, Integer> entry : normalizedList){
    198             if(!entry.getKey().isEmpty()){
    199                 try {
    200                     //System.out.println("result: " + greekParser.parse(entry.getKey())); 
     196        for (Map.Entry<String, Integer> entry : normalizedList) {
     197            if (!entry.getKey().isEmpty()) {
     198                try {
     199                    //System.out.println("result: " + greekParser.parse(entry.getKey()));
    201200                    String stemmedWord = greekParser.parse(entry.getKey()).toString();
    202201                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    203                     if(!stemmedWord.equals("")){
    204                         stemmedList.add(stemmed);
    205                     }                   
    206                 } catch (ParseException ex) {
    207                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    208                 }
    209             }
    210         } 
    211         return stemmedList;
    212     }
    213    
    214     private static ArrayList<Map.Entry<String, Integer>> stemEnglish(List<Map.Entry<String, Integer>> normalizedList){
     202                    if (!stemmedWord.equals("")) {
     203                        stemmedList.add(stemmed);
     204                    }
     205                } catch (ParseException ex) {
     206                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     207                }
     208            }
     209        }
     210        return stemmedList;
     211    }
     212
     213    private static ArrayList<Map.Entry<String, Integer>> stemEnglish(List<Map.Entry<String, Integer>> normalizedList) {
    215214        org.apache.lucene.analysis.Analyzer englishAnalyzer = new EnglishAnalyzer(Version.LUCENE_36);
    216215        QueryParser englishParser = new QueryParser(Version.LUCENE_36, "", englishAnalyzer);
    217216        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    218         for(Map.Entry<String, Integer> entry : normalizedList){           
    219             if(!entry.getKey().isEmpty()){
    220                 try {
    221                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     217        for (Map.Entry<String, Integer> entry : normalizedList) {
     218            if (!entry.getKey().isEmpty()) {
     219                try {
     220                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    222221                    String stemmedWord = englishParser.parse(entry.getKey()).toString();
    223222                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    224                     if(!stemmedWord.equals("")){
    225                         stemmedList.add(stemmed);
    226                     }                   
    227                 } catch (ParseException ex) {
    228                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    229                 }
    230             }
    231         } 
    232         return stemmedList;
    233     }
    234    
    235     private static ArrayList<Map.Entry<String, Integer>> stemGerman(List<Map.Entry<String, Integer>> normalizedList){
     223                    if (!stemmedWord.equals("")) {
     224                        stemmedList.add(stemmed);
     225                    }
     226                } catch (ParseException ex) {
     227                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     228                }
     229            }
     230        }
     231        return stemmedList;
     232    }
     233
     234    private static ArrayList<Map.Entry<String, Integer>> stemGerman(List<Map.Entry<String, Integer>> normalizedList) {
    236235        org.apache.lucene.analysis.Analyzer germanAnalyzer = new GermanAnalyzer(Version.LUCENE_36);
    237236        QueryParser germanParser = new QueryParser(Version.LUCENE_36, "", germanAnalyzer);
    238237        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    239         for(Map.Entry<String, Integer> entry : normalizedList){
    240             if(!entry.getKey().isEmpty()){
    241                 try {
    242                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     238        for (Map.Entry<String, Integer> entry : normalizedList) {
     239            if (!entry.getKey().isEmpty()) {
     240                try {
     241                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    243242                    String stemmedWord = germanParser.parse(entry.getKey()).toString();
    244243                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    245                     if(!stemmedWord.equals("")){
    246                         stemmedList.add(stemmed);
    247                     }                   
    248                 } catch (ParseException ex) {
    249                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    250                 }
    251             }
    252         } 
    253         return stemmedList;
    254     }   
    255    
    256     private static ArrayList<Map.Entry<String, Integer>> stemSpanish(List<Map.Entry<String, Integer>> normalizedList){
     244                    if (!stemmedWord.equals("")) {
     245                        stemmedList.add(stemmed);
     246                    }
     247                } catch (ParseException ex) {
     248                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     249                }
     250            }
     251        }
     252        return stemmedList;
     253    }
     254
     255    private static ArrayList<Map.Entry<String, Integer>> stemSpanish(List<Map.Entry<String, Integer>> normalizedList) {
    257256        org.apache.lucene.analysis.Analyzer spanishAnalyzer = new SpanishAnalyzer(Version.LUCENE_36);
    258257        QueryParser spanishParser = new QueryParser(Version.LUCENE_36, "", spanishAnalyzer);
    259258        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    260         for(Map.Entry<String, Integer> entry : normalizedList){
    261             if(!entry.getKey().isEmpty()){
    262                 try {
    263                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     259        for (Map.Entry<String, Integer> entry : normalizedList) {
     260            if (!entry.getKey().isEmpty()) {
     261                try {
     262                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    264263                    String stemmedWord = spanishParser.parse(entry.getKey()).toString();
    265264                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    266                     if(!stemmedWord.equals("")){
    267                         stemmedList.add(stemmed);
    268                     }                   
    269                 } catch (ParseException ex) {
    270                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    271                 }
    272             }
    273         } 
    274         return stemmedList;
    275     }     
    276    
    277     private static ArrayList<Map.Entry<String, Integer>> stemRussian(List<Map.Entry<String, Integer>> normalizedList){
     265                    if (!stemmedWord.equals("")) {
     266                        stemmedList.add(stemmed);
     267                    }
     268                } catch (ParseException ex) {
     269                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     270                }
     271            }
     272        }
     273        return stemmedList;
     274    }
     275
     276    private static ArrayList<Map.Entry<String, Integer>> stemRussian(List<Map.Entry<String, Integer>> normalizedList) {
    278277        org.apache.lucene.analysis.Analyzer russianAnalyzer = new RussianAnalyzer(Version.LUCENE_36);
    279278        QueryParser russianParser = new QueryParser(Version.LUCENE_36, "", russianAnalyzer);
    280279        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    281         for(Map.Entry<String, Integer> entry : normalizedList){
    282             if(!entry.getKey().isEmpty()){
    283                 try {
    284                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     280        for (Map.Entry<String, Integer> entry : normalizedList) {
     281            if (!entry.getKey().isEmpty()) {
     282                try {
     283                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    285284                    String stemmedWord = russianParser.parse(entry.getKey()).toString();
    286285                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    287                     if(!stemmedWord.equals("")){
    288                         stemmedList.add(stemmed);
    289                     }                   
    290                 } catch (ParseException ex) {
    291                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    292                 }
    293             }
    294         } 
    295         return stemmedList;
    296     }
    297 
    298     private static ArrayList<Map.Entry<String, Integer>> stemFrench(List<Map.Entry<String, Integer>> normalizedList){
     286                    if (!stemmedWord.equals("")) {
     287                        stemmedList.add(stemmed);
     288                    }
     289                } catch (ParseException ex) {
     290                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     291                }
     292            }
     293        }
     294        return stemmedList;
     295    }
     296
     297    private static ArrayList<Map.Entry<String, Integer>> stemFrench(List<Map.Entry<String, Integer>> normalizedList) {
    299298        org.apache.lucene.analysis.Analyzer frenchAnalyzer = new FrenchAnalyzer(Version.LUCENE_36);
    300299        QueryParser frenchParser = new QueryParser(Version.LUCENE_36, "", frenchAnalyzer);
    301300        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    302         for(Map.Entry<String, Integer> entry : normalizedList){
    303             if(!entry.getKey().isEmpty()){
    304                 try {
    305                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     301        for (Map.Entry<String, Integer> entry : normalizedList) {
     302            if (!entry.getKey().isEmpty()) {
     303                try {
     304                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    306305                    String stemmedWord = frenchParser.parse(entry.getKey()).toString();
    307306                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    308                     if(!stemmedWord.equals("")){
    309                         stemmedList.add(stemmed);
    310                     }                   
    311                 } catch (ParseException ex) {
    312                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    313                 }
    314             }
    315         } 
    316         return stemmedList;
    317     } 
    318    
    319     private static ArrayList<Map.Entry<String, Integer>> stemChinese(List<Map.Entry<String, Integer>> normalizedList){
    320         org.apache.lucene.analysis.Analyzer chineseAnalyzer = new StandardAnalyzer(Version.LUCENE_36); 
     307                    if (!stemmedWord.equals("")) {
     308                        stemmedList.add(stemmed);
     309                    }
     310                } catch (ParseException ex) {
     311                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     312                }
     313            }
     314        }
     315        return stemmedList;
     316    }
     317
     318    private static ArrayList<Map.Entry<String, Integer>> stemChinese(List<Map.Entry<String, Integer>> normalizedList) {
     319        org.apache.lucene.analysis.Analyzer chineseAnalyzer = new StandardAnalyzer(Version.LUCENE_36);
    321320        QueryParser chineseParser = new QueryParser(Version.LUCENE_36, "", chineseAnalyzer);
    322321        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    323         for(Map.Entry<String, Integer> entry : normalizedList){
    324             if(!entry.getKey().isEmpty()){
    325                 try {
    326                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     322        for (Map.Entry<String, Integer> entry : normalizedList) {
     323            if (!entry.getKey().isEmpty()) {
     324                try {
     325                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    327326                    String stemmedWord = chineseParser.parse(entry.getKey()).toString();
    328327                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    329                     if(!stemmedWord.equals("")){
    330                         stemmedList.add(stemmed);
    331                     }                   
    332                 } catch (ParseException ex) {
    333                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    334                 }
    335             }
    336         } 
    337         return stemmedList;
    338     } 
    339    
    340     private static ArrayList<Map.Entry<String, Integer>> stemTurkish(List<Map.Entry<String, Integer>> normalizedList){
    341         org.apache.lucene.analysis.Analyzer turkishAnalyzer = new TurkishAnalyzer(Version.LUCENE_36); 
     328                    if (!stemmedWord.equals("")) {
     329                        stemmedList.add(stemmed);
     330                    }
     331                } catch (ParseException ex) {
     332                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     333                }
     334            }
     335        }
     336        return stemmedList;
     337    }
     338
     339    private static ArrayList<Map.Entry<String, Integer>> stemTurkish(List<Map.Entry<String, Integer>> normalizedList) {
     340        org.apache.lucene.analysis.Analyzer turkishAnalyzer = new TurkishAnalyzer(Version.LUCENE_36);
    342341        QueryParser turkishParser = new QueryParser(Version.LUCENE_36, "", turkishAnalyzer);
    343342        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    344         for(Map.Entry<String, Integer> entry : normalizedList){
    345             if(!entry.getKey().isEmpty()){
    346                 try {
    347                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     343        for (Map.Entry<String, Integer> entry : normalizedList) {
     344            if (!entry.getKey().isEmpty()) {
     345                try {
     346                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    348347                    String stemmedWord = turkishParser.parse(entry.getKey()).toString();
    349348                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    350                     if(!stemmedWord.equals("")){
    351                         stemmedList.add(stemmed);
    352                     }                   
    353                 } catch (ParseException ex) {
    354                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    355                 }
    356             }
    357         } 
    358         return stemmedList;
    359     } 
    360 
    361     private static ArrayList<Map.Entry<String, Integer>> stemHindi(List<Map.Entry<String, Integer>> normalizedList){
    362         org.apache.lucene.analysis.Analyzer hindiAnalyzer = new HindiAnalyzer(Version.LUCENE_36); 
     349                    if (!stemmedWord.equals("")) {
     350                        stemmedList.add(stemmed);
     351                    }
     352                } catch (ParseException ex) {
     353                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     354                }
     355            }
     356        }
     357        return stemmedList;
     358    }
     359
     360    private static ArrayList<Map.Entry<String, Integer>> stemHindi(List<Map.Entry<String, Integer>> normalizedList) {
     361        org.apache.lucene.analysis.Analyzer hindiAnalyzer = new HindiAnalyzer(Version.LUCENE_36);
    363362        QueryParser hindiParser = new QueryParser(Version.LUCENE_36, "", hindiAnalyzer);
    364363        ArrayList<Map.Entry<String, Integer>> stemmedList = new ArrayList<>();
    365         for(Map.Entry<String, Integer> entry : normalizedList){
    366             if(!entry.getKey().isEmpty()){
    367                 try {
    368                     //System.out.println("result: " + englishParser.parse(entry.getKey())); 
     364        for (Map.Entry<String, Integer> entry : normalizedList) {
     365            if (!entry.getKey().isEmpty()) {
     366                try {
     367                    //System.out.println("result: " + englishParser.parse(entry.getKey()));
    369368                    String stemmedWord = hindiParser.parse(entry.getKey()).toString();
    370369                    SimpleEntry<String, Integer> stemmed = new SimpleEntry<>(stemmedWord, entry.getValue());
    371                     if(!stemmedWord.equals("")){
    372                         stemmedList.add(stemmed);
    373                     }                   
    374                 } catch (ParseException ex) {
    375                     Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    376                 }
    377             }
    378         } 
    379         return stemmedList;
    380     }
    381    
    382    
    383    
    384     private void loadStopWords(){
     370                    if (!stemmedWord.equals("")) {
     371                        stemmedList.add(stemmed);
     372                    }
     373                } catch (ParseException ex) {
     374                    Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     375                }
     376            }
     377        }
     378        return stemmedList;
     379    }
     380
     381    private void loadStopWords() {
    385382        //parse stopwordsList
    386383        InputStream fstream = Analyzer.class.getResourceAsStream("/resources/files/stopWords.txt");
    387        
     384
    388385        try (BufferedReader br = new BufferedReader(new InputStreamReader(fstream))) {
    389386            String strLine;
    390387
    391             while ((strLine = br.readLine()) != null)   {
    392                 //System.out.println (strLine);
     388            while ((strLine = br.readLine()) != null) {
    393389                stopWordsList.add(strLine);
    394390            }
    395             //System.out.println(stopWordsList.size());
    396391
    397392        } catch (IOException ex) {
    398         Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
    399         }
    400         //return stopWordsList;
    401     }
    402    
    403     private void setFrequencies(ArrayList<Map.Entry<String, Integer>> frequencies){
    404         this.frequencies = frequencies;       
    405     }
    406    
    407     public List<Map.Entry<String, Integer>> getFrequencies(){       
     393            Logger.getLogger(Analyzer.class.getName()).log(Level.SEVERE, null, ex);
     394        }
     395    }
     396
     397    private void setFrequencies(ArrayList<Map.Entry<String, Integer>> frequencies) {
     398        this.frequencies = frequencies;
     399    }
     400
     401    public List<Map.Entry<String, Integer>> getFrequencies() {
    408402        return Collections.unmodifiableList(frequencies);
    409403    }
    410    
    411     public List<Map.Entry<String, Integer>> getTopKMostFrequent(int topK){
     404
     405    public List<Map.Entry<String, Integer>> getTopKMostFrequent(int topK) {
    412406        //todo recheck
    413         if(topK > frequencies.size()){
     407        if (topK > frequencies.size()) {
    414408            return Collections.unmodifiableList(frequencies);
    415         }
    416         else{
     409        } else {
    417410            return frequencies.subList(0, topK);
    418411        }
    419        
    420     }
    421    
    422     public List<Map.Entry<String, Integer>> getWithFrequency(int minFrequency){
     412    }
     413
     414    public List<Map.Entry<String, Integer>> getWithFrequency(int minFrequency) {
    423415        ArrayList<Map.Entry<String, Integer>> withFrequency = new ArrayList<>();
    424         for(Map.Entry<String, Integer> entry : frequencies){
    425             if(entry.getValue()> minFrequency){
     416        for (Map.Entry<String, Integer> entry : frequencies) {
     417            if (entry.getValue() > minFrequency) {
    426418                withFrequency.add(entry);
    427             }
    428             else{
     419            } else {
    429420                return withFrequency;
    430421            }
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/extractor/FrequenceExtractor.java

    r32320 r32404  
    1 package org.openstreetmap.josm.plugins.extractor;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.extractor;
    23
    34import java.io.IOException;
     
    1011
    1112import org.openstreetmap.josm.Main;
    12 import org.openstreetmap.josm.plugins.container.OSMNode;
    13 import org.openstreetmap.josm.plugins.container.OSMRelation;
    14 import org.openstreetmap.josm.plugins.container.OSMWay;
     13import org.openstreetmap.josm.plugins.osmrec.container.OSMNode;
     14import org.openstreetmap.josm.plugins.osmrec.container.OSMRelation;
     15import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    1516import org.openstreetmap.josm.tools.Utils;
    1617import org.xml.sax.Attributes;
     
    2526
    2627public class FrequenceExtractor extends DefaultHandler {
    27    
    28     private final List<OSMNode> nodeList; //will be populated with nodes 
     28
     29    private final List<OSMNode> nodeList; //will be populated with nodes
    2930    private final List<OSMRelation> relationList;
    30     private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects     
     31    private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects
    3132    private final List<OSMWay> wayList;  //populated with ways of the OSM file
    3233    private final String osmXmlFileName;
    33     private OSMNode nodeTmp; 
    34     private OSMWay wayTmp; 
    35     private OSMRelation relationTmp; 
    36     private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position 
    37     private boolean inNode = false; //becomes true when the parser is in a simple node       
     34    private OSMNode nodeTmp;
     35    private OSMWay wayTmp;
     36    private OSMRelation relationTmp;
     37    private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position
     38    private boolean inNode = false; //becomes true when the parser is in a simple node
    3839    private boolean inRelation = false; //becomes true when the parser is in a relarion node
    39     private Map<String,Integer> frequency;
    40    
     40    private Map<String, Integer> frequency;
     41
    4142    public FrequenceExtractor(String osmXmlFileName) {
    42         this.osmXmlFileName = osmXmlFileName;       
     43        this.osmXmlFileName = osmXmlFileName;
    4344        nodeList = new ArrayList<>();
    4445        wayList = new ArrayList<>();
    4546        relationList = new ArrayList<>();
    46         nodesWithIDs = new HashMap<>(); 
     47        nodesWithIDs = new HashMap<>();
    4748        frequency = new HashMap<>();
    48         for (int i =0; i<100; i++){
     49        for (int i = 0; i < 100; i++) {
    4950            frequency.put("", 0);
    5051        }
     
    6263    @Override
    6364    public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
    64    
     65
    6566        // if current element is an OSMNode , create new node and populate with the appropriate values
    6667        if (elementName.equalsIgnoreCase("node")) {
     
    8889
    8990            if (inNode) {
    90                 //if the path is in an OSMNode set tagKey and value to the corresponding node     
     91                //if the path is in an OSMNode set tagKey and value to the corresponding node
    9192                nodeTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    9293            } else if (inWay) {
    9394                //else if the path is in an OSM way set tagKey and value to the corresponding way
    9495                wayTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    95             } else if(inRelation){
     96            } else if (inRelation) {
    9697                //set the key-value pairs of relation tags
    9798                relationTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    98             } 
    99            
     99            }
     100
    100101        } else if (elementName.equalsIgnoreCase("member")) {
    101102            //relationTmp.addMemberReference(attributes.getValue("ref"));
    102         }                 
     103        }
    103104    }
    104105
     
    107108        // if end of node element, add to appropriate list
    108109        if (element.equalsIgnoreCase("node")) {
    109             //nodeList.add(nodeTmp);
    110             //nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
    111                        
    112             Map<String,String> tags = nodeTmp.getTagKeyValue();
    113             //System.out.println("tag: " + tags);
    114             if (tags.keySet().contains("name")){
    115                 for (Map.Entry<String, String> tag : tags.entrySet()){
    116                     if (tag.getKey().equals("name")){
    117                         //split name value in each white space and store the values separetely. Count each occurance
     110            Map<String, String> tags = nodeTmp.getTagKeyValue();
     111            if (tags.keySet().contains("name")) {
     112                for (Map.Entry<String, String> tag : tags.entrySet()) {
     113                    if (tag.getKey().equals("name")) {
     114                        //split name value in each white space and store the values separetely. Count each occurance
    118115                        String name = tag.getValue();
    119116                        String[] SplitName = name.split("\\s+");
    120117
    121                         for (String split : SplitName){
    122                         //System.out.println("split:  " + split + "  0");
    123                        
    124                         //frequency.put(split, k);
    125                         //put all splits with zero, at the constructor. put here the incremented values. for tomoro
    126                             if (frequency.get(split) != null){
    127                             int k = frequency.get(split) +1;                       
    128                             frequency.put(split, k);
    129                             //System.out.println("get split exists,   k= " + k);
    130                             }
    131                             else{
     118                        for (String split : SplitName) {
     119                            //put all splits with zero, at the constructor. put here the incremented values. for tomoro
     120                            if (frequency.get(split) != null) {
     121                                int k = frequency.get(split) +1;
     122                                frequency.put(split, k);
     123                            } else {
    132124                                frequency.put(split, 1);
    133125                            }
    134                        
    135                         //System.out.println("frequency getValue +1  " + frequency.get(tag.getValue()) +1);
    136126                        }
    137                         //System.out.println("node name:  "  + tag.getValue());
    138127                    }
    139                 }                               
    140             }
    141         }
    142        
    143         if (element.equalsIgnoreCase("way")) {           
     128                }
     129            }
     130        }
     131
     132        if (element.equalsIgnoreCase("way")) {
    144133            //name frequency
    145             Map<String,String> tags = wayTmp.getTagKeyValue();
    146            
    147            
    148             //System.out.println("tag: " + tags);
    149             if (tags.keySet().contains("name")){
    150                 for (Map.Entry<String, String> tag : tags.entrySet()){
    151                     if (tag.getKey().equals("name")){
    152                         //split name value in each white space and store the values separetely. Count each occurance
     134            Map<String, String> tags = wayTmp.getTagKeyValue();
     135
     136            if (tags.keySet().contains("name")) {
     137                for (Map.Entry<String, String> tag : tags.entrySet()) {
     138                    if (tag.getKey().equals("name")) {
     139                        //split name value in each white space and store the values separetely. Count each occurance
    153140                        String name = tag.getValue();
    154141                        String[] SplitName = name.split("\\s+");
    155                         //String[] SplitName = name.split("[\\W]");
    156                         for (String split : SplitName){
    157                         //System.out.println("split:  " + split + "  0");
    158                        
    159                         //frequency.put(split, k);
    160                         //put all splits with zero, at the constructor. put here the incremented values. for tomoro
    161                             if (frequency.get(split) != null){
    162                             int k = frequency.get(split) +1;                       
    163                             frequency.put(split, k);
    164                             //System.out.println("get split exists,   k= " + k);
    165                             }
    166                             else{
     142                        for (String split : SplitName) {
     143                            //put all splits with zero, at the constructor. put here the incremented values. for tomoro
     144                            if (frequency.get(split) != null) {
     145                                int k = frequency.get(split) +1;
     146                                frequency.put(split, k);
     147                            } else {
    167148                                frequency.put(split, 1);
    168149                            }
    169                        
    170                         //System.out.println("frequency getValue +1  " + frequency.get(tag.getValue()) +1);
    171150                        }
    172                         //System.out.println("way name:  "  + tag.getValue());
    173151                    }
    174                 }                               
    175             }
    176         }
    177        
    178         if(element.equalsIgnoreCase("relation")) {
    179            
     152                }
     153            }
     154        }
     155
     156        if (element.equalsIgnoreCase("relation")) {
    180157            //name frequency
    181             Map<String,String> tags = relationTmp.getTagKeyValue();
    182  
    183             //System.out.println("tag: " + tags);
    184             if (tags.keySet().contains("name")){
    185                 for (Map.Entry<String, String> tag : tags.entrySet()){
    186                     if (tag.getKey().equals("name")){
    187                         //split name value in each white space and store the values separetely. Count each occurance
     158            Map<String, String> tags = relationTmp.getTagKeyValue();
     159
     160            if (tags.keySet().contains("name")) {
     161                for (Map.Entry<String, String> tag : tags.entrySet()) {
     162                    if (tag.getKey().equals("name")) {
     163                        //split name value in each white space and store the values separetely. Count each occurance
    188164                        String name = tag.getValue();
    189165                        String[] SplitName = name.split("\\s+");
    190166
    191                         for (String split : SplitName){
    192                         //System.out.println("split:  " + split + "  0");
    193                        
    194                         //frequency.put(split, k);
    195                         //put all splits with zero, at the constructor. put here the incremented values. for tomoro
    196                             if (frequency.get(split) != null){
    197                             int k = frequency.get(split) +1;                       
    198                             frequency.put(split, k);
    199                             //System.out.println("get split exists,   k= " + k);
    200                             }
    201                             else{
     167                        for (String split : SplitName) {
     168                            //put all splits with zero, at the constructor. put here the incremented values. for tomoro
     169                            if (frequency.get(split) != null) {
     170                                int k = frequency.get(split) +1;
     171                                frequency.put(split, k);
     172                            } else {
    202173                                frequency.put(split, 1);
    203174                            }
    204                        
    205                         //System.out.println("frequency getValue +1  " + frequency.get(tag.getValue()) +1);
    206175                        }
    207                         //System.out.println("relation name:  "  + tag.getValue());
    208176                    }
    209                 }                               
    210             }
    211             //relationList.add(relationTmp);
     177                }
     178            }
    212179        }
    213180    }
     
    220187        return wayList;
    221188    }
    222    
    223     public List<OSMRelation> getRelationList(){
     189
     190    public List<OSMRelation> getRelationList() {
    224191        return relationList;
    225192    }
     
    227194    public Map<String, OSMNode> getNodesWithIDs() {
    228195        return nodesWithIDs;
    229     }   
    230    
     196    }
     197
    231198    //frequency temp
    232     public Map<String, Integer> getFrequency(){
     199    public Map<String, Integer> getFrequency() {
    233200        return frequency;
    234201    }
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/extractor/LanguageDetector.java

    r32320 r32404  
    1 package org.openstreetmap.josm.plugins.extractor;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.extractor;
    23
    34import java.io.File;
     
    2021 * @author imis-nkarag
    2122 */
    22 public class LanguageDetector {
     23public final class LanguageDetector {
    2324
    2425    private static LanguageDetector languageDetector = null;
     
    3940    public static void loadProfilesFromStream(String languageProfilesPath) { //create profiles directory in system from stream and load them
    4041
    41         /*  supported languages 
    42             el:greek, en:english, de:german, fr:french, es:spanish, ru:russian, tr:turkish, zh-cn:chinese, hi:hindi 
    43         */
     42        /*  supported languages
     43            el:greek, en:english, de:german, fr:french, es:spanish, ru:russian, tr:turkish, zh-cn:chinese, hi:hindi
     44         */
    4445        InputStream languageProfilesInputStreamEl = LanguageDetector.class.getResourceAsStream("/profiles/el");
    4546        InputStream languageProfilesInputStreamEn = LanguageDetector.class.getResourceAsStream("/profiles/en");
     
    5051        InputStream languageProfilesInputStreamTr = LanguageDetector.class.getResourceAsStream("/profiles/tr");
    5152        InputStream languageProfilesInputStreamZh = LanguageDetector.class.getResourceAsStream("/profiles/zh-cn");
    52         InputStream languageProfilesInputStreamHi = LanguageDetector.class.getResourceAsStream("/profiles/hi");       
     53        InputStream languageProfilesInputStreamHi = LanguageDetector.class.getResourceAsStream("/profiles/hi");
    5354        //InputStream languageProfilesInputStream2 = LanguageDetector.class.getResourceAsStream("/resources/profiles/en");
    5455
     
    5657            Utils.mkDirs(new File(languageProfilesPath));
    5758        }
    58        
     59
    5960        File languageProfilesOutputFileEl = new File(languageProfilesPath + "/el");
    6061        File languageProfilesOutputFileEn = new File(languageProfilesPath + "/en");
     
    8384
    8485        try {
    85                 Files.copy(languageProfilesInputStreamEl, languageProfilesOutputFileEl.toPath());
    86                 Files.copy(languageProfilesInputStreamEn, languageProfilesOutputFileEn.toPath());
    87                 Files.copy(languageProfilesInputStreamDe, languageProfilesOutputFileDe.toPath());
    88                 Files.copy(languageProfilesInputStreamFr, languageProfilesOutputFileFr.toPath());
    89                 Files.copy(languageProfilesInputStreamEs, languageProfilesOutputFileEs.toPath());
    90                 Files.copy(languageProfilesInputStreamRu, languageProfilesOutputFileRu.toPath());
    91                 Files.copy(languageProfilesInputStreamTr, languageProfilesOutputFileTr.toPath());
    92                 Files.copy(languageProfilesInputStreamZh, languageProfilesOutputFileZh.toPath());
    93                 Files.copy(languageProfilesInputStreamHi, languageProfilesOutputFileHi.toPath());
     86            Files.copy(languageProfilesInputStreamEl, languageProfilesOutputFileEl.toPath());
     87            Files.copy(languageProfilesInputStreamEn, languageProfilesOutputFileEn.toPath());
     88            Files.copy(languageProfilesInputStreamDe, languageProfilesOutputFileDe.toPath());
     89            Files.copy(languageProfilesInputStreamFr, languageProfilesOutputFileFr.toPath());
     90            Files.copy(languageProfilesInputStreamEs, languageProfilesOutputFileEs.toPath());
     91            Files.copy(languageProfilesInputStreamRu, languageProfilesOutputFileRu.toPath());
     92            Files.copy(languageProfilesInputStreamTr, languageProfilesOutputFileTr.toPath());
     93            Files.copy(languageProfilesInputStreamZh, languageProfilesOutputFileZh.toPath());
     94            Files.copy(languageProfilesInputStreamHi, languageProfilesOutputFileHi.toPath());
    9495        } catch (IOException ex) {
    9596            Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/extractor/SampleModelsExtractor.java

    r31554 r32404  
    1 /*
    2  * To change this license header, choose License Headers in Project Properties.
    3  * To change this template file, choose Tools | Templates
    4  * and open the template in the editor.
    5  */
    6 package org.openstreetmap.josm.plugins.extractor;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.extractor;
    73
    84import java.io.File;
     
    106import java.io.IOException;
    117import java.io.InputStream;
    12 //import java.nio.charset.Charset;
    13 //import java.nio.charset.Charset;
    14 import java.util.Scanner;
    158import java.util.logging.Level;
    169import java.util.logging.Logger;
    17 //import org.openstreetmap.josm.plugins.osmrec.OSMRecPluginHelper;
    1810
    1911/**
     
    2719        FileOutputStream outputStream = null;
    2820
    29         //File modelFile = new File(bestModelPath);
    3021        File targetFile = new File(modelPath);
    31        
    32         if(targetFile.exists()){
     22
     23        if (targetFile.exists()) {
    3324            return;
    3425        }
     
    3829            Logger.getLogger(SampleModelsExtractor.class.getName()).log(Level.SEVERE, null, ex);
    3930        }
    40        
    41         //svmModelStream = SampleModelsExtractor.class.getResourceAsStream("/resources/profiles/el");
     31
    4232        System.out.println("trying to get stream.. for " + "/resources/files/" + modelName);
    4333        svmModelStream = SampleModelsExtractor.class.getResourceAsStream("/resources/files/" + modelName);
    44            
     34
    4535        try {
    4636            outputStream = new FileOutputStream(targetFile);
    47             //Scanner input = new Scanner(svmModelStream);
    48            
    49            
     37
    5038            int read = 0;
    5139            byte[] bytes = new byte[1024];
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/features/ClassFeatures.java

    r31106 r32404  
    1 package org.openstreetmap.josm.plugins.features;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.features;
    23
    3 import de.bwaldvogel.liblinear.FeatureNode;
    44import java.util.List;
    55import java.util.Map;
    66import java.util.Set;
    77import java.util.TreeSet;
    8 import org.openstreetmap.josm.plugins.container.OSMWay;
     8
     9import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
     10
     11import de.bwaldvogel.liblinear.FeatureNode;
    912
    1013/**
     
    1316 */
    1417public class ClassFeatures {
    15    
     18
    1619    private int directClassID = 0;
    17     //private static Map<String,String> mappings;
    18     //private final Map<String, Integer> mappingsWithIDs;
    19     //private final Map<String, List<String>> indirectClasses;
    20     //private final Map<String, Integer> indirectClassesIDs;
    21    
    22         public void createClassFeatures(OSMWay wayNode, Map<String,String> mappings, Map<String, Integer> mappingsWithIDs,
    23                 Map<String, List<String>> indirectClasses, Map<String, Integer> indirectClassesIDs) {
    24        
     20
     21    public void createClassFeatures(OSMWay wayNode, Map<String, String> mappings, Map<String, Integer> mappingsWithIDs,
     22            Map<String, List<String>> indirectClasses, Map<String, Integer> indirectClassesIDs) {
     23
    2524        //iteration for each way node in the wayList
    26         //FeatureNode[] shape1 = {new FeatureNode(1, 2), new FeatureNode(2, 2)};
    27         //ArrayList<FeatureNode> test = new ArrayList<>();
    28         //test.add(new FeatureNode(1, 2));
    29         //System.out.println(shape1.length);
    3025        Set<Integer> sortedIndirectIDs = new TreeSet<>();
    31         Set<Integer> sortedDirectIDs = new TreeSet<>();       
    32         for (Map.Entry<String, String> wayTagKeyValue : wayNode.getTagKeyValue().entrySet()){
     26        Set<Integer> sortedDirectIDs = new TreeSet<>();
     27        for (Map.Entry<String, String> wayTagKeyValue : wayNode.getTagKeyValue().entrySet()) {
    3328            //iteration for each tag (key-value) in the current way node
    34            
     29
    3530            //concat key and value to use it later for checking
    3631            String key = wayTagKeyValue.getKey() + " " + wayTagKeyValue.getValue();
    37            
    38             for (Map.Entry<String,String> tagMappedToClass : mappings.entrySet()){
     32
     33            for (Map.Entry<String, String> tagMappedToClass : mappings.entrySet()) {
    3934                //entry of mappings is e.g "highway residential <-> ResidentialHighway"
    4035                //iteration to discover the wayNode class. This class's ID will be the start of the vector
    41                
    42                 if (key.equals(tagMappedToClass.getKey())){
     36
     37                if (key.equals(tagMappedToClass.getKey())) {
    4338                    String className = tagMappedToClass.getValue();
    4439                    directClassID = mappingsWithIDs.get(className);
    45                    
    46                     sortedDirectIDs.add(directClassID); 
    47                    
    48                     //the direct class id is the last direct class that the instance is found to belong 
     40
     41                    sortedDirectIDs.add(directClassID);
     42
     43                    //the direct class id is the last direct class that the instance is found to belong
    4944
    5045                    List<String> superClassesList = indirectClasses.get(className);
    5146
    52                     if (superClassesList != null){//check if the class has no superclasses                     
    53                        
     47                    if (superClassesList != null) { //check if the class has no superclasses
     48
    5449                        for (String superClass: superClassesList) {
    5550
    56                             Integer indirectID = indirectClassesIDs.get(superClass);                                                                                                         //to save time here
    57                             if(indirectID != null){// there is a chance here that the ID is null,
     51                            Integer indirectID = indirectClassesIDs.get(superClass); //to save time here
     52                            if (indirectID != null) { // there is a chance here that the ID is null,
    5853                                //cause the list of super Classes  might contain extra classes  with no ID
    5954                                //in the indirectClassesIDs map which is constructed from listHierarchyRootClasses method
    6055                                //at the OntologyParser.
    6156                                //so this condition check will remain for now
    62                                
    63                                 if(!(sortedIndirectIDs.contains(indirectID))){
     57
     58                                if (!(sortedIndirectIDs.contains(indirectID))) {
    6459                                    sortedIndirectIDs.add(indirectID);
    6560                                    //wayNode.getIndexVector().put(indirectID, 1.0);
     
    7166                    }
    7267                }
    73             }           
    74         }   
     68            }
     69        }
    7570        wayNode.setClassIDs(sortedDirectIDs);
    76         for (Integer dirID : sortedDirectIDs){
    77             wayNode.getFeatureNodeList().add(new FeatureNode(dirID, 1));           
     71        for (Integer dirID : sortedDirectIDs) {
     72            wayNode.getFeatureNodeList().add(new FeatureNode(dirID, 1));
    7873        }
    79         for (Integer indID : sortedIndirectIDs){
     74        for (Integer indID : sortedIndirectIDs) {
    8075            wayNode.getFeatureNodeList().add(new FeatureNode(indID, 1));
    81         } 
     76        }
    8277        wayNode.setClassID(directClassID);
    8378        //System.out.println("class: " + wayNode.getFeatureNodeList());
    84     } 
     79    }
    8580}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/features/GeometryFeatures.java

    r31106 r32404  
    1 package org.openstreetmap.josm.plugins.features;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.features;
     3
     4import java.util.ArrayList;
     5import java.util.List;
     6
     7import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    28
    39import com.vividsolutions.jts.geom.Coordinate;
     
    511import com.vividsolutions.jts.geom.GeometryFactory;
    612import com.vividsolutions.jts.geom.LineString;
     13
    714import de.bwaldvogel.liblinear.FeatureNode;
    8 import java.util.ArrayList;
    9 import java.util.List;
    10 import org.openstreetmap.josm.plugins.container.OSMWay;
    1115
    1216/**
    1317 * Constructs the geometry feature nodes for liblinear.
    14  * 
     18 *
    1519 * @author imis-nkarag
    1620 */
    17 
    1821public class GeometryFeatures {
    19    
     22
    2023    private int id; //= 1422; //pass this as a param from main
    2124    private final GeometryFactory geometryFactory = new GeometryFactory();
     
    2427    private static final int NUMBER_OF_MEAN = 23; //for boolean intervals
    2528    private static final int NUMBER_OF_VARIANCE = 37; //for boolean intervals
    26    
    27     public GeometryFeatures(int id){
     29
     30    public GeometryFeatures(int id) {
    2831        this.id = id;
    2932    }
    30    
    31     public void createGeometryFeatures(OSMWay wayNode){
    32    
    33     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    34     ///////////////////  geometry Features ///////////////////           
    35     ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     33
     34    public void createGeometryFeatures(OSMWay wayNode) {
     35
     36        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     37        ///////////////////  geometry Features ///////////////////
     38        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    3639        // geometry type feature //
    37         String  geometryType= wayNode.getGeometry().getGeometryType();
     40        String geometryType = wayNode.getGeometry().getGeometryType();
    3841        switch (geometryType) {
    39             //the IDs are unique for each geometry type
    40             case "LineString":
    41                 wayNode.getFeatureNodeList().add(new FeatureNode(id, 1));
    42                 id += 4;
    43                 break;
    44             case "Polygon":               
    45                 wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1));
    46                 id += 4;
    47                 break;
    48             case "LinearRing":
    49                 wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1));
    50                 id += 4;
    51                 break;
    52             case "Point":
    53                 wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1));
    54                 id += 4;                                       
    55                 break;
    56         }
    57         //LOG.info("after type " + id + " and further increase " + (id+1));
     42        //the IDs are unique for each geometry type
     43        case "LineString":
     44            wayNode.getFeatureNodeList().add(new FeatureNode(id, 1));
     45            id += 4;
     46            break;
     47        case "Polygon":
     48            wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1));
     49            id += 4;
     50            break;
     51        case "LinearRing":
     52            wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1));
     53            id += 4;
     54            break;
     55        case "Point":
     56            wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1));
     57            id += 4;
     58            break;
     59        }
    5860        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    5961        // rectangle geometry shape feature //
    6062        //id 1426
    61         if (wayNode.getGeometry().isRectangle()){                 
     63        if (wayNode.getGeometry().isRectangle()) {
    6264            wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
    6365        }
     
    6567        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    6668        // number of points of geometry feature //
    67         id++; //1427   
    68         //System.out.println("should be 1427 -> " + id);
     69        id++; //1427
    6970        int numberOfPoints = wayNode.getGeometry().getNumPoints();
    7071        numberOfPointsFeature(numberOfPoints, wayNode);
     
    7475        double area = wayNode.getGeometry().getArea();
    7576
    76         if(geometryType.equals("Polygon")){
    77 
    78             areaFeature(area,wayNode);
     77        if (geometryType.equals("Polygon")) {
     78
     79            areaFeature(area, wayNode);
    7980            //the id increases by 25 in the areaFeature method
    80         }
    81         else{
     81        } else {
    8282            id += 25;
    8383        }
    8484
    85         //////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    86         // resembles to a circle feature // 
     85        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     86        // resembles to a circle feature //
    8787        //id 1465
    88         //id++;
    89         if(geometryResemblesCircle(wayNode)){ //this method checks if the shape of the geometry resembles to a circle
    90             wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
    91         }
    92        
    93         ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    94         // mean edge feature //
    95        
     88        if (geometryResemblesCircle(wayNode)) { //this method checks if the shape of the geometry resembles to a circle
     89            wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
     90        }
     91
     92        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     93        // mean edge feature //
     94
    9695        id++;
    9796        //TOGGLE COMMENT !! commenting out mean and variance to run the best case
    98        
    99         //System.out.println("mean start" + id);
     97
    10098        Coordinate[] nodeGeometries = wayNode.getGeometry().getCoordinates();
    10199        List<Double> edgeLengths = new ArrayList<>();
    102        
    103         if(!wayNode.getGeometry().getGeometryType().toUpperCase().equals("POINT")){
     100
     101        if (!wayNode.getGeometry().getGeometryType().toUpperCase().equals("POINT")) {
    104102            for (int i = 0; i < nodeGeometries.length-1; i++) {
    105103                Coordinate[] nodePair = new Coordinate[2];
     
    107105                nodePair[1] = nodeGeometries[i+1];
    108106                LineString tempGeom = geometryFactory.createLineString(nodePair);
    109                 edgeLengths.add(tempGeom.getLength()); 
     107                edgeLengths.add(tempGeom.getLength());
    110108            }
    111         }
    112         else{         
     109        } else {
    113110            edgeLengths.add(0.0);
    114111        }
    115112        double edgeSum = 0;
    116         for(Double edge : edgeLengths){
     113        for (Double edge : edgeLengths) {
    117114            edgeSum = edgeSum + edge;
    118115        }
    119116        double mean = edgeSum/edgeLengths.size();
    120         //double normalizedMean = sqrt(mean);
    121         //geometriesPortion = geometriesPortion + id + ":" + normalizedMean + " ";
    122         //wayNode.getIndexVector().put(id, normalizedMean);
    123 
    124 //intervals with boolean values for mean feature   
    125        
    126         if(mean<2){
    127             wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
    128             id = id + NUMBER_OF_MEAN;
    129         }
    130         else if(mean<4){
     117
     118        //intervals with boolean values for mean feature
     119
     120        handleMean(wayNode, mean);
     121
     122        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     123        // variance feature//
     124        double sum = 0;
     125        for (Double edge : edgeLengths) {
     126            sum = sum + (edge-mean)*(edge-mean);
     127        }
     128
     129        double normalizedVariance = (sum/edgeLengths.size())/(mean*mean); //normalized with square of mean value
     130
     131        handleVariance(wayNode, normalizedVariance);
     132        setLastID(id);
     133    }
     134
     135    private void handleMean(OSMWay wayNode, double mean) {
     136        if (mean < 2) {
     137            wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
     138            id = id + NUMBER_OF_MEAN;
     139        } else if (mean < 4) {
    131140            wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1.0));
    132141            id = id + NUMBER_OF_MEAN;
    133         }
    134         else if(mean<6){
     142        } else if (mean < 6) {
    135143            wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1.0));
    136144            id = id + NUMBER_OF_MEAN;
    137         }
    138         else if(mean<8){
     145        } else if (mean < 8) {
    139146            wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1.0));
    140147            id = id + NUMBER_OF_MEAN;
    141         }
    142         else if(mean<10){
     148        } else if (mean < 10) {
    143149            wayNode.getFeatureNodeList().add(new FeatureNode(id+4, 1.0));
    144150            id = id + NUMBER_OF_MEAN;
    145         }
    146         else if(mean<12){
     151        } else if (mean < 12) {
    147152            wayNode.getFeatureNodeList().add(new FeatureNode(id+5, 1.0));
    148153            id = id + NUMBER_OF_MEAN;
    149         }
    150         else if(mean<14){
     154        } else if (mean < 14) {
    151155            wayNode.getFeatureNodeList().add(new FeatureNode(id+6, 1.0));
    152156            id = id + NUMBER_OF_MEAN;
    153         }
    154         else if(mean<16){
     157        } else if (mean < 16) {
    155158            wayNode.getFeatureNodeList().add(new FeatureNode(id+7, 1.0));
    156159            id = id + NUMBER_OF_MEAN;
    157         }
    158         else if(mean<18){       
     160        } else if (mean < 18) {
    159161            wayNode.getFeatureNodeList().add(new FeatureNode(id+8, 1.0));
    160162            id = id + NUMBER_OF_MEAN;
    161         }
    162         else if(mean<20){       
     163        } else if (mean < 20) {
    163164            wayNode.getFeatureNodeList().add(new FeatureNode(id+9, 1.0));
    164165            id = id + NUMBER_OF_MEAN;
    165         }
    166         else if(mean<25){       
     166        } else if (mean < 25) {
    167167            wayNode.getFeatureNodeList().add(new FeatureNode(id+10, 1.0));
    168168            id = id + NUMBER_OF_MEAN;
    169         }
    170         else if(mean<30){       
     169        } else if (mean < 30) {
    171170            wayNode.getFeatureNodeList().add(new FeatureNode(id+11, 1.0));
    172171            id = id + NUMBER_OF_MEAN;
    173         }
    174         else if(mean<35){       
     172        } else if (mean < 35) {
    175173            wayNode.getFeatureNodeList().add(new FeatureNode(id+12, 1.0));
    176174            id = id + NUMBER_OF_MEAN;
    177         }
    178         else if(mean<40){       
     175        } else if (mean < 40) {
    179176            wayNode.getFeatureNodeList().add(new FeatureNode(id+13, 1.0));
    180177            id = id + NUMBER_OF_MEAN;
    181         }
    182         else if(mean<45){       
     178        } else if (mean < 45) {
    183179            wayNode.getFeatureNodeList().add(new FeatureNode(id+14, 1.0));
    184180            id = id + NUMBER_OF_MEAN;
    185         }
    186         else if(mean<50){
     181        } else if (mean < 50) {
    187182            wayNode.getFeatureNodeList().add(new FeatureNode(id+15, 1.0));
    188183            id = id + NUMBER_OF_MEAN;
    189         }       
    190         else if(mean<60){
     184        } else if (mean < 60) {
    191185            wayNode.getFeatureNodeList().add(new FeatureNode(id+16, 1.0));
    192186            id = id + NUMBER_OF_MEAN;
    193         }       
    194         else if(mean<70){
     187        } else if (mean < 70) {
    195188            wayNode.getFeatureNodeList().add(new FeatureNode(id+17, 1.0));
    196189            id = id + NUMBER_OF_MEAN;
    197         }       
    198         else if(mean<80){
     190        } else if (mean < 80) {
    199191            wayNode.getFeatureNodeList().add(new FeatureNode(id+18, 1.0));
    200192            id = id + NUMBER_OF_MEAN;
    201         }       
    202         else if(mean<90){
     193        } else if (mean < 90) {
    203194            wayNode.getFeatureNodeList().add(new FeatureNode(id+19, 1.0));
    204195            id = id + NUMBER_OF_MEAN;
    205         }
    206         else if(mean<100){
     196        } else if (mean < 100) {
    207197            wayNode.getFeatureNodeList().add(new FeatureNode(id+20, 1.0));
    208198            id = id + NUMBER_OF_MEAN;
    209         }
    210         else if(mean<200){
     199        } else if (mean < 200) {
    211200            wayNode.getFeatureNodeList().add(new FeatureNode(id+21, 1.0));
    212201            id = id + NUMBER_OF_MEAN;
    213         }
    214         else {
     202        } else {
    215203            wayNode.getFeatureNodeList().add(new FeatureNode(id+22, 1.0));
    216204            id = id + NUMBER_OF_MEAN;
    217205        }
    218 
    219         ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    220         // variance feature//
    221         //id++; //this should be removed if using boolean features with intervals
    222         //System.out.println("must be 1467" + id);
    223         double sum = 0;
    224         for(Double edge : edgeLengths){
    225             sum = sum + (edge-mean)*(edge-mean);
    226         }
    227        
    228         //double variance = sum/edgeLengths.size(); 
    229         double normalizedVariance = (sum/edgeLengths.size())/(mean*mean); //normalized with square of mean value
    230         //geometriesPortion = geometriesPortion + id + ":" + normalizedVariance + " ";
    231         //wayNode.getIndexVector().put(id, normalizedVariance);
    232  //intervals with boolean values for variance feature 
    233        
    234         if(normalizedVariance == 0){
    235             wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
    236             id = id + NUMBER_OF_VARIANCE;
    237         }                           
    238         else if(normalizedVariance < 0.005){
     206    }
     207
     208    private void handleVariance(OSMWay wayNode, double normalizedVariance) {
     209        if (normalizedVariance == 0) {
     210            wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
     211            id = id + NUMBER_OF_VARIANCE;
     212        } else if (normalizedVariance < 0.005) {
    239213            wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1.0));
    240214            id = id + NUMBER_OF_VARIANCE;
    241         }             
    242         else if(normalizedVariance < 0.01){
     215        } else if (normalizedVariance < 0.01) {
    243216            wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1.0));
    244217            id = id + NUMBER_OF_VARIANCE;
    245         }       
    246         else if(normalizedVariance < 0.02){
     218        } else if (normalizedVariance < 0.02) {
    247219            wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1.0));
    248220            id = id + NUMBER_OF_VARIANCE;
    249         }
    250         else if(normalizedVariance < 0.03){
     221        } else if (normalizedVariance < 0.03) {
    251222            wayNode.getFeatureNodeList().add(new FeatureNode(id+4, 1.0));
    252223            id = id + NUMBER_OF_VARIANCE;
    253         }
    254         else if(normalizedVariance < 0.04){
     224        } else if (normalizedVariance < 0.04) {
    255225            wayNode.getFeatureNodeList().add(new FeatureNode(id+5, 1.0));
    256226            id = id + NUMBER_OF_VARIANCE;
    257         }
    258         else if(normalizedVariance < 0.05){
     227        } else if (normalizedVariance < 0.05) {
    259228            wayNode.getFeatureNodeList().add(new FeatureNode(id+6, 1.0));
    260229            id = id + NUMBER_OF_VARIANCE;
    261         }       
    262         else if(normalizedVariance < 0.06){
     230        } else if (normalizedVariance < 0.06) {
    263231            wayNode.getFeatureNodeList().add(new FeatureNode(id+7, 1.0));
    264232            id = id + NUMBER_OF_VARIANCE;
    265         }       
    266         else if(normalizedVariance < 0.07){
     233        } else if (normalizedVariance < 0.07) {
    267234            wayNode.getFeatureNodeList().add(new FeatureNode(id+8, 1.0));
    268235            id = id + NUMBER_OF_VARIANCE;
    269         }       
    270         else if(normalizedVariance < 0.08){
     236        } else if (normalizedVariance < 0.08) {
    271237            wayNode.getFeatureNodeList().add(new FeatureNode(id+9, 1.0));
    272238            id = id + NUMBER_OF_VARIANCE;
    273         }       
    274         else if(normalizedVariance < 0.09){
     239        } else if (normalizedVariance < 0.09) {
    275240            wayNode.getFeatureNodeList().add(new FeatureNode(id+10, 1.0));
    276241            id = id + NUMBER_OF_VARIANCE;
    277         }       
    278         else if(normalizedVariance < 0.1){
     242        } else if (normalizedVariance < 0.1) {
    279243            wayNode.getFeatureNodeList().add(new FeatureNode(id+11, 1.0));
    280244            id = id + NUMBER_OF_VARIANCE;
    281         }       
    282         else if(normalizedVariance < 0.12){
     245        } else if (normalizedVariance < 0.12) {
    283246            wayNode.getFeatureNodeList().add(new FeatureNode(id+12, 1.0));
    284247            id = id + NUMBER_OF_VARIANCE;
    285         }     
    286         else if(normalizedVariance < 0.14){
     248        } else if (normalizedVariance < 0.14) {
    287249            wayNode.getFeatureNodeList().add(new FeatureNode(id+13, 1.0));
    288250            id = id + NUMBER_OF_VARIANCE;
    289         }
    290         else if(normalizedVariance < 0.16){
     251        } else if (normalizedVariance < 0.16) {
    291252            wayNode.getFeatureNodeList().add(new FeatureNode(id+14, 1.0));
    292253            id = id + NUMBER_OF_VARIANCE;
    293         }
    294         else if(normalizedVariance < 0.18){
     254        } else if (normalizedVariance < 0.18) {
    295255            wayNode.getFeatureNodeList().add(new FeatureNode(id+15, 1.0));
    296256            id = id + NUMBER_OF_VARIANCE;
    297         }
    298         else if(normalizedVariance < 0.20){
     257        } else if (normalizedVariance < 0.20) {
    299258            wayNode.getFeatureNodeList().add(new FeatureNode(id+16, 1.0));
    300259            id = id + NUMBER_OF_VARIANCE;
    301         }
    302         else if(normalizedVariance < 0.22){
     260        } else if (normalizedVariance < 0.22) {
    303261            wayNode.getFeatureNodeList().add(new FeatureNode(id+17, 1.0));
    304262            id = id + NUMBER_OF_VARIANCE;
    305         }
    306         else if(normalizedVariance < 0.24){
     263        } else if (normalizedVariance < 0.24) {
    307264            wayNode.getFeatureNodeList().add(new FeatureNode(id+18, 1.0));
    308265            id = id + NUMBER_OF_VARIANCE;
    309         }       
    310         else if(normalizedVariance < 0.26){
     266        } else if (normalizedVariance < 0.26) {
    311267            wayNode.getFeatureNodeList().add(new FeatureNode(id+19, 1.0));
    312268            id = id + NUMBER_OF_VARIANCE;
    313         }
    314         else if(normalizedVariance < 0.28){
     269        } else if (normalizedVariance < 0.28) {
    315270            wayNode.getFeatureNodeList().add(new FeatureNode(id+20, 1.0));
    316271            id = id + NUMBER_OF_VARIANCE;
    317         }       
    318         else if(normalizedVariance < 0.30){
     272        } else if (normalizedVariance < 0.30) {
    319273            wayNode.getFeatureNodeList().add(new FeatureNode(id+21, 1.0));
    320274            id = id + NUMBER_OF_VARIANCE;
    321         }       
    322         else if(normalizedVariance < 0.32){
     275        } else if (normalizedVariance < 0.32) {
    323276            wayNode.getFeatureNodeList().add(new FeatureNode(id+22, 1.0));
    324277            id = id + NUMBER_OF_VARIANCE;
    325         }
    326         else if(normalizedVariance < 0.34){
     278        } else if (normalizedVariance < 0.34) {
    327279            wayNode.getFeatureNodeList().add(new FeatureNode(id+23, 1.0));
    328280            id = id + NUMBER_OF_VARIANCE;
    329         }
    330         else if(normalizedVariance < 0.36){
     281        } else if (normalizedVariance < 0.36) {
    331282            wayNode.getFeatureNodeList().add(new FeatureNode(id+24, 1.0));
    332283            id = id + NUMBER_OF_VARIANCE;
    333         }
    334         else if(normalizedVariance < 0.38){
     284        } else if (normalizedVariance < 0.38) {
    335285            wayNode.getFeatureNodeList().add(new FeatureNode(id+25, 1.0));
    336286            id = id + NUMBER_OF_VARIANCE;
    337         }
    338         else if(normalizedVariance < 0.40){
     287        } else if (normalizedVariance < 0.40) {
    339288            wayNode.getFeatureNodeList().add(new FeatureNode(id+26, 1.0));
    340289            id = id + NUMBER_OF_VARIANCE;
    341         }
    342         else if(normalizedVariance < 0.42){
     290        } else if (normalizedVariance < 0.42) {
    343291            wayNode.getFeatureNodeList().add(new FeatureNode(id+27, 1.0));
    344292            id = id + NUMBER_OF_VARIANCE;
    345         }
    346         else if(normalizedVariance < 0.44){
     293        } else if (normalizedVariance < 0.44) {
    347294            wayNode.getFeatureNodeList().add(new FeatureNode(id+28, 1.0));
    348295            id = id + NUMBER_OF_VARIANCE;
    349         }
    350         else if(normalizedVariance < 0.46){
     296        } else if (normalizedVariance < 0.46) {
    351297            wayNode.getFeatureNodeList().add(new FeatureNode(id+29, 1.0));
    352298            id = id + NUMBER_OF_VARIANCE;
    353         }       
    354         else if(normalizedVariance < 0.48){
     299        } else if (normalizedVariance < 0.48) {
    355300            wayNode.getFeatureNodeList().add(new FeatureNode(id+30, 1.0));
    356301            id = id + NUMBER_OF_VARIANCE;
    357         }
    358         else if(normalizedVariance < 0.5){
     302        } else if (normalizedVariance < 0.5) {
    359303            wayNode.getFeatureNodeList().add(new FeatureNode(id+31, 1.0));
    360304            id = id + NUMBER_OF_VARIANCE;
    361         }
    362         else if(normalizedVariance < 0.6){
     305        } else if (normalizedVariance < 0.6) {
    363306            wayNode.getFeatureNodeList().add(new FeatureNode(id+32, 1.0));
    364307            id = id + NUMBER_OF_VARIANCE;
    365         }
    366         else if(normalizedVariance < 0.7){
     308        } else if (normalizedVariance < 0.7) {
    367309            wayNode.getFeatureNodeList().add(new FeatureNode(id+33, 1.0));
    368310            id = id + NUMBER_OF_VARIANCE;
    369         }
    370         else if(normalizedVariance < 0.8){
     311        } else if (normalizedVariance < 0.8) {
    371312            wayNode.getFeatureNodeList().add(new FeatureNode(id+34, 1.0));
    372313            id = id + NUMBER_OF_VARIANCE;
    373         }
    374         else if(normalizedVariance < 0.9){
     314        } else if (normalizedVariance < 0.9) {
    375315            wayNode.getFeatureNodeList().add(new FeatureNode(id+35, 1.0));
    376316            id = id + NUMBER_OF_VARIANCE;
    377         }
    378         else if(normalizedVariance < 1){
     317        } else if (normalizedVariance < 1) {
    379318            wayNode.getFeatureNodeList().add(new FeatureNode(id+36, 1.0));
    380319            id = id + NUMBER_OF_VARIANCE;
    381         }
    382         else {
     320        } else {
    383321            wayNode.getFeatureNodeList().add(new FeatureNode(id+37, 1.0));
    384322            id = id + NUMBER_OF_VARIANCE;
    385         }
    386         //System.out.println("mean end from instanceVectors " + id);
    387         //System.out.println("geom: " + wayNode.getFeatureNodeList());
    388         //System.out.println("last geometry id: " + id);
    389         setLastID(id);
    390        
    391        
    392     }
    393    
    394    
    395    
    396    
    397     private void numberOfPointsFeature(int numberOfPoints, OSMWay wayNode) {           
    398         //int NUMBER_OF_POINTS = 13; //increase the id after the feature is found for the next portion of the vector.
    399 
    400         if(numberOfPoints<10){
    401             wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
    402             id += NUMBER_OF_POINTS;
    403         }
    404         else if(numberOfPoints<20){
     323        }
     324    }
     325
     326    private void numberOfPointsFeature(int numberOfPoints, OSMWay wayNode) {
     327        //increase the id after the feature is found for the next portion of the vector.
     328
     329        if (numberOfPoints < 10) {
     330            wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
     331            id += NUMBER_OF_POINTS;
     332        } else if (numberOfPoints < 20) {
    405333            wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1.0));
    406334            id += NUMBER_OF_POINTS;
    407         }
    408         else if(numberOfPoints<30){
     335        } else if (numberOfPoints < 30) {
    409336            wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1.0));
    410337            id += NUMBER_OF_POINTS;
    411         }
    412         else if(numberOfPoints<40){
     338        } else if (numberOfPoints < 40) {
    413339            wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1.0));
    414340            id += NUMBER_OF_POINTS;
    415         }
    416         else if(numberOfPoints<50){
     341        } else if (numberOfPoints < 50) {
    417342            wayNode.getFeatureNodeList().add(new FeatureNode(id+4, 1.0));
    418343            id += NUMBER_OF_POINTS;
    419         }
    420         else if(numberOfPoints<75){
     344        } else if (numberOfPoints < 75) {
    421345            wayNode.getFeatureNodeList().add(new FeatureNode(id+5, 1.0));
    422346            id += NUMBER_OF_POINTS;
    423         }
    424         else if(numberOfPoints<100){
     347        } else if (numberOfPoints < 100) {
    425348            wayNode.getFeatureNodeList().add(new FeatureNode(id+6, 1.0));
    426349            id += NUMBER_OF_POINTS;
    427         }
    428         else if(numberOfPoints<150){
     350        } else if (numberOfPoints < 150) {
    429351            wayNode.getFeatureNodeList().add(new FeatureNode(id+7, 1.0));
    430352            id += NUMBER_OF_POINTS;
    431         }
    432         else if(numberOfPoints<200){
     353        } else if (numberOfPoints < 200) {
    433354            wayNode.getFeatureNodeList().add(new FeatureNode(id+8, 1.0));
    434355            id += NUMBER_OF_POINTS;
    435         }
    436         else if(numberOfPoints<300){
     356        } else if (numberOfPoints < 300) {
    437357            wayNode.getFeatureNodeList().add(new FeatureNode(id+9, 1.0));
    438358            id += NUMBER_OF_POINTS;
    439         }
    440         else if(numberOfPoints<500){
     359        } else if (numberOfPoints < 500) {
    441360            wayNode.getFeatureNodeList().add(new FeatureNode(id+10, 1.0));
    442361            id += NUMBER_OF_POINTS;
    443         }
    444         else if(numberOfPoints<1000){
     362        } else if (numberOfPoints < 1000) {
    445363            wayNode.getFeatureNodeList().add(new FeatureNode(id+11, 1.0));
    446364            id += NUMBER_OF_POINTS;
    447         }
    448         else{
     365        } else {
    449366            wayNode.getFeatureNodeList().add(new FeatureNode(id+12, 1.0));
    450367            id += NUMBER_OF_POINTS;
    451368        }
    452369    }
    453    
    454     private void areaFeature(double area, OSMWay wayNode) {       
    455        
    456         if(area<50){
    457             wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
    458             id += NUMBER_OF_AREA_FEATURES;
    459         }
    460         else if(area<100){
     370
     371    private void areaFeature(double area, OSMWay wayNode) {
     372
     373        if (area < 50) {
     374            wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
     375            id += NUMBER_OF_AREA_FEATURES;
     376        } else if (area < 100) {
    461377            wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1.0));
    462378            id += NUMBER_OF_AREA_FEATURES;
    463         }
    464         else if(area<150){
     379        } else if (area < 150) {
    465380            wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1.0));
    466381            id += NUMBER_OF_AREA_FEATURES;
    467         }
    468         else if(area<200){
     382        } else if (area < 200) {
    469383            wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1.0));
    470384            id += NUMBER_OF_AREA_FEATURES;
    471         }
    472         else if(area<250){
     385        } else if (area < 250) {
    473386            wayNode.getFeatureNodeList().add(new FeatureNode(id+4, 1.0));
    474387            id += NUMBER_OF_AREA_FEATURES;
    475         }
    476         else if(area<300){
     388        } else if (area < 300) {
    477389            wayNode.getFeatureNodeList().add(new FeatureNode(id+5, 1.0));
    478390            id += NUMBER_OF_AREA_FEATURES;
    479         }
    480         else if(area<350){
     391        } else if (area < 350) {
    481392            wayNode.getFeatureNodeList().add(new FeatureNode(id+6, 1.0));
    482393            id += NUMBER_OF_AREA_FEATURES;
    483         }
    484         else if(area<400){
     394        } else if (area < 400) {
    485395            wayNode.getFeatureNodeList().add(new FeatureNode(id+7, 1.0));
    486396            id += NUMBER_OF_AREA_FEATURES;
    487         }
    488         else if(area<450){
     397        } else if (area < 450) {
    489398            wayNode.getFeatureNodeList().add(new FeatureNode(id+8, 1.0));
    490399            id += NUMBER_OF_AREA_FEATURES;
    491         }
    492         else if(area<500){
     400        } else if (area < 500) {
    493401            wayNode.getFeatureNodeList().add(new FeatureNode(id+9, 1.0));
    494402            id += NUMBER_OF_AREA_FEATURES;
    495         }
    496         else if(area<750){
     403        } else if (area < 750) {
    497404            wayNode.getFeatureNodeList().add(new FeatureNode(id+10, 1.0));
    498405            id += NUMBER_OF_AREA_FEATURES;
    499         }
    500         else if(area<1000){
     406        } else if (area < 1000) {
    501407            wayNode.getFeatureNodeList().add(new FeatureNode(id+11, 1.0));
    502408            id += NUMBER_OF_AREA_FEATURES;
    503         }
    504         else if(area<1250){
     409        } else if (area < 1250) {
    505410            wayNode.getFeatureNodeList().add(new FeatureNode(id+12, 1.0));
    506411            id += NUMBER_OF_AREA_FEATURES;
    507         }
    508         else if(area<1500){
     412        } else if (area < 1500) {
    509413            wayNode.getFeatureNodeList().add(new FeatureNode(id+13, 1.0));
    510414            id += NUMBER_OF_AREA_FEATURES;
    511         }
    512         else if(area<1750){
     415        } else if (area < 1750) {
    513416            wayNode.getFeatureNodeList().add(new FeatureNode(id+14, 1.0));
    514417            id += NUMBER_OF_AREA_FEATURES;
    515         }
    516         else if(area<2000){
     418        } else if (area < 2000) {
    517419            wayNode.getFeatureNodeList().add(new FeatureNode(id+15, 1.0));
    518420            id += NUMBER_OF_AREA_FEATURES;
    519         }
    520         else if(area<2250){
     421        } else if (area < 2250) {
    521422            wayNode.getFeatureNodeList().add(new FeatureNode(id+16, 1.0));
    522423            id += NUMBER_OF_AREA_FEATURES;
    523         }
    524         else if(area<2500){
     424        } else if (area < 2500) {
    525425            wayNode.getFeatureNodeList().add(new FeatureNode(id+17, 1.0));
    526426            id += NUMBER_OF_AREA_FEATURES;
    527         }
    528         else if(area<2750){
     427        } else if (area < 2750) {
    529428            wayNode.getFeatureNodeList().add(new FeatureNode(id+18, 1.0));
    530429            id += NUMBER_OF_AREA_FEATURES;
    531         }
    532         else if(area<3000){
     430        } else if (area < 3000) {
    533431            wayNode.getFeatureNodeList().add(new FeatureNode(id+19, 1.0));
    534432            id += NUMBER_OF_AREA_FEATURES;
    535         }
    536         else if(area<3500){
     433        } else if (area < 3500) {
    537434            wayNode.getFeatureNodeList().add(new FeatureNode(id+20, 1.0));
    538435            id += NUMBER_OF_AREA_FEATURES;
    539         }
    540         else if(area<4000){
     436        } else if (area < 4000) {
    541437            wayNode.getFeatureNodeList().add(new FeatureNode(id+21, 1.0));
    542438            id += NUMBER_OF_AREA_FEATURES;
    543         }
    544         else if(area<5000){
     439        } else if (area < 5000) {
    545440            wayNode.getFeatureNodeList().add(new FeatureNode(id+22, 1.0));
    546441            id += NUMBER_OF_AREA_FEATURES;
    547         }
    548         else if(area<10000){
     442        } else if (area < 10000) {
    549443            wayNode.getFeatureNodeList().add(new FeatureNode(id+23, 1.0));
    550444            id += NUMBER_OF_AREA_FEATURES;
    551         }
    552         else{
     445        } else {
    553446            wayNode.getFeatureNodeList().add(new FeatureNode(id+24, 1.0));
    554447            id += NUMBER_OF_AREA_FEATURES;
    555         }       
    556     }     
    557    
    558    
    559     private boolean geometryResemblesCircle(OSMWay way){
     448        }
     449    }
     450
     451    private boolean geometryResemblesCircle(OSMWay way) {
    560452        Geometry wayGeometry = way.getGeometry();
    561453        boolean isCircle = false;
    562         if(wayGeometry.getGeometryType().equals("Polygon") && wayGeometry.getNumPoints()>=16){
    563              
    564             List<Geometry> points = way.getNodeGeometries();           
    565             Geometry firstPoint = points.get(0);           
     454        if (wayGeometry.getGeometryType().equals("Polygon") && wayGeometry.getNumPoints() >= 16) {
     455
     456            List<Geometry> points = way.getNodeGeometries();
     457            Geometry firstPoint = points.get(0);
    566458            double radius = firstPoint.distance(wayGeometry.getCentroid());
    567            
     459
    568460            // buffer around the distance of the first point to centroid
    569             double radiusBufferSmaller = radius*0.6; 
    570             //the rest of the point-to-centroid distances will be compared with these 
    571             double radiusBufferGreater = radius*1.4; 
     461            double radiusBufferSmaller = radius*0.6;
     462            //the rest of the point-to-centroid distances will be compared with these
     463            double radiusBufferGreater = radius*1.4;
    572464            isCircle = true;
    573            
    574             for (Geometry point : points){               
     465
     466            for (Geometry point : points) {
    575467                double tempRadius = point.distance(wayGeometry.getCentroid());
    576468                boolean tempIsCircle = (radiusBufferSmaller <= tempRadius) && (tempRadius <= radiusBufferGreater);
    577469                isCircle = isCircle && tempIsCircle; //if any of the points give a false, the method will return false
    578                 //if (!isCircle){break;}
    579             }     
    580            
    581             double ratio = wayGeometry.getLength() / wayGeometry.getArea();           
    582             boolean tempIsCircle = ratio < 0.06; //arbitary value based on statistic measure of osm instances. 
    583                                                  //The smaller this value, the closer this polygon resembles to a circle           
     470                //if (!isCircle) {break;}
     471            }
     472
     473            double ratio = wayGeometry.getLength() / wayGeometry.getArea();
     474            boolean tempIsCircle = ratio < 0.06; //arbitary value based on statistic measure of osm instances.
     475            //The smaller this value, the closer this polygon resembles to a circle
    584476            isCircle = isCircle && tempIsCircle;
    585477        }
    586478        return isCircle;
    587     }     
    588    
    589     private void setLastID(int lastID){
     479    }
     480
     481    private void setLastID(int lastID) {
    590482        this.id = lastID;
    591483    }
    592    
    593     public int getLastID(){
     484
     485    public int getLastID() {
    594486        return id + 1;
    595487    }
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/features/OSMClassification.java

    r31106 r32404  
    1 package org.openstreetmap.josm.plugins.features;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.features;
    23
    34import java.util.List;
     
    56import java.util.Set;
    67import java.util.TreeSet;
    7 import org.openstreetmap.josm.plugins.container.OSMWay;
     8
     9import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    810
    911/**
     
    1315
    1416public class OSMClassification {
    15    
     17
    1618    private int directClassID = 0;
    17    
    18         public void calculateClasses(OSMWay wayNode, Map<String,String> mappings, Map<String, Integer> mappingsWithIDs,
    19                 Map<String, List<String>> indirectClasses, Map<String, Integer> indirectClassesIDs) {
    20            
     19
     20    public void calculateClasses(OSMWay wayNode, Map<String, String> mappings, Map<String, Integer> mappingsWithIDs,
     21            Map<String, List<String>> indirectClasses, Map<String, Integer> indirectClassesIDs) {
     22
    2123        Set<Integer> sortedIndirectIDs = new TreeSet<>();
    22         Set<Integer> sortedDirectIDs = new TreeSet<>();       
    23         for (Map.Entry<String, String> wayTagKeyValue : wayNode.getTagKeyValue().entrySet()){
     24        Set<Integer> sortedDirectIDs = new TreeSet<>();
     25        for (Map.Entry<String, String> wayTagKeyValue : wayNode.getTagKeyValue().entrySet()) {
    2426            //iteration for each tag (key-value) in the current way node
    25            
     27
    2628            //concat key and value to use it later for checking
    2729            String key = wayTagKeyValue.getKey() + " " + wayTagKeyValue.getValue();
    28            
    29             for (Map.Entry<String,String> tagMappedToClass : mappings.entrySet()){
     30
     31            for (Map.Entry<String, String> tagMappedToClass : mappings.entrySet()) {
    3032                //entry of mappings is e.g "highway residential <-> ResidentialHighway"
    3133                //iteration to discover the wayNode class. This class's ID will be the start of the vector
    32                
    33                 if (key.equals(tagMappedToClass.getKey())){
     34
     35                if (key.equals(tagMappedToClass.getKey())) {
    3436                    String className = tagMappedToClass.getValue();
    3537                    directClassID = mappingsWithIDs.get(className);
    36                    
    37                     sortedDirectIDs.add(directClassID); 
    38                    
    39                     //the direct class id is the last direct class that the instance is found to belong 
     38
     39                    sortedDirectIDs.add(directClassID);
     40
     41                    //the direct class id is the last direct class that the instance is found to belong
    4042
    4143                    List<String> superClassesList = indirectClasses.get(className);
    4244
    43                     if (superClassesList != null){//check if the class has no superclasses                     
    44                        
     45                    if (superClassesList != null) { //check if the class has no superclasses
     46
    4547                        for (String superClass: superClassesList) {
    4648
    47                             Integer indirectID = indirectClassesIDs.get(superClass);                                                                                                         //to save time here
    48                             if(indirectID != null){// there is a chance here that the ID is null,
     49                            Integer indirectID = indirectClassesIDs.get(superClass); //to save time here
     50                            if (indirectID != null) { // there is a chance here that the ID is null,
    4951                                //cause the list of super Classes  might contain extra classes  with no ID
    5052                                //in the indirectClassesIDs map which is constructed from listHierarchyRootClasses method
    5153                                //at the OntologyParser.
    5254                                //so this condition check will remain for now
    53                                
    54                                 if(!(sortedIndirectIDs.contains(indirectID))){
     55
     56                                if (!(sortedIndirectIDs.contains(indirectID))) {
    5557                                    sortedIndirectIDs.add(indirectID);
    5658                                    //wayNode.getIndexVector().put(indirectID, 1.0);
     
    6264                    }
    6365                }
    64             }           
    65         }   
     66            }
     67        }
    6668        wayNode.setClassIDs(sortedDirectIDs);
    6769        //System.out.println("OSMClassification, selected instance classes: " + sortedDirectIDs);
    6870        wayNode.setClassID(directClassID);
    69     } 
     71    }
    7072}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/features/RelationFeatures.java

    r31106 r32404  
    1 package org.openstreetmap.josm.plugins.features;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.features;
     3
     4import java.util.List;
     5import java.util.Map;
     6
     7import org.openstreetmap.josm.plugins.osmrec.container.OSMRelation;
     8import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    29
    310import de.bwaldvogel.liblinear.FeatureNode;
    4 import java.util.List;
    5 import java.util.Map;
    6 import org.openstreetmap.josm.plugins.container.OSMRelation;
    7 import org.openstreetmap.josm.plugins.container.OSMWay;
    811
    912/**
    1013 * Constructs the relation features for liblinear.
    11  * 
     14 *
    1215 * @author imis-nkarag
    1316 */
    1417
    1518public class RelationFeatures {
    16         int id;
    17    
    18         public RelationFeatures(int id){
    19             this.id = id;
    20         }       
    21        
    22         public void createRelationFeatures(OSMWay wayNode, List<OSMRelation> relationList) {     
     19    int id;
     20
     21    public RelationFeatures(int id) {
     22        this.id = id;
     23    }
     24
     25    public void createRelationFeatures(OSMWay wayNode, List<OSMRelation> relationList) {
    2326        id++; //this should be removed when using boolean intervals for mean and variance
    24         //System.out.println("must be 1468" + id);
    25         //System.out.println("InstanceVectors rel start" + id);
    2627        boolean hasRelation = false;
    27         for(OSMRelation relation : relationList){
    28             if(hasRelation){
     28        for (OSMRelation relation : relationList) {
     29            if (hasRelation) {
    2930                break;
    30             } 
    31            
    32             if(relation.getMemberReferences().contains(wayNode.getID())){
     31            }
     32
     33            if (relation.getMemberReferences().contains(wayNode.getID())) {
    3334                hasRelation = true;
    3435                Map<String, String> tags = relation.getTagKeyValue();
    35                
    36                 if(tags.containsKey("route")){   
    37                     wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));     
    38                 }
    39                 else if(tags.containsKey("multipolygon")){
    40                     wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1.0));                                     
    41                 }
    42                 else if(tags.containsKey("boundary")){
    43                     wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1.0));                                       
    44                 }
    45                 else if(tags.containsKey("restriction")){
    46                     wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1.0));                                     
    47                 }
    48                 else{
     36
     37                if (tags.containsKey("route")) {
     38                    wayNode.getFeatureNodeList().add(new FeatureNode(id, 1.0));
     39                } else if (tags.containsKey("multipolygon")) {
     40                    wayNode.getFeatureNodeList().add(new FeatureNode(id+1, 1.0));
     41                } else if (tags.containsKey("boundary")) {
     42                    wayNode.getFeatureNodeList().add(new FeatureNode(id+2, 1.0));
     43                } else if (tags.containsKey("restriction")) {
     44                    wayNode.getFeatureNodeList().add(new FeatureNode(id+3, 1.0));
     45                } else {
    4946                    //the instance may be a member of a relation, but the relation has no type or is incomplete.
    50                     wayNode.getFeatureNodeList().add(new FeatureNode(id+4, 1.0));                 
     47                    wayNode.getFeatureNodeList().add(new FeatureNode(id+4, 1.0));
    5148                }
    5249                id = id + 5;
    5350            }
    5451        }
    55        
    56        
    57         if(!hasRelation){
     52
     53        if (!hasRelation) {
    5854            id = id + 5;
    59         }       
     55        }
    6056    }
    61        
    62     public int getLastID(){
     57
     58    public int getLastID() {
    6359        return id;
    64     }   
     60    }
    6561}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/features/TextualFeatures.java

    r31106 r32404  
    1 package org.openstreetmap.josm.plugins.features;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.features;
    23
    3 import com.cybozu.labs.langdetect.LangDetectException;
    4 import de.bwaldvogel.liblinear.FeatureNode;
    54import java.util.List;
    65import java.util.Map;
    76import java.util.TreeMap;
    8 import org.openstreetmap.josm.plugins.container.OSMWay;
    97import java.util.logging.Level;
    108import java.util.logging.Logger;
     9
    1110import org.apache.lucene.analysis.el.GreekAnalyzer;
    1211import org.apache.lucene.analysis.en.EnglishAnalyzer;
     
    1413import org.apache.lucene.queryParser.QueryParser;
    1514import org.apache.lucene.util.Version;
    16 import org.openstreetmap.josm.plugins.extractor.LanguageDetector;
     15import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
     16import org.openstreetmap.josm.plugins.osmrec.extractor.LanguageDetector;
     17
     18import com.cybozu.labs.langdetect.LangDetectException;
     19
     20import de.bwaldvogel.liblinear.FeatureNode;
    1721
    1822/**
    1923 * Constructs the textual features from the given textual list.
    20  * 
     24 *
    2125 * @author imis-nkarag
    2226 */
    2327
    2428public class TextualFeatures {
    25    
     29
    2630    private int id;
    2731    private int numberOfFeatures;
     
    3135    private final QueryParser englishParser;
    3236    private final LanguageDetector languageDetector;
    33    
     37
    3438    public TextualFeatures(int id, List<String> textualList, LanguageDetector languageDetector) {
    35        
     39
    3640        this.id = id;
    3741        this.textualList = textualList;
     
    4246        EnglishAnalyzer englishAnalyzer = new EnglishAnalyzer(Version.LUCENE_36);
    4347        englishParser = new QueryParser(Version.LUCENE_36, "", englishAnalyzer);
    44        
     48
    4549    }
    46    
    47     public void createTextualFeatures(OSMWay wayNode) {       
     50
     51    public void createTextualFeatures(OSMWay wayNode) {
    4852        //namesList.indexOf(name) this index can be zero.
    49         //In that case it conflicts the previous geometry id, so we increment id.
    50         //System.out.println("begin textual id from InstanceVectors = " + id);
    51        
     53        //In that case it conflicts the previous geometry id, so we increment id.
     54
    5255        //idWords: populated with the ID that will be ginen as a feature, mapped with the word found.
    5356        //Chose to store the name for future use.
    54         Map<Integer,String> idWords= new TreeMap<>();
     57        Map<Integer, String> idWords = new TreeMap<>();
    5558        Map<String, String> tags = wayNode.getTagKeyValue();
    56         if (tags.keySet().contains("name")){           
     59        if (tags.keySet().contains("name")) {
    5760            String nameTag = tags.get("name"); //get the value of the name tag of the current node
    58             String[] nameTagSplitList = nameTag.split("\\s");    //split the value to compare individually 
    59                                                                  //with the namesList
     61            String[] nameTagSplitList = nameTag.split("\\s");    //split the value to compare individually
     62            //with the namesList
    6063            String lang = "";
    6164            try {
     
    6568            }
    6669
    67             for(String split : nameTagSplitList){
     70            for (String split : nameTagSplitList) {
    6871                try {
    69                     //System.out.println("split before: " + split);
    70                     //detectLanguage(split);
    71 
    7272                    //TOGGLE
    7373                    split = split.replaceAll("[-+.^:,?;'{}\"!()\\[\\]]", "");
    74                     if(lang.equals("el")){
    75 
    76                         //if(false){
     74                    if (lang.equals("el")) {
    7775                        split = stemGreek(split);
    78                         //System.out.println("en: split after stem: " + split);
    79                     }
    80                     else{
     76                    } else {
    8177                        split = stemEnglish(split);
    82                         //System.out.println("el: split after stem: " + split);
    8378                    }
    8479
    85                     if(textualList.contains(split)){
     80                    if (textualList.contains(split)) {
    8681                        int currentID = textualList.indexOf(split) + id;
    8782                        idWords.put(currentID, split);
    88                         //System.out.println(currentID + " " + split);
    8983                    }
    9084                } catch (ParseException ex) {
    9185                    Logger.getLogger(TextualFeatures.class.getName()).log(Level.SEVERE, null, ex);
    9286                }
    93             } 
    94            
    95             for(Integer wordID : idWords.keySet()){
     87            }
     88
     89            for (Integer wordID : idWords.keySet()) {
    9690                wayNode.getFeatureNodeList().add(new FeatureNode(wordID, 1.0));
    9791                //System.out.println(wordID);
    98             } 
    99             //System.out.println("until textual " + wayNode.getFeatureNodeList());           
    100         }       
    101         //System.out.println("textual id (number of features):  " + (namesList.size()+id));
    102         //System.out.println("textual id (number of features):  " + numberOfFeatures);
     92            }
     93            //System.out.println("until textual " + wayNode.getFeatureNodeList());
     94        }
    10395    }
    104    
    105     public int getLastID(){
     96
     97    public int getLastID() {
    10698        return numberOfFeatures;
    10799    }
    108    
    109     private String detectLanguage(String nameTag) throws LangDetectException{
    110         //detect language       
    111        
    112         if(!nameTag.isEmpty()){
     100
     101    private String detectLanguage(String nameTag) throws LangDetectException {
     102        //detect language
     103
     104        if (!nameTag.isEmpty()) {
    113105            language = languageDetector.detect(nameTag);
    114106            return language;
    115         }
    116         else{
     107        } else {
    117108            return "no_lang";
    118109        }
     
    122113        String stemmedWord;
    123114
    124         if(!word.isEmpty()){
     115        if (!word.isEmpty()) {
    125116            stemmedWord = greekParser.parse(word).toString();
    126         }
    127         else{
     117        } else {
    128118            return word;
    129119        }
     
    131121        return stemmedWord;
    132122    }
    133    
    134     private String stemEnglish(String word) throws ParseException{
     123
     124    private String stemEnglish(String word) throws ParseException {
    135125
    136126        String stemmedWord;
    137127
    138         if(!word.isEmpty()){
     128        if (!word.isEmpty()) {
    139129            stemmedWord = englishParser.parse(word).toString();
    140         }
    141         else{
     130        } else {
    142131            return word;
    143132        }
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/parsers/Mapper.java

    r31554 r32404  
    1 
    2 package org.openstreetmap.josm.plugins.parsers;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.parsers;
    33
    44import java.io.FileNotFoundException;
     
    1414 * about the OSM tags and the ontology classes
    1515 * This info is used in the vector construction.
    16  * 
     16 *
    1717 * @author imis-nkarag
    1818 */
     
    2323    private final HashMap<String, Integer> mappingsWithIDs;
    2424    private final Map<Integer, String> idsWithMappings;
    25    
    26     public Mapper(){   
    27    
    28        mappings = new LinkedHashMap<>();
    29        mappingsWithIDs = new HashMap<>();
    30        idsWithMappings = new HashMap<>();
    31    
     25
     26    public Mapper() {
     27
     28        mappings = new LinkedHashMap<>();
     29        mappingsWithIDs = new HashMap<>();
     30        idsWithMappings = new HashMap<>();
     31
    3232    }
    33        
     33
    3434    public void parseFile(InputStream inps) throws FileNotFoundException {
    35                  
     35
    3636        Scanner input = new Scanner(inps); //the Map file contains lines of the mappings separated with the symbol "|"
    37                                             //e.g. highway motorway | Motorway
    38                                             //the key will be the string "highway motorway" and the value "Motorway"
    39         while(input.hasNext()) {
    40          
    41              String nextLine = input.nextLine();
    42              String[] splitContent = nextLine.split("\\|",2);   //split current line in two parts,
    43                                                                 //separated by the "|" symbol
    44              String key = splitContent[0];                      //this key will be mapped to a class 
    45              String value = splitContent[1];                    //this value is the mapped class
    46              key = key.trim();                                 
    47              value = value.trim();                             
    48              mappings.put(key, value);
     37        //e.g. highway motorway | Motorway
     38        //the key will be the string "highway motorway" and the value "Motorway"
     39        while (input.hasNext()) {
     40
     41            String nextLine = input.nextLine();
     42            String[] splitContent = nextLine.split("\\|", 2);   //split current line in two parts,
     43            //separated by the "|" symbol
     44            String key = splitContent[0];                      //this key will be mapped to a class
     45            String value = splitContent[1];                    //this value is the mapped class
     46            key = key.trim();
     47            value = value.trim();
     48            mappings.put(key, value);
    4949        }
    5050        constructMappingsWithIDs();
    5151        constructIDsWithMappings();
    5252        System.out.println("Mappings file parsed successfully!");
    53         //LOG.info("Mappings file parsed successfully!");     
    54     } 
    55    
    56     private void constructMappingsWithIDs(){
     53        //LOG.info("Mappings file parsed successfully!");
     54    }
     55
     56    private void constructMappingsWithIDs() {
    5757        Integer i = 1; //starting ID is 1: SVM multiclass does not accept 0 as a class ID
    58         for (String ontologyClass : mappings.values())
    59             mappingsWithIDs.put(ontologyClass, i);           
     58        for (String ontologyClass : mappings.values()) {
     59            mappingsWithIDs.put(ontologyClass, i);
    6060            i++;
    61         }       
     61        }
    6262    }
    63    
    64     public Map<String,Integer> getMappingsWithIDs(){
     63
     64    public Map<String, Integer> getMappingsWithIDs() {
    6565        return Collections.unmodifiableMap(mappingsWithIDs);
    6666    }
    67    
    68     public Map<String,String> getMappings(){
     67
     68    public Map<String, String> getMappings() {
    6969        return Collections.unmodifiableMap(mappings);
    70     }   
    71    
    72     private void constructIDsWithMappings(){
     70    }
     71
     72    private void constructIDsWithMappings() {
    7373        int i = 1; //starting ID is 1: SVM multiclass does not accept 0 as a class ID
    74  
    75         for (String ontologyClass : mappings.values())
     74
     75        for (String ontologyClass : mappings.values()) {
    7676            idsWithMappings.put(i, ontologyClass);
    7777            i++;
    7878        }
    79     } 
    80    
    81     public Map<Integer, String> getIDsWithMappings(){
     79    }
     80
     81    public Map<Integer, String> getIDsWithMappings() {
    8282        return Collections.unmodifiableMap(idsWithMappings);
    83     }   
     83    }
    8484}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/parsers/OSMParser.java

    r32320 r32404  
    1 package org.openstreetmap.josm.plugins.parsers;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.parsers;
    23
    34import java.io.IOException;
     
    2122import org.opengis.referencing.operation.TransformException;
    2223import org.openstreetmap.josm.Main;
    23 import org.openstreetmap.josm.plugins.container.OSMNode;
    24 import org.openstreetmap.josm.plugins.container.OSMRelation;
    25 import org.openstreetmap.josm.plugins.container.OSMWay;
     24import org.openstreetmap.josm.plugins.osmrec.container.OSMNode;
     25import org.openstreetmap.josm.plugins.osmrec.container.OSMRelation;
     26import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    2627import org.openstreetmap.josm.tools.Utils;
    2728import org.xml.sax.Attributes;
     
    4344 */
    4445public class OSMParser extends DefaultHandler {
    45    
     46
    4647    //private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OSMParser.class);
    47    
     48
    4849    //change from wgs84 to cartesian for later processing of the geometry
    4950    private static final CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;
     
    5152    private final GeometryFactory geometryFactory = new GeometryFactory();
    5253    private static MathTransform transform = null;
    53     private final List<OSMNode> nodeList; //will be populated with nodes 
     54    private final List<OSMNode> nodeList; //will be populated with nodes
    5455    private final List<OSMRelation> relationList;
    55     private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects     
     56    private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects
    5657    private final List<OSMWay> wayList;  //populated with ways of the OSM file
    5758    private final String osmXmlFileName;
    5859    private OSMNode nodeTmp; //variable to hold the node object
    5960    private OSMWay wayTmp;   //variable to hold the way object
    60     private OSMRelation relationTmp; 
    61     private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position 
    62     private boolean inNode = false; //becomes true when the parser is in a simple node       
     61    private OSMRelation relationTmp;
     62    private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position
     63    private boolean inNode = false; //becomes true when the parser is in a simple node
    6364    private boolean inRelation = false; //becomes true when the parser is in a relarion node
    64    
    65     public OSMParser(String osmXmlFileName)  {
    66         this.osmXmlFileName = osmXmlFileName;       
     65
     66    public OSMParser(String osmXmlFileName) {
     67        this.osmXmlFileName = osmXmlFileName;
    6768        nodeList = new ArrayList<>();
    6869        wayList = new ArrayList<>();
    6970        relationList = new ArrayList<>();
    70         nodesWithIDs = new HashMap<>(); 
     71        nodesWithIDs = new HashMap<>();
    7172        try {
    7273            transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
     
    8687    @Override
    8788    public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
    88    
     89
    8990        // if current element is an OSMNode , create new node and populate with the appropriate values
    9091        if (elementName.equalsIgnoreCase("node")) {
     
    9899            Coordinate targetGeometry = null;
    99100            Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
    100             try {   
     101            try {
    101102                targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    102103            } catch (MismatchedDimensionException | TransformException ex) {
    103104                Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
    104105            }
    105            
     106
    106107            //create geometry object
    107108            Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
     
    114115            wayTmp = new OSMWay();
    115116            wayTmp.setID(attributes.getValue("id"));
    116            
    117             if(attributes.getValue("user") != null){
     117
     118            if (attributes.getValue("user") != null) {
    118119                wayTmp.setUser(attributes.getValue("user"));
    119             }
    120             else{
     120            } else {
    121121                wayTmp.setUser("undefined");
    122122            }
    123                    
     123
    124124            inWay = true;
    125125            inNode = false;
     
    137137
    138138            if (inNode) {
    139                 //if the path is in an OSMNode set tagKey and value to the corresponding node     
     139                //if the path is in an OSMNode set tagKey and value to the corresponding node
    140140                nodeTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    141141            } else if (inWay) {
    142142                //else if the path is in an OSM way set tagKey and value to the corresponding way
    143143                wayTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    144             } else if(inRelation){
     144            } else if (inRelation) {
    145145                //set the key-value pairs of relation tags
    146146                relationTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    147             }           
     147            }
    148148        } else if (elementName.equalsIgnoreCase("member")) {
    149149            relationTmp.addMemberReference(attributes.getValue("ref"));
    150         }                 
     150        }
    151151    }
    152152
     
    158158            nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
    159159        }
    160        
    161         if (element.equalsIgnoreCase("way")) {           
    162            
     160
     161        if (element.equalsIgnoreCase("way")) {
     162
    163163            //construct the Way geometry from each node of the node references
    164164            List<String> references = wayTmp.getNodeReferences();
    165165
    166166            for (String entry: references) {
    167                Geometry geometry = nodesWithIDs.get(entry).getGeometry(); //get the geometry of the node with ID=entry
    168                wayTmp.addNodeGeometry(geometry); //add the node geometry in this way
    169                
     167                Geometry geometry = nodesWithIDs.get(entry).getGeometry(); //get the geometry of the node with ID=entry
     168                wayTmp.addNodeGeometry(geometry); //add the node geometry in this way
     169
    170170            }
    171171            Geometry geom = geometryFactory.buildGeometry(wayTmp.getNodeGeometries());
    172            
    173             if((wayTmp.getNumberOfNodes()>3) &&
     172
     173            if ((wayTmp.getNumberOfNodes() > 3) &&
    174174                    wayTmp.getNodeGeometries().get(0).equals(wayTmp.getNodeGeometries()
    175                                                                         .get(wayTmp.getNodeGeometries().size()-1))){
    176             //checks if the beginning and ending node are the same and the number of nodes are more than 3.
    177             //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
    178                
    179                if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))){
    180                //this is not a barrier nor a road, so construct a polygon geometry
    181                
    182                LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    183                Polygon poly = new Polygon(linear, null, geometryFactory);
    184                wayTmp.setGeometry(poly);               
    185                }
    186                else {
    187                //it is either a barrier or a road, so construct a linear ring geometry
    188                   LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    189                   wayTmp.setGeometry(linear); 
    190                }
    191             }
    192             else if (wayTmp.getNumberOfNodes()>1){
    193             //it is an open geometry with more than one nodes, make it linestring
    194                
    195                 LineString lineString =  geometryFactory.createLineString(geom.getCoordinates());
    196                 wayTmp.setGeometry(lineString);               
    197             }
    198             else{ //we assume all the rest geometries are points
    199             //some ways happen to have only one point. Construct a  Point.
     175                            .get(wayTmp.getNodeGeometries().size()-1))) {
     176                //checks if the beginning and ending node are the same and the number of nodes are more than 3.
     177                //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
     178
     179                if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))) {
     180                    //this is not a barrier nor a road, so construct a polygon geometry
     181
     182                    LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     183                    Polygon poly = new Polygon(linear, null, geometryFactory);
     184                    wayTmp.setGeometry(poly);
     185                } else {
     186                    //it is either a barrier or a road, so construct a linear ring geometry
     187                    LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     188                    wayTmp.setGeometry(linear);
     189                }
     190            } else if (wayTmp.getNumberOfNodes() > 1) {
     191                //it is an open geometry with more than one nodes, make it linestring
     192
     193                LineString lineString = geometryFactory.createLineString(geom.getCoordinates());
     194                wayTmp.setGeometry(lineString);
     195            } else { //we assume all the rest geometries are points
     196                //some ways happen to have only one point. Construct a  Point.
    200197                Point point = geometryFactory.createPoint(geom.getCoordinate());
    201198                wayTmp.setGeometry(point);
    202199            }
    203200            wayList.add(wayTmp);
    204         } 
    205        
    206         if(element.equalsIgnoreCase("relation")) {
     201        }
     202
     203        if (element.equalsIgnoreCase("relation")) {
    207204            relationList.add(relationTmp);
    208205        }
     
    216213        return wayList;
    217214    }
    218    
    219     public List<OSMRelation> getRelationList(){
     215
     216    public List<OSMRelation> getRelationList() {
    220217        return relationList;
    221218    }
     
    223220    public Map<String, OSMNode> getNodesWithIDs() {
    224221        return nodesWithIDs;
    225     }   
     222    }
    226223}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/parsers/Ontology.java

    r31441 r32404  
    1 package org.openstreetmap.josm.plugins.parsers;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.parsers;
     3
     4import java.io.InputStream;
     5import java.util.ArrayList;
     6import java.util.HashMap;
     7import java.util.Iterator;
     8import java.util.List;
     9import java.util.Map;
    210
    311/**
     
    1018import com.hp.hpl.jena.rdf.model.ModelFactory;
    1119import com.hp.hpl.jena.util.iterator.ExtendedIterator;
    12 import java.io.InputStream;
    13 import java.util.ArrayList;
    14 import java.util.HashMap;
    15 import java.util.Iterator;
    16 import java.util.List;
    17 import java.util.Map;
    1820
    1921/**
     
    2123 * The owl file contains information about the ontology and hierarchy of the classes
    2224 * Provides methods for retrieving information about the ontology.
    23  * 
    24  * 
     25 *
     26 *
    2527 * @author imis-nkarag
    2628 */
    2729
    28 public class Ontology {   
     30public class Ontology {
    2931    //private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(Ontology.class);
    3032
    3133    private OntModel ontologyModel;
    3234    private List<OntClass> listHierarchy;
    33     private static final int additiveID = 1373;     
    34     private Map<String, List<String>> indirectClasses;   
     35    private static final int additiveID = 1373;
     36    private Map<String, List<String>> indirectClasses;
    3537    private final Map<String, Integer> indirectClassesIDs;
    3638    private final InputStream owlFile;
    37    
    38     public Ontology(InputStream owlFile){
    39        
     39
     40    public Ontology(InputStream owlFile) {
     41
    4042        this.owlFile = owlFile;
    4143        indirectClassesIDs = new HashMap<>();
     
    4345        listHierarchy = new ArrayList<>();
    4446    }
    45    
     47
    4648    public void parseOntology() {
    4749        try {
    4850
    49         //create the ontology model using the base
    50         ontologyModel = ModelFactory.createOntologyModel();               
    51        
    52         org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);
    53         ontologyModel.read(owlFile, null);    //Hide RDFDefaultErrorHandler from terminal to keep clear output.
    54         org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
    55    
    56         listHierarchy = ontologyModel.listHierarchyRootClasses().toList();
    57         setListHierarchy(listHierarchy); 
    58        
    59         ExtendedIterator<OntClass> classes = ontologyModel.listClasses();
    60         while (classes.hasNext()) {
    61             String className;
    62             OntClass obj = classes.next();           
    63            
    64             //compare localname with class name from map and call getSuperclass     
    65             if (obj.hasSubClass()) {
     51            //create the ontology model using the base
     52            ontologyModel = ModelFactory.createOntologyModel();
    6653
    67                 for (Iterator<OntClass> i = obj.listSubClasses(true); i.hasNext();) {
    68                     OntClass currentClass = i.next();
    69                    
    70                     List<OntClass> superClasses = currentClass.listSuperClasses().toList();                   
    71                     List<String> superClassesStrings = new ArrayList<>();
    72                    
    73                     for (OntClass superClass : superClasses){                       
    74                         className = superClass.toString().replace("http://linkedgeodata.org/ontology/", "");
    75                         superClassesStrings.add(className);
     54            org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);
     55            ontologyModel.read(owlFile, null);    //Hide RDFDefaultErrorHandler from terminal to keep clear output.
     56            org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
     57
     58            listHierarchy = ontologyModel.listHierarchyRootClasses().toList();
     59            setListHierarchy(listHierarchy);
     60
     61            ExtendedIterator<OntClass> classes = ontologyModel.listClasses();
     62            while (classes.hasNext()) {
     63                String className;
     64                OntClass obj = classes.next();
     65
     66                //compare localname with class name from map and call getSuperclass
     67                if (obj.hasSubClass()) {
     68
     69                    for (Iterator<OntClass> i = obj.listSubClasses(true); i.hasNext();) {
     70                        OntClass currentClass = i.next();
     71
     72                        List<OntClass> superClasses = currentClass.listSuperClasses().toList();
     73                        List<String> superClassesStrings = new ArrayList<>();
     74
     75                        for (OntClass superClass : superClasses) {
     76                            className = superClass.toString().replace("http://linkedgeodata.org/ontology/", "");
     77                            superClassesStrings.add(className);
     78                        }
     79                        indirectClasses.put(currentClass.getLocalName(), superClassesStrings);
    7680                    }
    77                     indirectClasses.put(currentClass.getLocalName(), superClassesStrings);
    7881                }
    7982            }
     83            createIndirectClassesWithIDs();
     84            setIndirectClasses(indirectClasses);
     85            setOntologyModel(ontologyModel);
     86        } catch (IllegalArgumentException e) {
     87            System.out.println(e.getMessage());
    8088        }
    81         createIndirectClassesWithIDs();
    82         setIndirectClasses(indirectClasses);
    83         setOntologyModel(ontologyModel);
    84         }
    85         catch (IllegalArgumentException  e) {
    86              System.out.println(e.getMessage());
    87         }
    88     //LOG.info("Ontology from XML loaded!"); 
    8989    }
    90    
     90
    9191    private void createIndirectClassesWithIDs() {
    92         for (int i=0; i<(listHierarchy.size()); i++){
    93        
    94             String key = listHierarchy.get(i).toString().replace("http://linkedgeodata.org/ontology/", "");     
     92        for (int i = 0; i < listHierarchy.size(); i++) {
     93
     94            String key = listHierarchy.get(i).toString().replace("http://linkedgeodata.org/ontology/", "");
    9595            //we add 1 to the ID because we want IDs beginning from 1. listHierarchy has index beginning from 0
    9696            indirectClassesIDs.put(key, i + additiveID); //the IDs start from 1373 to avoid duplicate IDs at the vectorConstructor
    97         }       
     97        }
    9898    }
    99    
    100     private void setOntologyModel(OntModel ontologyModel){
    101         this.ontologyModel = ontologyModel; 
     99
     100    private void setOntologyModel(OntModel ontologyModel) {
     101        this.ontologyModel = ontologyModel;
    102102    }
    103    
    104     private void setIndirectClasses(Map<String, List<String>> indirectClasses){
     103
     104    private void setIndirectClasses(Map<String, List<String>> indirectClasses) {
    105105        this.indirectClasses = indirectClasses;
    106        
     106
    107107    }
    108    
    109     private void setListHierarchy(List<OntClass> listHierarchy){
     108
     109    private void setListHierarchy(List<OntClass> listHierarchy) {
    110110        this.listHierarchy = listHierarchy;
    111111    }
    112            
    113     public OntModel getOntologyModel(){       
     112
     113    public OntModel getOntologyModel() {
    114114        return this.ontologyModel;
    115115    }
    116116
    117     public Map<String, List<String>> getIndirectClasses(){
     117    public Map<String, List<String>> getIndirectClasses() {
    118118        return this.indirectClasses;
    119119    }
    120    
    121     public List<OntClass> getListHierarchy(){
     120
     121    public List<OntClass> getListHierarchy() {
    122122        return this.listHierarchy;
    123123    }
    124    
    125     public Map<String, Integer> getIndirectClassesIDs(){
     124
     125    public Map<String, Integer> getIndirectClassesIDs() {
    126126        return this.indirectClassesIDs;
    127127    }
    128            
     128
    129129}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/parsers/TextualStatistics.java

    r31402 r32404  
    1 package org.openstreetmap.josm.plugins.parsers;
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.plugins.osmrec.parsers;
    23
    34import java.io.InputStream;
     
    1011 * Provides functionality for parsing the names file
    1112 * This file contains name occurrences obtained from statistical measures on OSM data.
    12  * 
     13 *
    1314 * @author imis-nkarag
    1415 */
    1516
    1617public class TextualStatistics {
    17    
     18
    1819    //private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(TextualStatistics.class);
    1920    private List<String> textualList;
    20    
    21         public void parseTextualList(InputStream textualFileStream){
    22             textualList = new ArrayList<>();
    23            
    24             Scanner input = new Scanner(textualFileStream);
    25             while(input.hasNext()) {
    26                 String nextLine = input.nextLine();
    27                 textualList.add(nextLine);
    28             }
    29             //LOG.info("Name occurences parsed successfully!");
     21
     22    public void parseTextualList(InputStream textualFileStream) {
     23        textualList = new ArrayList<>();
     24
     25        Scanner input = new Scanner(textualFileStream);
     26        while (input.hasNext()) {
     27            String nextLine = input.nextLine();
     28            textualList.add(nextLine);
    3029        }
    31        
    32         public List<String> getTextualList(){
    33             return Collections.unmodifiableList(textualList);
    34         }
     30        //LOG.info("Name occurences parsed successfully!");
     31    }
     32
     33    public List<String> getTextualList() {
     34        return Collections.unmodifiableList(textualList);
     35    }
    3536}
    3637
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/personalization/HistoryParser.java

    r32320 r32404  
     1// License: GPL. For details, see LICENSE file.
    12package org.openstreetmap.josm.plugins.osmrec.personalization;
    23
     
    2526import org.openstreetmap.josm.Main;
    2627import org.openstreetmap.josm.io.OsmApi;
    27 import org.openstreetmap.josm.plugins.container.OSMNode;
    28 import org.openstreetmap.josm.plugins.container.OSMWay;
     28import org.openstreetmap.josm.plugins.osmrec.container.OSMNode;
     29import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    2930import org.openstreetmap.josm.tools.HttpClient;
    3031import org.openstreetmap.josm.tools.Utils;
     
    4344/**
    4445 * Parses the history of an OSM user's changesets using OSM API.
    45  * 
     46 *
    4647 * @author imis-nkarag
    4748 */
     
    5253    private static final GeometryFactory geometryFactory = new GeometryFactory();
    5354    private MathTransform transform;
    54     private OSMNode nodeTmp; 
     55    private OSMNode nodeTmp;
    5556
    5657    private final List<OSMNode> nodeList;
     
    6465     * @param username user name
    6566     */
    66     public HistoryParser(String username) {   
     67    public HistoryParser(String username) {
    6768        this.username = username;
    6869        transform = null;
     
    7879
    7980    public void historyParse(String timeInterval) {
    80        
     81
    8182        HashSet<String> changesetIDsList = new HashSet<>();
    82        
     83
    8384        try {
    8485            String osmUrl = OSM_API + "changesets?display_name=" + username + "&time=" + timeInterval;
     
    8889            Main.debug("changeset size "+ nodes.getLength());
    8990            for (int i = 0; i < nodes.getLength(); i++) {
    90                 Main.debug("attributes of " + i + "th changeset");
     91                Main.debug("attributes of " + i + "th changeset");
    9192                String id = nodes.item(i).getAttributes().item(3).toString();
    9293                Main.debug("id:" + nodes.item(i).getAttributes().item(3));
    9394                id = stripQuotes(id);
    94                 changesetIDsList.add(id);               
    95             }
    96 
    97             for(String id : changesetIDsList){
     95                changesetIDsList.add(id);
     96            }
     97
     98            for (String id : changesetIDsList) {
    9899                getChangesetByID(id);
    99100            }
     
    108109            InputStream xml = HttpClient.create(new URL(changesetByIDURL)).connect().getContent();
    109110            Node osmChange = Utils.parseSafeDOM(xml).getFirstChild();
    110  
     111
    111112            //get all nodes first, in order to be able to call all nodes references and create the geometries
    112             for(int i = 0; i < osmChange.getChildNodes().getLength(); i++){
     113            for (int i = 0; i < osmChange.getChildNodes().getLength(); i++) {
    113114                String changeType = osmChange.getChildNodes().item(i).getNodeName();
    114                 if(!(changeType.equals("#text") || changeType.equals("delete"))){
     115                if (!(changeType.equals("#text") || changeType.equals("delete"))) {
    115116
    116117                    NodeList changeChilds = osmChange.getChildNodes().item(i).getChildNodes();
     
    118119                    Node osmObject = changeChilds.item(1);
    119120
    120                     if(osmObject.getNodeName().equals("node")){
    121                         //node data 
     121                    if (osmObject.getNodeName().equals("node")) {
     122                        //node data
    122123                        nodeTmp = new OSMNode();
    123124                        nodeTmp.setID(osmObject.getAttributes().getNamedItem("id").getNodeValue());
     
    128129                        Coordinate targetGeometry = null;
    129130                        Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
    130                         try {   
     131                        try {
    131132                            targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    132133                        } catch (MismatchedDimensionException | TransformException ex) {
     
    136137                        //create geometry object
    137138                        Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
    138                         nodeTmp.setGeometry(geom);                   
     139                        nodeTmp.setGeometry(geom);
    139140
    140141                        nodeList.add(nodeTmp);
    141142                        nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
    142                     }                       
     143                    }
    143144                }
    144145            }
    145        
    146             for(int i = 0; i < osmChange.getChildNodes().getLength(); i++){
     146
     147            for (int i = 0; i < osmChange.getChildNodes().getLength(); i++) {
    147148                String changeType = osmChange.getChildNodes().item(i).getNodeName();
    148                 if(!(changeType.equals("#text") || changeType.equals("delete"))){
     149                if (!(changeType.equals("#text") || changeType.equals("delete"))) {
    149150                    NodeList changeChilds = osmChange.getChildNodes().item(i).getChildNodes();
    150151
    151152                    Node osmObject = changeChilds.item(1);
    152                     if(osmObject.getNodeName().equals("way")){
     153                    if (osmObject.getNodeName().equals("way")) {
    153154
    154155                        //get way data
    155156                        wayTmp = new OSMWay();
    156                         wayTmp.setID(osmObject.getAttributes().getNamedItem("id").getNodeValue()); 
    157                         //osmObject.getChildNodes() <-extract tags, then set tags to osm object
     157                        wayTmp.setID(osmObject.getAttributes().getNamedItem("id").getNodeValue());
     158                        // extract tags, then set tags to osm object
    158159                        Main.debug("\n\nWAY: " + wayTmp.getID());
    159                         for(int l=0; l<osmObject.getChildNodes().getLength(); l++){
     160                        for (int l = 0; l < osmObject.getChildNodes().getLength(); l++) {
    160161                            String wayChild = osmObject.getChildNodes().item(l).getNodeName();
    161162
    162                             if(wayChild.equals("tag")){
     163                            if (wayChild.equals("tag")) {
    163164                                String key = osmObject.getChildNodes().item(l).getAttributes().getNamedItem("k").getNodeValue();
    164165                                String value = osmObject.getChildNodes().item(l).getAttributes().getNamedItem("v").getNodeValue();
    165166                                System.out.println("key: " + key + " value: " + value);
    166                                 wayTmp.setTagKeyValue(key,value);
    167                             }
    168                             else if(wayChild.equals("nd")){
     167                                wayTmp.setTagKeyValue(key, value);
     168                            } else if (wayChild.equals("nd")) {
    169169                                wayTmp.addNodeReference(osmObject.getChildNodes().item(l).getAttributes().getNamedItem("ref").getNodeValue());
    170170                            }
    171171                        }
    172                        
     172
    173173                        //construct the Way geometry from each node of the node references
    174174                        List<String> references = wayTmp.getNodeReferences();
    175175
    176176                        for (String entry: references) {
    177                            if(nodesWithIDs.containsKey(entry)){
     177                            if (nodesWithIDs.containsKey(entry)) {
    178178                                Geometry geometry = nodesWithIDs.get(entry).getGeometry(); //get the geometry of the node with ID=entry
    179179                                wayTmp.addNodeGeometry(geometry); //add the node geometry in this way
    180                            }
    181                            else{
    182                                Main.debug("nodes with ids, no entry " + entry);
    183                                getNodeFromAPI(entry);
    184                            }
     180                            } else {
     181                                Main.debug("nodes with ids, no entry " + entry);
     182                                getNodeFromAPI(entry);
     183                            }
    185184                        }
    186185
    187186                        Geometry geom = geometryFactory.buildGeometry(wayTmp.getNodeGeometries());
    188                         if((wayTmp.getNodeGeometries().size()>3) &&
     187                        if ((wayTmp.getNodeGeometries().size() > 3) &&
    189188                                wayTmp.getNodeGeometries().get(0).equals(wayTmp.getNodeGeometries()
    190                                                                                     .get(wayTmp.getNodeGeometries().size()-1))){
    191                         //checks if the beginning and ending node are the same and the number of nodes are more than 3.
    192                         //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
    193 
    194                             if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))){
    195                             //this is not a barrier nor a road, so construct a polygon geometry
    196 
    197                             LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    198                             Polygon poly = new Polygon(linear, null, geometryFactory);
    199                             wayTmp.setGeometry(poly);               
     189                                        .get(wayTmp.getNodeGeometries().size()-1))) {
     190                            //checks if the beginning and ending node are the same and the number of nodes are more than 3.
     191                            //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
     192
     193                            if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))) {
     194                                //this is not a barrier nor a road, so construct a polygon geometry
     195
     196                                LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     197                                Polygon poly = new Polygon(linear, null, geometryFactory);
     198                                wayTmp.setGeometry(poly);
     199                            } else {
     200                                //it is either a barrier or a road, so construct a linear ring geometry
     201                                LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     202                                wayTmp.setGeometry(linear);
    200203                            }
    201                             else {
    202                             //it is either a barrier or a road, so construct a linear ring geometry
    203                                 LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    204                                 wayTmp.setGeometry(linear); 
    205                             }
    206                         }
    207                         else if (wayTmp.getNodeGeometries().size() > 1){
    208                         //it is an open geometry with more than one nodes, make it linestring
     204                        } else if (wayTmp.getNodeGeometries().size() > 1) {
     205                            //it is an open geometry with more than one nodes, make it linestring
    209206
    210207                            LineString lineString = geometryFactory.createLineString(geom.getCoordinates());
    211                             wayTmp.setGeometry(lineString);               
    212                         }
    213                         else{ //we assume all the rest geometries are points
    214                         //some ways happen to have only one point. Construct a  Point.
     208                            wayTmp.setGeometry(lineString);
     209                        } else { //we assume all the rest geometries are points
     210                            //some ways happen to have only one point. Construct a  Point.
    215211                            Point point = geometryFactory.createPoint(geom.getCoordinate());
    216212                            wayTmp.setGeometry(point);
    217213                        }
    218                         wayList.add(wayTmp);   
    219                     }   
     214                        wayList.add(wayTmp);
     215                    }
    220216                }
    221             }                 
     217            }
    222218        } catch (IOException | ParserConfigurationException | SAXException ex) {
    223219            Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    224         }   
     220        }
    225221    }
    226222
     
    236232            String lat = nodes.item(0).getAttributes().getNamedItem("lat").getNodeValue();
    237233            String lon = nodes.item(0).getAttributes().getNamedItem("lon").getNodeValue();
    238            
     234
    239235            nodeTmp = new OSMNode();
    240236            nodeTmp.setID(nodeID);
     
    245241            Coordinate targetGeometry = null;
    246242            Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
    247             try {   
     243            try {
    248244                targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    249245            } catch (MismatchedDimensionException | TransformException ex) {
     
    253249            //create geometry object
    254250            Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
    255             nodeTmp.setGeometry(geom);                   
     251            nodeTmp.setGeometry(geom);
    256252
    257253            nodeList.add(nodeTmp);
    258254            nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
    259            
     255
    260256        } catch (IOException | ParserConfigurationException | SAXException ex) {
    261257            Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    262258        }
    263259    }
    264    
    265     public List<OSMWay> getWayList(){
     260
     261    public List<OSMWay> getWayList() {
    266262        return wayList;
    267263    }
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/personalization/TrainByUser.java

    r31564 r32404  
     1// License: GPL. For details, see LICENSE file.
    12package org.openstreetmap.josm.plugins.osmrec.personalization;
    23
    34import static java.util.concurrent.TimeUnit.NANOSECONDS;
    4 import de.bwaldvogel.liblinear.FeatureNode;
    5 import de.bwaldvogel.liblinear.Linear;
    6 import de.bwaldvogel.liblinear.Model;
    7 import de.bwaldvogel.liblinear.Parameter;
    8 import de.bwaldvogel.liblinear.Problem;
    9 import de.bwaldvogel.liblinear.SolverType;
     5
    106import java.awt.event.ActionEvent;
    117import java.awt.event.ActionListener;
     
    2925import java.util.logging.Level;
    3026import java.util.logging.Logger;
     27
    3128import javax.swing.SwingWorker;
    32 import org.openstreetmap.josm.plugins.container.OSMRelation;
    33 import org.openstreetmap.josm.plugins.container.OSMWay;
    34 import org.openstreetmap.josm.plugins.extractor.Analyzer;
    35 import org.openstreetmap.josm.plugins.extractor.LanguageDetector;
    36 import org.openstreetmap.josm.plugins.features.ClassFeatures;
    37 import org.openstreetmap.josm.plugins.features.GeometryFeatures;
    38 import org.openstreetmap.josm.plugins.features.OSMClassification;
    39 import org.openstreetmap.josm.plugins.features.RelationFeatures;
    40 import org.openstreetmap.josm.plugins.features.TextualFeatures;
    41 import org.openstreetmap.josm.plugins.parsers.Mapper;
    42 import org.openstreetmap.josm.plugins.parsers.Ontology;
    43 import org.openstreetmap.josm.plugins.parsers.TextualStatistics;
     29
     30import org.openstreetmap.josm.plugins.osmrec.container.OSMRelation;
     31import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
     32import org.openstreetmap.josm.plugins.osmrec.extractor.Analyzer;
     33import org.openstreetmap.josm.plugins.osmrec.extractor.LanguageDetector;
     34import org.openstreetmap.josm.plugins.osmrec.features.ClassFeatures;
     35import org.openstreetmap.josm.plugins.osmrec.features.GeometryFeatures;
     36import org.openstreetmap.josm.plugins.osmrec.features.OSMClassification;
     37import org.openstreetmap.josm.plugins.osmrec.features.RelationFeatures;
     38import org.openstreetmap.josm.plugins.osmrec.features.TextualFeatures;
     39import org.openstreetmap.josm.plugins.osmrec.parsers.Mapper;
     40import org.openstreetmap.josm.plugins.osmrec.parsers.Ontology;
     41import org.openstreetmap.josm.plugins.osmrec.parsers.TextualStatistics;
     42
     43import de.bwaldvogel.liblinear.FeatureNode;
     44import de.bwaldvogel.liblinear.Linear;
     45import de.bwaldvogel.liblinear.Model;
     46import de.bwaldvogel.liblinear.Parameter;
     47import de.bwaldvogel.liblinear.Problem;
     48import de.bwaldvogel.liblinear.SolverType;
    4449
    4550/**
    4651 *  Trains a model by the history of given user.
    47  * 
     52 *
    4853 *  @author imis-nkarag
    4954 */
    50 
    51 public class TrainByUser extends SwingWorker<Void, Void> implements ActionListener{
    52    
     55public class TrainByUser extends SwingWorker<Void, Void> implements ActionListener {
     56
    5357    private final String inputFilePath;
    54     private static Map<String,String> mappings;
    55     private static Map<String,Integer> mapperWithIDs;
     58    private static Map<String, String> mappings;
     59    private static Map<String, Integer> mapperWithIDs;
    5660    private static List<OSMWay> wayList;
    5761    private static List<OSMRelation> relationList;
    58    
     62
    5963    private static Map<String, List<String>> indirectClasses;
    6064    private static Map<String, Integer> indirectClassesWithIDs;
    61     //private static List<OntClass> listHierarchy;
    62     private static List<String> namesList;       
     65    private static List<String> namesList;
    6366    private int numberOfTrainingInstances;
    6467    private final String modelDirectoryPath;
     
    7174    private static double foldScore10 = 0;
    7275    private static double bestScore = 0;
    73     //int trainProgress = 0;
    7476    private final boolean validateFlag;
    7577    private final double cParameterFromUser;
     
    7880    private final int frequency;
    7981    private final boolean topKIsSelected;
    80     private String textualListFilePath;   
     82    private String textualListFilePath;
    8183    private static final boolean USE_CLASS_FEATURES = false;
    8284    private static final boolean USE_RELATION_FEATURES = false;
     
    8688    private final String username;
    8789    private final String inputFileName;
    88        
    89     public TrainByUser(String inputFilePath, String username, boolean validateFlag, double cParameterFromUser, 
     90
     91    public TrainByUser(String inputFilePath, String username, boolean validateFlag, double cParameterFromUser,
    9092            int topK, int frequency, boolean topKIsSelected, LanguageDetector languageDetector, List<OSMWay> wayList) {
    91         super();
    92         TrainByUser.languageDetector = languageDetector;       
    93         this.inputFilePath = inputFilePath;
     93        TrainByUser.languageDetector = languageDetector;
     94        this.inputFilePath = inputFilePath;
    9495        this.username = username;
    9596        this.validateFlag = validateFlag;
     
    99100        this.topKIsSelected = topKIsSelected;
    100101        System.out.println("find parent directory, create osmrec dir for models: " + new File(inputFilePath).getParentFile());
    101        
    102         if(System.getProperty("os.name").contains("ux")){
     102
     103        if (System.getProperty("os.name").contains("ux")) {
    103104            inputFileName = inputFilePath.substring(inputFilePath.lastIndexOf("/"));
    104         }
    105         else{
     105        } else {
    106106            inputFileName = inputFilePath.substring(inputFilePath.lastIndexOf("\\"));
    107107        }
    108        
     108
    109109        modelDirectoryPath = new File(inputFilePath).getParentFile() + "/OSMRec_models";
    110         //textualDirectoryPath = new File(inputFilePath).getParentFile() + "/OSMRec_models/textualList.txt";
    111        
     110
    112111        modelDirectory = new File(modelDirectoryPath);
    113        
     112
    114113        if (!modelDirectory.exists()) {
    115114            modelDirectory.mkdir();
    116115            System.out.println("model directory created!");
    117         }
    118         else {
     116        } else {
    119117            System.out.println("directory already exists!");
    120         }   
     118        }
    121119        TrainByUser.wayList = wayList;
    122120    }
    123        
     121
    124122    @Override
    125     public Void doInBackground() throws Exception {         
     123    public Void doInBackground() throws Exception {
    126124        extractTextualList();
    127125        parseFiles();
    128         if(validateFlag){   
     126        if (validateFlag) {
    129127            firePropertyChange("progress", getProgress(), 5);
    130             //setProgress(5);
    131128            validateLoop();
    132129            firePropertyChange("progress", getProgress(), 40);
    133             //setProgress(40);
    134130            System.out.println("Training model with the best c: " + bestConfParam);
    135131            clearDataset();
    136132            trainModel(bestConfParam);
    137133            firePropertyChange("progress", getProgress(), 60);
    138             //setProgress(80);
    139134            clearDataset();
    140135            trainModelWithClasses(bestConfParam);
    141136            firePropertyChange("progress", getProgress(), 100);
    142137            setProgress(100);
    143         }
    144         else{
    145 
    146             //firePropertyChange("progress", getProgress(), 5);
    147             //setProgress(5);
     138        } else {
    148139            clearDataset();
    149140            firePropertyChange("progress", getProgress(), 10);
    150             //setProgress(10);
    151141            trainModel(cParameterFromUser);
    152             //setProgress(60);   
    153142            firePropertyChange("progress", getProgress(), 60);
    154143            clearDataset();
    155144            firePropertyChange("progress", getProgress(), 65);
    156             //setProgress(65);
    157             trainModelWithClasses(cParameterFromUser);         
    158            
     145            trainModelWithClasses(cParameterFromUser);
     146
    159147            firePropertyChange("progress", getProgress(), 100);
    160148            setProgress(100);
    161149            System.out.println("done.");
    162150        }
    163         System.out.println("Train by user process complete.");   
     151        System.out.println("Train by user process complete.");
    164152        return null;
    165153    }
    166    
    167     private void extractTextualList(){
     154
     155    private void extractTextualList() {
    168156        System.out.println("Running analysis..");
    169157        //provide top-K
     
    171159        //Keep terms with frequency higher than N
    172160        //Use the remaining terms as training features
    173        
     161
    174162        Analyzer anal = new Analyzer(inputFilePath, languageDetector);
    175163        anal.runAnalysis();
     
    177165        textualListFilePath = modelDirectory.getAbsolutePath()+"/textualList.txt";
    178166        File textualFile = new File(textualListFilePath); //decide path of models
    179         if(textualFile.exists()){
     167        if (textualFile.exists()) {
    180168            textualFile.delete();
    181         }       
     169        }
    182170        try {
    183171            textualFile.createNewFile();
    184172        } catch (IOException ex) {
    185173            Logger.getLogger(TrainByUser.class.getName()).log(Level.SEVERE, null, ex);
    186         }           
    187        
     174        }
     175
    188176        //writeTextualListToFile(textualFilePath, anal.getTopKMostFrequent(15));
    189177        List<Map.Entry<String, Integer>> textualList;
    190         if(topKIsSelected){
     178        if (topKIsSelected) {
    191179            textualList = anal.getTopKMostFrequent(topK);
    192180            System.out.println(textualList);
    193         }
    194         else{
     181        } else {
    195182            textualList = anal.getWithFrequency(frequency);
    196183            System.out.println(textualList);
     
    200187        System.out.println("textual list saved at location:\n" + textualListFilePath);
    201188        //write list to file and let parser do the loading from the names file
    202        
     189
    203190        //method read default list
    204191        //method extract textual list - > the list will be already in memory, so the names parser doesn t have to be called
    205         if(USE_CLASS_FEATURES){
     192        if (USE_CLASS_FEATURES) {
    206193            numberOfFeatures = 1422 + 105 + textualList.size();
    207         }
    208         else{         
     194        } else {
    209195            numberOfFeatures = 105 + textualList.size();
    210196        }
    211     } 
    212    
     197    }
     198
    213199    private void parseFiles() {
    214        // File tagsToClassesFile = new File(tagsToClassesFilePath);       
    215 
    216         //osmRecProperties.load(Train.class.getResourceAsStream("/resources/properties/osmRec.properties"));
    217200        InputStream tagsToClassesMapping = TrainByUser.class.getResourceAsStream("/resources/files/Map");
    218201
    219202        Mapper mapper = new Mapper();
    220         try {   
     203        try {
    221204            mapper.parseFile(tagsToClassesMapping);
    222205        } catch (FileNotFoundException ex) {
     
    224207        }
    225208        mappings = mapper.getMappings();
    226         mapperWithIDs = mapper.getMappingsWithIDs();
    227         //System.out.println("success. mappings empty? " + mappings.isEmpty());
    228        
     209        mapperWithIDs = mapper.getMappingsWithIDs();
     210
    229211        InputStream ontologyStream = TrainByUser.class.getResourceAsStream("/resources/files/owl.xml");
    230         Ontology ontology = new Ontology(ontologyStream);           
     212        Ontology ontology = new Ontology(ontologyStream);
    231213
    232214        ontology.parseOntology();
     
    234216        indirectClasses = ontology.getIndirectClasses();
    235217        indirectClassesWithIDs = ontology.getIndirectClassesIDs();
    236         //listHierarchy = ontology.getListHierarchy();       
    237 
    238         //InputStream textualFileStream = TrainWorker.class.getResourceAsStream("/resources/files/names");     
    239         InputStream textualFileStream = null; 
     218
     219        //InputStream textualFileStream = TrainWorker.class.getResourceAsStream("/resources/files/names");
     220        InputStream textualFileStream = null;
    240221        try {
    241222            textualFileStream = new FileInputStream(new File(textualListFilePath));
     
    243224            Logger.getLogger(TrainByUser.class.getName()).log(Level.SEVERE, null, ex);
    244225        }
    245        
    246         readTextualFromDefaultList(textualFileStream);     
    247        
     226
     227        readTextualFromDefaultList(textualFileStream);
     228
    248229        //osmParser.parseDocument();
    249230        //relationList = osmParser.getRelationList();
    250231        //wayList = osmParser.getWayList();
    251232        numberOfTrainingInstances = wayList.size();
    252         System.out.println("number of instances: " + numberOfTrainingInstances);   
    253         System.out.println("end of parsing files.");
    254         if(numberOfTrainingInstances == 0){
    255             System.out.println("This user has not edited the loaded area. Cannot train a model!");           
    256         }       
    257     }
    258 
    259     private void validateLoop(){
    260 //        Double[] confParams = new Double[] {Math.pow(2, -10), Math.pow(2, -5),Math.pow(2, -3),Math.pow(2, -1),
    261 //            Math.pow(2, 0),Math.pow(2, 1),Math.pow(2, 2),Math.pow(2, 3),Math.pow(2, 4),Math.pow(2, 5),Math.pow(2, 6),
    262 //            Math.pow(2, 8),Math.pow(2, 10),Math.pow(2, 12),Math.pow(2, 14),Math.pow(2, 15),Math.pow(2, 16),Math.pow(2, 17)};
    263        
    264         Double[] confParams = new Double[] {Math.pow(2, -10),Math.pow(2, -10), Math.pow(2, -5),Math.pow(2, -3),Math.pow(2, -1),Math.pow(2, 0)};       
    265                
     233        System.out.println("number of instances: " + numberOfTrainingInstances);
     234        System.out.println("end of parsing files.");
     235        if (numberOfTrainingInstances == 0) {
     236            System.out.println("This user has not edited the loaded area. Cannot train a model!");
     237        }
     238    }
     239
     240    private void validateLoop() {
     241        Double[] confParams = new Double[] {
     242                Math.pow(2, -10), Math.pow(2, -10), Math.pow(2, -5), Math.pow(2, -3), Math.pow(2, -1), Math.pow(2, 0)};
     243
    266244        double bestC = Math.pow(2, -10);
    267        
    268         for(Double param : confParams){
    269             //setProgress(4*((5*(trainProgress++))/confParams.length));
     245
     246        for (Double param : confParams) {
    270247            foldScore1 = 0;
    271248            foldScore5 = 0;
     
    273250            System.out.println("\n\n\nrunning for C = " + param);
    274251            clearDataset();
    275             System.out.println("fold1");           
    276             //crossValidateFold(0, 3, 3, 4, false, param);
     252            System.out.println("fold1");
    277253            crossValidateFold(0, 4, 4, 5, false, param); //4-1
    278             //setProgress(4*((5*(trainProgress++))/confParams.length));
    279             //System.out.println((5*trainProgress)/confParams.length);
    280            
     254
    281255            foldScore1 = foldScore1 + score1;
    282256            foldScore5 = foldScore5 + score5;
     
    284258            clearDataset();
    285259            System.out.println("fold2");
    286             //crossValidateFold(1, 4, 4, 5, false, param);
    287260            crossValidateFold(1, 5, 0, 1, false, param);
    288             //setProgress(4*((5*(trainProgress++))/confParams.length));
    289             //System.out.println((5*trainProgress)/confParams.length);
    290            
     261
    291262            foldScore1 = foldScore1 + score1;
    292263            foldScore5 = foldScore5 + score5;
     
    294265            clearDataset();
    295266            System.out.println("fold3");
    296             //crossValidateFold(2, 5, 0, 1, false, param);
    297267            crossValidateFold(0, 5, 1, 2, true, param);
    298             //setProgress(4*((5*(trainProgress++))/confParams.length));
    299             //System.out.println((5*trainProgress)/confParams.length);
    300            
     268
    301269            foldScore1 = foldScore1 + score1;
    302270            foldScore5 = foldScore5 + score5;
     
    304272            clearDataset();
    305273            System.out.println("fold4");
    306             //crossValidateFold(0, 5, 1, 2, true, param);
    307274            crossValidateFold(0, 5, 2, 3, true, param);
    308             //setProgress(4*((5*(trainProgress++))/confParams.length));
    309             //System.out.println((5*trainProgress)/confParams.length);
    310            
     275
    311276            foldScore1 = foldScore1 + score1;
    312277            foldScore5 = foldScore5 + score5;
     
    314279            clearDataset();
    315280            System.out.println("fold5");
    316             //crossValidateFold(0, 5, 2, 3, true, param);
    317281            crossValidateFold(0, 5, 3, 4, true, param);
    318             //setProgress(4*((5*(trainProgress++))/confParams.length));
    319             //System.out.println((5*trainProgress)/confParams.length);
    320            
     282
    321283            foldScore1 = foldScore1 + score1;
    322284            foldScore5 = foldScore5 + score5;
    323285            foldScore10 = foldScore10 + score10;
    324286            System.out.println("\n\nC=" + param + ", average score 1-5-10: " + foldScore1/5 +" "+ foldScore5/5 + " "+ foldScore10/5);
    325             if(bestScore < foldScore1 ){
     287            if (bestScore < foldScore1) {
    326288                bestScore = foldScore1;
    327289                bestC = param;
    328290            }
    329            
    330         }
    331         //System.out.println(4*((5*(trainProgress++))/confParams.length));
    332         //setProgress(100);
     291
     292        }
    333293        bestConfParam = bestC;
    334         System.out.println("best c param= " + bestC + ", score: " + bestScore/5 );
    335     }
    336    
    337     private void crossValidateFold(int a, int b, int c, int d, boolean skip, double param){
     294        System.out.println("best c param= " + bestC + ", score: " + bestScore/5);
     295    }
     296
     297    private void crossValidateFold(int a, int b, int c, int d, boolean skip, double param) {
    338298        System.out.println("Starting cross validation");
    339299        int testSize = wayList.size()/5;
    340300
    341         List<OSMWay> trainList= new ArrayList<>();
    342         for(int g = a*testSize; g<b*testSize; g++){  // 0~~1~~2~~3~~4~~5
    343             if(skip){
    344                 if(g == (c)*testSize){g=(c+1)*testSize;}
    345            
    346             }
    347             trainList.add(wayList.get(g));
    348         } 
     301        List<OSMWay> trainList = new ArrayList<>();
     302        for (int g = a*testSize; g < b*testSize; g++) {  // 0~~1~~2~~3~~4~~5
     303            if (skip) {
     304                if (g == (c)*testSize) {
     305                    g = (c+1)*testSize;
     306                }
     307            }
     308            trainList.add(wayList.get(g));
     309        }
    349310
    350311        int wayListSizeWithoutUnclassified = trainList.size();
    351         int u = 0;
    352312        System.out.println("trainList size: " + wayListSizeWithoutUnclassified);
    353        
     313
    354314        //set classes for each osm instance
    355         int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size 
    356         for(OSMWay way : trainList){
     315        int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
     316        for (OSMWay way : trainList) {
    357317
    358318            OSMClassification classifyInstances = new OSMClassification();
    359319            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    360320
    361             if(way.getClassIDs().isEmpty()){
     321            if (way.getClassIDs().isEmpty()) {
    362322                wayListSizeWithoutUnclassified -= 1;
    363                 u++;
    364             }
    365             else {
     323            } else {
    366324                sizeToBeAddedToArray = sizeToBeAddedToArray + way.getClassIDs().size()-1;
    367             }               
    368         } 
    369         double C = param;       
     325            }
     326        }
     327        double C = param;
    370328        double eps = 0.001;
    371         double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];//new double[117558];//               
    372         FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures]; //working[3812];
    373         int k =0;   
    374        
    375         for(OSMWay way : trainList){
    376             //adding multiple vectors                     
    377             int id;           
    378             if(USE_CLASS_FEATURES){               
     329        double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];
     330        FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures];
     331        int k = 0;
     332
     333        for (OSMWay way : trainList) {
     334            //adding multiple vectors
     335            int id;
     336            if (USE_CLASS_FEATURES) {
    379337                ClassFeatures class_vector = new ClassFeatures();
    380338                class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    381339                id = 1422;
    382             }
    383             else{
     340            } else {
    384341                id = 1;
    385342            }
     
    390347            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    391348            //id = 1526
    392             if(USE_RELATION_FEATURES){
     349            if (USE_RELATION_FEATURES) {
    393350                RelationFeatures relationFeatures = new RelationFeatures(id);
    394                 relationFeatures.createRelationFeatures(way, relationList);   
     351                relationFeatures.createRelationFeatures(way, relationList);
    395352                id = relationFeatures.getLastID();
    396             }
    397             else {
     353            } else {
    398354                id = geometryFeatures.getLastID();
    399355            }
    400356            //id 1531
    401            
     357
    402358            TextualFeatures textualFeatures;
    403             if(USE_TEXTUAL_FEATURES){
     359            if (USE_TEXTUAL_FEATURES) {
    404360                textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    405361                textualFeatures.createTextualFeatures(way);
    406362            }
    407            
     363
    408364            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
    409365            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    410                        
    411             if(!way.getClassIDs().isEmpty()){
    412                 int i =0;
    413                 for(FeatureNode featureNode : featureNodeList){
     366
     367            if (!way.getClassIDs().isEmpty()) {
     368                int i = 0;
     369                for (FeatureNode featureNode : featureNodeList) {
    414370                    featureNodeArray[i] = featureNode;
    415371                    i++;
    416                 }               
    417                 for(int classID : way.getClassIDs()){
     372                }
     373                for (int classID : way.getClassIDs()) {
    418374                    trainingSetWithUnknown2[k] = featureNodeArray;
    419375                    GROUPS_ARRAY2[k] = classID;
    420                     k++;                   
    421                 }                               
    422             }           
    423         }
    424        
    425         //Linear.enableDebugOutput();
    426         Problem problem = new Problem(); 
    427         problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;//wayListSizeWithoutUnclassified;//wayList.size();
    428         problem.n = numberOfFeatures; //(geometry 105 + textual        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
     376                    k++;
     377                }
     378            }
     379        }
     380
     381        Problem problem = new Problem();
     382        problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;
     383        problem.n = numberOfFeatures;
     384        //(geometry 105 + textual        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
    429385        problem.x = trainingSetWithUnknown2; // feature nodes
    430386        problem.y = GROUPS_ARRAY2; // target values
    431         //SolverType solver = SolverType.MCSVM_CS; //Cramer and Singer for multiclass classification - equivalent of SVMlight
    432387        SolverType solver2 = SolverType.getById(2); //2 -- L2-regularized L2-loss support vector classification (primal)
    433  
     388
    434389        Parameter parameter = new Parameter(solver2, C, eps);
    435         //System.out.println("param set ok");
    436         //System.out.println("number of features: " + vc.getNumOfFeatures());       
    437        
     390
    438391        long start = System.nanoTime();
    439392        System.out.println("training...");
    440393        PrintStream original = System.out;
    441394        System.setOut(new PrintStream(new OutputStream() {
    442            @Override
    443            public void write(int arg0) throws IOException {
    444                
    445            }
     395            @Override
     396            public void write(int arg0) throws IOException {
     397
     398            }
    446399        }));
    447          
     400
    448401        Model model = Linear.train(problem, parameter);
    449402        long end = System.nanoTime();
     
    451404        System.setOut(original);
    452405        System.out.println("training process completed in: " + NANOSECONDS.toSeconds(elapsedTime) + " seconds.");
    453         //System.out.println("trained");
    454        
    455         //decide model path and naming and/or way of deleting/creating 1 or more models.
    456         //File inFile = new File(inputFilePath).getParentFile();
    457        
     406
     407        //decide model path and naming and/or way of deleting/creating 1 or more models.
     408
    458409        File modelFile;
    459         if(USE_CLASS_FEATURES){
     410        if (USE_CLASS_FEATURES) {
    460411            modelFile = new File(modelDirectory.getAbsolutePath()+"/user_" + username + "_model_with_classes_c=" + param);
    461         }
    462         else{
     412        } else {
    463413            modelFile = new File(modelDirectory.getAbsolutePath()+"/user_" + username + "_model_geometries_textual_c=" + param);
    464414        }
    465  
    466         if(modelFile.exists()){
     415
     416        if (modelFile.exists()) {
    467417            modelFile.delete();
    468         }       
     418        }
    469419        try {
    470420            //System.out.println("file created");
    471421            model.save(modelFile);
    472             //System.out.println("saved"); 
     422            //System.out.println("saved");
    473423        } catch (IOException ex) {
    474424            Logger.getLogger(TrainByUser.class.getName()).log(Level.SEVERE, null, ex);
    475425        }
    476426
    477         //test set 
    478         List<OSMWay> testList= new ArrayList<>();
    479         for(int g = c*testSize; g<d*testSize; g++){
     427        //test set
     428        List<OSMWay> testList = new ArrayList<>();
     429        for (int g = c*testSize; g < d*testSize; g++) {
    480430            testList.add(wayList.get(g));
    481             //liblinear test                       
     431            //liblinear test
    482432        }
    483433        System.out.println("testList size: " + testList.size());
    484         int succededInstances=0;
    485         int succededInstances5=0;
    486         int succededInstances10=0;
     434        int succededInstances = 0;
     435        int succededInstances5 = 0;
     436        int succededInstances10 = 0;
    487437        try {
    488438            model = Model.load(modelFile);
     
    493443        int[] labels = model.getLabels();
    494444        Map<Integer, Integer> mapLabelsToIDs = new HashMap<>();
    495         for(int h =0; h < model.getLabels().length; h++){
     445        for (int h = 0; h < model.getLabels().length; h++) {
    496446            mapLabelsToIDs.put(labels[h], h);
    497             //System.out.println(h + "   <->    " + labels[h]);
    498         }
    499        
     447        }
     448
    500449        int wayListSizeWithoutUnclassified2 = testList.size();
    501         for(OSMWay way : testList){
     450        for (OSMWay way : testList) {
    502451
    503452            OSMClassification classifyInstances = new OSMClassification();
    504453            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    505             if(way.getClassIDs().isEmpty()){
    506                 //System.out.println("found unclassified" + way.getClassIDs() + "class: " +way.getClassID());
     454            if (way.getClassIDs().isEmpty()) {
    507455                wayListSizeWithoutUnclassified2 -= 1;
    508                 //u++;
    509             }
    510         }         
    511        
     456            }
     457        }
     458
    512459        FeatureNode[] testInstance2;
    513         for(OSMWay way : testList){
    514            
     460        for (OSMWay way : testList) {
     461
    515462            int id;
    516            
    517             if(USE_CLASS_FEATURES){               
     463
     464            if (USE_CLASS_FEATURES) {
    518465                ClassFeatures class_vector = new ClassFeatures();
    519466                class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    520467                id = 1422;
    521             }
    522             else{
     468            } else {
    523469                id = 1;
    524470            }
    525            
     471
    526472            //pass id also: 1422 if using classes, 1 if not
    527473            GeometryFeatures geometryFeatures = new GeometryFeatures(id);
     
    530476            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    531477            //id = 1526
    532             //System.out.println("id 1526 -> " + geometryFeatures.getLastID());
    533             if(USE_RELATION_FEATURES){
     478            if (USE_RELATION_FEATURES) {
    534479                RelationFeatures relationFeatures = new RelationFeatures(id);
    535                 relationFeatures.createRelationFeatures(way, relationList);       
     480                relationFeatures.createRelationFeatures(way, relationList);
    536481                id = relationFeatures.getLastID();
    537             }
    538             else {
     482            } else {
    539483                id = geometryFeatures.getLastID();
    540                 //System.out.println("geom feat " + id);
    541484            }
    542485            //id 1531
    543             //System.out.println("id 1532 -> " + relationFeatures.getLastID());
    544             if(USE_TEXTUAL_FEATURES){
     486            if (USE_TEXTUAL_FEATURES) {
    545487                TextualFeatures textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    546488                textualFeatures.createTextualFeatures(way);
    547                 //System.out.println("last textual id: " + textualFeatures.getLastID());
    548                 //System.out.println("full:  " + way.getFeatureNodeList());
    549             }
    550             else{
    551                
    552489            }
    553490            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
     
    555492            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    556493
    557             int i =0;
    558             for(FeatureNode featureNode : featureNodeList){
     494            int i = 0;
     495            for (FeatureNode featureNode : featureNodeList) {
    559496                featureNodeArray[i] = featureNode;
    560497                i++;
     
    562499
    563500            testInstance2 = featureNodeArray;
    564             //double prediction = Linear.predict(model, testInstance2);
    565             //System.out.println("test prediction: " + prediction);
    566501            double[] scores = new double[modelLabelSize];
    567502            Linear.predictValues(model, testInstance2, scores);
     
    570505            //iter scores and find 10 max values with their indexes first. then ask those indexes from model.getlabels
    571506            Map<Double, Integer> scoresValues = new HashMap<>();
    572             for(int h = 0; h < scores.length; h++){
    573                 scoresValues.put(scores[h], h);               
     507            for (int h = 0; h < scores.length; h++) {
     508                scoresValues.put(scores[h], h);
    574509                //System.out.println(h + "   <->    " + scores[h]);
    575             }         
     510            }
    576511
    577512            Arrays.sort(scores);
     
    582517            //System.out.println("way labels: " + way.getClassIDs());
    583518            //System.out.println("test prediction: " + prediction);
    584             if(way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])])){
    585                 succededInstances++;             
    586             }
    587             if(
    588                    
    589                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
    590                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
    591                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
    592                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
    593                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])])
    594               ){
     519            if (way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])])) {
     520                succededInstances++;
     521            }
     522            if (
     523
     524                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
     525                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
     526                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
     527                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
     528                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])])
     529                    ) {
    595530                succededInstances5++;
    596531            }
    597             if(
    598                    
    599                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
    600                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
    601                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
    602                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
    603                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])]) ||
    604                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-6])]) ||
    605                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-7])]) ||
    606                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-8])]) ||
    607                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-9])]) ||
    608                 way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-10])])
    609               ){
     532            if (
     533
     534                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-1])]) ||
     535                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-2])]) ||
     536                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-3])]) ||
     537                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-4])]) ||
     538                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-5])]) ||
     539                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-6])]) ||
     540                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-7])]) ||
     541                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-8])]) ||
     542                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-9])]) ||
     543                    way.getClassIDs().contains(labels[scoresValues.get(scores[scores.length-10])])
     544                    ) {
    610545                succededInstances10++;
    611             }
    612             //System.out.println("labels: " + Arrays.toString(model.getLabels()));
    613             //System.out.println("label[0]: " + model.getLabels()[0]);           
    614         }       
    615        
     546            }
     547        }
     548
    616549        System.out.println("Succeeded " + succededInstances + " of " + testList.size() + " total (1 class prediction)");
    617         double precision1 = succededInstances/(double)wayListSizeWithoutUnclassified2;
     550        double precision1 = succededInstances/(double) wayListSizeWithoutUnclassified2;
    618551        score1 = precision1;
    619552        System.out.println(precision1);
    620        
     553
    621554        System.out.println("Succeeded " + succededInstances5 + " of " + testList.size()+ " total (5 class prediction)");
    622         double precision5 = succededInstances5/(double)wayListSizeWithoutUnclassified2;
     555        double precision5 = succededInstances5/(double) wayListSizeWithoutUnclassified2;
    623556        score5 = precision5;
    624557        System.out.println(precision5);
    625        
     558
    626559        System.out.println("Succeeded " + succededInstances10 + " of " + testList.size()+ " total (10 class prediction)");
    627         double precision10 = succededInstances10/(double)wayListSizeWithoutUnclassified2;
     560        double precision10 = succededInstances10/(double) wayListSizeWithoutUnclassified2;
    628561        score10 = precision10;
    629         System.out.println(precision10);               
    630     } 
    631    
    632     private void trainModel(double param){
    633        
     562        System.out.println(precision10);
     563    }
     564
     565    private void trainModel(double param) {
     566
    634567        int wayListSizeWithoutUnclassified = wayList.size();
    635         int u = 0;
    636568        System.out.println("trainList size: " + wayListSizeWithoutUnclassified);
    637         if(wayListSizeWithoutUnclassified == 0){
     569        if (wayListSizeWithoutUnclassified == 0) {
    638570            System.out.println("aborting training process..");
    639571            return;
    640572        }
    641573        //set classes for each osm instance
    642         int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
    643 
    644         //System.out.println("starting classify instances");
    645         for(OSMWay way : wayList){
    646             //setProgress(trainProgress++);
     574        int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
     575
     576        for (OSMWay way : wayList) {
    647577            OSMClassification classifyInstances = new OSMClassification();
    648578            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    649579
    650             if(way.getClassIDs().isEmpty()){
     580            if (way.getClassIDs().isEmpty()) {
    651581                wayListSizeWithoutUnclassified -= 1;
    652                 u++;
    653             }
    654             else {
     582            } else {
    655583                sizeToBeAddedToArray = sizeToBeAddedToArray + way.getClassIDs().size()-1;
    656             }               
    657         } 
     584            }
     585        }
    658586        //System.out.println("end classify instances");
    659         double C = param;       
     587        double C = param;
    660588        double eps = 0.001;
    661         double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];//new double[117558];//               
    662         FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures]; //working[3812];
    663         int k =0;
    664        
    665         //setProgress(trainProgress+5);
    666         for(OSMWay way : wayList){
    667             //adding multiple vectors                     
    668             int id;           
    669             if(USE_CLASS_FEATURES){               
     589        double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];
     590        FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures];
     591        int k = 0;
     592
     593        for (OSMWay way : wayList) {
     594            //adding multiple vectors
     595            int id;
     596            if (USE_CLASS_FEATURES) {
    670597                ClassFeatures class_vector = new ClassFeatures();
    671598                class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    672599                id = 1422;
    673             }
    674             else{
     600            } else {
    675601                id = 1;
    676602            }
     
    681607            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    682608            //id = 1526
    683             if(USE_RELATION_FEATURES){
     609            if (USE_RELATION_FEATURES) {
    684610                RelationFeatures relationFeatures = new RelationFeatures(id);
    685                 relationFeatures.createRelationFeatures(way, relationList);   
     611                relationFeatures.createRelationFeatures(way, relationList);
    686612                id = relationFeatures.getLastID();
    687             }
    688             else {
     613            } else {
    689614                id = geometryFeatures.getLastID();
    690615            }
    691616            //id 1531
    692            
     617
    693618            TextualFeatures textualFeatures;
    694             if(USE_TEXTUAL_FEATURES){
    695                 textualFeatures = new TextualFeatures(id, namesList,languageDetector);
     619            if (USE_TEXTUAL_FEATURES) {
     620                textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    696621                textualFeatures.createTextualFeatures(way);
    697622            }
    698            
     623
    699624            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
    700625            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    701                        
    702             if(!way.getClassIDs().isEmpty()){
    703                 int i =0;
    704                 for(FeatureNode featureNode : featureNodeList){
     626
     627            if (!way.getClassIDs().isEmpty()) {
     628                int i = 0;
     629                for (FeatureNode featureNode : featureNodeList) {
    705630                    featureNodeArray[i] = featureNode;
    706631                    i++;
    707                 }               
    708                 for(int classID : way.getClassIDs()){
     632                }
     633                for (int classID : way.getClassIDs()) {
    709634                    trainingSetWithUnknown2[k] = featureNodeArray;
    710635                    GROUPS_ARRAY2[k] = classID;
    711                     k++;                   
    712                 }                               
    713             }           
    714         }
    715         //System.out.println("feature construction completed.");
    716         //Linear.enableDebugOutput();
    717         Problem problem = new Problem(); 
    718         problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;//wayListSizeWithoutUnclassified;//wayList.size();
    719         problem.n = numberOfFeatures;//3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
     636                    k++;
     637                }
     638            }
     639        }
     640        Problem problem = new Problem();
     641        problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;
     642        problem.n = numberOfFeatures;
     643        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
    720644        problem.x = trainingSetWithUnknown2; // feature nodes
    721645        problem.y = GROUPS_ARRAY2; // target values
    722         //SolverType solver = SolverType.MCSVM_CS; //Cramer and Singer for multiclass classification - equivalent of SVMlight
    723646        SolverType solver2 = SolverType.getById(2); //2 -- L2-regularized L2-loss support vector classification (primal)
    724  
     647
    725648        Parameter parameter = new Parameter(solver2, C, eps);
    726         //System.out.println("param set ok");
    727         //System.out.println("number of features: " + vc.getNumOfFeatures());       
    728        
     649
    729650        long start = System.nanoTime();
    730651        System.out.println("training...");
    731652        PrintStream original = System.out;
    732653        System.setOut(new PrintStream(new OutputStream() {
    733 
    734            @Override
    735            public void write(int arg0) throws IOException {
    736 
    737            }
    738         }));     
    739        
    740        
     654            @Override
     655            public void write(int arg0) throws IOException {
     656
     657            }
     658        }));
     659
     660
    741661        Model model = Linear.train(problem, parameter);
    742662        long end = System.nanoTime();
     
    744664        System.setOut(original);
    745665        System.out.println("training process completed in: " + NANOSECONDS.toSeconds(elapsedTime) + " seconds.");
    746         //System.out.println("trained");
    747        
    748         //decide model path and naming and/or way of deleting/creating 1 or more models.
    749         //File inFile = new File(inputFilePath).getParentFile();
    750        
     666
     667        //decide model path and naming and/or way of deleting/creating 1 or more models.
     668
    751669        File modelFile = new File(modelDirectory.getAbsolutePath()+"/best_model"); //decide path of models
    752        
     670
    753671        File customModelFile;
    754         if(topKIsSelected){
    755             customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model_c" + param + "_topK" + topK + "user" + username + ".0");
    756         }
    757         else{
    758             customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model_c" + param + "_maxF" + frequency + "user" + username + ".0");
    759         }
    760        
    761         if(modelFile.exists()){
     672        if (topKIsSelected) {
     673            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" +
     674                    inputFileName + "_model_c" + param + "_topK" + topK + "user" + username + ".0");
     675        } else {
     676            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" +
     677                    inputFileName + "_model_c" + param + "_maxF" + frequency + "user" + username + ".0");
     678        }
     679
     680        if (modelFile.exists()) {
    762681            modelFile.delete();
    763         } 
    764         if(customModelFile.exists()){
     682        }
     683        if (customModelFile.exists()) {
    765684            customModelFile.delete();
    766         }         
     685        }
    767686        try {
    768             //System.out.println("file created");
    769687            model.save(modelFile);
    770688            model.save(customModelFile);
    771             System.out.println("model saved at: " + modelFile); 
     689            System.out.println("model saved at: " + modelFile);
    772690            System.out.println("custom model saved at: " + customModelFile);
    773691        } catch (IOException ex) {
    774692            Logger.getLogger(TrainByUser.class.getName()).log(Level.SEVERE, null, ex);
    775         }       
    776     }
    777    
    778     private void trainModelWithClasses(double param){
    779        
     693        }
     694    }
     695
     696    private void trainModelWithClasses(double param) {
     697
    780698        int wayListSizeWithoutUnclassified = wayList.size();
    781         int u = 0;
    782699        System.out.println("trainList size: " + wayListSizeWithoutUnclassified);
    783        
    784         if(wayListSizeWithoutUnclassified == 0){
     700
     701        if (wayListSizeWithoutUnclassified == 0) {
    785702            System.out.println("aborting training process with classes..");
    786703            return;
    787704        }
    788705        //set classes for each osm instance
    789         int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
    790         //int lalala = 0;
    791         //setProgress(trainProgress-10);
    792         for(OSMWay way : wayList){
    793             //setProgress(trainProgress++);
     706        int sizeToBeAddedToArray = 0; //this will be used to proper init the features array, adding the multiple vectors size
     707        for (OSMWay way : wayList) {
    794708            OSMClassification classifyInstances = new OSMClassification();
    795709            classifyInstances.calculateClasses(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    796710
    797             if(way.getClassIDs().isEmpty()){
     711            if (way.getClassIDs().isEmpty()) {
    798712                wayListSizeWithoutUnclassified -= 1;
    799                 u++;
    800             }
    801             else {
     713            } else {
    802714                sizeToBeAddedToArray = sizeToBeAddedToArray + way.getClassIDs().size()-1;
    803             }               
    804         } 
    805         double C = param;       
     715            }
     716        }
     717        double C = param;
    806718        double eps = 0.001;
    807         double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];//new double[117558];//               
    808         FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures+1422]; //working[3812];
    809         int k =0;
    810        
    811         //setProgress(trainProgress+5);
    812         for(OSMWay way : wayList){
    813             //adding multiple vectors                     
    814             int id;           
    815             //if(USE_CLASS_FEATURES){               
    816                 ClassFeatures class_vector = new ClassFeatures();
    817                 class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
    818                 id = 1422;
    819 //            }
    820 //            else{
    821 //                id = 1;
    822 //            }
     719        double[] GROUPS_ARRAY2 = new double[wayListSizeWithoutUnclassified+sizeToBeAddedToArray];
     720        FeatureNode[][] trainingSetWithUnknown2 = new FeatureNode[wayListSizeWithoutUnclassified+sizeToBeAddedToArray][numberOfFeatures+1422];
     721        int k = 0;
     722
     723        for (OSMWay way : wayList) {
     724            //adding multiple vectors
     725            int id;
     726            ClassFeatures class_vector = new ClassFeatures();
     727            class_vector.createClassFeatures(way, mappings, mapperWithIDs, indirectClasses, indirectClassesWithIDs);
     728            id = 1422;
    823729            //pass id also: 1422 if using classes, 1 if not
    824730            GeometryFeatures geometryFeatures = new GeometryFeatures(id);
     
    827733            //id after geometry, cases: all geometry features with mean-variance boolean intervals:
    828734            //id = 1526
    829             if(USE_RELATION_FEATURES){
     735            if (USE_RELATION_FEATURES) {
    830736                RelationFeatures relationFeatures = new RelationFeatures(id);
    831                 relationFeatures.createRelationFeatures(way, relationList);   
     737                relationFeatures.createRelationFeatures(way, relationList);
    832738                id = relationFeatures.getLastID();
    833             }
    834             else {
     739            } else {
    835740                id = geometryFeatures.getLastID();
    836741            }
    837742            //id 1531
    838            
     743
    839744            TextualFeatures textualFeatures;
    840             if(USE_TEXTUAL_FEATURES){
    841                 textualFeatures = new TextualFeatures(id, namesList,languageDetector);
     745            if (USE_TEXTUAL_FEATURES) {
     746                textualFeatures = new TextualFeatures(id, namesList, languageDetector);
    842747                textualFeatures.createTextualFeatures(way);
    843748            }
    844            
     749
    845750            List<FeatureNode> featureNodeList = way.getFeatureNodeList();
    846751            FeatureNode[] featureNodeArray = new FeatureNode[featureNodeList.size()];
    847                        
    848             if(!way.getClassIDs().isEmpty()){
    849                 int i =0;
    850                 for(FeatureNode featureNode : featureNodeList){
     752
     753            if (!way.getClassIDs().isEmpty()) {
     754                int i = 0;
     755                for (FeatureNode featureNode : featureNodeList) {
    851756                    featureNodeArray[i] = featureNode;
    852757                    i++;
    853                 }               
    854                 for(int classID : way.getClassIDs()){
    855                     //lalala++;
     758                }
     759                for (int classID : way.getClassIDs()) {
    856760                    trainingSetWithUnknown2[k] = featureNodeArray;
    857761                    GROUPS_ARRAY2[k] = classID;
    858                     k++;                   
    859                 }                               
    860             }           
    861         } 
    862        
    863         //Linear.enableDebugOutput();
    864         Problem problem = new Problem(); 
    865         problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;//wayListSizeWithoutUnclassified;//wayList.size();
    866         problem.n = numberOfFeatures+1422;//3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
     762                    k++;
     763                }
     764            }
     765        }
     766
     767        Problem problem = new Problem();
     768        problem.l = wayListSizeWithoutUnclassified+sizeToBeAddedToArray;
     769        problem.n = numberOfFeatures+1422;
     770        //3797; // number of features //the largest index of all features //3811;//3812 //1812 with classes
    867771        problem.x = trainingSetWithUnknown2; // feature nodes
    868772        problem.y = GROUPS_ARRAY2; // target values
    869         //SolverType solver = SolverType.MCSVM_CS; //Cramer and Singer for multiclass classification - equivalent of SVMlight
    870773        SolverType solver2 = SolverType.getById(2); //2 -- L2-regularized L2-loss support vector classification (primal)
    871  
     774
    872775        Parameter parameter = new Parameter(solver2, C, eps);
    873         //System.out.println("param set ok");
    874         //System.out.println("number of features: " + vc.getNumOfFeatures());       
    875        
     776
    876777        long start = System.nanoTime();
    877778        System.out.println("training...");
    878779        PrintStream original = System.out;
    879780        System.setOut(new PrintStream(new OutputStream() {
    880 
    881            @Override
    882            public void write(int arg0) throws IOException {
    883 
    884            }
    885         }));     
    886        
    887        
     781            @Override
     782            public void write(int arg0) throws IOException {
     783
     784            }
     785        }));
     786
    888787        Model model = Linear.train(problem, parameter);
    889788        long end = System.nanoTime();
     
    891790        System.setOut(original);
    892791        System.out.println("training process completed in: " + NANOSECONDS.toSeconds(elapsedTime) + " seconds.");
    893         //System.out.println("trained");
    894        
    895         //decide model path and naming and/or way of deleting/creating 1 or more models.
    896         //File inFile = new File(inputFilePath).getParentFile();
    897        
    898         File modelFile = new File(modelDirectory.getAbsolutePath()+"/model_with_classes");
     792
     793        //decide model path and naming and/or way of deleting/creating 1 or more models.
     794
     795        File modelFile = new File(modelDirectory.getAbsolutePath()+"/model_with_classes");
    899796        File customModelFile;
    900         if(topKIsSelected){
    901             customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model_c" + param + "_topK" + topK + "user" + username + ".1");
    902         }
    903         else{
    904             customModelFile = new File(modelDirectory.getAbsolutePath()+"/" + inputFileName + "_model_c" + param + "_maxF" + frequency + "user" + username + ".1");
    905         }
    906 
    907         if(customModelFile.exists()){
     797        if (topKIsSelected) {
     798            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" +
     799                    inputFileName + "_model_c" + param + "_topK" + topK + "user" + username + ".1");
     800        } else {
     801            customModelFile = new File(modelDirectory.getAbsolutePath()+"/" +
     802                    inputFileName + "_model_c" + param + "_maxF" + frequency + "user" + username + ".1");
     803        }
     804
     805        if (customModelFile.exists()) {
    908806            customModelFile.delete();
    909         }       
    910         if(modelFile.exists()){
     807        }
     808        if (modelFile.exists()) {
    911809            modelFile.delete();
    912         }       
     810        }
    913811        try {
    914             //System.out.println("file created");
    915812            model.save(modelFile);
    916813            model.save(customModelFile);
    917             System.out.println("model with classes saved at: " + modelFile); 
     814            System.out.println("model with classes saved at: " + modelFile);
    918815            System.out.println("custom model with classes saved at: " + customModelFile);
    919816        } catch (IOException ex) {
    920817            Logger.getLogger(TrainByUser.class.getName()).log(Level.SEVERE, null, ex);
    921         } 
    922     }
    923    
    924     private static void clearDataset(){
    925         for(OSMWay way : wayList){
     818        }
     819    }
     820
     821    private static void clearDataset() {
     822        for (OSMWay way : wayList) {
    926823            way.getFeatureNodeList().clear();
    927824        }
    928     } 
    929    
     825    }
     826
    930827    private void readTextualFromDefaultList(InputStream textualFileStream) {
    931                  
     828
    932829        TextualStatistics textualStatistics = new TextualStatistics();
    933830        textualStatistics.parseTextualList(textualFileStream);
    934831        namesList = textualStatistics.getTextualList();
    935  
    936     }
    937 
    938     private static void writeTextualListToFile(String filePath, List<Map.Entry<String, Integer>> textualList)
    939     {
    940        
    941         try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"))) {           
    942             for(Map.Entry<String, Integer> entry : textualList){
     832
     833    }
     834
     835    private static void writeTextualListToFile(String filePath, List<Map.Entry<String, Integer>> textualList) {
     836        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"))) {
     837            for (Map.Entry<String, Integer> entry : textualList) {
    943838                writer.write(entry.getKey());
    944839                writer.newLine();
     
    951846        } catch (IOException ex) {
    952847            Logger.getLogger(TrainByUser.class.getName()).log(Level.SEVERE, null, ex);
    953         }       
    954     }
    955    
     848        }
     849    }
     850
    956851    @Override
    957852    protected void done() {
     
    960855            firePropertyChange("progress", getProgress(), 100);
    961856            setProgress(100);
    962         }
    963         catch (InterruptedException | ExecutionException ignore) {
     857        } catch (InterruptedException | ExecutionException ignore) {
    964858            System.out.println("Exception: " + ignore);
    965859        }
    966     }     
    967    
     860    }
     861
    968862    @Override
    969863    public void actionPerformed(ActionEvent ae) {
    970864        //cancel button, end process after clearing Dataset
    971     }   
     865    }
    972866}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/personalization/UserDataExtractAndTrainWorker.java

    r31441 r32404  
     1// License: GPL. For details, see LICENSE file.
    12package org.openstreetmap.josm.plugins.osmrec.personalization;
    23
     
    1112import java.util.List;
    1213import java.util.TimeZone;
     14
    1315import javax.swing.SwingWorker;
    14 import org.openstreetmap.josm.plugins.container.OSMWay;
    15 import org.openstreetmap.josm.plugins.extractor.LanguageDetector;
    16 import org.openstreetmap.josm.plugins.parsers.OSMParser;
     16
     17import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
     18import org.openstreetmap.josm.plugins.osmrec.extractor.LanguageDetector;
     19import org.openstreetmap.josm.plugins.osmrec.parsers.OSMParser;
    1720
    1821/**
    1922 * Extracts user information about history edits or by area and initiates the training process based on that user.
    20  * 
     23 *
    2124 * @author imis-nkarag
    2225 */
    2326
    24 public class UserDataExtractAndTrainWorker extends SwingWorker<Void, Void> implements ActionListener{
    25    
     27public class UserDataExtractAndTrainWorker extends SwingWorker<Void, Void> implements ActionListener {
     28
    2629    private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    2730    private static final ArrayList<String> timeIntervals = new ArrayList<>();
     
    3841    private final LanguageDetector languageDetector;
    3942    private int userTrainProgress = 0;
    40    
    41     public UserDataExtractAndTrainWorker(String inputFilePath, String username, Integer days, boolean byArea, boolean validateFlag, 
    42             double cParameterFromUser, int topK, int frequency, boolean topKIsSelected, LanguageDetector languageDetector){
    43        
     43
     44    public UserDataExtractAndTrainWorker(String inputFilePath, String username, Integer days, boolean byArea, boolean validateFlag,
     45            double cParameterFromUser, int topK, int frequency, boolean topKIsSelected, LanguageDetector languageDetector) {
     46
    4447        this.inputFilePath = inputFilePath;
    4548        this.username = username;
     
    5053        this.topK = topK;
    5154        this.frequency = frequency;
    52         this.topKIsSelected = topKIsSelected; 
     55        this.topKIsSelected = topKIsSelected;
    5356        this.languageDetector = languageDetector;
    54        
     57
    5558    }
    56    
     59
    5760    @Override
    5861    protected Void doInBackground() throws Exception {
    59        
     62
    6063        System.out.println("UserDataExtractAndTrainWorker doInBackground initiating..");
    61         if(byArea){
    62            extractByArea();
     64        if (byArea) {
     65            extractByArea();
     66        } else {
     67            extractHistory();
    6368        }
    64         else{
    65            extractHistory();
    66         }
    67        
    68         TrainByUser trainByUser = new TrainByUser(inputFilePath, username, validateFlag,
     69
     70        TrainByUser trainByUser = new TrainByUser(inputFilePath, username, validateFlag,
    6971                cParameterFromUser, topK, frequency, topKIsSelected, languageDetector, wayList);
    7072
    7173        System.out.println("trainByUser executing..");
    7274        trainByUser.addPropertyChangeListener(new PropertyChangeListener() {
    73                            
    74             @Override 
     75
     76            @Override
    7577            public void propertyChange(PropertyChangeEvent evt) {
    76                 if("progress".equals(evt.getPropertyName())) {
     78                if ("progress".equals(evt.getPropertyName())) {
    7779                    int progress = (Integer) evt.getNewValue();
    7880                    System.out.println("progress++ from property change listener, progress: " + progress);
    7981                    setProgress(progress);
    80                    
     82
    8183                }
    82             }                                                 
    83         });
    84        
    85        
    86        
    87        
    88        
     84            }
     85        });
     86
    8987        trainByUser.doInBackground();
    9088        setProgress(100);
    9189        return null;
    9290    }
    93    
     91
    9492    private void extractHistory() {
    95         if(wayList != null){
     93        if (wayList != null) {
    9694            wayList.clear();
    9795        }
    98        
     96
    9997        produceTimeIntervals(days);
    10098        HistoryParser historyParser = new HistoryParser(username);
    101        
    102         for(String time : timeIntervals){
     99
     100        for (String time : timeIntervals) {
    103101            System.out.println("interval\n " + time);
    104102            historyParser.historyParse(time);
     
    106104        wayList = historyParser.getWayList();
    107105    }
    108    
     106
    109107    private void extractByArea() {
    110108        System.out.println("Extracting by Area..");
    111109
    112         if(wayList != null){
     110        if (wayList != null) {
    113111            wayList.clear();
    114112        }
    115         //System.out.println("wayList cleared.");
    116        
     113
    117114        OSMParser osmParser = new OSMParser(inputFilePath);
    118115        osmParser.parseDocument();
    119116
    120         //System.out.println("OSMParser done.");
    121        
    122117        List<OSMWay> completeWayList = osmParser.getWayList();
    123118        System.out.println("completeWayList size: " + completeWayList.size());
    124119        System.out.println("populating wayList with edits from username: " + username);
    125         for(OSMWay way : completeWayList){
     120        for (OSMWay way : completeWayList) {
    126121            //System.out.println("current way user: " + way.getUser());
    127             if(way.getUser().equals(username)){
     122            if (way.getUser().equals(username)) {
    128123                System.out.println("found user edit!");
    129124                wayList.add(way);
    130             }           
    131         } 
     125            }
     126        }
    132127        System.out.println("weeding wayList by user done.");
    133         if(wayList.isEmpty()){
     128        if (wayList.isEmpty()) {
    134129            System.out.println("User has not edited this Area. Try \"By time\" option.");
    135         }
    136         else{
     130        } else {
    137131            System.out.println("User has edited " + wayList.size() + " OSM entities in this area.");
    138132        }
    139     }   
    140    
     133    }
     134
    141135    private void produceTimeIntervals(Integer days) {
    142136
     
    144138        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    145139
    146         Date currentDate = new Date();       
     140        Date currentDate = new Date();
    147141        Calendar cal = Calendar.getInstance();
    148142
    149143        cal.setTime(currentDate);
    150144        String currentTimeString = sdf.format(currentDate);
    151        
     145
    152146        cal.add(Calendar.DATE, -days); //starting date
    153147        Date startingTime = cal.getTime();
    154        
     148
    155149        String startingTimeString = sdf.format(startingTime);
    156         //System.out.println("starting date: " + startingTimeString);
    157         //add to list
    158        
     150        //add to list
     151
    159152        String nextIntervalTime = startingTimeString;
    160        
    161         //do, while date is before current date,after the addition of the 10 days       
     153
     154        //do, while date is before current date,after the addition of the 10 days
    162155        do {
    163156            cal.add(Calendar.DATE, 10);
    164            
     157
    165158            Date intervalTime = cal.getTime();
    166159            String intervalTimeString = sdf.format(intervalTime);
    167             String timeOsmApiArgument = nextIntervalTime + "," + intervalTimeString;       
    168            
    169             if(cal.getTime().after(currentDate)){
     160            String timeOsmApiArgument = nextIntervalTime + "," + intervalTimeString;
     161
     162            if (cal.getTime().after(currentDate)) {
    170163                //add the offset of remaining days as last interval
    171164                timeOsmApiArgument = nextIntervalTime + "," + currentTimeString;
     
    173166                System.out.println(timeOsmApiArgument);
    174167                break;
    175             }
    176             else{
     168            } else {
    177169                timeIntervals.add(timeOsmApiArgument);
    178170            }
    179171            nextIntervalTime = intervalTimeString;
    180172            System.out.println(" ti: " + timeOsmApiArgument);
    181         } while(cal.getTime().before(currentDate));
     173        } while (cal.getTime().before(currentDate));
    182174    }
    183175
     
    185177    public void actionPerformed(ActionEvent ae) {
    186178        //this.firePropertyChange("progress", userTrainProgress, userTrainProgress+10);
    187 //        if(userTrainProgress <100){
    188 //            setProgress(userTrainProgress+10);
    189 //        }
    190        
     179        //        if (userTrainProgress <100) {
     180        //            setProgress(userTrainProgress+10);
     181        //        }
     182
    191183    }
    192184}
Note: See TracChangeset for help on using the changeset viewer.