forked from yixuan/recosystem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.cpp
More file actions
126 lines (103 loc) · 2.63 KB
/
Copy pathconvert.cpp
File metadata and controls
126 lines (103 loc) · 2.63 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <string>
#include <iostream>
#include <cstring>
#include "mf.h"
#include <Rcpp.h>
namespace
{
/*
struct ConvertOption
{
std::string text_path, binary_path;
};
void convert_help()
{
printf("usage: libmf convert text_file [binary_file]\n");
}
std::shared_ptr<ConvertOption> parse_convert_option(
int const argc, char const * const * const argv)
{
if((argc != 1) && (argc != 2))
{
// convert_help();
return std::shared_ptr<ConvertOption>(nullptr);
}
std::shared_ptr<ConvertOption> option(new ConvertOption);
option->text_path = std::string(argv[0]);
if(argc == 2)
{
option->binary_path = std::string(argv[1]);
}
else
{
const char *p = strrchr(argv[0], '/');
if(!p)
p = argv[0];
else
p++;
option->binary_path = std::string(p) + ".bin";
}
return option;
}
*/
bool convert(std::string const &text_path, std::string const &binary_path)
{
FILE *f = fopen(text_path.c_str(), "r");
if(!f)
{
// fprintf(stderr, "\nError: Cannot open %s.", text_path.c_str());
Rcpp::stop("Cannot open %s", text_path.c_str());
return false;
}
Timer timer;
timer.tic("Converting...");
Matrix M;
double sum = 0;
while(true)
{
Node r;
if(fscanf(f, "%d %d %f\n", &r.uid, &r.iid, &r.rate) == EOF)
break;
if(r.uid < 0 || r.iid <0)
{
// fprintf(stderr, "\nError: User ID and Item ID should not be smaller than zero.\n");
Rcpp::stop("User ID and Item ID should not be smaller than zero");
return false;
}
if(r.uid+1 > M.nr_users)
M.nr_users = r.uid+1;
if(r.iid+1 > M.nr_items)
M.nr_items = r.iid+1;
sum += r.rate;
M.R.push_back(r);
}
M.nr_ratings = (long)(M.R.size());
M.avg = (float)(sum/M.nr_ratings);
timer.toc("done.");
if(!write_matrix(M, binary_path))
return false;
fclose(f);
return true;
}
} // namespace
/*
int convert(int const argc, const char * const * const argv)
{
std::shared_ptr<ConvertOption> option = parse_convert_option(argc, argv);
if(!option)
return EXIT_FAILURE;
if(!convert(option->text_path, option->binary_path))
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
*/
using namespace Rcpp;
extern "C" SEXP convert_wrapper(SEXP raw_file, SEXP bin_file)
{
BEGIN_RCPP
std::string raw_path = as<std::string>(raw_file);
std::string bin_path = as<std::string>(bin_file);
bool res = convert(raw_path, bin_path);
return wrap(res);
END_RCPP
}