id
stringlengths 36
36
| text
stringlengths 1
1.25M
|
---|---|
57cdc871-9ec3-464e-92be-68c4cbc5199d | public List<String> getFileNames() {
return fileNames;
} |
4d37eded-452b-482a-827f-798740e56c87 | public List<String> getMethods() {
return methods;
} |
761b1883-f720-44e4-9f46-1c84853f379b | public PseudolocalizationPipeline getPipeline() {
return pipeline;
} |
5c3f5e77-11f2-484d-bbe1-abc3bb20d6dc | public String getType() {
return fileType;
} |
7a57fd2a-47fc-4997-a6d8-732921c54fe3 | public String getVariant() {
return variant;
} |
e4af5a89-45e6-4306-82f6-2aada25e30f7 | public boolean isInteractive() {
return isInteractive;
} |
9fa73bbb-9110-49f5-80f6-38e940b0e346 | public boolean isOverwrite() {
return isOverwrite;
} |
a9d5a322-16fc-4f95-bfc1-49bc762e81f9 | public static void main(String[] args) throws IOException {
Pseudolocalizer pseudolocalizer = new Pseudolocalizer();
PseudolocalizerArguments arguments = new PseudolocalizerArguments(args);
pseudolocalizer.run(arguments);
} |
b5e33929-4224-4f85-b4f1-d8edd2f8f61b | void run(PseudolocalizerArguments arguments) throws IOException {
List<String> fileNames = arguments.getFileNames();
PseudolocalizationPipeline pipeline = arguments.getPipeline();
if (arguments.isInteractive()) {
runStdin(pipeline);
return;
}
if (fileNames.size() == 0) {
// if no files given, read from stdin / write to stdout
MessageCatalog msgCat = FormatRegistry.getMessageCatalog(arguments.getType());
writeMessages(msgCat, readAndProcessMessages(pipeline, msgCat, System.in), System.out);
return;
}
// get the suffix to use for output file names
String suffix = arguments.getVariant();
if (suffix == null) {
suffix = "_pseudo";
} else {
suffix = "_" + suffix;
}
for (String fileName : fileNames) {
try {
File file = new File(fileName);
if (!file.exists()) {
System.err.println("File " + fileName + " not found");
continue;
}
// get the extension of the input file and construct the output file name
int lastDot = fileName.lastIndexOf('.');
String extension;
String outFileName;
if (lastDot >= 0) {
extension = fileName.substring(lastDot + 1);
outFileName = fileName.substring(0, lastDot) + suffix + "." + extension;
} else {
extension = "";
outFileName = fileName + suffix;
}
if (arguments.isOverwrite()) {
outFileName = fileName;
}
System.out.println("Processing " + fileName + " into " + outFileName);
// get the message catalog object for the specified (or inferred) file type
String fileType = arguments.getType();
if (fileType == null) {
fileType = extension;
}
MessageCatalog msgCat = FormatRegistry.getMessageCatalog(fileType);
// read and process messages
InputStream inputStream = new FileInputStream(file);
List<Message> processedMessages = readAndProcessMessages(pipeline, msgCat, inputStream);
// replace source with psudolocalized file
if (arguments.isOverwrite()) {
// System.out.println("Back up source file " + file.getName() + " to " + file.getName() + "_backup");
// file.renameTo(new File(file.getName() + "_backup"));
}
OutputStream outputStream = new FileOutputStream(new File(outFileName));
writeMessages(msgCat, processedMessages, outputStream);
} catch (Exception e) {
System.out.println("Failed to processing " + fileName + " " + e.getMessage());
}
}
} |
ddda40cb-0116-43d4-8574-356c8e2d317e | private List<Message> readAndProcessMessages(PseudolocalizationPipeline pipeline,
MessageCatalog msgCat, InputStream inputStream)
throws IOException {
List<Message> processedMessages = new ArrayList<Message>();
ReadableMessageCatalog input = msgCat.readFrom(inputStream);
try {
for (Message msg : input.readMessages()) {
pipeline.localize(msg);
processedMessages.add(msg);
}
} finally {
input.close();
}
return processedMessages;
} |
7ee011c2-18e4-43d0-9016-a584c3404b68 | private void runStdin(PseudolocalizationPipeline pipeline) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.println("Enter text to pseudolocalize:");
while ((line = reader.readLine()) != null) {
if (line.length() == 0) {
break;
}
System.out.println("=> " + pipeline.localize(line));
}
} |
55df50a3-23c6-4a82-b5b5-2b11c02b12df | private void writeMessages(MessageCatalog msgCat, List<Message> messages,
OutputStream outputStream) throws IOException {
// write messages
WritableMessageCatalog output = msgCat.writeTo(outputStream);
try {
for (Message msg : messages) {
output.writeMessage(msg);
}
} finally {
output.close();
}
} |
7a738d4b-2c25-45ad-824f-15cd34a5c5ba | public FileCollector(String path, String fileRegex, String outputFile) {
this.rootPath = path;
this.outputFile = outputFile;
this.filePattern = Pattern.compile(fileRegex);
} |
095dfbfa-5666-40a5-835e-1f9e20eaae65 | public void collect() {
List<String> fileNames = new ArrayList<String>();
collect(rootPath, fileNames);
try {
writeToOutputFile(fileNames);
} catch (IOException ex) {
throw new CollectFileException("Fail to collect files under path: " + rootPath, ex);
}
} |
c4d772b9-f7b4-4098-89eb-f0f42602b754 | private void collect(String rootPath, List<String> fileNames) {
File dir = new File(rootPath);
File[] files = dir.listFiles();
if (files == null) {
return;
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
if (!file.isHidden()) {
collect(file.getAbsolutePath(), fileNames);
}
} else {
if (filePattern.matcher(file.getAbsolutePath()).find()) {
String strFileName = file.getAbsolutePath();
fileNames.add(strFileName);
}
}
}
} |
cdba14bb-6d65-4627-a24e-46362b2e5cf1 | public void writeToOutputFile(List<String> fileNames) throws IOException {
if (fileNames != null) {
BufferedWriter out = null;
try {
File output = new File(outputFile);
if (!output.exists()) {
output.createNewFile();
}
out = new BufferedWriter(new FileWriter(outputFile));
for (String path : fileNames) {
out.write(path);
out.newLine();
}
out.flush();
} finally {
if (out != null) {
out.close();
}
}
}
} |
6c9d94ca-efdc-498f-8d93-6ae5e6e8e9e6 | public CollectFileException() {
super();
} |
e6f97b9a-99fd-46a5-a822-900420545dd7 | public CollectFileException(String message) {
super(message);
} |
e0462376-a6fc-4463-bfc2-e214a70f9692 | public CollectFileException(String message, Throwable cause) {
super(message, cause);
} |
7c76b7dc-6c49-425f-8bd3-e1160deb0584 | public CollectFileException(Throwable cause) {
super(cause);
} |
8bb1ac69-c1d0-4742-8810-7a54b458ba09 | public AppTest( String testName )
{
super( testName );
} |
5d426ca5-3d06-4f90-9bc2-aea01416cb03 | public static Test suite()
{
return new TestSuite( AppTest.class );
} |
db3ea399-0dd3-4407-958a-f073bd24bd12 | public void testApp()
{
assertTrue( true );
} |
9858d766-3bec-4a41-b260-ae92372d84c1 | public void testCollectFile() {
// FileCollector collector = new FileCollector("D:\\Projects\\amarosa_6-3_TELUS\\JEDI\\jedi-assembly\\target\\jedi-6.3.0-TELUS-XMN-SNAPSHOT\\localStorage", ".*[\\\\/]en.js$", "WebBatch.txt");
FileCollector collector = new FileCollector("D:\\Projects\\amarosa_6-3_TELUS\\JEDI\\localStorage", ".*[\\\\/]en.js$", "WebBatch.txt");
collector.collect();
} |
46fb97a9-62a0-4ba2-9e52-2bc1bc4a5bc6 | @Test
public void testReplaceStrConnector() {
String str = "{HINT_TEXT:\"If you make international calls, the included plan mon the applicable international rate.\","+
"AUTO_PURCHASE_DESCRIPTION:\"Auto Purchase feature ensures you will never run out of calling credits. The \" +"+
" \"selected package will be automatically purchased when you are running low on calling redits, which prevents any potential interruption of service. Purchased funds will \" +\"" +
"\"rnths.\"," +
"AUTO_PURCHASE_FIELD_LABEL:\"Auto-Purchase\"," +
"CALLING_CREDITS_PACKAGE_FIELD_LABEL:\"Calling Credits Package\"," +
"WINDOW_TITLE:\"Auto-Purchase\"," +
"PACKAGES_INFO:\"(equivalent to {0} Plan minutes at {1})\"," +
"REDIO_GROUP_HINT_TEXT:\"<b>Plan and DigitalLine </b><br/>Plan minutes are approximate values based on your available Calling Credits, and are calculated based on the domestic rate of {0} for your account. \" +" +
" \"If you make international calls, the included plan mon the applicable international rate.\"" +
"}\"";
System.out.println(str);
str = str.replaceAll("(['\"])\\s*\\+\\s*\\1", "");
System.out.println(str);
} |
49cb2d86-9418-443c-b278-81af3a7dc564 | public Record(String line) {
String[] ls = line.split(",");
userID = Integer.parseInt(ls[0]);
latitude = Double.parseDouble(ls[1]);
longitude = Double.parseDouble(ls[2]);
time = ls[3];
try {
timestamp = sdf.parse(time).getTime() / 1000;
} catch (ParseException e) {
System.out.println(ls[3] + "\n" + e.getMessage());
}
locID = Integer.parseInt(ls[4]);
} |
4d812f9f-bf1e-4c18-8659-7948eb598de4 | public double distanceTo(Record o) {
double d2r = (Math.PI/180);
double distance = 0;
double longiE = o.longitude;
double latiE = o.latitude;
try {
double dlong = (longiE - longitude) * d2r;
double dlati = (latiE - latitude) * d2r;
double a = Math.pow(Math.sin(dlati/2.0), 2)
+ Math.cos(latitude * d2r)
* Math.cos(latiE * d2r)
* Math.pow(Math.sin(dlong / 2.0), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
distance = 6367 * c;
} catch (Exception e) {
e.printStackTrace();
}
return distance;
} |
464ce646-d9b8-41bc-b705-e37cd3712a7a | @Override
public int compareTo(Record o) {
return (int) (this.timestamp - o.timestamp);
} |
d044f732-78ca-455e-8749-1d7dec0ad05b | @Override
public String toString() {
return String.format("%d,%.6f,%.6f,%s,%d", userID, latitude, longitude, time, locID);
} |
c82539a6-6e74-4087-88b8-ebb50a0a58f6 | public String GPS() {
return String.format("%.3f%.3f", latitude, longitude);
} |
e0f32a88-3490-4878-8e6d-5b5936fbde10 | public static void main(String[] args) {
// test purpose
String test = "0,37.806167,-122.450135,2010-04-14 04:32:30,0";
Record r = new Record(test);
System.out.println(r);
} |
2b69ccd3-77bc-4645-94a0-5004b4b0c4a0 | User( Record r ) {
userID = r.userID;
records = new LinkedList<Record>();
friends = new HashSet<Integer>();
locs = new HashSet<String>();
records.add(r);
if ( ! allUserSet.containsKey(r.userID))
allUserSet.put(r.userID, this);
} |
8b79476e-12ac-44de-bf68-775e704190b6 | User (int uid) {
if (! allUserSet.containsKey(uid)) {
userID = uid;
records = new LinkedList<Record>();
friends = new HashSet<Integer>();
locs = new HashSet<String>();
try {
BufferedReader fin = new BufferedReader(new FileReader(String.format("%s/%d", userDir, uid)));
// add friends;
String l = fin.readLine();
String[] fids = l.split("\t");
if (fids.length == 1 && Integer.parseInt(fids[0]) == -1)
friends.clear();
else {
for (String fid : fids) {
friends.add(Integer.parseInt(fid));
}
}
// add records;
while ((l = fin.readLine()) != null) {
records.add(new Record(l));
}
fin.close();
} catch (Exception e) {
System.out.println("Exception in User constructor");
e.printStackTrace();
}
allUserSet.put(uid, this);
} else {
this.userID = uid;
this.records = allUserSet.get(uid).records;
this.friends = allUserSet.get(uid).friends;
}
//totalweight = totalWeight();
} |
802cd191-7767-4223-ae0d-b71e39b3e5d0 | public static void addAllUser() {
File dir = new File(userDir);
String[] fileNames = dir.list();
for (String fn : fileNames) {
new User(Integer.parseInt(fn));
}
System.out.println(String.format("Create %d users in total.", allUserSet.size()));
} |
e0b2a51f-50e8-4cdb-8667-131a7635ec48 | public static void addTopkUser( int k ) {
try {
BufferedReader fin = new BufferedReader( new FileReader("res/userCheckins-rank.txt"));
String l = null;
int c = 0;
while (( l = fin.readLine()) != null ) {
String[] ls = l.split("\t");
int uid = Integer.parseInt(ls[0]);
new User(uid);
c ++;
if (c==k)
break;
}
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(String.format("%d users have been initailized.", k));
} |
7706a2c2-7d24-4b6e-882b-f68c9ba60f5f | @Override
public String toString() {
return String.format("User %d: #friend -- %d; #records -- %d", userID, friends.size(), records.size());
} |
fa924532-3f08-445b-94fb-ece26ff101fe | HashSet<String> getLocations() {
if (locs.size() == 0) {
for (Record r : records) {
if ( ! locs.contains(r.GPS()) )
locs.add( r.GPS() );
}
}
return locs;
} |
ee3e10ca-5894-443f-81ab-49771443ff37 | public double locationWeight( Record rt ) {
double weight = 0;
double dist = 0;
for (Record r : records) {
dist = rt.distanceTo(r);
dist = Math.exp(- User.para_c * dist);
weight += dist;
}
// System.out.println(String.format("User %d Cnt: %d, records size %d, weight %g", userID, cnt, records.size(), weight));
weight /= records.size();
return weight;
} |
b206163f-4485-4f79-a2cc-79e321234e52 | public static void main(String[] args) {
// for (int i = 0; i <= 335; i++) {
// User u0 = new User(i);
// System.out.println(u0.getLocations().size());
// }
// User.addAllUser();
getUserRecordsNRanking();
} |
2cd5ac3a-d7b3-4c78-9124-8018d4b0544d | @Override
public int compareTo(User oth) {
return this.records.size() - oth.records.size();
} |
13a17bd6-4f13-4508-9812-91e7130a493c | private static void getUserRecordsNRanking() {
User.addAllUser();
List<User> users = new LinkedList<User>(User.allUserSet.values());
Collections.sort(users);
try {
BufferedWriter fout = new BufferedWriter( new FileWriter( "res/userCheckins-rank.txt" ));
for (int i = users.size() - 1; i >= 0; i--) {
User u = users.get(i);
u.getLocations();
fout.write(String.format("%d\t%d\t%d%n", u.userID, u.records.size(), u.locs.size()));
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
78cd2f32-c10f-489f-bd9e-56c98cbe6dc6 | MiningFramework() {
long t_start = System.currentTimeMillis();
System.out.println("Start create MiningFramework instance, and construct User instances.");
User.addAllUser();
friendPair = new ArrayList<int[]>();
distantFriend = new ArrayList<int[]>();
nonFriendMeeting = new ArrayList<int[]>();
friendMap = new HashMap<Integer, HashSet<Integer>>();
meetFreq = new HashMap<Integer, HashMap<Integer, Integer>>();
avgDistance = new HashMap<Integer, HashMap<Integer, Double>>();
// get friends networks
for (User u : User.allUserSet.values()) {
friendMap.put(u.userID, u.friends);
for (int i : u.friends) {
// eliminate duplications in friendPair
if (u.userID < i)
friendPair.add(new int[]{u.userID, i});
}
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Initailize case finder in %d seconds", (t_end-t_start)/1000));
} |
69c2dd3a-b69a-4950-b61b-e066e7d9279c | public void locationDistancePowerLaw( ) {
for (int id : User.allUserSet.keySet()) {
MiningFramework.locationDistancePowerLaw(id);
}
} |
3ac70ae9-0458-4884-bc4e-d65961ba9cac | public static void locationDistancePowerLaw( int uid ) {
try {
User u = new User(uid);
BufferedWriter fout = new BufferedWriter( new FileWriter (String.format("res/distance-%d.txt", u.userID)));
for (int i = 0; i < u.records.size(); i++) {
for (int j = i + 1; j < u.records.size(); j++ ) {
double d = u.records.get(i).distanceTo(u.records.get(j));
fout.write(Double.toString(d) + "\n");
}
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
b4576a38-3336-48d9-a232-099065a0284c | private boolean inFriendPair(int uaid, int ubid) {
if (friendMap.containsKey(uaid) && friendMap.get(uaid).contains(ubid))
return true;
else if (friendMap.containsKey(ubid) && friendMap.get(ubid).contains(uaid))
return true;
else
return false;
} |
8b662f2b-ba5c-4077-9478-f2a4f7705576 | public void allPairMeetingFreq(boolean IDorDist) {
long t_start = System.currentTimeMillis();
System.out.println("allPairMeetingFreq starts");
int K = User.allUserSet.size();
System.out.println(String.format("uary.length: %d", K));
for (int i = 0; i < K; i++) {
User ua = User.allUserSet.get(i);
HashSet<String> ua_locs = ua.getLocations();
for (int j = i+1; j < K; j++) {
User ub = User.allUserSet.get(j);
HashSet<String> ub_locs = ub.getLocations();
HashSet<String> diff = new HashSet<String>(ub_locs);
diff.retainAll(ua_locs);
if (diff.size() > 0) {
// iterate through their records to find co-location event.
int aind = 0;
int bind = 0;
while (aind < ua.records.size() && bind < ub.records.size()) {
Record ra = ua.records.get(aind);
Record rb = ub.records.get(bind);
// 1. count the meeting frequency
if (ra.timestamp - rb.timestamp > 4 * 3600) {
bind++;
continue;
} else if (rb.timestamp - ra.timestamp > 4 * 3600) {
aind++;
continue;
} else {
// judge the meeting event by different criteria
boolean isMeeting = false;
if (IDorDist) {
isMeeting = (ra.locID == rb.locID);
} else {
isMeeting = (ra.distanceTo(rb) < MiningFramework.distance_threshold);
}
if (isMeeting ) {
int first = (i <= j) ? i : j;
int second = (i > j) ? i : j;
if (meetFreq.containsKey(first)) {
if (meetFreq.get(first).containsKey(second)) {
int k = meetFreq.get(first).get(second);
meetFreq.get(first).put(second, k+1);
} else {
meetFreq.get(first).put(second, 1);
}
} else {
meetFreq.put(first, new HashMap<Integer, Integer>());
meetFreq.get(first).put(second, 1);
}
}
aind ++;
bind ++;
}
}
}
}
// monitor the process
if (i % (User.allUserSet.size() / 10) == 0)
System.out.println(String.format("Process - allPairMeetingFreq finished %d0%%.", i/(User.allUserSet.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("allPairMeetingFreq finishes in %d seconds, in total %d pairs meet.", (t_end - t_start)/1000, meetFreq.size()));
} |
1a9247ba-b0cc-4be5-b70a-2641a4c6355a | public void writeMeetingFreq() {
try {
BufferedWriter fout = new BufferedWriter(new FileWriter("res/freq.txt"));
for (int i : meetFreq.keySet()) {
for (int j : meetFreq.get(i).keySet()) {
// write out id_1, id_2, meeting frequency, distance
fout.write(String.format("%d\t%d\t%d\t", i, j, meetFreq.get(i).get(j) ));
if (inFriendPair(i, j))
fout.write("1\n");
else
fout.write("0\n");
}
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
9c0bf81f-7515-4c01-9e50-4d1dfa4b87c9 | public ArrayList<int[]> remoteFriends() {
// iterate over all user pair
long t_start = System.currentTimeMillis();
int c = 0;
for (int a : friendMap.keySet()) {
for (int b : friendMap.get(a)) {
System.out.println(String.format("Calculating user with id %d and %d", a, b));
int cnt = 0;
if (a <= b) {
for (Record ra : User.allUserSet.get(a).records) {
for (Record rb : User.allUserSet.get(b).records) {
// 1. calculate the average distance
double d = ra.distanceTo(rb);
if (avgDistance.containsKey(a)) {
if (avgDistance.get(a).containsKey(b)) {
double ext = avgDistance.get(a).get(b);
avgDistance.get(a).put(b, ext + d);
} else {
avgDistance.get(a).put(b, d);
}
} else {
avgDistance.put(a, new HashMap<Integer, Double>() );
avgDistance.get(a).put(b, d);
}
cnt ++;
}
}
double total = avgDistance.get(a).get(b);
avgDistance.get(a).put(b, total / cnt);
if (total > 100) {
int[] tuple = { a, b, (int) total };
distantFriend.add(tuple);
}
}
}
// monitor process
c++;
if (c % (friendMap.size()/10) == 0)
System.out.println(String.format("Process -- remoteFriends %d0%%", c / (friendMap.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Found remote friends in %d seconds", (t_end-t_start)/1000));
return distantFriend;
} |
5b357a75-3409-4d8b-b62b-2e130331eea2 | public void writeRemoteFriend() {
try {
BufferedWriter fout = new BufferedWriter(new FileWriter("res/remoteFriend.txt"));
for (int i = 0; i < distantFriend.size(); i++) {
// write out u_1, u_2, distance, meeting frequency
int uaid = distantFriend.get(i)[0];
int ubid = distantFriend.get(i)[1];
fout.write(String.format("%d\t%d\t%d\t%d\n", distantFriend.get(i)[0], distantFriend.get(i)[1], distantFriend.get(i)[2], meetFreq.get(uaid).get(ubid)));
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
3addbc86-544c-408f-b3cd-ae9af222ca4b | public ArrayList<int[]> nonFriendsMeetingFreq() {
int K = User.allUserSet.size();
for (int i = 0; i < K; i++ )
for (int j = i+1; j < K; j++) {
if (nonFriend(i, j) && meetFreq.get(i).get(j) > 0) {
int[] tuple = {i, j, meetFreq.get(i).get(j)};
nonFriendMeeting.add(tuple);
}
}
return nonFriendMeeting;
} |
d340436c-03fd-41d4-ac32-90f138e28e52 | private boolean nonFriend(int aid, int bid) {
if (friendMap.containsKey(aid)) {
if (friendMap.get(aid).contains(bid)) {
return false;
} else {
return true;
}
} else {
return true;
}
} |
af8572fb-a935-460b-988f-682355b8d860 | public void writeNonFriendsMeeting(){
try {
BufferedWriter fout2 = new BufferedWriter(new FileWriter("nonFriendsMeeting.txt"));
for (int i = 0; i < nonFriendMeeting.size(); i++) {
// write out u_1, u_2, meeting frequency
fout2.write(String.format("%d\t%d\t%d\n", nonFriendMeeting.get(i)[0], nonFriendMeeting.get(i)[1],nonFriendMeeting.get(i)[2]));
}
fout2.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
df80a9c8-fd79-4235-9f3a-0663d32e32a6 | public static void pairAnalysis( int uaid, int ubid ) {
User ua = new User(uaid);
User ub = new User(ubid);
// 1. get the co-locations and the corresponding meeting freq
HashMap<String, Integer> mf = meetingFreq(ua, ub);
// 2. get the total meeting frequency
int sum = 0;
for (int i : mf.values()) {
sum += i;
}
System.out.println(String.format("Total Meet %d times between user %d and %d.", sum, uaid, ubid));
// 3. get the location distribution of two users
TreeMap<String, Integer> loca = locationDistribution(ua);
TreeMap<String, Integer> locb = locationDistribution(ub);
// 4. get the ranking
LinkedList<Integer> freqa = new LinkedList<Integer>(loca.values());
Collections.sort(freqa);
Collections.reverse(freqa);
LinkedList<Integer> freqb = new LinkedList<Integer>(locb.values());
Collections.sort(freqb);
Collections.reverse(freqb);
System.out.println("loc \t meeting frequency \t rank of A \t frequency of A \t rank of B \t frequency of B");
for (String l : mf.keySet()) {
int fa = loca.get(l);
int ranka = freqa.indexOf(fa) + 1;
int fb = locb.get(l);
int rankb = freqb.indexOf(fb) + 1;
System.out.println(String.format("%s \t\t %d \t\t %d \t\t %d \t\t %d \t\t %d", l, mf.get(l), ranka, fa, rankb, fb));
}
} |
80033d3e-af52-4c12-ab04-75ee24468e44 | private static HashMap<String, Integer> meetingFreq( User ua, User ub ) {
HashMap<String, Integer> colofreq = new HashMap<String, Integer>();
int aind = 0;
int bind = 0;
while (aind < ua.records.size() && bind < ub.records.size()) {
Record ra = ua.records.get(aind);
Record rb = ub.records.get(bind);
if (ra.timestamp - rb.timestamp > 3600 * 4) {
bind ++;
continue;
} else if (rb.timestamp - ra.timestamp > 3600 * 4 ) {
aind ++;
continue;
} else {
if (ra.distanceTo(rb) < distance_threshold) {
if (colofreq.containsKey(ra.GPS())) {
int tmp = colofreq.get(ra.GPS());
colofreq.put(ra.GPS(), tmp + 1);
} else {
colofreq.put(ra.GPS(), 1);
}
}
aind ++;
bind ++;
}
}
return colofreq;
} |
040b9b0f-05af-45f1-8750-1cc51c2ce709 | @SuppressWarnings("unused")
private static int totalMeetingFreq( int uaid, int ubid ) {
User ua = new User(uaid);
User ub = new User(ubid);
HashMap<String, Integer> mf = meetingFreq(ua, ub);
int sum = 0;
for (int f : mf.values()) {
sum += f;
}
return sum;
} |
ac935ac8-5c29-4c5f-b1f8-f676219309ea | @SuppressWarnings("unused")
private static double[] locIDBasedSumLogMeasure(int uaid, int ubid) {
User ua = new User(uaid);
User ub = new User(ubid);
int aind = 0;
int bind = 0;
long lastMeet = 0;
double freq = 0;
double measure = 0;
while (aind < ua.records.size() && bind < ub.records.size()) {
Record ra = ua.records.get(aind);
Record rb = ub.records.get(bind);
if (ra.timestamp - rb.timestamp > 3600 * 4) {
bind ++;
continue;
} else if (rb.timestamp - ra.timestamp > 3600 * 4 ) {
aind ++;
continue;
} else {
if (ra.locID == rb.locID && ra.timestamp - lastMeet >= 3600) {
freq ++;
measure -= Math.log10(ua.locationWeight(ra)) + Math.log10(ub.locationWeight(rb));
lastMeet = ra.timestamp;
}
aind ++;
bind ++;
}
}
double[] rt = {measure, freq};
return rt;
} |
3cae25aa-b485-454b-be5c-0d128fdff305 | @SuppressWarnings("unused")
private static double[] locIDBasedARCTANweightEvent(int uaid, int ubid) {
User ua = new User(uaid);
User ub = new User(ubid);
LinkedList<Record> meetingEvent = new LinkedList<Record>();
LinkedList<Double> meetingRawWeight = new LinkedList<Double>();
int aind = 0;
int bind = 0;
long lastMeet = 0;
double freq = 0;
double measure = 0;
while (aind < ua.records.size() && bind < ub.records.size()) {
Record ra = ua.records.get(aind);
Record rb = ub.records.get(bind);
if (ra.timestamp - rb.timestamp > 3600 * 4) {
bind ++;
continue;
} else if (rb.timestamp - ra.timestamp > 3600 * 4 ) {
aind ++;
continue;
} else {
if (ra.locID == rb.locID && ra.timestamp - lastMeet >= 3600) {
freq ++;
measure = -(Math.log10(ua.locationWeight(ra)) + Math.log10(ub.locationWeight(rb)));
meetingEvent.add(ra);
meetingRawWeight.add(measure);
lastMeet = ra.timestamp;
}
aind ++;
bind ++;
}
}
double[] rt = new double[2];
double w = 0;
measure = 0;
if (meetingEvent.size() == 1) {
for (double m : meetingRawWeight)
rt[0] += m;
rt[1] = freq;
} else if (meetingEvent.size() > 1) {
for (int i = 0; i < meetingEvent.size(); i++) {
for (int j = i+1; j < meetingEvent.size(); j++) {
Record r1 = meetingEvent.get(i);
Record r2 = meetingEvent.get(j);
w = 2 / Math.PI * Math.atan(Math.abs(r2.timestamp - r1.timestamp) / 3600.0 / 24);
measure += (meetingRawWeight.get(i) + meetingRawWeight.get(j)) * w;
}
}
measure = measure * 2 / (meetingEvent.size() - 1);
rt[0] = measure;
rt[1] = freq;
}
return rt;
} |
786a62c7-0ce7-4392-b7f8-ddb5bdb94aaf | @SuppressWarnings("unused")
private static double[] PAIRWISEweightEvent(int uaid, int ubid, BufferedWriter fout, int friend_flag, boolean IDorDist,
boolean entroIDorDist, String RhoMethod, String weightMethod, String combMethod, int dependence, int sampleRate
) throws IOException {
User ua = new User(uaid);
User ub = new User(ubid);
LinkedList<Record> meetingEvent = new LinkedList<Record>();
LinkedList<Double> mw_pbg = new LinkedList<Double>(); // meeting weight _ personal background
LinkedList<Double> mw_le = new LinkedList<Double>(); // meeting weight _ location entropy
LinkedList<Double> mw_pbg_le = new LinkedList<Double>(); // meeting weight _ personal background _ location entropy
LinkedList<Double> probs = new LinkedList<Double>();
LinkedList<Double> entros = new LinkedList<Double>();
HashMap<Long, Double> locationEntropy = null;
HashMap<String, Double> GPSEntropy = null;
if (entroIDorDist) {
locationEntropy = Tracker.readLocationEntropyIDbased(sampleRate);
} else {
GPSEntropy = Tracker.readLocationEntropyGPSbased(sampleRate);
}
int aind = 0;
int bind = 0;
long lastMeet = 0;
double freq = 0;
double personBg = 0;
double locent = 0;
double comb = 0;
while (aind < ua.records.size() && bind < ub.records.size()) {
Record ra = ua.records.get(aind);
Record rb = ub.records.get(bind);
if (ra.timestamp - rb.timestamp > 3600 * 4) {
bind ++;
continue;
} else if (rb.timestamp - ra.timestamp > 3600 * 4 ) {
aind ++;
continue;
} else {
// judge the meeting event by different criteria
boolean isMeeting = false;
if (IDorDist) {
isMeeting = (ra.locID == rb.locID);
} else {
isMeeting = (ra.distanceTo(rb) < MiningFramework.distance_threshold);
}
if ( isMeeting ) { //&& ra.timestamp - lastMeet >= 3600) {
freq ++;
double prob = 0;
/** different methods to calculate rho **/
if (RhoMethod == "min") {
prob = Math.min( ua.locationWeight(ra) , ub.locationWeight(rb));
} else if (RhoMethod == "prod") {
// measure 1: - log (rho_1 * rho_2)
prob = ua.locationWeight(ra) * ub.locationWeight(rb);
}
probs.add(prob);
personBg = -(Math.log10(prob));
mw_pbg.add(personBg);
// measure 2: (1 - rho_1) * (1 - rho_2)
// measure = ( 1 - ua.locationWeight(ra) ) * ( 1- ub.locationWeight(rb));
/** different methods to calculate location entropy **/
double entro = 0;
if ( entroIDorDist ) {
if (locationEntropy.containsKey(ra.locID))
entro = locationEntropy.get(ra.locID); // + locationEntropy.get(rb.locID));
else
entro = 0;
} else {
if (GPSEntropy.containsKey(ra.GPS()))
entro = GPSEntropy.get(ra.GPS());
else
entro = 0;
}
entros.add(entro);
locent = Math.exp( - entropy_exp_para * entro );
mw_le.add(locent);
/** different method to calculate the product of two **/
comb = personBg * locent;
mw_pbg_le.add(comb);
meetingEvent.add(ra);
lastMeet = ra.timestamp;
}
aind ++;
bind ++;
}
}
double[] rt = new double[6];
personBg = 0;
locent = 0;
double pbg_lcen = 0;
double pbg_lcen_td = 0;
double td = 0; // temporal dependency
double min_prob = Double.MAX_VALUE;
double measure_sum = 0;
double avg_entro = 0;
double avg_le = 0;
double avg_pbg = 0;
for (double m : probs)
if ( min_prob > m )
min_prob = m;
// calculate the personal background
if (weightMethod == "min") {
personBg = - Math.log10(min_prob) * meetingEvent.size();
System.out.println(String.format("Sum of %d events by max %g is %g.", meetingEvent.size(), min_prob, personBg));
} else if (weightMethod == "sum") {
for (double m : mw_pbg)
personBg += m;
}
// calculate the location entropy
for (double m : mw_le) {
locent += m;
}
if (dependence == 0)
{
/** average measure **/
for (double m : entros)
avg_entro += m;
avg_entro /= entros.size();
for (double m : mw_pbg) {
measure_sum += m;
}
avg_pbg = measure_sum / mw_pbg.size();
if (combMethod == "min") {
pbg_lcen = - Math.log10(min_prob) * locent;
} else if (combMethod == "prod") {
for (double m : mw_pbg_le) {
pbg_lcen += m;
}
} else if (combMethod == "wsum") {
pbg_lcen = alpha * personBg + beta * locent;
}
// fout.write(String.format("%g\t%g\t%d\n", measure, locent, friend_flag));
avg_le = locent / mw_le.size();
fout.write(String.format("%g\t%d\t%d\n", avg_le, (int)freq, friend_flag));
} else {
double avg_w = 0;
if (meetingEvent.size() == 1) {
pbg_lcen = mw_pbg_le.get(0);
pbg_lcen_td = pbg_lcen;
td = 1;
} else if (meetingEvent.size() > 1) {
for (int i = 0; i < meetingEvent.size(); i++) {
double w = 0;
for (int j = 0; j < meetingEvent.size(); j++) {
if (i != j) {
Record r1 = meetingEvent.get(i);
Record r2 = meetingEvent.get(j);
if (dependence == 1) {
w += 1 - Math.exp(- event_time_exp_para_c * Math.abs(r2.timestamp - r1.timestamp) / 3600.0 / 24);
} else if (dependence == 2) {
double dist = r2.distanceTo(r1);
w += 1 - Math.exp(- event_space_exp_para_c * dist);
// fout.write(String.format("%g\t%g\n", dist, w));
}
}
}
w /= (meetingEvent.size() - 1);
if (combMethod == "min") {
double tmp = - Math.log10(min_prob) * mw_le.get(i);
pbg_lcen += tmp;
td += w;
pbg_lcen_td += tmp * w;
}
else if (combMethod == "prod") {
pbg_lcen += mw_pbg_le.get(i);
td += w;
pbg_lcen_td += mw_pbg_le.get(i) * w;
}
else if (combMethod == "wsum") {
double tmp = alpha * mw_pbg.get(i) + beta * mw_le.get(i);
pbg_lcen += tmp;
td += w;
pbg_lcen_td += tmp * w;
}
}
avg_w = td / meetingEvent.size();
}
fout.write(String.format("ID: %d %d; %g\t%d\t%d\n", uaid, ubid, avg_w, (int)freq, friend_flag));
/** write out the distance / time between consecutive meeting
if (meetingEvent.size() == 5) {
fout.write(String.format("%d\t%d\t", uaid, ubid));
for (int l = 0; l < 4; l++) {
fout.write(String.format("%d\t", meetingEvent.get(l+1).timestamp - meetingEvent.get(l).timestamp));
}
fout.write(String.format("%d\n", friend_flag));
}
*/
}
rt[0] = personBg;
rt[1] = freq;
rt[2] = pbg_lcen;
rt[3] = locent;
rt[4] = pbg_lcen_td;
rt[5] = td;
return rt;
} |
849cf3f8-4c91-4500-8903-aa7a6a89365a | @SuppressWarnings("unused")
private static double[] locIDBasedOneMinusExpCONSECUTIVEweightEvent(int uaid, int ubid) {
User ua = new User(uaid);
User ub = new User(ubid);
LinkedList<Record> meetingEvent = new LinkedList<Record>();
LinkedList<Double> meetingRawWeight = new LinkedList<Double>();
int aind = 0;
int bind = 0;
long lastMeet = 0;
double freq = 0;
double measure = 0;
// weight each meeting event by user personal mobility background
while (aind < ua.records.size() && bind < ub.records.size()) {
Record ra = ua.records.get(aind);
Record rb = ub.records.get(bind);
if (ra.timestamp - rb.timestamp > 3600 * 4) {
bind ++;
continue;
} else if (rb.timestamp - ra.timestamp > 3600 * 4 ) {
aind ++;
continue;
} else {
if (ra.locID == rb.locID && ra.timestamp - lastMeet >= 3600) {
freq ++;
measure = -(Math.log10(ua.locationWeight(ra)) + Math.log10(ub.locationWeight(rb)));
meetingEvent.add(ra);
meetingRawWeight.add(measure);
lastMeet = ra.timestamp;
}
aind ++;
bind ++;
}
}
// combine each meeting event into one measure by using the temporal dependence in the meeting events
double[] rt = new double[2];
double w = 0;
measure = 0;
int cnt = 0;
if (meetingEvent.size() == 1) {
for (double m : meetingRawWeight)
rt[0] += m;
rt[1] = freq;
} else if (meetingEvent.size() > 1) {
for (int i = 0; i < meetingEvent.size(); i++) {
long t1 = 0, t2 = 0;
if (i == 0)
t1 = Long.MAX_VALUE;
else
t1 = meetingEvent.get(i).timestamp - meetingEvent.get(i-1).timestamp;
if (i == meetingEvent.size()-1)
t2 = Long.MAX_VALUE;
else
t2 = meetingEvent.get(i+1).timestamp - meetingEvent.get(i).timestamp;
long t = Math.min(t1, t2);
w = 1 - Math.exp(- event_time_exp_para_c * t / 3600.0 / 24);
// w = 2 / Math.PI * Math.atan(t / 3600.0 / 24);
System.out.println(Double.toString(w) + "\t" + Double.toString(t/3600.0 / 24));
measure += meetingRawWeight.get(i) * w;
cnt ++;
}
if ( cnt != meetingRawWeight.size())
System.out.println("Error in calculate events total weight, missing event");
rt[0] = measure;
rt[1] = freq;
}
return rt;
} |
7c825797-03e3-4435-86d0-75c5b694d47a | public static double[] distanceBasedSumLogMeasure(int uaid, int ubid, boolean printFlag) {
User ua = new User(uaid);
User ub = new User(ubid);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// get the co-locating event
ArrayList<double[]> coloEnt = meetingWeight(ua, ub, MiningFramework.distance_threshold);
// aggregate the measure
// location entropy
HashMap<String, Double> locationEntropy = Tracker.readLocationEntropyGPSbased(101);
double M = Double.MAX_VALUE;
double entro = 0;
for (double[] a : coloEnt) {
if ( M > a[0] * a[1])
M = a[0] * a[1];
// System.out.println(locationEntropy.get((long) a[4]));
a[4] = Math.exp( - entropy_exp_para * locationEntropy.get(String.format("%.3f%.3f", a[2], a[3])));
entro += a[4];
}
double minMeasure = - Math.log10(M) * coloEnt.size();
// calculate the temporal correlation
double minTC = 0;
for (int i = 0; i < coloEnt.size(); i++) {
double[] a = coloEnt.get(i);
double[] b = null;
double w = 0;
for (int j = 0; j < coloEnt.size(); j++) {
b = coloEnt.get(j);
if (i != j) {
double deltaT = Math.abs( b[7] - a[7] ) / 3600 / 24;
w += 1 - Math.exp(- event_time_exp_para_c * deltaT);
// System.out.println(String.format("%g\t%g\t%g", w, 1-Math.exp(-1.5* deltaT) , deltaT));
}
}
minTC += w * (- Math.log10(M)) / (coloEnt.size() - 1);
}
// print out the probability
if (printFlag) {
System.out.println(String.format("User %d and %d meet %d times.\nA.weight\tB.weight\tA.lati\tA.longi\tA.loc entropy\tB.lati\t\tB.longi",
ua.userID, ub.userID, coloEnt.size()));
for (double[] a : coloEnt) {
cal1.setTimeInMillis((long) a[7] * 1000);
cal2.setTimeInMillis((long) a[8] * 1000);
System.out.println(String.format("%g\t%g\t%g\t%g\t%g\t%g\t\t%g\t\t%8$tF %8$tT\t\t%9$tF %9$tT", a[0], a[1], a[2],
a[3], a[4], a[5], a[6], cal1, cal2));
}
System.out.println(String.format("User pair %d and %d has min personal measure %g, global measure %g, temporal dependence measure %g", uaid, ubid, minMeasure, entro, minTC));
}
double[] rt = {minMeasure, (double) coloEnt.size()};
return rt;
} |
63818a86-c3cc-483c-b983-7ba9d0798bb4 | public static double[] distanceBasedSumLogMeasure(int uaid, int ubid) {
return distanceBasedSumLogMeasure(uaid, ubid, false);
} |
3639f376-cf32-4818-9e36-b9d8a642685b | public static void writeOutDifferentMeasures(double para_c, int sampleRate) {
System.out.println("==========================================\nStart writeOutDifferentMeasures");
long t_start = System.currentTimeMillis();
User.addAllUser();
// User.addTopkUser(2800);
long t_mid = System.currentTimeMillis();
System.out.println(String.format("Add all users finished in %d seconds", (t_mid - t_start) / 1000));
try {
BufferedReader fin = new BufferedReader(new FileReader("res/freq.txt"));
BufferedWriter fout = new BufferedWriter(new FileWriter(String.format("res/distance-c%g-%ds.txt", event_time_exp_para_c, sampleRate)));
String l = null;
double[] locidm = null;
BufferedWriter fout2 = new BufferedWriter(new FileWriter("res/Pair-glob-measure.txt"));
while ( (l = fin.readLine()) != null ) {
String[] ls = l.split("\\s+");
int uaid = Integer.parseInt(ls[0]);
int ubid = Integer.parseInt(ls[1]);
int freq = Integer.parseInt(ls[2]);
int friflag = Integer.parseInt(ls[3]);
// if (User.allUserSet.containsKey(uaid) && User.allUserSet.containsKey(ubid) && freq > 0) {
if (freq > 0) {
// locidm contains: personal background, frequency, personal background + location entropy,
// location entropy, personal bg + location entro + temporal dependency, temporal dependency
locidm = PAIRWISEweightEvent(uaid, ubid, fout2, friflag, false, false, "prod", "min", "min", 1, sampleRate);
fout.write(String.format("%d\t%d\t%g\t%g\t%g\t%d\t%g\t%g\t%d%n", uaid, ubid, locidm[2], locidm[3], locidm[0], (int) locidm[1], locidm[4], locidm[5], friflag));
}
}
fin.close();
fout.close();
fout2.close();
} catch (Exception e) {
e.printStackTrace();
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Process writeOutDifferentMeasures finished in %d seconds", (t_end - t_start) / 1000));
} |
37988aa2-52ab-4259-8221-23a85aab2889 | private static ArrayList<double[]> meetingWeight( User ua, User ub, double dist_threshold ) {
ArrayList<double[]> coloEnt = new ArrayList<double[]>();
int aind = 0;
int bind = 0;
while (aind < ua.records.size() && bind < ub.records.size()) {
Record ra = ua.records.get(aind);
Record rb = ub.records.get(bind);
if (ra.timestamp - rb.timestamp > 3600 * 4) {
bind ++;
continue;
} else if (rb.timestamp - ra.timestamp > 3600 * 4) {
aind ++;
continue;
} else {
if (ra.distanceTo(rb) < dist_threshold) {
double wta = ua.locationWeight(ra);
double wtb = ub.locationWeight(rb);
double[] evnt = { wta, wtb, ra.latitude, ra.longitude, ra.locID, rb.latitude, rb.longitude, ra.timestamp, rb.timestamp };
coloEnt.add(evnt);
}
// if (ra.locID == rb.locID && ra.timestamp - time_lastMeet >= 3600 ) {
// double wta = ua.locationWeight(ra);
// double wtb = ub.locationWeight(rb);
// double[] evnt = {wta, wtb, ra.latitude, ra.longitude, rb.latitude, rb.longitude, ra.timestamp, rb.timestamp };
// coloEnt.add(evnt);
// time_lastMeet = ra.timestamp;
// }
aind ++;
bind ++;
}
}
return coloEnt;
} |
0babe470-0942-4d93-a43d-2434c80b2b7b | @SuppressWarnings("unused")
private static ArrayList<double[]> meetingWeight( User ua, User ub ) {
return meetingWeight(ua, ub, MiningFramework.distance_threshold);
} |
08d2ecbe-75dd-4e83-8e99-b4200c140d63 | private static TreeMap<String, Integer> locationDistribution( User ua ) {
TreeMap<String, Integer> freq = new TreeMap<String, Integer>();
for (Record r : ua.records) {
if (freq.containsKey(r.GPS())) {
int tmp = freq.get(r.GPS());
freq.put(r.GPS(), tmp + 1);
} else {
freq.put(r.GPS(), 1);
}
}
return freq;
} |
a070f325-b9ca-4662-9804-9318a7d95f32 | public static void main(String argv[]) {
// MiningFramework cf = new MiningFramework();
// cf.locationDistancePowerLaw();
// cf.allPairMeetingFreq(false);
// cf.writeMeetingFreq();
// cf.remoteFriends();
// cf.writeRemoteFriend();
// cf.nonFriendsMeetingFreq();
// cf.writeNonFriendsMeeting();
// int[][] friend_pair = {{19404, 350}, {3756, 4989}, {819, 3328}, {588, 401}, {551, 3340}};
// int[][] nonfriend_pair = {{819, 956}, {267, 18898}, {19096, 3756}, {19404, 267}};
// double m = 0;
// for (int[] u : friend_pair) {
//// pairAnalysis(u[0], u[1]);
// m = distanceBased_pairAnalysis(u[0], u[1]);
// System.out.println(String.format("User pair %d and %d has measure %g", u[0], u[1], m));
// }
//
// for (int[] u : nonfriend_pair) {
//// pairAnalysis(u[0], u[1]);
// m = distanceBased_pairAnalysis(u[0], u[1]);
// System.out.println(String.format("User pair %d and %d has measure %g", u[0], u[1], m));
// }
//
// distanceBasedSumLogMeasure(8320 , 10244 ,true);
// for (int i = 0; i < 10; i++) {
// User.para_c = 10 + i * 10;
// writeOutDifferentMeasures(User.para_c);
// }
// for (int i = 1; i < 11; i++ )
// MiningFramework.event_time_exp_para_c = 0.2;
writeOutDifferentMeasures(User.para_c, 101);
// locationDistancePowerLaw(2241);
// pairAnalysis(8320, 10244);
} |
91ab0082-a86f-4764-a183-90b42d60884b | public DataPreProcessor() {
long t_start = System.currentTimeMillis();
System.out.println("Data pre-processing starts ...");
BufferedReader fin = null;
int c1=0, c2=0;
try {
// initialize all users
fin = new BufferedReader(new FileReader(rawCheckinsPath));
String l = fin.readLine();
l = fin.readLine();
while (l != null) {
c1++;
Record tmp = new Record(l);
if (!users.containsKey(tmp.userID))
users.put(tmp.userID, new LinkedList<Record>());
users.get(tmp.userID).add(tmp);
l = fin.readLine();
}
fin.close();
// initialize all friendships
fin = new BufferedReader(new FileReader(rawConnectionPath));
l = fin.readLine();
l = fin.readLine();
while (l != null) {
c2++;
String[] ls = l.split(",");
int u1 = Integer.parseInt(ls[0]);
int u2 = Integer.parseInt(ls[1]);
if (!friendship.containsKey(u1))
friendship.put(u1, new LinkedList<Integer>());
if (!friendship.containsKey(u2))
friendship.put(u2, new LinkedList<Integer>());
friendship.get(u1).add(u2);
friendship.get(u2).add(u1);
l = fin.readLine();
}
fin.close();
} catch (Exception e) {
System.out.println(String.format("Line 1 %d\tLine 2 %d", c1, c2));
System.out.println(e.getMessage());
e.printStackTrace();
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Data pre-processing finished in %d seconds", (t_end - t_start)/1000));
} |
0ca37af3-c65f-457d-9f2e-a39a0a526e0f | public void generateUserFiles() {
long t_start = System.currentTimeMillis();
System.out.println("generateUserFiles starts ...");
File dir = new File(userDir);
dir.mkdir();
for (int uid : users.keySet()) {
try {
BufferedWriter fout = new BufferedWriter(new FileWriter(userDir + Integer.toString(uid)));
if (friendship.containsKey(uid))
for (int fid : friendship.get(uid))
fout.write(Integer.toString(fid) + "\t");
else
fout.write("-1");
fout.write("\n");
// sort the Records
Collections.sort(users.get(uid));
for (Record r : users.get(uid))
fout.write(r + "\n");
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("generateUserFiles ends in %d seconds", (t_end-t_start)/1000));
} |
90fb8372-f455-43d1-9737-45c411a2e890 | public void userDistribution() {
try {
BufferedWriter fout = new BufferedWriter(new FileWriter("res/checkinsN-dist.txt"));
for (int uid : users.keySet())
fout.write(Integer.toString(users.get(uid).size()) + "\n");
fout.close();
fout = new BufferedWriter(new FileWriter("res/friendsN-dist"));
for (int uid : users.keySet()) {
int cnt = 0;
if (friendship.containsKey(uid))
cnt = friendship.get(uid).size();
fout.write(Integer.toString(cnt) + "\n");
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
9a614153-cbfa-45f1-9c0e-5a8a62fecd09 | public static void main(String[] args) {
DataPreProcessor dpp = new DataPreProcessor();
// dpp.generateUserFiles();
dpp.userDistribution();
System.out.println(String.format("#user: %d\t#user with friends: %d", users.size(), friendship.size()));
} |
670ba574-db22-49d8-874a-28b2e362e9c8 | public static void initializeUsers() {
long t_start = System.currentTimeMillis();
System.out.println("Start initializeUsers.");
User.addAllUser();
long t_mid = System.currentTimeMillis();
System.out.println(String.format("Initialize all users in %d seconds", (t_mid - t_start)/1000));
} |
903f3f44-6ede-4eaa-847b-abb4c6963b5a | public static LinkedList<Integer> shareLocationCount() {
long t_start = System.currentTimeMillis();
System.out.println("shareLocationCount starts ...");
HashMap<Integer, User> users = User.allUserSet;
int cnt = 0;
// get the first level iterator
Object[] array = users.values().toArray();
for (int i = 0; i < array.length; i++) {
cnt ++;
User ui = (User) array[i];
// get the second level iterator
if (ui.friends.size() > 0) {
for (int j : ui.friends) {
if (! users.containsKey(j)) {
System.out.println(String.format("Error: friend ID %d does not exist!", j));
} else {
User uj = users.get(j);
HashSet<String> ui_loc = ui.getLocations();
HashSet<String> uj_loc = uj.getLocations();
// get intersection of two sets
HashSet<String> colocations = new HashSet<String>(ui_loc);
colocations.retainAll(uj_loc);
numOfColocations.add(colocations.size());
// record the pair that share more than 1 common locations
if (colocations.size() >= 1) {
int[] p = new int[3];
p[0] = ui.userID;
p[1] = uj.userID;
p[2] = colocations.size();
FrequentPair.add(p);
FrequentPair_CoLocations.add(colocations);
}
}
}
}
// monitor the process
if (cnt % (users.size()/10) == 0)
System.out.println(String.format("Process - shareLocationCount finished %d0%%", cnt/(users.size()/10)));
}
// output
try {
BufferedWriter fout = new BufferedWriter(new FileWriter("res/colocation-cnt.txt"));
BufferedWriter foutpair = new BufferedWriter(new FileWriter("res/pair-meetcnt.txt"));
for (int i : numOfColocations) {
fout.write(Integer.toString(i) + "\n");
}
for (int[] j : FrequentPair) {
foutpair.write(Integer.toString(j[0]) + " " + Integer.toString(j[1]) + " "
+ Integer.toString(j[2]) + "\n" );
}
fout.close();
foutpair.close();
} catch (IOException e) {
e.printStackTrace();
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Finish shareLocationCount in %d seconds", (t_end - t_start)/1000));
return numOfColocations;
} |
29787b1b-7659-44a2-bcf1-799946011202 | @SuppressWarnings("unused")
private static void writeOutPairColocations() {
System.out.println("Start writeOutPairColocations.");
try {
BufferedWriter fout = new BufferedWriter(new FileWriter("res/colocations.txt"));
String l = null;
for (User ua : User.allUserSet.values()) {
for (int ubid : ua.friends) {
if (ubid > ua.userID) {
User ub = User.allUserSet.get(ubid);
// get intersection of two sets
HashSet<String> ua_loc = ua.getLocations();
HashSet<String> ub_loc = ub.getLocations();
ua_loc.retainAll(ub_loc);
for (String loc : ua_loc)
fout.write(loc + "\t");
fout.write("\n");
}
}
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Process writeOutPairColocations ends.");
} |
b6521a43-9d38-4511-8c07-593c7e251dd7 | public static LinkedList<Double> RenyiEntropyDiversity() {
long t_start = System.currentTimeMillis();
int c1 = 0, c2 = 0;
double avg_freq1 = 0, avg_freq2 = 0;
for (int i = 0; i < FrequentPair.size(); i++) {
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
// 1. calculate the number of co-occurrence on each co-locating places
HashMap<Long, Integer> coloc = coLocationFreq (uaid, ubid);
int sum = 0;
for (int f : coloc.values()) {
sum += f;
}
// 2. calculate the probability of co-occurrence
double[] prob = new double[coloc.size()];
int ind = 0;
for (int f : coloc.values()) {
prob[ind] = (double) f / sum;
ind ++;
}
// 3. calculate the Renyi Entropy (q = 0.1)
double renyiEntropy = 0;
for (int j = 0; j < coloc.size(); j++) {
renyiEntropy += Math.pow(prob[j], 0.1);
}
renyiEntropy = Math.log(renyiEntropy) / 0.9;
// 4. calculate diversity
double divs = Math.exp(renyiEntropy);
if (sum > 1)
if (sum != coloc.size()) {
c1 ++;
avg_freq2 += sum;
} else {
c2 ++;
avg_freq1 += sum;
}
renyiDiversity.add(divs);
}
System.out.println(String.format("uniform: %d pair, %g\t non-unif %d pairs, %g", c2, avg_freq2 / (double)c2, c1, avg_freq1 / (double) c1));
long t_end = System.currentTimeMillis();
System.out.println(String.format("Renyi entropy based diversity (%d pair) found in %d seconds!", renyiDiversity.size(), (t_end - t_start)/1000));
return renyiDiversity;
} |
c37670dc-185c-4877-90da-0be94352cf6a | private static HashMap<Long, Integer> coLocationFreq( int user_a_id, int user_b_id) {
LinkedList<Record> ras = User.allUserSet.get(user_a_id).records;
LinkedList<Record> rbs = User.allUserSet.get(user_b_id).records;
HashMap<Long, Integer> loc_cnts = new HashMap<Long, Integer>();
// find records of user_a in colocating places
int aind = 0;
int bind = 0;
long last_Meet = 0;
while (aind < ras.size() && bind < rbs.size()) {
Record ra = ras.get(aind);
Record rb = rbs.get(bind);
// count the frequency
if (ra.timestamp - rb.timestamp > 3600 * 4) {
bind ++;
continue;
} else if (rb.timestamp - ra.timestamp > 3600 * 4) {
aind ++;
continue;
} else {
if (ra.locID == rb.locID && ra.timestamp - last_Meet >= 3600) {
// if (ra.distanceTo(rb) < distance_threshold && ra.timestamp - last_Meet >= 3600 ) {
if (loc_cnts.containsKey(ra.locID)) {
int f = loc_cnts.get(ra.locID);
loc_cnts.put(ra.locID, f+1);
} else {
loc_cnts.put(ra.locID, 1);
}
last_Meet = ra.timestamp;
}
aind ++;
bind ++;
}
}
return loc_cnts;
} |
ab5b08b9-cff8-4189-9509-0bf2a05704f8 | private static void initialTopKPair(int topk) {
System.out.println("Start initialTopKPair.");
try {
BufferedReader fin = new BufferedReader(new FileReader(String.format("topk_freqgt1-%d.txt", topk)));
String l = null;
BufferedReader fin2 = new BufferedReader(new FileReader(String.format("topk_colocations-%d.txt", topk)));
String l2 = null;
int c1 = 0;
int c2 = 0;
while ( (l=fin.readLine()) != null ) {
c1 ++;
String[] ls = l.split("\\s+");
if (Integer.parseInt(ls[2]) > 0) {
int uaid = Integer.parseInt(ls[0]);
int ubid = Integer.parseInt(ls[1]);
new User(uaid);
new User(ubid);
int friFlag = Integer.parseInt(ls[3]);
int[] fp = {uaid, ubid, friFlag};
FrequentPair.add(fp);
while (c2 < c1) {
c2 ++;
l2 = fin2.readLine();
if (c2 == c1) {
HashSet<String> colocs = new HashSet<String>();
String[] ls2 = l2.split("\\s+");
for (String s : ls2)
colocs.add(s);
FrequentPair_CoLocations.add(colocs);
}
}
}
}
fin.close();
fin2.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Process initialTopKPair ends.");
} |
02873cff-3238-436e-868f-260263ba34db | public static LinkedList<Double> weightedFrequency() {
long t_start = System.currentTimeMillis();
/*
* The calculation of location entropy is not efficient.
* The original execution time in HP laptop is 470s.
* After we factor out the location entropy calculation,
* now the execution time in HP is 4s.
*/
locationEntropy = readLocationEntropyIDbased();
for (int i = 0; i < FrequentPair.size(); i++) {
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
// 1. calculate the frequency of co-occurrence on each co-locating places
HashMap<Long, Integer> coloc = coLocationFreq (uaid, ubid);
// only consider people with meeting events
// if (coloc.size() > 0) {
double weightedFrequency = 0;
int frequen = 0;
for (int f : coloc.values())
frequen += f;
frequency.add(frequen);
// 2. calculate location entropy
for (long locid : coloc.keySet()) {
// the locationEntropy should contain this locid Key, otherwise we should use 0 as its entropy
weightedFrequency += coloc.get(locid) * Math.exp(- locationEntropy.get(locid));
}
weightedFreq.add(weightedFrequency);
// }
// monitor the process
if (i % (FrequentPair.size()/10) == 0)
System.out.println(String.format("Process - weightedFrequency finished %d0%%", i/(FrequentPair.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Weighted frequency (%d pairs) found in %d seconds", weightedFreq.size(), (t_end - t_start)/1000));
return weightedFreq;
} |
69db4fbe-b7c7-4d9b-ac9f-78925119c96b | private static void writePairMeasure() {
System.out.println("Start writePairMeasure");
System.out.println(String.format("%d %d %d %d", renyiDiversity.size(), weightedFreq.size(), frequency.size(), FrequentPair.size()));
long t_start = System.currentTimeMillis();
try {
BufferedWriter fout = new BufferedWriter(new FileWriter("res/sigmod13.txt"));
for (int i = 0; i < FrequentPair.size(); i++) {
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
// id_a, id_b, co-locatoin entropy, weighted frequency, frequency, friends flag
fout.write(String.format("%d\t%d\t%g\t%g\t%d\t%d\n", uaid, ubid, renyiDiversity.get(i), weightedFreq.get(i), frequency.get(i), FrequentPair.get(i)[2]));
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Process writePairMeasure finished in %d secondes.", (t_end - t_start)/1000) );
} |
048022d3-9455-4e83-96f9-69c3acf9d6dc | private static HashMap<Long, Double> locationEntropyIDbased() {
long t_start = System.currentTimeMillis();
HashMap<Long, Double> loc_entro = new HashMap<Long, Double>();
HashMap<Long, HashMap<Integer, Integer>> loc_user_visit = new HashMap<Long, HashMap<Integer, Integer>>();
HashMap<Long, Integer> loc_total_visit = new HashMap<Long, Integer>();
// 1. get the location visiting frequency
for (User u : User.allUserSet.values()) {
for (Record r : u.records) {
// count individual user visiting
if (loc_user_visit.containsKey(r.locID)) {
if (loc_user_visit.get(r.locID).containsKey(u.userID)) {
int freq = loc_user_visit.get(r.locID).get(u.userID);
loc_user_visit.get(r.locID).put(u.userID, freq + 1);
} else {
loc_user_visit.get(r.locID).put(u.userID, 1);
}
} else {
loc_user_visit.put(r.locID, new HashMap<Integer, Integer>());
loc_user_visit.get(r.locID).put(u.userID, 1);
}
// count total visiting for one location
if (loc_total_visit.containsKey(r.locID)) {
int f = loc_total_visit.get(r.locID);
loc_total_visit.put(r.locID, f+1);
} else {
loc_total_visit.put(r.locID, 1);
}
}
}
// 2. calculate the per user probability
for (Long locid : loc_user_visit.keySet()) {
double locEntropy = 0;
for (int uid : loc_user_visit.get(locid).keySet()) {
if (loc_user_visit.get(locid).size() > 1) { // if there is only one user visit this locatin, then its entropy is 0, and there won't be any meeting events.
if (loc_user_visit.get(locid).get(uid) > 0) {
double prob = (double) loc_user_visit.get(locid).get(uid) / loc_total_visit.get(locid);
locEntropy += - prob * Math.log(prob);
}
}
}
loc_entro.put(locid, locEntropy);
}
// 3. return the entropy
long t_end = System.currentTimeMillis();
System.out.println(String.format("Size of loc_entropy: %d.\n locationEntropyIDbased finished in %d seconds.", loc_entro.size(), (t_end - t_start)/1000));
return loc_entro;
} |
5ad4fa47-978a-4630-8995-36e70d851470 | private static HashMap<String, Double> locationEntropyGPSbased() {
long t_start = System.currentTimeMillis();
HashMap<String, Double> loc_entro = new HashMap<String, Double>();
HashMap<String, HashMap<Integer, Integer>> loc_user_visit = new HashMap<String, HashMap<Integer, Integer>>();
HashMap<String, Integer> loc_total_visit = new HashMap<String, Integer>();
// 1. get the GPS visiting frequency
for (User u : User.allUserSet.values()) {
for (Record r : u.records) {
// count individual user visiting
if (loc_user_visit.containsKey(r.GPS())) {
if (loc_user_visit.get(r.GPS()).containsKey(u.userID)) {
int freq = loc_user_visit.get(r.GPS()).get(u.userID);
loc_user_visit.get(r.GPS()).put(u.userID, freq + 1);
} else {
loc_user_visit.get(r.GPS()).put(u.userID, 1);
}
} else {
loc_user_visit.put(r.GPS(), new HashMap<Integer, Integer>());
loc_user_visit.get(r.GPS()).put(u.userID, 1);
}
// count total visiting for on location
if (loc_total_visit.containsKey(r.GPS())) {
int f = loc_total_visit.get(r.GPS());
loc_total_visit.put(r.GPS(), f+1);
} else {
loc_total_visit.put(r.GPS(), 1);
}
}
}
// 2. calculate the per user probability
for (String gps : loc_user_visit.keySet()) {
double locEntropy = 0;
for (int uid : loc_user_visit.get(gps).keySet()) {
if (loc_user_visit.get(gps).size() > 1)
if (loc_user_visit.get(gps).get(uid) > 0) {
double prob = (double) loc_user_visit.get(gps).get(uid) / loc_total_visit.get(gps);
locEntropy += - prob * Math.log(prob);
}
}
loc_entro.put(gps, locEntropy);
}
// 3. return the entropy
long t_end = System.currentTimeMillis();
System.out.println(String.format("Size of loc_entropy: %d.\n locationEntropyGPSbased finished in %d seconds.", loc_entro.size(), (t_end - t_start)/1000));
return loc_entro;
} |
9e4cc29c-c044-4a3e-8202-e1c9aa53b48b | public static void writeLocationEntropy(boolean IDflag, int sampleRate) {
// initialize users
int numUser = User.allUserSet.size();
Random r = new Random();
try {
HashMap<Integer, User> sampleSet = new HashMap<Integer, User>();
int c = 0;
for (User u : User.allUserSet.values()) {
if (r.nextDouble() <= sampleRate / 100.0 ) {
c++;
sampleSet.put(u.userID, u);
if (sampleSet.size() == sampleRate / 100.0 * numUser)
break;
}
}
System.out.println(String.format("Total user %d\t%d", c, User.allUserSet.size()));
User.allUserSet = sampleSet;
} catch (Exception e) {
e.printStackTrace();
}
if (IDflag == true) {
// calculate location entropy
locationEntropy = locationEntropyIDbased();
} else {
GPSEntropy = locationEntropyGPSbased();
}
// write out location entropy
try {
BufferedWriter fout;
if (IDflag == true) {
if (sampleRate <= 100) {
fout = new BufferedWriter(new FileWriter(String.format("res/locationEntropy-%ds.txt", sampleRate)));
} else {
fout = new BufferedWriter(new FileWriter("res/locationEntropy.txt"));
}
for (long loc : locationEntropy.keySet())
fout.write(String.format("%d\t%g\n", loc, locationEntropy.get(loc)));
} else {
if (sampleRate <= 100) {
fout = new BufferedWriter(new FileWriter(String.format("res/GPSEntropy-%ds.txt", sampleRate)));
} else {
fout = new BufferedWriter(new FileWriter("res/GPSEntropy.txt"));
}
for (String gps : GPSEntropy.keySet())
fout.write(String.format("%s\t%g\n", gps, GPSEntropy.get(gps)));
}
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
6d86a510-654e-4bc6-bcb7-f614406af2d8 | public static void writeLocationEntropy(boolean IDflag) {
writeLocationEntropy(IDflag, 100);
} |
9152f388-fb67-402c-b5e8-b1fadeb8b856 | public static HashMap<Long, Double> readLocationEntropyIDbased(int sampleRate) {
if (locationEntropy.isEmpty()) {
try {
BufferedReader fin;
if (sampleRate <= 100) {
fin = new BufferedReader( new FileReader(String.format("res/locationEntropy-%ds.txt", sampleRate)));
System.out.println(String.format("File locationEntropy-%ds.txt found!", sampleRate));
} else {
fin = new BufferedReader( new FileReader("res/locationEntropy.txt"));
System.out.println("File locationEntropy.txt found!");
}
String l = null;
while ((l = fin.readLine()) != null) {
String[] ls = l.split("\\s+");
long loc = Long.parseLong(ls[0]);
double entropy = Double.parseDouble(ls[1]);
locationEntropy.put(loc, entropy);
}
fin.close();
} catch (FileNotFoundException e) {
System.out.println("No location entropy file found. Generate new one ...");
writeLocationEntropy(true, sampleRate); // true use location ID, false to use GPS
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(String.format("Location entropy size %d.", locationEntropy.size()));
}
return locationEntropy;
} |
7d64d619-0707-401f-8d53-25ea21d3030b | public static HashMap<Long, Double> readLocationEntropyIDbased() {
return readLocationEntropyIDbased(101);
} |
63c58e7b-b36b-41ee-9e67-71117cb4e7f7 | public static HashMap<String, Double> readLocationEntropyGPSbased( int sampleRate ) {
if (GPSEntropy.isEmpty()) {
String fname = null;
try {
BufferedReader fin;
if (sampleRate <= 100) {
fname = String.format("res/GPSEntropy-%ds.txt", sampleRate);
} else {
fname = "res/GPSEntropy.txt";
}
fin = new BufferedReader( new FileReader(fname));
System.out.println(String.format("File %s found!", fname));
String l = null;
while ( (l=fin.readLine()) != null) {
String[] ls = l.split("\\s+");
String gps = ls[0];
double entropy = Double.parseDouble(ls[1]);
if (! GPSEntropy.containsKey(gps))
GPSEntropy.put(gps, entropy);
}
fin.close();
} catch (FileNotFoundException e) {
System.out.println(String.format("No GPS entropy file %s found. Generate a new one ...", fname));
writeLocationEntropy(false, sampleRate);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(String.format("GPS location size %d.", GPSEntropy.size()));
}
return GPSEntropy;
} |
ba12c8ab-48f6-4e5b-b993-3f302c48ef78 | public static LinkedList<Double> mutualInformation() {
long t_start = System.currentTimeMillis();
/*
* Speed boost
* the old method is not efficient, because it is not necessary to calculate the
* marginal entropy repeatedly.
*/
HashMap<Integer, Double> entro = new HashMap<Integer,Double>();
for (int i = 0; i < FrequentPair.size(); i++) {
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
// 1. calculate the marginal entropy of user a
double entroA;
if (entro.containsKey(uaid))
entroA = entro.get(uaid);
else {
entroA = marginalEntropy(uaid);
entro.put(uaid, entroA);
}
// 2. calculate the marginal entropy of user b
double entroB;
if (entro.containsKey(ubid))
entroB = entro.get(ubid);
else {
entroB = marginalEntropy(ubid);
entro.put(ubid, entroB);
}
// 3. joint entropy of A and B
double jointEntro = jointEntropy(uaid, ubid);
// 4. mutual information
mutualInfo.add(entroA + entroB - jointEntro);
// monitor the process
if (i % (FrequentPair.size()/10) == 0)
System.out.println(String.format("Process - mutualInformation finished %d0%%", i/(FrequentPair.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Calculate mutual inforamtion in %d seconds", (t_end - t_start)/1000));
return mutualInfo;
} |
2713cbdf-2c9a-4644-8a30-addbeeda348b | private static double marginalEntropy(int uid) {
User u = User.allUserSet.get(uid);
HashMap<Long, Integer> locFreq = new HashMap<Long, Integer>();
// 1. count frequency
int totalLocationNum = u.records.size();
for (Record r : u.records) {
if (locFreq.containsKey(r.locID))
locFreq.put(r.locID, locFreq.get(r.locID) + 1);
else
locFreq.put(r.locID, 1);
}
// 2. probability and entropy
double prob = 0;
double entro = 0;
for (Long i : locFreq.keySet()) {
prob = (double) locFreq.get(i) / totalLocationNum;
entro += - prob * Math.log(prob);
}
return entro;
} |
4e73b11b-d64c-476c-89ff-5d53daf1888b | private static double jointEntropy( int uaid, int ubid ) {
User a = User.allUserSet.get(uaid);
User b = User.allUserSet.get(ubid);
HashMap<Long, HashMap<Long, Integer>> locFreq = new HashMap<>();
// 1. count frequency of multi-variables distribution
int totalCase = 0;
for (Record ar : a.records) {
for (Record br : b.records) {
// ar and br are in the same time slots
//if (Math.abs(ar.timestamp - br.timestamp) <= 4 * 3600) {
// put that observation at the same timeslot into the two level maps
if (locFreq.containsKey(ar.locID) && locFreq.get(ar.locID).containsKey(br.locID)) {
int f = locFreq.get(ar.locID).get(br.locID) + 1;
locFreq.get(ar.locID).put(br.locID, f);
totalCase ++;
}
else if (locFreq.containsKey(ar.locID) && ! locFreq.get(ar.locID).containsKey(br.locID)) {
locFreq.get(ar.locID).put(br.locID, 1);
totalCase ++;
}
else if (!locFreq.containsKey(ar.locID)) {
locFreq.put(ar.locID, new HashMap<Long, Integer>());
locFreq.get(ar.locID).put(br.locID, 1);
totalCase ++;
}
//}
}
}
//System.out.println(String.format("Total case of joint entropy %d", totalCase));
// 2. probability and entropy
double prob = 0;
double entro = 0;
for (Long i : locFreq.keySet()) {
for (Long j : locFreq.get(i).keySet()) {
prob = (double) locFreq.get(i).get(j) / totalCase;
entro += - prob * Math.log(prob);
}
}
return entro;
} |
55cdf147-4d87-49ed-be17-544a06509ecd | public static LinkedList<Double> mutualInformation_v2() {
long t_start = System.currentTimeMillis();
// 1. calculate the individual probability
HashMap<Integer, HashMap<Long, Double>> user_loc_prob = new HashMap<Integer, HashMap<Long, Double>>();
for (int[] p : FrequentPair) {
for (int i = 0; i < 2; i++ ) {
int uid = p[i];
for (Record ra : User.allUserSet.get(uid).records) {
if (user_loc_prob.containsKey(uid)) {
if (user_loc_prob.get(uid).containsKey(ra.locID)) {
double f = user_loc_prob.get(uid).get(ra.locID);
user_loc_prob.get(uid).put(ra.locID, f + 1);
} else {
user_loc_prob.get(uid).put(ra.locID, 1.0);
}
} else {
user_loc_prob.put(uid, new HashMap<Long, Double>());
user_loc_prob.get(uid).put(ra.locID, 1.0);
}
}
int cnt = User.allUserSet.get(uid).records.size();
for (Long locid : user_loc_prob.get(uid).keySet()) {
double freq = user_loc_prob.get(uid).get(locid);
user_loc_prob.get(uid).put(locid, freq / cnt);
}
}
}
for (int i = 0; i < FrequentPair.size(); i++ ) {
// 2. calculate the pair frequency
HashMap<Long, HashMap<Long, Double>> pairLocProb = new HashMap<>();
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
int totalCase = 0;
for (Record ar : User.allUserSet.get(uaid).records) {
for (Record br : User.allUserSet.get(ubid).records) {
if (pairLocProb.containsKey(ar.locID) && pairLocProb.get(ar.locID).containsKey(br.locID)) {
double f = pairLocProb.get(ar.locID).get(br.locID) + 1;
pairLocProb.get(ar.locID).put(br.locID, f);
totalCase ++;
}
else if (pairLocProb.containsKey(ar.locID) && ! pairLocProb.get(ar.locID).containsKey(br.locID)) {
pairLocProb.get(ar.locID).put(br.locID, 1.0);
totalCase ++;
}
else if (!pairLocProb.containsKey(ar.locID)) {
pairLocProb.put(ar.locID, new HashMap<Long, Double>());
pairLocProb.get(ar.locID).put(br.locID, 1.0);
totalCase ++;
}
}
}
double mutualE = 0;
for (Long l1 : pairLocProb.keySet()) {
for (Long l2: pairLocProb.get(l1).keySet()) {
// 3. calculate the pair probability
double f = pairLocProb.get(l1).get(l2);
double pairProb = f / totalCase;
// 4. calculate the mutual information
mutualE += pairProb * Math.log(pairProb / user_loc_prob.get(uaid).get(l1) / user_loc_prob.get(ubid).get(l2));
}
}
mutualInfo.add(mutualE);
// monitor the process
if (i % (FrequentPair.size()/10) == 0)
System.out.println(String.format("Process - mutualInformation_v2 finished %d0%%", i/(FrequentPair.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("mutualInformation_v2 executed for %d seconds", (t_end-t_start)/1000));
return mutualInfo;
} |
fc1f36f0-fde7-4818-8de0-8f42ddf437fe | public static LinkedList<Double> interestingnessPAKDD() {
long t_start = System.currentTimeMillis();
for (int i = 0; i < FrequentPair.size(); i++ ) {
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
HashSet<String> colocs = FrequentPair_CoLocations.get(i);
// 1. calculate the colocating interestness
double Finterest = coLocationScore(uaid, ubid, colocs);
interestingness.add(Finterest);
// monitor the process
if (i % (FrequentPair.size()/10) == 0)
System.out.println(String.format("Process - interestingnessPAKDD finished %d0%%", i/(FrequentPair.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("Interestingness score found in %d seconds", (t_end - t_start)/1000));
return interestingness;
} |
705a1a9e-c195-45db-832c-dd7ba7fe7850 | private static double coLocationScore( int user_a_id, int user_b_id, HashSet<String> colocs ) {
LinkedList<Record> ra = User.allUserSet.get(user_a_id).records;
HashMap<String, LinkedList<Record>> raco = new HashMap<String, LinkedList<Record>>();
LinkedList<Record> rb = User.allUserSet.get(user_b_id).records;
HashMap<String, LinkedList<Record>> rbco = new HashMap<String, LinkedList<Record>>();
double interest = 0;
// System.out.println(String.format("Colocs size %d", colocs.size()));
// find the reverse map of location count
for (Record r : ra) {
if (raco.containsKey(r.GPS())) {
raco.get(r.GPS()).add(r);
} else {
raco.put(r.GPS(), new LinkedList<Record>());
raco.get(r.GPS()).add(r);
}
}
for (Record r : rb) {
if (rbco.containsKey(r.GPS())) {
rbco.get(r.GPS()).add(r);
} else {
rbco.put(r.GPS(), new LinkedList<Record>());
rbco.get(r.GPS()).add(r);
}
}
for (String loc_id : colocs) {
// judge their co-locating events with time
for (Record r1 : raco.get(loc_id)) {
for (Record r2 : rbco.get(loc_id)) {
// We identify the co-locating event with a 4-hour time window
if (r1.timestamp - r2.timestamp <= 3600 * 4)
interest += - Math.log( (double) raco.get(loc_id).size() / ra.size())
- Math.log( (double) rbco.get(loc_id).size() / rb.size() );
}
}
}
return interest;
} |
9c1259e5-5a79-4edd-849f-3a11e9fc82f0 | public static LinkedList<Double> mutualEntropyOnColocation() {
long t_start = System.currentTimeMillis();
// calculate the marginal entropy of each user only once.
HashMap<Integer, Double> entro = new HashMap<Integer, Double>();
for (int i = 0; i < FrequentPair.size(); i++) {
// get two user
User a = User.allUserSet.get(FrequentPair.get(i)[0]);
User b = User.allUserSet.get(FrequentPair.get(i)[1]);
HashSet<String> locs = FrequentPair_CoLocations.get(i);
// 1. calculate the marginal entropy of U_a over co-locations
double entroA = 0;
if (entro.containsKey(a.userID)) {
entroA = entro.get(a.userID);
} else {
entroA = marginalEntropy(a.userID, locs );
entro.put(a.userID, entroA);
}
// 2. calculate the marginal entropy of U_b over co-locations
double entroB = 0;
if (entro.containsKey(b.userID)) {
entroB = entro.get(b.userID);
} else {
entroB = marginalEntropy(b.userID, locs);
entro.put(b.userID, entroB);
}
// 3. calculate the joint entropy of U_a and U_b over
double joint_entro = jointEntropy(a.userID, b.userID, locs);
mutualEntroColoc.add(entroA + entroB - joint_entro);
// monitor the process
if (i % (FrequentPair.size()/10) == 0)
System.out.println(String.format("Process - mutualEntropyOnColocation finished %d0%%", i/(FrequentPair.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("mutualEntropyOnColocation executed %d seconds", (t_end - t_start)/1000));
return mutualEntroColoc;
} |
e460142e-9c36-4bcb-8cf4-aa8c2249274b | private static double marginalEntropy(int uid, HashSet<String> locs) {
User u = User.allUserSet.get(uid);
HashMap<Long, Integer> locFreq = new HashMap<Long, Integer>();
// 1. count frequency on each locations in location set
int totalLocationNum = 0;
for (Record r : u.records) {
if (locs.contains(r.locID)) {
if (locFreq.containsKey(r.locID)) {
totalLocationNum ++;
locFreq.put(r.locID, locFreq.get(r.locID) + 1);
}
else {
totalLocationNum ++;
locFreq.put(r.locID, 1);
}
}
}
// 2. probability and entropy
double prob = 0;
double entro = 0;
for (Long i : locFreq.keySet()) {
prob = (double) locFreq.get(i) / totalLocationNum;
entro += - prob * Math.log(prob);
}
return entro;
} |
3ad9fc97-8041-4149-a6f3-0b83c6c61843 | private static double jointEntropy( int uaid, int ubid, HashSet<String> locs ) {
User a = User.allUserSet.get(uaid);
User b = User.allUserSet.get(ubid);
HashMap<Long, HashMap<Long, Integer>> locFreq = new HashMap<Long, HashMap<Long, Integer>>();
// 1. count frequency over given location set
int totalCase = 0;
for (Record ar : a.records) {
for (Record br : b.records) {
// Two records in same timeslot
//if (Math.abs(ar.timestamp-br.timestamp) <= 4 * 3600) {
// count frequency only on the target set
if (locs.contains(ar.locID) && locs.contains(br.locID)) {
if (locFreq.containsKey(ar.locID) && locFreq.get(ar.locID).containsKey(br.locID)) {
int f = locFreq.get(ar.locID).get(br.locID) + 1;
locFreq.get(ar.locID).put(br.locID, f);
totalCase ++;
}
else if (locFreq.containsKey(ar.locID) && ! locFreq.get(ar.locID).containsKey(br.locID)) {
locFreq.get(ar.locID).put(br.locID, 1);
totalCase ++;
}
else if (!locFreq.containsKey(ar.locID)) {
locFreq.put(ar.locID, new HashMap<Long, Integer>());
locFreq.get(ar.locID).put(br.locID, 1);
totalCase ++;
}
}
//}
}
}
// 2. probability and entropy
double prob = 0;
double entro = 0;
for (Long i : locFreq.keySet()) {
for (Long j : locFreq.get(i).keySet()) {
prob = (double) locFreq.get(i).get(j) / totalCase;
entro += - prob * Math.log(prob);
}
}
return entro;
} |
e350b73f-dede-4eeb-a1df-8a93dafb6dbd | public static LinkedList<Double> mutualEntropyOnColocation_v2() {
long t_start = System.currentTimeMillis();
// 1. calculate the individual probability
HashMap<Integer, HashMap<Long, Double>> user_loc_prob = new HashMap<Integer, HashMap<Long, Double>>();
for (int i = 0; i < FrequentPair.size(); i++) {
int[] p = FrequentPair.get(i);
// get given target locatoin set
HashSet<String> locs = FrequentPair_CoLocations.get(i);
for (int j = 0; j < 2; j++ ) {
int uid = p[j];
int cnt = 0;
for (Record ra : User.allUserSet.get(uid).records) {
if (locs.contains(ra.locID)) {
if (user_loc_prob.containsKey(uid)) {
if (user_loc_prob.get(uid).containsKey(ra.locID)) {
double f = user_loc_prob.get(uid).get(ra.locID);
user_loc_prob.get(uid).put(ra.locID, f + 1);
} else {
user_loc_prob.get(uid).put(ra.locID, 1.0);
}
} else {
user_loc_prob.put(uid, new HashMap<Long, Double>());
user_loc_prob.get(uid).put(ra.locID, 1.0);
}
cnt ++;
}
}
for (Long locid : user_loc_prob.get(uid).keySet()) {
double freq = user_loc_prob.get(uid).get(locid);
user_loc_prob.get(uid).put(locid, freq / cnt);
}
}
}
for (int i = 0; i < FrequentPair.size(); i++ ) {
// 2. calculate the pair frequency
HashMap<Long, HashMap<Long, Double>> pairLocProb = new HashMap<>();
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
HashSet<String> locs = FrequentPair_CoLocations.get(i);
int totalCase = 0;
for (Record ar : User.allUserSet.get(uaid).records) {
for (Record br : User.allUserSet.get(ubid).records) {
if (locs.contains(ar.locID) && locs.contains(br.locID)) {
if (pairLocProb.containsKey(ar.locID) && pairLocProb.get(ar.locID).containsKey(br.locID)) {
double f = pairLocProb.get(ar.locID).get(br.locID) + 1;
pairLocProb.get(ar.locID).put(br.locID, f);
totalCase ++;
}
else if (pairLocProb.containsKey(ar.locID) && ! pairLocProb.get(ar.locID).containsKey(br.locID)) {
pairLocProb.get(ar.locID).put(br.locID, 1.0);
totalCase ++;
}
else if (!pairLocProb.containsKey(ar.locID)) {
pairLocProb.put(ar.locID, new HashMap<Long, Double>());
pairLocProb.get(ar.locID).put(br.locID, 1.0);
totalCase ++;
}
}
}
}
double mutualE = 0;
for (Long l1 : pairLocProb.keySet()) {
for (Long l2: pairLocProb.get(l1).keySet()) {
// 3. calculate the pair probability
double f = pairLocProb.get(l1).get(l2);
double pairProb = f / totalCase;
// 4. calculate the mutual information
mutualE += pairProb * Math.log(pairProb / user_loc_prob.get(uaid).get(l1) / user_loc_prob.get(ubid).get(l2));
}
}
mutualEntroColoc.add(mutualE);
// monitor the process
if (i % (FrequentPair.size()/10) == 0)
System.out.println(String.format("Process - mutualEntroColocation_v2 finished %d0%%", i/(FrequentPair.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("mutualEntroColocation_v2 executed for %d seconds", (t_end-t_start)/1000));
return mutualEntroColoc;
} |
ed3b7840-d3ca-40f6-84e8-c39bab2c6857 | public static LinkedList<Double> mutualEntropyOnColocation_v3() {
long t_start = System.currentTimeMillis();
// 1. calculate the individual probability
HashMap<Integer, HashMap<Long, Double>> user_loc_prob = new HashMap<Integer, HashMap<Long, Double>>();
for (int i = 0; i < FrequentPair.size(); i++) {
int[] p = FrequentPair.get(i);
// get given target locatoin set
HashSet<String> locs = FrequentPair_CoLocations.get(i);
for (int j = 0; j < 2; j++ ) {
int uid = p[j];
int cnt = 0;
for (Record ra : User.allUserSet.get(uid).records) {
if (locs.contains(ra.locID)) {
if (user_loc_prob.containsKey(uid)) {
if (user_loc_prob.get(uid).containsKey(ra.locID)) {
double f = user_loc_prob.get(uid).get(ra.locID);
user_loc_prob.get(uid).put(ra.locID, f + 1);
} else {
user_loc_prob.get(uid).put(ra.locID, 1.0);
}
} else {
user_loc_prob.put(uid, new HashMap<Long, Double>());
user_loc_prob.get(uid).put(ra.locID, 1.0);
}
cnt ++;
}
}
for (Long locid : user_loc_prob.get(uid).keySet()) {
double freq = user_loc_prob.get(uid).get(locid);
user_loc_prob.get(uid).put(locid, freq / cnt);
}
}
}
for (int i = 0; i < FrequentPair.size(); i++ ) {
// 2. calculate the pair frequency
HashMap<Long, Double> pairLocProb = new HashMap<>();
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
HashSet<String> locs = FrequentPair_CoLocations.get(i);
int totalCase = 0;
for (Record ar : User.allUserSet.get(uaid).records) {
for (Record br : User.allUserSet.get(ubid).records) {
// ar and br are same location
if (locs.contains(ar.locID) && ar.locID == br.locID) {
if (pairLocProb.containsKey(ar.locID)) {
double f = pairLocProb.get(ar.locID) + 1;
pairLocProb.put(ar.locID, f);
totalCase ++;
} else {
pairLocProb.put(ar.locID, 1.0);
totalCase ++;
}
}
}
}
double mutualE = 0;
for (Long l : pairLocProb.keySet()) {
// 3. calculate the pair probability
double f = pairLocProb.get(l);
double pairProb = f / totalCase;
// 4. calculate the mutual information
mutualE += pairProb * Math.log(pairProb / user_loc_prob.get(uaid).get(l) / user_loc_prob.get(ubid).get(l));
}
mutualEntroColoc_v3.add(mutualE);
// monitor the process
if (i % (FrequentPair.size()/10) == 0)
System.out.println(String.format("Process - mutualEntroColocation_v3 finished %d0%%", i/(FrequentPair.size()/10)));
}
long t_end = System.currentTimeMillis();
System.out.println(String.format("mutualEntroColocation_v3 executed for %d seconds", (t_end-t_start)/1000));
return mutualEntroColoc_v3;
} |
69956888-7059-4280-b786-ac72090d53c1 | public static LinkedList<Double> relativeMutualEntropy() {
for (int i = 0; i < FrequentPair.size(); i++) {
int uaid = FrequentPair.get(i)[0];
int ubid = FrequentPair.get(i)[1];
HashSet<String> locs = FrequentPair_CoLocations.get(i);
double entroA = marginalEntropy(uaid, locs);
double entroB = marginalEntropy(ubid, locs);
System.out.println(String.format("entro A %g, B %g", entroA, entroB));
relaMutualEntro.add(mutualEntroColoc.get(i) / (entroA + entroB));
}
return relaMutualEntro;
} |
cb43e564-fb40-4af4-b066-f4cec31f8c96 | @SuppressWarnings("unused")
private static void writeThreeMeasures(String filename) {
try{
BufferedWriter fout = new BufferedWriter(new FileWriter(filename));
// output Renyi entropy diversity
for (double d : renyiDiversity) {
fout.write(Double.toString(d) + "\t");
}
fout.write("\n");
// output weighted co-occurrence frequency
for (double d : weightedFreq) {
fout.write(Double.toString(d) + "\t");
}
fout.write("\n");
// output mutual information
for (double d : mutualInfo) {
fout.write(Double.toString(d) + "\t");
}
fout.write("\n");
// output interestingness from PAKDD
for (double d : interestingness) {
fout.write(Double.toString(d) + "\t");
}
fout.write("\n");
// output frequency
for (int i : frequency) {
fout.write(Integer.toString(i) + "\t");
}
fout.write("\n");
for (double i : mutualEntroColoc) {
fout.write(Double.toString(i) + "\t");
}
fout.write("\n");
for (double i : mutualEntroColoc_v3) {
fout.write(Double.toString(i) + "\t");
}
fout.write("\n");
for (double i : relaMutualEntro) {
fout.write(Double.toString(i) + "\t");
}
fout.write("\n");
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
f04657b7-a6ee-4d11-8912-8188353fe23e | public static void main(String argv[]) {
// 1. find frequent user pair
initializeUsers();
shareLocationCount();
// 2. calculate feature one -- Renyi entropy based diversity
RenyiEntropyDiversity();
// // 3. calculate feature two -- weighted frequency, and frequency
weightedFrequency();
writePairMeasure();
// // 4. calculate feature three -- mutual information
// mutualInformation();
// mutualInformation_v2();
// // 5. calculate feature four -- interestingness
// interestingnessPAKDD();
// // 6. calculate mutual information over colocations
// mutualEntropyOnColocation();
// mutualEntropyOnColocation_v2();
// mutualEntropyOnColocation_v3();
// relativeMutualEntropy();
// 6. write the results
// writeThreeMeasures("feature-vectors-rme.txt");
// writeOutPairColocations();
// for (int i = 1; i < 10; i += 1)
// writeLocationEntropy(5000, true, 2);
// evaluateSIGMOD();
} |
d36777ed-7d39-443a-be05-385b854b5969 | public static void evaluateSIGMOD() {
// initialize top users
initializeUsers();
initialTopKPair(5000);
RenyiEntropyDiversity();
weightedFrequency();
writePairMeasure();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.