<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shian Su on Medium]]></title>
        <description><![CDATA[Stories by Shian Su on Medium]]></description>
        <link>https://medium.com/@shiansu?source=rss-a261550a18a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*X3t5yZigXtr8OaVEHc93Mg.png</url>
            <title>Stories by Shian Su on Medium</title>
            <link>https://medium.com/@shiansu?source=rss-a261550a18a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:25:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shiansu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding vectorisation in R]]></title>
            <link>https://medium.com/@shiansu/understanding-vectorisation-in-r-7ee7ea66b889?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee7ea66b889</guid>
            <category><![CDATA[vectorization]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 06:37:28 GMT</pubDate>
            <atom:updated>2024-04-23T06:37:28.738Z</atom:updated>
            <content:encoded><![CDATA[<p>Vectorisation in R comes up often when talking about performance. Most people learning R come across the idea that you should vectorise code to make it run faster. However, the idea of vectorisation is often misunderstood and misapplied, potentially leading to reduced performance.</p><p>Vectorisation, as commonly used in the R context, simply refers to the usage of functions that are able to operate on entire vectors and return an element-wise vector result. Functions that do this are called “vectorised”. Essentially all basic mathematical operations and functions are vectorised, as are string operations. The alternative to using vectorised functions is to loop through the elements one by one and computing the result.</p><p>People are told, and can easily verify for themselves, that looping is slower than simply using the vectorised functions. This leads to a misleading belief that for-loops are slow and vectorised functions are fast. It is not that for-loops are slow, but that for-loops in R are slow. Fast vectorised functions are fast because they perform their loops in C or another lower level compiled language. Looping in a interpreted language such as R requires that the contents of the loop be interpreted each loop (ignoring JIT optimisations), this creates overhead that does not affect compiled functions in a lower level language such as C. We can see below how a for-loop compares to a vectorised function.</p><pre>&gt; fn_loop &lt;- function(x) {<br>+     res &lt;- numeric(length(x))<br>+     for (i in seq_along(x)) {<br>+         res[i] &lt;- sqrt(x[i])<br>+     }<br>+     res<br>+ }<br>&gt; <br>&gt; fn_vec &lt;- function(x) {<br>+     sqrt(x)<br>+ }<br>&gt; <br>&gt; bm &lt;- bench::mark(<br>+     fn_loop(1:1e6),<br>+     fn_vec(1:1e6)<br>+ )<br>&gt; <br>&gt; bm[1:4]<br># A tibble: 2 × 4<br>  expression            min   median `itr/sec`<br>  &lt;bch:expr&gt;       &lt;bch:tm&gt; &lt;bch:tm&gt;     &lt;dbl&gt;<br>1 fn_loop(1:1e+06)  29.46ms  31.14ms      32.3<br>2 fn_vec(1:1e+06)    1.52ms   1.83ms     549. <br></pre><p>The vectorised function is over 15x faster here!</p><h3>You can’t vectorise using apply()</h3><p>This often leads people into believing that they should avoid for-loops altogether and that eliminating for-loops leads to better performance. This can often lead to the belief that the apply() function provides superior performance because it does not require you to use a loops. Unfortunately the loops is simply used inside of the apply() function, and due to the fact that it is used to apply an R function, the looping must be done in R and therefore has all the performance issues associated with an R loop. Even worse, it causes a list to be created, which is generally a less efficient data type than a vector.</p><pre>&gt; fn_apply &lt;- function(x) {<br>+     sapply(x, sqrt)<br>+ }<br>&gt;<br>&gt; bm &lt;- bench::mark(<br>+     fn_loop(1:1e6),<br>+     fn_vec(1:1e6),<br>+     fn_apply(1:1e6),<br>+     check = FALSE<br>+ )<br>&gt;<br>&gt; bm[1:4]<br># A tibble: 3 × 4<br>  expression             min   median `itr/sec`<br>  &lt;bch:expr&gt;        &lt;bch:tm&gt; &lt;bch:tm&gt;     &lt;dbl&gt;<br>1 fn_loop(1:1e+06)   29.96ms  30.14ms     33.1 <br>2 fn_vec(1:1e+06)     1.45ms   1.83ms    434.  <br>3 fn_apply(1:1e+06) 204.24ms 267.11ms      3.74</pre><p>We can see here that using apply() is almost 10x slower than just doing a for-loop. The performance hit can be seen in all members of the apply() family of functions, and similarly in the map() family of functions in purrr .</p><p>It’s important to note here that this is a worst-case scenario for apply() type functions, where the underlying function is very fast. When the underlying function takes some time to run, the overhead is negligible and using apply() allows you to avoid any bugs resulting from indexing and store results that are complex objects.</p><h3>Conclusion</h3><p>I will conclude with some key ideas when dealing with optimisation using vectorisation.</p><ol><li>Vectorisation only leads to better performance when the vectorisation is provided by the function itself.</li><li>Sometimes for-loops are the best you can do.</li><li>Always measure to be certain.</li></ol><p>When the function itself provides the option, you should prefer to use functions in a vectorised way. You can often reorganise problems in order to take advantage of vectorisation. For example generating a large number of random numbers at once then looping through the values, rather than trying to generate a random number at each loop. There’s no real reason to avoid for-loops when it appears to be the simplest solution and no vectorised function is available.</p><p>Most importantly, whenever you are attempting to optimise performance, you must set up benchmarking to confirm that performance has increased, ideally over different input sizes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee7ea66b889" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Querying on Genomic Region Tables]]></title>
            <link>https://medium.com/@shiansu/efficient-querying-on-genomic-region-tables-55ef3f965656?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ef3f965656</guid>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 04:13:45 GMT</pubDate>
            <atom:updated>2020-04-13T11:08:43.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article presents a series of optimisations on querying genomic locations in tabular data. We have data in the following format</p><pre>sample,chr,pos,strand,modified,statistic<br>B6Cast_Prom_2_bl6,chr1,3001006,*,TRUE,1.46<br>B6Cast_Prom_2_cast,chr1,3001628,*,FALSE,-3.02<br>B6Cast_Prom_3_bl6,chr1,3003338,*,TRUE,0.02<br>B6Cast_Prom_3_bl6,chr1,3003639,*,FALSE,-3.11<br>B6Cast_Prom_1_bl6,chr1,3003720,*,FALSE,-0.15<br>B6Cast_Prom_2_cast,chr1,3003720,*,TRUE,0.62<br>...1B more rows</pre><p>and I want to query a specifis such as chr1:12000000-12010000. This is very slow because I have a billion rows, and I wish to perform this type of query on tens of thousands of different regions. So some optimisation is necessary to do this effectively.</p><h3>Reading in the Data</h3><p>It’s worth checking what reader is the fastest, simply reading it in takes a while because of the size of the data. R comes with read.csv and popular third party readers include readr::read_csv(), data.table::fread() and vroom::vroom(). I test this on a subset of my data with 1M rows.</p><pre>library(microbenchmark)</pre><pre>read_base &lt;- function(file) read.csv(file = file)<br>read_readr &lt;- function(file) readr::read_csv(file = file)<br>read_dt &lt;- function(file) data.table::fread(file = file)<br>read_vroom &lt;- function(file) vroom::vroom(file = file)</pre><pre>file &lt;- &quot;methylation_data_1M.csv&quot;</pre><pre>microbenchmark(<br>    read_base(file),<br>    read_readr(file),<br>    read_dt(file),<br>    read_vroom(file),<br>    times = 3<br>)</pre><pre>#&gt;Unit: milliseconds<br>#&gt;             expr ...      mean     median ...<br>#&gt;  read_base(file) ... 17021.030 17166.2375 ...<br>#&gt; read_readr(file) ...  2000.361  2085.3284 ...<br>#&gt;    read_dt(file) ...  1047.321   972.8298 ...<br>#&gt; read_vroom(file) ...   294.833   298.4807 ...</pre><p>So vroom::vroom() is the clear winner here.</p><h3>Naive Querying</h3><p>I want to query our data for chr==&quot;chr1&quot; AND 12000000&lt;=pos AND pos&lt;=12010000. So I can take our table and perform a naive query, however I also tried addition strategies, they are as follows:</p><ul><li><strong>Naive query</strong>, the most basic filtering directly translated from our region.</li><li><strong>Separated querying</strong>, we use a separate filter for each condition, the reasoning being that each filter cuts down the data.</li><li><strong>Chromosome first querying</strong>, we separate the chromosome and position filtering, with chromosome filtering first.</li><li><strong>Position first querying</strong>, we separate the chromosome and location filtering, with position filtering first.</li></ul><pre>library(dplyr)</pre><pre>methy_data &lt;- vroom::vroom(&quot;methylation_data_1M.csv&quot;)</pre><pre>naive_query &lt;- function() {<br>    methy_data %&gt;%<br>        filter(chr == &quot;chr1&quot; &amp; pos &gt;= 12000000 &amp; pos &lt;= 12010000)<br>}</pre><pre>fully_sep_query &lt;- function() {<br>    methy_data %&gt;%<br>        filter(chr == &quot;chr1&quot;) %&gt;%<br>        filter(pos &gt;= 12000000) %&gt;%<br>        filter(pos &lt;= 12010000)<br>}</pre><pre>chr_first_query &lt;- function() {<br>    methy_data %&gt;%<br>        filter(chr == &quot;chr1&quot;) %&gt;%<br>        filter(pos &gt;= 12000000 &amp; pos &lt;= 12010000)<br>}</pre><pre>pos_first_query &lt;- function() {<br>    methy_data %&gt;%<br>        filter(pos &gt;= 12000000 &amp; pos &lt;= 12010000) %&gt;%<br>        filter(chr == &quot;chr1&quot;)<br>}</pre><pre>pos_first_between_query &lt;- function() {<br>    methy_data %&gt;%<br>        filter(between(pos, 12000000, 12010000)) %&gt;%<br>        filter(chr == &quot;chr1&quot;)<br>}</pre><pre>microbenchmark(<br>    naive_query(),<br>    fully_sep_query(),<br>    chr_first_query(),<br>    pos_first_query(),<br>    pos_first_between_query(),<br>    times = 3<br>)</pre><pre>#&gt;Unit: milliseconds<br>#&gt;                      expr ...      mean    median ...<br>#&gt;             naive_query() ... 126.45807 121.28030 ...<br>#&gt;         fully_sep_query() ... 187.57005 184.78433 ...<br>#&gt;         chr_first_query() ... 172.06545 172.24274 ...<br>#&gt;         pos_first_query() ...  19.78268  19.24331 ...<br>#&gt; pos_first_between_query() ...  11.98263  10.90633 ...</pre><p>So my first two attempts to “improve” our query actually made it worse, each taking about 50% more time. I reason this is due to additional passes over the data, in the naive query each row is inspected and the data from the 3 relevant columns are filtered on. In the separated queries, the data is passed over once, filtered down to a smaller set, then passed over again for each subsequent filter. The cost of passing over data again outweighs the cost of the comparisons.</p><p>However I do see an improvement when filtering on position first. The reason for this is because comparing integers is much cheaper than comparing strings, additionally, the range we are interested in is quite small so I end up with very few rows to filter the chromosome on. Had my range been wider the results may have been very different, but I know my ranges are roughly a few 10s of kb in width so it seems this strategy will be the fastest. In addition, dplyr provides the between() function for range queries, which further speeds up my filtering. Comparatively I am more than 10x faster than the naive query!</p><h3>data.table Querying</h3><p>It’s impossible to talk about fast table querying in R without mentioning data.table(), so let’s see how much it improves our situation. First I take a larger subset of our data containing 10M rows instead of 1M, then I compare 3 strategies.</p><ul><li>Position-chromosome filtering, the fastest method in my original tests.</li><li>dtplyr semantics, to make use of data.table without too much change to our code.</li><li>Proper data.table syntax, dtplyr indicates they will not be as fast as native data.table code, so we can see how much of a difference there is.</li></ul><pre>library(data.table)<br>library(dtplyr)</pre><pre>methy_data &lt;- vroom::vroom(&quot;methylation_data_10M.csv&quot;)</pre><pre>methy_dt_lazy &lt;- lazy_dt(methy_data)<br>methy_dt_proper &lt;- as.data.table(methy_data)</pre><pre>pos_first_between_query &lt;- function() {<br>    methy_data %&gt;%<br>        filter(dplyr::between(pos, 12000000, 12010000)) %&gt;%<br>        filter(chr == &quot;chr1&quot;)<br>}</pre><pre>query_dtplyr &lt;- function() {<br>    methy_dt_lazy %&gt;%<br>        filter(data.table::between(pos, 12000000, 12010000)) %&gt;%<br>        filter(chr == &quot;chr1&quot;) %&gt;%<br>        as_tibble()<br>}</pre><pre>query_dt_proper &lt;- function() {<br>    methy_dt_proper[<br>        data.table::between(pos, 12000000, 12010000)<br>    ][<br>        chr == &quot;chr1&quot;<br>    ]<br>}</pre><pre>microbenchmark(<br>    pos_first_between_query(),<br>    query_dtplyr(),<br>    query_dt_proper(),<br>    times = 3<br>)</pre><pre>#&gt;Unit: milliseconds<br>#&gt;                      expr ...      mean    median ...<br>#&gt; pos_first_between_query() ... 172.20579 110.27329 ...<br>#&gt;            query_dtplyr() ...  27.24067  26.13366 ...<br>#&gt;         query_dt_proper() ...  22.10649  22.34707 ...</pre><p>Now I are more than 4–5x faster again than my fastest solution in dplyr, that’s more than 40–50x faster than our naive query! As advertised, using the native syntax of data.table is a bit faster than going through dtplyr, also data.table implements their own between() that is also faster than the dplyr version.</p><p>Finally there is the possibility to used keyed querying in data.table, the idea is that sorting particular columns and making data.table aware of it reduces querying time. However doing so in this case does not appear to improve performance.</p><pre>methy_dt_keyed &lt;- copy(methy_dt_proper)<br>setkey(methy_dt_keyed, pos, chr)</pre><pre>query_dt_keyed &lt;- function() {<br>    methy_dt_keyed[<br>        data.table::between(pos, 12000000, 12010000)<br>    ][<br>        chr == &quot;chr1&quot;<br>    ]<br>}</pre><pre>microbenchmark(<br>    query_dt_proper(),<br>    query_dt_keyed(),<br>    times = 3<br>)</pre><pre>#&gt;Unit: milliseconds<br>#&gt;              expr ...     mean   median ...<br>#&gt; query_dt_proper() ... 26.50873 25.49776 ...<br>#&gt;  query_dt_keyed() ... 30.98936 25.12049 ...</pre><h3>Moving to SQLite</h3><p>My actual data is about a billion rows, larger than can be reasonably fit into memory, in this case it’s sensible to create a SQL table to query from. Fortunately this is quite simple as SQLite has a CSV import function. Also to achieve good performance, an index is required on the chr and pos columns.</p><pre>CREATE TABLE methylation(<br>  &quot;sample&quot; TEXT,<br>  &quot;chr&quot; TEXT,<br>  &quot;pos&quot; INTEGER,<br>  &quot;strand&quot; TEXT,<br>  &quot;modified&quot; TEXT,<br>  &quot;statistic&quot; REAL,<br>  &quot;read_name&quot; TEXT<br>);<br>.mode csv<br>.import methylation_data.csv methylation<br>DELETE FROM methylation WHERE rowid = 1;<br>CREATE INDEX chr_pos_idx ON methylation(chr, pos);</pre><p>I can then use dbplyr to query this database in familiar tidyverse verbs.</p><pre>library(dbplyr)<br>con &lt;- DBI::dbConnect(RSQLite::SQLite(), dbname = &quot;methylation.sqlite&quot;)<br>methy_db &lt;- tbl(con, &quot;methylation&quot;)</pre><pre>pos_first_db &lt;- function() {<br>    methy_db %&gt;%<br>        filter(dplyr::between(pos, 12000000, 12010000)) %&gt;%<br>        filter(chr == &quot;chr1&quot;)<br>}</pre><p>Now because SQL cleverly caches past results, repeated queries are processed in essentially no time, so I timed a single execution and it took 46.2 milliseconds. That’s not too much slower than a data.table sitting in memory, and with 100 times the data to look through. Very impressive!</p><p>UPDATE: I have realised that the dbplyr code above does not really perform the full data extraction for the query, but stores the query as a lazy object. This is the reason for its blistering speed. When performing the query then fully evaluating it using as.data.frame(), the query took around 1–2 seconds. Still very fast considering the amount of data being processed, and more scalable than in-memory approaches.</p><h3>Conclusion</h3><p>We see that being clever about how we filter can dramatically improve the performance of our queries, changing from a combined query to a position-then-chromosome query improved our speed by 10x. Then we see that going from dplyr to data.tables got us another 4–5x performance increase, with dtplyr achieving around 85% the speed of proper data.table calls. Finally, for extremely large datasets, SQLite provides an elegant solution with indexing that allows us to easily query our data at speeds comparable to in-memory data objects.</p><p><strong>A brief summary of our timings</strong></p><p>On 1M rows:</p><ul><li>Naive query: 121.2 ms</li><li>pos-then-chr query: 10.9ms</li></ul><p>On 10M rows:</p><ul><li>pos-then-chr query: 110.3ms</li><li>dtplyr query: 26.1ms</li><li>native data.table query: 22.3ms</li></ul><p>On 1B rows:</p><ul><li>SQLite3 via dbplyr: 1.32s</li></ul><h3>Further Reading</h3><ul><li><a href="https://kbroman.org/blog/2017/04/30/sqlite-feather-and-fst/">https://kbroman.org/blog/2017/04/30/sqlite-feather-and-fst/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ef3f965656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed of String Indexing for Matrices in R]]></title>
            <link>https://medium.com/@shiansu/spee-of-string-indexing-for-matrices-in-r-a05b66f4db92?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a05b66f4db92</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 01:03:45 GMT</pubDate>
            <atom:updated>2026-04-29T05:38:21.746Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Speed of String Indexing for Matrices in R</h3><p>R matrices can be indexed in a number of ways, using strings, factors or numbers. At the basic level, matrices should only be indexed by integers, this is the only way to figure out an actual position in the matrix. So in order to index by character or factors, R must do extra work to convert them to integers.</p><p>I encountered a scenario where I wanted to tally up entries in a data.frame to a matrix. The simplified version of my problem is that I have 3 columns</p><ul><li>Matrix row I’m referring to (feature)</li><li>Matrix column I’m referring to (sample)</li><li>Whether I need to add 1 to the cell (add)</li></ul><pre>samples &lt;- paste(&quot;sample&quot;, 1:20, sep = &quot;-&quot;)<br>features &lt;- paste(&quot;feature&quot;, 1:500000, sep = &quot;-&quot;)</pre><pre>n_queries &lt;- 1000<br>query_df &lt;- data.frame(<br>    sample = sample(samples, n_queries, replace = TRUE),<br>    feature = sample(features, n_queries, replace = TRUE),<br>    add = sample(c(TRUE, FALSE), n_queries, replace = TRUE),<br>    stringsAsFactors = FALSE<br>)</pre><p>I then have a large matrix in which I want to summarise these values</p><pre>data &lt;- matrix(<br>    0L,<br>    ncol = length(samples),<br>    nrow = length(features),<br>    dimnames = list(features, samples)<br>)</pre><p>This matrix is constructed with row names and column names corresponding to the values I have in my data.frame, so I can directly index using the character strings.</p><pre>character_index &lt;- function(data, query_df) {<br>    for (i in 1:nrow(query_df)) {<br>        data[query_df$feature[i], query_df$sample[i]] &lt;- <br>            data[query_df$feature[i], query_df$sample[i]] +<br>                query_df$add[i]<br>    }<br>}</pre><p>This is the simplest version, but it takes quite a while. What’s happening is that that R must use the strings to look up the names of the dimensions and figure out which row or column it corresponds to. So more efficient solution would be to first convert the values to factors, which are internally encoded as integers and can be used for indexing with less overhead.</p><pre>factor_index &lt;- function(data, query_df) {<br>    query_df$row_fact &lt;- factor(<br>        query_df$feature, levels = rownames(data))<br>    query_df$col_fact &lt;- factor(<br>        query_df$sample, levels = colnames(data))</pre><pre>    for (i in 1:nrow(query_df)) {<br>        data[query_df$row_fact[i], query_df$col_fact[i]] &lt;- <br>            data[query_df$row_fact[i], query_df$col_fact[i]] + <br>                query_df$add[i]<br>    }<br>}</pre><p>For me this was about much faster than using the strings to index, even with the conversion cost included. A further optimisation is to extract the columns out into their own variables, so R doesn’t have to look up the data.frame first. This has the additional benefit of cleaning up the code.</p><pre>ext_factor_ind &lt;- function(data, query_df) {<br>    row_fact &lt;- factor(query_df$feature, levels = rownames(data))<br>    col_fact &lt;- factor(query_df$sample, levels = colnames(data))<br>    add &lt;- query_df$add<br>    for (i in 1:nrow(query_df)) {<br>        data[row_fact[i], col_fact[i]] &lt;- <br>            data[row_fact[i], col_fact[i]] + add[i]<br>    }<br>}</pre><p>Then final optimisation is to pre-convert the factor values of the indices to integers, we don’t need to know the factor levels anyway for indexing into the matrix, so dropping them makes our objects more lightweight.</p><p>Let’s see how effective these strategies are through benchmarks.</p><pre>library(microbenchmark)</pre><pre>samples &lt;- paste(&quot;sample&quot;, 1:20, sep = &quot;-&quot;)<br>features &lt;- paste(&quot;feature&quot;, 1:500000, sep = &quot;-&quot;)</pre><pre>n_queries &lt;- 1000<br>query_df &lt;- data.frame(<br>    sample = sample(samples, n_queries, replace = TRUE),<br>    feature = sample(features, n_queries, replace = TRUE),<br>    add = sample(c(TRUE, FALSE), n_queries, replace = TRUE),<br>    stringsAsFactors = FALSE<br>)</pre><pre>data &lt;- matrix(<br>    0L,<br>    ncol = length(samples),<br>    nrow = length(features),<br>    dimnames = list(features, samples)<br>)</pre><pre>character_index &lt;- function(data, query_df) {<br>    for (i in 1:nrow(query_df)) {<br>        data[query_df$feature[i], query_df$sample[i]] &lt;- <br>            data[query_df$feature[i], query_df$sample[i]] +<br>                query_df$add[i]<br>    }<br>}</pre><pre>factor_index &lt;- function(data, query_df) {<br>    query_df$row_fact &lt;- factor(<br>        query_df$feature, levels = rownames(data))<br>    query_df$col_fact &lt;- factor(<br>        query_df$sample, levels = colnames(data))</pre><pre>for (i in 1:nrow(query_df)) {<br>        data[query_df$row_fact[i], query_df$col_fact[i]] &lt;- <br>            data[query_df$row_fact[i], query_df$col_fact[i]] + <br>                query_df$add[i]<br>    }<br>}</pre><pre>ext_factor_ind &lt;- function(data, query_df) {<br>    row_fact &lt;- factor(query_df$feature, levels = rownames(data))<br>    col_fact &lt;- factor(query_df$sample, levels = colnames(data))<br>    add &lt;- query_df$add<br>    for (i in 1:nrow(query_df)) {<br>        data[row_fact[i], col_fact[i]] &lt;- <br>            data[row_fact[i], col_fact[i]] + add[i]<br>    }<br>}</pre><pre>microbenchmark(<br>    character_index(data, query_df),<br>    factor_index(data, query_df),<br>    ext_factor_ind(data, query_df),<br>    ext_int_ind(data, query_df),<br>    times = 50<br>)</pre><pre>#Unit: milliseconds<br>#                            expr ...       mean    median ...<br># character_index(data, query_df) ... 8506.64918 8548.4343 ...<br>#    factor_index(data, query_df) ...  127.28733  108.8640 ...<br>#  ext_factor_ind(data, query_df) ...  125.48546  103.0244 ...<br>#     ext_int_ind(data, query_df) ...   95.22599   87.9410 ...</pre><p>We can summarise this further to look at the relative performance</p><pre>#                           expr median_time rel_perf<br>#character_index(data, query_df)      8.548s   97.14x<br>#   factor_index(data, query_df)      0.109s    1.24x<br># ext_factor_ind(data, query_df)      0.103s    1.17x<br>#    ext_int_ind(data, query_df)      0.088s    1.00x</pre><p>So the final optimised version is around 100x faster than the string indexing, and also has modest gains over the factor indexing strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a05b66f4db92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling BLAS in R (the hard way)]]></title>
            <link>https://medium.com/@shiansu/calling-blas-in-r-the-hard-way-da90e0206d99?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/da90e0206d99</guid>
            <category><![CDATA[bla]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Tue, 05 Nov 2019 02:04:54 GMT</pubDate>
            <atom:updated>2020-08-12T00:28:55.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*MdYv03paUD9lG2jemPZOQg.png" /></figure><h3>Introduction</h3><p>This article covers some details about R’s API to C and subsequently C’s API to Fortran which is used to call BLAS routines. In modern use, I think the best way to make explicit use of BLAS is to work via <a href="https://cran.r-project.org/web/packages/RcppEigen/index.html">RcppEigen</a> or <a href="https://cran.r-project.org/web/packages/RcppArmadillo/index.html">RcppArmadillo</a>, direct interface to BLAS is complex and error-prone, and likely without significant performance advantage over Eigen or Armadillo. We are doing it the hard way through C as an exploratory exercise, not as a recommended pratice.</p><h3>What is BLAS?</h3><p><a href="https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms">Basic Linear Algebra Subprograms (BLAS)</a> are a set of functions for performing matrix operations ubiquitous in scientific computation. These functions are <a href="http://www.netlib.org/blas/#_blas_routines">defined abstractly</a> and have been implemented by various groups in the form of <a href="http://math-atlas.sourceforge.net/">ATLAS</a>, <a href="https://www.openblas.net/">openBLAS</a>, <a href="https://software.intel.com/en-us/mkl-developer-reference-c-blas-and-sparse-blas-routines">MKL</a>, and more. Netlib publishes a useful <a href="http://www.netlib.org/blas/blasqr.pdf">summary of all the BLAS operations</a>.</p><h3>Why use BLAS?</h3><p>The advantage is that we call BLAS routines in our code through the canonical interface, and we can then <a href="https://www.cybaea.net/Journal/2010/06/15/Faster-R-through-better-BLAS/">link different implementations</a> to our program which will provide different performance profiles. We can go from a general public distribution, to a proprietary version optimised to our hardware, we can even swap out the implementation for one that operates on the GPU, all without changing our code. Because it’s so widely used in scientific computing, the routines are among the most highly optimised in all of computing. <a href="https://stackoverflow.com/questions/1303182/how-does-blas-get-such-extreme-performance">A discussion on stackoverflow</a> details the performance and reason behind the performance of BLAS routines.</p><h3>How do I use BLAS?</h3><p>If we are just writing regular R code, chances are we are already using BLAS. Regular operations like matrix multiplication using %*% and useful matrix functions like crossprod() are all implemented using BLAS algorithms, this means that R code can already be very efficient without having to directly interface with BLAS.</p><p>If you really want to make sure you’re using BLAS, you should look into RcppEigen or RcppArmadillo, which transform your matrix operations into efficient BLAS calls, it’s likely more efficient than manual BLAS calls. But the point of this article is to show how you would do it in base R, so we are going to call the C interface from R and the Fortran interface from C.</p><h3>An Aside about Computer Memory</h3><p>To understand the interface between languages, and half the performance equation for calling C code, we need to talk about how computer memory works.</p><p>All data on computers are effectively at some memory address along a long 1D strip of memory as something like 0|1|0|1|1|0|1|1, this corresponds with tape storage and we can imagine the data forming one long spiral from the edge of a CD to the center. Matrices are then stored as consecutive columns (in R and Fortran, many other languages use are row-based), so we have column1|column2|column3 to represent a matrix in memory.</p><p>The machine keeps track of the data using addresses, it knows variable x lives at address 0x0014AF40 for example, and when we call for x, the machine will read out what it sees in that memory address.</p><p>R takes care of memory management, it will allocate space in memory for our variables, it will free the memory when we delete our variables. It will make copies of our variables for our functions, so changes inside the functions don’t affect our variable. For example</p><pre>x &lt;- 10</pre><pre>f &lt;- function(x) {<br>  x &lt;- x + 2<br>  return(x * x)<br>}</pre><pre>f(x) # returns 144</pre><p>will not affect the value of x, because it’s operating on a copy of x. This is strictly enforced in R (with few exceptions such as in data.tables) and it is useful because if we use functions written by others, we don’t need to worry about our variables changing value after running the function.</p><h3>The C API in R</h3><p>There are two APIs from R to C, the .C() and .Call() interfaces. The differences are summarised at the bottom of <a href="http://www.mazamascience.com/WorkingWithData/?p=1067">this great article</a>, the modern advice is basically to only use .Call() if possible, it is safer and more efficient. To use C code, the easiest way is to create a package, in this package we need a src folder and to have useDynLib(pkgName) in our NAMESPACE file. Then we can write C functions to be called in R. I’m going to put all my functions in a file called lib.c, and we will end up with the following folder structure.</p><pre>.<br>├── DESCRIPTION<br>├── NAMESPACE<br>├── R<br>│   └── main.R<br>├── man<br>└── src<br>    └── lib.c</pre><p>To make use of C functions, we need to write the function in C with special data types, then write a corresponding function in R to call the C function through the .Call() interface.</p><p><strong>lib.c</strong></p><pre>#include &lt;R.h&gt;<br>#include &lt;Rinternals.h&gt;</pre><pre>SEXP add_c(SEXP x, SEXP y) {<br>  SEXP res;<br>  PROTECT(res = allocateVector(REALSXP, 1));<br>  <br>  REAL(res)[0] = asReal(x) + asReal(y);<br>  <br>  UNPROTECT(1);<br>  return(res);<br>}</pre><p><strong>main.R</strong></p><pre>add_c &lt;- function(x, y) {<br>  .Call(&quot;add_c&quot;, x, y)<br>}</pre><p>Then we can call add_c() in R and it will execute the C code to return our result. The C code looks very convoluted because it is doing a lot of memory management and manipulation. This is necessary because R shares data with C via memory addresses, this is more efficient than outputting the data from R and reading it in from C. To share data, R tells C the memory addresses at which its variables are stored, C reads the data from this memory, it writes a result to another address in memory, that it passes back to R to read from.</p><p>It’s actually quite expensive to allocate and write memory for large objects, so this scheme offers significant efficiency gains at the cost of more complicated code and extremely opaque errors when memory is mismanaged. A more detailed and concise explanation of the C interface can be found in <a href="http://adv-r.had.co.nz/C-interface.html">this article</a>, make sure to also follow the links to the source R documentation. Simon Urbanek provides a <a href="https://tolstoy.newcastle.edu.au/R/e17/devel/att-0724/R_API_cheat_sheet.pdf">useful cheatsheet</a> for the C macros.</p><h3>Calling BLAS from C</h3><p>Without including any external libraries, the way to call BLAS routines in C with the R headers is to use the Fortran interface. This is really not particularly well documented, we can find the R wrappers for Fortran in the <a href="https://github.com/wch/r-source/blob/5f7205fa1699a9e0b5bbb7a1c4ac096084fbc9c3/src/include/R_ext/BLAS.h">R source code</a>, but there are no explanations for the variables, but they match up with the canonical <a href="http://www.netlib.org/lapack/explore-html/d1/d54/group__double__blas__level3_gaeda3cbd99c8fb834a60a6412878226e1.html#gaeda3cbd99c8fb834a60a6412878226e1">BLAS interface</a> so it can be used as a reference. The way to call these routines is probably best discovered in the <a href="https://github.com/wch/r-source/blob/77ce5ba9d509a160e89658c8b3639f400969fc24/src/main/array.c#L802-L812">R source code</a>. So we can write a simple C function to multiply two matrices using BLAS via the F77_CALL() interface.</p><p><strong>blas.c</strong></p><pre>#include &lt;R.h&gt;<br>#include &lt;Rinternals.h&gt;</pre><pre>SEXP mat_mult_blas(<br>  SEXP A_, SEXP a_rows_,<br>  SEXP B_, SEXP b_cols_, SEXP k_)<br>{<br>  char * TRANSA = &quot;N&quot;;<br>  char * TRANSB = &quot;N&quot;;</pre><pre>  double * A = REAL(A_);<br>  double * B = REAL(B_);</pre><pre>  int K = asInteger(k_);<br>  int M = asInteger(a_rows_);<br>  int N = asInteger(b_cols_);</pre><pre>  int LDA = K;<br>  int LDB = N;</pre><pre>  double ALPHA = 1.0;<br>  double BETA = 0.0;</pre><pre>  SEXP result_;<br>  PROTECT(result_ = allocMatrix(REALSXP, M, N));<br>  double * result = REAL(result_);</pre><pre>  F77_CALL(dgemm)(<br>    TRANSA, TRANSB, &amp;M, &amp;N, &amp;K, &amp;ALPHA,<br>    A, &amp;LDA, B, &amp;LDB, &amp;BETA, result, &amp;N);</pre><pre>  UNPROTECT(1);<br>  return(result_);<br>}</pre><p><strong>blas.R</strong></p><pre>mat_mult_blas &lt;- function(A, B) {<br>  .Call(<br>    &quot;mat_mult_blas&quot;,<br>    A, nrow(A),<br>    B, ncol(B), ncol(A)<br>  )<br>}</pre><p>When I said simple, I meant a nightmare of keeping track of what is an R address, a C value or a C pointer, I triggered at least two dozen segmentation faults while getting this code to work.</p><p>Like from going R to C, going from C to Fortran means passing everything through as memory addresses, unlike going from R to C, this requires manually keeping track of what is an address and what is a value, thus the &amp; and * syntax littered throughout. The result of this is now a function that multiplies two matrices together.</p><p>When working with BLAS, we also need to think about a lot of other things we would not think about in regular matrix multiplication, like whether the matrices need to be transposed, the size of the leading dimension (relates to <a href="https://en.wikipedia.org/wiki/Row-_and_column-major_order">row or column order</a>) and whether to pre-multiply by a scalar.</p><h3>It’s Not Necessarily Faster Than Base R</h3><p>For basic matrix multiplication, we saw in the <a href="https://github.com/wch/r-source/blob/77ce5ba9d509a160e89658c8b3639f400969fc24/src/main/array.c#L802-L812">source code</a> that R already uses BLAS for matrix operations, so there’s really no reason that my implementation here should make a difference.</p><pre>&gt; library(microbenchmark)<br>&gt; <br>&gt; A &lt;- matrix(rnorm(50^2), nrow = 50)<br>&gt; B &lt;- matrix(rnorm(50^2), nrow = 50)<br>&gt; <br>&gt; microbenchmark(<br>+     A %*% B,<br>+     mat_mult_blas(A, B)<br>+ )<br>Unit: microseconds<br>                expr  ...     mean  median ...<br>             A %*% B  ... 17.50035 17.1635 ...<br> mat_mult_blas(A, B)  ... 20.63844 20.2045 ...</pre><p>In fact, I am just a little slower than the base R implementation as I put no effort into optimising my code. However, we can compare this to a naive implementation of matrix multiplication using for looks in R.</p><p><strong>mat_mult_R_dumb.R</strong></p><pre>mat_mult_R_dumb &lt;- function(A, B) {<br>  out &lt;- matrix(0, nrow = nrow(A), ncol = ncol(B))</pre><pre>  for (i in 1:nrow(out)) {<br>    for (j in 1:nrow(out)) {<br>      for (k in 1:ncol(A)) {<br>        out[i, j] &lt;- out[i, j] + A[i, k] * B[k, j]<br>      }<br>    }<br>  }</pre><pre> out<br>}</pre><p>Now we see just how fast BLAS is</p><pre>&gt; microbenchmark(<br>+     A %*% B,<br>+     mat_mult_blas(A, B),<br>+     mat_mult_R_dumb(A, B)<br>+ )<br>Unit: microseconds<br>                 expr  ...        mean     median ...<br>              A %*% B  ...    17.50035    17.1635 ...<br>  mat_mult_blas(A, B)  ...    20.63844    20.2045 ...<br>mat_mult_R_dumb(A, B)  ... 22897.69396 22349.3155 ...</pre><p>So BLAS is over 1000x faster than a naive matrix multiplication in R!</p><p>Where you can beat R’s basic matrix multiplication is usually if you want to perform particularly strange operations, like if we needed to have t(A) %*% t(B). In the BLAS code, we can make the following change.</p><pre>SEXP mat_mult_ta_tb(...)<br>{<br>  char * TRANSA = &quot;T&quot;;<br>  char * TRANSB = &quot;T&quot;;<br>  ...<br>}</pre><p>Then we can compare again to base R.</p><pre>&gt; microbenchmark(<br>+     t(A) %*% t(B),<br>+     mat_mult_ta_tb(A, B)<br>+ )<br>Unit: microseconds<br>                 expr ...     mean  median ...<br>        t(A) %*% t(B) ... 64.13438 62.6235 ...<br> mat_mult_ta_tb(A, B) ... 35.48643 29.7255 ...</pre><p>Here, by the nature of how R functions, the matrices are transposed before they are multiplied, which is a relatively expensive operation. BLAS takes advantage of the fact that multiplying a transpose only requires you switch indices used for the rows and columns to save on computation. This is a cherry-picked pathological example. The more likely use-cases are covered by crossprod() and tcrossprod() which are implemented using BLAS and highly efficient.</p><h3>So What?</h3><p>So all this work and we’ve gained nothing, but I think there are a few useful takeaways here.</p><ol><li>Many matrix operations in R are implemented as efficient BLAS routines.</li><li>R’s use of BLAS is more efficient than naive uses of BLAS.</li><li>BLAS can be easily a thousand times faster than naive R code.</li></ol><p>If you want peak performance, you want to transform your problem into a matrix operation defined by BLAS, then find the R function which implements that function. If some BLAS operations exist but are not implemented in base R then you’re better off writing more readable matrix operations in RcppArmadillo or RcppEigen which will generate the BLAS automatically.</p><p>BLAS is actually more powerful than I showed because I am merely using the default BLAS library packaged with R. There are implementations like MKL that are intensively optimised for Intel CPUs, and cuBLAS which dispatches certain BLAS operations on Nvidia GPUs which yield even greater performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da90e0206d99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create and Distribute an R Package]]></title>
            <link>https://medium.com/@shiansu/how-to-create-and-distribute-an-r-package-a296217435dc?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a296217435dc</guid>
            <category><![CDATA[packaging]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Tue, 09 Jul 2019 03:25:00 GMT</pubDate>
            <atom:updated>2019-08-13T00:22:50.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhGDw_mJ2yt7i9VwehDsiQ.png" /></figure><p>R is an open-source statistical programming language commonly used for data analysis. It features an easy-to-use package system that allows code to easily be shared.</p><p>The goal of the article to set up an easily installable R package on Github for others to use via remotes::install_github(). I will assume you have a working understanding of Git and Github.</p><p>The official repository for R packages is CRAN, and the alternative repository <a href="https://bioconductor.org/">Bioconductor</a> containing many methods for bioinformatics. While these are the preferred channels for sharing R packages, it’s possible to distribute packages through Github which has fewer requirements.</p><p>The main tools required are <a href="https://www.rstudio.com/">RStudio</a> along with the packages <a href="https://cran.r-project.org/web/packages/roxygen2/vignettes/roxygen2.html">roxygen2</a> and <a href="https://cran.r-project.org/package=usethis">usethis</a>. RStudio will be the program used for developing your package, roxygen2 provides support for documentation and usethis provides useful utilities for enhancing your package distribution.</p><h3>Why make a package?</h3><p>Creating a package allows you to share your analysis methods with others in a very efficient way. Having a package available for your methods dramatically improves usability and visibility of your work.</p><p>Packages are not just for complete software packages, they are also useful for sharing reproducible research. The most important facility packages provide is the inclusion of depdencies. When set up properly, a package will install with a single line and its contents can be run with minimal effort.</p><h3>How to create an R package?</h3><p>The easiest way to get started with creating a package is to use <a href="https://www.rstudio.com/">RStudio</a>. Then simply follow the instructions at <a href="https://support.rstudio.com/hc/en-us/articles/200486488-Developing-Packages-with-RStudio">Developing Packages with RStudio</a> and at the “Creating a New Package” make sure to check “Create a git repository”.</p><p>I have called my package “PackageHow” and RStudio has generated the following folder structure.</p><pre>.<br>├── DESCRIPTION<br>├── PackageHow.Rproj<br>├── NAMESPACE<br>├── R<br>│   └── hello.R<br>└── man<br>    └── hello.Rd</pre><p>hello.R and hello.Rd are placeholders you are going to want to delete. So you should end up with a clean package looking like the structure below.</p><pre>.<br>├── DESCRIPTION<br>├── PackageHow.Rproj<br>├── NAMESPACE<br>├── R<br>└── man</pre><p>For my package I want just one function that links to this article. The function is documented using roxygen2, see <a href="https://support.rstudio.com/hc/en-us/articles/200532317-Writing-Package-Documentation">RStudio’s instructions</a> on how to set this up.</p><pre>#&#39; How to create an R package<br>#&#39;<br>#&#39; Open up an article describing how to create and distribute an R <br>#&#39;   package<br>#&#39;<br>#&#39; <a href="http://twitter.com/return">@return</a> None<br>#&#39; <a href="http://twitter.com/export">@export</a><br>package_how &lt;- function() {<br>    browseURL(&quot;<a href="https://medium.com/">https://medium.com</a>&quot;)<br>}</pre><p>Save this in package_how.R under the R directory and build the documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*3DZ0FSMBKyNf7tqo2k8Kuw.png" /></figure><p>Aftewards we will have the following structure.</p><pre>.<br>├── DESCRIPTION<br>├── NAMESPACE<br>├── PackageHow.Rproj<br>├── R<br>│   └── package_how.R<br>└── man<br>    └── package_how.Rd</pre><p>As per the <a href="https://support.rstudio.com/hc/en-us/articles/200486488-Developing-Packages-with-RStudio">instructions from RStudio</a>, this package is now buildable and installable. But before it’s ready to be distributed, there is more work to be done.</p><h3>Filling in the DESCRIPTION</h3><p>Looking into the DESCRIPTION file you will find</p><pre>Package: PackageHow<br>Type: Package<br>Title: What the Package Does (Title Case)<br>Version: 0.1.0<br>Author: Who wrote it<br>Maintainer: The package maintainer &lt;<a href="/service/mailto:yourself@somewhere.net">yourself@somewhere.net</a>&gt;<br>Description: More about what it does (maybe more than one line)<br>    Use four spaces when indenting paragraphs within the Description.<br>License: What license is it under?<br>Encoding: UTF-8<br>LazyData: true</pre><p>I will edit this with the basic information.</p><pre>Package: PackageHow<br>Type: Package<br>Title: How to Make an R <br>Version: 0.1.0<br>Author: Shian Su<br>Maintainer: Shian Su &lt;<a href="/service/mailto:yourself@somewhere.net">my_email_address@</a>geemail.com&gt;<br>Description: Link to an medium article describing how to create an<br>    R package.<br>License: What license is it under?<br>Encoding: UTF-8<br>LazyData: true</pre><h3>Dependencies</h3><h4>CRAN dependencies</h4><p>Then we need to add in the dependencies. R has three notions of dependencies: Depends, Imports and Suggests. These affect how packages are installed and loaded¹.</p><ul><li><strong>Depends.</strong> These packages are loaded when your package loads. It is the “strongest” form of dependency and usually shouldn’t be used. It should be used when your package essentially complements another package. An example of when Depends is necessary is if you package mainly operates on a data structure defined by another package.</li><li><strong>Imports</strong>. This should be the most common form of dependency, the functions of these packages are made available to your package but not to the user.</li><li><strong>Suggests.</strong> This is the weakest form of dependency, it indicates packages whose functions are used in your package but only in rare instances. This allows you to provide obscure features that might be useful to some users but does not force every user to install the packages required to support the features.</li></ul><p>Under default options of remotes::install_github(), installing a package will also install the packagesDepends and Imports, while additional options can be used to also install packages from Suggests. These can be added to your DESCRIPTION file as follows.</p><pre>Package: PackageHow<br>Type: Package<br>Title: How to Make an R <br>Version: 0.1.0<br>Author: Shian Su<br>Maintainer: Shian Su &lt;<a href="/service/mailto:yourself@somewhere.net">my_email_address@</a>geemail.com&gt;<br>Description: Link to an medium article describing how to create an<br>    R package.<br>Depends:<br>    tibble<br>Imports:<br>    dplyr<br>    tidyr<br>Suggests:<br>    ggplot2<br>License: What license is it under?<br>Encoding: UTF-8<br>LazyData: true</pre><h4>Bioconductor and Github Dependencies</h4><p>By default the installer will only look for dependencies on CRAN. Two additional tricks can be applied for other dependencies, Remotes and biocViews.</p><ul><li><strong>Remotes</strong>. This allows you to depend on other github packages that are not yet on CRAN or Bioconductor. This works the same way as the other fields, list the desired packages using user/repository notation.</li><li><strong>biocViews.</strong> This tells remotes::install_github() to also look inside Bioconductor for dependencies. This works different from the other fields, it’s simply the tagging system for Bioconductor. You will list your dependencies in there regular fields while adding biocViews: Software to let remotes know that your dependencies might be found on Bioconductor.</li></ul><pre>Package: PackageHow<br>Type: Package<br>Title: How to Make an R <br>Version: 0.1.0<br>Author: Shian Su<br>Maintainer: Shian Su &lt;<a href="/service/mailto:yourself@somewhere.net">my_email_address@</a>geemail.com&gt;<br>Description: Link to an medium article describing how to create an<br>    R package.<br>Depends:<br>    tibble<br>Imports:<br>    dplyr<br>    tidyr<br>    limma<br>Suggests:<br>    ggplot2<br>Remotes:<br>    r-lib/testthat<br>biocViews:<br>    Software<br>License: What license is it under?<br>Encoding: UTF-8<br>LazyData: true</pre><p>At this point your package can be installed along with all the required dependencies using a single command.</p><h3>Finishing Touches</h3><p>The final things to do are to put in a license for your open source project and write a helpful README. The usethis package provides some quick functions to help with this, it can also help you set up unit-testing and continuous-integration but we won’t worry about that here. To set up your README and license (I’ll use MIT in this example) you run</p><pre>usethis::use_readme_md()<br>usethis::use_mit_license()</pre><p>This will have created the files README.md, LICENSE, and LICENSE.md for you as well as have modified your DESCRIPTION to say License: MIT + file LICENSE.</p><pre>.<br>├── DESCRIPTION<br>├── LICENSE<br>├── LICENSE.md<br>├── NAMESPACE<br>├── PackageHow.Rproj<br>├── R<br>│   └── package_how.R<br>├── README.md<br>└── man<br>    └── package_how.Rd</pre><p>Then we should fill in the README with useful information.</p><pre># PackageHow</pre><pre>&lt;!-- badges: start --&gt;<br>&lt;!-- badges: end --&gt;</pre><pre>This package links to an article about creating R packages.</pre><pre>## Installation</pre><pre>You can install this package with using</pre><pre>``` r<br>remotes::install_github(&quot;shians/PackageHow&quot;)<br>```</pre><pre>## Example</pre><pre>To use the function provided by this package, run the following code.</pre><pre>```r<br>library(PackageHow)<br>package_how()<br>```</pre><pre>## License</pre><pre>This package is licensed under MIT license.</pre><h3>Publishing the Package</h3><p>To publish the package via Github, you first need to commit all your work to the local git repository. You can do this within RStudio’s integrated git interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*hlBeAKQSJ_k1SzZxOrUOvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*M3aFUdHQVtK73z2pInbEag.png" /><figcaption>You can quickly add all the files by using Ctrl/Cmd + a and Space/Enter</figcaption></figure><p>Once you’ve added all your files to git and commited your first set of changes. Head over to Github.com to create a new repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*YsPPNsFBJ0py9fNegpik8g.png" /></figure><p>All you need is the name, leave everything else as is and after clicking “Create Repository” you should be given instructions on how to upload from an existing local repository. For me the commands look like this.</p><pre>git remote add origin git@github.com:Shians/PackageHow.git<br>git push -u origin master</pre><p>You can run this command inside RStudio’s terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*vyHKwihZg1Chd5LPfE5X_A.png" /><figcaption>The first two lines are taken from Github’s instructions upon creating a new blank repository</figcaption></figure><p>My package is now ready at <a href="https://github.com/shians/packagehow">https://github.com/shians/packagehow</a>, and it doesn’t look half bad! Good luck with creating your own R packages and please comment with suggestions on how to improve this article.</p><p>[1]: R documentation uses the terms “attached” and “loaded” to have specific meanings. I use “loaded” in the sense of “attached and loaded”, as the distinction is beyond the scope of this article. Attached refers to when the functions of a package are made available to the user, while loaded refers to when the functions are made available to the package specifying the dependency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a296217435dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(Opinion) Don’t ever use single read fast5]]></title>
            <link>https://medium.com/@shiansu/opinion-dont-ever-use-single-read-fast5-1d5a717a8c5a?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d5a717a8c5a</guid>
            <category><![CDATA[sequencing]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[oxford-nanopore]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Fri, 31 May 2019 12:35:07 GMT</pubDate>
            <atom:updated>2020-07-01T00:01:50.514Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my opinionated rant on the single read fast5 format, it follows from the more objective exploration of the fast5 format done in my other article:</p><p><a href="https://medium.com/@shiansu/a-look-at-the-nanopore-fast5-format-f711999e2ff6">A Look at the Nanopore fast5 Format</a></p><h3>The Problems with Single Read fast5</h3><p>Latest softwares from Oxford Nanopore Technology (ONT) will produce reads in the multifast5 format, but most datasets currently are stored in the single-read format. I urge everyone to convert their data to multifast5 as soon as possible and also for softwares to start supporting the new format.</p><p>You can convert your files using ONT’s official fast5 API at <a href="https://github.com/nanoporetech/ont_fast5_api">https://github.com/nanoporetech/ont_fast5_api</a>.</p><p>As it stands, using single-read fast5 means</p><ul><li>Putting enormous strain on your filesystem</li><li>Crippling the access times of tools trying to use the data</li><li>Using up more space than is necessary for your data</li></ul><h3>Blowing Up Your Filesystem</h3><p>The MinION can potential produce <a href="https://bioinformatics.stackexchange.com/a/298">10 million reads in a run</a>, this means 10 million files. Filesystems are generally not prepared to deal with these kinds of situations, it breaks all sorts of things in devastating ways.</p><p><strong>Bash commands get really slow. </strong>Unix systems, the workhorses of computational biology, does not deal with this situation well at all. If you ever wanted to list the files or figure out the size of a folder containing many fast5 you’ll notice everything slows to a crawl. Here’s a du command to figure out the size of a folder on an HPC, Unix systems have some magical filesystem caching so running this the second time immediately returns the result, this is done on a “cold” folder.</p><pre>$ time du -h fast5_folder<br>259M fast5_folder</pre><pre>real 0m17.638s<br>user 0m0.003s<br>sys 0m0.075s</pre><p>17 seconds to figure out the size of a 259MB folder. That’s really not great, it’s essentially working things out at 15MB per second, an abysmal speed. Copying things around is similarly slow, and this has negative impacts on backup systems as well.</p><p><strong>Bash commands get really broken.</strong> The other way Bash falls over is in the command size limit, whenever you write something like du *.fastq bash expands that “glob” out to the filenames and then executes the command. There’s actually a limit to how long a command can be; this can be found using getconf ARG_MAX which for the system I’m working on is 20,971,520 which you would think is enough for anything. Well here’s the name of one of the files</p><pre>PC1235_20180622_FAH86282_MN27307_sequencing_run_brdu_seq_01_85876_read_362_ch_452_strand.fast5</pre><p>That’s 95 characters long, so 20 million characters buys me around 200,000 files. On my Mac the limit is a “tiny” 262,144 meaning I can barely fit 2500 files into each operation.</p><p><strong>Filesystems fill up.</strong> If you’re on a shared computing system, then things get real bad, because there’s a <a href="https://stackoverflow.com/questions/466521/how-many-files-can-i-put-in-a-directory">4,294,967,295 file limit</a> on ext4 systems, the latest Unix filesystem standard. 4 billion reads, at 10 million reads per MinION run, that’s potentially a limit of 400 MinION runs to be shared around in a research institute.</p><h3>Access is Crippled</h3><p>We see just having this many files is wreaks havoc all over the place, what happens when you actually need to compute on them? You get some bad performance issues such as in the <a href="https://hasindu2008.github.io/f5c/docs/hdf5-performance">findings of the f5c developers</a> where a 72 hour job spent ~69 hours loading files and ~3 hours processing files. They happen to also report the loading speed: ~14.1MB/s, on a system that could otherwise be moving files at 1.35GB/s.</p><p>I believe there are two parts to this issue: accessing a series of small files, and going through HDF5.</p><p><strong>Randomly accessing small file is slow.</strong> Accessing a bunch of small files is much slower than accessing a big block of data. For example the top-of-the-line consumer SSD <a href="https://ssd.userbenchmark.com/SpeedTest/497261/Samsung-SSD-970-PRO-1TB">Samsung 970 Pro NVMe</a> benchmarks show a sequential read speed on average of 2,267MB/s but a random 4k read speed of only 52.6MB/s, reflecting what we see from the above measurements.</p><p><strong>Opening and closing HDF5 is expensive.</strong> It’s expensive to be opening small files all over the place, significantly more expensive to be opening HDF5 files. From my <a href="https://medium.com/@shiansu/a-look-at-the-nanopore-fast5-format-f711999e2ff6">other article</a> I describe the flexible structure and clever access strategies of HDF5, this comes with overhead. There’s essentially a little HDF5 engine you have to spin up and shut down every time you access a HDF5 file, imagine opening up Microsoft Word to read a single sentence, closing it down, then opening it up again to read the next sentence. That’s what you’re doing when you try to read many HDF5.</p><p>This crippled access affects every single tool that works with single read fast5 files. Everyone is bottlenecked from the start, you can throw all the processing power you want at the program but it will not pull in enough data to process.</p><h3>File-sizes Balloon</h3><p>fast5 files are slow to work with, but that’s generally the price you pay for efficiently compressed data. So maybe these single read fast5 are saving you space? Nope, in fact they are taking up more space they need to for a few important reasons.</p><p><strong>Single-read fast5 contain duplicate information.</strong> There is a lot of information that is essentially the same within a sequencing run, this would be duplicated across every single fast5 file. For example, the version number of the fast5 file would be stored in every single fast5 file, but would be identical within a sequencing run.</p><p><strong>fast5 does not gzip efficiently.</strong> The <a href="https://zlib.net/feldspar.html">gzip algorithm</a> is more efficient when there’s groups of similar data close to each other, one of the fundamental techniques of the algorithm is to replace blocks of data with a reference to previous occurrences of the data. This means the more repetitive the data is, the more efficiently it can be compressed. Well the most space-consuming part of the fast5 is the raw squiggle signal values, and it’s separated from other signal values because they are separate files. This kind of structure does not lend itself well to the compression.</p><p><strong>HDF5 has data overhead.</strong> Metadata must be included with each HDF5 file to facilitate the features provided by HDF5, even in an empty HDF5 file this will be <a href="https://support.hdfgroup.org/HDF5/doc/Advanced/FileSpaceManagement/FileSpaceManagement.pdf">800 bytes</a>. Across 1 million reads this could be 800 MB of wasted space. It’s probably less than 5% of the total file size, but waste is waste.</p><p><strong>Many fast5 are below the filesystem block size.</strong> Filesystems have a block size that represents the minimum amount of address assigned to a file; this means that each file is at least a certain size. In a basic Unix system this should be 4k, but for large filesystems on HPC or storage systems it could be larger. On ext4 systems (default filesystem for linux distributions) it’s common to have 64k block sizes for petabyte-scale systems, on exFat over 32gb (common for portable drives) its <a href="https://support.microsoft.com/en-au/help/140365/default-cluster-size-for-ntfs-fat-and-exfat">128k</a>. This means a set of fast5 files can be different sizes depending on what filesystem it stored on. A folder of 4000 fast5 files is 129MB on desktop with 4k block size, 250MB on the HPC with 64k block size and 500MB on a flash drive with 128k block size. So even in a common situation it’s possible to use up 4 times the storage space than is required.</p><p><strong>There is insufficient compression in fast5.</strong> I don’t know the cause for this is, but the compression of fast5 file is just not particularly impressive. As a comparison, I used h5dump to dump the contents of HDF5 files into plain-text and then gzipped it. This haphazard pile of data compressed to be 109MB from the 250MB of fast5 files on the HPC, a reduction even over the 129MB on the most efficient filesystem I have access to. For a specialised data format to underperform gzipped plaintext is quite concerning. <strong>(Update 07–06–19) </strong>After getting to know the fast5 files a bit better, I am no longer concerned about the size of these files. HDF5 is optimised for random access and size is a secondary concern, so it’s not meant to be extremely space-efficient. Using h5ls -vr read_file.fast5/Raw shows the signals have around 160% space utilisation. Experimenting with HDF5’s filtering and compression options allow me to get this up to 230% space utilisation, but the impact on access speed has not been investigated.</p><h3>Transition into multifast5 now!</h3><p>Multifast5 files are much easier on the filesystem, they are more space-efficient and can be processed faster because the HDF5 files don’t need to be opened as many times.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d5a717a8c5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Look at the Nanopore fast5 Format]]></title>
            <link>https://medium.com/@shiansu/a-look-at-the-nanopore-fast5-format-f711999e2ff6?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f711999e2ff6</guid>
            <category><![CDATA[oxford-nanopore]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[sequencing]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Fri, 31 May 2019 04:55:04 GMT</pubDate>
            <atom:updated>2021-11-29T04:49:25.926Z</atom:updated>
            <content:encoded><![CDATA[<p>The fast5 format is the native container for data coming out of Oxford Nanopore Technology’s (ONT) various nanopore sequencers. It is meant to contain the raw electrical signal levels measured by the nanopores, from which various information can be extracted. This article is my exploration into what the fast5 format contains, and the implications this has on methods research.</p><p>As a part of my recently started PhD research project, I am planning to use and develop tools for the analysis of DNA methylation using Nanopore sequencing. To perform this type of analysis requires inference based on the raw “squiggle” signals that come off the nanopore sequencers, and these are stored in the hdf5-based fast5 format.</p><p>There appeared to efforts to do away with the fast5 format, as hinted to by a slide in the tweet below,</p><h3>Vielka Salazar on Twitter</h3><p>Watching the Nanopore updates webinar. No more Fast5 files, more accurate base calling &amp;amp; improved bioinformatics. Yeahh! @nanopore</p><p>and again at 1:12:50 of the <a href="https://vimeo.com/303444091">Clive Brown NCM Plenary 2018</a>.</p><p>However as basecallers still have room for improvement, and basecalled files do not have sufficient information for methylation calling, there is still a need for the raw signals. As far as I am aware, there is no public formal specification of the fast5 format, at least not to the level of clarity as the <a href="https://samtools.github.io/hts-specs/SAMv1.pdf">SAM format specification</a> or Illumina’s <a href="http://sapac.support.illumina.com/content/dam/illumina-support/documents/documentation/software_documentation/bcl2fastq/bcl2fastq2-v2-20-software-guide-15051736-03.pdf">raw bcl file documentation</a>. The closest I could discover are the yaml files contained in the <a href="https://github.com/nanoporetech/ont_h5_validator/tree/master/h5_validator/schemas">schemas</a> from the ont_fast5_validator github project from ONT.</p><p>To understand what is inside an fast5 file requires some understanding of HDF5 files, which I am also learning about for the first time at the time of writing, so please correct me on any mistakes.</p><h3>HDF5</h3><p>The HDF stands for Hierarchical Data Format, this reflects the structuring of the data in a nested format, essentially in the same form as <a href="https://en.wikipedia.org/wiki/JSON#Example">JSON</a>. The data contained inside HDF5 is nested elements, giving it enormous flexibility in the structure of data stored. It is supported by all languages commonly used in scientific programming.</p><p>The terms used by HDF5 are “Groups” , “Datasets” and “Attributes”. Groups contain Groups or Datasets whereas Datasets contain homogenous multi-dimensional arrays of data. Groups may have Attributes which provide metadata. So you end up with a folder-like structure that can either contain more folders or eventually data. Given it’s similarity to JSON, its main advantage is in the on-disk nature of the data files.</p><p>In general with JSON, you are parsing the entire object into memory and navigating through it to get to the data you want. With HDF5 you can query the object to extract only the piece of information you need, allowing you to work with data piecewise. This is what makes HDF5 so attractive for scientific programming, it has a flexible schema and handles multidimensional blocks of data extremely well.</p><p>HDF5 employs a clever chunking strategy for its multidimensional data. Gzipped data in general cannot be randomly accessed, you have to start from the start and decompress data until you end up with what you want. In the pathological case, getting the very last value requires the full dataset to be decompressed.</p><p>We see below one possible realisation of HDF5’s chunking strategy. A 9x9 grid of data can be broken into 9 3x3 chunks, each chunk is then individually gzipped. Then obtaining the last element requires only fully decompressing the final chunk. Common access patterns like single rows or columns can also be serviced efficiently without fully decompressing all the data. The chunking strategy can even be customised to better optimise for likely access patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*zycGFFbOeCd8A1OIwgKPDw.png" /><figcaption>Figure 1: Contiguous Dataset (source: HDF5Group)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*-slBSCbuoUM0bEjc0Rcvjw.png" /><figcaption>Figure 2: Chunked Dataset (source: HDF5Group)</figcaption></figure><p>This is only one piece of data inside the HDF5 file, the other pieces of data can sit undisturbed while this is happening, if you were working with JSON you’d have loaded all the other pieces of data in as well.</p><h3>fast5</h3><p>The fast5 format is a specification over a HDF5 file, imposing a specific structure over the contents of a HDF5 file. These files are used to store the output of nanopore sequencers. The main data is the “squiggles” that represent pico-amp measurements taken around thousands of times a second at the nanopores. Each read resulting from sequencing a molecule is stores as its own fast5 file. That’s the gist of it, so what is actually inside an fast5 file?</p><p>We can find out using h5ls. This is not a “pure” fast5 file as would come off a sequencer, I don’t have one of those handy.</p><pre>$ h5ls -r read.fast5<br>/                        Group<br>/Analyses                Group<br>/Analyses/Basecall_1D_000 Group<br>/Analyses/Basecall_1D_000/BaseCalled_template Group<br>/Analyses/Basecall_1D_000/BaseCalled_template/Fastq Dataset {SCALAR}<br>/Analyses/Basecall_1D_000/Summary Group<br>/Analyses/Basecall_1D_000/Summary/basecall_1d_template Group<br>/Analyses/RawGenomeCorrected_000 Group<br>/Analyses/RawGenomeCorrected_000/BaseCalled_template Group<br>/Analyses/RawGenomeCorrected_000/BaseCalled_template/Alignment Group<br>/Analyses/RawGenomeCorrected_000/BaseCalled_template/Events Dataset {470}<br>/Analyses/Segmentation_000 Group<br>/Analyses/Segmentation_000/Summary Group<br>/Analyses/Segmentation_000/Summary/segmentation Group<br>/PreviousReadInfo        Group<br>/Raw                     Group<br>/Raw/Reads               Group<br>/Raw/Reads/Read_362      Group<br>/Raw/Reads/Read_362/Signal Dataset {7127/Inf}<br>/UniqueGlobalKey         Group<br>/UniqueGlobalKey/channel_id Group<br>/UniqueGlobalKey/context_tags Group<br>/UniqueGlobalKey/tracking_id Group</pre><p>There are 3 main branches of data stored in the fast5, Analysis, Raw, and UniqueGlobalKey. Raw stores the raw signal levels, Analysis stores analysis results such as base-calls, signal correction and segmentation information.</p><p>I’m mainly interested in the raw data, so we can use h5dump -A -g &quot;/Raw&quot; to have a look at it</p><pre>$ h5dump -A -g &quot;/Raw&quot; read.fast5<br>HDF5 &quot;batch_0.fast5&quot; {<br>GROUP &quot;/Raw&quot; {<br>   GROUP &quot;Reads&quot; {<br>      GROUP &quot;Read_362&quot; {<br>         ATTRIBUTE &quot;duration&quot; {<br>            DATATYPE  H5T_STD_U32LE<br>            DATASPACE  SCALAR<br>            DATA {<br>            (0): 7127<br>            }<br>         }<br>         ATTRIBUTE &quot;median_before&quot; {<br>            DATATYPE  H5T_IEEE_F64LE<br>            DATASPACE  SCALAR<br>            DATA {<br>            (0): 242.657<br>            }<br>         }<br>         ATTRIBUTE &quot;read_id&quot; {<br>            DATATYPE  H5T_STRING {<br>               STRSIZE 38;<br>               STRPAD H5T_STR_NULLTERM;<br>               CSET H5T_CSET_ASCII;<br>               CTYPE H5T_C_S1;<br>            }<br>            DATASPACE  SCALAR<br>            DATA {<br>            (0): &quot;ef9d76d4-f5e8-41ba-89bf-e3d8d1666094&quot;<br>            }<br>         }<br>         ATTRIBUTE &quot;read_number&quot; {<br>            DATATYPE  H5T_STD_U32LE<br>            DATASPACE  SCALAR<br>            DATA {<br>            (0): 362<br>            }<br>         }<br>         ATTRIBUTE &quot;start_mux&quot; {<br>            DATATYPE  H5T_STD_U8LE<br>            DATASPACE  SCALAR<br>            DATA {<br>            (0): 3<br>            }<br>         }<br>         ATTRIBUTE &quot;start_time&quot; {<br>            DATATYPE  H5T_STD_U64LE<br>            DATASPACE  SCALAR<br>            DATA {<br>            (0): 612061<br>            }<br>         }<br>         DATASET &quot;Signal&quot; {<br>            DATATYPE  H5T_STD_I16LE<br>            DATASPACE  SIMPLE { ( 7127 ) / ( H5S_UNLIMITED ) }<br>         }<br>      }<br>   }<br>}<br>}</pre><p>So there are other pieces of imporant information stored inside “Attribute” fields for helping process the raw signals. The names of the attributes should be relatively self-explanatory.</p><p>To access these values in programs you can go through either the official <a href="https://github.com/nanoporetech/ont_fast5_api">ont_fast5_api</a> for Python or the unofficial C++ API at <a href="https://github.com/mateidavid/fast5">mateidavid/fast5</a>.</p><p>The signals are orignally measured as pA (picoamps) values and stored as 16-bit integer values. To transform back into the original pA values requires offset and scaling, I discovered the transformation in the <a href="https://github.com/nanoporetech/ont_fast5_api/blob/4d5691645ce2d5e326f6dfa7ef28bc4c3b9bc903/ont_fast5_api/fast5_file.py#L691">source code</a> of ONT’s fast5 API: pA_val = scale * (raw + offset). Where raw is the 16-bit values stored inside Raw/Read_####/Signal and scale is calculated as range/digitisation. range, digitisation and offset can be found in the Attributes of /UniqueGlobalKey/channel_id.</p><pre>h5dump -g &quot;/UniqueGlobalKey/channel_id&quot; read.fast5<br>HDF5 &quot;read.fast5&quot; {<br>GROUP &quot;/UniqueGlobalKey/channel_id&quot; {<br>   ATTRIBUTE &quot;channel_number&quot; {<br>      DATATYPE  H5T_STRING {<br>         STRSIZE 4;<br>         STRPAD H5T_STR_NULLTERM;<br>         CSET H5T_CSET_ASCII;<br>         CTYPE H5T_C_S1;<br>      }<br>      DATASPACE  SCALAR<br>      DATA {<br>      (0): &quot;381&quot;<br>      }<br>   }<br>   ATTRIBUTE &quot;digitisation&quot; {<br>      DATATYPE  H5T_IEEE_F64LE<br>      DATASPACE  SCALAR<br>      DATA {<br>      (0): 8192<br>      }<br>   }<br>   ATTRIBUTE &quot;offset&quot; {<br>      DATATYPE  H5T_IEEE_F64LE<br>      DATASPACE  SCALAR<br>      DATA {<br>      (0): 18<br>      }<br>   }<br>   ATTRIBUTE &quot;range&quot; {<br>      DATATYPE  H5T_IEEE_F64LE<br>      DATASPACE  SCALAR<br>      DATA {<br>      (0): 1534.59<br>      }<br>   }<br>   ATTRIBUTE &quot;sampling_rate&quot; {<br>      DATATYPE  H5T_IEEE_F64LE<br>      DATASPACE  SCALAR<br>      DATA {<br>      (0): 4000<br>      }<br>   }<br>}<br>}</pre><p>Without this conversion the raw signal values between two samples cannot be meaningfully compared.</p><h3>multifast5</h3><p>Multi-fast5 files, first appearing around September 2018, are the currently stable format to be used for future nanopore sequencing. It batches up thousands of fast5 files into a multifast5 file which has the same extension. Because the extension is the same, the official way to determine if you’re looking at a multifast5 is to run `h5dump -a file_version` on your file</p><pre>$ h5dump -a file_version batch_0.fast5<br>HDF5 &quot;batch_0.fast5&quot; {<br>ATTRIBUTE &quot;file_version&quot; {<br>   DATATYPE  H5T_STRING {<br>      STRSIZE H5T_VARIABLE;<br>      STRPAD H5T_STR_NULLTERM;<br>      CSET H5T_CSET_UTF8;<br>      CTYPE H5T_C_S1;<br>   }<br>   DATASPACE  SCALAR<br>   DATA {<br>   (0): &quot;2.0&quot;<br>   }<br>}<br>}</pre><p>We see that this file is version 2.0, all previous version are to be treated as single file fast5.</p><p>The new structure of these files creates a Group at the top level for each read. I’ve packed 10 reads into a multifast5 and here is the output of h5ls.</p><pre>$ h5ls batch_0.fast5<br>read_1 Group<br>read_2 Group<br>read_3 Group<br>read_4 Group<br>read_5 Group<br>read_6 Group<br>read_7 Group<br>read_8 Group<br>read_9 Group<br>read_10 Group</pre><p>If I dig deeper into each of these groups they will have the exact same structure inside as the single read shown above</p><pre>$ h5ls -r batch_0.fast5<br>/ Group<br>/read_1 Group<br>/read_1/Analyses Group<br>/read_1/Analyses/Basecall_1D_000 Group<br>/read_1/Analyses/Basecall_1D_000/BaseCalled_template Group<br>/read_1/Analyses/Basecall_1D_000/BaseCalled_template/Fastq Dataset {SCALAR}<br>/read_1/Analyses/Basecall_1D_000/Summary Group<br>/read_1/Analyses/Basecall_1D_000/Summary/basecall_1d_template Group<br>/read_1/Analyses/RawGenomeCorrected_000 Group<br>/read_1/Analyses/RawGenomeCorrected_000/BaseCalled_template Group<br>/read_1/Analyses/RawGenomeCorrected_000/BaseCalled_template/Alignment Group<br>/read_1/Analyses/RawGenomeCorrected_000/BaseCalled_template/Events Dataset {581}<br>/read_1/Analyses/Segmentation_000 Group<br>/read_1/Analyses/Segmentation_000/Summary Group<br>/read_1/Analyses/Segmentation_000/Summary/segmentation Group<br>/read_1/PreviousReadInfo Group<br>/read_1/Raw Group<br>/read_1/Raw/Signal Dataset {12065/Inf}<br>/read_1/channel_id Group<br>/read_1/context_tags Group<br>/read_1/tracking_id Group<br>/read_2 Group<br>/read_2/Analyses Group<br>/read_2/Analyses/Basecall_1D_000 Group<br>/read_2/Analyses/Basecall_1D_000/BaseCalled_template Group<br>/read_2/Analyses/Basecall_1D_000/BaseCalled_template/Fastq Dataset {SCALAR}<br>/read_2/Analyses/Basecall_1D_000/Summary Group<br>/read_2/Analyses/Basecall_1D_000/Summary/basecall_1d_template Group<br>/read_2/Analyses/RawGenomeCorrected_000 Group<br>/read_2/Analyses/RawGenomeCorrected_000/BaseCalled_template Group<br>/read_2/Analyses/RawGenomeCorrected_000/BaseCalled_template/Alignment Group<br>/read_2/Analyses/RawGenomeCorrected_000/BaseCalled_template/Events Dataset {282}<br>/read_2/Analyses/Segmentation_000 Group<br>/read_2/Analyses/Segmentation_000/Summary Group<br>/read_2/Analyses/Segmentation_000/Summary/segmentation Group<br>/read_2/PreviousReadInfo Group<br>/read_2/Raw Group<br>/read_2/Raw/Signal Dataset {4304/Inf}<br>/read_2/channel_id Group<br>/read_2/context_tags Group<br>/read_2/tracking_id Group<br>...more</pre><p>This format uses contains the same information but uses less disk space, and is expected to be compatible with future nanopore tools.</p><p>EDIT (29 Nov 2021): a more comprehensive, technical and up-to-date description of multi-fast5 files can be found <a href="https://hasindu2008.github.io/slow5specs/fast5_demystified.pdf">here</a>. If there are any contradictions with information here, assume the newer document is correct and please let me know.</p><h3>CRAM</h3><p>There is relatively quiet effort to <a href="https://github.com/EGA-archive/ont2cram">convert fast5 to CRAM</a> and back.</p><h3>Thomas Keane on Twitter</h3><p>@ewanbirney @Clive_G_Brown @gringene_bio @nanopore Please try out the ONT2CRAM converter here: https://t.co/52w7lAEJ09 Some stats and details in this slide deck: https://t.co/9W0Sdhdr81</p><p>CRAM is usually an alternative to SAM and BAM files which leverages reference genomes and column-based rearrangement of the data to support better compression. According to the linked slides, ~30GB of fast5 files with basecalling data included can be compressed down to ~9.7GB using the CRAM format. I’m not 100% sure but it seems like the signal data is stored inside SAM tags when using this approach.</p><h3>References</h3><ul><li><a href="https://porecamp.github.io/2016/tutorials/PoreCamp2016-02-MinIONData.pdf">Porecamp 2016: Understanding your MinION data</a></li><li>ont_fast5_api: <a href="https://github.com/nanoporetech/ont_fast5_api">https://github.com/nanoporetech/ont_fast5_api</a></li><li>ont_fast5_validator (schema): <a href="https://github.com/nanoporetech/ont_h5_validator">https://github.com/nanoporetech/ont_h5_validator</a></li><li><a href="https://github.com/mw55309/EG_MinION_2016/blob/master/02_Data_Extraction_QC.md">Edinburgh Genomics — MinION Bioinformatics</a></li><li><a href="http://simpsonlab.github.io/2017/02/27/packing_fast5/">Packing ONT Fast5 Files</a></li></ul><h3>Update Log</h3><p><strong>27-Jan-2019</strong></p><ul><li>Corrected quantization to digitisation . (Thanks @kxk302)</li></ul><p><strong>17-Jun-2019</strong></p><ul><li>Added h5dump of channel_id attributes</li></ul><p><strong>11-Jun-2019</strong></p><ul><li>Added details about fast5 to pA conversion</li></ul><p><strong>05-Jun-2019</strong></p><ul><li>Added information about CRAM</li></ul><p><strong>See my opinion on single read fast5 files at my other article</strong></p><p><a href="https://medium.com/@shiansu/opinion-dont-ever-use-single-read-fast5-1d5a717a8c5a">(Opinion) Don’t ever use single read fast5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f711999e2ff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple parallelism in R and Bash for Bioinformatics]]></title>
            <link>https://medium.com/@shiansu/simple-parallelism-in-r-and-bash-for-bioinformatics-852a55027c35?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/852a55027c35</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 01:09:42 GMT</pubDate>
            <atom:updated>2019-05-10T00:38:51.603Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Parallel R and Bash for Bioinformatics</h3><p>Parallelism is the future of performance. CPUs these days are fundamentally not getting much faster, the work that can be done by a CPU have been scraping against physical limits for a long time now. Most of the performance gains of single core performance over the last decade have been a result of advanced pipelining architectures that attempt to predict future computations and have them ready ahead of time, and the performance gain from such practices have tapered off in recent years.</p><p>In the current computing landscape, parallelism is the clear path towards greater performance. Computing hardware are gradually increasing in core counts, these days mid-range laptops can have 4 cores and 8 core desktops can be found in high-end home desktops. Even high end phones these days can have 8 cores. To not leverage these cores is not only a waste of time but also of resources. There are many tasks that can be performed in parallel which cut down the time spent waiting for results. This also generally saves power, as power usage does not scale linearly with core usage, thus allowing you to do n times the work without using n times the electricity. So parallelism should be exploited whenever it is possible.</p><p>It’s difficult to find someone who disagrees with the merits of parallel computing, the main roadblock is usually how to actually make use of it. There are two main ways to make use of multiple cores, concurrency and parallelism. Concurrency is doing multiple tasks at the same time, whereas parallelism is doing the exact same task simultaneously over multiple instances. Parallism can be considered a strict instance of concurrency. Here we will cover only parallelism, because it’s generally simpler, and many tasks are considered “embarassingly parallel” in that it is almost trivial to transform the problem into parallel tasks.</p><p>Before I begin I’d like to point out three important considerations when parallelising a task:</p><ol><li><strong>Memory usage</strong>, you can generally expect your memory usage to be multiplied by the number of tasks you run in parallel. Running out of memory will cripple the speed at which work can be done, and potentially crash the system altogether.</li><li><strong>Task size</strong>, spinning up parallel tasks is not a free operation, it is important that you only parallelise things that are worth parallelising. Each small parallel task should at least be big enough to take a few seconds to run, if not then you will need to consider batching up tasks so each process has enough work after it spins up so the cost of spinning up and destroying processes doesn’t account for the majority of your time. A good example of a task work parallelising is a fitting a model over many datasets, each fit taking a few seconds. A bad example would be adding two vectors together, where each addition is near instantenous.</li><li><strong>IO Bottleneck,</strong> for some tasks the bottleneck is not processing speed, but rather disk speed. If you are already reading data as fast as possible off disks then you are unlikely to find any performance gain in parallisation. In fact you may suffer performance penalties as your tasks request data from different regions of the disk simultaneously, requiring a hard-disk drive’s read head to skip back and forth.</li></ol><p>To achieve parallism in multiple tasks we can use two simple tools from R and Bash respectively: parallel::mclapply and parallel. Fundamentally this article is aimed at replacing some common structures with parallel variants using as little effort as possible.</p><h3>Parallelism in R</h3><p>R comes with a library for handling parallel computing, conveniently names parallel which can be loaded in with library(parallel). The simplest function to use in this package is mclapply() which should be familiar to anyone who has used lapply(). The idea is to have a list where a function is applied to each element of the list and a list is returned containing the results of each computation. I will demonstrate a few useful patterns for using this function.</p><pre># this just returns 0 or 1 with 50/50 probability but the wait makes<br># it seem like it&#39;s doing a lot of work<br>expensive_simulation &lt;- function() {<br>    Sys.sleep(3)<br>    return(round(runif(1)));<br>}</pre><pre># transforming a for loop into a mclapply<br># typical for loop (takes 12 seconds)<br>results &lt;- numeric(4)<br>for (i in 1:4) {<br>    results[i] &lt;- expensive_simulation()<br>}</pre><pre># do it parallel (takes 3 seconds)<br>library(parallel)<br>library(magrittr)<br>results &lt;- mclapply(<br>    mc.cores = 4, <br>    X = 1:4,<br>    FUN = function(x) { expensive_simulation() }<br>) %&gt;% unlist()</pre><p>Note: the %&gt;% operator (referred to as “pipe”) comes from magrittr and a %&gt;% f() is equivalent to f(a).</p><p>What happened was that we applied an anonymous function to the vector 1:4 which returned us 4 results in a list that we used unlist() to transform into a regular vector. It’s easy to see that this cuts the time taken to perform the tasks by a factor of 4, with near perfect scaling when more cores are used. We can obviously also use the value x passed into the function if we chose to, it was simply unnecessary here.</p><p>The two main elements you will need to consider is:</p><ol><li>The input list (or vector), this forms the variable portion of your tasks, because lists are very flexible, you can achieve very flexible workflows.</li><li>The function applied over the list, this forms the fixed part of your task, things that you would otherwise put in a for-loop or copy-and-paste with small changes.</li><li>The output object, because each output object is captured as an element of a list, the output can be any kind of object.</li></ol><p>In the first example we demonstrated applying a function over a vector where the elements of the vector are simply there to control the number of iterations and are not used. Obviously we can actually make use of the elements, for example if we were to process files identically</p><pre>library(parallel)</pre><pre>process_file &lt;- function(filename) {<br>    Sys.sleep(3)<br>    return(1 + 1)<br>}</pre><pre>files &lt;- c(&quot;file1.txt&quot;, &quot;file2.txt&quot;, &quot;file3.txt&quot;, &quot;file4.txt&quot;)</pre><pre>output &lt;- mclapply(<br>    mc.cores = 4,<br>    X = files,<br>    FUN = process_file<br>)</pre><p>Once again I’m using sleep to simulate some intensive task. As mentioned in the first section, if a single instance of this task is already maxing out your disk speed then you are unlikely to see any gains.</p><p>One trick that you may find useful is to set the options(&quot;mc.cores&quot; = 4L) option in your script. This allows you to omit the mc.cores = 4 argument every time you call mclapply. So you would have</p><pre>library(parallel)<br>options(&quot;mc.cores&quot; = 4L)</pre><p>then all subsequent calls to mclapply are going to use 4 cores. This helps if you already use lapply and want to switch between the two with minimal changes.</p><p>Note thatmclapply does <strong>NOT</strong> work on Windows, you will need to look into parLapply which has a more complicate setup, or other parallelism packages. Fortunately the mapping of lists in parallel is a general pattern in most parallelism packages so if you have your jobs organised into lists and functions then it’s mostly straight-foward to use other packages.</p><h3>Parallelism in Bash</h3><p>There are many bioinformatics tools that work on the command line interface, usually accessed through a terminal running the Bash Unix shell. There are programming facilities available in Bash that allow concise expressions of tasks that would otherwise be cumbersome to perform.</p><p>For example we can easily query all the gzipped files in a directory by typing ls *.gz, some programs take these “wildcards” arguments and process each listed value in turn so you can write gunzip *.gz to unzip all the files rather than typing them out one by one.</p><p>Another useful tool is the Bash piping operator | which allows the output of one command to be immediately used as the input to the next command, allowing expressions like ls *.gz | grep &quot;mouse&quot; which will take all the gzip files in the local folder and filter it down to only those containing the word “mouse”. Piping allows very powerful composition of commands, for example if I wanted to find the first 10 sequences from a zipped fastq file:</p><pre>gunzip -c file.fq.gz | sed -n &quot;2~4p&quot; | head -n 10</pre><p>gunzip -c prints the unzipped contents, sed -n &quot;2~4p&quot; prints every 4 line starting from the second line and head -n 10 prints the first 10 values. Piping together different programs essentially allows you to establish flexible pipelines composed of small steps.</p><p>The parallel tool will take arguments from the command line, and run each line in parallel. Say you have a series of files to compress, then you can write a script.sh containing</p><pre>gzip file1.fq<br>gzip file2.fq<br>gzip file3.fq<br>gzip file4.fq<br>gzip file5.fq<br>gzip file6.fq<br>...</pre><p>Then you can use cat script.sh | parallel to run all of these commands in parallel. However in situations like this, it may be better to construct the commands interactively and execute them without creating the script.</p><pre>ls *.fq | while read f; do echo gzip &quot;$f&quot;; done | parallel -P 4</pre><p>In this command we first used ls *.fq to list all the fastq files in the directory. We then use while read f to read the names of each of these files into the variable f. The syntax for a while loop in bash is</p><pre>while ...; do ...; done</pre><p>So with each filename read into f we do echo gzip &quot;$f&quot;, this prints the commands such as gzip file.f1. This can also be done using awk, and paralel has its own powerful syntax for constructing commands, but I find this form more readable and sufficiently powerful for my use cases. I would suggest initially omitting the | parallel portion to inspect the generated commands before they are dispatched, then only adding it once you’re happy with what you’re about to run.</p><p>By default parallel runs one job per processor, if you work on a shared machine it’s good practice to limit your resource usage, in which case you can use parallel -P4 to use 4 cores or any other number of CPU cores.</p><p>Further Reading</p><ul><li><a href="https://cran.r-project.org/web/views/HighPerformanceComputing.html">CRAN Parallel Computing Task View</a></li><li><a href="https://www.gnu.org/software/bash/manual/html_node/GNU-Parallel.html">GNU Parallel Introduction</a></li><li><a href="https://www.biostars.org/p/63816/">GNU Parallel for Bioinformatics</a></li><li><a href="https://zenodo.org/record/1146014#.XMZOkS1L0UE">GNU Parallel Book</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=852a55027c35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop making cat paste in R]]></title>
            <link>https://medium.com/@shiansu/stop-making-cat-paste-in-r-c09386a372e6?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09386a372e6</guid>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 05:40:56 GMT</pubDate>
            <atom:updated>2019-02-26T05:42:08.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop making cat paste in R!</h3><p><a href="https://github.com/search?l=R&amp;q=cat%28paste&amp;type=Code">Every once in a while</a> I come across the following kind of code</p><pre>cat(paste(&quot;this is x:&quot;, x))</pre><p>R has enough of a reputation problem without making people think we do bad things to cats. You only need cat on its own to achieve the same effect</p><pre>cat(&quot;this is x:&quot;, x, sep = &quot; &quot;)</pre><p>or</p><pre>cat(&quot;this is x: &quot;, x)</pre><p>But cats are disobedient and difficult to suppress. So instead you might want to use message.</p><pre>message(&quot;this is x:&quot;, x)</pre><p>This means if people don’t want to listen to your cat they can just suppress it with suppressMessages</p><pre>double &lt;- function(x) {<br>    message(&quot;Hey I&#39;m about to double &quot;, x, &quot;, you&#39;re welcome!&quot;)<br>    return(2 * x)<br>}</pre><pre>double(2)<br>suppressMessages(double(2))</pre><p>Cats don’t make good paste or messengers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09386a372e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strict Weak Ordering and the C++ STL]]></title>
            <link>https://medium.com/@shiansu/strict-weak-ordering-and-the-c-stl-f7dcfa4d4e07?source=rss-a261550a18a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7dcfa4d4e07</guid>
            <category><![CDATA[stl]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shian Su]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 11:56:01 GMT</pubDate>
            <atom:updated>2023-02-27T23:50:01.806Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>We are told in algorithms class that the majority of programming tasks can be reduced to sorting and/or searching. As such there are many very general and highly efficient algorithms dedicated to both these tasks implemented in the C++ STL. As a part of the generality of these algorithms, they can be applied to any data type as long as you define a <em>comparator</em> for them.</p><h3><strong>The Comparator</strong></h3><p>The comparator is a function for comparing two elements and determining their relationship to each other. For numbers it’s clear what x &lt; y means, for characters we may adopt alphabetical order and for words you can use <a href="https://en.wikipedia.org/wiki/Lexicographical_order">lexicographical order</a>. Once you have a <em>comparator</em> declared, you gain access to a wealth of powerful <a href="http://en.cppreference.com/w/cpp/algorithm">algorithms in the C++ STL</a> for efficient operations on a vector of some arbitrary data type. You can use it for dates, students, zoo animals or books as long as you can tell your algorithm which one should come before the other when two elements are compared.</p><p>Now there is one very immediate issue that comes to mind, what if your data has a circular relationship? For example in <em>rock-paper-scissors</em> you have scissors &gt; paper, rock &gt; scissors, paper &gt; rock. In this awkward case it’s impossible to properly sort a vector of such elements, meaning that it’s impossible to guarantee that for any member of the vector, that element is always greater than any element to its left and lesser than any element to its right. This is an <em>undefined behaviour</em> in C++, there are no rules for how this is supposed to be handled, the compiler cannot work out that your <em>comparator</em> is valid. Your program may or may not crash, and it may or may not produce mildly sensible looking results that fool you at a glance (for example putting all the scissors first, then rocks, then papers).</p><h3><strong>Strict Weak Ordering</strong></h3><p>Having a circular relationship is called non-transitivity for the &lt; operator. It’s not too hard to realise that if your relationships are circular then you won’t be getting reasonable results. In fact there is a very strict set of rules that a data type and its comparators must abide by in order to get correct results from C++ STL algorithms, that is <a href="https://en.wikipedia.org/wiki/Weak_ordering#Axiomatizations"><strong>strict weak ordering</strong></a>. In general we need only define the &lt; operator and we will get &gt; and == for free because:</p><ul><li>a &gt; b is equivalent to b &lt; a</li><li>a == b is equivalent to !(a &lt; b) &amp;&amp; !(b &lt; a)</li></ul><p>Then for strict weak ordering we must have</p><ul><li>For all x: x &lt; x is never true, everything should be equal to itself</li><li>If x &lt; y then y &lt; x cannot be true</li><li>If x &lt; y and y &lt; z then x &lt; z, the ordering should be transitive</li><li>If x == y and y == z then x == z, equality should be transitive</li></ul><h3>Example of Failure</h3><p>It’s difficult to imagine how one might violate the first condition and second of strict weak ordering accidentally. The third condition is violated in our rock-paper scissors example and it’s reasonably easy to understand how such a violation prevents proper sorting. But the fourth condition is subtle and is the pitfall that caught me.</p><p>We will demonstrate the problem using intervals, each interval has two properties start and end. We say that:</p><p>interval1 &lt; interval2 if interval1.end &lt; interval2.start</p><p>That is to say that for two disjoint intervals, the “lesser” one ends before the “greater” one starts. For example we have[1, 10] &lt; [14, 25] and [14, 25] &gt; [10, 13]. This on the surface appears to give us a really nice property, that two intervals are considered equal if they are overlapping. For example [10, 15] == [14, 25]. One of the most common operations on intervals is to find all overlapping intervals, one might think “Great! Once I’ve sorted I can use std::equal_range to get all overlapping intervals.”</p><p>Had you violated any of the first 3 conditions, you might quickly encounter garbage results that alert you to an issue, but violating the fourth has very subtle consequences. The fourth condition has been violated by our intervals because</p><p>[1, 5] == [2, 10] and [4, 10] == [8, 15] but [1, 5] != [8, 15]</p><p>This means that the results of the STL operations will be undefined, in particular let’s say we had a set of intervals ordered as follows:</p><p>[[4, 10], [1, 5], [8, 15], [20, 30]]</p><p>This is a correct ordering based on our rules, if you do the pairwise comparisons between any two elements you can see they are in fact in a permissible order.</p><p>So we technically have a sorted array, which means we should be able to leverage fast algorithms that require sorted arrays, primarily binary search. With our definition of inequality, we have the convenient fact that equality holds when two intervals overlap, so it is tempting to think that we could use binary search to quickly find overlapping intervals.</p><p>Consider the interval [6, 7], we start in the middle and check [1, 5], we find that [6, 7] &gt; [1, 5] and so we move onto the right side of the array to continue our search, and clearly neither [8, 15] nor [20, 30] overlaps our interval. But actually [4, 10] overlaps [6, 7] and was never considered due to the nature of binary search. THIS is the danger we face when we do not provide a comparator that satisfies strict weak ordering.</p><p>It is a most insidious bug, because many results may appear correct, it was only by a very specific arrangement that I was able to produce an incorrect result. Such a problem would be difficult to discover and subsequently debug; we are generally interested in fast algorithms when dealing with large data, where it’s infeasible to check by hand the full data set. But the act of creating a smaller test set changes the path taken by the algorithm and can suddenly yield the correct result.</p><h3>Conclusion</h3><p>The take-away is to always pay attention to requirements <a href="https://en.cppreference.com/w/cpp/named_req/Compare">if they exist</a> and in general be mindful of how you apply STL algorithms such you do not find yourself in the land of <em>undefined behaviour</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7dcfa4d4e07" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>