├── .gitattributes ├── .gitignore ├── ex.log ├── files ├── Code notes.txt └── blank tile.png ├── libs ├── jsi-1.1.0-javadoc.jar ├── jsi-1.1.0-sources.jar ├── jsi-1.1.0.jar └── unfolding.0.9.6.jar ├── pom.xml ├── run_evaluation_scalability_Synthetic.sh ├── run_full_evaluation.sh ├── run_full_global.sh ├── run_full_inference.sh ├── run_inference_scalability_Synthetic.sh ├── run_matching_Beijing-All-Map.sh ├── run_matching_Beijing-Compression.sh ├── run_matching_Beijing-M-Synthetic.sh ├── run_matching_Beijing-M.sh ├── run_matching_Beijing-Varying-SamplingRate.sh ├── run_matching_CandidateRange.sh ├── run_matching_on-sco-parameter-tunning.sh ├── run_matching_threads.sh └── src ├── __init__.py └── main ├── __init__.py ├── java ├── algorithm │ ├── cooptimization │ │ ├── CoOptimization.java │ │ ├── CoOptimizationFunc.java │ │ ├── CoOptimizationMain.java │ │ └── TrajectoryIndex.java │ ├── mapinference │ │ ├── MapInferenceMain.java │ │ ├── kde │ │ │ └── KDEMapInference.java │ │ ├── lineclustering │ │ │ ├── Cluster.java │ │ │ ├── DouglasPeuckerFilter.java │ │ │ ├── LineClusteringMapInference.java │ │ │ └── pcurves │ │ │ │ ├── AWT │ │ │ │ ├── ChoiceLabelPanel.java │ │ │ │ ├── ColorChoice.java │ │ │ │ ├── ScrollbarLabelPanel.java │ │ │ │ └── ScrollbarTextFieldPanel.java │ │ │ │ ├── CRoutines │ │ │ │ ├── LinearAlgebra_VektorDD.h │ │ │ │ ├── MakefilePrincipalCurves │ │ │ │ ├── Utilities_MyMath.h │ │ │ │ ├── jni.h │ │ │ │ ├── linearAlgebra.c │ │ │ │ └── utilities.c │ │ │ │ ├── Debug │ │ │ │ ├── Debug.java │ │ │ │ └── DebugEvent.java │ │ │ │ ├── Internet │ │ │ │ ├── DownLoadDialog.java │ │ │ │ ├── DownLoadFile.java │ │ │ │ ├── EmailFile.java │ │ │ │ ├── UpLoadFile.java │ │ │ │ └── UpLoadFileOffline.java │ │ │ │ ├── LinearAlgebra │ │ │ │ ├── CovarianceMatrix.java │ │ │ │ ├── CovarianceMatrix2D.java │ │ │ │ ├── Curve.java │ │ │ │ ├── GraphAbstract.java │ │ │ │ ├── Line.java │ │ │ │ ├── LineAbstract.java │ │ │ │ ├── LineObject.java │ │ │ │ ├── LineSegment.java │ │ │ │ ├── LineSegmentAbstract.java │ │ │ │ ├── LineSegmentObject.java │ │ │ │ ├── Loadable.java │ │ │ │ ├── OnlineSampleStatistics.java │ │ │ │ ├── OnlineSampleStatisticsDegreeOne.java │ │ │ │ ├── OnlineSampleStatisticsDegreeTwo.java │ │ │ │ ├── OnlineSampleStatisticsWeight.java │ │ │ │ ├── Sample.java │ │ │ │ ├── Sample2D.java │ │ │ │ ├── Sample2DWeighted.java │ │ │ │ ├── SampleLoadable.java │ │ │ │ ├── SampleWithOnlineStatistics.java │ │ │ │ ├── SampleWithOnlineStatisticsDegreeTwo.java │ │ │ │ ├── Vektor.java │ │ │ │ ├── Vektor2D.java │ │ │ │ ├── Vektor2DWeighted.java │ │ │ │ ├── VektorObject.java │ │ │ │ └── Weighted.java │ │ │ │ ├── Optimize │ │ │ │ ├── Optimizable.java │ │ │ │ └── Optimizer.java │ │ │ │ ├── PostScript │ │ │ │ ├── PostScriptDocument.java │ │ │ │ └── PostScriptSetupDialog.java │ │ │ │ ├── PrincipalCurve │ │ │ │ ├── PrincipalCurveAlgorithm.java │ │ │ │ ├── PrincipalCurveAlgorithmThread.java │ │ │ │ ├── PrincipalCurveClass.java │ │ │ │ ├── PrincipalCurveParameters.java │ │ │ │ ├── PrincipalCurveSampleVektor.java │ │ │ │ ├── SetOfCurves.java │ │ │ │ └── Vertex │ │ │ │ │ ├── CornerVertex.java │ │ │ │ │ ├── DummyVertex.java │ │ │ │ │ ├── Elements │ │ │ │ │ ├── Edge.java │ │ │ │ │ ├── EdgeDirection.java │ │ │ │ │ ├── ElementInitializationException.java │ │ │ │ │ ├── ElementVertex.java │ │ │ │ │ ├── EndVertexOfThree.java │ │ │ │ │ ├── EndVertexOfTwo.java │ │ │ │ │ ├── EndVertexOfY.java │ │ │ │ │ ├── HasOneEdge.java │ │ │ │ │ ├── HasTwoSymmetricEdges.java │ │ │ │ │ ├── MiddleVertexOfFive.java │ │ │ │ │ ├── MiddleVertexOfFour.java │ │ │ │ │ ├── MiddleVertexOfMany.java │ │ │ │ │ ├── MiddleVertexOfThree.java │ │ │ │ │ ├── NumeratorAndDenominator.java │ │ │ │ │ ├── PenaltyCoefficients.java │ │ │ │ │ └── Vertex.java │ │ │ │ │ ├── EndVertex.java │ │ │ │ │ ├── JoinVertex.java │ │ │ │ │ ├── LineVertex.java │ │ │ │ │ ├── RegularVertex.java │ │ │ │ │ ├── StarOfFourVertex.java │ │ │ │ │ ├── StarOfManyVertex.java │ │ │ │ │ ├── StarOfThreeVertex.java │ │ │ │ │ ├── TVertex.java │ │ │ │ │ ├── TwoOppositeEdgeIndexesException.java │ │ │ │ │ ├── XVertex.java │ │ │ │ │ └── YVertex.java │ │ │ │ ├── PrincipalCurveGenerator.java │ │ │ │ └── Utilities │ │ │ │ ├── AppletButton.java │ │ │ │ ├── Environment.java │ │ │ │ ├── Misc.java │ │ │ │ └── MyMath.java │ │ ├── pointclustering │ │ │ └── KharitaMapInference.java │ │ ├── roadrunner │ │ │ └── RoadRunnerMapInference.java │ │ ├── topicmodel │ │ │ └── CRIFMapInference.java │ │ └── tracemerge │ │ │ ├── EdgeTM.java │ │ │ ├── LineTM.java │ │ │ ├── TraceMergeMapInference.java │ │ │ └── VertexTM.java │ ├── mapmatching │ │ ├── MapMatchingMain.java │ │ ├── MapMatchingMethod.java │ │ ├── hmm │ │ │ ├── Distributions.java │ │ │ ├── ForwardBackwardAlgorithm.java │ │ │ ├── HMMMapMatching.java │ │ │ ├── HMMProbabilities.java │ │ │ ├── HMMUtils.java │ │ │ ├── RoadPath.java │ │ │ ├── SequenceState.java │ │ │ ├── TimeStep.java │ │ │ ├── Transition.java │ │ │ └── ViterbiAlgorithm.java │ │ ├── mht │ │ │ └── MHTMapMatching.java │ │ ├── simpleHMM │ │ │ ├── Minset.java │ │ │ ├── SequenceMemory.java │ │ │ ├── SimpleHMMMatching.java │ │ │ ├── StateCandidate.java │ │ │ ├── StateMemory.java │ │ │ ├── StateSample.java │ │ │ └── StateTransition.java │ │ ├── stmatching │ │ │ └── FeatureSTMapMatching.java │ │ └── weightBased │ │ │ ├── Utilities.java │ │ │ └── WeightBasedMapMatching.java │ └── mapmerge │ │ └── MapMerge.java ├── evaluation │ ├── mapevaluation │ │ ├── MapInferenceEvaluationMain.java │ │ ├── MeasureEvaluationMain.java │ │ ├── graphmatching │ │ │ └── GraphMatchingMapEvaluation.java │ │ ├── graphsampling │ │ │ └── GraphSamplingMapEvaluation.java │ │ └── pathbaseddistance │ │ │ ├── benchmarkexperiments │ │ │ └── PathBasedMapEvaluation.java │ │ │ ├── generatepaths │ │ │ └── GeneratePaths.java │ │ │ ├── mapmatching │ │ │ ├── HausdorffDistance.java │ │ │ └── MapMatching.java │ │ │ └── mapmatchingbasics │ │ │ ├── IntervalComparator.java │ │ │ ├── IntervalComparatorEdge.java │ │ │ ├── PBDEdge.java │ │ │ ├── PBDLine.java │ │ │ ├── PBDVertex.java │ │ │ └── PathLabelComparator.java │ └── matchingevaluation │ │ ├── MapMatchingEvaluationMain.java │ │ ├── PointMatchingEvaluation.java │ │ └── RouteMatchingEvaluation.java ├── preprocessing │ ├── MapGenerator.java │ ├── MapPreprocessing.java │ ├── PreprocessingMain.java │ ├── PreprocessingStatistics.java │ ├── StatisticsMain.java │ └── TrajectoryGenerator.java ├── test │ ├── TempWorkMain.java │ └── TestMain.java └── util │ ├── dijkstra │ ├── MinPriorityQueue.java │ ├── RoutingEdge.java │ ├── RoutingGraph.java │ └── RoutingVertex.java │ ├── exceptions │ ├── DistanceFunctionException.java │ ├── SpatialObjectConstructionException.java │ ├── SpatialQueryException.java │ └── SpatialRelationException.java │ ├── function │ ├── Decimal.java │ ├── DistanceFunction.java │ ├── EuclideanDistanceFunction.java │ ├── GreatCircleDistanceFunction.java │ ├── HausdorffDistanceFunction.java │ ├── SpatialUtils.java │ └── VectorDistanceFunction.java │ ├── index │ ├── SpatialDataStructure.java │ ├── SpatialIndexModel.java │ ├── SpatialPartition.java │ ├── SpatialQuery.java │ ├── grid │ │ ├── Grid.java │ │ ├── GridModel.java │ │ └── GridPartition.java │ └── rtree │ │ ├── RTreeIndexing.java │ │ ├── RTreeModel.java │ │ ├── STRNode.java │ │ └── STRTree.java │ ├── io │ ├── BeijingMapLoader.java │ ├── BeijingTrajectoryLoader.java │ ├── GlobalMapLoader.java │ ├── GlobalTrajectoryLoader.java │ ├── IOService.java │ ├── MapMatchingReader.java │ ├── MapReader.java │ ├── MapWriter.java │ ├── MatchResultReader.java │ ├── MatchResultWriter.java │ ├── OSMMapLoader.java │ ├── OSMTrajectoryLoader.java │ ├── TrajectoryReader.java │ └── TrajectoryWriter.java │ ├── ml │ └── libsvm │ │ ├── TrainAndTestByLibSVM.java │ │ ├── svm.java │ │ ├── svm.m4 │ │ ├── svm_model.java │ │ ├── svm_node.java │ │ ├── svm_parameter.java │ │ ├── svm_print_interface.java │ │ └── svm_problem.java │ ├── object │ ├── roadnetwork │ │ ├── RoadNetworkGraph.java │ │ ├── RoadNetworkPrimitive.java │ │ ├── RoadNode.java │ │ └── RoadWay.java │ ├── spatialobject │ │ ├── Circle.java │ │ ├── ComplexSpatialObject.java │ │ ├── Point.java │ │ ├── Polygon.java │ │ ├── Rect.java │ │ ├── Segment.java │ │ ├── SimpleSpatialObject.java │ │ ├── SpatialObject.java │ │ ├── SpatialTemporalObject.java │ │ ├── Trajectory.java │ │ ├── TrajectoryPoint.java │ │ └── TrajectorySegment.java │ └── structure │ │ ├── InverselyComparableObject.java │ │ ├── LengthObject.java │ │ ├── MatchResultWithUnmatchedTraj.java │ │ ├── MultipleTrajectoryMatchResult.java │ │ ├── Pair.java │ │ ├── PointMatch.java │ │ ├── Route.java │ │ ├── SegmentWithIndex.java │ │ ├── SimpleTrajectoryMatchResult.java │ │ ├── Triplet.java │ │ └── XYObject.java │ ├── settings │ ├── BaseProperty.java │ ├── CoOptimizationProperty.java │ ├── MapInferenceProperty.java │ ├── MapMatchingProperty.java │ ├── MapServiceLogger.java │ └── PreprocessingProperty.java │ └── visualization │ ├── BlankMap.java │ ├── UnfoldingBeijingMapDisplay.java │ └── VisualizationMain.java ├── python ├── __init__.py ├── crif │ ├── README.md │ ├── matcher │ │ ├── .ipynb_checkpoints │ │ │ └── 3.30 Matcher for Deep Learning-checkpoint.ipynb │ │ ├── __init__.py │ │ ├── gpsmatcher.py │ │ ├── graphdb_matcher.py │ │ ├── graphdb_matcher_run.py │ │ ├── matcher.py │ │ ├── mathfunclib.py │ │ ├── pylibs │ │ │ ├── __init__.py │ │ │ ├── mathfunclib.py │ │ │ └── spatialfunclib.py │ │ ├── spatialfunclib.py │ │ ├── streetmap.py │ │ ├── train.py │ │ └── viterbi.py │ ├── mymap │ │ ├── db.sqlite3 │ │ ├── mainapp │ │ │ ├── __init__.py │ │ │ ├── admin.py │ │ │ ├── migrations │ │ │ │ └── __init__.py │ │ │ ├── models.py │ │ │ ├── templates │ │ │ │ └── mainapp │ │ │ │ │ └── index.html │ │ │ ├── tests.py │ │ │ ├── urls.py │ │ │ └── views.py │ │ ├── manage.py │ │ └── mymap │ │ │ ├── __init__.py │ │ │ ├── settings.py │ │ │ ├── urls.py │ │ │ └── wsgi.py │ ├── src │ │ ├── .log │ │ ├── __init__.py │ │ ├── biagioni.py │ │ ├── bitlist.py │ │ ├── coordTransform_utils.py │ │ ├── gis.py │ │ ├── mf.py │ │ ├── plot.py │ │ ├── plsa │ │ │ ├── README │ │ │ ├── __init__.py │ │ │ ├── _plsa.c │ │ │ ├── _plsa.so │ │ │ ├── build │ │ │ │ ├── lib.linux-x86_64-2.7 │ │ │ │ │ ├── _plsa.so │ │ │ │ │ └── plsa.py │ │ │ │ └── temp.linux-x86_64-2.7 │ │ │ │ │ ├── _plsa.o │ │ │ │ │ └── plsa_train.o │ │ │ ├── example_lsa.py │ │ │ ├── example_plsa.py │ │ │ ├── lsa.py │ │ │ ├── plsa.py │ │ │ ├── plsa_train.c │ │ │ ├── setup.py │ │ │ ├── tests.py │ │ │ └── tfidf │ │ │ │ ├── __init__.py │ │ │ │ ├── featsel.py │ │ │ │ ├── porter.py │ │ │ │ ├── preprocessing.py │ │ │ │ ├── smoothing.py │ │ │ │ └── tfidf.py │ │ ├── preprocessing.py │ │ ├── quad.py │ │ ├── sacred_trajmap.py │ │ ├── sacred_turn_hmm.py │ │ ├── script.py │ │ ├── script.sh │ │ ├── script_sh.py │ │ ├── svd.py │ │ ├── tools.py │ │ ├── trajmap.py │ │ ├── turn.py │ │ └── turn_script.py │ └── visual │ │ ├── ahmed.js │ │ ├── ahmed_maxsh.js │ │ ├── ahmed_maxsh_rural.js │ │ ├── ahmed_shanghai.js │ │ ├── baseline_lack.js │ │ ├── baseline_lack.js.1 │ │ ├── baseline_minsh.js │ │ ├── baseline_surplus.js │ │ ├── biagioni.js │ │ ├── biagioni_shanghai.js │ │ ├── data.js │ │ ├── data_Bmap.js │ │ ├── gmap.html │ │ ├── heatmap.html │ │ ├── index.html │ │ ├── index_backup.html │ │ ├── karag.js │ │ ├── minsh_trajmap.js │ │ ├── minsh_trajmap_2.js │ │ ├── minsh_trajmap_3.js │ │ ├── minsh_trajmap_del.js │ │ ├── readfile.js │ │ ├── shanghai_lack.js │ │ ├── trajectories.html │ │ ├── trajmap.js │ │ ├── transform.html │ │ └── untransform.html ├── kde │ ├── __init__.py │ ├── gpsmatcher.py │ ├── graph_extract.py │ ├── graphdb_matcher.py │ ├── graphdb_matcher_run.py │ ├── kde.py │ ├── location.py │ ├── mathfunclib.py │ ├── process_map_matches.py │ ├── pylibs │ │ ├── __init__.py │ │ ├── mathfunclib.py │ │ └── spatialfunclib.py │ ├── refine_topology.py │ ├── skeleton.py │ ├── spatialfunclib.py │ ├── streetmap.py │ └── viterbi.py ├── kharita │ ├── __init__.py │ ├── kharita.py │ ├── kharita_star.py │ ├── methods.py │ └── methods_kharita.py ├── pif │ ├── __init__.py │ ├── log_math.py │ ├── log_math_test.py │ └── path_inference │ │ ├── HardFilter.py │ │ ├── SoftFilter.py │ │ ├── __init__.py │ │ ├── example.py │ │ ├── example_utils.py │ │ ├── json.py │ │ ├── learning_traj.py │ │ ├── learning_traj_elements.py │ │ ├── learning_traj_elements_test.py │ │ ├── learning_traj_em.py │ │ ├── learning_traj_em_test.py │ │ ├── learning_traj_filter.py │ │ ├── learning_traj_filter_test.py │ │ ├── learning_traj_optimizer.py │ │ ├── learning_traj_optimizer_test.py │ │ ├── learning_traj_smoother.py │ │ ├── learning_traj_smoother_test.py │ │ ├── learning_traj_test.py │ │ ├── learning_traj_viterbi.py │ │ ├── learning_traj_viterbi_test.py │ │ ├── mapping │ │ ├── Counter.py │ │ ├── FancyFeatureMapper.py │ │ ├── FeatureMapper.py │ │ ├── FlowAnalysis.py │ │ ├── HFDecimation.py │ │ ├── PathCounter.py │ │ ├── SparseDecimation.py │ │ ├── __init__.py │ │ ├── decimation.py │ │ ├── decimation_test.py │ │ └── utils.py │ │ ├── path_builder.py │ │ ├── projector.py │ │ ├── structures.py │ │ └── utils.py └── roadrunner │ ├── GPSTraceServer │ ├── GaussianMixtureModel │ │ └── GMM.go │ ├── create_index.go │ └── trace_server.go │ ├── MergeDetector.py │ ├── PathSimilarity.py │ ├── Readme.md │ ├── RoadForest2RoadGraph.py │ ├── RoadGraph.py │ └── RoadRunner.py └── resources ├── cooptimization.properties ├── log4j.properties ├── mapinference.properties ├── mapmatching.properties └── preprocessing.properties /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Log file 18 | display.log 19 | # Windows shortcuts 20 | *.lnk 21 | 22 | # ========================= 23 | # Operating System Files 24 | # ========================= 25 | 26 | # OSX 27 | # ========================= 28 | 29 | .DS_Store 30 | .AppleDouble 31 | .LSOverride 32 | 33 | # Thumbnails 34 | ._* 35 | 36 | # Files that might appear in the root of a volume 37 | .DocumentRevisions-V100 38 | .fseventsd 39 | .Spotlight-V100 40 | .TemporaryItems 41 | .Trashes 42 | .VolumeIcon.icns 43 | 44 | 45 | # Directories potentially created on remote AFP share 46 | .AppleDB 47 | .AppleDesktop 48 | Network Trash Folder 49 | Temporary Items 50 | .apdisk 51 | 52 | # compiled files 53 | target/ 54 | Archive/ 55 | 56 | # cython files 57 | *.pyx 58 | 59 | # intellij IDEA configuration 60 | .idea/ 61 | *.iml -------------------------------------------------------------------------------- /files/Code notes.txt: -------------------------------------------------------------------------------- 1 | IO: 2 | 1.File names: 3 | 1.1 Map file: "($DATATYPE)_[$STATE_]($PERCENTAGE).txt 4 | - DATATYPE: vertices/edges 5 | - STATE: temp/remove/infer/NULL 6 | - temp: the intermediate result for map update. The map contains newly inferred roads whose correctness are not yet validated. 7 | - remove: the road edges removed from original road map. Usually there is no vertices file generated with it. The file name must 8 | come with a non-zero percentage value. 9 | - infer: the inferred road edges. Usually there is no vertices file generated with it. 10 | - NULL: this field is skipped. The format for original map, input map, output map and ground-truth map. 11 | - PERCENTAGE: >=0 integer representing the percentage of road ways removed from the original map. 12 | 2.Folder: 13 | 1.1 raw data: $DATASET/raw/(trajectory/map)/ 14 | input trajectory: $DATASET/input/trajectory/L?_I?_N?/ 15 | input map: $DATASET/input/map/ 16 | output map: $DATASET/output/map/ 17 | output matching result: $DATASET/output/matchResult/L?_I?_N?/ 18 | ground-truth map: $DATASET/groundTruth/map/ 19 | ground-truth matching result: $DATASET/groundTruth/matchResult/(route/point)/L?_I?_N?/ 20 | ground-truth manual matching result: $DATASET/groundTruth/matchResultM/L?_I?_N?/ 21 | log: $DATASET/(matching/inference/update/preprocess)/log/ 22 | intermediate result: $DATASET/(matching/inference/update/preprocess)/cache/ 23 | (map/matchResult/unmatchedTrajectory/unmatchedTrajectoryNextInput/inference)/iteration/ -------------------------------------------------------------------------------- /files/blank tile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/files/blank tile.png -------------------------------------------------------------------------------- /libs/jsi-1.1.0-javadoc.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/libs/jsi-1.1.0-javadoc.jar -------------------------------------------------------------------------------- /libs/jsi-1.1.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/libs/jsi-1.1.0-sources.jar -------------------------------------------------------------------------------- /libs/jsi-1.1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/libs/jsi-1.1.0.jar -------------------------------------------------------------------------------- /libs/unfolding.0.9.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/libs/unfolding.0.9.6.jar -------------------------------------------------------------------------------- /run_evaluation_scalability_Synthetic.sh: -------------------------------------------------------------------------------- 1 | mvn -q clean compile exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 2 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di5 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 3 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di10 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 4 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di20 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 5 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di35 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 6 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di50 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 7 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr1 -dc-1" -Dexec.cleanupDaemonThreads=false 8 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr10 -dc-1" -Dexec.cleanupDaemonThreads=false 9 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr30 -dc-1" -Dexec.cleanupDaemonThreads=false 10 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr60 -dc-1" -Dexec.cleanupDaemonThreads=false 11 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di5 -dr120 -dc-1" -Dexec.cleanupDaemonThreads=false 12 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di5 -dr180 -dc-1" -Dexec.cleanupDaemonThreads=false 13 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr1 -dc10" -Dexec.cleanupDaemonThreads=false 14 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr1 -dc20" -Dexec.cleanupDaemonThreads=false 15 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr1 -dc30" -Dexec.cleanupDaemonThreads=false 16 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr1 -dc40" -Dexec.cleanupDaemonThreads=false 17 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr1 -dc50" -Dexec.cleanupDaemonThreads=false 18 | mvn exec:java -Dexec.mainClass=evaluation.mapevaluation.MapInferenceEvaluationMain -Dexec.args="-di0 -dr1 -dc60" -Dexec.cleanupDaemonThreads=false 19 | -------------------------------------------------------------------------------- /run_inference_scalability_Synthetic.sh: -------------------------------------------------------------------------------- 1 | mvn compile 2 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 3 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di5 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 4 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di10 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 5 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di20 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 6 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di35 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 7 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di50 -dr5 -dc-1" -Dexec.cleanupDaemonThreads=false 8 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr10 -dc-1" -Dexec.cleanupDaemonThreads=false 9 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr30 -dc-1" -Dexec.cleanupDaemonThreads=false 10 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr60 -dc-1" -Dexec.cleanupDaemonThreads=false 11 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr120 -dc-1" -Dexec.cleanupDaemonThreads=false 12 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr180 -dc-1" -Dexec.cleanupDaemonThreads=false 13 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr1 -dc10" -Dexec.cleanupDaemonThreads=false 14 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr1 -dc20" -Dexec.cleanupDaemonThreads=false 15 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr1 -dc30" -Dexec.cleanupDaemonThreads=false 16 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr1 -dc40" -Dexec.cleanupDaemonThreads=false 17 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr1 -dc50" -Dexec.cleanupDaemonThreads=false 18 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr1 -dc60" -Dexec.cleanupDaemonThreads=false 19 | mvn exec:java -Dexec.mainClass=algorithm.mapinference.MapInferenceMain -Dexec.args="-di0 -dr1 -dc-1" -Dexec.cleanupDaemonThreads=false 20 | -------------------------------------------------------------------------------- /run_matching_Beijing-All-Map.sh: -------------------------------------------------------------------------------- 1 | mvn compile 2 | # test on-hmm-fixed on all maps 3 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-HMM-fixed -ddBeijing-S" -Dexec.cleanupDaemonThreads=false 4 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-HMM-fixed -ddBeijing-S" -Dexec.cleanupDaemonThreads=false 5 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-HMM-fixed -ddBeijing-R" -Dexec.cleanupDaemonThreads=false 6 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-HMM-fixed -ddBeijing-R" -Dexec.cleanupDaemonThreads=false 7 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-HMM-fixed -ddGlobal" -Dexec.cleanupDaemonThreads=false 8 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-HMM-fixed -ddGlobal" -Dexec.cleanupDaemonThreads=false 9 | 10 | # 11 | ## test on-sco on all maps 12 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-SCO -ddBeijing-S" -Dexec.cleanupDaemonThreads=false 13 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-SCO -ddBeijing-S" -Dexec.cleanupDaemonThreads=false 14 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-SCO -ddBeijing-R" -Dexec.cleanupDaemonThreads=false 15 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-SCO -ddBeijing-R" -Dexec.cleanupDaemonThreads=false 16 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-SCO -ddGlobal" -Dexec.cleanupDaemonThreads=false 17 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-SCO -ddGlobal" -Dexec.cleanupDaemonThreads=false 18 | # 19 | ## test on-wgt on all maps 20 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-WGT -ddBeijing-S" -Dexec.cleanupDaemonThreads=false 21 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-WGT -ddBeijing-S" -Dexec.cleanupDaemonThreads=false 22 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-WGT -ddBeijing-R" -Dexec.cleanupDaemonThreads=false 23 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-WGT -ddBeijing-R" -Dexec.cleanupDaemonThreads=false 24 | mvn exec:java -Dexec.mainClass=algorithm.mapmatching.MapMatchingMain -Dexec.args="-mmON-WGT -ddGlobal" -Dexec.cleanupDaemonThreads=false 25 | mvn compile exec:java -Dexec.mainClass=evaluation.matchingevaluation.MapMatchingEvaluationMain -Dexec.args="-mmON-WGT -ddGlobal" -Dexec.cleanupDaemonThreads=false 26 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/__init__.py -------------------------------------------------------------------------------- /src/main/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/__init__.py -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/Cluster.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering; 2 | 3 | import util.function.HausdorffDistanceFunction; 4 | import util.object.spatialobject.Trajectory; 5 | 6 | import java.util.ArrayList; 7 | import java.util.HashSet; 8 | import java.util.LinkedHashSet; 9 | import java.util.List; 10 | 11 | /** 12 | * Data structure for storing trajectory cluster. 13 | */ 14 | public class Cluster { 15 | private List itemList; 16 | private String id; 17 | private HashSet startAnchorPoint = new LinkedHashSet<>(); 18 | private HashSet endAnchorPoint = new LinkedHashSet<>(); 19 | 20 | Cluster(String id) { 21 | this.id = id; 22 | this.itemList = new ArrayList<>(); 23 | } 24 | 25 | Cluster(String id, Trajectory traj) { 26 | this.id = id; 27 | this.itemList = new ArrayList<>(); 28 | itemList.add(traj); 29 | } 30 | 31 | Cluster(String id, List trajList) { 32 | this.id = id; 33 | this.itemList = trajList; 34 | } 35 | 36 | public List getTrajectoryList() { 37 | return itemList; 38 | } 39 | 40 | public Trajectory getTraj(int index) { 41 | return itemList.get(index); 42 | } 43 | 44 | public String getId() { 45 | return id; 46 | } 47 | 48 | public void setId(String id) { 49 | this.id = id; 50 | } 51 | 52 | public void add(Trajectory traj) { 53 | this.itemList.add(traj); 54 | } 55 | 56 | void addStartAnchor(String s) { 57 | this.startAnchorPoint.add(s); 58 | } 59 | 60 | private void addAllStartAnchor(HashSet anchorSet) { 61 | this.startAnchorPoint.addAll(anchorSet); 62 | } 63 | 64 | void addEndAnchor(String s) { 65 | this.endAnchorPoint.add(s); 66 | } 67 | 68 | private void addAllEndAnchor(HashSet anchorSet) { 69 | this.endAnchorPoint.addAll(anchorSet); 70 | } 71 | 72 | HashSet getStartAnchorPoints() { 73 | return startAnchorPoint; 74 | } 75 | 76 | HashSet getEndAnchorPoints() { 77 | return endAnchorPoint; 78 | } 79 | 80 | void merge(Cluster cluster) { 81 | this.itemList.addAll(cluster.itemList); 82 | addAllStartAnchor(cluster.getStartAnchorPoints()); 83 | addAllEndAnchor(cluster.getEndAnchorPoints()); 84 | } 85 | 86 | double getDistance(Trajectory traj, HausdorffDistanceFunction distFunc) { 87 | double minDistance = Double.POSITIVE_INFINITY; 88 | for (Trajectory currTraj : this.itemList) { 89 | double currDistance = distFunc.distance(currTraj, traj); 90 | minDistance = minDistance > currDistance ? currDistance : minDistance; 91 | } 92 | if (minDistance == Double.POSITIVE_INFINITY) 93 | throw new NullPointerException("ERROR! The distance between a cluster and a trajectory is infinity: " + this.id); 94 | return minDistance; 95 | } 96 | 97 | int size() { 98 | return itemList.size(); 99 | } 100 | 101 | boolean isEmpty() { 102 | return itemList.isEmpty(); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/AWT/ChoiceLabelPanel.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.AWT; 2 | 3 | import java.awt.*; 4 | 5 | final public class ChoiceLabelPanel extends Panel { 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = -2004461919306901613L; 10 | private Label label; 11 | private Choice choice; 12 | 13 | public ChoiceLabelPanel(String text, int alignment, boolean horizontal) { 14 | label = new Label(text, alignment); 15 | choice = new Choice(); 16 | if (horizontal) 17 | setLayout(new GridLayout(1, 0)); 18 | else 19 | setLayout(new GridLayout(0, 1)); 20 | add(label); 21 | add(choice); 22 | validate(); 23 | } 24 | 25 | public ChoiceLabelPanel(Choice in_choice, String text, int alignment, boolean horizontal) { 26 | choice = in_choice; 27 | label = new Label(text, alignment); 28 | if (horizontal) 29 | setLayout(new GridLayout(1, 0)); 30 | else 31 | setLayout(new GridLayout(0, 1)); 32 | add(label); 33 | add(choice); 34 | validate(); 35 | } 36 | 37 | final public void addItem(String item) { 38 | choice.addItem(item); 39 | } 40 | 41 | final public int countItems() { 42 | return choice.getItemCount(); 43 | } 44 | 45 | final public String getItem(int index) { 46 | return choice.getItem(index); 47 | } 48 | 49 | final public int getSelectedIndex() { 50 | return choice.getSelectedIndex(); 51 | } 52 | 53 | final public String getSelectedItem() { 54 | return choice.getSelectedItem(); 55 | } 56 | 57 | final public void select(int pos) { 58 | choice.select(pos); 59 | } 60 | 61 | final public void select(String str) { 62 | choice.select(str); 63 | } 64 | 65 | @SuppressWarnings("deprecation") 66 | @Override 67 | final public boolean handleEvent(Event event) { 68 | if (event.target == choice) { 69 | postEvent(new Event(this, event.id, event.arg)); 70 | } 71 | return super.handleEvent(event); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/AWT/ColorChoice.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.AWT; 2 | 3 | import java.awt.*; 4 | 5 | final public class ColorChoice extends Choice { 6 | public final static int NUM_OF_COLORS = 13; 7 | public final static Color[] colors; 8 | /** 9 | * 10 | */ 11 | private static final long serialVersionUID = 1L; 12 | private final static String[] colorStrings = {"Black", "Blue", "Cyan", "Dark gray", "Gray", "Green", "Light gray", 13 | "Magenta", "Orange", "Pink", "Red", "White", "Yellow"}; 14 | 15 | static { 16 | colors = new Color[13]; 17 | int i1 = 0, i2 = 63, i3 = 127; // bug in LiNuX compiler 18 | colors[0] = new Color(i1, i1, i1); 19 | colors[1] = new Color(0, 0, 255); 20 | colors[2] = new Color(0, 255, 255); 21 | colors[3] = new Color(i2, i2, i2); 22 | colors[4] = new Color(i3, i3, i3); 23 | colors[5] = new Color(0, 255, 0); 24 | colors[6] = new Color(191, 191, 191); 25 | colors[7] = new Color(255, 0, 255); 26 | colors[8] = new Color(255, 204, 0); 27 | colors[9] = new Color(255, 179, 179); 28 | colors[10] = new Color(255, 0, 0); 29 | colors[11] = new Color(255, 255, 255); 30 | colors[12] = new Color(255, 255, 0); 31 | } 32 | 33 | public ColorChoice(String initialColorString) { 34 | super(); 35 | for (int i = 0; i < NUM_OF_COLORS; i++) 36 | addItem(colorStrings[i]); 37 | for (int i = 0; i < NUM_OF_COLORS; i++) 38 | if (initialColorString.equals(colorStrings[i])) 39 | select(i); 40 | } 41 | 42 | public ColorChoice(Color initialColor) { 43 | super(); 44 | for (int i = 0; i < NUM_OF_COLORS; i++) 45 | addItem(colorStrings[i]); 46 | for (int i = 0; i < NUM_OF_COLORS; i++) 47 | if (initialColor.equals(colors[i])) 48 | select(i); 49 | } 50 | 51 | public static Color GetColor(String colorString) { 52 | for (int i = 0; i < NUM_OF_COLORS; i++) 53 | if (colorString.equals(colorStrings[i])) 54 | return colors[i]; 55 | return colors[11]; // white 56 | } 57 | 58 | public static void main(String args[]) { 59 | for (int i = 0; i < NUM_OF_COLORS; i++) { 60 | System.out.println(colorStrings[i] + ":\t " + colors[i].getRed() + " \t" + colors[i].getGreen() 61 | + " \t" + colors[i].getBlue()); 62 | } 63 | } 64 | 65 | final public Color getSelectedColor() { 66 | return colors[getSelectedIndex()]; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/AWT/ScrollbarLabelPanel.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.AWT; 2 | 3 | import java.awt.*; 4 | 5 | final public class ScrollbarLabelPanel extends Panel { 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = 1L; 10 | private Label label; 11 | private Scrollbar scrollbar; 12 | 13 | public ScrollbarLabelPanel(String text, int alignment, int value, int minimum, int maximum, boolean horizontal) { 14 | label = new Label(text, alignment); 15 | scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, value, (maximum - minimum) / 100 + 1, minimum, maximum); 16 | if (horizontal) 17 | setLayout(new GridLayout(1, 0)); 18 | else 19 | setLayout(new GridLayout(0, 1)); 20 | add(label); 21 | add(scrollbar); 22 | validate(); 23 | } 24 | 25 | @SuppressWarnings("deprecation") 26 | final public int getLineIncrement() { 27 | return scrollbar.getLineIncrement(); 28 | } 29 | 30 | @SuppressWarnings("deprecation") 31 | final public void setLineIncrement(int l) { 32 | scrollbar.setLineIncrement(l); 33 | } 34 | 35 | final public int getMaximum() { 36 | return scrollbar.getMaximum(); 37 | } 38 | 39 | final public int getMinimum() { 40 | return scrollbar.getMinimum(); 41 | } 42 | 43 | final public int getOrientation() { 44 | return scrollbar.getOrientation(); 45 | } 46 | 47 | @SuppressWarnings("deprecation") 48 | final public int getPageIncrement() { 49 | return scrollbar.getPageIncrement(); 50 | } 51 | 52 | final public void setPageIncrement(int l) { 53 | scrollbar.setBlockIncrement(l); 54 | } 55 | 56 | final public int getValue() { 57 | return scrollbar.getValue(); 58 | } 59 | 60 | final public void setValue(int value) { 61 | scrollbar.setValue(value); 62 | } 63 | 64 | @SuppressWarnings("deprecation") 65 | final public int getVisible() { 66 | return scrollbar.getVisible(); 67 | } 68 | 69 | final public void setValues(int value, int visible, int minimum, int maximum) { 70 | scrollbar.setValues(value, visible, minimum, maximum); 71 | } 72 | 73 | @Override 74 | @SuppressWarnings("deprecation") 75 | final public boolean handleEvent(Event event) { 76 | if (event.target == scrollbar && ScrollbarTextFieldPanel.ScrollbarEvent(event)) { 77 | postEvent(new Event(this, event.id, event.arg)); 78 | } 79 | return super.handleEvent(event); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/CRoutines/MakefilePrincipalCurves: -------------------------------------------------------------------------------- 1 | all: libutilities.so liblinearAlgebra.so 2 | 3 | libutilities.so: utilities.c 4 | gcc -lm -shared -I/usr/java1.1/include -I/usr/java1.1/include/solaris utilities.c -o libutilities.so 5 | 6 | liblinearAlgebra.so: linearAlgebra.c 7 | gcc -lm -shared -I/usr/java1.1/include -I/usr/java1.1/include/solaris linearAlgebra.c -o liblinearAlgebra.so 8 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/CRoutines/Utilities_MyMath.h: -------------------------------------------------------------------------------- 1 | /* DO NOT EDIT THIS FILE - it is machine generated */ 2 | #include "jni.h" 3 | /* Header for class Utilities_MyMath */ 4 | 5 | #ifndef _Included_Utilities_MyMath 6 | #define _Included_Utilities_MyMath 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | /* 11 | * Class: Utilities_MyMath 12 | * Method: IndexArrayC 13 | * Signature: ([D[II)V 14 | */ 15 | JNIEXPORT void JNICALL Java_Utilities_MyMath_IndexArrayC 16 | (JNIEnv *, jclass, jdoubleArray, jintArray, jint); 17 | 18 | /* 19 | * Class: Utilities_MyMath 20 | * Method: equalsC 21 | * Signature: (DDD)I 22 | */ 23 | JNIEXPORT jint JNICALL Java_Utilities_MyMath_equalsC 24 | (JNIEnv *, jclass, jdouble, jdouble, jdouble); 25 | 26 | /* 27 | * Class: Utilities_MyMath 28 | * Method: MatrixInvertC 29 | * Signature: ([DI)I 30 | */ 31 | JNIEXPORT jint JNICALL Java_Utilities_MyMath_MatrixInvertC 32 | (JNIEnv *, jclass, jdoubleArray, jint); 33 | 34 | #ifdef __cplusplus 35 | } 36 | #endif 37 | #endif 38 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Debug/Debug.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Debug; 2 | 3 | import java.awt.*; 4 | 5 | final public class Debug { 6 | public static TextComponent diagnosisTextComponent; 7 | 8 | int iterator; 9 | String previousString; 10 | String presentString; 11 | String newString; 12 | 13 | @SuppressWarnings("deprecation") 14 | public Debug(String string) { 15 | iterator = 0; 16 | newString = string; 17 | previousString = diagnosisTextComponent.getText(); 18 | presentString = previousString + newString; 19 | diagnosisTextComponent.setText(presentString); 20 | diagnosisTextComponent.postEvent(new DebugEvent(diagnosisTextComponent, DebugEvent.STARTED_DEBUG_THREAD, 21 | newString)); 22 | } 23 | 24 | final public void SetIterator(int in_iterator) { 25 | iterator = in_iterator; 26 | } 27 | 28 | final public int GetIterator() { 29 | return iterator; 30 | } 31 | 32 | @SuppressWarnings("deprecation") 33 | final public void Reset(String string) { 34 | iterator = 0; 35 | newString = string; 36 | presentString = previousString + newString; 37 | diagnosisTextComponent.setText(presentString); 38 | diagnosisTextComponent.postEvent(new DebugEvent(diagnosisTextComponent, DebugEvent.RESET_DEBUG_THREAD, 39 | newString)); 40 | } 41 | 42 | @SuppressWarnings("deprecation") 43 | final public void Terminate() { 44 | diagnosisTextComponent.setText(previousString); 45 | diagnosisTextComponent.postEvent(new DebugEvent(diagnosisTextComponent, DebugEvent.FINISHED_DEBUG_THREAD, 46 | newString)); 47 | } 48 | 49 | @SuppressWarnings("deprecation") 50 | final public void Iterate() { 51 | diagnosisTextComponent.setText(presentString + " " + ++iterator + " "); 52 | diagnosisTextComponent.postEvent(new DebugEvent(diagnosisTextComponent, DebugEvent.ITERATE_DEBUG_THREAD, 53 | newString)); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Debug/DebugEvent.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Debug; 2 | 3 | import java.awt.*; 4 | 5 | final public class DebugEvent extends Event { 6 | public final static int STARTED_DEBUG_THREAD = 10000; 7 | public final static int FINISHED_DEBUG_THREAD = 10001; 8 | public final static int ITERATE_DEBUG_THREAD = 10002; 9 | public final static int RESET_DEBUG_THREAD = 10003; 10 | /** 11 | * 12 | */ 13 | private static final long serialVersionUID = 1L; 14 | 15 | public DebugEvent(Object target, int id, Object arg) { 16 | super(target, id, arg); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Internet/DownLoadDialog.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Internet; 2 | 3 | import java.awt.*; 4 | 5 | final public class DownLoadDialog extends Dialog { 6 | /** 7 | * 8 | */ 9 | private static final long serialVersionUID = 1L; 10 | private TextField urlTextField; 11 | private Button doneButton; 12 | 13 | public DownLoadDialog(Frame frame, String title, String initialURL) { 14 | super(frame, title, true); 15 | setLayout(new BorderLayout()); 16 | urlTextField = new TextField(initialURL, initialURL.length() + 30); 17 | add("North", urlTextField); 18 | doneButton = new Button("Done"); 19 | add("South", doneButton); 20 | validate(); 21 | pack(); 22 | } 23 | 24 | final public String getURL() { 25 | return urlTextField.getText(); 26 | } 27 | 28 | @Override 29 | @SuppressWarnings("deprecation") 30 | final public boolean action(Event event, Object arg) { 31 | // Done 32 | if (event.target == doneButton) { 33 | postEvent(new Event(this, Event.WINDOW_DESTROY, "")); 34 | } 35 | return true; 36 | } 37 | 38 | @SuppressWarnings("deprecation") 39 | @Override 40 | final public boolean handleEvent(Event event) { 41 | // Done 42 | if (event.id == Event.WINDOW_DESTROY) { 43 | dispose(); 44 | } 45 | return super.handleEvent(event); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Internet/EmailFile.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Internet; 2 | 3 | import algorithm.mapinference.lineclustering.pcurves.Utilities.Environment; 4 | 5 | import java.io.DataInputStream; 6 | import java.io.IOException; 7 | import java.net.URL; 8 | 9 | final class EmailFile { 10 | @SuppressWarnings("deprecation") 11 | public EmailFile(String email, String subject, String filename) { 12 | try { 13 | URL url = 14 | new URL(Environment.cgiRootURL + "/mailFile.cgi?email=" + email + "&subject=" + subject + "&file=" + filename); 15 | DataInputStream dIn = new DataInputStream(url.openStream()); 16 | String string = dIn.readLine(); 17 | while (string != null) { 18 | string = dIn.readLine(); 19 | } 20 | } catch (IOException e) { 21 | throw new RuntimeException("MYERROR: " + e.getMessage() + " in Internet.EmailString.init()"); 22 | } 23 | } 24 | // public static void main(String args[]) { 25 | // EmailString email= new EmailString("kegl@iro.umontreal.ca","trySubject","tryBody\ntryBody2"); 26 | // } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Internet/UpLoadFile.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Internet; 2 | 3 | public final class UpLoadFile extends UpLoadFileOffline implements Runnable { 4 | public final static int ACTION_OPEN = 0; 5 | // Actions 6 | private final static int NO_ACTION = -1; 7 | private final static int ACTION_APPEND = 1; 8 | private final static int ACTION_TERMINATE = 2; 9 | private Thread upLoadFileThread = null; 10 | private int action = NO_ACTION; 11 | 12 | // filename is relative to $root/CgiOutput (see openFile.cgi and appendFile.cgi). If filename is needed to 13 | // be accessessed from the net, it should be pre-created manually to set the rights. 14 | public UpLoadFile(String in_filename, long in_uniquenumber) { 15 | super(in_filename, in_uniquenumber); 16 | start(); 17 | } 18 | 19 | // Random uniqueNumber 20 | public UpLoadFile(String in_filename) { 21 | super(in_filename); 22 | start(); 23 | } 24 | 25 | void start() { 26 | if (upLoadFileThread == null) { 27 | upLoadFileThread = new Thread(this, "UpLoadFile"); 28 | upLoadFileThread.start(); 29 | } 30 | } 31 | 32 | public void stop() { 33 | upLoadFileThread = null; 34 | } 35 | 36 | @Override 37 | public void run() { 38 | boolean cont = true; 39 | upLoadFileThread.setPriority(Thread.MIN_PRIORITY); 40 | Thread myThread = Thread.currentThread(); 41 | while (upLoadFileThread == myThread && cont) { 42 | ActionLoopIsWaiting(); 43 | switch (action) { 44 | case ACTION_OPEN: 45 | Open(); 46 | action = NO_ACTION; 47 | break; 48 | case ACTION_APPEND: 49 | Append(); 50 | action = NO_ACTION; 51 | break; 52 | case ACTION_TERMINATE: 53 | cont = false; 54 | break; 55 | } 56 | } 57 | } 58 | 59 | synchronized void ActionLoopIsWaiting() { 60 | notifyAll(); 61 | try { 62 | // to avoid deadlock, action loop repeats once a second 63 | wait(1000); 64 | } catch (InterruptedException e) { 65 | } 66 | } 67 | 68 | public synchronized void SetAction(int in_action) { 69 | try { 70 | wait(); 71 | } catch (InterruptedException e) { 72 | } 73 | action = in_action; 74 | notifyAll(); 75 | } 76 | 77 | public synchronized void AppendString(String in_stringToAppend) { 78 | try { 79 | wait(); 80 | } catch (InterruptedException e) { 81 | } 82 | stringToAppend = in_stringToAppend; 83 | action = ACTION_APPEND; 84 | notifyAll(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/CovarianceMatrix.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | public interface CovarianceMatrix { 4 | public void AddEqual(Vektor y_i, double weight); 5 | 6 | public void SubEqual(Vektor y_i, double weight); 7 | 8 | public Vektor Mul(Vektor A); // \sum_i=1^n (y_i^tA)y_i 9 | 10 | public double MulSquared(Vektor A); // \sum_i=1^n (y_i^tA)^2 11 | 12 | public double GetNorm2Squared(); // \sum_i=1^n y_i^ty_i 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/CovarianceMatrix2D.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | final public class CovarianceMatrix2D implements CovarianceMatrix { 4 | double xx; 5 | private double xy; 6 | private double yy; 7 | 8 | protected CovarianceMatrix2D() { 9 | xx = 0; 10 | xy = 0; 11 | yy = 0; 12 | } 13 | 14 | @Override 15 | final public void AddEqual(Vektor y_i, double weight) { 16 | double coordX = ((Vektor2D) y_i).coordX; 17 | double coordY = ((Vektor2D) y_i).coordY; 18 | xx += weight * coordX * coordX; 19 | xy += weight * coordX * coordY; 20 | yy += weight * coordY * coordY; 21 | } 22 | 23 | @Override 24 | final public void SubEqual(Vektor y_i, double weight) { 25 | double coordX = ((Vektor2D) y_i).coordX; 26 | double coordY = ((Vektor2D) y_i).coordY; 27 | xx -= weight * coordX * coordX; 28 | xy -= weight * coordX * coordY; 29 | yy -= weight * coordY * coordY; 30 | } 31 | 32 | // \sum_i=1^n (y_i^tA)y_i 33 | @Override 34 | final public Vektor Mul(Vektor A) { 35 | double coordX = ((Vektor2D) A).coordX; 36 | double coordY = ((Vektor2D) A).coordY; 37 | return new Vektor2D(coordX * xx + coordY * xy, coordX * xy + coordY * yy); 38 | } 39 | 40 | // \sum_i=1^n (y_i^tA)^2 41 | @Override 42 | final public double MulSquared(Vektor A) { 43 | double coordX = ((Vektor2D) A).coordX; 44 | double coordY = ((Vektor2D) A).coordY; 45 | return coordX * coordX * xx + coordY * coordY * yy + 2 * coordX * coordY * xy; 46 | } 47 | 48 | // \sum_i=1^n y_i^ty_i 49 | @Override 50 | final public double GetNorm2Squared() { 51 | return xx + yy; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/Line.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | 4 | public interface Line { 5 | public Vektor GetVektor1(); 6 | 7 | public Vektor GetVektor2(); 8 | 9 | public Vektor GetDirectionalVektor(); 10 | 11 | public Vektor Reflect(Vektor vektor); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/LineAbstract.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | // This is an abstract class for all lines. The abstract functions are 4 | // the minimum requirement for a line, the other functions in the 5 | // Line inteface are derived from them. For efficiency reasons, these derived 6 | // functions can be rewritten in extending classes. 7 | abstract public class LineAbstract implements Line { 8 | @Override 9 | abstract public Vektor GetVektor1(); 10 | 11 | @Override 12 | abstract public Vektor GetVektor2(); 13 | 14 | abstract public void SetVektor1(Vektor vektor); 15 | 16 | abstract public void SetVektor2(Vektor vektor); 17 | 18 | @Override 19 | final public boolean equals(Object o) { 20 | try { 21 | Line line = (Line) o; 22 | Vektor vektor1 = GetVektor1().Sub(GetVektor2()); 23 | Vektor vektor2 = line.GetVektor1().Sub(line.GetVektor2()); 24 | Vektor vektor3 = GetVektor1().Sub(line.GetVektor1()); 25 | vektor1.DivEqual(vektor1.Norm2()); 26 | vektor2.DivEqual(vektor2.Norm2()); 27 | vektor3.DivEqual(vektor3.Norm2()); 28 | return ((vektor1.equals(vektor2) || vektor1.equals(vektor2.Mul(-1))) && (vektor1.equals(vektor3) || vektor1 29 | .equals(vektor3.Mul(-1)))); 30 | } catch (ClassCastException e) { 31 | return false; 32 | } 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | // TODO Auto-generated method stub 38 | return super.hashCode(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/LineSegment.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | 4 | public interface LineSegment { 5 | public Vektor GetVektor1(); 6 | 7 | public Vektor GetVektor2(); 8 | 9 | public void SetVektor1(Vektor vektor); 10 | 11 | public void SetVektor2(Vektor vektor); 12 | 13 | public double GetLength(); 14 | 15 | public double GetLengthSquared(); 16 | 17 | public Vektor GetMidVektor(); 18 | 19 | public Vektor GetPointAtParameter(double parameter); 20 | 21 | public boolean equals(LineSegment lineSegment); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/LineSegmentAbstract.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | // This is an abstract class for all line segments. The abstract functions are 4 | // the minimum requirement for a line segment, the other functions in the 5 | // LineSegment inteface are derived from them. For efficiency reasons, these derived 6 | // functions can be rewritten in extending classes. 7 | abstract public class LineSegmentAbstract implements LineSegment { 8 | @Override 9 | abstract public Vektor GetVektor1(); 10 | 11 | @Override 12 | abstract public Vektor GetVektor2(); 13 | 14 | @Override 15 | abstract public void SetVektor1(Vektor vektor); 16 | 17 | @Override 18 | abstract public void SetVektor2(Vektor vektor); 19 | 20 | final public LineSegmentObject GetEdgeAsLineSegmentObject() { 21 | return new LineSegmentObject(GetVektor1(), GetVektor2()); 22 | } 23 | 24 | @Override 25 | final public double GetLength() { 26 | return GetVektor1().Dist2(GetVektor2()); 27 | } 28 | 29 | @Override 30 | final public double GetLengthSquared() { 31 | return GetVektor1().Dist2Squared(GetVektor2()); 32 | } 33 | 34 | @Override 35 | final public Vektor GetMidVektor() { 36 | return GetVektor1().Add(GetVektor2()).Div(2); 37 | } 38 | 39 | @Override 40 | final public Vektor GetPointAtParameter(double parameter) { 41 | Vektor vektor = GetVektor2().Sub(GetVektor1()); 42 | vektor.MulEqual(parameter / GetLength()); 43 | vektor.AddEqual(GetVektor1()); 44 | return vektor; 45 | } 46 | 47 | @Override 48 | final public boolean equals(LineSegment lineSegment) { 49 | return ((lineSegment.GetVektor1().equals(GetVektor1()) && lineSegment.GetVektor2().equals(GetVektor2())) || (lineSegment 50 | .GetVektor1().equals(GetVektor2()) && lineSegment.GetVektor2().equals(GetVektor1()))); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/LineSegmentObject.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | final public class LineSegmentObject extends LineSegmentAbstract { 4 | private Vektor vektor1; 5 | private Vektor vektor2; 6 | 7 | public LineSegmentObject(Vektor in_vektor1, Vektor in_vektor2) { 8 | vektor1 = in_vektor1; 9 | vektor2 = in_vektor2; 10 | } 11 | 12 | @Override 13 | final public Vektor GetVektor1() { 14 | return vektor1; 15 | } 16 | 17 | @Override 18 | final public Vektor GetVektor2() { 19 | return vektor2; 20 | } 21 | 22 | @Override 23 | final public void SetVektor1(Vektor vektor) { 24 | vektor1 = vektor; 25 | } 26 | 27 | @Override 28 | final public void SetVektor2(Vektor vektor) { 29 | vektor2 = vektor; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/Loadable.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | import algorithm.mapinference.lineclustering.pcurves.Debug.Debug; 4 | 5 | import java.io.DataInputStream; 6 | import java.io.File; 7 | import java.io.FileNotFoundException; 8 | import java.io.IOException; 9 | 10 | public interface Loadable { 11 | public void Load(File f, Debug d) throws FileNotFoundException, IOException; 12 | 13 | public void Load(File f) throws FileNotFoundException, IOException; 14 | 15 | public void Load(DataInputStream din, Debug d) throws IOException; 16 | 17 | public void Load(DataInputStream din) throws IOException; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/OnlineSampleStatistics.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | public abstract class OnlineSampleStatistics { 4 | abstract public void Reset(); 5 | 6 | abstract public void AddPoint(Vektor vektor); 7 | 8 | abstract public void DeletePoint(Vektor vektor); 9 | 10 | // This can be overridden for efficiency 11 | public void UpdatePoint(Vektor vektorFrom, Vektor vektorTo) { 12 | DeletePoint(vektorFrom); 13 | AddPoint(vektorTo); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/OnlineSampleStatisticsDegreeOne.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | final public class OnlineSampleStatisticsDegreeOne extends OnlineSampleStatistics implements Weighted { 4 | private Vektor prototypeVektor; 5 | private double weight; 6 | private Vektor sum; 7 | private Vektor center; 8 | private double sigmaSquaredTimesWeight; 9 | 10 | public OnlineSampleStatisticsDegreeOne(Vektor vektor) { 11 | prototypeVektor = vektor.DefaultClone(); 12 | Reset(); 13 | } 14 | 15 | @Override 16 | final public void Reset() { 17 | weight = 0; 18 | sigmaSquaredTimesWeight = weight = 0; 19 | sum = prototypeVektor.DefaultClone(); 20 | center = null; 21 | } 22 | 23 | @Override 24 | final public void AddPoint(Vektor vektor) { 25 | double w; 26 | try { 27 | w = ((Weighted) vektor).GetWeight(); 28 | } catch (ClassCastException e) { 29 | w = 1; 30 | } 31 | if (weight == 0) { 32 | sum = vektor.Mul(w); 33 | center = vektor.Clone(); 34 | sigmaSquaredTimesWeight = 0; 35 | weight = w; 36 | } else { 37 | Vektor oldCenter = center.Clone(); 38 | sum.AddEqual(vektor.Mul(w)); 39 | center = sum.Div(weight + w); 40 | double d = center.Dist2Squared(oldCenter); 41 | double dn = center.Dist2Squared(vektor); 42 | sigmaSquaredTimesWeight += weight * d + w * dn; 43 | weight += w; 44 | } 45 | } 46 | 47 | @Override 48 | final public void DeletePoint(Vektor vektor) { 49 | double w; 50 | try { 51 | w = ((Weighted) vektor).GetWeight(); 52 | } catch (ClassCastException e) { 53 | w = 1; 54 | } 55 | if (weight - w == 0) 56 | Reset(); 57 | else { 58 | Vektor oldCenter = center.Clone(); 59 | sum.SubEqual(vektor.Mul(w)); 60 | center = sum.Div(weight - w); 61 | double d = center.Dist2Squared(oldCenter); 62 | double dn = oldCenter.Dist2Squared(vektor); 63 | sigmaSquaredTimesWeight -= (weight - w) * d + w * dn; 64 | weight -= w; 65 | } 66 | } 67 | 68 | final public Vektor GetSum() { 69 | return sum; 70 | } 71 | 72 | final public Vektor GetCenter() { 73 | return center; 74 | } 75 | 76 | final public double GetSigmaSquaredTimesWeight() { 77 | return sigmaSquaredTimesWeight; 78 | } 79 | 80 | final public double GetSigmaSquared() { 81 | return sigmaSquaredTimesWeight / weight; 82 | } 83 | 84 | @Override 85 | final public double GetWeight() { 86 | return weight; 87 | } 88 | 89 | final public double GetMSETimesWeight(Vektor vektor) { 90 | try { 91 | if (center == null) 92 | return 0; 93 | return sigmaSquaredTimesWeight + weight * center.Dist2Squared(vektor); 94 | } 95 | // if center is null, there is no point in the set 96 | catch (NullPointerException e) { 97 | return 0; 98 | } 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/OnlineSampleStatisticsWeight.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | final public class OnlineSampleStatisticsWeight extends OnlineSampleStatistics implements Weighted { 4 | private double weight; 5 | 6 | public OnlineSampleStatisticsWeight() { 7 | Reset(); 8 | } 9 | 10 | @Override 11 | final public void Reset() { 12 | weight = 0; 13 | } 14 | 15 | @Override 16 | final public void AddPoint(Vektor vektor) { 17 | try { 18 | weight += ((Weighted) vektor).GetWeight(); 19 | } catch (ClassCastException e) { 20 | weight += 1; 21 | } 22 | } 23 | 24 | @Override 25 | final public void DeletePoint(Vektor vektor) { 26 | try { 27 | weight -= ((Weighted) vektor).GetWeight(); 28 | } catch (ClassCastException e) { 29 | weight -= 1; 30 | } 31 | } 32 | 33 | @Override 34 | final public double GetWeight() { 35 | return weight; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/Sample2D.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | import java.util.NoSuchElementException; 4 | import java.util.StringTokenizer; 5 | 6 | public class Sample2D extends SampleLoadable { 7 | public Sample2D() { 8 | super(); 9 | } 10 | 11 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 12 | // abstract functions of SampleLoadable BEGIN 13 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 14 | @Override 15 | final public Sample DefaultClone() { 16 | return new Sample2D(); 17 | } 18 | 19 | @Override 20 | protected boolean AddPoint(StringTokenizer t) { 21 | try { 22 | Vektor2D point = new Vektor2D(t); 23 | AddPoint(point); 24 | return true; 25 | } 26 | // If wrong format, we just don't load it, and return false 27 | catch (NoSuchElementException e1) { 28 | return false; 29 | } catch (NumberFormatException e) { 30 | return false; 31 | } 32 | } 33 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 34 | // abstract functions of SampleLoadable END 35 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/Sample2DWeighted.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | import java.util.NoSuchElementException; 4 | import java.util.StringTokenizer; 5 | 6 | final public class Sample2DWeighted extends Sample2D { 7 | public Sample2DWeighted() { 8 | super(); 9 | } 10 | 11 | @Override 12 | final protected boolean AddPoint(StringTokenizer t) { 13 | try { 14 | Vektor2D point = new Vektor2DWeighted(t); 15 | AddPoint(point); 16 | return true; 17 | } 18 | // If wrong format, we just don't load it, and return false 19 | catch (NoSuchElementException e1) { 20 | return false; 21 | } catch (NumberFormatException e) { 22 | return false; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/SampleLoadable.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | import algorithm.mapinference.lineclustering.pcurves.Debug.Debug; 4 | 5 | import java.io.*; 6 | import java.util.StringTokenizer; 7 | 8 | abstract public class SampleLoadable extends Sample implements Loadable { 9 | SampleLoadable() { 10 | super(); 11 | } 12 | 13 | abstract protected boolean AddPoint(StringTokenizer t); 14 | 15 | final public void Load(String s) { 16 | Reset(); 17 | StringTokenizer t = new StringTokenizer(s); 18 | while (t.hasMoreTokens()) 19 | AddPoint(t); 20 | } 21 | 22 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 23 | // interface Loadable BEGIN 24 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 25 | @Override 26 | final public void Load(File f) throws FileNotFoundException, IOException { 27 | FileInputStream fin = new FileInputStream(f); 28 | DataInputStream din = new DataInputStream(fin); 29 | Load(din); 30 | din.close(); 31 | fin.close(); 32 | } 33 | 34 | @Override 35 | final public void Load(DataInputStream din) throws IOException { 36 | Reset(); 37 | while (din.available() > 0) 38 | AddPoint(din); 39 | } 40 | 41 | @Override 42 | final public void Load(File f, Debug d) throws FileNotFoundException, IOException { 43 | FileInputStream fin = new FileInputStream(f); 44 | DataInputStream din = new DataInputStream(fin); 45 | Load(din, d); 46 | din.close(); 47 | fin.close(); 48 | } 49 | 50 | @Override 51 | final public void Load(DataInputStream din, Debug d) throws IOException { 52 | Reset(); 53 | while (din.available() > 0) { 54 | if (AddPoint(din)) 55 | d.Iterate(); 56 | } 57 | } 58 | 59 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 60 | // interface Loadable END 61 | // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 62 | 63 | @SuppressWarnings("deprecation") 64 | final boolean AddPoint(DataInputStream din) throws IOException { 65 | String line = new String(din.readLine()); 66 | StringTokenizer t = new StringTokenizer(line); 67 | return AddPoint(t); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/SampleWithOnlineStatistics.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | // no abstract functions, but statistics[i]'s must be initialized 4 | abstract public class SampleWithOnlineStatistics { 5 | protected OnlineSampleStatistics[] statistics; 6 | protected Sample sample; 7 | 8 | protected SampleWithOnlineStatistics(int numOfStatistics) { 9 | statistics = new OnlineSampleStatistics[numOfStatistics]; 10 | sample = new Sample(); 11 | } 12 | 13 | final protected void Copy(Sample in_sample) { 14 | Reset(); 15 | sample = in_sample.Clone(); 16 | for (int j = 0; j < sample.getSize(); j++) 17 | for (OnlineSampleStatistics statistic : statistics) 18 | statistic.AddPoint(sample.GetPointAt(j)); 19 | } 20 | 21 | final protected void ShallowCopy(Sample in_sample) { 22 | Reset(); 23 | sample = in_sample.ShallowClone(); 24 | for (int j = 0; j < sample.getSize(); j++) 25 | for (OnlineSampleStatistics statistic : statistics) 26 | statistic.AddPoint(sample.GetPointAt(j)); 27 | } 28 | 29 | final public void Reset() { 30 | sample.Reset(); 31 | for (OnlineSampleStatistics statistic : statistics) 32 | statistic.Reset(); 33 | } 34 | 35 | final public void UpdatePointAt(Vektor vektor, int index) { 36 | for (OnlineSampleStatistics statistic : statistics) 37 | statistic.UpdatePoint(sample.GetPointAt(index), vektor); 38 | sample.UpdatePointAt(vektor, index); 39 | } 40 | 41 | final public void SetPointAt(Vektor vektor, int index) { 42 | for (OnlineSampleStatistics statistic : statistics) 43 | statistic.UpdatePoint(sample.GetPointAt(index), vektor); 44 | sample.SetPointAt(vektor, index); 45 | } 46 | 47 | final public void AddPoint(Vektor vektor) { 48 | sample.AddPoint(vektor); 49 | for (OnlineSampleStatistics statistic : statistics) 50 | statistic.AddPoint(vektor); 51 | } 52 | 53 | final public void DeletePointAt(int index) { 54 | for (OnlineSampleStatistics statistic : statistics) 55 | statistic.DeletePoint(sample.GetPointAt(index)); 56 | sample.DeletePointAt(index); 57 | } 58 | 59 | final public int GetSize() { 60 | return sample.getSize(); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/SampleWithOnlineStatisticsDegreeTwo.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | final public class SampleWithOnlineStatisticsDegreeTwo extends SampleWithOnlineStatistics { 4 | private OnlineSampleStatisticsDegreeTwo statisticsDegreeTwo; 5 | 6 | public SampleWithOnlineStatisticsDegreeTwo(Sample in_sample) { 7 | super(1); 8 | statisticsDegreeTwo = new OnlineSampleStatisticsDegreeTwo(in_sample.GetPointAt(0)); 9 | statistics[0] = statisticsDegreeTwo; 10 | ShallowCopy(in_sample); 11 | } 12 | 13 | final public double GetMSE(Line line) { 14 | return statisticsDegreeTwo.GetMSETimesWeightFromLine(line.GetVektor1(), line.GetVektor2()) 15 | / statisticsDegreeTwo.GetWeight(); 16 | } 17 | 18 | final public double GetRMSE(Line line) { 19 | return Math.sqrt(statisticsDegreeTwo.GetMSETimesWeightFromLine(line.GetVektor1(), line.GetVektor2()) 20 | / statisticsDegreeTwo.GetWeight()); 21 | } 22 | 23 | final public LineObject FirstPrincipalComponent() { 24 | return statisticsDegreeTwo.FirstPrincipalComponent(); 25 | } 26 | 27 | final public Sample GetProjectionResiduals(Line line) { 28 | return sample.GetProjectionResiduals(line); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/Vektor.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | import java.io.PrintStream; 4 | 5 | public interface Vektor { 6 | public Vektor Clone(); 7 | 8 | public Vektor DefaultClone(); 9 | 10 | public CovarianceMatrix CovarianceMatrixClone(); 11 | 12 | public void Update(Vektor vektor); 13 | 14 | public int Dimension(); 15 | 16 | public double GetCoords(int i); 17 | 18 | public Vektor Add(Vektor vektor); // + 19 | 20 | public Vektor Sub(Vektor vektor); // - 21 | 22 | public Vektor Mul(double d); // * 23 | 24 | public Vektor Div(double d); // / 25 | 26 | public double Mul(Vektor vektor); // inner product 27 | 28 | public void AddEqual(Vektor vektor); // += 29 | 30 | public void SubEqual(Vektor vektor); // -= 31 | 32 | public void MulEqual(double d); // *= 33 | 34 | public void DivEqual(double d); // /= 35 | 36 | @Override 37 | public boolean equals(Object vektor); 38 | 39 | public double Norm2(); 40 | 41 | public double Norm2Squared(); 42 | 43 | public double Dist2(Vektor vektor); 44 | 45 | public double Dist2Squared(Vektor vektor); 46 | 47 | public double Dist2(LineSegment lineSegment); 48 | 49 | public double Dist2Squared(LineSegment lineSegment); 50 | 51 | public Vektor Project(LineSegment lineSegment); 52 | 53 | public Vektor Project(Line line); 54 | 55 | public double CosAngle(Vektor vektor1, Vektor vektor2); 56 | 57 | @Override 58 | public String toString(); 59 | 60 | public void Save(PrintStream pOut); 61 | 62 | public String SaveToString(); 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/Vektor2DWeighted.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | import algorithm.mapinference.lineclustering.pcurves.Utilities.MyMath; 4 | 5 | import java.io.PrintStream; 6 | import java.util.NoSuchElementException; 7 | import java.util.StringTokenizer; 8 | 9 | 10 | final public class Vektor2DWeighted extends Vektor2D implements Weighted { 11 | private static double maxWeight = 1.0; // for painting 12 | private double weight; 13 | 14 | private Vektor2DWeighted() { 15 | super(); 16 | weight = 1; 17 | } 18 | 19 | private Vektor2DWeighted(double in_coordX, double in_coordY, double in_weight) { 20 | super(in_coordX, in_coordY); 21 | weight = in_weight; 22 | } 23 | 24 | public Vektor2DWeighted(StringTokenizer t) throws NoSuchElementException, NumberFormatException { 25 | super(new Double(t.nextToken()), new Double(t.nextToken())); 26 | weight = new Double(t.nextToken()); 27 | } 28 | 29 | @Override 30 | final public Vektor Clone() { 31 | return new Vektor2DWeighted(coordX, coordY, weight); 32 | } 33 | 34 | @Override 35 | final public Vektor DefaultClone() { 36 | return new Vektor2DWeighted(); 37 | } 38 | 39 | @Override 40 | final public double GetWeight() { 41 | return weight; 42 | } 43 | 44 | final public void SetWeight(double in_weight) { 45 | weight = in_weight; 46 | } 47 | 48 | @Override 49 | final public String toString() { 50 | return super.toString() + "w = " + MyMath.RoundDouble(weight, 4); 51 | } 52 | 53 | @Override 54 | final public void Save(PrintStream pOut) { 55 | super.Save(pOut); 56 | pOut.print(" " + weight); 57 | } 58 | 59 | @Override 60 | final public String SaveToString() { 61 | return super.SaveToString() + " " + weight; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/VektorObject.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | import java.io.PrintStream; 4 | 5 | // This is an abstract class for all vectors. The abstract functions are 6 | // the minimum requirement for a vector, the other functions in the 7 | // Vektor inteface are derived from them. For efficiency reasons, these derived 8 | // functions can be rewritten in extending classes. 9 | abstract public class VektorObject implements Vektor { 10 | 11 | @Override 12 | abstract public Vektor Clone(); 13 | 14 | @Override 15 | abstract public Vektor DefaultClone(); 16 | 17 | @Override 18 | abstract public int Dimension(); 19 | 20 | @Override 21 | abstract public double GetCoords(int i); 22 | 23 | @Override 24 | abstract public CovarianceMatrix CovarianceMatrixClone(); 25 | 26 | @Override 27 | abstract public void Update(Vektor vektor); 28 | 29 | @Override 30 | abstract public void AddEqual(Vektor vektor); // += 31 | 32 | @Override 33 | abstract public void MulEqual(double d); // += 34 | 35 | @Override 36 | abstract public double Mul(Vektor vektor); // inner product 37 | 38 | @Override 39 | abstract public boolean equals(Object vektor); 40 | 41 | @Override 42 | abstract public String toString(); 43 | 44 | @Override 45 | abstract public void Save(PrintStream pOut); 46 | 47 | @Override 48 | public Vektor Add(Vektor vektor) { // + 49 | Vektor v = Clone(); 50 | v.AddEqual(vektor); 51 | return v; 52 | } 53 | 54 | @Override 55 | public Vektor Sub(Vektor vektor) { // - 56 | Vektor v = Clone(); 57 | v.SubEqual(vektor); 58 | return v; 59 | } 60 | 61 | @Override 62 | public Vektor Mul(double d) { // * 63 | Vektor v = Clone(); 64 | v.MulEqual(d); 65 | return v; 66 | } 67 | 68 | @Override 69 | public Vektor Div(double d) { // / 70 | Vektor v = Clone(); 71 | v.DivEqual(d); 72 | return v; 73 | } 74 | 75 | @Override 76 | public void SubEqual(Vektor vektor) { // *= 77 | AddEqual(vektor.Mul(-1)); 78 | } 79 | 80 | @Override 81 | public void DivEqual(double d) {// /= 82 | MulEqual(1 / d); 83 | } 84 | 85 | @Override 86 | public double Norm2() { 87 | return Math.sqrt(Norm2Squared()); 88 | } 89 | 90 | @Override 91 | public double Norm2Squared() { 92 | return Mul(this); 93 | } 94 | 95 | @Override 96 | public double CosAngle(Vektor vektor1, Vektor vektor2) { 97 | Vektor v1 = vektor1.Sub(this); 98 | Vektor v2 = vektor2.Sub(this); 99 | double a = v1.Mul(v2); 100 | double b = v1.Norm2() * v2.Norm2(); 101 | return a / b; 102 | } 103 | 104 | public double Angle(Vektor vektor1, Vektor vektor2) { 105 | return 180 * Math.acos(CosAngle(vektor1, vektor2)) / Math.PI; 106 | } 107 | 108 | @Override 109 | public int hashCode() { 110 | // TODO Auto-generated method stub 111 | return super.hashCode(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/LinearAlgebra/Weighted.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.LinearAlgebra; 2 | 3 | public interface Weighted { 4 | public double GetWeight(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Optimize/Optimizable.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Optimize; 2 | 3 | public interface Optimizable { 4 | public void OptimizingStep(double step); 5 | 6 | public double GetCriterion(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/PrincipalCurveAlgorithmThread.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve; 2 | 3 | final class PrincipalCurveAlgorithmThread extends PrincipalCurveAlgorithm implements Runnable { 4 | public final static int ACTION_INIT = 0; 5 | public final static int ACTION_INNER_STEP = 1; 6 | public final static int ACTION_OUTER_STEP = 2; 7 | public final static int ACTION_ADD_VERTEX_AS_ONE_MIDPOINT = 3; 8 | public final static int ACTION_START = 4; 9 | public final static int ACTION_CONTINUE = 5; 10 | private final static int ACTION_TERMINATE = 6; 11 | private Thread algorithmThread = null; 12 | // Actions 13 | private int action; 14 | 15 | public PrincipalCurveAlgorithmThread(PrincipalCurveClass initialCurve, 16 | PrincipalCurveParameters principalCurveParameters) { 17 | super(initialCurve, principalCurveParameters); 18 | start(); 19 | } 20 | 21 | final void start() { 22 | if (algorithmThread == null) { 23 | algorithmThread = new Thread(this, "PrincipalCurveAlgorithm"); 24 | algorithmThread.start(); 25 | } 26 | } 27 | 28 | final public void stop() { 29 | algorithmThread = null; 30 | } 31 | 32 | @Override 33 | final public void run() { 34 | boolean cont = true; 35 | algorithmThread.setPriority(Thread.MIN_PRIORITY); 36 | Thread myThread = Thread.currentThread(); 37 | try { 38 | while (algorithmThread == myThread && cont) { 39 | ActionLoopIsWaiting(); 40 | stop = false; 41 | switch (action) { 42 | case ACTION_INIT: 43 | Initialize(0); 44 | break; 45 | case ACTION_INNER_STEP: 46 | InnerStep(); 47 | break; 48 | case ACTION_OUTER_STEP: 49 | OuterStep(); 50 | break; 51 | case ACTION_START: 52 | start(0); 53 | break; 54 | case ACTION_CONTINUE: 55 | Continue(); 56 | break; 57 | case ACTION_ADD_VERTEX_AS_ONE_MIDPOINT: 58 | AddOneVertexAsMidpoint(true); 59 | break; 60 | case ACTION_TERMINATE: 61 | cont = false; 62 | break; 63 | } 64 | } 65 | } catch (InterruptedException e) { 66 | } 67 | } 68 | 69 | final synchronized void ActionLoopIsWaiting() { 70 | try { 71 | wait(); 72 | } catch (InterruptedException e) { 73 | } 74 | } 75 | 76 | final public synchronized void SetAction(int in_action) { 77 | action = in_action; 78 | notifyAll(); 79 | } 80 | 81 | final public synchronized void ReleaseStep() { 82 | notifyAll(); 83 | } 84 | 85 | final public void Stop() { 86 | stop = true; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/PrincipalCurveParameters.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve; 2 | 3 | import java.awt.*; 4 | 5 | final public class PrincipalCurveParameters { 6 | public static final int ADD_ONE_VERTEX = 0; 7 | public static final int ADD_VERTICES = 1; 8 | public static final int ADD_ONE_VERTEX_TO_LONGEST = 2; 9 | public double penaltyCoefficient = 0.09; 10 | public double relativeLengthPenaltyCoefficient = 0.01; 11 | public double terminatingConditionCoefficient = 0.5; 12 | public double terminatingConditionMaxLength = 47.16; 13 | // public double penaltyCoefficient = 0.0015; //for rivers 14 | public double relativeChangeInCriterionThreshold = 0.003; 15 | public int addVertexMode = ADD_ONE_VERTEX; 16 | public boolean paintProjectionPoints = false; 17 | public TextArea diagnosisTextArea; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/DummyVertex.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex; 2 | 3 | import algorithm.mapinference.lineclustering.pcurves.LinearAlgebra.Vektor; 4 | import algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements.Edge; 5 | import algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements.ElementVertex; 6 | import algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements.NumeratorAndDenominator; 7 | import algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements.Vertex; 8 | 9 | final public class DummyVertex extends Vertex { 10 | public DummyVertex(Vektor vektor) { 11 | super(vektor); 12 | } 13 | 14 | public DummyVertex(Vertex vertex) { 15 | super(vertex); 16 | } 17 | 18 | static public Vektor GetTangent(Vertex neighbor) { 19 | throw new RuntimeException("ABSTRACT FUNCTION!!!"); 20 | } 21 | 22 | // "Abstract" functions 23 | @Override 24 | final public int GetDegree() { 25 | return 0; 26 | } 27 | 28 | @Override 29 | final public Edge[] GetEdges() { 30 | return new Edge[0]; 31 | } 32 | 33 | @Override 34 | final public Vertex[] GetNeighbors() { 35 | return new Vertex[0]; 36 | } 37 | 38 | @Override 39 | final public int[] GetEdgeIndexes() { 40 | return new int[0]; 41 | } 42 | 43 | @Override 44 | final public int[] GetNeighborIndexes() { 45 | return new int[0]; 46 | } 47 | 48 | @Override 49 | final public ElementVertex[] GetElementVertices() { 50 | return new ElementVertex[0]; 51 | } 52 | 53 | @Override 54 | final public void Maintain(Vertex neighbor) { 55 | } 56 | 57 | @Override 58 | final public Vertex Degrade(Vertex neighbor) { 59 | return this; 60 | } 61 | 62 | @Override 63 | final public ElementVertex GetMainElementVertex() { 64 | throw new RuntimeException("ABSTRACT FUNCTION!!!"); 65 | } 66 | 67 | @Override 68 | final public double GetPenalty() { 69 | throw new RuntimeException("ABSTRACT FUNCTION!!!"); 70 | } 71 | 72 | @Override 73 | final public NumeratorAndDenominator GetNumeratorAndDenominatorForPenalty() { 74 | throw new RuntimeException("ABSTRACT FUNCTION!!!"); 75 | } 76 | 77 | @Override 78 | final public Vertex Restructure() { 79 | return this; 80 | } 81 | 82 | @Override 83 | final public String toString() { 84 | String s = "DummyVertex:\t"; 85 | s += super.toString() + "\t"; 86 | return s; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/Elements/EdgeDirection.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements; 2 | 3 | final public class EdgeDirection { 4 | public int edgeIndex; 5 | public boolean forward; 6 | 7 | public EdgeDirection(int in_edgeIndex, boolean in_forward) { 8 | edgeIndex = in_edgeIndex; 9 | forward = in_forward; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/Elements/ElementInitializationException.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements; 2 | 3 | final public class ElementInitializationException extends ArithmeticException { 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = 1L; 8 | 9 | public ElementInitializationException(String s) { 10 | super(s); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/Elements/ElementVertex.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements; 2 | 3 | import algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.PrincipalCurveClass; 4 | 5 | // if you compile first time, comment out //*, and uncomment //** 6 | // once PrincipalCurve.PrincipalCurveClass exists, restore the file 7 | abstract public class ElementVertex { 8 | public static PrincipalCurveClass principalCurve;// * 9 | 10 | static protected int GetEdgeVertexIndex1At(int index) { 11 | return principalCurve.GetEdgeAt(index).GetVertexIndex1();// * 12 | // ** return 0; 13 | } 14 | 15 | static protected int GetEdgeVertexIndex2At(int index) { 16 | return principalCurve.GetEdgeAt(index).GetVertexIndex2();// * 17 | // ** return 0; 18 | } 19 | 20 | static protected Edge GetEdgeAt(int index) { 21 | return principalCurve.GetEdgeAt(index);// * 22 | // ** return null; 23 | } 24 | 25 | abstract public void ReplaceEdgeIndexesForInsertion(int oei, int nei1, int nei2, Vertex vertex); 26 | 27 | abstract public void ReplaceEdgeIndexesForDeletion(int oei, int nei); 28 | 29 | abstract public void DecrementEdgeIndexes(int lowerIndex); 30 | 31 | abstract public void SetVertexIndexOfEdges(int vi); 32 | 33 | abstract public boolean EmptySet(); 34 | 35 | abstract public NumeratorAndDenominator GetNumeratorAndDenominatorForMSE(); 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/Elements/HasOneEdge.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements; 2 | 3 | // if you compile first time, comment out //*, and uncomment //** 4 | // once PrincipalCurve.Vertex.Elements.Vertex exists, restore the file 5 | public interface HasOneEdge { 6 | public EdgeDirection GetEdgeIndex(Vertex vertex);// * 7 | 8 | public Vertex GetVertex();// * 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/Elements/HasTwoSymmetricEdges.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements; 2 | 3 | // if you compile first time, comment out //*, and uncomment //** 4 | // once PrincipalCurve.Vertex.Elements.Vertex exists, restore the file 5 | public interface HasTwoSymmetricEdges extends HasOneEdge { 6 | public EdgeDirection GetOppositeEdgeIndex(Vertex vertex);// * 7 | 8 | public Vertex GetOppositeVertex(Vertex vertex);// * 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/Elements/NumeratorAndDenominator.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements; 2 | 3 | import algorithm.mapinference.lineclustering.pcurves.LinearAlgebra.Vektor; 4 | 5 | final public class NumeratorAndDenominator { 6 | public Vektor numerator; 7 | public double denominator; 8 | 9 | public NumeratorAndDenominator(Vektor prototypeVektor) { 10 | numerator = prototypeVektor.DefaultClone(); 11 | denominator = 0.0; 12 | } 13 | 14 | final public Vektor Resolve() { 15 | numerator.DivEqual(denominator); 16 | return numerator; 17 | } 18 | 19 | final public void AddEqual(NumeratorAndDenominator nd) { 20 | numerator.AddEqual(nd.numerator); 21 | denominator += nd.denominator; 22 | } 23 | 24 | final public void DivEqual(double d) { 25 | numerator.DivEqual(d); 26 | denominator /= d; 27 | } 28 | 29 | final public void MulEqual(double d) { 30 | numerator.MulEqual(d); 31 | denominator *= d; 32 | } 33 | 34 | @Override 35 | final public String toString() { 36 | return ("numerator: \n" + numerator + "\ndenominator:\n" + denominator); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/Elements/PenaltyCoefficients.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex.Elements; 2 | 3 | final public class PenaltyCoefficients { 4 | public static double ANGLE_PENALTY_COEFFICIENT; 5 | public static double LENGTH_PENALTY_COEFFICIENT; 6 | public static double WEIGHT_DIFFERENCE_PENALTY_COEFFICIENT; // lambda 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/JoinVertex.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex; 2 | 3 | public interface JoinVertex { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/RegularVertex.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex; 2 | 3 | public interface RegularVertex { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/PrincipalCurve/Vertex/TwoOppositeEdgeIndexesException.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.PrincipalCurve.Vertex; 2 | 3 | final public class TwoOppositeEdgeIndexesException extends RuntimeException { 4 | /** 5 | * 6 | */ 7 | private static final long serialVersionUID = 1L; 8 | 9 | public TwoOppositeEdgeIndexesException() { 10 | super(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Utilities/Environment.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Utilities; 2 | 3 | final public class Environment { 4 | public final static String email = "kegl@iro.umontreal.ca"; 5 | public final static String homeDirectory = "/u/kegl"; 6 | // public final static String homeURL = "http://www.cs.concordia.ca/~grad/kegl"; 7 | public final static String homeURL = "http://www.iro.umontreal.ca/~kegl"; 8 | public final static String cgiRootURL = "http://www.cs.concordia.ca/cgi-bin/cgiwrap/~grad/kegl"; 9 | public static boolean inApplet = false; 10 | public static boolean cRoutines = false; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapinference/lineclustering/pcurves/Utilities/Misc.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapinference.lineclustering.pcurves.Utilities; 2 | 3 | import java.io.DataInputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.IOException; 7 | import java.util.StringTokenizer; 8 | 9 | public final class Misc { 10 | // public static void swap(Object o1,Object o2) { 11 | // Object temp = o1; 12 | // o1 = o2; 13 | // o2 = temp; 14 | // } 15 | public static String MouseButton(int modifier) { 16 | if (modifier == 0) 17 | return "Left"; 18 | else if (modifier == 4) 19 | return "Right"; 20 | else if (modifier == 8) 21 | return "Middle"; 22 | else 23 | return ""; 24 | } 25 | 26 | public static String FormatString(double d, int width, int whiteSpaces) { 27 | String sOut = new String(); 28 | sOut += d; 29 | if (sOut.length() > width - whiteSpaces) 30 | sOut = sOut.substring(0, width - whiteSpaces); 31 | for (int l = sOut.length(); l < width; l++) 32 | sOut += " "; 33 | return sOut; 34 | } 35 | 36 | public static int ReadInt(String filename) throws IOException { 37 | File f = new File(filename); 38 | DataInputStream din = new DataInputStream(new FileInputStream(f)); 39 | @SuppressWarnings("deprecation") 40 | String line = new String(din.readLine()); 41 | StringTokenizer t = new StringTokenizer(line); 42 | int integer = new Integer(t.nextToken()); 43 | din.close(); 44 | return integer; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/hmm/Distributions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015-2016, BMW Car IT GmbH and BMW AG 3 | * Author: Stefan Holder (stefan.holder@bmw.de) 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package algorithm.mapmatching.hmm; 18 | 19 | import java.io.Serializable; 20 | 21 | import static java.lang.Math.*; 22 | 23 | /** 24 | * Implements various probability distributions. 25 | */ 26 | public class Distributions implements Serializable { 27 | 28 | /** 29 | * Normal/Gaussian distribution 30 | * 31 | * @param sigma 32 | * @param x Variable (value less the mean) 33 | */ 34 | public static double normalDistribution(double sigma, double x) { 35 | return 1.0 / (sqrt(2.0 * PI) * sigma) * exp(-0.5 * pow(x / sigma, 2)); 36 | } 37 | 38 | /** 39 | * Use this function instead of Math.log(normalDistribution(sigma, x)) to avoid an 40 | * arithmetic underflow for very small probabilities. 41 | */ 42 | public static double logNormalDistribution(double sigma, double x) { 43 | return Math.log(1.0 / (sqrt(2.0 * PI) * sigma)) + (-0.5 * pow(x / sigma, 2)); 44 | } 45 | 46 | /** 47 | * @param beta =1/lambda with lambda being the standard exponential distribution rate parameter 48 | */ 49 | public static double exponentialDistribution(double beta, double x) { 50 | return 1.0 / beta * exp(-x / beta); 51 | } 52 | 53 | /** 54 | * Use this function instead of Math.log(exponentialDistribution(beta, x)) to avoid an 55 | * arithmetic underflow for very small probabilities. 56 | * 57 | * @param beta =1/lambda with lambda being the standard exponential distribution rate parameter 58 | */ 59 | public static double logExponentialDistribution(double beta, double x) { 60 | return log(1.0 / beta) - (x / beta); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/hmm/HMMUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015, BMW Car IT GmbH 3 | * Author: Stefan Holder (stefan.holder@bmw.de) 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package algorithm.mapmatching.hmm; 19 | 20 | import java.io.Serializable; 21 | import java.util.LinkedHashMap; 22 | import java.util.Map; 23 | 24 | /** 25 | * Implementation utilities. 26 | */ 27 | class HMMUtils implements Serializable { 28 | 29 | static int initialHashMapCapacity(int maxElements) { 30 | // Default load factor of HashMaps is 0.75 31 | return (int) (maxElements / 0.75) + 1; 32 | } 33 | 34 | static Map logToNonLogProbabilities(Map logProbabilities) { 35 | final Map result = new LinkedHashMap<>(); 36 | for (Map.Entry entry : logProbabilities.entrySet()) { 37 | result.put(entry.getKey(), Math.exp(entry.getValue())); 38 | } 39 | return result; 40 | } 41 | 42 | /** 43 | * Note that this check must not be used for probability densities. 44 | */ 45 | static boolean probabilityInRange(double probability, double delta) { 46 | return probability >= -delta && probability <= 1.0 + delta; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/hmm/RoadPath.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016, BMW Car IT GmbH and BMW AG 3 | * Author: Stefan Holder (stefan.holder@bmw.de) 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package algorithm.mapmatching.hmm; 19 | 20 | import util.object.structure.PointMatch; 21 | 22 | import java.io.Serializable; 23 | import java.util.List; 24 | import java.util.Objects; 25 | 26 | /** 27 | * Represents the road path between two consecutive road positions. 28 | */ 29 | @SuppressWarnings("serial") 30 | public class RoadPath implements Serializable { 31 | // The following members are used to check whether the correct road paths are retrieved 32 | // from the most likely sequence 33 | public final PointMatch from; 34 | public final PointMatch to; 35 | public final List passingRoadID; 36 | 37 | /** 38 | * Creates a new road path between the two given road node. 39 | * 40 | * @param from Origin node. 41 | * @param to destiny node. 42 | */ 43 | RoadPath(PointMatch from, PointMatch to, List roadIdList) { 44 | this.from = from; 45 | this.to = to; 46 | this.passingRoadID = roadIdList; 47 | } 48 | 49 | public void setPassingRoads(List ids) { 50 | this.passingRoadID.addAll(ids); 51 | } 52 | 53 | public List getPassingRoadID() { 54 | return this.passingRoadID; 55 | } 56 | 57 | @Override 58 | public int hashCode() { 59 | return Objects.hash(from, to); 60 | } 61 | 62 | @Override 63 | public boolean equals(Object obj) { 64 | if (this == obj) 65 | return true; 66 | if (obj == null) 67 | return false; 68 | if (getClass() != obj.getClass()) 69 | return false; 70 | RoadPath other = (RoadPath) obj; 71 | if (from == null) { 72 | if (other.from != null) 73 | return false; 74 | } else if (!from.equals(other.from)) 75 | return false; 76 | if (to == null) { 77 | return other.to == null; 78 | } else return to.equals(other.to); 79 | } 80 | } -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/hmm/SequenceState.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016, BMW Car IT GmbH and BMW AG 3 | * Author: Stefan Holder (stefan.holder@bmw.de) 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package algorithm.mapmatching.hmm; 19 | 20 | import java.io.Serializable; 21 | import java.util.Objects; 22 | 23 | /** 24 | * State of the most likely sequence with additional information. 25 | * 26 | * @param the state type 27 | * @param the observation type 28 | * @param the transition descriptor type 29 | */ 30 | @SuppressWarnings("serial") 31 | class SequenceState implements Serializable { 32 | 33 | public final S state; 34 | 35 | /** 36 | * Null if HMM was started with initial state probabilities and state is the initial state. 37 | */ 38 | public final O observation; 39 | 40 | /** 41 | * Null if transition descriptor was not provided. 42 | */ 43 | public final D transitionDescriptor; 44 | 45 | public SequenceState(S state, O observation, D transitionDescriptor) { 46 | this.state = state; 47 | this.observation = observation; 48 | this.transitionDescriptor = transitionDescriptor; 49 | } 50 | 51 | @Override 52 | public String toString() { 53 | return "SequenceState [state=" + state + ", observation=" + observation 54 | + ", transitionDescriptor=" + transitionDescriptor 55 | + "]"; 56 | } 57 | 58 | @Override 59 | public int hashCode() { 60 | return Objects.hash(state, observation, transitionDescriptor); 61 | } 62 | 63 | @Override 64 | public boolean equals(Object obj) { 65 | if (this == obj) 66 | return true; 67 | if (obj == null) 68 | return false; 69 | if (getClass() != obj.getClass()) 70 | return false; 71 | SequenceState other = (SequenceState) obj; 72 | return Objects.equals(state, other.state) && 73 | Objects.equals(observation, other.observation) && 74 | Objects.equals(transitionDescriptor, other.transitionDescriptor); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/hmm/Transition.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2015-2016, BMW Car IT GmbH and BMW AG 3 | * Author: Stefan Holder (stefan.holder@bmw.de) 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package algorithm.mapmatching.hmm; 19 | 20 | import java.io.Serializable; 21 | import java.util.Objects; 22 | 23 | /** 24 | * Represents the transition between two consecutive candidates. 25 | * 26 | * @param the state type 27 | */ 28 | class Transition implements Serializable { 29 | public final S fromCandidate; 30 | public final S toCandidate; 31 | 32 | public Transition(S fromCandidate, S toCandidate) { 33 | this.fromCandidate = fromCandidate; 34 | this.toCandidate = toCandidate; 35 | } 36 | 37 | @Override 38 | public int hashCode() { 39 | return Objects.hash(fromCandidate, toCandidate); 40 | } 41 | 42 | @Override 43 | public boolean equals(Object obj) { 44 | if (this == obj) 45 | return true; 46 | if (obj == null) 47 | return false; 48 | if (getClass() != obj.getClass()) 49 | return false; 50 | @SuppressWarnings("unchecked") 51 | Transition other = (Transition) obj; 52 | return Objects.equals(fromCandidate, other.fromCandidate) && Objects.equals(toCandidate, 53 | other.toCandidate); 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "Transition [fromCandidate=" + fromCandidate + ", toCandidate=" 59 | + toCandidate + "]"; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/simpleHMM/StateCandidate.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapmatching.simpleHMM; 2 | 3 | import util.object.structure.PointMatch; 4 | 5 | public class StateCandidate { 6 | 7 | private StateSample stateSample; 8 | private StateCandidate predecessor = null; 9 | private double filtProb = 0d; 10 | // private double seqProb = 0d; 11 | private PointMatch pointMatch; 12 | private StateTransition transition = new StateTransition(); 13 | private double emiProb = 0d; 14 | private String id; 15 | 16 | public StateCandidate() { 17 | super(); 18 | } 19 | 20 | public StateCandidate(PointMatch self, StateSample stateSample) { 21 | this.pointMatch = self; 22 | this.stateSample = stateSample; 23 | this.id = self.getRoadID() + "_" + stateSample.getTime(); 24 | } 25 | 26 | public StateCandidate getPredecessor() { 27 | return predecessor; 28 | } 29 | 30 | public void setPredecessor(StateCandidate predecessor) { 31 | this.predecessor = predecessor; 32 | } 33 | 34 | public double getFiltProb() { 35 | return filtProb; 36 | } 37 | 38 | public void setFiltProb(double filtProb) { 39 | this.filtProb = filtProb; 40 | } 41 | 42 | public StateSample getStateSample() { 43 | return stateSample; 44 | } 45 | 46 | public PointMatch getPointMatch() { 47 | return pointMatch; 48 | } 49 | 50 | public StateTransition getTransition() { 51 | return transition; 52 | } 53 | 54 | public void setTransition(StateTransition transition) { 55 | this.transition = transition; 56 | } 57 | 58 | public double getEmiProb() { 59 | return emiProb; 60 | } 61 | 62 | public void setEmiProb(double emiProb) { 63 | this.emiProb = emiProb; 64 | } 65 | 66 | public double lon() { 67 | return pointMatch.lon(); 68 | } 69 | 70 | public double lat() { 71 | return pointMatch.lat(); 72 | } 73 | 74 | public String getId() { 75 | return id; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/simpleHMM/StateMemory.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapmatching.simpleHMM; 2 | 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | /** 9 | * Manages StateCandidates at a same timestamp 10 | */ 11 | public class StateMemory { 12 | private Map stateCandidates = new HashMap<>(); 13 | private StateSample sample; 14 | private StateCandidate filtProbCandidate = null; // the candidate with the largest filter probability 15 | private String id; 16 | 17 | public StateMemory(Set stateCandidates, StateSample sample) { 18 | for (StateCandidate stateCandidate : stateCandidates) { 19 | this.stateCandidates.put(stateCandidate.getId(), stateCandidate); 20 | } 21 | this.sample = sample; 22 | this.id = Double.toString(sample.getTime()); 23 | for (StateCandidate candidate : stateCandidates) { 24 | if (filtProbCandidate == null || filtProbCandidate.getFiltProb() < candidate.getFiltProb()) { 25 | filtProbCandidate = candidate; 26 | } 27 | } 28 | } 29 | 30 | public Map getStateCandidates() { 31 | return this.stateCandidates; 32 | } 33 | 34 | public StateSample getSample() { 35 | return this.sample; 36 | } 37 | 38 | public StateCandidate getFiltProbCandidate() { 39 | return filtProbCandidate; 40 | } 41 | 42 | public String getId() { 43 | return id; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/simpleHMM/StateSample.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapmatching.simpleHMM; 2 | 3 | import util.object.spatialobject.Point; 4 | 5 | import java.util.Objects; 6 | 7 | public class StateSample { 8 | 9 | private Point sampleMeasurement; 10 | private double heading; 11 | private double sampleTime = -1; 12 | 13 | 14 | public StateSample(Point point, double heading, double time) { 15 | this.sampleMeasurement = point; 16 | this.heading = heading; 17 | this.sampleTime = time; 18 | } 19 | 20 | public double x() { 21 | return this.sampleMeasurement.x(); 22 | } 23 | 24 | public double y() { 25 | return this.sampleMeasurement.y(); 26 | } 27 | 28 | public Point getSampleMeasurement() { 29 | return sampleMeasurement; 30 | } 31 | 32 | public double getTime() { 33 | return sampleTime; 34 | } 35 | 36 | public double getHeading() { 37 | return heading; 38 | } 39 | 40 | @Override 41 | public boolean equals(Object o) { 42 | if (this == o) return true; 43 | if (o == null || getClass() != o.getClass()) return false; 44 | StateSample that = (StateSample) o; 45 | 46 | return sampleTime == that.getTime() 47 | && heading == that.getHeading() 48 | && sampleMeasurement.equals(that.getSampleMeasurement()); 49 | } 50 | 51 | @Override 52 | public int hashCode() { 53 | return Objects.hash(sampleMeasurement, sampleTime, heading); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/algorithm/mapmatching/simpleHMM/StateTransition.java: -------------------------------------------------------------------------------- 1 | package algorithm.mapmatching.simpleHMM; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Objects; 7 | 8 | /** 9 | * State transition between matching candidates in Hidden Markov Model (HMM) map matching and 10 | * contains a route between respective map positions. 11 | */ 12 | public class StateTransition { 13 | 14 | private List route = new ArrayList<>(); 15 | 16 | public StateTransition() { 17 | } 18 | 19 | public StateTransition(List route) { 20 | this.route = route; 21 | } 22 | 23 | public List getRoute() { 24 | return route; 25 | } 26 | 27 | // public void setRoute(List route) { 28 | // this.route = route; 29 | // } 30 | 31 | @Override 32 | public boolean equals(Object o) { 33 | if (this == o) return true; 34 | if (o == null || getClass() != o.getClass()) return false; 35 | StateTransition that = (StateTransition) o; 36 | return route.equals(that.getRoute()); 37 | } 38 | 39 | @Override 40 | public int hashCode() { 41 | return Objects.hash(route); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/evaluation/mapevaluation/pathbaseddistance/mapmatchingbasics/IntervalComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | Path-based graph distance 1.0 3 | Copyright 2014 Mahmuda Ahmed, K. S. Hickmann and Carola Wenk 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | ------------------------------------------------------------------------ 18 | 19 | This software is based on the following article. Please cite this 20 | article when using this code as part of a research publication: 21 | 22 | M. Ahmed, K. S. Hickmann, and C. Wenk. 23 | Path-based distance for street map comparison. 24 | arXiv:1309.6131, 2013. 25 | ------------------------------------------------------------------------ 26 | 27 | Author: Mahmuda Ahmed 28 | Filename: IntervalComparator.java 29 | */ 30 | package evaluation.mapevaluation.pathbaseddistance.mapmatchingbasics; 31 | 32 | import java.util.Comparator; 33 | 34 | 35 | public class IntervalComparator implements Comparator { 36 | @Override 37 | public int compare(PBDVertex x, PBDVertex y) { 38 | if (x.startindex < y.startindex) { 39 | return -1; 40 | } else if (x.startindex > y.startindex) { 41 | return 1; 42 | } else { 43 | if (x.left < y.left) { 44 | return -1; 45 | } else if (x.left > y.left) { 46 | return 1; 47 | } else if (x.left == y.left) { 48 | if (x.right < y.right) { 49 | return -1; 50 | } 51 | if (x.right > y.right) { 52 | return 1; 53 | } 54 | 55 | } 56 | return 0; 57 | } 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/evaluation/mapevaluation/pathbaseddistance/mapmatchingbasics/IntervalComparatorEdge.java: -------------------------------------------------------------------------------- 1 | /* 2 | Path-based graph distance 1.0 3 | Copyright 2014 Mahmuda Ahmed, K. S. Hickmann and Carola Wenk 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | ------------------------------------------------------------------------ 18 | 19 | This software is based on the following article. Please cite this 20 | article when using this code as part of a research publication: 21 | 22 | M. Ahmed, K. S. Hickmann, and C. Wenk. 23 | Path-based distance for street map comparison. 24 | arXiv:1309.6131, 2013. 25 | ------------------------------------------------------------------------ 26 | 27 | Author: Mahmuda Ahmed 28 | Filename: IntervalComparatorEdge.java 29 | */ 30 | package evaluation.mapevaluation.pathbaseddistance.mapmatchingbasics; 31 | 32 | import java.util.Comparator; 33 | 34 | public class IntervalComparatorEdge implements Comparator { 35 | @Override 36 | public int compare(PBDEdge x, PBDEdge y) { 37 | 38 | if (x.cstart < y.cstart) { 39 | return -1; 40 | } else if (x.cstart > y.cstart) { 41 | return 1; 42 | } else { 43 | return Double.compare(x.cend, y.cend); 44 | } 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/evaluation/mapevaluation/pathbaseddistance/mapmatchingbasics/PBDEdge.java: -------------------------------------------------------------------------------- 1 | /* 2 | Path-based graph distance 1.0 3 | Copyright 2014 Mahmuda Ahmed, K. S. Hickmann and Carola Wenk 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | ------------------------------------------------------------------------ 18 | 19 | This software is based on the following article. Please cite this 20 | article when using this code as part of a research publication: 21 | 22 | M. Ahmed, K. S. Hickmann, and C. Wenk. 23 | Path-based distance for street map comparison. 24 | arXiv:1309.6131, 2013. 25 | ------------------------------------------------------------------------ 26 | 27 | Author: Mahmuda Ahmed 28 | Filename: PBDEdge.java 29 | */ 30 | package evaluation.mapevaluation.pathbaseddistance.mapmatchingbasics; 31 | 32 | public class PBDEdge { 33 | 34 | public PBDVertex v1, v2; 35 | public double cstart, cend; 36 | public double vstart, vend; 37 | public PBDLine line; 38 | public boolean done; 39 | public int startIndex, endIndex; 40 | 41 | public PBDEdge(PBDVertex v1, PBDVertex v2) { 42 | this.v1 = v1; 43 | this.v2 = v2; 44 | this.cstart = Double.MAX_VALUE; 45 | this.cend = -1; 46 | this.vstart = Double.MAX_VALUE; 47 | this.vend = -1; 48 | this.line = new PBDLine(v1, v2); 49 | this.done = false; 50 | } 51 | 52 | public void reset() { 53 | this.cstart = Double.MAX_VALUE; 54 | this.cend = -1; 55 | this.vstart = Double.MAX_VALUE; 56 | this.vend = -1; 57 | this.line = new PBDLine(v1, v2); 58 | this.done = false; 59 | } 60 | 61 | public String toString() { 62 | return this.line.toString(); 63 | } 64 | 65 | public String getKeyString() { 66 | return v1.x + " " + v2.x + " " + v1.y + " " + v2.y; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/evaluation/mapevaluation/pathbaseddistance/mapmatchingbasics/PathLabelComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | Path-based graph distance 1.0 3 | Copyright 2014 Mahmuda Ahmed, K. S. Hickmann and Carola Wenk 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | ------------------------------------------------------------------------ 18 | 19 | This software is based on the following article. Please cite this 20 | article when using this code as part of a research publication: 21 | 22 | M. Ahmed, K. S. Hickmann, and C. Wenk. 23 | Path-based distance for street map comparison. 24 | arXiv:1309.6131, 2013. 25 | ------------------------------------------------------------------------ 26 | 27 | Author: Mahmuda Ahmed 28 | Filename: PathLabelComparator.java 29 | */ 30 | package evaluation.mapevaluation.pathbaseddistance.mapmatchingbasics; 31 | 32 | import java.util.ArrayList; 33 | import java.util.Comparator; 34 | 35 | public class PathLabelComparator implements Comparator { 36 | 37 | private ArrayList vList; 38 | 39 | public PathLabelComparator(ArrayList vList) { 40 | this.vList = vList; 41 | } 42 | 43 | @Override 44 | public int compare(Integer x, Integer y) { 45 | 46 | // Assume neither string is null. Real code should probably be more robust 47 | return Double.compare(vList.get(x).left, vList.get(y).left); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/util/dijkstra/RoutingEdge.java: -------------------------------------------------------------------------------- 1 | package util.dijkstra; 2 | 3 | public class RoutingEdge { 4 | private final int index; 5 | private final int fromNodeIndex; 6 | private final int toNodeIndex; 7 | private final double length; 8 | 9 | RoutingEdge(int index, int fromNodeIndex, int toNodeIndex, double length) { 10 | this.index = index; 11 | this.fromNodeIndex = fromNodeIndex; 12 | this.toNodeIndex = toNodeIndex; 13 | this.length = length; 14 | } 15 | 16 | int getFromNodeIndex() { 17 | return fromNodeIndex; 18 | } 19 | 20 | int getToNodeIndex() { 21 | return toNodeIndex; 22 | } 23 | 24 | public double getLength() { 25 | return length; 26 | } 27 | 28 | public int getIndex() { 29 | return index; 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/util/dijkstra/RoutingVertex.java: -------------------------------------------------------------------------------- 1 | package util.dijkstra; 2 | 3 | import util.object.spatialobject.Point; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class RoutingVertex { 9 | private List outGoingRoutingEdges = new ArrayList(); // now we must create outGoingRoutingEdges 10 | private Point vertexPoint; 11 | private int index; 12 | 13 | List getOutGoingRoutingEdges() { 14 | return outGoingRoutingEdges; 15 | } 16 | 17 | public void setOutGoingRoutingEdges(ArrayList outGoingRoutingEdges) { 18 | this.outGoingRoutingEdges = outGoingRoutingEdges; 19 | } 20 | 21 | public int getIndex() { 22 | return index; 23 | } 24 | 25 | public void setIndex(int index) { 26 | this.index = index; 27 | } 28 | 29 | public Point getVertexPoint() { 30 | return vertexPoint; 31 | } 32 | 33 | public void setVertexPoint(Point vertexPoint) { 34 | this.vertexPoint = vertexPoint; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/util/exceptions/DistanceFunctionException.java: -------------------------------------------------------------------------------- 1 | package util.exceptions; 2 | 3 | /** 4 | * Exception for Distance functions runtime errors. 5 | * 6 | * @author uqdalves, Hellisk 7 | */ 8 | public class DistanceFunctionException extends RuntimeException { 9 | /** 10 | * Constructs a new Distance function exception without detail message. 11 | */ 12 | public DistanceFunctionException() { 13 | } 14 | 15 | /** 16 | * Constructs a new Distance function exception with the specified detail message. 17 | * 18 | * @param message The exception detail message. 19 | */ 20 | public DistanceFunctionException(String message) { 21 | super(message); 22 | } 23 | 24 | /** 25 | * Constructs a new Distance function exception with the specified cause. 26 | * 27 | * @param cause The cause for the exception. 28 | */ 29 | public DistanceFunctionException(Throwable cause) { 30 | super(cause); 31 | } 32 | 33 | /** 34 | * Constructs a new Distance function exception with the specified cause and a detail message. 35 | * 36 | * @param message The exception detail message. 37 | * @param cause The cause for the exception. 38 | */ 39 | public DistanceFunctionException(String message, Throwable cause) { 40 | super(message, cause); 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/main/java/util/exceptions/SpatialObjectConstructionException.java: -------------------------------------------------------------------------------- 1 | package util.exceptions; 2 | 3 | /** 4 | * Exception for spatial objects invariant errors. 5 | * 6 | * @author uqdalves 7 | */ 8 | public class SpatialObjectConstructionException extends RuntimeException { 9 | /** 10 | * Constructs a new empty exception without detail message. 11 | */ 12 | public SpatialObjectConstructionException() { 13 | } 14 | 15 | /** 16 | * Constructs a new exception with the specified detail message. 17 | * 18 | * @param message The exception detail message. 19 | */ 20 | public SpatialObjectConstructionException(String message) { 21 | super(message); 22 | } 23 | 24 | /** 25 | * Constructs a new exception with the specified cause. 26 | * 27 | * @param cause The cause for the exception. 28 | */ 29 | public SpatialObjectConstructionException(Throwable cause) { 30 | super(cause); 31 | } 32 | 33 | /** 34 | * Constructs a new exception with the specified cause 35 | * and a detail message. 36 | * 37 | * @param message The exception detail message. 38 | * @param cause The cause for the exception. 39 | */ 40 | public SpatialObjectConstructionException(String message, Throwable cause) { 41 | super(message, cause); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/util/exceptions/SpatialQueryException.java: -------------------------------------------------------------------------------- 1 | package util.exceptions; 2 | 3 | /** 4 | * Exception for spatial queries processing errors. 5 | * 6 | * @author uqdalves 7 | */ 8 | public class SpatialQueryException extends RuntimeException { 9 | /** 10 | * Constructs a new empty exception without detail message. 11 | */ 12 | public SpatialQueryException() { 13 | } 14 | 15 | /** 16 | * Constructs a new exception with the specified detail message. 17 | * 18 | * @param message The exception detail message. 19 | */ 20 | public SpatialQueryException(String message) { 21 | super(message); 22 | } 23 | 24 | /** 25 | * Constructs a new exception with the specified cause. 26 | * 27 | * @param cause The cause for the exception. 28 | */ 29 | public SpatialQueryException(Throwable cause) { 30 | super(cause); 31 | } 32 | 33 | /** 34 | * Constructs a new exception with the specified cause and a detail message. 35 | * 36 | * @param message The exception detail message. 37 | * @param cause The cause for the exception. 38 | */ 39 | public SpatialQueryException(String message, Throwable cause) { 40 | super(message, cause); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/util/exceptions/SpatialRelationException.java: -------------------------------------------------------------------------------- 1 | package util.exceptions; 2 | 3 | /** 4 | * Exception for unsupported spatial relations. 5 | * 6 | * @author uqdalves 7 | */ 8 | @SuppressWarnings("serial") 9 | public class SpatialRelationException extends RuntimeException { 10 | /** 11 | * Constructs a new empty exception without detail message. 12 | */ 13 | public SpatialRelationException() { 14 | } 15 | 16 | /** 17 | * Constructs a new exception with the specified detail message. 18 | * 19 | * @param message The exception detail message. 20 | */ 21 | public SpatialRelationException(String message) { 22 | super(message); 23 | } 24 | 25 | /** 26 | * Constructs a new exception with the specified cause. 27 | * 28 | * @param cause The cause for the exception. 29 | */ 30 | public SpatialRelationException(Throwable cause) { 31 | super(cause); 32 | } 33 | 34 | /** 35 | * Constructs a new exception with the specified cause and a detail message. 36 | * 37 | * @param message The exception detail message. 38 | * @param cause The cause for the exception. 39 | */ 40 | public SpatialRelationException(String message, Throwable cause) { 41 | super(message, cause); 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/util/function/HausdorffDistanceFunction.java: -------------------------------------------------------------------------------- 1 | package util.function; 2 | 3 | import util.object.spatialobject.Trajectory; 4 | import util.object.spatialobject.TrajectoryPoint; 5 | 6 | public class HausdorffDistanceFunction { 7 | private DistanceFunction distFunc; 8 | 9 | public HausdorffDistanceFunction(DistanceFunction distFunc) { 10 | this.distFunc = distFunc; 11 | } 12 | 13 | public double distance(Trajectory traj1, Trajectory traj2) { 14 | return Math.max(maxMinDistance(traj1, traj2), maxMinDistance(traj2, traj1)); 15 | } 16 | 17 | // TODO: Optimize the performance if needed. 18 | private double maxMinDistance(Trajectory traj1, Trajectory traj2) { 19 | double maxDistance = 0; 20 | for (TrajectoryPoint aTraj1 : traj1) { 21 | double minDistance = Double.POSITIVE_INFINITY; 22 | for (TrajectoryPoint aTraj2 : traj2) { 23 | double currDistance = distFunc.distance(aTraj1, aTraj2); 24 | minDistance = minDistance > currDistance ? currDistance : minDistance; 25 | } 26 | maxDistance = maxDistance < minDistance ? minDistance : maxDistance; 27 | } 28 | return maxDistance; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/util/function/VectorDistanceFunction.java: -------------------------------------------------------------------------------- 1 | package util.function; 2 | 3 | import util.exceptions.DistanceFunctionException; 4 | 5 | /** 6 | * Interface for distance functions between N-dimensional vectors. 7 | * 8 | * @author uqdalves 9 | */ 10 | public interface VectorDistanceFunction { 11 | 12 | /** 13 | * Distance between two N-Dimensional vectors. 14 | *
15 | * Vectors should have the same dimensions. 16 | * 17 | * @param v N-dimensional vector V. 18 | * @param u N-dimensional vector U. 19 | * @return Distance between U and V. 20 | * @throws DistanceFunctionException If vectors U and V do not have the same dimensions. 21 | */ 22 | double distance(double[] v, double[] u) throws DistanceFunctionException; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/util/index/SpatialIndexModel.java: -------------------------------------------------------------------------------- 1 | package util.index; 2 | 3 | import util.object.spatialobject.SpatialObject; 4 | 5 | import java.util.HashSet; 6 | 7 | /** 8 | * Interface for spatial indexes. 9 | * 10 | * @author uqdalves 11 | */ 12 | public interface SpatialIndexModel { 13 | /** 14 | * Search and return the index of the partition that intersects with the spatial object in the position (x,y). 15 | * 16 | * @param x The X coordinate to search. 17 | * @param y The Y coordinate to search. 18 | * @return Returns null if the (x,y) position is out of the boundaries of this index model. 19 | */ 20 | String search(double x, double y); 21 | 22 | /** 23 | * Search and Return the indexes of all partitions intersecting with the given spatial object. 24 | * 25 | * @param obj The spatial object to do the search. 26 | * @return The indexes of all partitions intersecting with this spatial object. An empty set if the object is out of the boundaries 27 | * of this index model. 28 | */ 29 | HashSet rangeSearch(SpatialObject obj); 30 | 31 | /** 32 | * Returns a spatial object representing the boundary of the partition with the given index. 33 | * 34 | * @param index The partition index to search. 35 | * @return The boundary of the partition in this model with the given index. 36 | */ 37 | SpatialObject get(String index); 38 | 39 | /** 40 | * @return Returns the spatial object representing the boundaries of this spatial model. 41 | */ 42 | SpatialObject getBoundary(); 43 | 44 | /** 45 | * @return The number of partitions in this model. 46 | */ 47 | int size(); 48 | 49 | /** 50 | * Check whether this index is empty. 51 | * 52 | * @return True if this model is empty. 53 | */ 54 | boolean isEmpty(); 55 | 56 | /** 57 | * Print this model to the system standard output. 58 | */ 59 | void print(); 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/util/index/SpatialQuery.java: -------------------------------------------------------------------------------- 1 | package util.index; 2 | 3 | import util.function.DistanceFunction; 4 | import util.object.spatialobject.SpatialObject; 5 | import util.object.structure.XYObject; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Base interface for spatial queries implemented by the 11 | * spatial data structures. 12 | * 13 | * @param The type of spatial object to query, i.e. the type 14 | * of spatial object stored in the spatial data structure. 15 | * @author uqdalves 16 | */ 17 | public interface SpatialQuery { 18 | 19 | /** 20 | * Search the nearest-neighbor from the object in the (x,y) position. 21 | * 22 | * @param x Query object X coordinate. 23 | * @param y Query object Y coordinate. 24 | * @param distFunc The function to calculate the object's distance 25 | * (points distance only). 26 | * @return The nearest-neighbor from the object in the (x,y) position. 27 | */ 28 | XYObject nearestNeighborSearch(double x, double y, DistanceFunction distFunc); 29 | 30 | /** 31 | * Search the k-nearest-neighbors from the object in the (x,y) position. 32 | * 33 | * @param x Query object X coordinate. 34 | * @param y Query object Y coordinate. 35 | * @param k The number of neighbor to return. 36 | * @param distFunc The function to calculate the object's distance 37 | * (points distance only). 38 | * @return The nearest-neighbor from the object in the (x,y) position. 39 | */ 40 | List> kNearestNeighborsSearch(double x, double y, int k, DistanceFunction distFunc); 41 | 42 | /** 43 | * Search all spatial objects intersecting with the given query object. 44 | * 45 | * @param queryObj The query object. 46 | * @return A list of spatial objects intersecting with the query object. 47 | */ 48 | List> rangeSearch(SpatialObject queryObj); 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/util/index/grid/GridPartition.java: -------------------------------------------------------------------------------- 1 | package util.index.grid; 2 | 3 | import util.function.DistanceFunction; 4 | import util.index.SpatialPartition; 5 | import util.object.spatialobject.Rect; 6 | import util.object.spatialobject.SpatialObject; 7 | import util.object.structure.XYObject; 8 | 9 | /** 10 | * Spatial partition representing a cell in a Grid diagram. 11 | *

12 | * Each partition is represented by its its boundary rectangle, and contains the list of spatial objects in the partition. 13 | * 14 | * @param Type of spatial object to store in this partition. 15 | * @author uqdalves 16 | */ 17 | public class GridPartition extends SpatialPartition> { 18 | /** 19 | * The boundaries of this grid cell 20 | */ 21 | private final Rect boundary; 22 | 23 | /** 24 | * Creates a new empty grid cell partition with the given rectangle dimensions. 25 | * 26 | * @param cellId The id/index of this cell. 27 | * @param cellBoundary The boundaries of this grid cell. 28 | */ 29 | public GridPartition(String cellId, Rect cellBoundary) { 30 | super(cellId); 31 | if (cellBoundary == null) { 32 | throw new NullPointerException("Grid cell boundary cannot be null."); 33 | } 34 | this.boundary = cellBoundary; 35 | } 36 | 37 | /** 38 | * Creates a new empty grid cell partition with the given rectangle dimensions. 39 | * 40 | * @param cellId The id/index of this cell. 41 | * @param minX Lower-left X coordinate. 42 | * @param minY Lower-left Y coordinate. 43 | * @param maxX Upper-right X coordinate. 44 | * @param maxY Upper-right Y coordinate. 45 | */ 46 | public GridPartition(String cellId, double minX, double minY, double maxX, double maxY, DistanceFunction df) { 47 | super(cellId); 48 | this.boundary = new Rect(minX, minY, maxX, maxY, df); 49 | } 50 | 51 | @Override 52 | public Rect getBoundary() { 53 | return boundary; 54 | } 55 | 56 | @Override 57 | public boolean insert(XYObject obj) { 58 | // Ignore objects that do not belong in this cell 59 | if (obj == null || !boundary.contains(obj.x(), obj.y())) { 60 | return false; // object cannot be added 61 | } 62 | return objectsList.add(obj); 63 | } 64 | 65 | @Override 66 | public boolean remove(XYObject obj) { 67 | // object is not here 68 | if (obj == null || !boundary.contains(obj.x(), obj.y())) { 69 | return false; 70 | } 71 | return objectsList.remove(obj); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/util/index/rtree/STRNode.java: -------------------------------------------------------------------------------- 1 | package util.index.rtree; 2 | 3 | import util.function.DistanceFunction; 4 | import util.index.SpatialPartition; 5 | import util.object.spatialobject.Rect; 6 | import util.object.spatialobject.SpatialObject; 7 | import util.object.structure.XYObject; 8 | 9 | /** 10 | * A spatial partition representing a node in a STRTree. 11 | *

12 | * Each node is represented by its boundary rectangle, 13 | * and contains the list of spatial objects in the node. 14 | * 15 | * @param Type of spatial object to store in this node. 16 | * @author uqdalves 17 | */ 18 | @SuppressWarnings("serial") 19 | public class STRNode extends SpatialPartition> { 20 | /** 21 | * The spatial boundaries of this node/partition 22 | */ 23 | private final Rect boundary; 24 | 25 | /** 26 | * Creates a new RTree cell with the given rectangle dimensions. 27 | * 28 | * @param partitionId The identifier/index of this node. 29 | * @param nodeBoundary The spatial boundary of this node. 30 | */ 31 | public STRNode(String partitionId, Rect nodeBoundary) { 32 | super(partitionId); 33 | if (nodeBoundary == null) { 34 | throw new NullPointerException("STRTree node boundary cannot be null."); 35 | } 36 | this.boundary = nodeBoundary; 37 | } 38 | 39 | /** 40 | * Creates a new STRTree node with the given rectangle dimensions. 41 | * 42 | * @param partitionId The identifier/index of this node. 43 | * @param minX Lower-left X coordinate. 44 | * @param minY Lower-left Y coordinate. 45 | * @param maxX Upper-right X coordinate. 46 | * @param maxY Upper-right Y coordinate. 47 | */ 48 | public STRNode(String partitionId, double minX, double minY, double maxX, double maxY, DistanceFunction df) { 49 | super(partitionId); 50 | this.boundary = new Rect(minX, minY, maxX, maxY, df); 51 | } 52 | 53 | @Override 54 | public boolean insert(XYObject obj) { 55 | // Ignore objects that do not belong in this node 56 | if (obj == null || !boundary.contains(obj.x(), obj.y())) { 57 | return false; // object cannot be added 58 | } 59 | return objectsList.add(obj); 60 | } 61 | 62 | @Override 63 | public boolean remove(XYObject obj) { 64 | // object is not here 65 | if (obj == null || !boundary.contains(obj.x(), obj.y())) { 66 | return false; 67 | } 68 | return objectsList.remove(obj); 69 | } 70 | 71 | @Override 72 | public Rect getBoundary() { 73 | return boundary; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/util/io/MapMatchingReader.java: -------------------------------------------------------------------------------- 1 | package util.io; 2 | 3 | import util.object.roadnetwork.RoadNetworkGraph; 4 | import util.object.spatialobject.Trajectory; 5 | import util.object.structure.MultipleTrajectoryMatchResult; 6 | import util.settings.BaseProperty; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Reader abstract class for map-matching applications which support reading input trajectories, underlying map(s) and ground-truth 12 | * map-matching results from raw data. 13 | * 14 | * @author Hellisk 15 | * @since 30/03/2019 16 | */ 17 | public interface MapMatchingReader { 18 | 19 | /** 20 | * The main function for parsing input trajectory, map and ground-truth result. The parsed results are stored within the reader and 21 | * retrieved by different read operations. 22 | * 23 | * @param baseFolderName The root path of the current dataset. 24 | * @param prop The list of parameters. 25 | */ 26 | void inputParser(String baseFolderName, BaseProperty prop); 27 | 28 | List getTrajectoryList(); 29 | 30 | List getGroundTruthMatchResult(); 31 | 32 | RoadNetworkGraph getMap(); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/util/ml/libsvm/TrainAndTestByLibSVM.java: -------------------------------------------------------------------------------- 1 | package util.ml.libsvm; 2 | 3 | public class TrainAndTestByLibSVM { 4 | /** 5 | * Build a 2d feature vector 6 | * 7 | * @param x 8 | * @param y 9 | * @return 10 | */ 11 | public static svm_node[] buildPoint(double x, double y) { 12 | svm_node[] point = new svm_node[2]; 13 | 14 | // x 15 | point[0] = new svm_node(); 16 | point[0].index = 1; 17 | point[0].value = x; 18 | 19 | // y 20 | point[1] = new svm_node(); 21 | point[1].index = 2; 22 | point[1].value = y; 23 | 24 | return point; 25 | } 26 | 27 | public static svm_model buildModel(svm_node[][] nodes) { 28 | // Build Parameters 29 | svm_parameter param = new svm_parameter(); 30 | param.svm_type = svm_parameter.ONE_CLASS; 31 | param.kernel_type = svm_parameter.RBF; 32 | param.gamma = 0.5; 33 | param.C = 0.25; 34 | param.nu = 0.1608; 35 | param.cache_size = 100; 36 | 37 | // Build Problem 38 | svm_problem problem = new svm_problem(); 39 | problem.x = nodes; 40 | problem.l = nodes.length; 41 | problem.y = prepareY(nodes.length); // y is label of the tuple 42 | 43 | // Build Model 44 | return svm.svm_train(problem, param); 45 | } 46 | 47 | private static double[] prepareY(int size) { 48 | double[] y = new double[size]; 49 | 50 | for (int i = 0; i < size; i++) 51 | y[i] = 1; 52 | 53 | return y; 54 | } 55 | 56 | public static double predict(svm_model model, svm_node[] nodes) { 57 | double[] scores = new double[2]; 58 | double result = svm.svm_predict(model, nodes); 59 | 60 | return scores[0]; 61 | } 62 | 63 | public static void main(String[] args) { 64 | svm_node[] point = TrainAndTestByLibSVM.buildPoint(1, 2); 65 | 66 | svm_node[][] points = new svm_node[2][3]; 67 | svm_model model = TrainAndTestByLibSVM.buildModel(points); 68 | TrainAndTestByLibSVM.predict(model, point); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/util/ml/libsvm/svm_model.java: -------------------------------------------------------------------------------- 1 | // 2 | // svm_model 3 | // 4 | package util.ml.libsvm; 5 | 6 | public class svm_model implements java.io.Serializable { 7 | public svm_parameter param; // parameter 8 | public int nr_class; // number of classes, = 2 in regression/one class svm 9 | public int l; // total #SV 10 | public svm_node[][] SV; // SVs (SV[l]) 11 | public double[][] sv_coef; // coefficients for SVs in decision functions (sv_coef[k-1][l]) 12 | public double[] rho; // constants in decision functions (rho[k*(k-1)/2]) 13 | public double[] probA; // pariwise probability information 14 | public double[] probB; 15 | public int[] sv_indices; // sv_indices[0,...,nSV-1] are values in [1,...,num_traning_data] to indicate SVs in the training set 16 | 17 | // for classification only 18 | 19 | public int[] label; // label of each class (label[k]) 20 | public int[] nSV; // number of SVs for each class (nSV[k]) 21 | // nSV[0] + nSV[1] + ... + nSV[k-1] = l 22 | }; 23 | -------------------------------------------------------------------------------- /src/main/java/util/ml/libsvm/svm_node.java: -------------------------------------------------------------------------------- 1 | package util.ml.libsvm; 2 | 3 | public class svm_node implements java.io.Serializable { 4 | public int index; 5 | public double value; 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/util/ml/libsvm/svm_parameter.java: -------------------------------------------------------------------------------- 1 | package util.ml.libsvm; 2 | 3 | public class svm_parameter implements Cloneable, java.io.Serializable { 4 | /* svm_type */ 5 | public static final int C_SVC = 0; 6 | public static final int NU_SVC = 1; 7 | public static final int ONE_CLASS = 2; 8 | public static final int EPSILON_SVR = 3; 9 | public static final int NU_SVR = 4; 10 | 11 | /* kernel_type */ 12 | public static final int LINEAR = 0; 13 | public static final int POLY = 1; 14 | public static final int RBF = 2; 15 | public static final int SIGMOID = 3; 16 | public static final int PRECOMPUTED = 4; 17 | 18 | public int svm_type; 19 | public int kernel_type; 20 | public int degree; // for poly 21 | public double gamma; // for poly/rbf/sigmoid 22 | public double coef0; // for poly/sigmoid 23 | 24 | // these are for training only 25 | public double cache_size; // in MB 26 | public double eps; // stopping criteria 27 | public double C; // for C_SVC, EPSILON_SVR and NU_SVR 28 | public int nr_weight; // for C_SVC 29 | public int[] weight_label; // for C_SVC 30 | public double[] weight; // for C_SVC 31 | public double nu; // for NU_SVC, ONE_CLASS, and NU_SVR 32 | public double p; // for EPSILON_SVR 33 | public int shrinking; // use the shrinking heuristics 34 | public int probability; // do probability estimates 35 | 36 | public Object clone() { 37 | try { 38 | return super.clone(); 39 | } catch (CloneNotSupportedException e) { 40 | return null; 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/util/ml/libsvm/svm_print_interface.java: -------------------------------------------------------------------------------- 1 | package util.ml.libsvm; 2 | 3 | public interface svm_print_interface { 4 | public void print(String s); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/util/ml/libsvm/svm_problem.java: -------------------------------------------------------------------------------- 1 | package util.ml.libsvm; 2 | 3 | public class svm_problem implements java.io.Serializable { 4 | public int l; 5 | public double[] y; 6 | public svm_node[][] x; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/util/object/spatialobject/SimpleSpatialObject.java: -------------------------------------------------------------------------------- 1 | package util.object.spatialobject; 2 | 3 | /** 4 | * Base superclass for simple/basic spatial objects. 5 | * Simple spatial objects are by definition immutable. 6 | * 7 | * @author uqdalves 8 | */ 9 | public abstract class SimpleSpatialObject implements SpatialObject { 10 | 11 | /** 12 | * Spatial object identifier. 13 | */ 14 | private String oid = null; 15 | 16 | /** 17 | * Number of spatial dimension of this object (2 by default). 18 | */ 19 | private byte dimension = 2; 20 | 21 | /** 22 | * Creates a new empty simple spatial object. 23 | */ 24 | public SimpleSpatialObject() { 25 | } 26 | 27 | /** 28 | * Creates a new simple spatial object with the given id. 29 | * 30 | * @param id Spatial object identifier. 31 | */ 32 | public SimpleSpatialObject(String id) { 33 | this.oid = id; 34 | } 35 | 36 | @Override 37 | public String getID() { 38 | return this.oid; 39 | } 40 | 41 | @Override 42 | public void setID(String id) { 43 | this.oid = id; 44 | } 45 | 46 | @Override 47 | public void setDimension(byte dim) { 48 | if (dim < 1) { 49 | throw new IllegalArgumentException("Number of spatial dimensions must be positive [1..127]."); 50 | } 51 | this.dimension = dim; 52 | } 53 | 54 | @Override 55 | public byte getDimension() { 56 | return this.dimension; 57 | } 58 | 59 | @Override 60 | public abstract SimpleSpatialObject clone(); 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/util/object/spatialobject/SpatialTemporalObject.java: -------------------------------------------------------------------------------- 1 | package util.object.spatialobject; 2 | 3 | import java.util.Comparator; 4 | 5 | /** 6 | * Base interface for Spatial-Temporal objects. Spatial objects with temporal features. 7 | * 8 | * @author uqdalves, Hellisk 9 | */ 10 | public interface SpatialTemporalObject extends SpatialObject { 11 | /** 12 | * Compare objects by their Temporal value. First by initial time, 13 | * then by final time. 14 | */ 15 | Comparator TIME_COMPARATOR = (o1, o2) -> { 16 | if (o1.timeStart() > o2.timeStart()) 17 | return 1; 18 | if (o1.timeStart() < o2.timeStart()) 19 | return -1; 20 | return Long.compare(o1.timeFinal(), o2.timeFinal()); 21 | }; 22 | 23 | /** 24 | * @return The initial/start time of this spatial-temporal object. 25 | */ 26 | long timeStart(); 27 | 28 | /** 29 | * @return The final/end time of this spatial-temporal object. 30 | */ 31 | long timeFinal(); 32 | 33 | /** 34 | * The duration in time of this spatial-temporal object. 35 | * That is, the time duration this object was active. 36 | * 37 | * @return The temporal duration of this object. 38 | */ 39 | default long duration() { 40 | return (this.timeFinal() - this.timeStart()); 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/util/object/structure/LengthObject.java: -------------------------------------------------------------------------------- 1 | package util.object.structure; 2 | 3 | import util.function.DistanceFunction; 4 | 5 | /** 6 | * A item that can be represented by its length. 7 | * 8 | * @author Hellisk 9 | * @since 30/03/2019 10 | */ 11 | public class LengthObject implements Comparable { 12 | 13 | private final DistanceFunction distFunc; 14 | private double length; 15 | private String parentID; 16 | 17 | LengthObject(DistanceFunction df) { 18 | this.length = 0; 19 | this.parentID = ""; 20 | this.distFunc = df; 21 | } 22 | 23 | LengthObject(double length, String parentID, DistanceFunction df) { 24 | this.length = length; 25 | this.parentID = parentID; 26 | this.distFunc = df; 27 | } 28 | 29 | public double getLength() { 30 | return length; 31 | } 32 | 33 | public void setLength(double length) { 34 | this.length = length; 35 | } 36 | 37 | public String getID() { 38 | return this.parentID; 39 | } 40 | 41 | public void setID(String parentID) { 42 | this.parentID = parentID; 43 | } 44 | 45 | public DistanceFunction getDistanceFunction() { 46 | return distFunc; 47 | } 48 | 49 | @Override 50 | public int compareTo(LengthObject o) { 51 | if (o == null) 52 | throw new NullPointerException(); 53 | return Double.compare(this.length, o.length); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/util/object/structure/MatchResultWithUnmatchedTraj.java: -------------------------------------------------------------------------------- 1 | package util.object.structure; 2 | 3 | /* 4 | The matching result of a trajectory, including the matching result and the derived unmatched trajectories. 5 | */ 6 | 7 | import util.object.spatialobject.Trajectory; 8 | 9 | import java.io.Serializable; 10 | import java.util.List; 11 | 12 | public class MatchResultWithUnmatchedTraj implements Serializable { 13 | 14 | private MultipleTrajectoryMatchResult matchResult; 15 | private List> unmatchedTrajectoryList; 16 | 17 | public MatchResultWithUnmatchedTraj(MultipleTrajectoryMatchResult matchResult, List> unmatchedTrajectoryList) { 18 | this.matchResult = matchResult; 19 | this.unmatchedTrajectoryList = unmatchedTrajectoryList; 20 | } 21 | 22 | public String getTrajID() { 23 | return matchResult.getTrajID(); 24 | } 25 | 26 | public MultipleTrajectoryMatchResult getMatchResult() { 27 | return matchResult; 28 | } 29 | 30 | public List> getUnmatchedTrajectoryList() { 31 | return unmatchedTrajectoryList; 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/util/object/structure/Pair.java: -------------------------------------------------------------------------------- 1 | package util.object.structure; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * A wrapper to store a pair of objects (auxiliary object). 7 | * 8 | * @param Type of the first object of the pair. 9 | * @param Type of the second object of the pair. 10 | * @author uqdalves 11 | */ 12 | public class Pair implements Serializable { 13 | /** 14 | * The two objects to pair 15 | */ 16 | private T _1; 17 | private S _2; 18 | 19 | /** 20 | * Creates a new pair of objects. 21 | * 22 | * @param _1 The first object of the pair. 23 | * @param _2 The second object of the pair. 24 | */ 25 | public Pair(T _1, S _2) { 26 | this._1 = _1; 27 | this._2 = _2; 28 | } 29 | 30 | /** 31 | * @return The first object of the pair. 32 | */ 33 | public T _1() { 34 | return _1; 35 | } 36 | 37 | /** 38 | * @return The second object of the pair. 39 | */ 40 | public S _2() { 41 | return _2; 42 | } 43 | 44 | @Override 45 | public int hashCode() { 46 | final int prime = 31; 47 | int result = 1; 48 | result = prime * result + ((_1 == null) ? 0 : _1.hashCode()); 49 | result = prime * result + ((_2 == null) ? 0 : _2.hashCode()); 50 | return result; 51 | } 52 | 53 | @Override 54 | public boolean equals(Object obj) { 55 | if (this == obj) return true; 56 | if (obj == null) return false; 57 | if (getClass() != obj.getClass()) return false; 58 | Pair other = (Pair) obj; 59 | if (_1 == null) { 60 | if (other._1 != null) 61 | return false; 62 | } else if (!_1.equals(other._1)) 63 | return false; 64 | if (_2 == null) { 65 | return other._2 == null; 66 | } else return _2.equals(other._2); 67 | } 68 | 69 | public void set_2(S _2) { 70 | this._2 = _2; 71 | } 72 | 73 | public void set_1(T _1) { 74 | this._1 = _1; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/util/object/structure/Triplet.java: -------------------------------------------------------------------------------- 1 | package util.object.structure; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * A wrapper to store a triplet of objects (auxiliary object). 7 | * 8 | * @param Type of the first object of the triplet. 9 | * @param Type of the second object of the triplet. 10 | * @param Type of the third object of the triplet. 11 | * @author Hellisk 12 | */ 13 | public class Triplet implements Serializable { 14 | /** 15 | * The three objects to combine 16 | */ 17 | private final T _1; 18 | private final S _2; 19 | private final R _3; 20 | 21 | /** 22 | * Creates a new triplet of objects. 23 | * 24 | * @param _1 The first object of the triplet. 25 | * @param _2 The second object of the triplet. 26 | * @param _3 The third object of the triplet. 27 | */ 28 | public Triplet(T _1, S _2, R _3) { 29 | this._1 = _1; 30 | this._2 = _2; 31 | this._3 = _3; 32 | } 33 | 34 | /** 35 | * @return The first object of the triplet. 36 | */ 37 | public T _1() { 38 | return _1; 39 | } 40 | 41 | /** 42 | * @return The second object of the triplet. 43 | */ 44 | public S _2() { 45 | return _2; 46 | } 47 | 48 | /** 49 | * @return The third object of the triplet. 50 | */ 51 | public R _3() { 52 | return _3; 53 | } 54 | 55 | @Override 56 | public int hashCode() { 57 | final int prime = 31; 58 | int result = 1; 59 | result = prime * result + ((_1 == null) ? 0 : _1.hashCode()); 60 | result = prime * result + ((_2 == null) ? 0 : _2.hashCode()); 61 | result = prime * result + ((_3 == null) ? 0 : _3.hashCode()); 62 | return result; 63 | } 64 | 65 | @Override 66 | public boolean equals(Object obj) { 67 | if (this == obj) return true; 68 | if (obj == null) return false; 69 | if (getClass() != obj.getClass()) return false; 70 | Triplet other = (Triplet) obj; 71 | if (_1 == null) { 72 | if (other._1 != null) 73 | return false; 74 | } else if (!_1.equals(other._1)) 75 | return false; 76 | if (_2 == null) { 77 | return other._2 == null; 78 | } else if (!_2.equals(other._2)) 79 | return false; 80 | if (_3 == null) { 81 | return other._3 == null; 82 | } else return _3.equals(other._3); 83 | } 84 | } -------------------------------------------------------------------------------- /src/main/java/util/settings/MapServiceLogger.java: -------------------------------------------------------------------------------- 1 | package util.settings; 2 | 3 | import org.apache.log4j.Logger; 4 | import org.apache.log4j.PropertyConfigurator; 5 | import util.io.IOService; 6 | 7 | import java.io.InputStream; 8 | 9 | /** 10 | * Log entry for simple file logs using log4j package 11 | * 12 | * @author Hellisk 13 | * @since 25/02/2019 14 | */ 15 | public class MapServiceLogger { 16 | 17 | /** 18 | * Initialise the log file of the project given the file path and name 19 | * 20 | * @param logPath The file path for storing logs. All the path should end with "/" 21 | * @param fileName The file name for the log without extension ".log" 22 | */ 23 | public static void logInit(String logPath, String fileName) { 24 | System.setProperty("logfile.name", logPath + fileName + ".log"); 25 | // create the log folder if not exist, set the log file name 26 | IOService.createFolder(logPath); 27 | // read the log settings from property file 28 | InputStream in = MapServiceLogger.class.getClassLoader().getResourceAsStream("log4j.properties"); 29 | PropertyConfigurator.configure(in); // refresh the log file path property 30 | final Logger LOG = Logger.getLogger(MapServiceLogger.class); // log entry 31 | LOG.debug("Log initialization done."); 32 | } 33 | } -------------------------------------------------------------------------------- /src/main/java/util/visualization/BlankMap.java: -------------------------------------------------------------------------------- 1 | package util.visualization; 2 | 3 | import de.fhpotsdam.unfolding.core.Coordinate; 4 | import de.fhpotsdam.unfolding.providers.OpenStreetMap; 5 | import processing.core.PApplet; 6 | 7 | public class BlankMap { 8 | 9 | public static abstract class BlankMapProvider extends OpenStreetMap.OpenStreetMapProvider { 10 | 11 | BlankMapProvider() { 12 | super(); 13 | } 14 | 15 | public String getZoomString(Coordinate coordinate) { 16 | // Rows are numbered from bottom to top (opposite to OSM) 17 | float gridSize = PApplet.pow(2, coordinate.zoom); 18 | float negativeRow = gridSize - coordinate.row - 1; 19 | 20 | return (int) coordinate.zoom + "/" + (int) coordinate.column + "/" + (int) negativeRow; 21 | } 22 | 23 | public String getPositiveZoomString(Coordinate coordinate) { 24 | float gridSize = PApplet.pow(2, coordinate.zoom); 25 | 26 | return (int) coordinate.zoom + "/" + (int) coordinate.column + "/" + (int) coordinate.row; 27 | } 28 | } 29 | 30 | public static class BlankProvider extends BlankMapProvider { 31 | public String[] getTileUrls(Coordinate coordinate) { 32 | String localDir = System.getProperty("user.dir"); 33 | String url = "file:///" + localDir + "/files/blank tile.png"; 34 | return new String[]{url}; 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/main/java/util/visualization/VisualizationMain.java: -------------------------------------------------------------------------------- 1 | package util.visualization; 2 | 3 | public class VisualizationMain { 4 | public static void main(String[] args) { 5 | System.setProperty("logfile.name", "display.log"); 6 | UnfoldingBeijingMapDisplay mapDisplay = new UnfoldingBeijingMapDisplay(); 7 | mapDisplay.display(); 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/__init__.py -------------------------------------------------------------------------------- /src/main/python/crif/README.md: -------------------------------------------------------------------------------- 1 | # Topic Model-based Road Network Inference from Massive Trajectories 2 | 3 | This project is the implementation of the paper [Topic Model-based Road Network Inference from Massive Trajectories](http://www.renj.me/roadnet.pdf) (MDM 2017) 4 | 5 | ## 1. Data 6 | 7 | Data Structure: (tid, x, y, lon, lat, time) 8 | 9 | ### 1.1 Chicago 10 | 11 | * Trajectories 12 | - utm_axis = (442551, 447326, 4634347, 4637377) 13 | - gps_axis = (41.858952 -87.69215 41.886565 -87.634896) 14 | - TrajMap 15 | + /Data/Chicago/chicago.pickle 16 | + id, x (utm), y (utm), t, tid 17 | - Biagioni 18 | + /Data/Chicago/all_trips 19 | * Real map 20 | - osm 21 | + /Data/Chicago/chicago_edges_osm.txt 22 | + /Data/Chicago/chicago_vertices_osm.txt 23 | - dataframe 24 | + /Data/Chicago/chicago_map_df.csv 25 | 26 | ### 1.2 Shanghai 27 | 28 | * Trajectories 29 | * Shanghai small data 30 | - utm_axis = (347500, 352500, 3447500, 3452500) 31 | - gps_axis = (121.4, 121.452, 31.1515, 31.197) 32 | - Data: 33 | + /Data/Shanghai/minsh_1000.pickle 34 | + /Data/Shanghai/minsh_1000_biagioni 35 | + /Data/Shanghai/minsh_5000.pickle 36 | + /Data/Shanghai/minsh_10000.pickle 37 | * Shanghai big data: 38 | - utm_axis = (345000, 365000, 3445000, 3465000) 39 | * Map: 40 | - /Data/Shanghai/sh_map_df.csv 41 | 42 | ### 1.3 Biagioni 43 | 44 | chicago_biagioni LineSegment 798 3.7801833333333335 45 | 46 | * data need to change 47 | - ./bounding_boxes 48 | * data need store 49 | - ./skeleton_maps/* 50 | * data after runing 51 | - ./*.png 52 | - ./trips/* 53 | - ./skeleton_images/* 54 | - ./skeleton_maps/* 55 | 56 | ## 2. Run experiment script 57 | 58 | ```bash 59 | python script.py 60 | ``` 61 | 62 | ## 3. Map-matching 63 | 64 | ```python 65 | data.index = range(len(data)) 66 | data[['tLon','tLat','pLon','pLat']] 67 | ``` 68 | 69 | ## 4. compile plsa 70 | 71 | ```bash 72 | python setup.py build_ext --inplace --force 73 | ``` 74 | 75 | ## 5. Parameters 76 | 77 | * $u_{ij}$: topic matrix with $j$ th topic and $i$ th cell 78 | * $k$: number of topics 79 | * $w$: grid width 80 | * $p$: padding -------------------------------------------------------------------------------- /src/main/python/crif/matcher/.ipynb_checkpoints/3.30 Matcher for Deep Learning-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 0 6 | } 7 | -------------------------------------------------------------------------------- /src/main/python/crif/matcher/__init__.py: -------------------------------------------------------------------------------- 1 | import train 2 | 3 | __all__ = [ 4 | 'train', 5 | ] 6 | -------------------------------------------------------------------------------- /src/main/python/crif/matcher/mathfunclib.py: -------------------------------------------------------------------------------- 1 | # 2 | # Mathematical function library. 3 | # Author: James P. Biagioni (jbiagi1@uic.edu) 4 | # Company: University of Illinois at Chicago 5 | # Created: 12/16/10 6 | # 7 | 8 | import math 9 | 10 | 11 | # Normal distribution PDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 12 | def normal_distribution_pdf(x, mu, sigma): 13 | return (1.0 / math.sqrt(2.0 * math.pi * math.pow(sigma, 2.0))) * math.exp( 14 | -1.0 * (math.pow((x - mu), 2.0) / (2.0 * math.pow(sigma, 2.0)))) 15 | 16 | 17 | # Normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 18 | def normal_distribution_cdf(x, mu, sigma): 19 | return (0.5 * (1.0 + erf((x - mu) / math.sqrt(2.0 * math.pow(sigma, 2.0))))) 20 | 21 | 22 | # Complementary normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Cumulative_distribution_function 23 | def complementary_normal_distribution_cdf(x, mu, sigma): 24 | return (1.0 - normal_distribution_cdf(x, mu, sigma)) 25 | 26 | 27 | # Spring force. Formula obtained from: http://en.wikipedia.org/wiki/Hooke%27s_law 28 | def spring_force(x, k): 29 | return ((-1.0 * k) * x) 30 | 31 | 32 | # Gaussian error function. Algorithm obtained from: http://www.johndcook.com/python_erf.html 33 | def erf(x): 34 | # constants 35 | a1 = 0.254829592 36 | a2 = -0.284496736 37 | a3 = 1.421413741 38 | a4 = -1.453152027 39 | a5 = 1.061405429 40 | p = 0.3275911 41 | 42 | # Save the sign of x 43 | sign = 1 44 | if x < 0: 45 | sign = -1 46 | x = abs(x) 47 | 48 | # A&S formula 7.1.26 49 | t = 1.0 / (1.0 + p * x) 50 | y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * math.exp(-x * x) 51 | 52 | return sign * y 53 | -------------------------------------------------------------------------------- /src/main/python/crif/matcher/pylibs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/matcher/pylibs/__init__.py -------------------------------------------------------------------------------- /src/main/python/crif/matcher/pylibs/mathfunclib.py: -------------------------------------------------------------------------------- 1 | # 2 | # Mathematical function library. 3 | # Author: James P. Biagioni (jbiagi1@uic.edu) 4 | # Company: University of Illinois at Chicago 5 | # Created: 12/16/10 6 | # 7 | 8 | import math 9 | 10 | 11 | # Normal distribution PDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 12 | def normal_distribution_pdf(x, mu, sigma, numerator=1.0): 13 | return (numerator / math.sqrt(2.0 * math.pi * math.pow(sigma, 2.0))) * math.exp( 14 | -1.0 * (math.pow((x - mu), 2.0) / (2.0 * math.pow(sigma, 2.0)))) 15 | 16 | 17 | # Normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 18 | def normal_distribution_cdf(x, mu, sigma): 19 | return (0.5 * (1.0 + erf((x - mu) / math.sqrt(2.0 * math.pow(sigma, 2.0))))) 20 | 21 | 22 | # Complementary normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Cumulative_distribution_function 23 | def complementary_normal_distribution_cdf(x, mu, sigma): 24 | return (1.0 - normal_distribution_cdf(x, mu, sigma)) 25 | 26 | 27 | # Spring force. Formula obtained from: http://en.wikipedia.org/wiki/Hooke%27s_law 28 | def spring_force(x, k): 29 | return ((-1.0 * k) * x) 30 | 31 | 32 | # Gaussian error function. Algorithm obtained from: http://www.johndcook.com/python_erf.html 33 | def erf(x): 34 | # constants 35 | a1 = 0.254829592 36 | a2 = -0.284496736 37 | a3 = 1.421413741 38 | a4 = -1.453152027 39 | a5 = 1.061405429 40 | p = 0.3275911 41 | 42 | # Save the sign of x 43 | sign = 1 44 | if x < 0: 45 | sign = -1 46 | x = abs(x) 47 | 48 | # A&S formula 7.1.26 49 | t = 1.0 / (1.0 + p * x) 50 | y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * math.exp(-x * x) 51 | 52 | return sign * y 53 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/mymap/db.sqlite3 -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mainapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/mymap/mainapp/__init__.py -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mainapp/admin.py: -------------------------------------------------------------------------------- 1 | # Register your models here. 2 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mainapp/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/mymap/mainapp/migrations/__init__.py -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mainapp/models.py: -------------------------------------------------------------------------------- 1 | # Create your models here. 2 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mainapp/tests.py: -------------------------------------------------------------------------------- 1 | # Create your tests here. 2 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mainapp/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | url(r'^$', views.index, name='index'), 7 | url(r'^ajax_lines/$', views.ajax_lines, name='ajax_lines'), 8 | ] 9 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mainapp/views.py: -------------------------------------------------------------------------------- 1 | from django.http import JsonResponse 2 | from django.shortcuts import render 3 | 4 | 5 | # Create your views here. 6 | 7 | def index(request): 8 | return render(request, 'mainapp/index.html') 9 | 10 | 11 | def ajax_lines(request): 12 | lines = [[ 13 | [116.288200, 39.835730], 14 | [116.288200, 39.835730], 15 | [116.288190, 39.835810], 16 | [116.288190, 39.835810], 17 | [116.288190, 39.835810], 18 | [116.286470, 39.835560], 19 | [116.286210, 39.835390], 20 | [116.286630, 39.834190], 21 | [116.286630, 39.834190], 22 | [116.280650, 39.838170], 23 | [116.277370, 39.852100], 24 | [116.277170, 39.855320], 25 | [116.304270, 39.865350], 26 | [116.307530, 39.867820], 27 | [116.307530, 39.867820], 28 | [116.305590, 39.875930], 29 | [116.311700, 39.877000], 30 | [116.311440, 39.881620], 31 | [116.310660, 39.885260], 32 | [116.310580, 39.885550], 33 | [116.303140, 39.883100], 34 | [116.295310, 39.879960], 35 | [116.292440, 39.879300], 36 | [116.286520, 39.888450], 37 | [116.280680, 39.888410], 38 | [116.278600, 39.887440], 39 | [116.278600, 39.887440], 40 | [116.278600, 39.887440], 41 | [116.278600, 39.887440], 42 | [116.278600, 39.887440], 43 | [116.278630, 39.887450], 44 | [116.278630, 39.887450], 45 | [116.278630, 39.887450], 46 | [116.278630, 39.887450], 47 | [116.278630, 39.887450], 48 | [116.278630, 39.887450], 49 | [116.278630, 39.887450], 50 | [116.278630, 39.887450], 51 | ]] 52 | return JsonResponse(lines, safe=False) 53 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | 4 | import sys 5 | 6 | if __name__ == "__main__": 7 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mymap.settings") 8 | 9 | from django.core.management import execute_from_command_line 10 | 11 | execute_from_command_line(sys.argv) 12 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mymap/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/mymap/mymap/__init__.py -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mymap/urls.py: -------------------------------------------------------------------------------- 1 | """mymap URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/dev/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Add an import: from blog import urls as blog_urls 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) 15 | """ 16 | from django.conf.urls import include, url 17 | from django.contrib import admin 18 | 19 | urlpatterns = [ 20 | url(r'^', include('mainapp.urls', namespace="mainapp")), 21 | url(r'^admin/', include(admin.site.urls)), 22 | ] 23 | -------------------------------------------------------------------------------- /src/main/python/crif/mymap/mymap/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mymap project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mymap.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /src/main/python/crif/src/__init__.py: -------------------------------------------------------------------------------- 1 | from .trajmap import Sag 2 | 3 | __all__ = ['Sag', ] 4 | -------------------------------------------------------------------------------- /src/main/python/crif/src/mf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Created by Albert Au Yeung (2010) 4 | # 5 | # An implementation of matrix factorization 6 | # 7 | try: 8 | import numpy 9 | except: 10 | print "This implementation requires the numpy module." 11 | exit(0) 12 | 13 | ############################################################################### 14 | 15 | """ 16 | @INPUT: 17 | R : a matrix to be factorized, dimension N x M 18 | P : an initial matrix of dimension N x K 19 | Q : an initial matrix of dimension M x K 20 | K : the number of latent features 21 | steps : the maximum number of steps to perform the optimisation 22 | alpha : the learning rate 23 | beta : the regularization parameter 24 | @OUTPUT: 25 | the final matrices P and Q 26 | """ 27 | 28 | 29 | def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02): 30 | Q = Q.T 31 | for step in xrange(steps): 32 | for i in xrange(len(R)): 33 | for j in xrange(len(R[i])): 34 | if R[i][j] > 0: 35 | eij = R[i][j] - numpy.dot(P[i, :], Q[:, j]) 36 | for k in xrange(K): 37 | P[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k]) 38 | Q[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j]) 39 | eR = numpy.dot(P, Q) 40 | e = 0 41 | for i in xrange(len(R)): 42 | for j in xrange(len(R[i])): 43 | if R[i][j] > 0: 44 | e = e + pow(R[i][j] - numpy.dot(P[i, :], Q[:, j]), 2) 45 | for k in xrange(K): 46 | e = e + (beta / 2) * (pow(P[i][k], 2) + pow(Q[k][j], 2)) 47 | if e < 0.001: 48 | break 49 | return P, Q.T 50 | 51 | 52 | ############################################################################### 53 | 54 | if __name__ == "__main__": 55 | R = [ 56 | [5, 3, 0, 1], 57 | [4, 0, 0, 1], 58 | [1, 1, 0, 5], 59 | [1, 0, 0, 4], 60 | [0, 1, 5, 4], 61 | ] 62 | 63 | R = numpy.array(R) 64 | 65 | N = len(R) 66 | M = len(R[0]) 67 | K = 2 68 | 69 | P = numpy.random.rand(N, K) 70 | Q = numpy.random.rand(M, K) 71 | 72 | nP, nQ = matrix_factorization(R, P, Q, K) 73 | print R 74 | print nP * nQ.T 75 | -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/README: -------------------------------------------------------------------------------- 1 | 2 | Dependencies for plsa.py: 3 | * Numpy 4 | 5 | Dependencies for example.py: 6 | 7 | * git clone http://www.mblondel.org/code/tfidf.git 8 | * git clone http://www.mblondel.org/code/taskmanager.git -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/src/plsa/__init__.py -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/_plsa.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/src/plsa/_plsa.so -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/build/lib.linux-x86_64-2.7/_plsa.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/src/plsa/build/lib.linux-x86_64-2.7/_plsa.so -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/build/temp.linux-x86_64-2.7/_plsa.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/src/plsa/build/temp.linux-x86_64-2.7/_plsa.o -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/build/temp.linux-x86_64-2.7/plsa_train.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/src/plsa/build/temp.linux-x86_64-2.7/plsa_train.o -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/example_lsa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | 5 | import taskmanager as tm 6 | 7 | from lsa import LSA 8 | from tfidf.preprocessing import read_files, preprocess_documents 9 | from tfidf.tfidf import * 10 | 11 | 12 | @tm.task(str) 13 | def feat(folder): 14 | docs = preprocess_documents(read_files(os.path.join(folder, "*.txt"))) 15 | assert (len(docs) > 0) 16 | # stemmer = PorterStemmer() 17 | # docs = stemmer.stem_documents(docs) 18 | td_dict, vocab = tc(docs) 19 | td = to_sparse_matrix(td_dict, vocab).toarray() 20 | idf = to_vector(idf_from_tc(td_dict), vocab) 21 | print "term-document matrix size", td.shape 22 | return td, idf, vocab 23 | 24 | 25 | @tm.task(feat) 26 | def train(data): 27 | td, idf, vocab = data 28 | td = td[:, :-1] 29 | lsa = LSA() 30 | return lsa.train(td, Z=10) 31 | 32 | 33 | @tm.task(feat, train) 34 | def folding_in(data, model): 35 | td, idf, vocab = data 36 | d = td[:, -1] 37 | lsa = LSA(model) 38 | print lsa.folding_in(d).shape 39 | 40 | 41 | @tm.nocache 42 | @tm.task(train) 43 | def document_topics(model): 44 | lsa = LSA(model) 45 | print lsa.document_topics().shape 46 | 47 | 48 | @tm.nocache 49 | @tm.task(train) 50 | def word_topics(model): 51 | lsa = LSA(model) 52 | print lsa.word_topics().shape 53 | 54 | 55 | @tm.nocache 56 | @tm.task(feat, train) 57 | def unigram_smoothing(data, model): 58 | td, idf, vocab = data 59 | td = td[:, :-1] 60 | lsa = LSA(model) 61 | res = lsa.unigram_smoothing() 62 | print res.shape 63 | print np.abs(td - res).sum() / float(res.shape[0] * res.shape[1]) 64 | 65 | 66 | @tm.nocache 67 | @tm.task(feat, train, int) 68 | def topic_labels(data, model, N=15): 69 | td, idf, vocab = data 70 | lsa = LSA(model) 71 | inv_vocab = inverse_vocab(vocab) 72 | print lsa.topic_labels(inv_vocab, N) 73 | 74 | 75 | def main(): 76 | import sys 77 | 78 | try: 79 | tm.TaskManager.OUTPUT_FOLDER = "./tmp" 80 | tm.run_command(sys.argv[1:]) 81 | except tm.TaskManagerError, m: 82 | print >> sys.stderr, m 83 | 84 | 85 | if __name__ == "__main__": 86 | main() 87 | -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from distutils.core import setup 3 | from distutils.extension import Extension 4 | 5 | import numpy as np 6 | from Cython.Distutils import build_ext 7 | 8 | setup( 9 | name="plsa", 10 | cmdclass={'build_ext': build_ext}, 11 | ext_modules=[Extension("_plsa", ["_plsa.pyx", "plsa_train.c"], 12 | include_dirs=[np.get_include(), '.'], 13 | extra_compile_args=['-O3'])], 14 | py_modules=['plsa', ], 15 | ) 16 | -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import unittest 4 | 5 | import numpy as np 6 | 7 | from plsa import normalize 8 | 9 | 10 | class UtilsTest(unittest.TestCase): 11 | 12 | def test_normalize(self): 13 | # 1d-case 14 | a = normalize(np.random.random(10)) 15 | self.assertAlmostEquals(1.0, np.sum(a)) 16 | 17 | # 1d-case where all values are 0 18 | a = normalize(np.array([0.0] * 10)) 19 | self.assertEquals(0.0, np.sum(a)) 20 | 21 | # 2d-case, axis 1 22 | M = normalize(np.random.random(20).reshape(2, 10), axis=1) 23 | res = M.sum(axis=1) # a 2-array 24 | self.assertAlmostEquals(1.0, res[0]) 25 | self.assertAlmostEquals(1.0, res[1]) 26 | 27 | # 2d-case, axis 0 28 | M = normalize(np.random.random(20).reshape(10, 2), axis=0) 29 | res = M.sum(axis=0) 30 | self.assertAlmostEquals(1.0, res[0]) 31 | self.assertAlmostEquals(1.0, res[1]) 32 | 33 | # 2d-case, where the normalized axis has length 1 34 | M_ = np.random.random(10).reshape(10, 1) 35 | M = normalize(M_, axis=1) 36 | self.assertTrue(np.array_equal(M, M_)) 37 | 38 | M_ = np.random.random(10).reshape(1, 10) 39 | M = normalize(M_, axis=0) 40 | self.assertTrue(np.array_equal(M, M_)) 41 | 42 | 43 | if __name__ == "__main__": 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/tfidf/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/crif/src/plsa/tfidf/__init__.py -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/tfidf/preprocessing.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import re 3 | import string 4 | 5 | 6 | def strip_punctuation(s): 7 | return re.sub("([%s]+)" % string.punctuation, " ", s) 8 | 9 | 10 | def strip_punctuation2(s): 11 | return s.translate(string.maketrans("", ""), string.punctuation) 12 | 13 | 14 | def strip_tags(s): 15 | # assumes s is already lowercase 16 | return re.sub(r"<([^>]+)>", "", s) 17 | 18 | 19 | def strip_short(s, minsize=3): 20 | return " ".join([e for e in s.split() if len(e) >= minsize]) 21 | 22 | 23 | def strip_numeric(s): 24 | return re.sub(r"[0-9]+", "", s) 25 | 26 | 27 | def strip_non_alphanum(s): 28 | # assumes s is already lowercase 29 | return re.sub(r"[^a-z0-9\ ]", " ", s) 30 | 31 | 32 | def strip_multiple_whitespaces(s): 33 | return re.sub(r"(\s|\\n|\\r|\\t)+", " ", s) 34 | # return s 35 | 36 | 37 | def split_alphanum(s): 38 | s = re.sub(r"([a-z]+)([0-9]+)", r"\1 \2", s) 39 | return re.sub(r"([0-9]+)([a-z]+)", r"\1 \2", s) 40 | 41 | 42 | STOPWORDS = """ 43 | a about again all almost also although always among an 44 | and another any are as at 45 | be because been before being between both but by 46 | can could 47 | did do does done due during 48 | each either enough especially etc 49 | for found from further 50 | had has have having here how however 51 | i if in into is it its itself 52 | just 53 | kg km 54 | made mainly make may mg might ml mm most mostly must 55 | nearly neither no nor not 56 | obtained of often on our overall 57 | perhaps pmid 58 | quite 59 | rather really regarding 60 | seem seen several should show showed shown shows significantly 61 | since so some such 62 | than that the their theirs them then there therefore these they too 63 | this those through thus to 64 | upon use used using 65 | various very 66 | was we were what when which while with within without would will 67 | """ 68 | 69 | STOPWORDS = dict((w, 1) for w in STOPWORDS.strip().replace("\n", " ").split()) 70 | 71 | 72 | def remove_stopwords(s): 73 | return " ".join([w for w in s.split() if w not in STOPWORDS]) 74 | 75 | 76 | DEFAULT_FILTERS = [str.lower, strip_tags, strip_punctuation, 77 | strip_multiple_whitespaces, strip_numeric, remove_stopwords, strip_short] 78 | 79 | 80 | def preprocess_string(s, filters=DEFAULT_FILTERS): 81 | for f in filters: 82 | s = f(s) 83 | return s 84 | 85 | 86 | def preprocess_documents(docs): 87 | return map(preprocess_string, docs) 88 | 89 | 90 | def read_file(path): 91 | f = open(path) 92 | ret = f.read() 93 | return ret 94 | 95 | 96 | def read_files(pattern): 97 | return map(read_file, glob.glob(pattern)) 98 | -------------------------------------------------------------------------------- /src/main/python/crif/src/plsa/tfidf/smoothing.py: -------------------------------------------------------------------------------- 1 | def laplace(td): 2 | """ 3 | Laplace smoothing a.k.a as "add one" smoothing. 4 | 5 | In a bayesian setting, this corresponds to a uniform prior on events. 6 | 7 | It has a tendency to over-estimate probabilities of unseen terms for large 8 | matrices. 9 | 10 | td: V x X term document matrix 11 | """ 12 | V, X = td.shape 13 | return (1.0 + td) / (V + td.sum(axis=0)) 14 | 15 | 16 | def lidstone(td, lambda_=0.5): 17 | V, X = td.shape 18 | return (lambda_ + td) / (V * lambda_ + td.sum(axis=0)) 19 | -------------------------------------------------------------------------------- /src/main/python/crif/src/tools.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | 4 | import numpy as np 5 | import pandas as pd 6 | import sys 7 | 8 | 9 | def sample(data, k): 10 | tids = data.tid.unique() 11 | df = pd.DataFrame() 12 | i = 0 13 | for tid in random.sample(tids, k): 14 | _df = data[data.tid == tid].copy() 15 | _df.tid = i 16 | df = pd.concat([df, _df]) 17 | i += 1 18 | return df 19 | 20 | 21 | def to_biagioni(data, to_folder, x='lon', y='lat'): 22 | print os.system('mkdir %s' % (to_folder)) 23 | trip_counter = 0 24 | data['pid'] = range(1, len(data) + 1) 25 | data['timestamp'] = (data.time.values - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's') 26 | if not to_folder.endswith('/'): 27 | to_folder += '/' 28 | for tid in data.tid.unique(): 29 | file_name = "trip_%d.txt" % (tid) 30 | # print to_folder+file_name 31 | f = open(to_folder + file_name, 'w') 32 | d = data[data.tid == tid] 33 | i = 0 34 | for idx, row in d.iterrows(): 35 | if ((trip_counter % 100 == 0) or (trip_counter == len(data))): 36 | sys.stdout.write("\rCompleted: " + str(trip_counter) + "/" + str(len(data)) + "... ") 37 | sys.stdout.flush() 38 | if i == 0: 39 | f.write("%d,%f,%f,%.1f,%s,%d\n" % (row.pid, row[y], row[x], row.timestamp, 'None', row.pid + 1)) 40 | elif i == len(d) - 1: 41 | f.write("%d,%f,%f,%.1f,%d,%s\n" % (row.pid, row[y], row[x], row.timestamp, row.pid - 1, 'None')) 42 | else: 43 | f.write("%d,%f,%f,%.1f,%d,%d\n" % (row.pid, row[y], row[x], row.timestamp, row.pid - 1, row.pid + 1)) 44 | i += 1 45 | trip_counter += 1 46 | 47 | 48 | def to_ahmed(data, to_folder, x='x', y='y', time='t'): 49 | print os.system('mkdir %s' % (to_folder)) 50 | trip_counter = 0 51 | data['pid'] = range(1, len(data) + 1) 52 | data[time] = (data.time.values - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's') 53 | if not to_folder.endswith('/'): 54 | to_folder += '/' 55 | for tid in data.tid.unique(): 56 | file_name = "trip_%d.txt" % (tid) 57 | # print to_folder+file_name 58 | f = open(to_folder + file_name, 'w') 59 | d = data[data.tid == tid] 60 | i = 0 61 | for idx, row in d.iterrows(): 62 | if ((trip_counter % 100 == 0) or (trip_counter == len(data))): 63 | sys.stdout.write("\rCompleted: " + str(trip_counter) + "/" + str(len(data)) + "... ") 64 | sys.stdout.flush() 65 | f.write("%f %f %.1f\n" % (row[x], row[y], row.t)) 66 | 67 | i += 1 68 | trip_counter += 1 69 | 70 | 71 | if __name__ == '__main__': 72 | pass 73 | -------------------------------------------------------------------------------- /src/main/python/crif/src/turn_script.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pp 4 | 5 | data = 'minsh_1000' 6 | # data = 'chicago' 7 | # ex_name = 'topic2road_inc' 8 | ex_name = 'turn_hmm' 9 | 10 | 11 | def cmdline(ex_name, data, limit=-1): 12 | cmd = 'python sacred_turn_hmm.py with ex_name=%s data=%s limit=%d' % (ex_name, data, limit) 13 | return cmd 14 | 15 | 16 | def execute(cmd): 17 | print cmd 18 | ret = os.popen(cmd).read() 19 | # ret = os.system(cmd) 20 | ''' 21 | if ret == 256: 22 | print 'KeyboardInterrupt' 23 | exit() 24 | return ret 25 | ''' 26 | print ret 27 | return 1 28 | 29 | 30 | ppservers = () 31 | job_server = pp.Server(ppservers=ppservers) 32 | job_server.set_ncpus(6) 33 | print "Starting pp with", job_server.get_ncpus(), "workers" 34 | 35 | idx = 0 36 | jobs = [] 37 | for data in ['minsh_2000', 'minsh_4000', 'minsh_6000', 'minsh_8000', 'minsh_10000']: 38 | # for data in ['minsh_1000']: 39 | for limit in [-1]: 40 | idx += 1 41 | cmd = cmdline(ex_name, data, limit) 42 | # execute(cmd) 43 | jobs.append([idx, cmd, job_server.submit(execute, (cmd,), )]) 44 | 45 | for idx, cmd, job in jobs: 46 | print '%d/%d: %s Return: %d' % (idx, len(jobs), cmd, job()) 47 | 48 | job_server.print_stats() 49 | -------------------------------------------------------------------------------- /src/main/python/crif/visual/gmap.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Simple Polylines 7 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |

27 | 79 | 81 | 82 | -------------------------------------------------------------------------------- /src/main/python/crif/visual/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 基本地图展示 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 |
20 |
21 | 背景 22 | 道路 23 | 建筑物 24 | 标注 25 |
26 | 27 | 39 |
40 | 41 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/main/python/crif/visual/index_backup.html: -------------------------------------------------------------------------------- 1 | trajectories.html 2 | heatmap.html -------------------------------------------------------------------------------- /src/main/python/crif/visual/trajectories.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 23 | 24 | 25 | Trajectories 26 | 27 | 28 |
29 |
30 | 31 | 32 |
33 | 34 | 35 | 62 | -------------------------------------------------------------------------------- /src/main/python/crif/visual/transform.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 设置地图显示内容 8 | 9 | 11 | 12 | 13 | 14 | 15 |
16 |
17 | 18 |
19 |
20 | 背景 21 | 道路 22 | 建筑物 23 | 标注 24 |
25 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/main/python/crif/visual/untransform.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 设置地图显示内容 8 | 9 | 11 | 12 | 13 | 14 | 15 |
16 |
17 | 18 |
19 |
20 | 背景 21 | 道路 22 | 建筑物 23 | 标注 24 |
25 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/main/python/kde/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/kde/__init__.py -------------------------------------------------------------------------------- /src/main/python/kde/mathfunclib.py: -------------------------------------------------------------------------------- 1 | # 2 | # Mathematical function library. 3 | # Author: James P. Biagioni (jbiagi1@uic.edu) 4 | # Company: University of Illinois at Chicago 5 | # Created: 12/16/10 6 | # 7 | 8 | import math 9 | 10 | 11 | # Normal distribution PDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 12 | def normal_distribution_pdf(x, mu, sigma): 13 | return (1.0 / math.sqrt(2.0 * math.pi * math.pow(sigma, 2.0))) * math.exp( 14 | -1.0 * (math.pow((x - mu), 2.0) / (2.0 * math.pow(sigma, 2.0)))) 15 | 16 | 17 | # Normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 18 | def normal_distribution_cdf(x, mu, sigma): 19 | return (0.5 * (1.0 + erf((x - mu) / math.sqrt(2.0 * math.pow(sigma, 2.0))))) 20 | 21 | 22 | # Complementary normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Cumulative_distribution_function 23 | def complementary_normal_distribution_cdf(x, mu, sigma): 24 | return (1.0 - normal_distribution_cdf(x, mu, sigma)) 25 | 26 | 27 | # Spring force. Formula obtained from: http://en.wikipedia.org/wiki/Hooke%27s_law 28 | def spring_force(x, k): 29 | return ((-1.0 * k) * x) 30 | 31 | 32 | # Gaussian error function. Algorithm obtained from: http://www.johndcook.com/python_erf.html 33 | def erf(x): 34 | # constants 35 | a1 = 0.254829592 36 | a2 = -0.284496736 37 | a3 = 1.421413741 38 | a4 = -1.453152027 39 | a5 = 1.061405429 40 | p = 0.3275911 41 | 42 | # Save the sign of x 43 | sign = 1 44 | if x < 0: 45 | sign = -1 46 | x = abs(x) 47 | 48 | # A&S formula 7.1.26 49 | t = 1.0 / (1.0 + p * x) 50 | y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * math.exp(-x * x) 51 | 52 | return sign * y 53 | -------------------------------------------------------------------------------- /src/main/python/kde/pylibs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/kde/pylibs/__init__.py -------------------------------------------------------------------------------- /src/main/python/kde/pylibs/mathfunclib.py: -------------------------------------------------------------------------------- 1 | # 2 | # Mathematical function library. 3 | # Author: James P. Biagioni (jbiagi1@uic.edu) 4 | # Company: University of Illinois at Chicago 5 | # Created: 12/16/10 6 | # 7 | 8 | import math 9 | 10 | 11 | # Normal distribution PDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 12 | def normal_distribution_pdf(x, mu, sigma, numerator=1.0): 13 | return (numerator / math.sqrt(2.0 * math.pi * math.pow(sigma, 2.0))) * math.exp( 14 | -1.0 * (math.pow((x - mu), 2.0) / (2.0 * math.pow(sigma, 2.0)))) 15 | 16 | 17 | # Normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Normal_Distribution 18 | def normal_distribution_cdf(x, mu, sigma): 19 | return (0.5 * (1.0 + erf((x - mu) / math.sqrt(2.0 * math.pow(sigma, 2.0))))) 20 | 21 | 22 | # Complementary normal distribution CDF. Formula obtained from: http://en.wikipedia.org/wiki/Cumulative_distribution_function 23 | def complementary_normal_distribution_cdf(x, mu, sigma): 24 | return (1.0 - normal_distribution_cdf(x, mu, sigma)) 25 | 26 | 27 | # Spring force. Formula obtained from: http://en.wikipedia.org/wiki/Hooke%27s_law 28 | def spring_force(x, k): 29 | return ((-1.0 * k) * x) 30 | 31 | 32 | # Gaussian error function. Algorithm obtained from: http://www.johndcook.com/python_erf.html 33 | def erf(x): 34 | # constants 35 | a1 = 0.254829592 36 | a2 = -0.284496736 37 | a3 = 1.421413741 38 | a4 = -1.453152027 39 | a5 = 1.061405429 40 | p = 0.3275911 41 | 42 | # Save the sign of x 43 | sign = 1 44 | if x < 0: 45 | sign = -1 46 | x = abs(x) 47 | 48 | # A&S formula 7.1.26 49 | t = 1.0 / (1.0 + p * x) 50 | y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * math.exp(-x * x) 51 | 52 | return sign * y 53 | -------------------------------------------------------------------------------- /src/main/python/kharita/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/kharita/__init__.py -------------------------------------------------------------------------------- /src/main/python/kharita/kharita.py: -------------------------------------------------------------------------------- 1 | """ 2 | author: rade 3 | Create the road network by merging trajectories. 4 | """ 5 | import getopt 6 | 7 | import sys 8 | import time 9 | 10 | from methods_kharita import getdata, computeclusters, coocurematrix, prunegraph, printedges 11 | 12 | if __name__ == '__main__': 13 | # Default parameters 14 | start = time.time(); 15 | # LL = (41, -87); 16 | # print(vincenty(LL, (LL[0] + 1, LL[1])).meters, vincenty(LL, (LL[0], LL[1] + 1)).meters) 17 | # latconst = vincenty(LL, (LL[0] + 1, LL[1])).meters; 18 | # lonconst = vincenty(LL, (LL[0], LL[1] + 1)).meters 19 | theta = 150; 20 | SEEDRADIUS = 100; 21 | datafile = '' # 'gps_points_01-10' 22 | write_file = '' 23 | noise_percent = -1 24 | max_noise_radius = -1 25 | drawmap = False 26 | (opts, args) = getopt.getopt(sys.argv[1:], "f:m:p:r:s:a:d:h") 27 | for o, a in opts: 28 | if o == "-f": 29 | datafile = str(a) 30 | if o == "-r": 31 | SEEDRADIUS = float(a) 32 | if o == "-s": 33 | theta = float(a) 34 | if o == "-p": 35 | write_file = str(a) 36 | if o == "-h": 37 | print("Usage: python kharita.py [-f ] [-r ] [-s = 10]; # filter low speed points 44 | print('datapoints with speed>=5kmph: ', len(datapointwts)) 45 | seeds = computeclusters(datapointwts, 50, SEEDRADIUS, theta); # compute k-means; seeds cluster centroids 46 | print('clusters: ', len(seeds), time.time() - start) 47 | gedges = coocurematrix(datapointwts, seeds, theta) # compute connectivity graph 48 | print('coocurence matrix computed: ', time.time() - start) 49 | gedges = prunegraph(gedges, seeds); # spanner; pruning edges 50 | print('graph pruning. number of edges = ', len(gedges), time.time() - start) 51 | printedges(gedges, seeds, datapointwts, write_file, theta) 52 | # plotmap(seeds, gedges, datapointwts) 53 | # plt.show() 54 | -------------------------------------------------------------------------------- /src/main/python/pif/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hellisk/map-service/694e0a056c8728e07659a3fdeaac1016e4d21678/src/main/python/pif/__init__.py -------------------------------------------------------------------------------- /src/main/python/pif/log_math_test.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright 2011, 2012 Timothy Hunter 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) version 3. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library. If not, see . 16 | ''' 17 | # pylint: disable=W0105 18 | ''' 19 | Created on Sep 2, 2011 20 | 21 | @author: tjhunter 22 | ''' 23 | 24 | import numpy as np 25 | from mm.log_math import lse, lse_vec, MINUS_INF 26 | 27 | # Forces Numpy to consider warnings as errors. 28 | np.seterr(all='raise') 29 | from numpy import log 30 | 31 | 32 | def log_safe(x): 33 | """ Ensure that log(0) == -inf and not an error. """ 34 | if x == 0.0: 35 | return -float('inf') 36 | return log(x) 37 | 38 | 39 | def test_1(): 40 | """ test_1 """ 41 | v = [1, 2, 0.0] 42 | lv = [log_safe(x) for x in v] 43 | assert abs(log(3) - lse(lv)) < 1e-6, (v, lv) 44 | 45 | 46 | def test_lse_vec_1(): 47 | ''' test_lse_vec_1 ''' 48 | # Trying to add a zero vector with itself 49 | xs = [(MINUS_INF, np.zeros(2))] 50 | (u, v) = lse_vec(xs) 51 | assert u == MINUS_INF, u 52 | assert np.abs(v).max() == 0 53 | 54 | 55 | def test_lse_vec_2(): 56 | ''' test_lse_vec_2 ''' 57 | # Trying to add a zero vector with itself 58 | xs = [(MINUS_INF, np.ones(2))] 59 | (u, v) = lse_vec(xs) 60 | assert u == MINUS_INF, u 61 | assert np.abs(v).max() == 0 62 | 63 | 64 | def test_2(): 65 | """ test_1 """ 66 | inf = float("inf") 67 | xs = [(log(3.0), np.ones(2)), (2, np.zeros(2)), \ 68 | (-inf, np.ones(2)), (-inf, np.zeros(2))] 69 | (norm, x) = lse_vec(xs) 70 | assert abs(norm - log(3)) < 1e-6, (norm, log(3), x) 71 | assert np.abs(x - 1).max() < 1e-6, (x) 72 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/HardFilter.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' 16 | Created on Nov 25, 2011 17 | 18 | @author: tjhunter 19 | ''' 20 | 21 | 22 | class HardFilter(object): 23 | """ Interface for a filter that performs hard assignments. 24 | 25 | Interesting fields: 26 | - traj : a trajectory object 27 | - assignments : a list of assignment (integer index, for each feature 28 | element of the trajectory) 29 | """ 30 | 31 | # pylint: disable=w0201 32 | def __init__(self): 33 | pass 34 | 35 | def computeAssignments(self): 36 | """ Computes the assignments. 37 | """ 38 | self.assignments = None 39 | raise NotImplementedError() 40 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/SoftFilter.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' 16 | Created on Nov 27, 2011 17 | 18 | @author: tjhunter 19 | ''' 20 | from mm.path_inference.HardFilter import HardFilter 21 | 22 | 23 | class SoftFilter(HardFilter): 24 | """ Interface for a filter that performs soft assignments (probability 25 | distributions). 26 | 27 | Interesting fields: 28 | - traj : a trajectory object 29 | - probabilities : list of numpy arrays 30 | - log_probabilities : list of numpy arrays 31 | - assignments : the most likely element, computed from the probabilities. 32 | """ 33 | 34 | # pylint: disable=w0201 35 | def __init__(self): 36 | HardFilter.__init__(self) 37 | 38 | def computeProbabilities(self): 39 | """ This function computes the values of self.probabilities 40 | and self.log_probabilities. 41 | """ 42 | self.probabilities = None 43 | raise NotImplementedError() 44 | 45 | def computeAssignments(self): 46 | self.assignments = [list(probs).index(max(probs)) for \ 47 | probs in self.probabilities] 48 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' Main package for path inference. 16 | 17 | Take a look at at the example to see how to use the classes in the package. 18 | 19 | More documentation should be added to run the optimizer. 20 | ''' 21 | from HardFilter import HardFilter 22 | from SoftFilter import SoftFilter 23 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/learning_traj_em.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' EM algorithm to optimize the parameters. 16 | 17 | Created on Sep 2, 2011 18 | 19 | @author: tjhunter 20 | ''' 21 | import numpy as np 22 | from mm.path_inference.learning_traj_optimizer import optimize_function 23 | from mm.path_inference.learning_traj_smoother import \ 24 | TrajectorySmoother1 25 | 26 | 27 | def get_traj_estims(trajs, theta): 28 | """ Given a set of trajectories, returns a set of trajectory estimates. 29 | 30 | i.e., a list of (traj, weights). weights is a sequence of probability 31 | vectors that contain the posterior probabilities from the smoother. 32 | """ 33 | 34 | def inner(traj): 35 | """ Inner function that does the work. """ 36 | smoother = TrajectorySmoother1(traj, theta) 37 | smoother.computeProbs() 38 | probabilities = smoother.probabilities 39 | del smoother 40 | return (traj, probabilities) 41 | 42 | return [inner(traj) for traj in trajs] 43 | 44 | 45 | def learn_em(opt_function_provider, trajs, start_value, \ 46 | max_iters=10, max_inner_iters=5): 47 | """ Learn EM function. 48 | 49 | Returns the history of the progression: list of: 50 | - log likelihood 51 | - learned parameter 52 | 53 | Arguments: 54 | - opt_function_provider: traj_estims -> (optimizable function) 55 | - trajs: a set of trajectories 56 | - start_value: numpy array, start vector 57 | - max_iters: maximum number of iterations 58 | """ 59 | theta = np.array(start_value) 60 | history = [] 61 | for step in range(max_iters): 62 | traj_estims = get_traj_estims(trajs, theta) 63 | opt_fun = opt_function_provider(traj_estims) 64 | (theta1, ys) = optimize_function(opt_fun, theta, max_inner_iters) 65 | print 'Epoch %i : %f' % (step, ys[-1]) 66 | history.append((ys[-1], theta1)) 67 | theta = theta1 68 | return history 69 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/learning_traj_em_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' Tests for the EM. 16 | 17 | Created on Sep 5, 2011 18 | 19 | @author: tjhunter 20 | ''' 21 | import numpy as np 22 | from mm.path_inference.learning_traj_em import learn_em 23 | from mm.path_inference.learning_traj_optimizer import trajs_estim_obj_fun_1 24 | from mm.path_inference.learning_traj_test import (simple_traj1, 25 | simple_traj4, simple_traj3) 26 | 27 | # Forces Numpy to consider warnings as errors. 28 | np.seterr(all='raise') 29 | 30 | 31 | def test_em_1(): 32 | """ Very simple test: we pick some trajectories and verify that 33 | the LL increases with EM. 34 | """ 35 | trajs = [simple_traj1(), simple_traj4(), simple_traj3()] 36 | theta_start = 0.1 * np.ones(2) 37 | history = learn_em(trajs_estim_obj_fun_1, trajs, theta_start) 38 | # (ll_end, theta_end) = history[-1] 39 | # Very simple check here: we verify the progression goes upward 40 | # the likelihood: 41 | for t in range(len(history) - 1): 42 | (ll_1, _) = history[t] 43 | (ll_2, _) = history[t + 1] 44 | assert ll_1 <= ll_2 45 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/mapping/Counter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright 2011, 2012 Timothy Hunter 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) version 3. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library. If not, see . 16 | ''' 17 | # pylint: disable=W0105 18 | ''' 19 | Created on Nov 8, 2011 20 | 21 | @author: tjhunter 22 | ''' 23 | from mm.path_inference.json import decode_StateCollection 24 | 25 | 26 | class Counter(object): 27 | """ Provide a counter class for collecting statistics on the objects. 28 | """ 29 | 30 | def __init__(self, filter_non_hired=False): 31 | self.count = 0 32 | self.num_states = [] 33 | self.filter_non_hired = filter_non_hired 34 | 35 | def call(self, dct): 36 | ''' closure ''' 37 | sc = decode_StateCollection(dct) 38 | # if self.filter_non_hired and sc.hired != True: 39 | # self.num_states.append(0) 40 | # else: 41 | self.num_states.append(len(sc.states)) 42 | self.count += 1 43 | return None 44 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/mapping/PathCounter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright 2011, 2012 Timothy Hunter 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) version 3. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library. If not, see . 16 | ''' 17 | # pylint: disable=W0105 18 | ''' 19 | Created on Nov 8, 2011 20 | 21 | @author: tjhunter 22 | ''' 23 | 24 | 25 | class PathCounter(object): 26 | """ Use it as a closure to count the paths. 27 | """ 28 | 29 | def __init__(self): 30 | self.count = 0 31 | self.num_paths = [] 32 | 33 | def call(self, dct): 34 | """ Closure call. 35 | """ 36 | (_, paths, _, _) = dct 37 | self.num_paths.append(len(paths)) 38 | self.count += 1 39 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/mapping/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright 2011, 2012 Timothy Hunter 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) version 3. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library. If not, see . 16 | ''' 17 | # pylint: disable=W0105 18 | """ Mapping data package. 19 | """ 20 | # Standard imports 21 | from Counter import Counter 22 | 23 | try: 24 | from FancyFeatureMapper import FancyFeatureMapper 25 | from FeatureMapper import FeatureMapper 26 | except ImportError: 27 | pass 28 | from HFDecimation import HFDecimation 29 | from FlowAnalysis import FlowAnalysis 30 | from PathCounter import PathCounter 31 | from SparseDecimation import SparseDecimation 32 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/path_builder.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' 16 | Created on Sep 20, 2011 17 | 18 | @author: tjhunter 19 | ''' 20 | 21 | 22 | class PathBuilder(object): 23 | """ Creates candidate paths between states. 24 | 25 | INTERFACE ONLY. 26 | """ 27 | 28 | def getPaths(self, s1, s2): 29 | """ Returns a set of candidate paths between state s1 and state s3. 30 | Arguments: 31 | - s1 : a State object 32 | - s2 : a State object 33 | """ 34 | raise NotImplementedError() 35 | 36 | def getPathsBetweenCollections(self, sc1, sc2): 37 | trans1 = [] 38 | trans2 = [] 39 | paths = [] 40 | n1 = len(sc1.states) 41 | n2 = len(sc2.states) 42 | num_paths = 0 43 | for i1 in range(n1): 44 | for i2 in range(n2): 45 | ps = self.getPaths(sc1.states[i1], sc2.states[i2]) 46 | for path in ps: 47 | trans1.append((i1, num_paths)) 48 | trans2.append((num_paths, i2)) 49 | paths.append(path) 50 | num_paths += 1 51 | return (trans1, paths, trans2) 52 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/projector.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' 16 | Created on Sep 20, 2011 17 | 18 | @author: tjhunter 19 | ''' 20 | 21 | 22 | class PointProjector(object): 23 | """ Interface that defines how a point is projected on the road network. 24 | """ 25 | 26 | def project(self, gps_pos): 27 | """ (abstract) : takes a GPS position and returns a collection of states. 28 | """ 29 | raise NotImplementedError() 30 | -------------------------------------------------------------------------------- /src/main/python/pif/path_inference/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011, 2012 Timothy Hunter 2 | # 3 | # This library is free software; you can redistribute it and/or 4 | # modify it under the terms of the GNU Lesser General Public 5 | # License as published by the Free Software Foundation; either 6 | # version 2.1 of the License, or (at your option) version 3. 7 | # 8 | # This library is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 11 | # Lesser General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU Lesser General Public 14 | # License along with this library. If not, see . 15 | ''' Utility functions for the path inference. 16 | Created on Sep 23, 2011 17 | 18 | @author: tjhunter 19 | 20 | ''' 21 | import math 22 | 23 | 24 | def haversine(lon1, lat1, lon2, lat2): 25 | """ 26 | Calculate the great circle distance between two points 27 | on the earth (specified in decimal degrees) 28 | """ 29 | # convert decimal degrees to radians 30 | lon1, lat1, lon2, lat2 = \ 31 | [math.radians(deg) for deg in [lon1, lat1, lon2, lat2]] 32 | # haversine formula 33 | dlon = lon2 - lon1 34 | dlat = lat2 - lat1 35 | a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * \ 36 | math.cos(lat2) * math.sin(dlon / 2) ** 2 37 | c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) 38 | meters = 6367 * c * 1000 39 | return meters 40 | 41 | 42 | def distance(gps1, gps2): 43 | """ Computes the distance (in meters) between two LatLng objects. 44 | """ 45 | return haversine(gps1.lng, gps1.lat, gps2.lng, gps2.lat) 46 | -------------------------------------------------------------------------------- /src/main/python/roadrunner/MergeDetector.py: -------------------------------------------------------------------------------- 1 | import StringIO 2 | import socket 3 | 4 | import math 5 | import numpy as np 6 | import scipy.ndimage 7 | from scipy.ndimage.filters import gaussian_filter 8 | 9 | 10 | def getGPSHistogram(lat2, lon2, lat1, lon1, lat0, lon0, radius, img_size, region, host="localhost", port=8002, center_lat=None, 11 | center_lon=None, filename="tmp.png"): 12 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 | s.connect((host, port)) 14 | 15 | if center_lat is None: 16 | center_lat = lat0 17 | center_lon = lon0 18 | 19 | minlat = region[0] 20 | maxlat = region[2] 21 | 22 | minlon = region[1] 23 | maxlon = region[3] 24 | 25 | data_string = "G," + str(lat2) + "," + str(lon2) + "," + str(lat1) + "," + str(lon1) + "," + str(lat0) + "," + str(lon0) + "," + str( 26 | radius) + "," + str(minlat) + "," + str(minlon) + "," + str(maxlat) + "," + str(maxlon) + "," + str(img_size) + ", " 27 | # print(data_string) 28 | s.send(data_string) 29 | num_str = s.recv(16384) 30 | num = int(num_str.split(' ')[1]) 31 | 32 | # print(num_str) 33 | s.send("ok") 34 | 35 | result = "" 36 | for i in range(num): 37 | result += s.recv(16384) 38 | 39 | imgfile = StringIO.StringIO(result) 40 | # #print(len(result)) 41 | 42 | # f = open("tmp"+filename, 'wb') 43 | 44 | # f.write(result) 45 | # f.close() 46 | 47 | img = scipy.ndimage.imread(imgfile) 48 | 49 | img = img.astype(np.float) 50 | 51 | # GPSHistogramCache[(lat2, lon2, lat1, lon1, lat0, lon0, radius, img_size)] = gps_img/255.0 52 | 53 | return img 54 | 55 | 56 | def mergeDetector(path1, path2, port=8002): 57 | lat = path1[0][0] 58 | lon = path1[0][1] 59 | 60 | size = 0.00400 # 200 meters 61 | 62 | sub_region = [lat - size, lon - size / math.cos(math.radians(lat)), lat + size, lon + size / math.cos(math.radians(lat))] 63 | 64 | img1 = getGPSHistogram(path1[5][0], path1[5][1], path1[3][0], path1[3][1], path1[0][0], path1[0][1], 0.00005, 512, sub_region, 65 | filename="path1.png", port=port) 66 | img2 = getGPSHistogram(path2[5][0], path2[5][1], path2[3][0], path2[3][1], path2[0][0], path2[0][1], 0.00005, 512, sub_region, 67 | filename="path2.png", port=port) 68 | 69 | img1[192:320, 192:320] = 0 70 | img2[192:320, 192:320] = 0 71 | 72 | blurred1 = gaussian_filter(img1, sigma=4) 73 | blurred2 = gaussian_filter(img2, sigma=4) 74 | 75 | m1 = np.amax(blurred1) 76 | m2 = np.amax(blurred2) 77 | 78 | if m1 != 0: 79 | blurred1 /= m1 80 | 81 | if m2 != 0: 82 | blurred2 /= m2 83 | 84 | diff = blurred2 - blurred1 85 | diff[np.where(diff < 0)] = 0 86 | 87 | sum_diff = np.sum(diff) 88 | sum_2 = np.sum(blurred2) 89 | 90 | if sum_2 == 0: 91 | return 0.0 92 | 93 | # print(sum_diff, sum_2, 1.0 - sum_diff/sum_2) 94 | 95 | return 1.0 - sum_diff / sum_2 96 | -------------------------------------------------------------------------------- /src/main/resources/cooptimization.properties: -------------------------------------------------------------------------------- 1 | # Available dataset: Beijing-(S,M,L) 2 | OS=Win 3 | data.RootPath=C:/data/ 4 | data.Dataset=Beijing-S 5 | data.BoundingBoxS=116.4,116.435,39.95,39.98 6 | data.BoundingBoxM=116.34,116.44,39.89,39.95 7 | data.BoundingBoxL=0 8 | data.IsRawInitRequired=true 9 | data.IsManualGTRequired=false 10 | # Tunable parameters 11 | data.TrajectoryMinimalLengthSec=-1 12 | data.SampleMaximalIntervalSec=-1 13 | data.NumberOfTrajectory=-1 14 | algorithm.cooptimization.data.RoadRemovalPercentage=0 15 | # The trajectory point will be included as unmatched point if no candidate is found within range 16 | algorithm.cooptimization.GapExtensionDistance=15 17 | algorithm.cooptimization.CorrectRoadPercentage=20 18 | # Index-based trajectory filter: 0(no index), 1(DMA), 2(DMA + STA) 19 | algorithm.cooptimization.IndexFilter=0 20 | # The factor of the index-based DMA bounding box 21 | algorithm.cooptimization.IndexBBFactor=1 22 | # The weight of linearly combining confidence and influence score 23 | algorithm.cooptimization.ScoreLambda=0.5 24 | # Whether there is new road inside the map, initial value is false. Only set true during the co-optimization process. 25 | algorithm.cooptimization.isNewRoadIncluded=false 26 | algorithm.mapmatching.hmm.Beta=0.08 27 | # Used also in filtering input trajectory points. Point whose distance to its predecessor closer than 2*SIGMA is removed 28 | algorithm.mapmatching.Sigma=4 29 | algorithm.mapmatching.CandidateRange=50 30 | # The k of the top-k map-matching results 31 | algorithm.mapmatching.hmm.RankLength=3 32 | algorithm.mapmatching.hmm.UTurnPenalty=50 33 | # Used when trajectory point move backwards due to GPS noise 34 | algorithm.mapmatching.hmm.BackwardsFactor=0.2 35 | # Available map mapinference methods: LC(TraceClustering from Liu2012), KDE(KDE-based method from Biagioni2012) 36 | algorithm.mapinference.InferenceMethod=LC 37 | algorithm.mapinference.kde.CellSize=1 38 | algorithm.mapinference.kde.GaussianBlur=17 39 | # Maximum allowable angle change within a road segment, used for 40 | algorithm.mapinference.lineclustering.MaximumAngleChangeDegree=15 41 | # Epsilon for Douglas-Peucker filter 42 | algorithm.mapinference.lineclustering.DPEpsilon=10 43 | # Maximum merge distance between two unmatched trajectories when merging clustered trajectory segmentation 44 | algorithm.mapinference.lineclustering.MaximumClusteringDistance=50 45 | algorithm.mapmerge.MinimumRoadLength=30 46 | # The maximum allowed distance to attach a end point to an intersection 47 | algorithm.mapmerge.SubTrajectoryMergeDistance=15 -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Define the root logger with appender file 2 | log4j.rootLogger=INFO, file, stdout 3 | # Define the file appender 4 | log4j.appender.file=org.apache.log4j.FileAppender 5 | log4j.appender.file.File=${logfile.name} 6 | # Define the layout for file appender 7 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 8 | log4j.appender.file.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%C{1}]: %m%n 9 | # Direct log messages to stdout 10 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 11 | log4j.appender.stdout.Target=System.out 12 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 13 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p [%C{1}]: %m%n -------------------------------------------------------------------------------- /src/main/resources/mapinference.properties: -------------------------------------------------------------------------------- 1 | # Available OS: Win,Linux 2 | OS=Win 3 | data.RootPath=C:/data/ 4 | #data.RootPath=F:/data/ 5 | #data.RootPath=/home/uqpchao/data/ 6 | data.PythonCodeRootPath=C:/Users/uqpchao/OneDrive/code/github/map-service/src/main/python/ 7 | #data.PythonCodeRootPath=F:/OneDrive/code/github/map-service/src/main/python/ 8 | #data.PythonCodeRootPath=/home/uqpchao/code/map-service/src/main/python/ 9 | # Available datasets: Beijing-S,Beijing-M,Beijing-L,Chicago,Berlin 10 | data.Dataset=Beijing-S 11 | data.BoundingBoxS=116.4,116.435,39.95,39.98 12 | data.BoundingBoxM=116.34,116.44,39.89,39.95 13 | data.BoundingBoxL=0 14 | data.BoundingBoxChicago=441000.060093,447999.42519,4633501.598592,4637999.749903 15 | data.BoundingBoxBerlin=390000.822516,395198.155647,5817001.478875,5822996.116636 16 | # Trajectory preprocessing parameters 17 | data.TrajectoryMinimalLengthSec=180 18 | data.SampleMaximalIntervalSec=120 19 | data.NumberOfTrajectory=-1 20 | # specs for synthetic trajectory generation 21 | data.IsSyntheticTrajectory=true 22 | data.Sigma=10 23 | data.SamplingInterval=5 24 | data.Coverage=-1 25 | # Available map mapinference methods: LC(LineClustering from Liu2012), TM(TraceMerging from Ahmed2012), KDE(KDE-based method from 26 | # Biagioni2012), RR(RoadRunner from He2018), CRIF(TopicModel from Zheng17), KHA (Kharita from Stanojevic18) 27 | algorithm.mapinference.InferenceMethod=CRIF 28 | algorithm.mapinference.kde.CellSize=1 29 | algorithm.mapinference.kde.GaussianBlur=20 30 | # Maximum allowable angle change within a road segment 31 | algorithm.mapinference.lineclustering.MaximumAngleChangeDegree=15 32 | # Epsilon for Douglas-Peucker filter 33 | algorithm.mapinference.lineclustering.DPEpsilon=80 34 | # Maximum merge distance between two unmatched trajectories when merging clustered trajectory segmentation 35 | algorithm.mapinference.lineclustering.MaximumClusteringDistance=40 36 | # Epsilon used in trace merge algorithm. The default settings in paper is 150. Our value should be 2*(trajectory_measurement_error)=100 37 | algorithm.mapinference.tracemerge.Epsilon=40 38 | # parameters for RoadRunner algorithm. 39 | algorithm.mapinference.roadrunner.HistoryLength=4 40 | algorithm.mapinference.roadrunner.NumberOfDeferredBranch=5 41 | algorithm.mapinference.roadrunner.MinNumberOfTrajectory=2 42 | # cell width in the algorithm. Another parameter h follows the formula h*cw=50 43 | algorithm.mapinference.crif.CellWidth=5 44 | # parameters for Kharita point clustering algorithm 45 | algorithm.mapinference.pointclustering.Radius=40 46 | algorithm.mapinference.pointclustering.DensityDistance=20 47 | algorithm.mapinference.pointclustering.AngleTolerance=60 -------------------------------------------------------------------------------- /src/main/resources/mapmatching.properties: -------------------------------------------------------------------------------- 1 | # Available OS: Win,Linux 2 | OS=Win 3 | data.RootPath=C:/data/ 4 | # Available dataset: Global,Beijing-S,Beijing-R,Beijing-M,Beijing-L 5 | data.Dataset=Beijing-S 6 | data.BoundingBoxS=116.4,116.435,39.95,39.98 7 | data.BoundingBoxM=116.34,116.44,39.89,39.95 8 | data.BoundingBoxR=116.5,116.535,40.00,40.03 9 | data.BoundingBoxL=0 10 | # Trajectory preprocessing parameters 11 | data.TrajectoryMinimalLengthSec=180 12 | data.SampleMaximalIntervalSec=120 13 | data.NumberOfTrajectory=-1 14 | # down-sample the trajectory by pick one point from every 'data.DownSample' points 15 | data.DownSample=3 16 | # specs for synthetic trajectory generation 17 | data.IsSyntheticTrajectory=false 18 | data.Sigma=5 19 | data.SamplingInterval=5 20 | # percentage of points that are outliers 21 | data.OutlierPct=2 22 | # Available map-matching methods: 23 | # OF-HMM-old(Newson09 with breakpoint management),OF-HMM(Newson09),ON-HMM-goh(Goh12),ON-HMM-eddy(Wang13),ON-HMM-fixed(Newson09),ON-WGT 24 | # (Yin18), ON-SCO(Quddus15) 25 | algorithm.mapmatching.MatchingMethod=OF-HMM 26 | # Search radius for point candidate, default=20m, ON-MHT default=30m 27 | algorithm.mapmatching.CandidateRange=20 28 | algorithm.mapmatching.NumOfThreads=-1 29 | algorithm.mapmatching.WindowSize=10 30 | # The tolerance for Douglas-Peucker algorithm, measured in meter 31 | algorithm.mapmatching.Tolerance=0 32 | # Emission probability standard deviation, default=5m 33 | algorithm.mapmatching.Sigma=4 34 | # Transition weighting factor 35 | algorithm.mapmatching.hmm.Beta=0.008 36 | # The weight of turn cost 37 | algorithm.mapmatching.hmm.turnWeight=0 38 | # The candidate size for each key point 39 | algorithm.mapmatching.wgt.CandidateSize=10 40 | # The maximum bound for distance weight between candidate road segment and trajectory points 41 | algorithm.mapmatching.wgt.MaxCTraj=100 42 | # The balancing factor used in action weight 43 | algorithm.mapmatching.wgt.Omega=1 44 | # The heading weight factor 45 | algorithm.mapmatching.sco.DijkstraThreshold=1000 46 | algorithm.mapmatching.sco.HeadingWC=12 47 | algorithm.mapmatching.sco.BearingWC=21 48 | algorithm.mapmatching.sco.PDWC=32 49 | algorithm.mapmatching.sco.ShortestPathWC=35 50 | # Dynamic window size latency cost weight in Eddy 51 | algorithm.mapmatching.hmm.Eddy.Gamma=0.01 52 | # Velocity model system error used in Kalman Filter (m/s), default=3.0m/s 53 | algorithm.mapmatching.mht.SigmaA=3 54 | # Velocity observation error used in Kalman Filter (km/h), default=30km/h 55 | algorithm.mapmatching.mht.SigmaV=30 56 | # Prediction threshold used to rule out low probability predictions 57 | algorithm.mapmatching.mht.PredictionThreshold=0.00001 58 | # Update threshold used to rule out hypothesis routes 59 | algorithm.mapmatching.mht.UpdateThreshold=0.00001 -------------------------------------------------------------------------------- /src/main/resources/preprocessing.properties: -------------------------------------------------------------------------------- 1 | # Available OS: Win,Linux 2 | OS=Win 3 | data.RootPath=F:/data/ 4 | #data.RootPath=/home/uqpchao/data 5 | # Available dataset: Beijing-S,Beijing-M,Beijing-L,Chicago,Berlin,Athens-S,Athens-L 6 | data.Dataset=Beijing-S 7 | data.BoundingBoxS=116.4,116.435,39.95,39.98 8 | data.BoundingBoxM=116.34,116.44,39.89,39.95 9 | data.BoundingBoxR=116.5,116.535,40.00,40.03 10 | data.BoundingBoxL=0 11 | # Trajectory preprocessing parameters 12 | data.TrajectoryMinimalLengthSec=180 13 | data.SampleMaximalIntervalSec=120 14 | data.NumberOfTrajectory=-1 15 | data.DownSample=1 16 | # The tolerance for Douglas-Peucker algorithm, measured in meter 17 | data.Tolerance=0 --------------------------------------------------------------------------------