Update: Do not run the in-memory demo below. Unfortunately, each worker makes a copy. Another possibility, on Linux platforms, is taking the prior demonstration and opening the Kyoto DB file in /dev/shm. Follow-up: From testing, storing in /dev/shm is not necessary. The Linux OS typically caches the entire file into memory, if available. Subsequent scans pull from the file system cache. For extra performance, see the parallel chunking demonstration on the same page.
# open the database
if (! $db->open('/dev/shm/db.kch#msiz=128m', $db->OREADER)) {
die "open error (db): ", $db->error;
}
Yes, of course ++ when data fits in-memory. The following constructs an in-memory DB. Combine the script in Part Three with Part Four or Part Five.
# https://www.perlmonks.org/?node_id=11110379
# usage: perl search_in_memory.pl > Outfile.txt
use strict;
use warnings;
use KyotoCabinet;
use MCE;
###########################################################
# Part Three
###########################################################
# construct the database object
my $db = KyotoCabinet::DB->new();
# open the database - in memory (i.e. *)
if (! $db->open('*#msiz=128m', $db->OREADER | $db->OWRITER | $db->OCRE
+ATE)) {
die "open error (db): ", $db->error;
}
open my $fh, '<', 'NR.fasta' or die "open error: $!\n";
my $nrid = '';
my $seq = '';
while ( <$fh> ) {
chomp; $_ =~ s/\r$//g;
if ( /^>/ ) {
$db->set($nrid, $seq) if $seq;
$nrid = ( split /\s/, $_, 2 )[0];
$seq = '';
}
else {
$seq .= $_;
}
}
$db->set($nrid, $seq) if $seq;
close $fh;
###########################################################
# Part Five
###########################################################
my $cur;
my $mce = MCE->new(
max_workers => MCE::Util::get_ncpu(),
chunk_size => 1,
init_relay => 1,
user_begin => sub {
$cur = $db->cursor;
},
user_end => sub {
$cur->disable;
},
user_func => sub {
my $pep = $_; chomp $pep;
my $ids = '';
$cur->jump; # first record
while ( my ($key, $val) = $cur->get(1) ) {
$ids .= ",$key" if index($val, $pep) >= 0;
}
# output serially, one worker at a time
MCE::relay {
print "$pep\t", substr($ids, 1), "\n" if $ids;
};
}
);
$mce->process('peptides.txt');
$mce->shutdown;
$db->close;
Regards, Mario
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.