-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchunktermsearch.php
executable file
·414 lines (368 loc) · 12.9 KB
/
chunktermsearch.php
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php
// FUNCTIONS
//####################
function cosine_sim($vecstring1, $vecstring2, $sumsq1, $sumsq2) {
//echo "vecstring1: ".$vecstring1."<br/>";
$vector1 = explode(" ", $vecstring1);
$vector2 = explode(" ", $vecstring2);
$numdims = count($vector1);
//echo "count: ".$numdims.", ";
$dotproduct = 0.0;
$increment = 0.0;
for ($d = 0; $d < $numdims; $d++) {
$increment = $vector1[$d] * $vector2[$d];
$dotproduct = $dotproduct + $increment;
}
$magnitude = ($sumsq1 * $sumsq2);
//echo "magn: ".$magnitude.", ";
$rawcorrelation = $dotproduct / $magnitude;
//echo "raw corr: ".$rawcorrelation.". ";
$correlation = round($rawcorrelation, 4);
return $correlation;
}
function combine_key($int1, $int2) {
$newkey = $int1 * 1000000000;
$newkey = $newkey + $int2;
return $newkey;
}
function extract_key2($keyint) {
$key2 = $keyint % 1000000000;
return $key2;
}
function extract_key1($keyint, $mod) {
$key0 = $keyint - $mod;
$key1 = $key0 / 1000000000;
return $key1;
}
function test_for_presence($connection, $fragset, $term, $chunk) {
$fragtable = "frag250";
if ($fragset == "ch1000") {
$fragtable = "frag1000";
}
$fragresult = mysqli_query($connection, "SELECT ctext FROM $fragtable WHERE id=$chunk");
$fragment = mysqli_fetch_row($fragresult);
$fstring = $fragment[0];
$lc_term = strtolower($term);
$lc_string = strtolower($fstring);
$ourterm = "/\b".$lc_term."\b/";
if (preg_match($ourterm, $lc_string)) {
return 1;
}
else {
return 0;
}
}
// MAIN PROCEDURE
//####################
// run the search over the correlation matrix
// open the database
$textSite = "";
$connection = new mysqli();
require_once("functions/mysql_connection.php");
$logfile = "log/chunktermsearch.txt";
$log = fopen($logfile, "w");
if (!$log) {
echo "log OPEN FAILED.<br/>";
return;
}
fwrite($log, "open chunktermsearch: ".memory_get_usage()." at ".date("M d g:i:s")."\n");
$list = $_GET['list'];
$frags = $_GET['frags'];
$scope = $_GET['scope'];
$outf = $_GET['outf'];
$bound = $_GET['bound'];
$qs = $_GET['qs'];
fwrite($log, "list=$list, frags=$frags, scope=$scope, outf=$outf, bound=$bound, qs=$qs\n");
// filename for possible network graph will need a hash value
$hash_value = md5($list."|".$frags."|".$scope."|".$bound."|".$qs);
if($outf == "TDcsv" && file_exists("graphs/xy-".$hash_value.".csv")) {
$downloadpath = "graphs/xy-".$hash_value.".csv";
echo "<br/><br/>(Right-click the link and use <em>Save link as...</em> to get a copy of a CSV file for viewing an XY Chart in Excel or another program.)<br/><br/>
<table>
<tr><td>XY scatterplot CSV file (cached):</td><td><a href='".$downloadpath."'>Link for download.</a> Give it a new name.</td></tr>
</table><br/><br/>";
exit;
}
//begin setup
$listTable = "doc250_list";
$termlistTable = "term250_list";
$correlationTable0 = "termdoc250_cosines0";
$correlationTable1 = "termdoc250_cosines1";
$correlationTable4 = "termdoc250_cosines4";
if ($frags == "ch1000") {
$listTable = "doc1000_list";
$termlistTable = "term1000_list";
$correlationTable0 = "termdoc1000_cosines0";
$correlationTable1 = "termdoc1000_cosines1";
$correlationTable4 = "termdoc1000_cosines4";
}
// put the selected term ids in a memory array and terms in a WHERE IN string unless user chose "ALL"
$selected = array(); // array is used when $qs not "ALL" to detect doc1 and doc2 cases
$chunkindex = array();
$chidx = 0;
$selectedchunks = "";
if ($qs == "ALL") {
unset($selected);
print "'ALL' chunks is more than the webapp can handle. Try choosing (many) individual chunks.";
return;
}
else {
$selectedchunks = str_replace("_", ",", $qs);
//$selectedchunks = "'".$selectedchunks."'";
$getselecteddocids = "SELECT id, alch FROM ".$listTable." WHERE id IN (".$selectedchunks.")";
$selectedrows = mysqli_query($connection, $getselecteddocids);
while ($nextid = mysqli_fetch_row($selectedrows)) {
$selected[] = $nextid[0];
$chunkindex[$nextid[0]] = $chidx;
$chidx++;
}
mysqli_free_result($selectedrows);
}
fwrite($log, "selected array loaded: ".memory_get_usage()."\n");
fwrite($log, "count in selected: ".count($selected)."\n");
fwrite($log, "selectedchunks: $selectedchunks\n");
fwrite($log, "get selected query: $getselecteddocids\n");
// going to try using a temporary table called results to organize the work
// create temporary table results
$removeresultstemp = "DROP TEMPORARY TABLE IF EXISTS results";
mysqli_query($connection, $removeresultstemp);
$makeresultstemp = "CREATE TEMPORARY TABLE results (
correlation TEXT,
term INT NOT NULL,
doc INT NOT NULL)";
mysqli_query($connection, $makeresultstemp);
$pairs4 = 0;
$pairs1 = 0;
$pairs0 = 0;
// load the temporary table
$getcosines4 = "INSERT INTO results (correlation, term, doc)
SELECT correlation, term, doc FROM $correlationTable4
WHERE (correlation >= $bound) AND (doc IN ($selectedchunks) )";
mysqli_query($connection, $getcosines4);
$pairs4 = mysqli_affected_rows($connection);
fwrite($log, "getcosines4 query executed: ".memory_get_usage()."\n");
fwrite($log, "cosines4 rows: $pairs4\n");
$pairs5 = mysqli_affected_rows($connection);
if ($bound <= 0.4) {
$getcosines1 = "INSERT INTO results (correlation, term, doc)
SELECT correlation, term, doc FROM $correlationTable1
WHERE (correlation >= $bound) AND (doc IN ($selectedchunks) )";
mysqli_query($connection, $getcosines1);
fwrite($log, "getcosines1 query executed: ".memory_get_usage()."\n");
$pairs1 = mysqli_affected_rows();
fwrite($log, "cosines1 rows: $pairs1\n");
}
if ($bound <= 0.1) {
$getcosines0 = "INSERT INTO results (correlation, term, doc)
SELECT correlation, term, doc FROM $correlationTable0
WHERE (correlation >= $bound) AND (doc IN ($selectedchunks) )";
mysqli_query($getcosines0);
fwrite($log, "getcosines0 query executed: ".memory_get_usage()."\n");
$pairs0 = mysqli_affected_rows();
}
fwrite($log, "Made it to line 182!\n");
// load the appropriate term list into memory array for output
$getallterms = "SELECT wordform FROM ".$termlistTable;
$termliststring = "BASE\n";
$termrows = mysqli_query($connection, $getallterms);
while ($termrow = mysqli_fetch_row($termrows)) {
$termliststring = $termliststring.$termrow[0]."\n";
}
$termlist = explode("\n", $termliststring);
fwrite($log, "termlist array loaded: ".memory_get_usage()."\n");
unset($termliststring);
mysqli_free_result($termrows);
fwrite($log, "termliststring and termrows freed: ".memory_get_usage()."\n");
fwrite($log, "termlist count: ".count($termlist)."\n");
// load the chunk list so we can write out titles and files names for displaycorrs.php
$getchunksdata = "SELECT id, ctitle FROM doc250_list";
$displayscript = "javascript:openTDViewer(\"ch250\", \"";
if ($frags == "ch1000") {
$getchunksdata = "SELECT id, ctitle FROM doc1000_list";
$displayscript = "javascript:openTDViewer(\"ch1000\", \"";
}
$chunksdata = mysqli_query($connection, $getchunksdata);
$chunks = array();
$chunks[] = "BASE"; // fills that pesky $chunks[0] member
while ($outchunk = mysqli_fetch_array($chunksdata)) {
$chunks[] = $outchunk;
}
fwrite($log, "chunks name array initialized. memory used: ".memory_get_usage()."\n");
fwrite($log, "chunks array initialized. ".memory_get_usage()."\n");
echo "<br/><br/>";
$output = NULL;
$getoutput = "";
// everything is gathered in results, time to work through them
if ($outf == "ranked" || $outf == "byterms" || $outf == "bychunks") {
if ($outf == "ranked") {
$getoutput = "SELECT * FROM results ORDER BY correlation DESC";
//$output = $db->query("select * from results order by correlation desc");
}
elseif ($outf == "byterms") {
$getoutput = "SELECT * FROM results ORDER BY term ASC, doc ASC";
//$output = $db->query("select * from results order by item1 asc, item2 asc");
}
elseif ($outf == "bychunks") {
$getoutput = "SELECT * FROM results ORDER BY doc ASC, term ASC";
//$output = $db->query("select * from results order by item2 asc, item1 asc");
}
$output = mysqli_query($connection, $getoutput);
$outputcount = 0;
//fwrite($log, "output array initialized. ".memory_get_usage()."\n");
echo "<table cellpadding=5>";
while ($outrow = mysqli_fetch_row($output)) {
//
$corr = $outrow[0];
$term_id = $outrow[1];
$chunk_id = $outrow[2];
$term = $termlist[$term_id];
$chunktitle = $chunks[$chunk_id][1];
$termisthere = 1;
if ($scope == "presence"|| $scope == "presentonly") {
$termisthere = test_for_presence($connection, $frags, $term, $chunk_id);
}
if ($termisthere == 1) {
echo "<tr><td>".$chunktitle."</td><td>~</td><td>".$term."</td>";
echo "<td><a href ='".$displayscript.$chunk_id."\", \"".$term."\", \"".$corr."\")'>";
echo $corr;
echo "</a></td>";
if ($scope == "presence") {
echo "<td></td>";
}
}
else {
if ($scope == "presence") {
echo "<tr><td>".$chunktitle."</td><td>~</td><td>".$term."</td>";
echo "<td><a href ='".$displayscript.$chunk_id."\", \"".$term."\", \"".$corr."\")'>";
echo $corr;
echo "</a></td>";
echo "<td>(not present)</td>";
}
}
echo "</tr>";
$outputcount++;
}
if ($outputcount == 0) {
echo "<tr><td>No results greater than or equal to ".$bound." were found.</td></tr>";
}
echo "</table>";
mysqli_free_result($output);
}
else if ($outf == "TDcsv") {
// Make a csv file for use in Excel to make an XY chart with X as docIds and corrs as Ys
//$output2 = $db->query("select * from results order by item1 asc");
$csvoutputselect = "SELECT * FROM results ORDER BY term ASC";
$output2 = mysqli_query($connection, $csvoutputselect);
// We have to know how many chunks there are in selected. Each gets one column. Add two columns for
// the document names and for the chunk IDs.
$numchunks = count($selected);
// make as a filler to represent each row in the results table
$thisRow = array();
$notHere = array();
for ($iC = 0; $iC < $numchunks; $iC++) {
$thisRow[$iC] = "";
if ($scope == "presence") {
$notHere[$iC] = "";
}
}
$rowCount = count($thisRow);
// prepare the csv file
$newcsv = "xy-".$hash_value.".csv";
$downloadpath = "graphs/$newcsv";
$csv = fopen("graphs/$newcsv", 'w');
if ($csv == '' || $csv == 0) {
fwrite($log, "Can't open csv file.\n");
}
chmod($csv, 0666); # make sure the file is user/group writable.
// First row will have the term headers
fwrite($csv, '"","",""');
for ($iT = 0; $iT < $numchunks; $iT++) {
$chunknn = $chunks[$selected[$iT]][0];
$chunkname = preg_replace("/,/", ".", $chunknn);
fwrite($csv, ",");
fwrite($csv, $chunkname);
if ($scope == "presence") {
fwrite($csv, ",");
fwrite($csv, "like ".$chunkname);
}
}
fwrite($csv, "\n");
// Other rows will have the chunk IDs and term correlations
while ($outrow2 = mysqli_fetch_row($output2)) {
// check the bound
$corr = $outrow2[0];
// test the bound
if ($corr < $bound) {
continue;
}
for ($iD = 0; $iD < $numchunks; $iD++) {
$thisRow[$iD] = "";
$notHere[$iD] = "";
}
// collect the information
$termID = $outrow2[1];
$chunkID = $outrow2[2];
$term = $termlist[$termID];
$chunktitle = $chunks[$chunkID][1];
$chunkname = preg_replace("/,/", ".", $chunktitle);
$termIsThere = 1;
// everything is reported unless the user tests for present/not present
if ($scope == "presence" || $scope = "presentonly") {
$termIsThere = test_for_presence($connection, $frags, $term, $chunkID);
}
// put $corr into the array
$chunkkey = $chunkindex[$chunkID];
// write to file
if ($termIsThere == 1) {
$thisRow[$chunkkey] = $corr;
// now output the line to $csv
fwrite($csv, $term.",");
fwrite($csv, $chunkname.",");
fwrite($csv, $termID);
// now print the corrs to file
for ($iE = 0; $iE < $numchunks; $iE++) {
fwrite($csv, ",".$thisRow[$iE]);
if ($scope == "presence") {
// if user is testing for presence, must fill the row
fwrite($csv, ",".$notHere[$iE]);
}
}
fwrite($csv, "\n");
}
else {
// term is not there, must exclude if "presentonly"
if ($scope == "presence") {
// only print if user wants to see "not present" contexts
$notHere[$chunkkey] = $corr;
// now output the line to $csv
fwrite($csv, $term.",");
fwrite($csv, $chunkname.",");
fwrite($csv, $termID);
// now print the corrs to file
for ($iE = 0; $iE < $numchunks; $iE++) {
fwrite($csv, ",".$thisRow[$iE]);
fwrite($csv, ",".$notHere[$iE]);
}
fwrite($csv, "\n");
}
// excludes "presentonly"
}
}
fclose($csv);
// change the permissions for the new graph file
chmod("graphs/".$newcsv, 0644);
echo "<br/><br/>(Right-click the link and use <em>Save link as...</em> to get a copy of a CSV file for viewing an XY Chart in Excel or another program.)<br/><br/>
<table>
<tr><td>XY scatterplot CSV file:</td><td><a href='".$downloadpath."'>Link for download.</a> Give it a new name.</td></tr>
</table><br/><br/>";
mysqli_free_result($output2);
}
// clean up
unset($termlist);
unset($chunks);
//mysqli_free_result($output);
mysqli_close($connection);
fwrite($log, "quitting, memory now ".memory_get_usage().".\n");
fclose($log);
return;
?>