m2mnbrs.c 9.46 KB
Newer Older
lisj's avatar
lisj committed
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*!
\file  
\brief It takes as input two CSR matrices and finds for each row of the 
       first matrix the most similar rows in the second matrix.

\date 9/27/2014
\author George
\version \verbatim $Id: m2mnbrs.c 17699 2014-09-27 18:05:31Z karypis $ \endverbatim
*/

#include <GKlib.h>

/*************************************************************************/
/*! Data structures for the code */
/*************************************************************************/
typedef struct {
  int simtype;             /*!< The similarity type to use */
  int nnbrs;               /*!< The maximum number of nearest neighbots to output */
  float minsim;            /*!< The minimum similarity to use for keeping neighbors */

  int verbosity;           /*!< The reporting verbosity level */

  char *qfile;             /*!< The file storing the query documents */
  char *cfile;             /*!< The file storing the collection documents */
  char *outfile;           /*!< The file where the output will be stored */

  /* timers */
  double timer_global;
  double timer_1;
  double timer_2;
  double timer_3;
  double timer_4;
} params_t;


/*************************************************************************/
/*! Constants */
/*************************************************************************/
/* Versions */
#define VER_MAJOR           0
#define VER_MINOR           1
#define VER_SUBMINOR        0

/* Command-line option codes */
#define CMD_SIMTYPE         10
#define CMD_NNBRS           20
#define CMD_MINSIM          22
#define CMD_VERBOSITY       70
#define CMD_HELP            100

/* The text labels for the different simtypes */
static char simtypenames[][10] = {"", "dotp", "cos", "jac", ""};



/*************************************************************************/
/*! Local variables */
/*************************************************************************/
static struct gk_option long_options[] = {
  {"simtype",           1,      0,      CMD_SIMTYPE},
  {"nnbrs",             1,      0,      CMD_NNBRS},
  {"minsim",            1,      0,      CMD_MINSIM},
  {"verbosity",         1,      0,      CMD_VERBOSITY},

  {"help",              0,      0,      CMD_HELP},
  {0,                   0,      0,      0}
};

static gk_StringMap_t simtype_options[] = {
  {"cos",                GK_CSR_COS},
  {"jac",                GK_CSR_JAC},
  {NULL,                 0}
};


/*-------------------------------------------------------------------
 * Mini help
 *-------------------------------------------------------------------*/
static char helpstr[][100] =
{
" ",
"Usage: m2mnbrs [options] qfile cfile [outfile]",
" ",
" Options",
"  -simtype=string",
"     Specifies the type of similarity to use. Possible values are:",
"       cos   - Cosine similarity",
"       jac   - Jacquard similarity [default]", 
" ",
"  -nnbrs=int",
"     Specifies the maximum number of nearest neighbors.",
"     A value of -1 indicates that all neighbors will be considered.",
"     Default value is 100.",
" ",
"  -minsim=float",
"     The minimum allowed similarity between neighbors. ",
"     Default value is .25.",
" ",
"  -verbosity=int",
"     Specifies the level of debugging information to be displayed.",
"     Default value is 0.",
" ",
"  -help",
"     Prints this message.",
""
};



/*************************************************************************/
/*! Function prototypes */
/*************************************************************************/
params_t *parse_cmdline(int argc, char *argv[]);
void FindNeighbors(params_t *params, gk_csr_t *qmat, gk_csr_t *cmat);


