Skip to content
Commits on Source (4)
FROM alpine:latest as builder
FROM debian:stable-slim as builder
RUN apk add --no-cache gcc g++ cmake musl-dev vim ninja
RUN apt-get update && apt-get install -y \
build-essential cmake xxd ninja-build \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /opt/hh-suite
ADD . .
......@@ -9,9 +11,12 @@ WORKDIR /opt/hh-suite/build
RUN cmake -G Ninja -DHAVE_SSE2=1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/hh-suite ..
RUN ninja && ninja install
FROM alpine:latest
FROM debian:stable-slim
MAINTAINER Milot Mirdita <milot@mirdita.de>
RUN apk add --no-cache libstdc++ libgomp
RUN apt-get update && apt-get install -y \
libstdc++6 libgomp1 \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /usr/local/hh-suite /usr/local/hh-suite
......@@ -19,3 +24,4 @@ ENV HHLIB=/usr/local/hh-suite
ENV PATH="/usr/local/hh-suite/bin:/usr/local/hh-suite/scripts:${PATH}"
CMD ["hhblits"]
hhsuite (3.1.0-1) UNRELEASED; urgency=medium
hhsuite (3.2.0-1) unstable; urgency=medium
[ Michael R. Crusoe ]
* Team upload.
......@@ -16,7 +16,7 @@ hhsuite (3.1.0-1) UNRELEASED; urgency=medium
[ Andrius Merkys ]
* Revoking executable permission from Perl modules.
-- Andrius Merkys <andrius.merkys@gmail.com> Sun, 10 Mar 2019 05:55:13 -0400
-- Michael R. Crusoe <michael.crusoe@gmail.com> Tue, 23 Jul 2019 12:06:51 +0200
hhsuite (3.0~beta3+dfsg-3) unstable; urgency=high
......
......@@ -22,7 +22,7 @@ Depends: ${shlibs:Depends},
${perl:Depends},
ffindex (>= 0.9.9.8),
hhsuite-data (= ${source:Version}),
python
python3
Breaks: hhsuite-data (<= 2.0.16-1)
Description: sensitive protein sequence searching based on HMM-HMM alignment
HH-suite is an open-source software package for sensitive protein sequence
......
......@@ -3,8 +3,8 @@ Upstream-Name: hhsuite
Upstream-Contact: Andreas Hauser <hauser@genzentrum.lmu.de>
Johannes Soeding <soeding@genzentrum.lmu.de>
Source: ftp://toolkit.lmb.uni-muenchen.de/HH-suite/releases/hhsuite-([0-9.]+)\.tar\.gz
File-Excluded: scripts/hhpred/
lib/ffindex/
Files-Excluded: scripts/hhpred
lib/ffindex
Files: *
Copyright: 2006, 2012 Johannes Soeding
......
......@@ -19,3 +19,25 @@ Author: Sascha Steinbiss <satta@debian.org>
#include "cs219.lib.h"
#define SWAP(tmp, arg1, arg2) tmp = arg1; arg1 = arg2; arg2 = tmp;
--- hhsuite.orig/src/cs/cstranslate_app.h
+++ hhsuite/src/cs/cstranslate_app.h
@@ -32,7 +32,6 @@
#include "a3m_compress.h"
#include "ffindexdatabase.h"
-#include "ext/fmemopen.h"
#include "context_data.lib.h"
//include "context_data.crf.h"
#include "cs219.lib.h"
--- hhsuite.orig/src/CMakeLists.txt
+++ hhsuite/src/CMakeLists.txt
@@ -118,9 +118,6 @@
hhviterbialgorithm_with_celloff
hhviterbialgorithm_and_ss
hhviterbialgorithm_with_celloff_and_ss)
-if (NOT HAVE_FMEMOPEN)
-target_link_libraries(HH_OBJECTS ext)
-endif()
add_executable(hhblits hhblits_app.cpp)
target_link_libraries(hhblits HH_OBJECTS)
Author: Michael R. Crusoe <michael.crusoe@gmail.com>
Description: Scripts are already Python3 compatible; mark them as so
--- hhsuite.orig/scripts/a3m.py
+++ hhsuite/scripts/a3m.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
class A3MFormatError(Exception):
--- hhsuite.orig/scripts/check_a3m.py
+++ hhsuite/scripts/check_a3m.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
from a3m import A3M_Container
from a3m import A3MFormatError
--- hhsuite.orig/scripts/cif2fasta.py
+++ hhsuite/scripts/cif2fasta.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
"""
Created on Mon Jun 15 21:49:32 2015
--- hhsuite.orig/scripts/ffindex.py
+++ hhsuite/scripts/ffindex.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
'''
Created on Apr 30, 2014
--- hhsuite.orig/scripts/get_a3m_size.py
+++ hhsuite/scripts/get_a3m_size.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
from a3m import A3M_Container
from a3m import A3MFormatError
--- hhsuite.orig/scripts/hh_reader.py
+++ hhsuite/scripts/hh_reader.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
"""
Parser for hhr result files created with hhblits|hhsearch|hhalign -o <hhr_file>
--- hhsuite.orig/scripts/hhmakemodel.py
+++ hhsuite/scripts/hhmakemodel.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
from hh_reader import read_result
from copy import deepcopy
--- hhsuite.orig/scripts/hhsuitedb.py
+++ hhsuite/scripts/hhsuitedb.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
"""
hhbsuite.py
--- hhsuite.orig/scripts/pdbfilter.py
+++ hhsuite/scripts/pdbfilter.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
"""
Created in Jun 2016
......@@ -4,3 +4,4 @@ add_Makefile_in_data.patch
disable-ffindex-build.patch
drop-fmemopen.h.patch
disable-AVX-SSE.patch
python3
cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR)
SET(HAVE_MPI 1 CACHE BOOL "Have MPI")
project(ffindex C)
include_directories(src)
include_directories(src/ext)
add_subdirectory(src)
## creative commons
# Attribution-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
### Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 – Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. __BY-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
k. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 – Scope.
a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. __Term.__ The term of this Public License is specified in Section 6(a).
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. __Downstream recipients.__
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. ___Other rights.___
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
### Section 3 – License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ___ShareAlike.___
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
### Section 4 – Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
### Section 6 – Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 – Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
### Section 8 – Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the [CC0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/legalcode). Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
> Creative Commons may be contacted at creativecommons.org.
# FFindex - A database wrapped around mmap
FFindex is a very simple index/database for huge amounts of small files. The
files are stored concatenated in one big data file, seperated by '\0'. A second
file contains a plain text index, giving name, offset and length of of the
small files. The lookup is currently done with a binary search on an array made
from the index file. The attatched binaries (see Usage below) and their source
code shall give an impression of how to use the functions supported by the library in C/C++ code.
## Copyright
FFindex was written by Andreas Hauser <hauser@genzentrum.lmu.de>.
Please add your name here if you distribute modified versions.
* Martin Steinegger <martin.steinegger@mpibpc.mpg.de>
* Markus Meier <markus.meier@mpibpc.mpg.de>
FFindex is provided under the Create Commons license "Attribution-ShareAlike 4.0",
which basically captures the spirit of the Gnu Public License (GPL).
See:
http://creativecommons.org/licenses/by-sa/4.0/
## Thanks
Thanks to Laszlo Kajan for creating and maintaining Debian packages
and many suggestions to improve the build and user experience.
## Installation
### Compilation
With the sourcecode ready, simply run cmake with the default settings and libraries should be auto-detected:
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=${INSTALL_BASE_DIR} ..
make
make install
**Please use a sensible value for ${INSTALL_BASE_DIR}, e.g. /usr/local or /opt/ffindex or $HOME/ffindex**
### Setting environment variables
Please note that before querying or unlinking entries a ffindex must be
sorted, although you can add to it without. So either specify -s with
ffindex_build or sorted later with ffindex_modify -s.
Setup environment:
export PATH="${INSTALL_BASE_DIR}/bin:${PATH}"
export LD_LIBRARY_PATH="${INSTALL_BASE_DIR}/lib:${LD_LIBRARY_PATH}"
On OS X set DYLD_LIBRARY_PATH instead of LD_LIBRARY_PATH.
## Usage
Build index from files in test/data and test/data2.
ffindex_build -s /tmp/test.data /tmp/test.ffindex test/data test/data2
Retrieve three entries:
ffindex_get /tmp/test.data /tmp/test.ffindex a b foo
Unlink (Remove reference from index) an entry:
ffindex_modify -u /tmp/test.ffindex b
Retrieve three entries, "b" should now be missing:
ffindex_get /tmp/test.data /tmp/test.ffindex a b foo
Convert a Fasta file to ffindex, entry names are incerental IDs starting from 1:
ffindex_from_fasta -s fasta.ffdata fasta.ffindex NC_007779.ffn
Get first entry by name:
ffindex_get fasta.ffdata fasta.ffindex 1
Get first and third entry by entry index, this a little faster:
ffindex_get fasta.ffdata fasta.ffindex -n 1 3
Count the characters including header in each entry:
ffindex_apply fasta.ffdata fasta.ffindex wc -c
Count the number of characters in each sequence, without the header:
ffindex_apply fasta.ffdata fasta.ffindex perl -ne '$x += length unless(/^>/); END{print "$x\n"}'
Parallel version for counting the characters including header in each entry:
mpirun -np 4 ffindex_apply_mpi fasta.ffdata fasta.ffindex -- wc -c
Parallel version for counting the characters including header in each entry and
saving the output to a new ffindex:
mpirun -np 4 ffindex_apply_mpi fasta.ffdata fasta.ffindex -i out-wc.ffindex -o out-wc.ffdata -- wc -c
set(CMAKE_C_FLAGS "-std=c99 ${CMAKE_C_FLAGS}")
add_library(ffindex ffindex.c ffutil.c)
target_include_directories(ffindex PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
add_subdirectory(ext)
if (NOT HAVE_FMEMOPEN)
target_link_libraries(ffindex ext)
endif ()
add_executable(ffindex_apply ffindex_apply_mpi.c)
target_link_libraries(ffindex_apply ffindex)
set_property(TARGET ffindex_apply PROPERTY COMPILE_FLAGS "-UHAVE_MPI")
find_package(MPI)
if (MPI_C_FOUND AND HAVE_MPI)
add_executable(ffindex_apply_mpi ffindex_apply_mpi.c)
target_link_libraries(ffindex_apply_mpi ffindex)
add_subdirectory(mpq)
set_property(TARGET ffindex_apply_mpi PROPERTY COMPILE_FLAGS "-DHAVE_MPI=1 ${MPI_C_COMPILE_FLAGS}")
set_property(TARGET ffindex_apply_mpi PROPERTY LINK_FLAGS "${MPI_C_LINK_FLAGS}")
target_include_directories(ffindex_apply_mpi PUBLIC ${MPI_C_INCLUDE_PATH})
target_link_libraries(ffindex_apply_mpi mpq ${MPI_C_LIBRARIES})
install(TARGETS ffindex_apply_mpi DESTINATION bin)
endif ()
add_executable(ffindex_reduce ffindex_reduce.c)
target_link_libraries(ffindex_reduce ffindex)
add_executable(ffindex_build ffindex_build.c)
target_link_libraries(ffindex_build ffindex)
add_executable(ffindex_from_fasta ffindex_from_fasta.c)
target_link_libraries(ffindex_from_fasta ffindex)
add_executable(ffindex_get ffindex_get.c)
target_link_libraries(ffindex_get ffindex)
add_executable(ffindex_modify ffindex_modify.c)
target_link_libraries(ffindex_modify ffindex)
add_executable(ffindex_unpack ffindex_unpack.c)
target_link_libraries(ffindex_unpack ffindex)
add_executable(ffindex_order ffindex_order.c)
target_link_libraries(ffindex_order ffindex)
add_executable(ffindex_from_fasta_with_split ffindex_from_fasta_with_split.c)
target_link_libraries(ffindex_from_fasta_with_split ffindex)
INSTALL(TARGETS ffindex_reduce
ffindex_apply
ffindex_build
ffindex_from_fasta
ffindex_get
ffindex_modify
ffindex_unpack
ffindex_order
ffindex_from_fasta_with_split
DESTINATION bin)
include(${CMAKE_ROOT}/Modules/CheckFunctionExists.cmake)
check_function_exists(fmemopen HAVE_FMEMOPEN)
if (NOT HAVE_FMEMOPEN)
set(EXT_SRC fmemopen.c fmemopen.h)
add_library(ext ${EXT_SRC})
endif ()
/**
* Copyright (c) 2009 Open Information Security Foundation
*
* \author Pablo Rincon Crespo <pablo.rincon.crespo@gmail.com>
* Based on FMem.c of Alexandre Flori (2008/10/17 AF)
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fmemopen.h"
/**
* \brief Seek the mem file from offset and whence
* \param handler pointer to the memfile
* \param osffset number of bytes to move from whence
* \param whence SEEK_SET, SEEK_CUR, SEEK_END
* \retval pos the position by the last operation, -1 if sizes are out of bounds
*/
static fpos_t SeekFn(void *handler, fpos_t offset, int whence) {
size_t pos = 0;
fmem_t *mem = handler;
switch (whence) {
case SEEK_SET:
if (offset > 0 && (size_t)offset <= mem->size)
return mem->pos = offset;
break;
case SEEK_CUR:
if (mem->pos + offset <= mem->size)
return mem->pos = offset;
break;
case SEEK_END:
/* must be negative */
if (mem->size + offset <= mem->size)
return pos = mem->size + offset;
break;
}
return -1;
}
/**
* \brief Read from the buffer looking for the available memory limits
* \param handler pointer to the memfile
* \param buf buffer to read from the handler
* \param number of bytes to read
* \retval count , the number of bytes read
*/
static int ReadFn(void *handler, char *buf, int size) {
size_t count = 0;
fmem_t *mem = handler;
size_t available = mem->size - mem->pos;
if (size < 0) return - 1;
if ((size_t)size > available)
size = available;
while (count < (size_t)size)
buf[count++] = mem->buffer[mem->pos++];
return count;
}
/**
* \brief Write into the buffer looking for the available memory limits
* \param handler pointer to the memfile
* \param buf buffer to write in the handler
* \param number of bytes to write
* \retval count , the number of bytes writen
*/
static int WriteFn(void *handler, const char *buf, int size) {
size_t count = 0;
fmem_t *mem = handler;
size_t available = mem->size - mem->pos;
if (size < 0) return - 1;
if ((size_t)size > available)
size = available;
while (count < (size_t)size)
mem->buffer[mem->pos++] = buf[count++];
return count;
}
/**
* \brief close the mem file handler
* \param handler pointer to the memfile
* \retval 0 on succesful
*/
static int CloseFn(void *handler) {
free (handler);
return 0;
}
/**
* \brief portable version of SCFmemopen for OS X / BSD built on top of funopen()
* \param buffer that holds the file content
* \param size of the file buffer
* \param mode mode of the file to open
* \retval pointer to the file; NULL if something is wrong
*/
FILE *fmemopen(void *buf, size_t size, const char *mode) {
fmem_t *mem = (fmem_t *) malloc(sizeof(fmem_t));
memset(mem, 0, sizeof(fmem_t));
mem->size = size, mem->buffer = buf;
return funopen(mem, ReadFn, WriteFn, SeekFn, CloseFn);
}
#ifndef __FMEMOPEN_H__
#define __FMEMOPEN_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct fmem {
size_t pos;
size_t size;
char *buffer;
};
typedef struct fmem fmem_t;
FILE *fmemopen(void *, size_t, const char *);
#endif /* __FMEMOPEN_H__ */
/*
* Ffindex
* written by Andy Hauser <hauser@genzentrum.lmu.de>.
* Please add your name here if you distribute modified versions.
*
* Ffindex is provided under the Create Commons license "Attribution-ShareAlike
* 4.0", which basically captures the spirit of the Gnu Public License (GPL).
*
* See:
* http://creativecommons.org/licenses/by-sa/4.0/
*/
#define _GNU_SOURCE 1
#define _LARGEFILE64_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include "ffindex.h"
#include "ffutil.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <libgen.h>
#include <search.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "ext/fmemopen.h" /* For OS not yet implementing this new standard function */
/* XXX Use page size? */
#define FFINDEX_BUFFER_SIZE 4096
char* ffindex_copyright_text = "Designed and implemented by Andy Hauser <hauser@genzentrum.lmu.de>.";
char* ffindex_copyright()
{
return ffindex_copyright_text;
}
/* return *out_data_file, *out_index_file, out_offset.
Setting to a given offset could be supported with a special mode.
*/
int ffindex_index_open(char *data_filename, char *index_filename, char* mode, FILE **out_data_file, FILE **out_index_file, size_t *out_offset)
{
/* open index and data file, seek to end if needed */
if(mode[0] == 'a')
{
*out_data_file = fopen(data_filename, "a");
if(*out_data_file == NULL) { perror(data_filename); return EXIT_FAILURE; }
*out_index_file = fopen(index_filename, "a+");
if(*out_index_file == NULL) { perror(index_filename); return EXIT_FAILURE; }
struct stat sb;
fstat(fileno(*out_index_file), &sb);
fseek(*out_index_file, sb.st_size, SEEK_SET);
fstat(fileno(*out_data_file), &sb);
fseek(*out_data_file, sb.st_size, SEEK_SET);
*out_offset = sb.st_size;
}
else
{
struct stat st;
if(stat(data_filename, &st) == 0) { errno = EEXIST; perror(data_filename); return EXIT_FAILURE; }
*out_data_file = fopen(data_filename, "w");
if(*out_data_file == NULL) { perror(data_filename); return EXIT_FAILURE; }
if(stat(index_filename, &st) == 0) { errno = EEXIST; perror(index_filename); return EXIT_FAILURE; }
*out_index_file = fopen(index_filename, "w+");
if(*out_index_file == NULL) { perror(index_filename); return EXIT_FAILURE; }
*out_offset = 0;
}
return EXIT_SUCCESS;
}
int ffindex_insert_ffindex(FILE* data_file, FILE* index_file, size_t* offset, char* data_to_add, ffindex_index_t* index_to_add)
{
for(size_t entry_i = 0; entry_i < index_to_add->n_entries; entry_i++)
{
ffindex_entry_t *entry = ffindex_get_entry_by_index(index_to_add, entry_i);
if(entry == NULL) { fferror_print(__FILE__, __LINE__, __func__, ""); return EXIT_FAILURE; }
int err = ffindex_insert_memory(data_file, index_file, offset, ffindex_get_data_by_entry(data_to_add, entry), entry->length - 1, entry->name); // skip \0 suffix
if(err != EXIT_SUCCESS) { fferror_print(__FILE__, __LINE__, __func__, ""); return EXIT_FAILURE;}
}
return EXIT_SUCCESS;
}
/* Insert a memory chunk (string even without \0) into ffindex */
int ffindex_insert_memory(FILE *data_file, FILE *index_file, size_t *offset, char *from_start, size_t from_length, char *name)
{
int myerrno = 0;
size_t offset_before = *offset;
size_t write_size = fwrite(from_start, sizeof(char), from_length, data_file);
*offset += write_size;
if(from_length != write_size)
fferror_print(__FILE__, __LINE__, __func__, name);
/* Seperate by '\0' and thus also make sure at least one byte is written */
char buffer[1] = {'\0'};
if(fwrite(buffer, sizeof(char), 1, data_file) != 1)
perror("ffindex_insert_memory");
*offset += 1;
if(ferror(data_file) != 0)
goto EXCEPTION_ffindex_insert_memory;
/* write index entry */
fprintf(index_file, "%s\t%zd\t%zd\n", name, offset_before, *offset - offset_before);
return myerrno;
EXCEPTION_ffindex_insert_memory:
{
fferror_print(__FILE__, __LINE__, __func__, "");
return myerrno;
}
}
/* Insert all file from a list into ffindex */
int ffindex_insert_list_file(FILE *data_file, FILE *index_file, size_t *start_offset, FILE *list_file)
{
size_t offset = *start_offset;
char path[PATH_MAX];
while(fgets(path, PATH_MAX, list_file) != NULL)
ffindex_insert_file(data_file, index_file, &offset, ffnchomp(path, strlen(path)), basename(path));
/* update return value */
*start_offset = offset;
return 0;
}
/* Insert all files from directory into ffindex */
int ffindex_insert_dir(FILE *data_file, FILE *index_file, size_t *start_offset, char *input_dir_name)
{
DIR *dir = opendir(input_dir_name);
if(dir == NULL)
{
fferror_print(__FILE__, __LINE__, __func__, input_dir_name);
return -1;
}
size_t input_dir_name_len = strlen(input_dir_name);
char path[PATH_MAX];
strncpy(path, input_dir_name, NAME_MAX);
if(input_dir_name[input_dir_name_len - 1] != '/')
{
path[input_dir_name_len] = '/';
input_dir_name_len += 1;
}
size_t offset = *start_offset;
struct dirent *entry;
while((entry = readdir(dir)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
strncpy(path + input_dir_name_len, entry->d_name, NAME_MAX);
struct stat sb;
if(stat(path, &sb) == -1)
fferror_print(__FILE__, __LINE__, __func__, path);
if(!S_ISREG(sb.st_mode))
continue;
ffindex_insert_file(data_file, index_file, &offset, path, entry->d_name);
}
closedir(dir);
/* update return value */
*start_offset = offset;
return 0;
}
/* Insert one file by path into ffindex */
int ffindex_insert_file(FILE *data_file, FILE *index_file, size_t *offset, const char *path, char *name)
{
FILE *file = fopen(path, "r");
if(file == NULL)
return errno;
int ret = ffindex_insert_filestream(data_file, index_file, offset, file, name);
fclose(file);
return ret;
}
/* Insert one file by handle into ffindex */
int ffindex_insert_filestream(FILE *data_file, FILE *index_file, size_t *offset, FILE* file, char *name)
{
int myerrno = 0;
/* copy and paste file to data file */
char buffer[FFINDEX_BUFFER_SIZE];
size_t offset_before = *offset;
size_t read_size;
while((read_size = fread(buffer, sizeof(char), sizeof(buffer), file)) > 0)
{
size_t write_size = fwrite(buffer, sizeof(char), read_size, data_file);
*offset += write_size;
if(read_size != write_size)
fferror_print(__FILE__, __LINE__, __func__, name);
}
if(ferror(file))
warn("fread");
/* Seperate by '\0' and thus also make sure at least one byte is written */
buffer[0] = '\0';
if(fwrite(buffer, sizeof(char), 1, data_file) != 1)
perror("ffindex_insert_filestream");
*offset += 1;
if(ferror(data_file) != 0)
goto EXCEPTION_ffindex_insert_file;
/* write index entry */
fprintf(index_file, "%s\t%zd\t%zd\n", name, offset_before, *offset - offset_before);
if(ferror(file) != 0)
goto EXCEPTION_ffindex_insert_file;
return myerrno;
EXCEPTION_ffindex_insert_file:
{
fferror_print(__FILE__, __LINE__, __func__, "");
return myerrno;
}
}
/* XXX not implemented yet */
int ffindex_restore(FILE *data_file, FILE *index_file, char *input_dir_name)
{
return -1;
}
char* ffindex_mmap_data(FILE *file, size_t* size)
{
struct stat sb;
fstat(fileno(file), &sb);
*size = sb.st_size;
int fd = fileno(file);
if(fd < 0)
{
fferror_print(__FILE__, __LINE__, __func__, "mmap failed");
return MAP_FAILED;
}
return (char*)mmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
}
static int ffindex_compare_entries_by_name(const void *pentry1, const void *pentry2)
{
ffindex_entry_t* entry1 = (ffindex_entry_t*)pentry1;
ffindex_entry_t* entry2 = (ffindex_entry_t*)pentry2;
return strncmp(entry1->name, entry2->name, FFINDEX_MAX_ENTRY_NAME_LENTH);
}
ffindex_entry_t* ffindex_get_entry_by_name(ffindex_index_t *index, char *name)
{
if(index != NULL) {
return ffindex_bsearch_get_entry(index, name);
}
else {
return NULL;
}
}
ffindex_entry_t* ffindex_bsearch_get_entry(ffindex_index_t *index, char *name)
{
ffindex_entry_t search;
strncpy(search.name, name, FFINDEX_MAX_ENTRY_NAME_LENTH);
return (ffindex_entry_t*)bsearch(&search, index->entries, index->n_entries, sizeof(ffindex_entry_t), ffindex_compare_entries_by_name);
}
ffindex_index_t* ffindex_index_parse(FILE *index_file, size_t num_max_entries)
{
if(num_max_entries == 0)
num_max_entries = FFINDEX_MAX_INDEX_ENTRIES_DEFAULT;
size_t nbytes = sizeof(ffindex_index_t) + (sizeof(ffindex_entry_t) * num_max_entries);
ffindex_index_t *index = (ffindex_index_t *)malloc(nbytes);
if(index == NULL)
{
fprintf(stderr, "Failed to allocate %ld bytes\n", nbytes);
fferror_print(__FILE__, __LINE__, __func__, "malloc failed");
return NULL;
}
index->num_max_entries = num_max_entries;
index->file = index_file;
index->index_data = ffindex_mmap_data(index_file, &(index->index_data_size));
if(index->index_data_size == 0)
warn("Problem with data file. Is the file empty or is another process reading it?");
if(index->index_data == MAP_FAILED)
{
free(index);
return NULL;
}
size_t i = 0;
char* d = index->index_data;
char* end;
/* Faster than scanf per line */
for(i = 0; d < (index->index_data + index->index_data_size); i++)
{
int p;
for(p = 0; *d != '\t'; d++)
index->entries[i].name[p++] = *d;
index->entries[i].name[p] = '\0';
index->entries[i].offset = strtoull(d, &end, 10);
d = end;
index->entries[i].length = strtoull(d, &end, 10);
d = end + 1; /* +1 for newline */
}
index->n_entries = i;
if(index->n_entries == 0)
warn("index with 0 entries");
return index;
}
ffindex_entry_t* ffindex_get_entry_by_index(ffindex_index_t *index, size_t entry_index)
{
if(index != NULL && entry_index < index->n_entries)
return &index->entries[entry_index];
else
return NULL;
}
/* Using a function for this looks like overhead. But a more advanced data format,
* say a compressed one, can do it's magic here.
*/
char* ffindex_get_data_by_offset(char* data, size_t offset)
{
return data + offset;
}
char* ffindex_get_data_by_entry(char *data, ffindex_entry_t* entry)
{
return ffindex_get_data_by_offset(data, entry->offset);
}
char* ffindex_get_data_by_name(char *data, ffindex_index_t *index, char *name)
{
ffindex_entry_t* entry = ffindex_bsearch_get_entry(index, name);
if(entry == NULL)
return NULL;
return ffindex_get_data_by_entry(data, entry);
}
char* ffindex_get_data_by_index(char *data, ffindex_index_t *index, size_t entry_index)
{
ffindex_entry_t* entry = ffindex_get_entry_by_index(index, entry_index);
if(entry == NULL)
return NULL;
return ffindex_get_data_by_entry(data, entry);
}
FILE* ffindex_fopen_by_entry(char *data, ffindex_entry_t* entry)
{
char *filedata = ffindex_get_data_by_offset(data, entry->offset);
return fmemopen(filedata, entry->length, "r");
}
FILE* ffindex_fopen_by_name(char *data, ffindex_index_t *index, char *filename)
{
ffindex_entry_t* entry = ffindex_bsearch_get_entry(index, filename);
if(entry == NULL)
return NULL;
return ffindex_fopen_by_entry(data, entry);
}
void ffindex_sort_index_file(ffindex_index_t *index)
{
qsort(index->entries, index->n_entries, sizeof(ffindex_entry_t), ffindex_compare_entries_by_name);
}
int ffindex_write(ffindex_index_t* index, FILE* index_file)
{
for(size_t i = 0; i < index->n_entries; i++)
{
ffindex_entry_t ffindex_entry = index->entries[i];
if(fprintf(index_file, "%s\t%zd\t%zd\n", ffindex_entry.name, ffindex_entry.offset, ffindex_entry.length) < 0)
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
ffindex_index_t* ffindex_unlink_entries(ffindex_index_t* index, char** sorted_names_to_unlink, int n_names)
{
size_t i = index->n_entries - 1;
/* walk list of names to delete */
for(int n = n_names - 1; n >= 0; n--)
{
char* name_to_unlink = sorted_names_to_unlink[n];
/* walk index entries */
for(; i-- > 0;)
{
int cmp = strncmp(name_to_unlink, index->entries[i].name, FFINDEX_MAX_ENTRY_NAME_LENTH);
if(cmp == 0) /* found entry */
{
/* Move entries after the unlinked ones to close the gap */
size_t n_entries_to_move = index->n_entries - i - 1;
if(n_entries_to_move > 0) /* not last element of array */
memmove(index->entries + i, index->entries + i + 1, n_entries_to_move * sizeof(ffindex_entry_t));
index->n_entries--;
break;
}
else if(cmp > 0) /* not found */
break;
}
}
return index;
}
ffindex_index_t* ffindex_unlink(ffindex_index_t* index, char* name_to_unlink)
{
ffindex_entry_t* entry = ffindex_bsearch_get_entry(index, name_to_unlink);
if(entry == NULL)
{
fprintf(stderr, "Warning: could not find '%s'\n", name_to_unlink);
return index;
}
/* Move entries after the unlinked one to close the gap */
size_t n_entries_to_move = index->entries + index->n_entries - entry - 1;
if(n_entries_to_move > 0) /* not last element of array */
memmove(entry, entry + 1, n_entries_to_move * sizeof(ffindex_entry_t));
index->n_entries--;
return index;
}
void ffsort_index(const char* index_filename) {
FILE* index_fh = fopen(index_filename, "r");
size_t lines = ffcount_lines(index_filename);
ffindex_index_t* index = ffindex_index_parse(index_fh, lines);
fclose(index_fh);
if(index == NULL) {
perror("ffindex_index_parse failed");
exit(EXIT_FAILURE);
}
ffindex_sort_index_file(index);
index_fh = fopen(index_filename, "w");
if(index_fh == NULL) { perror(index_filename); }
ffindex_write(index, index_fh);
fclose(index_fh);
}
void ffmerge_splits(const char* data_filename, const char* index_filename,
int first_split_index, int last_split_index, int remove_temporary) {
FILE* data_file = fopen(data_filename, "w");
if( data_file == NULL) {
char error_message[2*FILENAME_MAX];
sprintf(error_message, "Could not open file: %s", data_filename);
perror(error_message);
exit(EXIT_FAILURE);
}
FILE* index_file = fopen(index_filename, "w");
if(index_file == NULL) {
char error_message[2*FILENAME_MAX];
sprintf(error_message, "Could not open file: %s", index_filename);
perror(error_message);
exit(EXIT_FAILURE);
}
size_t offset = 0;
// Append ffindex split databases
for (int i = first_split_index; i <= last_split_index; i++) {
char data_file_name_to_add[FILENAME_MAX];
char index_file_name_to_add[FILENAME_MAX];
snprintf(data_file_name_to_add, FILENAME_MAX, "%s.%d", data_filename, i);
snprintf(index_file_name_to_add, FILENAME_MAX, "%s.%d", index_filename, i);
FILE* data_file_to_add = fopen(data_file_name_to_add, "r");
if (data_file_to_add == NULL) {
char error_message[2*FILENAME_MAX];
sprintf(error_message, "Could not open file: %s", data_file_name_to_add);
perror(error_message);
exit(EXIT_FAILURE);
}
fseek(data_file_to_add, 0L, SEEK_END);
size_t size_data_to_add = ftell(data_file_to_add);
if(size_data_to_add == 0) {
fclose(data_file_to_add);
if(remove_temporary) {
remove(data_file_name_to_add);
remove(index_file_name_to_add);
}
continue;
}
rewind(data_file_to_add);
size_t entries = ffcount_lines(index_file_name_to_add);
FILE* index_file_to_add = fopen(index_file_name_to_add, "r");
if (index_file_to_add == NULL) {
char error_message[2*FILENAME_MAX];
sprintf(error_message, "Could not open file: %s", index_file_name_to_add);
perror(error_message);
exit(EXIT_FAILURE);
}
size_t data_size;
char *data_to_add = ffindex_mmap_data(data_file_to_add, &data_size);
ffindex_index_t* index_to_add = ffindex_index_parse(index_file_to_add, entries);
for(size_t entry_i = 0; entry_i < index_to_add->n_entries; entry_i++) {
ffindex_entry_t *entry = ffindex_get_entry_by_index(index_to_add, entry_i);
ffindex_insert_memory(data_file, index_file, &offset,
ffindex_get_data_by_entry(data_to_add, entry),
entry->length - 1, entry->name);
}
fclose(data_file_to_add);
fclose(index_file_to_add);
if(remove_temporary) {
remove(data_file_name_to_add);
remove(index_file_name_to_add);
}
}
fclose(data_file);
fclose(index_file);
ffsort_index(index_filename);
}
/* vim: ts=2 sw=2 et
*/
/*
* Ffindex
* written by Andy Hauser <hauser@genzentrum.lmu.de>.
* Please add your name here if you distribute modified versions.
*
* Ffindex is provided under the Create Commons license "Attribution-ShareAlike
* 4.0", which basically captures the spirit of the Gnu Public License (GPL).
*
* See:
* http://creativecommons.org/licenses/by-sa/4.0/
*
* Ffindex is a very simple database for small files. The files are stored
* concatenated in one big data file, seperated by '\0'. A second file
* contains a plain text index, giving name, offset and length of of the small
* files.
*/
#ifndef _FFINDEX_H
#define _FFINDEX_H 1
#include <stdio.h>
#define FFINDEX_VERSION 0.980
#define FFINDEX_MAX_INDEX_ENTRIES_DEFAULT 200000000
#define FFINDEX_MAX_ENTRY_NAME_LENTH 32
typedef struct ffindex_entry {
size_t offset;
size_t length;
char name[FFINDEX_MAX_ENTRY_NAME_LENTH];
} ffindex_entry_t;
typedef struct ffindex_index {
char* filename;
FILE* file;
char* index_data;
size_t index_data_size;
size_t num_max_entries;
size_t n_entries;
ffindex_entry_t entries[]; /* This array is as big as the excess memory allocated for this struct. */
} ffindex_index_t;
/* return *out_data_file, *out_index_file, out_offset. */
int ffindex_index_open(char *data_filename, char *index_filename, char* mode, FILE **out_data_file, FILE **out_index_file, size_t *out_offset);
int ffindex_insert_filestream(FILE *data_file, FILE *index_file, size_t *offset, FILE* file, char *name);
int ffindex_insert_ffindex(FILE* data_file, FILE* index_file, size_t* offset, char* data_to_add, ffindex_index_t* index_to_add);
ffindex_entry_t* ffindex_get_entry_by_name(ffindex_index_t *index, char *name);
int ffindex_insert_memory(FILE *data_file, FILE *index_file, size_t *offset, char *from_start, size_t from_length, char *name);
int ffindex_insert_file(FILE *data_file, FILE *index_file, size_t *offset, const char *path, char *name);
int ffindex_insert_list_file(FILE *data_file, FILE *index_file, size_t *start_offset, FILE *list_file);
int ffindex_insert_dir(FILE *data_file, FILE *index_file, size_t *offset, char *input_dir_name);
FILE* ffindex_fopen_by_entry(char *data, ffindex_entry_t* entry);
FILE* ffindex_fopen_by_name(char *data, ffindex_index_t *index, char *name);
char* ffindex_mmap_data(FILE *file, size_t* size);
char* ffindex_get_data_by_offset(char* data, size_t offset);
char* ffindex_get_data_by_entry(char *data, ffindex_entry_t* entry);
char* ffindex_get_data_by_name(char *data, ffindex_index_t *index, char *name);
char* ffindex_get_data_by_index(char *data, ffindex_index_t *index, size_t entry_index);
ffindex_entry_t* ffindex_get_entry_by_index(ffindex_index_t *index, size_t entry_index);
ffindex_entry_t* ffindex_get_entry_by_name(ffindex_index_t *index, char *name);
ffindex_index_t* ffindex_index_parse(FILE *index_file, size_t num_max_entries);
ffindex_entry_t* ffindex_bsearch_get_entry(ffindex_index_t *index, char *name);
void ffindex_sort_index_file(ffindex_index_t *index);
int ffindex_write(ffindex_index_t* index, FILE* index_file);
ffindex_index_t* ffindex_unlink(ffindex_index_t* index, char *entry_name);
ffindex_index_t* ffindex_unlink_entries(ffindex_index_t* index, char** sorted_names_to_unlink, int n_names);
int ffindex_insert_filestream(FILE *data_file, FILE *index_file, size_t *offset, FILE* file, char *name);
void ffsort_index(const char* index_filename);
void ffmerge_splits(const char* data_filename, const char* index_filename,
int first_split_index, int last_split_index, int remove_temporary);
char* ffindex_copyright();
#endif
/*
* FFindex
* written by Andy Hauser <hauser@genzentrum.lmu.de>,
* and Milot Mirdita <milot@mirdita.de>
* Please add your name here if you distribute modified versions.
*
* FFindex is provided under the Create Commons license "Attribution-ShareAlike
* 4.0", which basically captures the spirit of the Gnu Public License (GPL).
*
* See:
* http://creativecommons.org/licenses/by-sa/4.0/
*
* ffindex_apply_mpi
* apply a program to each FFindex entry
*/
#define _GNU_SOURCE 1
#define _LARGEFILE64_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include <limits.h> // PIPE_BUF
#include <stdlib.h> // EXIT_*, system, malloc, free
#include <unistd.h> // pipe, fork, close, dup2, execvp, write, read, opt*
#include <stdint.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/mman.h> // munmap
#include <fcntl.h> // fcntl, F_*, O_*
#include <signal.h> // sigaction, sigemptyset
#include <getopt.h> // getopt_long
#include <spawn.h> // spawn_*
#include "ffindex.h"
#include "ffutil.h"
#ifdef HAVE_MPI
#include "mpq/mpq.h"
#endif
char read_buffer[400 * 1024 * 1024];
extern char **environ;
int
ffindex_apply_by_entry(char *data, ffindex_entry_t *entry, char *program_name, char **program_argv,
FILE *data_file_out, FILE *index_file_out, FILE *log_file_out, size_t *offset, int quiet) {
int ret = 0;
int capture_stdout = (data_file_out != NULL && index_file_out != NULL);
int pipefd_stdin[2];
int pipefd_stdout[2];
ret = pipe(pipefd_stdin);
if (ret != 0) {
fprintf(stderr, "ERROR in pipe stdin!\n");
perror(entry->name);
return errno;
}
if (capture_stdout) {
ret = pipe(pipefd_stdout);
if (ret != 0) {
fprintf(stderr, "ERROR in pipe stdout!\n");
perror(entry->name);
return errno;
}
// Flush so child doesn't copy and also flushes, leading to duplicate output
fflush(data_file_out);
fflush(index_file_out);
}
posix_spawn_file_actions_t factions;
posix_spawn_file_actions_init(&factions);
posix_spawn_file_actions_addclose(&factions, pipefd_stdin[1]);
posix_spawn_file_actions_adddup2(&factions, pipefd_stdin[0], fileno(stdin));
if (capture_stdout) {
posix_spawn_file_actions_addclose(&factions, pipefd_stdout[0]);
posix_spawn_file_actions_adddup2(&factions, pipefd_stdout[1], fileno(stdout));
}
short spawnFlags = 0;
posix_spawnattr_t attr;
posix_spawnattr_init(&attr);
#ifdef POSIX_SPAWN_USEVFORK
spawnFlags |= POSIX_SPAWN_USEVFORK;
#endif
posix_spawnattr_setflags(&attr, spawnFlags);
pid_t child_pid;
struct timeval tv;
gettimeofday(&tv, NULL);
int64_t start = (tv.tv_sec) * 1000LL + (tv.tv_usec) / 1000;
int err = posix_spawnp(&child_pid, program_name, &factions, &attr, program_argv, environ);
if (err) {
fprintf(stderr, "ERROR in fork()\n");
perror(entry->name);
return errno;
}
else {
// parent writes to and possible reads from child
int flags = 0;
// Read end is for child only
close(pipefd_stdin[0]);
if (capture_stdout) {
close(pipefd_stdout[1]);
}
char *file_data = ffindex_get_data_by_entry(data, entry);
if (capture_stdout) {
flags = fcntl(pipefd_stdout[0], F_GETFL, 0);
fcntl(pipefd_stdout[0], F_SETFL, flags | O_NONBLOCK);
}
char *b = read_buffer;
// Write file data to child's stdin.
ssize_t written = 0;
// Don't write ffindex trailing '\0'
size_t to_write = entry->length - 1;
while (written < to_write) {
size_t rest = to_write - written;
size_t batch_size = PIPE_BUF;
if (rest < PIPE_BUF) {
batch_size = rest;
}
ssize_t w = write(pipefd_stdin[1], file_data + written, batch_size);
if (w < 0 && errno != EPIPE) {
fprintf(stderr, "ERROR in child!\n");
perror(entry->name);
break;
}
else {
written += w;
}
if (capture_stdout) {
// To avoid blocking try to read some data
ssize_t r = read(pipefd_stdout[0], b, PIPE_BUF);
if (r > 0) {
b += r;
}
}
}
close(pipefd_stdin[1]); // child gets EOF
if (capture_stdout) {
// Read rest
fcntl(pipefd_stdout[0], F_SETFL, flags); // Remove O_NONBLOCK
ssize_t r;
while ((r = read(pipefd_stdout[0], b, PIPE_BUF)) > 0) {
b += r;
}
close(pipefd_stdout[0]);
ffindex_insert_memory(data_file_out, index_file_out, offset, read_buffer, b - read_buffer, entry->name);
}
int status;
waitpid(child_pid, &status, 0);
if (!quiet) {
struct timeval tv;
gettimeofday(&tv, NULL);
int64_t end = (tv.tv_sec) * 1000LL + (tv.tv_usec) / 1000;
fprintf(log_file_out, "%s\t%ld\t%ld\t%lld\t%d\n", entry->name, entry->offset, entry->length, end - start, WEXITSTATUS(status));
}
}
return EXIT_SUCCESS;
}
#ifdef HAVE_MPI
typedef struct ffindex_apply_mpi_data_s ffindex_apply_mpi_data_t;
struct ffindex_apply_mpi_data_s {
void *data;
ffindex_index_t *index;
FILE *data_file_out;
FILE *index_file_out;
FILE *log_file_out;
char *program_name;
char **program_argv;
int quiet;
size_t offset;
};
void ffindex_apply_worker_payload(void *pEnv, const size_t start, const size_t end) {
ffindex_apply_mpi_data_t *env = (ffindex_apply_mpi_data_t *) pEnv;
for (size_t i = start; i < end; i++) {
ffindex_entry_t *entry = ffindex_get_entry_by_index(env->index, i);
if (entry == NULL) {
break;
}
int error = ffindex_apply_by_entry(env->data, entry,
env->program_name,
env->program_argv,
env->data_file_out,
env->index_file_out,
env->log_file_out,
&(env->offset),
env->quiet);
if (error != 0) {
perror(entry->name);
break;
}
}
return;
}
#endif
void ignore_signal(int signal) {
struct sigaction handler;
handler.sa_handler = SIG_IGN;
sigemptyset(&handler.sa_mask);
handler.sa_flags = 0;
sigaction(signal, &handler, NULL);
}
void usage() {
fprintf(stderr,
"USAGE: ffindex_apply_mpi [-q] [-k] "
#ifdef HAVE_MPI
"[-p PARTS] [-l LOG_FILENAME_PREFIX] "
#endif
"[-d DATA_FILENAME_OUT -i INDEX_FILENAME_OUT] DATA_FILENAME INDEX_FILENAME -- PROGRAM [PROGRAM_ARGS]*\n"
"\nDesigned and implemented by Andy Hauser <hauser@genzentrum.lmu.de> and Milot Mirdita <milot@mirdita.de>.\n\n"
#ifdef HAVE_MPI
"\t[-p PARTS]\t\tSets how many entries one worker processes per job.\n"
"\t[-l LOG_FILE_PREFIX]\tPrefix for filename for the per worker process logfiles.\n"
#endif
"\t[-q]\t\t\tSilence the logging of every processed entry.\n"
"\t[-k]\t\t\tKeep unmerged ffindex splits.\n"
"\t[-d DATA_FILENAME_OUT]\tFFindex data file where the results will be saved to.\n"
"\t[-i INDEX_FILENAME_OUT]\tFFindex index file where the results will be saved to.\n"
"\tDATA_FILENAME\t\tInput ffindex data file.\n"
"\tINDEX_FILENAME\t\tInput ffindex index file.\n"
"\tPROGRAM [PROGRAM_ARGS]\tProgram to be executed for every ffindex entry.\n"
);
}
int main(int argn, char **argv) {
ignore_signal(SIGPIPE);
int exit_status = EXIT_SUCCESS;
int quiet = 0;
int keepTmp = 0;
char *data_filename_out = NULL;
char *index_filename_out = NULL;
#ifdef HAVE_MPI
size_t parts = 1;
char *log_filename = NULL;
#endif
static struct option long_options[] =
{
#ifdef HAVE_MPI
{"parts", required_argument, NULL, 'p'},
{"logfile", required_argument, NULL, 'l'},
#endif
{"data", required_argument, NULL, 'd'},
{"index", required_argument, NULL, 'i'},
{"quiet", no_argument, NULL, 'q'},
{"keep-tmp", no_argument, NULL, 'k'},
{NULL, 0, NULL, 0}
};
int opt;
while (1) {
int option_index = 0;
#ifdef HAVE_MPI
const char *short_options = "kql:p:d:i:";
#else
const char* short_options = "kqd:i:";
#endif
opt = getopt_long(argn, argv, short_options, long_options, &option_index);
if (opt == -1)
break;
switch (opt) {
#ifdef HAVE_MPI
case 'p':
parts = strtoull(optarg, NULL, 10);
break;
case 'l':
log_filename = optarg;
break;
#endif
case 'd':
data_filename_out = optarg;
break;
case 'i':
index_filename_out = optarg;
break;
case 'q':
quiet = 1;
break;
case 'k':
keepTmp = 1;
break;
default:
break;
}
}
const int remaining_arguments = argn - optind;
if (remaining_arguments < 3) {
if (remaining_arguments < 2) {
fprintf(stderr, "Please specify input data and index file.\n\n");
}
fprintf(stderr, "Please specify a program to execute.\n\n");
usage();
return EXIT_FAILURE;
}
if ((!data_filename_out && index_filename_out) || (data_filename_out && !index_filename_out)) {
fprintf(stderr, "Please specify both output data and index file.\n\n");
usage();
return EXIT_FAILURE;
}
char *data_filename = argv[optind++];
FILE *data_file = fopen(data_filename, "r");
if (data_file == NULL) {
fferror_print(__FILE__, __LINE__, argv[0], data_filename);
return EXIT_FAILURE;
}
char *index_filename = argv[optind++];
FILE *index_file = fopen(index_filename, "r");
if (index_file == NULL) {
fferror_print(__FILE__, __LINE__, argv[0], index_filename);
exit_status = EXIT_FAILURE;
goto cleanup_1;
}
char *program_name = argv[optind];
char **program_argv = argv + optind;
size_t data_size;
char *data = ffindex_mmap_data(data_file, &data_size);
if (data == MAP_FAILED) {
fferror_print(__FILE__, __LINE__, "ffindex_mmap_data", data_filename);
exit_status = EXIT_FAILURE;
goto cleanup_2;
}
size_t entries = ffcount_lines(index_filename);
ffindex_index_t *index = ffindex_index_parse(index_file, entries);
if (index == NULL) {
fferror_print(__FILE__, __LINE__, "ffindex_index_parse", index_filename);
exit_status = EXIT_FAILURE;
goto cleanup_3;
}
#ifdef HAVE_MPI
if (log_filename != NULL && quiet) {
fprintf(stderr, "Please specify either quiet (-q) or a logfile (-l).\n\n");
usage();
exit_status = EXIT_FAILURE;
goto cleanup_3;
}
int mpq_status = MPQ_Init(argn, (const char**)argv, index->n_entries);
if (mpq_status == MPQ_SUCCESS) {
if (MPQ_rank != MPQ_MASTER) {
ffindex_apply_mpi_data_t *env = malloc(sizeof(ffindex_apply_mpi_data_t));
env->data = data;
env->index = index;
env->program_name = program_name;
env->program_argv = program_argv;
env->quiet = quiet;
env->offset = 0;
env->data_file_out = NULL;
if (data_filename_out != NULL) {
char data_filename_out_rank[FILENAME_MAX];
snprintf(data_filename_out_rank, FILENAME_MAX, "%s.%d",
data_filename_out, MPQ_rank);
env->data_file_out = fopen(data_filename_out_rank, "w+");
if (env->data_file_out == NULL) {
fferror_print(__FILE__, __LINE__, "fopen", data_filename_out_rank);
exit_status = EXIT_FAILURE;
goto cleanup_4;
}
}
env->index_file_out = NULL;
if (index_filename_out != NULL) {
char index_filename_out_rank[FILENAME_MAX];
snprintf(index_filename_out_rank, FILENAME_MAX, "%s.%d",
index_filename_out, MPQ_rank);
env->index_file_out = fopen(index_filename_out_rank, "w+");
if (env->index_file_out == NULL) {
fferror_print(__FILE__, __LINE__, "fopen", index_filename_out_rank);
exit_status = EXIT_FAILURE;
goto cleanup_5;
}
}
env->log_file_out = stdout;
if (log_filename != NULL) {
char log_filename_out_rank[FILENAME_MAX];
snprintf(log_filename_out_rank, FILENAME_MAX, "%s.%d",
log_filename, MPQ_rank);
env->log_file_out = fopen(log_filename_out_rank, "w+");
if (env->log_file_out == NULL) {
fferror_print(__FILE__, __LINE__, "fopen", log_filename_out_rank);
exit_status = EXIT_FAILURE;
goto cleanup_6;
}
}
MPQ_Worker(ffindex_apply_worker_payload, env);
// make sure that all written files are properly flushed and synced
// so that ffmerge_splits wont work on stale data
if (env->log_file_out) {
int fd = fileno(env->log_file_out);
fflush(env->log_file_out);
fsync(fd);
fclose(env->log_file_out);
}
cleanup_6:
if (env->index_file_out) {
int fd = fileno(env->index_file_out);
fflush(env->index_file_out);
fsync(fd);
fclose(env->index_file_out);
}
cleanup_5:
if (env->data_file_out) {
int fd = fileno(env->data_file_out);
fflush(env->data_file_out);
fsync(fd);
fclose(env->data_file_out);
}
cleanup_4:
free(env);
MPI_Barrier(MPI_COMM_WORLD);
} else {
MPQ_Master(parts);
MPI_Barrier(MPI_COMM_WORLD);
int removeTmp = keepTmp == 0;
ffmerge_splits(data_filename_out, index_filename_out, 1, MPQ_size - 1, removeTmp);
}
} else {
if (mpq_status == MPQ_ERROR_NO_WORKERS) {
fprintf(stderr, "MPQ_Init: Needs at least one worker process.\n");
exit_status = EXIT_FAILURE;
}
}
#else
FILE* data_file_out = NULL;
if (data_filename_out != NULL)
{
char data_filename_out_rank[FILENAME_MAX];
snprintf(data_filename_out_rank, FILENAME_MAX, "%s", data_filename_out);
data_file_out = fopen(data_filename_out_rank, "w+");
if (data_file_out == NULL)
{
fferror_print(__FILE__, __LINE__, "ffindex_apply_worker_payload", data_filename_out);
return EXIT_FAILURE;
}
}
FILE* index_file_out = NULL;
if (index_filename_out != NULL)
{
char index_filename_out_rank[FILENAME_MAX];
snprintf(index_filename_out_rank, FILENAME_MAX, "%s", index_filename_out);
index_file_out = fopen(index_filename_out_rank, "w+");
if (index_file_out == NULL)
{
fferror_print(__FILE__, __LINE__, "ffindex_apply_worker_payload", index_filename_out);
return EXIT_FAILURE;
}
}
size_t offset = 0;
for (size_t i = 0; i < index->n_entries; i++)
{
ffindex_entry_t *entry = ffindex_get_entry_by_index(index, i);
if (entry == NULL)
{
exit_status = errno;
break;
}
int error = ffindex_apply_by_entry(data, entry,
program_name, program_argv,
data_file_out, index_file_out, stdout,
&offset, quiet);
if (error != 0)
{
perror(entry->name);
exit_status = errno;
break;
}
}
if (index_file_out) {
fclose(index_file_out);
}
if (data_file_out) {
fclose(data_file_out);
}
#endif
munmap(index->index_data, index->index_data_size);
free(index);
cleanup_3:
munmap(data, data_size);
cleanup_2:
if (index_file) {
fclose(index_file);
}
cleanup_1:
if (data_file) {
fclose(data_file);
}
#ifdef HAVE_MPI
MPI_Finalize();
#endif
return exit_status;
}
/*
* Ffindex
* written by Andy Hauser <hauser@genzentrum.lmu.de>.
* Please add your name here if you distribute modified versions.
*
* Ffindex is provided under the Create Commons license "Attribution-ShareAlike
* 4.0", which basically captures the spirit of the Gnu Public License (GPL).
*
* See:
* http://creativecommons.org/licenses/by-sa/4.0/
*/
#define _GNU_SOURCE 1
#define _LARGEFILE64_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <getopt.h>
#include "ffindex.h"
#include "ffutil.h"
#define MAX_FILENAME_LIST_FILES 4096
void usage(char *program_name)
{
fprintf(stderr, "USAGE: %s [-a|-v] [-s] [-f file]* OUT_DATA_FILE OUT_INDEX_FILE [-d 2ND_DATA_FILE -i 2ND_INDEX_FILE] [DIR_TO_INDEX|FILE]*\n"
"\t-a\t\tappend files/indexes, also needed for sorting an already existing ffindex\n"
"\t-d FFDATA_FILE\ta second ffindex data file for inserting/appending\n"
"\t-i FFINDEX_FILE\ta second ffindex index file for inserting/appending\n"
"\t-f FILE\t\tfile containing a list of file names, one per line\n"
"\t\t\t-f can be specified up to %d times\n"
"\t-s\t\tsort index file, so that the index can queried.\n"
"\t\t\tAnother append operations can be done without sorting.\n"
"\t-v\t\tprint version and other info then exit\n"
"\nEXAMPLES:\n"
"\tCreate a new ffindex containing all files from the \"bar/\" directory containing\n"
"\tsay myfile1.txt, myfile2.txt and sort (-s) it so that e.g. ffindex_get can use it.\n"
"\t\t$ ffindex_build -s foo.ffdata foo.ffindex bar/\n"
"\n\tAdd (-a) more files: myfile3.txt, myfile4.txt.\n"
"\t\t$ ffindex_build -a foo.ffdata foo.ffindex myfile3.txt myfile4.txt\n"
"\n\tOops, forgot to sort it (-s) so do it afterwards:\n"
"\t\t$ ffindex_build -as foo.ffdata foo.ffindex\n"
"\nNOTE:\n"
"\tMaximum key/filename length is %d and maximum entries are by default %d\n"
"\tThis can be changed in the sources.\n"
"\nDesigned and implemented by Andreas W. Hauser <hauser@genzentrum.lmu.de>.\n",
program_name, MAX_FILENAME_LIST_FILES, FFINDEX_MAX_ENTRY_NAME_LENTH, FFINDEX_MAX_INDEX_ENTRIES_DEFAULT);
}
int main(int argn, char** argv)
{
int append = 0, sort = 0, version = 0;
int err = EXIT_SUCCESS;
char* list_filenames[MAX_FILENAME_LIST_FILES];
char* list_ffindex_data[MAX_FILENAME_LIST_FILES];
char* list_ffindex_index[MAX_FILENAME_LIST_FILES];
size_t list_ffindex_data_index = 0;
size_t list_ffindex_index_index = 0;
size_t list_filenames_index = 0;
static struct option long_options[] =
{
{ "append", no_argument, NULL, 'a' },
{ "data", required_argument, NULL, 'd' },
{ "index", required_argument, NULL, 'i' },
{ "file", required_argument, NULL, 'f' },
{ "sort", no_argument, NULL, 's' },
{ "version", no_argument, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
int opt;
while (1)
{
int option_index = 0;
opt = getopt_long(argn, argv, "ad:i:f:sv", long_options, &option_index);
if (opt == -1)
break;
switch (opt)
{
case 'a':
append = 1;
break;
case 'd':
list_ffindex_data[list_ffindex_data_index++] = optarg;
break;
case 'i':
list_ffindex_index[list_ffindex_index_index++] = optarg;
break;
case 'f':
list_filenames[list_filenames_index++] = optarg;
break;
case 's':
sort = 1;
break;
case 'v':
version = 1;
break;
default:
usage(argv[0]);
return EXIT_FAILURE;
}
}
if(version == 1)
{
/* Don't you dare running it on a platform where byte != 8 bits */
printf("%s version %.2f, off_t = %zd bits\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8);
return EXIT_SUCCESS;
}
if(argn - optind < 2)
{
usage(argv[0]);
return EXIT_FAILURE;
}
if(list_ffindex_data_index != list_ffindex_index_index)
{
fprintf(stderr, "ERROR: -d and -i must be specified pairwise\n");
return EXIT_FAILURE;
}
char *data_filename = argv[optind++];
char *index_filename = argv[optind++];
FILE *data_file, *index_file;
size_t offset = 0;
/* open index and data file, seek to end if needed */
if(append)
{
data_file = fopen(data_filename, "a");
if( data_file == NULL) { perror(data_filename); return EXIT_FAILURE; }
index_file = fopen(index_filename, "a+");
if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; }
struct stat sb;
fstat(fileno(data_file), &sb);
fseek(data_file, sb.st_size, SEEK_SET);
offset = sb.st_size;
fstat(fileno(index_file), &sb);
fseek(index_file, sb.st_size, SEEK_SET);
}
else
{
struct stat st;
if(stat(data_filename, &st) == 0) { errno = EEXIST; perror(data_filename); return EXIT_FAILURE; }
data_file = fopen(data_filename, "w");
if( data_file == NULL) { perror(data_filename); return EXIT_FAILURE; }
if(stat(index_filename, &st) == 0) { errno = EEXIST; perror(index_filename); return EXIT_FAILURE; }
index_file = fopen(index_filename, "w+");
if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; }
}
/* For each list_file insert */
if(list_filenames_index > 0)
for(int i = 0; i < list_filenames_index; i++)
{
FILE *list_file = fopen(list_filenames[i], "r");
if( list_file == NULL) { perror(list_filenames[i]); return EXIT_FAILURE; }
if(ffindex_insert_list_file(data_file, index_file, &offset, list_file) < 0)
{
perror(list_filenames[i]);
err = -1;
}
}
/* Append other ffindexes */
if(list_ffindex_data_index > 0)
{
for(int i = 0; i < list_ffindex_data_index; i++)
{
FILE* data_file_to_add = fopen(list_ffindex_data[i], "r"); if( data_file_to_add == NULL) { perror(list_ffindex_data[i]); return EXIT_FAILURE; }
FILE* index_file_to_add = fopen(list_ffindex_index[i], "r"); if( index_file_to_add == NULL) { perror(list_ffindex_index[i]); return EXIT_FAILURE; }
// ignore empty files
struct stat sb;
fstat(fileno(data_file_to_add), &sb);
if(sb.st_size == 0)
continue;
fstat(fileno(index_file_to_add), &sb);
if(sb.st_size == 0)
continue;
size_t data_size;
char *data_to_add = ffindex_mmap_data(data_file_to_add, &data_size);
size_t entries = ffcount_lines(list_ffindex_index[i]);
ffindex_index_t* index_to_add = ffindex_index_parse(index_file_to_add, entries);
for(size_t entry_i = 0; entry_i < index_to_add->n_entries; entry_i++)
{
ffindex_entry_t *entry = ffindex_get_entry_by_index(index_to_add, entry_i);
ffindex_insert_memory(data_file, index_file, &offset, ffindex_get_data_by_entry(data_to_add, entry), entry->length - 1, entry->name); // skip \0 suffix
}
}
}
/* Insert files and directories into the index */
for(int i = optind; i < argn; i++)
{
char *path = argv[i];
struct stat sb;
if(stat(path, &sb) == -1)
{
fferror_print(__FILE__, __LINE__, __func__, path);
continue;
}
if(S_ISDIR(sb.st_mode))
{
err = ffindex_insert_dir(data_file, index_file, &offset, path);
if(err < 0)fferror_print(__FILE__, __LINE__, __func__, path);
}
else if(S_ISREG(sb.st_mode))
{
ffindex_insert_file(data_file, index_file, &offset, path, path);
}
}
fclose(data_file);
/* Sort the index entries and write back */
if(sort)
{
fclose(index_file);
size_t entries = ffcount_lines(index_filename);
index_file = fopen(index_filename, "r+");
ffindex_index_t* index = ffindex_index_parse(index_file, entries);
if(index == NULL)
{
fferror_print(__FILE__, __LINE__, __func__, index_filename);
exit(EXIT_FAILURE);
}
fclose(index_file);
ffindex_sort_index_file(index);
index_file = fopen(index_filename, "w");
if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; }
err += ffindex_write(index, index_file);
}
return err;
}
/* vim: ts=2 sw=2 et
*/
/*
* FFindex
* written by Andy Hauser <hauser@genzentrum.lmu.de>.
* Please add your name here if you distribute modified versions.
*
* FFindex is provided under the Create Commons license "Attribution-ShareAlike
* 4.0", which basically captures the spirit of the Gnu Public License (GPL).
*
* See:
* http://creativecommons.org/licenses/by-sa/4.0/
*/
#define _GNU_SOURCE 1
#define _LARGEFILE64_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <getopt.h>
#include "ffindex.h"
#include "ffutil.h"
#define MAX_FILENAME_LIST_FILES 4096
#define MAX_ENTRY_LENGTH 100000
void usage(char *program_name)
{
fprintf(stderr, "USAGE: %s -v | [-s] data_filename index_filename fasta_filename\n"
"\t-s\tsort index file\n"
"\nBases on a Design and Implementation of Andreas W. Hauser <hauser@genzentrum.lmu.de>.\n", program_name);
}
int main(int argn, char **argv)
{
int sort = 0, version = 0;
int err = EXIT_SUCCESS;
static struct option long_options[] =
{
{ "sort", no_argument, NULL, 's' },
{ "version", no_argument, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
int opt;
while (1)
{
int option_index = 0;
opt = getopt_long(argn, argv, "sv", long_options, &option_index);
if (opt == -1)
break;
switch (opt)
{
case 's':
sort = 1;
break;
case 'v':
version = 1;
break;
default:
usage(argv[0]);
return EXIT_FAILURE;
}
}
if(version == 1)
{
/* Don't you dare running it on a platform where byte != 8 bits */
printf("%s version %.2f, off_t = %zd bits\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8);
return EXIT_SUCCESS;
}
if(argn - optind < 3)
{
usage(argv[0]);
return EXIT_FAILURE;
}
char *data_filename = argv[optind++];
char *index_filename = argv[optind++];
char *fasta_filename = argv[optind++];
printf("data file: %s\n", data_filename);
printf("index file: %s\n", index_filename);
printf("fasta file: %s\n", fasta_filename);
FILE *data_file, *index_file, *fasta_file;
size_t offset = 0;
//open output ffindex
struct stat st;
if(stat(data_filename, &st) == 0) { errno = EEXIST; perror(data_filename); return EXIT_FAILURE; }
data_file = fopen(data_filename, "w");
if( data_file == NULL) { perror(data_filename); return EXIT_FAILURE; }
if(stat(index_filename, &st) == 0) { errno = EEXIST; perror(index_filename); return EXIT_FAILURE; }
index_file = fopen(index_filename, "w+");
if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; }
fasta_file = fopen(fasta_filename, "r");
if(fasta_file == NULL) { perror(fasta_filename); return EXIT_FAILURE; }
size_t fasta_size;
char *fasta_data = ffindex_mmap_data(fasta_file, &fasta_size);
// size_t from_length = 0;
char name[FFINDEX_MAX_ENTRY_NAME_LENTH];
int seq_id = 1;
size_t seq_id_length = 0;
size_t count_ws = 0;
char entry[MAX_ENTRY_LENGTH];
entry[0] = '>';
size_t entry_length = 0;
for(size_t fasta_offset = 1; fasta_offset < fasta_size; fasta_offset++) // position after first ">"
{
seq_id_length = 0;
count_ws = 0;
entry_length = 1;
while(fasta_offset < fasta_size && !(*(fasta_data + fasta_offset) == '>' && *(fasta_data + fasta_offset - 1) == '\n'))
{
char input = *(fasta_data + fasta_offset);
//get fasta name
if(isspace(input))
{
count_ws++;
name[seq_id_length] = '\0';
}
else if(count_ws == 0)
{
name[seq_id_length++] = *(fasta_data + fasta_offset);
}
entry[entry_length++] = input;
fasta_offset++;
}
if(seq_id_length == 0) {
sprintf(name, "%d", seq_id);
}
seq_id++;
ffindex_insert_memory(data_file, index_file, &offset, entry, entry_length, name);
}
fclose(data_file);
/* Sort the index entries and write back */
if(sort)
{
fclose(index_file);
size_t entries = ffcount_lines(index_filename);
index_file = fopen(index_filename, "r+");
ffindex_index_t* index = ffindex_index_parse(index_file, entries);
if(index == NULL)
{
perror("ffindex_index_parse failed");
exit(EXIT_FAILURE);
}
fclose(index_file);
ffindex_sort_index_file(index);
index_file = fopen(index_filename, "w");
if(index_file == NULL) { perror(index_filename); return EXIT_FAILURE; }
err += ffindex_write(index, index_file);
}
return err;
}
/* vim: ts=2 sw=2 et: */
/*
* FFindex
* written by Andy Hauser <hauser@genzentrum.lmu.de>.
* Please add your name here if you distribute modified versions.
*
* FFindex is provided under the Create Commons license "Attribution-ShareAlike
* 4.0", which basically captures the spirit of the Gnu Public License (GPL).
*
* See:
* http://creativecommons.org/licenses/by-sa/4.0/
*/
#define _GNU_SOURCE 1
#define _LARGEFILE64_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctype.h>
#include "ffindex.h"
#include "ffutil.h"
#define MAX_FILENAME_LIST_FILES 4096
#define MAX_ENTRY_LENGTH 100000
void usage(char *program_name)
{
fprintf(stderr, "USAGE: %s -v | [-s] data_header_filename index_header_filename data_sequence_filename index_sequence_filename fasta_filename\n"
"\t-s\tsort index file\n"
"\nBases on a Design and Implementation of Andreas W. Hauser <hauser@genzentrum.lmu.de>.\n", program_name);
}
void get_short_id(char* id, const char delimiter, const int field) {
size_t l = strlen(id);
size_t first_separator_index = l;
if (field == 1) {
first_separator_index = -1;
}
size_t second_separator_index = l;
int field_counter = 1;
for (size_t index = 0; index < l; index++) {
if (id[index] == delimiter) {
field_counter++;
if(field_counter == field && first_separator_index == l) {
first_separator_index = index;
}
else if(field_counter - 1 == field && second_separator_index == l) {
second_separator_index = index;
break;
}
}
}
if (field_counter < field) {
fprintf(stderr, "Warning: short id could not be extracted from '%s'!", id);
}
char* substr = malloc(sizeof(char*) * (second_separator_index - first_separator_index));
strncpy(substr, id + first_separator_index + 1, (second_separator_index - first_separator_index - 1));
strncpy(id, substr, (second_separator_index - first_separator_index - 1));
id[second_separator_index - first_separator_index - 1] = '\0';
free(substr);
}
int main(int argn, char **argv)
{
int sort = 0, version = 0;
int opt, err = EXIT_SUCCESS;
while ((opt = getopt(argn, argv, "sv")) != -1)
{
switch (opt)
{
case 's':
sort = 1;
break;
case 'v':
version = 1;
break;
default:
usage(argv[0]);
return EXIT_FAILURE;
}
}
if(version == 1)
{
/* Don't you dare running it on a platform where byte != 8 bits */
printf("%s version %.2f, off_t = %zd bits\n", argv[0], FFINDEX_VERSION, sizeof(off_t) * 8);
return EXIT_SUCCESS;
}
if(argn - optind < 3)
{
usage(argv[0]);
return EXIT_FAILURE;
}
char *data_header_filename = argv[optind++];
char *index_header_filename = argv[optind++];
char *data_sequence_filename = argv[optind++];
char *index_sequence_filename = argv[optind++];
char *fasta_filename = argv[optind++];
printf("data header file: %s\n", data_header_filename);
printf("index header file: %s\n", index_header_filename);
printf("data sequence file: %s\n", data_sequence_filename);
printf("index sequence file: %s\n", index_sequence_filename);
printf("fasta file: %s\n", fasta_filename);
FILE *data_header_file, *index_header_file, *data_sequence_file, *index_sequence_file, *fasta_file;
size_t header_offset = 0;
size_t sequence_offset = 0;
struct stat st;
// open header ffindex
if(stat(data_header_filename, &st) == 0) { errno = EEXIST; perror(data_header_filename); return EXIT_FAILURE; }
data_header_file = fopen(data_header_filename, "w");
if( data_header_file == NULL) { perror(data_header_filename); return EXIT_FAILURE; }
if(stat(index_header_filename, &st) == 0) { errno = EEXIST; perror(index_header_filename); return EXIT_FAILURE; }
index_header_file = fopen(index_header_filename, "w+");
if(index_header_file == NULL) { perror(index_header_filename); return EXIT_FAILURE; }
//open sequence ffindex
if(stat(data_sequence_filename, &st) == 0) { errno = EEXIST; perror(data_sequence_filename); return EXIT_FAILURE; }
data_sequence_file = fopen(data_sequence_filename, "w");
if( data_sequence_file == NULL) { perror(data_sequence_filename); return EXIT_FAILURE; }
if(stat(index_sequence_filename, &st) == 0) { errno = EEXIST; perror(index_sequence_filename); return EXIT_FAILURE; }
index_sequence_file = fopen(index_sequence_filename, "w+");
if(index_sequence_file == NULL) { perror(index_sequence_filename); return EXIT_FAILURE; }
fasta_file = fopen(fasta_filename, "r");
if(fasta_file == NULL) { perror(fasta_filename); return EXIT_FAILURE; }
size_t fasta_size;
char *fasta_data = ffindex_mmap_data(fasta_file, &fasta_size);
// size_t from_length = 0;
char name[FFINDEX_MAX_ENTRY_NAME_LENTH];
int seq_id = 1;
size_t seq_id_length = 0;
size_t count_ws = 0;
char header[MAX_ENTRY_LENGTH];
header[0] = '>';
size_t header_length = 1;
char is_header = 1;
char sequence[MAX_ENTRY_LENGTH];
size_t sequence_length = 0;
for(size_t fasta_offset = 1; fasta_offset < fasta_size; fasta_offset++) // position after first ">"
{
seq_id_length = 0;
count_ws = 0;
is_header = 1;
header_length = 1;
sequence_length = 0;
while(fasta_offset < fasta_size && !(*(fasta_data + fasta_offset) == '>' && *(fasta_data + fasta_offset - 1) == '\n'))
{
char input = *(fasta_data + fasta_offset);
//get fasta name
if(isspace(input))
{
count_ws++;
name[seq_id_length] = '\0';
}
else if(count_ws == 0)
{
name[seq_id_length++] = *(fasta_data + fasta_offset);
}
if(input == '\n') {
is_header = 0;
header[header_length] = '\0';
sequence[sequence_length] = '\0';
}
else {
if(is_header == 1) {
header[header_length++] = input;
}
else {
sequence[sequence_length++] = input;
}
}
fasta_offset++;
}
if(seq_id_length == 0) {
sprintf(name, "%d", seq_id);
}
seq_id++;
get_short_id(name, '|', 2);
ffindex_insert_memory(data_header_file, index_header_file, &header_offset, header, header_length, name);
ffindex_insert_memory(data_sequence_file, index_sequence_file, &sequence_offset, sequence, sequence_length, name);
}
fclose(data_header_file);
fclose(data_sequence_file);
fclose(index_header_file);
fclose(index_sequence_file);
/* Sort the index entries and write back */
if(sort) {
ffsort_index(index_header_filename);
ffsort_index(index_sequence_filename);
}
return err;
}
/* vim: ts=2 sw=2 et: */