/*************************************************************************/
/*! This is the entry point of the command-line argument parser */
/*************************************************************************/
params_t *parse_cmdline(int argc, char *argv[])
{
  int i;
  int c, option_index;
  params_t *params;

  params = (params_t *)gk_malloc(sizeof(params_t), "parse_cmdline: params");

  /* initialize the params data structure */
  params->simtype   = GK_CSR_JAC;
  params->nnbrs     = 100;
  params->minsim    = .25;
  params->verbosity = -1;
  params->qfile     = NULL;
  params->cfile     = NULL;
  params->outfile   = NULL;


  /* Parse the command line arguments  */
  while ((c = gk_getopt_long_only(argc, argv, "", long_options, &option_index)) != -1) {
    switch (c) {
      case CMD_SIMTYPE:
        if (gk_optarg) {
          if ((params->simtype = gk_GetStringID(simtype_options, gk_optarg)) == -1)
            errexit("Invalid simtype of %s.\n", gk_optarg);
        }
        break;

      case CMD_NNBRS:
        if (gk_optarg) params->nnbrs = atoi(gk_optarg);
        break;

      case CMD_MINSIM:
        if (gk_optarg) params->minsim = atof(gk_optarg);
        break;

      case CMD_VERBOSITY:
        if (gk_optarg) params->verbosity = atoi(gk_optarg);
        break;

      case CMD_HELP:
        for (i=0; strlen(helpstr[i]) > 0; i++)
          printf("%s\n", helpstr[i]);
        exit(EXIT_SUCCESS);
        break;

      case '?':
      default:
        printf("Illegal command-line option(s)\nUse %s -help for a summary of the options.\n", argv[0]);
        exit(EXIT_FAILURE);
    }
  }

  /* Get the input/output file info */
  if (argc-gk_optind < 1) {
    printf("Missing input/output file info.\n  Use %s -help for a summary of the options.\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  params->qfile   = gk_strdup(argv[gk_optind++]);
  params->cfile   = gk_strdup(argv[gk_optind++]);
  params->outfile = (gk_optind < argc ? gk_strdup(argv[gk_optind++]) : NULL);

  if (!gk_fexists(params->qfile))
    errexit("input file %s does not exist.\n", params->qfile);
  if (!gk_fexists(params->cfile))
    errexit("input file %s does not exist.\n", params->cfile);

  return params;
}


/*************************************************************************/
/*! This is the entry point of the program */
/**************************************************************************/
int main(int argc, char *argv[])
{
  params_t *params;
  gk_csr_t *qmat, *cmat;
  int rc = EXIT_SUCCESS;

  params = parse_cmdline(argc, argv);

  qmat = gk_csr_Read(params->qfile, GK_CSR_FMT_CSR, 1, 0);
  cmat = gk_csr_Read(params->cfile, GK_CSR_FMT_CSR, 1, 0);


  printf("********************************************************************************\n");
  printf("sd (%d.%d.%d) Copyright 2014, GK.\n", VER_MAJOR, VER_MINOR, VER_SUBMINOR);
  printf("  simtype=%s, nnbrs=%d, minsim=%.2f\n",
      simtypenames[params->simtype], params->nnbrs, params->minsim);
  printf("  qfile=%s, nrows=%d, ncols=%d, nnz=%zd\n",
      params->qfile, qmat->nrows, qmat->ncols, qmat->rowptr[qmat->nrows]);
  printf("  cfile=%s, nrows=%d, ncols=%d, nnz=%zd\n",
      params->cfile, cmat->nrows, cmat->ncols, cmat->rowptr[cmat->nrows]);

  gk_clearwctimer(params->timer_global);
  gk_clearwctimer(params->timer_1);
  gk_clearwctimer(params->timer_2);
  gk_clearwctimer(params->timer_3);
  gk_clearwctimer(params->timer_4);

  gk_startwctimer(params->timer_global);

  FindNeighbors(params, qmat, cmat);

  gk_stopwctimer(params->timer_global);

  printf("    wclock: %.2lfs\n", gk_getwctimer(params->timer_global));
  printf("    timer1: %.2lfs\n", gk_getwctimer(params->timer_1));
  printf("    timer2: %.2lfs\n", gk_getwctimer(params->timer_2));
  printf("    timer3: %.2lfs\n", gk_getwctimer(params->timer_3));
  printf("    timer4: %.2lfs\n", gk_getwctimer(params->timer_4));
  printf("********************************************************************************\n");

  gk_csr_Free(&qmat);
  gk_csr_Free(&cmat);

  exit(rc);
}


/*************************************************************************/
/*! Reads and computes the neighbors of each query document against the
    collection of documents */
/**************************************************************************/
void FindNeighbors(params_t *params, gk_csr_t *qmat, gk_csr_t *cmat)
{
  int iQ, iH, nhits;
  int32_t *marker;
  gk_fkv_t *hits, *cand;
  FILE *fpout;

  GKASSERT(qmat->ncols <= cmat->ncols);

  /* if cosine, make rows unit length */
  if (params->simtype == GK_CSR_COS) {
    gk_csr_Normalize(qmat, GK_CSR_ROW, 2);
    gk_csr_Normalize(cmat, GK_CSR_ROW, 2);
  }

  /* create the inverted index */
  gk_csr_CreateIndex(cmat, GK_CSR_COL);

  /* compute the row norms */
  gk_csr_ComputeSquaredNorms(cmat, GK_CSR_ROW);

  /* create the output file */
  fpout = (params->outfile ? gk_fopen(params->outfile, "w", "FindNeighbors: fpout") : NULL);

  /* allocate memory for the necessary working arrays */
  hits   = gk_fkvmalloc(cmat->nrows, "FindNeighbors: hits");
  marker = gk_i32smalloc(cmat->nrows, -1, "FindNeighbors: marker");
  cand   = gk_fkvmalloc(cmat->nrows, "FindNeighbors: cand");


  /* find the best neighbors for each query document */
  gk_startwctimer(params->timer_1);
  for (iQ=0; iQ<qmat->nrows; iQ++) {
    if (params->verbosity > 0)
      printf("Working on query %7d\n", iQ);

    /* find the neighbors of the ith document */ 
    nhits = gk_csr_GetSimilarRows(cmat, 
                 qmat->rowptr[iQ+1]-qmat->rowptr[iQ], 
                 qmat->rowind+qmat->rowptr[iQ], 
                 qmat->rowval+qmat->rowptr[iQ], 
                 params->simtype, params->nnbrs, params->minsim, 
                 hits, marker, cand);

    /* write the results in the file */
    if (fpout) {
      for (iH=0; iH<nhits; iH++) 
        fprintf(fpout, "%8d %8zd %.3f\n", iQ, hits[iH].val, hits[iH].key);
    }
  }
  gk_stopwctimer(params->timer_1);


  /* cleanup and exit */
  if (fpout) gk_fclose(fpout);

  gk_free((void **)&hits, &marker, &cand, LTERM);
}