repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
yp/Heu-MCHC
pers-lib/m4ri/testsuite/bench_trsm_upperleft.c
<filename>pers-lib/m4ri/testsuite/bench_trsm_upperleft.c #include <stdlib.h> #include "cpucycles.h" #include "walltime.h" #include "m4ri/m4ri.h" int main(int argc, char **argv) { int n,m; unsigned long long t; double wt; double clockZero = 0.0; if (argc != 3) { m4ri_die("Parameters m, n expected.\n"); } m = atoi(argv[1]); n = atoi(argv[2]); mzd_t *B = mzd_init(m, n); mzd_t *U = mzd_init(m, m); mzd_randomize(B); mzd_randomize(U); size_t i,j; for (i=0; i<n; ++i){ for (j=0; j<i;++j) mzd_write_bit(U,i,j, 0); mzd_write_bit(U,i,i, 1); } wt = walltime(&clockZero); t = cpucycles(); mzd_trsm_upper_left(U, B, 2048); printf("n: %5d, cpu cycles: %llu wall time: %lf\n",n, cpucycles() - t, walltime(&wt)); mzd_free(B); mzd_free(U); }
yp/Heu-MCHC
include/log.h
/** * * * Heu-MCHC * * A fast and accurate heuristic algorithm for the haplotype inference * problem on pedigree data with recombinations and mutations * * Copyright (C) 2009,2010,2011 <NAME> * * Distributed under the terms of the GNU General Public License (GPL) * * * This file is part of Heu-MCHC. * * Heu-MCHC is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Heu-MCHC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>. * **/ /** * * @file log.h * * Funzioni per la stampa di messaggi di log. * **/ #ifdef __cplusplus extern "C" { #endif #ifndef _LOG_H_ #define _LOG_H_ #define LOG_LEVEL_FATAL (0) #define LOG_LEVEL_ERROR (1) #define LOG_LEVEL_WARN (2) #define LOG_LEVEL_INFO (3) #define LOG_LEVEL_STATS (3) #define LOG_LEVEL_DEBUG (4) #define LOG_LEVEL_TRACE (5) #define LOG_LEVEL_FINETRACE (6) #ifndef LOG_THRESHOLD #define LOG_THRESHOLD LOG_LEVEL_INFO #endif #ifndef LOG_PREFIX #define LOG_PREFIX "* " #endif #include <stddef.h> void log_format_str(const char* funz, const char* srcf, char* dst, int max_len1, int max_len2); #endif // _LOG_H_ #ifdef LOG #undef __INTERNAL_LOG #undef LOG #undef LOG_NOTN #undef FATAL #undef ERROR #undef WARN #undef INFO #undef STATS #undef DEBUG #undef TRACE #undef FINETRACE #undef FATAL_NOTN #undef ERROR_NOTN #undef WARN_NOTN #undef INFO_NOTN #undef STATS_NOTN #undef DEBUG_NOTN #undef TRACE_NOTN #undef FINETRACE_NOTN #undef FATAL_IF_NOTN #undef ERROR_IF_NOTN #undef WARN_IF_NOTN #undef INFO_IF_NOTN #undef STATS_IF_NOTN #undef DEBUG_IF_NOTN #undef TRACE_IF_NOTN #undef FINETRACE_IF_NOTN #undef LOG_FATAL_ENABLED #undef LOG_ERROR_ENABLED #undef LOG_WARN_ENABLED #undef LOG_INFO_ENABLED #undef LOG_STATS_ENABLED #undef LOG_DEBUG_ENABLED #undef LOG_TRACE_ENABLED #undef LOG_FINETRACE_ENABLED #endif #ifdef LOG_MSG #include <stdio.h> #include <string.h> #define MAX_LEN_FUNC_NAME 16 #define MAX_LEN_FILE_NAME 12 #define BASIC_LOG(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__) #define __BASIC_STATS(format, ...) do { \ BASIC_LOG("@ STATS " \ format "%s", \ ## __VA_ARGS__); \ } while (0) #define LOG_NOTN(level, prefix, ...) __INTERNAL_LOG(level, prefix, ## __VA_ARGS__, "") #define LOG(level, prefix, ...) __INTERNAL_LOG(level, prefix, ## __VA_ARGS__, "\n") #define __INTERNAL_LOG(level, prefix, format, ...) do { \ if (level<=LOG_THRESHOLD) { \ char __my_internal_buff__[MAX_LEN_FUNC_NAME+MAX_LEN_FILE_NAME+2]; \ log_format_str(__func__, __FILE__, __my_internal_buff__, \ MAX_LEN_FUNC_NAME, MAX_LEN_FILE_NAME); \ BASIC_LOG(LOG_PREFIX prefix "(%s:%4d) " \ format "%s", \ __my_internal_buff__, __LINE__, \ ## __VA_ARGS__); \ } \ } while (0) #if (LOG_LEVEL_FATAL<=LOG_THRESHOLD) #define LOG_FATAL_ENABLED #endif #if (LOG_LEVEL_ERROR<=LOG_THRESHOLD) #define LOG_ERROR_ENABLED #endif #if (LOG_LEVEL_WARN<=LOG_THRESHOLD) #define LOG_WARN_ENABLED #endif #if (LOG_LEVEL_INFO<=LOG_THRESHOLD) #define LOG_INFO_ENABLED #endif #if (LOG_LEVEL_STATS<=LOG_THRESHOLD) #define LOG_STATS_ENABLED #endif #if (LOG_LEVEL_DEBUG<=LOG_THRESHOLD) #define LOG_DEBUG_ENABLED #endif #if (LOG_LEVEL_TRACE<=LOG_THRESHOLD) #define LOG_TRACE_ENABLED #endif #if (LOG_LEVEL_FINETRACE<=LOG_THRESHOLD) #define LOG_FINETRACE_ENABLED #endif #else #define LOG(level, prefix, ...) do { } while (0) #define LOG_NOTN(level, prefix, ...) do { } while (0) #endif #ifdef LOG_FATAL_ENABLED #define FATAL(...) LOG(LOG_LEVEL_FATAL, "FATAL", ## __VA_ARGS__) #define FATAL_MSG(fmt, ...) BASIC_LOG(fmt, ## __VA_ARGS__) #define FATAL_NOTN(...) LOG_NOTN(LOG_LEVEL_FATAL, "FATAL", ## __VA_ARGS__) #define FATAL_IF(cond, ...) if ((cond)) { \ FATAL(##__VA_ARGS__); \ } #define FATAL_IF_NOTN(cond, ...) if ((cond)) { \ FATAL_NOTN(##__VA_ARGS__); \ } #else #define FATAL(...) do {} while (0) #define FATAL_MSG(...) do {} while (0) #define FATAL_IF(...) do {} while (0) #define FATAL_NOTN(...) do {} while (0) #define FATAL_IF_NOTN(...) do {} while (0) #endif #ifdef LOG_ERROR_ENABLED #define ERROR(...) LOG(LOG_LEVEL_ERROR, "ERROR", ## __VA_ARGS__) #define ERROR_MSG(fmt, ...) BASIC_LOG(fmt,## __VA_ARGS__) #define ERROR_NOTN(...) LOG_NOTN(LOG_LEVEL_ERROR, "ERROR", ## __VA_ARGS__) #define ERROR_IF(cond, ...) if ((cond)) { \ ERROR( __VA_ARGS__); \ } #define ERROR_IF_NOTN(cond, ...) if ((cond)) { \ ERROR_NOTN( __VA_ARGS__); \ } #else #define ERROR(...) do {} while (0) #define ERROR_MSG(...) do {} while (0) #define ERROR_IF(...) do {} while (0) #define ERROR_NOTN(...) do {} while (0) #define ERROR_IF_NOTN(...) do {} while (0) #endif #ifdef LOG_WARN_ENABLED #define WARN(...) LOG(LOG_LEVEL_WARN, "WARN ", ## __VA_ARGS__) #define WARN_MSG(fmt, ...) BASIC_LOG(fmt,## __VA_ARGS__) #define WARN_NOTN(...) LOG_NOTN(LOG_LEVEL_WARN, "WARN ", ## __VA_ARGS__) #define WARN_IF(cond, ...) if ((cond)) { \ WARN( __VA_ARGS__); \ } #define WARN_IF_NOTN(cond, ...) if ((cond)) { \ WARN_NOTN( __VA_ARGS__); \ } #else #define WARN(...) do {} while (0) #define WARN_MSG(...) do {} while (0) #define WARN_IF(...) do {} while (0) #define WARN_NOTN(...) do {} while (0) #define WARN_IF_NOTN(...) do {} while (0) #endif #ifdef LOG_INFO_ENABLED #define INFO(...) LOG(LOG_LEVEL_INFO, "INFO ", ## __VA_ARGS__) #define INFO_MSG(fmt, ...) BASIC_LOG(fmt,## __VA_ARGS__) #define INFO_NOTN(...) LOG_NOTN(LOG_LEVEL_INFO, "INFO ", ## __VA_ARGS__) #define INFO_IF(cond, ...) if ((cond)) { \ INFO( __VA_ARGS__); \ } #define INFO_IF_NOTN(cond, ...) if ((cond)) { \ INFO_NOTN( __VA_ARGS__); \ } #else #define INFO(...) do {} while (0) #define INFO_MSG(...) do {} while (0) #define INFO_IF(...) do {} while (0) #define INFO_NOTN(...) do {} while (0) #define INFO_IF_NOTN(...) do {} while (0) #endif #ifdef LOG_STATS_ENABLED #define STATS(fmt, ...) __BASIC_STATS(fmt,##__VA_ARGS__, "\n") #define STATS_MSG(fmt, ...) BASIC_LOG(fmt,##__VA_ARGS__) #define STATS_NOTN(...) __BASIC_STATS(__VA_ARGS__, "") #define STATS_IF(cond, ...) if ((cond)) { \ STATS( __VA_ARGS__); \ } #define STATS_IF_NOTN(cond, ...) if ((cond)) { \ STATS_NOTN( __VA_ARGS__); \ } #else #define STATS(...) do {} while (0) #define STATS_MSG(...) do {} while (0) #define STATS_IF(...) do {} while (0) #define STATS_NOTN(...) do {} while (0) #define STATS_IF_NOTN(...) do {} while (0) #endif #ifdef LOG_DEBUG_ENABLED #define DEBUG(...) LOG(LOG_LEVEL_DEBUG, "DEBUG", ## __VA_ARGS__) #define DEBUG_MSG(fmt, ...) BASIC_LOG(fmt,## __VA_ARGS__) #define DEBUG_NOTN(...) LOG_NOTN(LOG_LEVEL_DEBUG, "DEBUG", ## __VA_ARGS__) #define DEBUG_IF(cond, ...) if ((cond)) { \ DEBUG( __VA_ARGS__); \ } #define DEBUG_IF_NOTN(cond, ...) if ((cond)) { \ DEBUG_NOTN( __VA_ARGS__); \ } #else #define DEBUG(...) do {} while (0) #define DEBUG_MSG(...) do {} while (0) #define DEBUG_IF(...) do {} while (0) #define DEBUG_NOTN(...) do {} while (0) #define DEBUG_IF_NOTN(...) do {} while (0) #endif #ifdef LOG_TRACE_ENABLED #define TRACE(...) LOG(LOG_LEVEL_TRACE, "TRACE", ## __VA_ARGS__) #define TRACE_MSG(fmt, ...) BASIC_LOG(fmt,## __VA_ARGS__) #define TRACE_NOTN(...) LOG_NOTN(LOG_LEVEL_TRACE, "TRACE", ## __VA_ARGS__) #define TRACE_IF(cond, ...) if ((cond)) { \ TRACE( __VA_ARGS__); \ } #define TRACE_IF_NOTN(cond, ...) if ((cond)) { \ TRACE_NOTN( __VA_ARGS__); \ } #else #define TRACE(...) do {} while (0) #define TRACE_MSG(...) do {} while (0) #define TRACE_IF(...) do {} while (0) #define TRACE_NOTN(...) do {} while (0) #define TRACE_IF_NOTN(...) do {} while (0) #endif #ifdef LOG_FINETRACE_ENABLED #define FINETRACE(...) LOG(LOG_LEVEL_FINETRACE, "TRAC+", ## __VA_ARGS__) #define FINETRACE_MSG(fmt, ...) BASIC_LOG(fmt,## __VA_ARGS__) #define FINETRACE_NOTN(...) LOG_NOTN(LOG_LEVEL_FINETRACE, "TRAC+", ## __VA_ARGS__) #define FINETRACE_IF(cond, ...) if ((cond)) { \ FINETRACE( __VA_ARGS__); \ } #define FINETRACE_IF_NOTN(cond, ...) if ((cond)) { \ FINETRACE_NOTN( __VA_ARGS__); \ } #else #define FINETRACE(...) do {} while (0) #define FINETRACE_MSG(...) do {} while (0) #define FINETRACE_IF(...) do {} while (0) #define FINETRACE_NOTN(...) do {} while (0) #define FINETRACE_IF_NOTN(...) do {} while (0) #endif #ifdef __cplusplus } #endif
yp/Heu-MCHC
src/conversion-2simwalk.c
/** * * * Heu-MCHC * * A fast and accurate heuristic algorithm for the haplotype inference * problem on pedigree data with recombinations and mutations * * Copyright (C) 2009,2010,2011 <NAME> * * Distributed under the terms of the GNU General Public License (GPL) * * * This file is part of Heu-MCHC. * * Heu-MCHC is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Heu-MCHC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>. * **/ /* ** conversion-2simwalk.c ** ** Made by (<NAME>) ** Login <<EMAIL>> ** ** Started on Wed Mar 17 12:18:27 2010 <NAME> ** Last update Sun May 12 01:17:25 2002 Speed Blue */ #include "gen-ped-IO.h" #include "util.h" #include "log-build-info.h" int main() { PRINT_SYSTEM_INFORMATIONS; pgenped pg= gp_read_from_file(stdin); char* gender= NPALLOC(char, pg->n_indiv); for (size_t i= 0; i<pg->n_indiv; ++i) { gender[i]= 'M'; } for (size_t i= 0; i<pg->n_indiv; ++i) { if (pg->individuals[i]->fi>=0) { gender[pg->individuals[i]->fi]= 'M'; } if (pg->individuals[i]->mi>=0) { gender[pg->individuals[i]->mi]= 'F'; } } // Save MAP file INFO("Saving file MAP.DAT..."); FILE* MAP= fopen("MAP.DAT", "w"); fail_if_msg(MAP == NULL, "Impossible to write to file MAP.DAT"); for (unsigned int j= 0; j<pg->n_loci; ++j) { fprintf(MAP, "L%u\n 0.01000\n", j); } fclose(MAP); // Save LOCUS file INFO("Saving file LOCUS.DAT..."); FILE* LOCUS= fopen("LOCUS.DAT", "w"); fail_if_msg(LOCUS == NULL, "Impossible to write to file LOCUS.DAT"); for (unsigned int j= 0; j<pg->n_loci; ++j) { fprintf(LOCUS, "L%-7uAUTOSOME 2 0\n" " 1 0.50000\n" " 2 0.50000\n", j); } fclose(LOCUS); // Save PEDIGREE file INFO("Saving file PEDIGREE.DAT..."); FILE* PEDIGREE= fopen("PEDIGREE.DAT", "w"); fail_if_msg(PEDIGREE == NULL, "Impossible to write to file PEDIGREE.DAT"); fprintf(PEDIGREE, "(I5,1X,A8)\n" "(3A8,2A1,1X,%u(A3,1X))\n",pg->n_loci); fprintf(PEDIGREE, "%-5u PEDIGREE\n",pg->n_indiv); for (unsigned int i= 0; i<pg->n_indiv; ++i) { pindiv in= pg->individuals[i]; fprintf(PEDIGREE, "I%-7u", in->id+1); if (in->fi<0) fprintf(PEDIGREE, " "); else fprintf(PEDIGREE, "I%-7u", in->fi+1); if (in->mi<0) fprintf(PEDIGREE, " "); else fprintf(PEDIGREE, "I%-7u", in->mi+1); fprintf(PEDIGREE, "%c ", gender[i]); for (unsigned int j= 0; j<pg->n_loci; ++j) { if (in->g[j]==2) { fprintf(PEDIGREE, "1/2 "); } else { fprintf(PEDIGREE, "%d/%d ", in->g[j]+1, in->g[j]+1); } } fprintf(PEDIGREE, "\n"); } fclose(PEDIGREE); INFO("Saving file BATCH2.DAT..."); FILE* BATCH2= fopen("BATCH2.DAT", "w"); fail_if_msg(BATCH2 == NULL, "Impossible to write to file BATCH2.DAT"); fprintf(BATCH2, "\n" "01 ! batch item number\n" "1 ! analysis: 1=Haplo; 2=LOD; 3=NPL; 4=IBD; 5=Mistyping\n" "\n" "02 ! batch item number\n" "01 ! integer label for this run of the program\n" "\n" "03 ! batch item number\n" "General test \n" "\n" "09 ! batch item number\n" "MAP.DAT ! name of map file\n" "\n" "10 ! batch item number\n" "LOCUS.DAT ! name of locus file\n" "\n" "11 ! batch item number\n" "PEDIGREE.DAT ! name of pedigree file\n" "\n" "12 ! batch item number\n" "F ! symbol for female (case insensitive)\n" "M ! symbol for male (case insensitive)\n" "\n" "13 ! batch item number\n" "N ! is trait listed in locus and pedigree files?\n" "\n" "18 ! batch item number\n" "0 ! number of quantitative variables in pedigree file\n"); fclose(BATCH2); INFO("Finished successfully!"); }
yp/Heu-MCHC
pers-lib/m4ri/testsuite/test_solve.c
<filename>pers-lib/m4ri/testsuite/test_solve.c #include <stdlib.h> #include "m4ri/m4ri.h" int test_pluq_solve_left(size_t m, size_t n, size_t offsetA, size_t offsetB){ mzd_t* Abase = mzd_init(2048, 2048); mzd_t* Bbase = mzd_init(2048, 2048); mzd_randomize(Abase); mzd_randomize(Bbase); mzd_t* A = mzd_init_window(Abase, 0, offsetA, m, offsetA + m); mzd_t* B = mzd_init_window(Bbase, 0, offsetB, m, offsetB + n); size_t i,j; // copy B mzd_t* Bcopy = mzd_init(B->nrows, B->ncols); for ( i=0; i<B->nrows; ++i) for ( j=0; j<B->ncols; ++j) mzd_write_bit(Bcopy,i,j, mzd_read_bit (B,i,j)); for (i=0; i<m; ++i) { mzd_write_bit(A,i,i, 1); } mzd_t *Acopy = mzd_copy(NULL, A); size_t r = mzd_echelonize_m4ri(Acopy,0,0); printf("solve_left m: %4zu, n: %4zu, r: %4zu da: %2zu db: %2zu ",m, n, r, offsetA, offsetB); mzd_free(Acopy); Acopy = mzd_copy(NULL, A); mzd_solve_left(A, B, 0, 1); //copy B mzd_t *X = mzd_init(B->nrows,B->ncols); for ( i=0; i<B->nrows; ++i) for ( j=0; j<B->ncols; ++j) mzd_write_bit(X,i,j, mzd_read_bit (B,i,j)); mzd_t *B1 = mzd_mul(NULL, Acopy, X, 0); mzd_t *Z = mzd_add(NULL, Bcopy, B1); int status = 0; if(r==m) { for ( i=0; i<m; ++i) for ( j=0; j<n; ++j){ if (mzd_read_bit (Z,i,j)){ status = 1; } } if (!status) printf("passed\n"); else printf("FAILED\n"); } else { printf("check skipped r!=m\n"); } mzd_free(Bcopy); mzd_free(B1); mzd_free(Z); mzd_free_window(A); mzd_free_window(B); mzd_free(Acopy); mzd_free(Abase); mzd_free(Bbase); mzd_free(X); return status; } int main(int argc, char **argv) { int status = 0; status += test_pluq_solve_left( 2, 4, 0, 0); status += test_pluq_solve_left( 4, 1, 0, 0); status += test_pluq_solve_left( 10, 20, 0, 0); status += test_pluq_solve_left( 20, 1, 0, 0); status += test_pluq_solve_left( 20, 20, 0, 0); status += test_pluq_solve_left( 30, 1, 0, 0); status += test_pluq_solve_left( 30, 30, 0, 0); status += test_pluq_solve_left( 80, 1, 0, 0); status += test_pluq_solve_left( 80, 20, 0, 0); status += test_pluq_solve_left( 80, 80, 0, 0); status += test_pluq_solve_left( 2, 4, 0, 1); status += test_pluq_solve_left( 4, 1, 0, 1); status += test_pluq_solve_left( 10, 20, 0, 1); status += test_pluq_solve_left( 20, 1, 0, 1); status += test_pluq_solve_left( 20, 20, 0, 1); status += test_pluq_solve_left( 30, 1, 0, 1); status += test_pluq_solve_left( 30, 30, 0, 1); status += test_pluq_solve_left( 80, 1, 0, 1); status += test_pluq_solve_left( 80, 20, 0, 1); status += test_pluq_solve_left( 80, 80, 0, 1); status += test_pluq_solve_left( 2, 4, 0, 15); status += test_pluq_solve_left( 4, 1, 0, 15); status += test_pluq_solve_left( 10, 20, 0, 15); status += test_pluq_solve_left( 20, 1, 0, 15); status += test_pluq_solve_left( 20, 20, 0, 15); status += test_pluq_solve_left( 30, 1, 0, 15); status += test_pluq_solve_left( 30, 30, 0, 15); status += test_pluq_solve_left( 80, 1, 0, 15); status += test_pluq_solve_left( 80, 20, 0, 15); status += test_pluq_solve_left( 80, 80, 0, 15); /* status += test_pluq_solve_left (10, 20, 15, 0); */ /* status += test_pluq_solve_left (10, 80, 15, 0); */ /* status += test_pluq_solve_left (10, 20, 15, 20); */ /* status += test_pluq_solve_left (10, 80, 15, 20); */ /* status += test_pluq_solve_left (70, 20, 15, 0); */ /* status += test_pluq_solve_left (70, 80, 15, 0); */ /* status += test_pluq_solve_left (70, 20, 15, 20); */ /* status += test_pluq_solve_left (70, 80, 15, 20); */ /* status += test_pluq_solve_left (770, 1600, 75, 89); */ /* status += test_pluq_solve_left (1764, 1345, 198, 123); */ if (!status) { printf("All tests passed.\n"); } else { return 1; } return 0; }
yp/Heu-MCHC
pers-lib/m4ri/src/permutation.h
<reponame>yp/Heu-MCHC /** * \file permutation.h * * \brief Permutation matrices. * * \author <NAME> <<EMAIL>> * */ /****************************************************************************** * * M4RI: Linear Algebra over GF(2) * * Copyright (C) 2008 <NAME> <<EMAIL>> * * Distributed under the terms of the GNU General Public License (GPL) * version 2 or higher. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full text of the GPL is available at: * * http://www.gnu.org/licenses/ ******************************************************************************/ #ifndef PERMUTATION_H #define PERMUTATION_H #include "misc.h" #include "packedmatrix.h" /** * \brief Permutations. */ typedef struct { /** * The swap operations in LAPACK format. */ size_t *values; /** * The length of the swap array. */ size_t length; } mzp_t; // note that this is NOT mpz_t /** * Construct an identity permutation. * * \param length Length of the permutation. */ mzp_t *mzp_init(size_t length); /** * Free a mzp_t. * * \param P Permutation to free. */ void mzp_free(mzp_t *P); /** * \brief Create a window/view into the permutation P. * * Use mzp_free_mzp_t_window() to free the window. * * \param P Permutaiton matrix * \param begin Starting index (inclusive) * \param end Ending index (exclusive) * */ mzp_t *mzp_init_window(mzp_t* P, size_t begin, size_t end); /** * \brief Free a permutation window created with * mzp_init_mzp_t_window(). * * \param condemned Permutation Matrix */ void mzp_free_window(mzp_t* condemned); /** * \brief Set the permutation P to the identity permutation. The only * allowed value is 1. * * * \param P Permutation * \param value 1 * * \note This interface was chosen to be similar to mzd_set_ui(). */ void mzp_set_ui(mzp_t *P, unsigned int value); /** * Apply the permutation P to A from the left. * * This is equivalent to row swaps walking from 0 to length-1. * * \param A Matrix. * \param P Permutation. */ void mzd_apply_p_left(mzd_t *A, mzp_t *P); /** * Apply the permutation P to A from the left but transpose P before. * * This is equivalent to row swaps walking from length-1 to 0. * * \param A Matrix. * \param P Permutation. */ void mzd_apply_p_left_trans(mzd_t *A, mzp_t *P); /** * Apply the permutation P to A from the right. * * This is equivalent to column swaps walking from length-1 to 0. * * \param A Matrix. * \param P Permutation. */ void mzd_apply_p_right(mzd_t *A, mzp_t *P); /** * Apply the permutation P to A from the right but transpose P before. * * This is equivalent to column swaps walking from 0 to length-1. * * \param A Matrix. * \param P Permutation. */ void mzd_apply_p_right_trans(mzd_t *A, mzp_t *P); /** * Apply the permutation P to A from the right starting at start_row. * * This is equivalent to column swaps walking from length-1 to 0. * * \param A Matrix. * \param P Permutation. * \param start_row Start swapping at this row. * * \wordoffset */ void mzd_apply_p_right_even_capped(mzd_t *A, mzp_t *P, size_t start_row, size_t start_col); /** * Apply the permutation P^T to A from the right starting at start_row. * * This is equivalent to column swaps walking from 0 to length-1. * * \param A Matrix. * \param P Permutation. * \param start_row Start swapping at this row. * * \wordoffset */ void mzd_apply_p_right_trans_even_capped(mzd_t *A, mzp_t *P, size_t start_row, size_t start_col); /** * Apply the mzp_t P to A from the right but transpose P before. * * This is equivalent to column swaps walking from 0 to length-1. * * \param A Matrix. * \param P Permutation. */ void mzd_apply_p_right_trans(mzd_t *A, mzp_t *P); /** * Apply the permutation P to A from the right, but only on the lower * triangular part of the matrix A. * * This is equivalent to column swaps walking from length-1 to 0. * * \param A Matrix. * \param P Permutation. */ void mzd_apply_p_right_tri(mzd_t * A, mzp_t * Q); /* /\** */ /* * Rotate zero columns to the end. */ /* * */ /* * Given a matrix M with zero columns from zs up to ze (exclusive) and */ /* * nonzero columns from ze to de (excluse) with zs < ze < de rotate */ /* * the zero columns to the end such that the the nonzero block comes */ /* * before the zero block. */ /* * */ /* * \param M Matrix. */ /* * \param zs Start index of the zero columns. */ /* * \param ze End index of the zero columns (exclusive). */ /* * \param de End index of the nonzero columns (exclusive). */ /* * */ /* *\/ */ /* void mzd_col_block_rotate(mzd_t *M, size_t zs, size_t ze, size_t de) ; */ /** * Print the mzp_t P * * \param P Permutation. */ void mzp_print(mzp_t *P); #endif //PERMUTATION_H
yp/Heu-MCHC
pers-lib/m4ri/src/solve.c
/******************************************************************* * * M4RI: Linear Algebra over GF(2) * * Copyright (C) 2008 Jean-Guilla<EMAIL> * * Distributed under the terms of the GNU General Public License (GPL) * version 2 or higher. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full text of the GPL is available at: * * http://www.gnu.org/licenses/ * ********************************************************************/ #include "solve.h" #include "strassen.h" #include "lqup.h" #include "trsm.h" #include "permutation.h" void mzd_solve_left(mzd_t *A, mzd_t *B, const int cutoff, const int inconsistency_check) { if(A->ncols > B->nrows) m4ri_die("mzd_solve_left: A ncols (%d) need to be lower than B nrows (%d).\n", A->ncols, B->nrows); _mzd_solve_left (A, B, cutoff, inconsistency_check); } void mzd_pluq_solve_left (mzd_t *A, size_t rank, mzp_t *P, mzp_t *Q, mzd_t *B, const int cutoff, const int inconsistency_check) { if(A->ncols > B->nrows) m4ri_die("mzd_pluq_solve_left: A ncols (%d) need to be lower than B nrows (%d).\n", A->ncols, B->nrows); if(P->length != A->nrows) m4ri_die("mzd_pluq_solve_left: A nrows (%d) need to match P size (%d).\n", A->nrows, P->length); if(Q->length != A->ncols) m4ri_die("mzd_pluq_solve_left: A ncols (%d) need to match Q size (%d).\n", A->ncols, P->length); _mzd_pluq_solve_left (A, rank, P, Q, B, cutoff, inconsistency_check); } void _mzd_pluq_solve_left (mzd_t *A, size_t rank, mzp_t *P, mzp_t *Q, mzd_t *B, const int cutoff, const int inconsistency_check) { /** A is supposed to store L lower triangular and U upper triangular * B is modified in place * (Bi's in the comments are just modified versions of B) * PLUQ = A * 1) P B2 = B1 * 2) L B3 = B2 * 3) U B4 = B3 * 4) Q B5 = B4 */ /* P B2 = B1 or B2 = P^T B1*/ mzd_apply_p_left(B, P); /* L B3 = B2 */ /* view on the upper part of L */ mzd_t *LU = mzd_init_window(A,0,0,rank,rank); mzd_t *Y1 = mzd_init_window(B,0,0,rank,B->ncols); mzd_trsm_lower_left(LU, Y1, cutoff); if (inconsistency_check) { /* Check for inconsistency */ /** FASTER without this check * * update with the lower part of L */ mzd_t *H = mzd_init_window(A, rank, 0, A->nrows, rank); mzd_t *Y2 = mzd_init_window(B,rank,0,B->nrows,B->ncols); mzd_addmul(Y2, H, Y1, cutoff); /* * test whether Y2 is the zero matrix */ if( !mzd_is_zero(Y2) ) { //printf("inconsistent system of size %llu x %llu\n", Y2->nrows, Y2->ncols); //printf("Y2="); //mzd_print(Y2); } mzd_free_window(H); mzd_free_window(Y2); } /* U B4 = B3 */ mzd_trsm_upper_left(LU, Y1, cutoff); mzd_free_window(LU); mzd_free_window(Y1); if (!inconsistency_check) { /** Default is to set the indefined bits to zero * if inconsistency has been checked then * Y2 bits are already all zeroes * thus this clearing is not needed */ for(size_t i = rank; i<B->nrows; i++) { for(size_t j=0; j<B->ncols; j+=RADIX) { mzd_clear_bits(B, i, j, MIN(RADIX,B->ncols - j)); } } } /* Q B5 = B4 or B5 = Q^T B4*/ mzd_apply_p_right(B, Q); /* P L U Q B5 = B1 */ } void _mzd_solve_left (mzd_t *A, mzd_t *B, const int cutoff, const int inconsistency_check) { /** * B is modified in place * (Bi's in the comments are just modified versions of B) * 1) PLUQ = A * 2) P B2 = B1 * 3) L B3 = B2 * 4) U B4 = B3 * 5) Q B5 = B4 */ mzp_t * P = mzp_init(A->nrows); mzp_t * Q = mzp_init(A->ncols); /* PLUQ = A */ size_t rank = _mzd_pluq(A, P, Q, cutoff); /* 2, 3, 4, 5 */ mzd_pluq_solve_left(A, rank, P, Q, B, cutoff, inconsistency_check); mzp_free(P); mzp_free(Q); } mzd_t *mzd_kernel_left_pluq(mzd_t *A, const int cutoff) { mzp_t *P = mzp_init(A->nrows); mzp_t *Q = mzp_init(A->ncols); size_t r = mzd_pluq(A, P, Q, cutoff); if (r == A->ncols) { mzp_free(P); mzp_free(Q); return NULL; } mzd_t *U = mzd_init_window(A, 0, 0, r, r); mzd_t *B = mzd_init_window(A, 0, r, r, A->ncols); mzd_trsm_upper_left(U, B, cutoff); mzd_t *R = mzd_init(A->ncols, A->ncols - r); mzd_t *RU = mzd_init_window(R, 0, 0, r, R->ncols); mzd_copy(RU, B); for(size_t i=0;i<R->ncols;i++) { mzd_write_bit(R, r+i, i, 1); } mzd_apply_p_left_trans(R, Q); mzp_free(P); mzp_free(Q); mzd_free_window(RU); mzd_free_window(U); mzd_free_window(B); return R; }
yp/Heu-MCHC
pers-lib/m4ri/src/packedmatrix.c
<reponame>yp/Heu-MCHC /****************************************************************************** * * M4RI: Linear Algebra over GF(2) * * Copyright (C) 2007 <NAME> <<EMAIL>> * * Distributed under the terms of the GNU General Public License (GEL) * version 2 or higher. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full text of the GPL is available at: * * http://www.gnu.org/licenses/ ******************************************************************************/ #include <stdlib.h> #include <string.h> #include "packedmatrix.h" #include "parity.h" #define SAFECHAR (int)(RADIX+RADIX/3) void mzd_copy_row_weird_to_even(mzd_t* B, size_t i, const mzd_t* A, size_t j); mzd_t *mzd_init(size_t r, size_t c) { mzd_t *A; size_t i,j; A=(mzd_t *)m4ri_mmc_malloc(sizeof(mzd_t)); A->width=DIV_CEIL(c,RADIX); #ifdef HAVE_SSE2 int incw = 0; /* make sure each row is 16-byte aligned */ if (A->width & 1) { A->width++; incw = 1; } #endif A->ncols=c; A->nrows=r; A->offset = 0; A->rowperm= (size_t*)calloc( r, sizeof(size_t)); A->rows=(word **)m4ri_mmc_calloc( sizeof(word*), r+1); //we're overcomitting here if(r && c) { /* we allow more than one malloc call so he have to be a bit clever here */ for (i=0; i<r; ++i) A->rowperm[i]= i; const size_t bytes_per_row = A->width*sizeof(word); const size_t max_rows_per_block = MM_MAX_MALLOC/bytes_per_row; assert(max_rows_per_block); size_t rest = r % max_rows_per_block; size_t nblocks = (rest == 0) ? r / max_rows_per_block : r / max_rows_per_block + 1; A->blocks = (mmb_t*)m4ri_mmc_calloc(nblocks + 1, sizeof(mmb_t)); for(i=0; i<nblocks-1; i++) { A->blocks[i].size = MM_MAX_MALLOC; A->blocks[i].data = m4ri_mmc_calloc(MM_MAX_MALLOC,1); for(j=0; j<max_rows_per_block; j++) A->rows[max_rows_per_block*i + j] = ((word*)A->blocks[i].data) + j*A->width; } if(rest==0) rest = max_rows_per_block; A->blocks[nblocks-1].size = rest * bytes_per_row; A->blocks[nblocks-1].data = m4ri_mmc_calloc(rest, bytes_per_row); for(j=0; j<rest; j++) { A->rows[max_rows_per_block*(nblocks-1) + j] = (word*)(A->blocks[nblocks-1].data) + j*A->width; } } else { A->blocks = NULL; } #ifdef HAVE_SSE2 if (incw) { A->width--; } #endif return A; } mzd_t *mzd_init_window (const mzd_t *m, size_t lowr, size_t lowc, size_t highr, size_t highc) { size_t nrows, ncols, i, offset; mzd_t *window; window = (mzd_t *)m4ri_mmc_malloc(sizeof(mzd_t)); nrows = MIN(highr - lowr, m->nrows - lowr); ncols = highc - lowc; window->ncols = ncols; window->nrows = nrows; window->offset = (m->offset + lowc) % RADIX; offset = (m->offset + lowc) / RADIX; window->width = (window->offset + ncols) / RADIX; if ((window->offset + ncols) % RADIX) window->width++; window->blocks = NULL; if(nrows) window->rows = (word **)m4ri_mmc_calloc(sizeof(word*), nrows+1); else window->rows = NULL; for(i=0; i<nrows; i++) { window->rows[i] = m->rows[lowr + i] + offset; } window->rowperm= NULL; return window; } void mzd_free( mzd_t *A) { if(A->rows) m4ri_mmc_free(A->rows, (A->nrows+1) * sizeof(word*)); if(A->blocks) { size_t i; for(i=0; A->blocks[i].size; i++) { m4ri_mmc_free(A->blocks[i].data, A->blocks[i].size); } m4ri_mmc_free(A->blocks, (i+1) * sizeof(mmb_t)); } if (A->rowperm!=NULL) { free(A->rowperm); A->rowperm= NULL; } m4ri_mmc_free(A, sizeof(mzd_t)); } void mzd_print( const mzd_t *M ) { size_t i, j, wide; char temp[SAFECHAR]; word *row; for (i=0; i< M->nrows; i++ ) { printf("["); row = M->rows[i]; if(M->offset == 0) { for (j=0; j< M->width-1; j++) { m4ri_word_to_str(temp, row[j], 1); printf("%s ", temp); } row = row + M->width - 1; if(M->ncols%RADIX) wide = (size_t)M->ncols%RADIX; else wide = RADIX; for (j=0; j< wide; j++) { if (GET_BIT(*row, j)) printf("1"); else printf(" "); if (((j % 4)==3) && (j!=RADIX-1)) printf(":"); } } else { for (j=0; j< M->ncols; j++) { if(mzd_read_bit(M, i, j)) printf("1"); else printf(" "); if (((j % 4)==3) && (j!=RADIX-1)) printf(":"); } } printf("]\n"); } } void mzd_print_tight( const mzd_t *M ) { assert(M->offset == 0); size_t i, j; char temp[SAFECHAR]; word *row; for (i=0; i< M->nrows; i++ ) { printf("%5d [", M->rowperm[i]); row = M->rows[i]; for (j=0; j< M->ncols/RADIX; j++) { m4ri_word_to_str(temp, row[j], 0); printf("%s", temp); } row = row + M->width - 1; for (j=0; j< (int)(M->ncols%RADIX); j++) { printf("%d", (int)GET_BIT(*row, j)); } printf("]\n"); } } void mzd_row_add( mzd_t *m, size_t sourcerow, size_t destrow) { mzd_row_add_offset(m, destrow, sourcerow, 0); } int mzd_gauss_delayed(mzd_t *M, size_t startcol, int full) { assert(M->offset == 0); size_t i,j; size_t start; size_t startrow = startcol; size_t ii; size_t pivots = 0; for (i=startcol ; i<M->ncols ; i++) { for(j=startrow ; j < M->nrows; j++) { if (mzd_read_bit(M,j,i)) { mzd_row_swap(M,startrow,j); pivots++; if (full==TRUE) start=0; else start=startrow+1; for(ii=start ; ii < M->nrows ; ii++) { if (ii != startrow) { if (mzd_read_bit(M, ii, i)) { mzd_row_add_offset(M, ii, startrow, i); } } } startrow = startrow + 1; break; } } } return pivots; } int mzd_echelonize_naive(mzd_t *m, int full) { return mzd_gauss_delayed(m, 0, full); } /** * Transpose the 128 x 128-bit matrix inp and write the result in DST. */ static inline mzd_t *_mzd_transpose_direct_128(mzd_t *DST, const mzd_t *SRC) { assert(DST->offset==0); assert(SRC->offset==0); int j, k; word m, t[4]; /* we do one recursion level * [AB] -> [AC] * [CD] [BD] */ for(j=0; j<64; j++) { DST->rows[ j][0] = SRC->rows[ j][0]; //A DST->rows[64+j][0] = SRC->rows[ j][1]; //B DST->rows[ j][1] = SRC->rows[64+j][0]; //C DST->rows[64+j][1] = SRC->rows[64+j][1]; //D } /* now transpose each block A,B,C,D separately, cf. Hacker's Delight */ m = 0x00000000FFFFFFFFULL; for (j = 32; j != 0; j = j >> 1, m = m ^ (m << j)) { for (k = 0; k < 64; k = (k + j + 1) & ~j) { t[0] = (DST->rows[k][0] ^ (DST->rows[k+j][0] >> j)) & m; t[1] = (DST->rows[k][1] ^ (DST->rows[k+j][1] >> j)) & m; t[2] = (DST->rows[64+k][0] ^ (DST->rows[64+k+j][0] >> j)) & m; t[3] = (DST->rows[64+k][1] ^ (DST->rows[64+k+j][1] >> j)) & m; DST->rows[k][0] = DST->rows[k][0] ^ t[0]; DST->rows[k][1] = DST->rows[k][1] ^ t[1]; DST->rows[k+j][0] = DST->rows[k+j][0] ^ (t[0] << j); DST->rows[k+j][1] = DST->rows[k+j][1] ^ (t[1] << j); DST->rows[64+k][0] = DST->rows[64+k][0] ^ t[2]; DST->rows[64+k][1] = DST->rows[64+k][1] ^ t[3]; DST->rows[64+k+j][0] = DST->rows[64+k+j][0] ^ (t[2] << j); DST->rows[64+k+j][1] = DST->rows[64+k+j][1] ^ (t[3] << j); } } return DST; } static inline mzd_t *_mzd_transpose_direct(mzd_t *DST, const mzd_t *A) { size_t i,j,k, eol; word *temp; if(A->offset || DST->offset) { for(i=0; i<A->nrows; i++) { for(j=0; j<A->ncols; j++) { mzd_write_bit(DST, j, i, mzd_read_bit(A,i,j)); } } return DST; } if (A->nrows == 128 && A->ncols == 128 && RADIX == 64) { _mzd_transpose_direct_128(DST, A); return DST; } if(DST->ncols%RADIX) { eol = RADIX*(DST->width-1); } else { eol = RADIX*(DST->width); } for (i=0; i<DST->nrows; i++) { temp = DST->rows[i]; for (j=0; j < eol; j+=RADIX) { for (k=0; k<RADIX; k++) { *temp |= ((word)mzd_read_bit(A, j+k, i+A->offset))<<(RADIX-1-k); } temp++; } j = A->nrows - (A->nrows%RADIX); for (k=0; k<(size_t)(A->nrows%RADIX); k++) { *temp |= ((word)mzd_read_bit(A, j+k, i+A->offset))<<(RADIX-1-k); } } return DST; } static inline mzd_t *_mzd_transpose(mzd_t *DST, const mzd_t *X) { assert(X->offset == 0); const size_t nr = X->nrows; const size_t nc = X->ncols; const size_t cutoff = 128; // must be >= 128. if(nr <= cutoff || nc <= cutoff) { mzd_t *x = mzd_copy(NULL, X); _mzd_transpose_direct(DST, x); mzd_free(x); return DST; } /* we cut at multiples of 128 if possible, otherwise at multiples of 64 */ size_t nr2 = (X->nrows > 256) ? 2*RADIX*(X->nrows/(4*RADIX)) : RADIX*(X->nrows/(2*RADIX)); size_t nc2 = (X->ncols > 256) ? 2*RADIX*(X->ncols/(4*RADIX)) : RADIX*(X->ncols/(2*RADIX)); mzd_t *A = mzd_init_window(X, 0, 0, nr2, nc2); mzd_t *B = mzd_init_window(X, 0, nc2, nr2, nc); mzd_t *C = mzd_init_window(X, nr2, 0, nr, nc2); mzd_t *D = mzd_init_window(X, nr2, nc2, nr, nc); mzd_t *AT = mzd_init_window(DST, 0, 0, nc2, nr2); mzd_t *CT = mzd_init_window(DST, 0, nr2, nc2, nr); mzd_t *BT = mzd_init_window(DST, nc2, 0, nc, nr2); mzd_t *DT = mzd_init_window(DST, nc2, nr2, nc, nr); _mzd_transpose(AT, A); _mzd_transpose(BT, B); _mzd_transpose(CT, C); _mzd_transpose(DT, D); mzd_free_window(A); mzd_free_window(B); mzd_free_window(C); mzd_free_window(D); mzd_free_window(AT); mzd_free_window(CT); mzd_free_window(BT); mzd_free_window(DT); return DST; } mzd_t *mzd_transpose(mzd_t *DST, const mzd_t *A) { if (DST == NULL) { DST = mzd_init( A->ncols, A->nrows ); } else { if (DST->nrows != A->ncols || DST->ncols != A->nrows) { m4ri_die("mzd_transpose: Wrong size for return matrix.\n"); } } if(A->offset || DST->offset) return _mzd_transpose_direct(DST, A); else return _mzd_transpose(DST, A); } mzd_t *mzd_mul_naive(mzd_t *C, const mzd_t *A, const mzd_t *B) { if (C==NULL) { C=mzd_init(A->nrows, B->ncols); } else { if (C->nrows != A->nrows || C->ncols != B->ncols) { m4ri_die("mzd_mul_naive: Provided return matrix has wrong dimensions.\n"); } } if(B->ncols < RADIX-10) { /* this cutoff is rather arbitrary */ mzd_t *BT = mzd_transpose(NULL, B); _mzd_mul_naive(C, A, BT, 1); mzd_free (BT); } else { _mzd_mul_va(C, A, B, 1); } return C; } mzd_t *mzd_addmul_naive(mzd_t *C, const mzd_t *A, const mzd_t *B) { if (C->nrows != A->nrows || C->ncols != B->ncols) { m4ri_die("mzd_mul_naive: Provided return matrix has wrong dimensions.\n"); } if(B->ncols < RADIX-10) { /* this cutoff is rather arbitrary */ mzd_t *BT = mzd_transpose(NULL, B); _mzd_mul_naive(C, A, BT, 0); mzd_free (BT); } else { _mzd_mul_va(C, A, B, 0); } return C; } mzd_t *_mzd_mul_naive(mzd_t *C, const mzd_t *A, const mzd_t *B, const int clear) { assert(A->offset == 0); assert(B->offset == 0); assert(C->offset == 0); size_t i, j, k, ii, eol; word *a, *b, *c; if (clear) { for (i=0; i<C->nrows; i++) { for (j=0; j<C->width-1; j++) { C->rows[i][j] = 0; } C->rows[i][j] &= ~LEFT_BITMASK(C->ncols); } } if(C->ncols%RADIX) { eol = (C->width-1); } else { eol = (C->width); } word parity[64]; for (i=0; i<64; i++) { parity[i] = 0; } const size_t wide = A->width; const size_t blocksize = MZD_MUL_BLOCKSIZE; size_t start; for (start = 0; start + blocksize <= C->nrows; start += blocksize) { for (i=start; i<start+blocksize; i++) { a = A->rows[i]; c = C->rows[i]; for (j=0; j<RADIX*eol; j+=RADIX) { for (k=0; k<RADIX; k++) { b = B->rows[j+k]; parity[k] = a[0] & b[0]; for (ii=wide-1; ii>=1; ii--) parity[k] ^= a[ii] & b[ii]; } c[j/RADIX] ^= parity64(parity); } if (eol != C->width) { for (k=0; k<(int)(C->ncols%RADIX); k++) { b = B->rows[RADIX*eol+k]; parity[k] = a[0] & b[0]; for (ii=1; ii<A->width; ii++) parity[k] ^= a[ii] & b[ii]; } c[eol] ^= parity64(parity) & LEFT_BITMASK(C->ncols); } } } for (i=C->nrows - (C->nrows%blocksize); i<C->nrows; i++) { a = A->rows[i]; c = C->rows[i]; for (j=0; j<RADIX*eol; j+=RADIX) { for (k=0; k<RADIX; k++) { b = B->rows[j+k]; parity[k] = a[0] & b[0]; for (ii=wide-1; ii>=1; ii--) parity[k] ^= a[ii] & b[ii]; } c[j/RADIX] ^= parity64(parity); } if (eol != C->width) { for (k=0; k<(int)(C->ncols%RADIX); k++) { b = B->rows[RADIX*eol+k]; parity[k] = a[0] & b[0]; for (ii=1; ii<A->width; ii++) parity[k] ^= a[ii] & b[ii]; } c[eol] ^= parity64(parity) & LEFT_BITMASK(C->ncols); } } return C; } mzd_t *_mzd_mul_va(mzd_t *C, const mzd_t *v, const mzd_t *A, const int clear) { assert(C->offset == 0); assert(A->offset == 0); assert(v->offset == 0); if(clear) mzd_set_ui(C,0); size_t i,j; const size_t m=v->nrows; const size_t n=v->ncols; for(i=0; i<m; i++) for(j=0;j<n;j++) if (mzd_read_bit(v,i,j)) mzd_combine(C,i,0,C,i,0,A,j,0); return C; } void mzd_randomize(mzd_t *A) { size_t i, j; assert(A->offset == 0); for (i=0; i < A->nrows; i++) { for (j=0; j < A->ncols; j++) { mzd_write_bit(A, i, j, m4ri_coin_flip() ); } } } void mzd_set_ui( mzd_t *A, unsigned int value) { size_t i,j; size_t stop = MIN(A->nrows, A->ncols); word mask_begin = RIGHT_BITMASK(RADIX - A->offset); word mask_end = LEFT_BITMASK((A->offset + A->ncols)%RADIX); if(A->width==1) { for (i=0; i<A->nrows; i++) { for(j=0 ; j<A->ncols; j++) mzd_write_bit(A,i,j, 0); } } else { for (i=0; i<A->nrows; i++) { word *row = A->rows[i]; row[0] &= ~mask_begin; for(j=1 ; j<A->width-1; j++) row[j] = 0; row[A->width - 1] &= ~mask_end; } } if(value%2 == 0) return; for (i=0; i<stop; i++) { mzd_write_bit(A, i, i, 1); } } BIT mzd_equal(const mzd_t *A, const mzd_t *B) { assert(A->offset == 0); assert(B->offset == 0); size_t i, j; if (A->nrows != B->nrows) return FALSE; if (A->ncols != B->ncols) return FALSE; for (i=0; i< A->nrows; i++) { for (j=0; j< A->width; j++) { if (A->rows[i][j] != B->rows[i][j]) return FALSE; } } return TRUE; } int mzd_cmp(const mzd_t *A, const mzd_t *B) { assert(A->offset == 0); assert(B->offset == 0); size_t i,j; if(A->nrows < B->nrows) return -1; if(B->nrows < A->nrows) return 1; if(A->ncols < B->ncols) return -1; if(B->ncols < A->ncols) return 1; for(i=0; i < A->nrows ; i++) { for(j=0 ; j< A->width ; j++) { if ( A->rows[i][j] < B->rows[i][j] ) return -1; else if( A->rows[i][j] > B->rows[i][j] ) return 1; } } return 0; } mzd_t *mzd_copy(mzd_t *N, const mzd_t *P) { if (N == P) return N; if (!P->offset){ if (N == NULL) { N = mzd_init(P->nrows, P->ncols); } else { if (N->nrows < P->nrows || N->ncols < P->ncols) m4ri_die("mzd_copy: Target matrix is too small."); } size_t i, j; word *p_truerow, *n_truerow; const size_t wide = P->width-1; word mask = LEFT_BITMASK(P->ncols); for (i=0; i<P->nrows; i++) { p_truerow = P->rows[i]; n_truerow = N->rows[i]; for (j=0; j<wide; j++) { n_truerow[j] = p_truerow[j]; } n_truerow[wide] = (n_truerow[wide] & ~mask) | (p_truerow[wide] & mask); } } else { // P->offset > 0 if (N == NULL) { N = mzd_init(P->nrows, P->ncols+ P->offset); N->ncols -= P->offset; N->offset = P->offset; N->width=P->width; } else { if (N->nrows < P->nrows || N->ncols < P->ncols) m4ri_die("mzd_copy: Target matrix is too small."); } if(N->offset == P->offset) { for(size_t i=0; i<P->nrows; i++) { mzd_copy_row(N, i, P, i); } } else if(N->offset == 0) { for(size_t i=0; i<P->nrows; i++) { mzd_copy_row_weird_to_even(N, i, P, i); } } else { m4ri_die("mzd_copy: completely unaligned copy not implemented yet."); } } /* size_t i, j, p_truerow, n_truerow; */ /* /\** */ /* * \todo This is wrong */ /* *\/ */ /* int trailingdim = RADIX - P->ncols - P->offset; */ /* if (trailingdim >= 0) { */ /* // All columns fit in one word */ /* word mask = ((ONE << P->ncols) - 1) << trailingdim; */ /* for (i=0; i<P->nrows; i++) { */ /* p_truerow = P->rowswap[i]; */ /* n_truerow = N->rowswap[i]; */ /* N->values[n_truerow] = (N->values[n_truerow] & ~mask) | (P->values[p_truerow] & mask); */ /* } */ /* } else { */ /* int r = (P->ncols + P->offset) % RADIX; */ /* word mask_begin = RIGHT_BITMASK(RADIX - P->offset); */ /* word mask_end = LEFT_BITMASK(r); */ /* for (i=0; i<P->nrows; i++) { */ /* p_truerow = P->rowswap[i]; */ /* n_truerow = N->rowswap[i]; */ /* N->values[n_truerow] = (N->values[n_truerow] & ~mask_begin) | (P->values[p_truerow] & mask_begin); */ /* for (j=1; j<P->width-1; j++) { */ /* N->values[n_truerow + j] = P->values[p_truerow + j]; */ /* } */ /* N->values[n_truerow + j] = (N->values[n_truerow + j] & ~mask_end) | (P->values[p_truerow + j] & mask_end); */ /* } */ /* } */ return N; } /* This is sometimes called augment */ mzd_t *mzd_concat(mzd_t *C, const mzd_t *A, const mzd_t *B) { assert(A->offset == 0); assert(B->offset == 0); size_t i, j; word *src_truerow, *dst_truerow; if (A->nrows != B->nrows) { m4ri_die("mzd_concat: Bad arguments to concat!\n"); } if (C == NULL) { C = mzd_init(A->nrows, A->ncols + B->ncols); } else if (C->nrows != A->nrows || C->ncols != (A->ncols + B->ncols)) { m4ri_die("mzd_concat: C has wrong dimension!\n"); } for (i=0; i<A->nrows; i++) { dst_truerow = C->rows[i]; src_truerow = A->rows[i]; for (j=0; j <A->width; j++) { dst_truerow[j] = src_truerow[j]; } } for (i=0; i<B->nrows; i++) { for (j=0; j<B->ncols; j++) { mzd_write_bit(C, i, j+(A->ncols), mzd_read_bit(B, i, j) ); } } return C; } mzd_t *mzd_stack(mzd_t *C, const mzd_t *A, const mzd_t *B) { assert(A->offset == 0); assert(B->offset == 0); size_t i, j; word *src_truerow, *dst_truerow; if (A->ncols != B->ncols) { m4ri_die("mzd_stack: A->ncols (%d) != B->ncols (%d)!\n",A->ncols, B->ncols); } if (C == NULL) { C = mzd_init(A->nrows + B->nrows, A->ncols); } else if (C->nrows != (A->nrows + B->nrows) || C->ncols != A->ncols) { m4ri_die("mzd_stack: C has wrong dimension!\n"); } for(i=0; i<A->nrows; i++) { src_truerow = A->rows[i]; dst_truerow = C->rows[i]; for (j=0; j<A->width; j++) { dst_truerow[j] = src_truerow[j]; } } for(i=0; i<B->nrows; i++) { dst_truerow = C->rows[A->nrows + i]; src_truerow = B->rows[i]; for (j=0; j<B->width; j++) { dst_truerow[j] = src_truerow[j]; } } return C; } mzd_t *mzd_invert_naive(mzd_t *INV, mzd_t *A, const mzd_t *I) { assert(A->offset == 0); mzd_t *H; int x; H = mzd_concat(NULL, A, I); x = mzd_echelonize_naive(H, TRUE); if (x == FALSE) { mzd_free(H); return NULL; } INV = mzd_submatrix(INV, H, 0, A->ncols, A->nrows, A->ncols*2); mzd_free(H); return INV; } mzd_t *mzd_add(mzd_t *ret, const mzd_t *left, const mzd_t *right) { if (left->nrows != right->nrows || left->ncols != right->ncols) { m4ri_die("mzd_add: rows and columns must match.\n"); } if (ret == NULL) { ret = mzd_init(left->nrows, left->ncols); } else if (ret != left) { if (ret->nrows != left->nrows || ret->ncols != left->ncols) { m4ri_die("mzd_add: rows and columns of returned matrix must match.\n"); } } return _mzd_add(ret, left, right); } mzd_t *_mzd_add(mzd_t *C, const mzd_t *A, const mzd_t *B) { size_t i; size_t nrows = MIN(MIN(A->nrows, B->nrows), C->nrows); const mzd_t *tmp; if (C == B) { //swap tmp = A; A = B; B = tmp; } for(i=0; i<nrows; i++) { mzd_combine(C,i,0, A,i,0, B,i,0); } return C; } mzd_t *mzd_submatrix(mzd_t *S, const mzd_t *M, const size_t startrow, const size_t startcol, const size_t endrow, const size_t endcol) { size_t nrows, ncols, i, colword, x, y, block, spot, startword; word *truerow; word temp = 0; nrows = endrow - startrow; ncols = endcol - startcol; if (S == NULL) { S = mzd_init(nrows, ncols); } else if(S->nrows < nrows || S->ncols < ncols) { m4ri_die("mzd_submatrix: got S with dimension %d x %d but expected %d x %d\n",S->nrows,S->ncols,nrows,ncols); } assert(M->offset == S->offset); startword = (M->offset + startcol) / RADIX; /* we start at the beginning of a word */ if ((M->offset + startcol)%RADIX == 0) { if(ncols/RADIX) { for(x = startrow, i=0; i<nrows; i++, x++) { memcpy(S->rows[i], M->rows[x] + startword, 8*(ncols/RADIX)); } } if (ncols%RADIX) { for(x = startrow, i=0; i<nrows; i++, x++) { /* process remaining bits */ temp = M->rows[x][startword + ncols/RADIX] & LEFT_BITMASK(ncols); S->rows[i][ncols/RADIX] = temp; } } /* startcol is not the beginning of a word */ } else { spot = (M->offset + startcol) % RADIX; for(x = startrow, i=0; i<nrows; i++, x+=1) { truerow = M->rows[x]; /* process full words first */ for(colword=0; colword<(int)(ncols/RADIX); colword++) { block = colword + startword; temp = (truerow[block] << (spot)) | (truerow[block + 1] >> (RADIX-spot) ); S->rows[i][colword] = temp; } /* process remaining bits (lazy)*/ colword = ncols/RADIX; for (y=0; y < (int)(ncols%RADIX); y++) { temp = mzd_read_bit(M, x, startcol + colword*RADIX + y); mzd_write_bit(S, i, colword*RADIX + y, (BIT)temp); } } } return S; } void mzd_combine( mzd_t * C, const size_t c_row, const size_t c_startblock, const mzd_t * A, const size_t a_row, const size_t a_startblock, const mzd_t * B, const size_t b_row, const size_t b_startblock) { size_t i; if(C->offset || A->offset || B->offset) { /** * \todo this code is slow if offset!=0 */ for(i=0; i+RADIX<=A->ncols; i+=RADIX) { const word tmp = mzd_read_bits(A, a_row, i, RADIX) ^ mzd_read_bits(B, b_row, i, RADIX); for(size_t j=0; j<RADIX; j++) { mzd_write_bit(C, c_row, i*RADIX+j, GET_BIT(tmp, j)); } } for( ; i<A->ncols; i++) { mzd_write_bit(C, c_row, i, mzd_read_bit(A, a_row, i) ^ mzd_read_bit(B, b_row, i)); } return; } size_t wide = A->width - a_startblock; word *a = a_startblock + A->rows[a_row]; word *b = b_startblock + B->rows[b_row]; if( C == A && a_row == c_row && a_startblock == c_startblock) { #ifdef HAVE_SSE2 if(wide > SSE2_CUTOFF) { /** check alignments **/ if (ALIGNMENT(a,16)) { *a++ ^= *b++; wide--; } if (ALIGNMENT(a,16)==0 && ALIGNMENT(b,16)==0) { __m128i *a128 = (__m128i*)a; __m128i *b128 = (__m128i*)b; const __m128i *eof = (__m128i*)((unsigned long)(a + wide) & ~0xF); do { *a128 = _mm_xor_si128(*a128, *b128); ++b128; ++a128; } while(a128 < eof); a = (word*)a128; b = (word*)b128; wide = ((sizeof(word)*wide)%16)/sizeof(word); } } #endif //HAVE_SSE2 for(i=0; i < wide; i++) a[i] ^= b[i]; return; } else { /* C != A */ word *c = c_startblock + C->rows[c_row]; /* this is a corner case triggered by Strassen multiplication which assumes certain (virtual) matrix sizes */ if (a_row >= A->nrows) { for(i = 0; i<wide; i++) { c[i] = b[i]; } } else { #ifdef HAVE_SSE2 if(wide > SSE2_CUTOFF) { /** check alignments **/ if (ALIGNMENT(a,16)) { *c++ = *b++ ^ *a++; wide--; } if ((ALIGNMENT(b,16)==0) && (ALIGNMENT(c,16)==0)) { __m128i *a128 = (__m128i*)a; __m128i *b128 = (__m128i*)b; __m128i *c128 = (__m128i*)c; const __m128i *eof = (__m128i*)((unsigned long)(a + wide) & ~0xF); do { *c128 = _mm_xor_si128(*a128, *b128); ++c128; ++b128; ++a128; } while(a128 < eof); a = (word*)a128; b = (word*)b128; c = (word*)c128; wide = ((sizeof(word)*wide)%16)/sizeof(word); } } #endif //HAVE_SSE2 for(i = 0; i<wide; i++) { c[i] = a[i] ^ b[i]; } return; } } } void mzd_col_swap(mzd_t *M, const size_t cola, const size_t colb) { if (cola == colb) return; const size_t _cola = cola + M->offset; const size_t _colb = colb + M->offset; const size_t a_word = _cola/RADIX; const size_t b_word = _colb/RADIX; const size_t a_bit = _cola%RADIX; const size_t b_bit = _colb%RADIX; word a, b, *base; size_t i; if(a_word == b_word) { const word ai = RADIX - a_bit - 1; const word bi = RADIX - b_bit - 1; for (i=0; i<M->nrows; i++) { base = (M->rows[i] + a_word); register word b = *base; register word x = ((b >> ai) ^ (b >> bi)) & 1; // XOR temporary *base = b ^ ((x << ai) | (x << bi)); } return; } const word a_bm = (ONE<<(RADIX - (a_bit) - 1)); const word b_bm = (ONE<<(RADIX - (b_bit) - 1)); if(a_bit > b_bit) { const size_t offset = a_bit - b_bit; for (i=0; i<M->nrows; i++) { base = M->rows[i]; a = *(base + a_word); b = *(base + b_word); a ^= (b & b_bm) >> offset; b ^= (a & a_bm) << offset; a ^= (b & b_bm) >> offset; *(base + a_word) = a; *(base + b_word) = b; } } else { const size_t offset = b_bit - a_bit; for (i=0; i<M->nrows; i++) { base = M->rows[i]; a = *(base + a_word); b = *(base + b_word); a ^= (b & b_bm) << offset; b ^= (a & a_bm) >> offset; a ^= (b & b_bm) << offset; *(base + a_word) = a; *(base + b_word) = b; } } } int mzd_is_zero(mzd_t *A) { /* Could be improved: stopping as the first non zero value is found (status!=0)*/ size_t mb = A->nrows; size_t nb = A->ncols; size_t Aoffset = A->offset; size_t nbrest = (nb + Aoffset) % RADIX; word status=0; if (nb + Aoffset >= RADIX) { // Large A word mask_begin = RIGHT_BITMASK(RADIX-Aoffset); if (Aoffset == 0) mask_begin = ~mask_begin; word mask_end = LEFT_BITMASK(nbrest); size_t i; for (i=0; i<mb; ++i) { status |= A->rows[i][0] & mask_begin; size_t j; for ( j = 1; j < A->width-1; ++j) status |= A->rows[i][j]; status |= A->rows[i][A->width - 1] & mask_end; } } else { // Small A word mask = LEFT_BITMASK(nb); size_t i; for (i=0; i < mb; ++i) { status |= A->rows[i][0] & mask; } } return (int)(!status); } void mzd_copy_row_weird_to_even(mzd_t* B, size_t i, const mzd_t* A, size_t j) { assert(B->offset == 0); assert(B->ncols >= A->ncols); word *b = B->rows[j]; size_t c; size_t rest = A->ncols%RADIX; for(c = 0; c+RADIX <= A->ncols; c+=RADIX) { b[c/RADIX] = mzd_read_bits(A, i, c, RADIX); } if (rest) { const word temp = mzd_read_bits(A, i, c, rest); b[c/RADIX] &= LEFT_BITMASK(RADIX-rest); b[c/RADIX] |= temp<<(RADIX-rest); } } void mzd_copy_row(mzd_t* B, size_t i, const mzd_t* A, size_t j) { assert(B->offset == A->offset); assert(B->ncols >= A->ncols); size_t k; const size_t width= MIN(B->width, A->width) - 1; word* a = A->rows[j]; word* b = B->rows[i]; word mask_begin = RIGHT_BITMASK(RADIX - A->offset); word mask_end = LEFT_BITMASK( (A->offset + A->ncols)%RADIX ); if (width != 0) { b[0] = (b[0] & ~mask_begin) | (a[0] & mask_begin); for(k = 1; k<width; k++) b[k] = a[k]; b[width] = (b[width] & ~mask_end) | (a[width] & mask_end); } else { b[0] = (b[0] & ~mask_begin) | (a[0] & mask_begin & mask_end) | (b[0] & ~mask_end); } } void mzd_row_clear_offset(mzd_t *M, size_t row, size_t coloffset) { coloffset += M->offset; size_t startblock= coloffset/RADIX; size_t i; word temp; /* make sure to start clearing at coloffset */ if (coloffset%RADIX) { temp = M->rows[row][startblock]; temp &= RIGHT_BITMASK(RADIX - coloffset); } else { temp = 0; } M->rows[row][startblock] = temp; temp=0; for ( i=startblock+1; i < M->width; i++ ) { M->rows[row][i] = temp; } } int mzd_find_pivot(mzd_t *A, size_t start_row, size_t start_col, size_t *r, size_t *c) { assert(A->offset == 0); register size_t i = start_row; register size_t j = start_col; const size_t nrows = A->nrows; const size_t ncols = A->ncols; size_t row_candidate = 0; word data = 0; if(A->ncols - start_col < RADIX) { for(j=start_col; j<A->ncols; j+=RADIX) { const size_t length = MIN(RADIX, ncols-j); for(i=start_row; i<nrows; i++) { const word curr_data = (word)mzd_read_bits(A, i, j, length); if (curr_data > data && leftmost_bit(curr_data) > leftmost_bit(data)) { row_candidate = i; data = curr_data; if(GET_BIT(data,RADIX-length-1)) break; } } if(data) { i = row_candidate; data <<=(RADIX-length); for(size_t l=0; l<length; l++) { if(GET_BIT(data, l)) { j+=l; break; } } *r = i, *c = j; return 1; } } } else { /* we definitely have more than one word */ /* handle first word */ const size_t bit_offset = (start_col % RADIX); const size_t word_offset = start_col / RADIX; const word mask_begin = RIGHT_BITMASK(RADIX-bit_offset); for(i=start_row; i<nrows; i++) { const word curr_data = A->rows[i][word_offset] & mask_begin; if (curr_data > data && leftmost_bit(curr_data) > leftmost_bit(data)) { row_candidate = i; data = curr_data; if(GET_BIT(data,bit_offset)) { break; } } } if(data) { i = row_candidate; data <<=bit_offset; for(size_t l=0; l<(RADIX-bit_offset); l++) { if(GET_BIT(data, l)) { j+=l; break; } } *r = i, *c = j; return 1; } /* handle complete words */ for(j=word_offset + 1; j<A->width - 1; j++) { for(i=start_row; i<nrows; i++) { const word curr_data = A->rows[i][j]; if (curr_data > data && leftmost_bit(curr_data) > leftmost_bit(data)) { row_candidate = i; data = curr_data; if(GET_BIT(data, 0)) break; } } if(data) { i = row_candidate; for(size_t l=0; l<RADIX; l++) { if(GET_BIT(data, l)) { j=j*RADIX + l; break; } } *r = i, *c = j; return 1; } } /* handle last word */ const size_t end_offset = A->ncols % RADIX ? (A->ncols%RADIX) : RADIX; const word mask_end = LEFT_BITMASK(end_offset); j = A->width-1; for(i=start_row; i<nrows; i++) { const word curr_data = A->rows[i][j] & mask_end; if (curr_data > data && leftmost_bit(curr_data) > leftmost_bit(data)) { row_candidate = i; data = curr_data; if(GET_BIT(data,0)) break; } } if(data) { i = row_candidate; for(size_t l=0; l<end_offset; l++) { if(GET_BIT(data, l)) { j=j*RADIX+l; break; } } *r = i, *c = j; return 1; } } return 0; } #define MASK(c) (((word)(-1)) / (TWOPOW(TWOPOW(c)) + ONE)) #define COUNT(x,c) ((x) & MASK(c)) + (((x) >> (TWOPOW(c))) & MASK(c)) static inline int m4ri_bitcount(word n) { n = COUNT(n, 0); n = COUNT(n, 1); n = COUNT(n, 2); n = COUNT(n, 3); n = COUNT(n, 4); n = COUNT(n, 5); return (int)n; } double mzd_density(mzd_t *A, int res) { long count = 0; long total = 0; if(res == 0) res = (int)(A->width/100.0); if (res < 1) res = 1; if(A->width == 1) { for(size_t i=0; i<A->nrows; i++) for(size_t j=0; j<A->ncols; j++) if(mzd_read_bit(A, i, j)) count++; return ((double)count)/(A->ncols * A->nrows); } else { for(size_t i=0; i<A->nrows; i++) { word *truerow = A->rows[i]; for(size_t j = A->offset; j<RADIX; j++) if(mzd_read_bit(A, i, j)) count++; total += (long)RADIX - A->offset; for(size_t j=1; j<A->width-1; j+=res) { count += m4ri_bitcount(truerow[j]); total += RADIX; } for(size_t j = 0; j < (A->offset + A->ncols)%RADIX; j++) if(mzd_read_bit(A, i, j)) count++; total += (A->offset + A->ncols)%RADIX; } } return ((double)count)/(total); } size_t mzd_first_zero_row(mzd_t *A) { word mask_begin = RIGHT_BITMASK(RADIX-A->offset); word mask_end = LEFT_BITMASK((A->ncols + A->offset)%RADIX); const size_t end = A->width - 1; word *row; for(long i = A->nrows - 1; i>=0; i--) { word tmp = 0; row = A->rows[i]; tmp |= row[0] & mask_begin; for (size_t j = 1; j < end; ++j) tmp |= row[j]; tmp |= row[end] & mask_end; if(tmp) return i+1; } return 0; }
yp/Heu-MCHC
src/gen-ped-IO.c
<reponame>yp/Heu-MCHC /** * * * Heu-MCHC * * A fast and accurate heuristic algorithm for the haplotype inference * problem on pedigree data with recombinations and mutations * * Copyright (C) 2009,2010,2011 <NAME> * * Distributed under the terms of the GNU General Public License (GPL) * * * This file is part of Heu-MCHC. * * Heu-MCHC is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Heu-MCHC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Heu-MCHC. If not, see <http://www.gnu.org/licenses/>. * **/ #include "gen-ped-IO.h" #include "util.h" #include "log.h" #include <string.h> #include <stdlib.h> /** * Read a file with the following structure: * n_loci * n_indiv * gen_1 * gen_2 * ... * gen_n * id_father id_mother id_children * ... * id_father id_mother id_children * * It ignores any row starting with a "#". **/ #define LEN_BUFFER 10001 pindiv indiv_create(const int n_loci, const int n_individuals) { my_assert(n_loci>0); my_assert(n_individuals>0); pindiv pi= PALLOC(struct _indiv); pi->id= -1; pi->fi= pi->mi= -1; pi->f= pi->m= NULL; pi->g= NPALLOC(int, n_loci); _SET_VECTOR(pi->g, 0, n_loci); pi->p= NPALLOC(int, n_loci); _SET_VECTOR(pi->p, 0, n_loci); pi->df= NPALLOC(int, n_loci); _SET_VECTOR(pi->df, 0, n_loci); pi->dm= NPALLOC(int, n_loci); _SET_VECTOR(pi->dm, 0, n_loci); pi->rf= NPALLOC(int, n_loci); _SET_VECTOR(pi->rf, 0, n_loci); pi->rm= NPALLOC(int, n_loci); _SET_VECTOR(pi->rm, 0, n_loci); pi->h_f= pi->h_m= -1; pi->hv_f= NPALLOC(int, n_loci); _SET_VECTOR(pi->hv_f, -1, n_loci); pi->hv_m= NPALLOC(int, n_loci); _SET_VECTOR(pi->hv_m, -1, n_loci); pi->n_children= 0; pi->children= NPALLOC(pindiv, n_individuals); _SET_VECTOR(pi->children, NULL, n_individuals); return pi; } void indiv_destroy(pindiv pi) { my_assert(pi!=NULL); pfree(pi->g); pfree(pi->p); pfree(pi->df); pfree(pi->dm); pfree(pi->rf); pfree(pi->rm); pfree(pi->hv_f); pfree(pi->hv_m); pfree(pi->children); pfree(pi); } pgenped gp_create(const int n_loci, const int n_individuals) { my_assert(n_loci>0); my_assert(n_individuals>0); pgenped gp= PALLOC(struct _genped); gp->n_loci= n_loci; gp->n_indiv= n_individuals; gp->individuals= NPALLOC(pindiv, n_individuals); for (int i= 0; i<n_individuals; ++i) { gp->individuals[i]=indiv_create(n_loci, n_individuals); gp->individuals[i]->id= i; } return gp; } static pindiv indiv_copy(pindiv src, const unsigned int n_loci, const unsigned int n_individuals) { pindiv ris= indiv_create(n_loci, n_individuals); ris->id= src->id; ris->f= src->f; ris->m= src->m; ris->fi= src->fi; ris->mi= src->mi; ris->h_f= src->h_f; ris->h_m= src->h_m; ris->n_children= src->n_children; for (unsigned int i= 0; i<n_loci; ++i) { ris->g[i]= src->g[i]; ris->p[i]= src->p[i]; ris->df[i]= src->df[i]; ris->dm[i]= src->dm[i]; ris->rf[i]= src->rf[i]; ris->rm[i]= src->rm[i]; ris->hv_f[i]= src->hv_f[i]; ris->hv_m[i]= src->hv_m[i]; } for (unsigned int i= 0; i<ris->n_children; ++i) { ris->children[i]= src->children[i]; } return ris; } pgenped gp_copy(pgenped src) { pgenped ris= PALLOC(struct _genped); ris->n_loci= src->n_loci; ris->n_indiv= src->n_indiv; ris->individuals= NPALLOC(pindiv, src->n_indiv); for (unsigned int i= 0; i<src->n_indiv; ++i) { ris->individuals[i]= indiv_copy(src->individuals[i], src->n_loci, src->n_indiv); } for (unsigned int i= 0; i<src->n_indiv; ++i) { pindiv const c= ris->individuals[i]; if (c->fi>=0) c->f= ris->individuals[c->fi]; if (c->mi>=0) c->m= ris->individuals[c->mi]; for (unsigned int j= 0; j<c->n_children; ++j) { c->children[j]= ris->individuals[c->children[j]->id]; } } return ris; } void gp_destroy(pgenped gp) { my_assert(gp!=NULL); for (unsigned int i= 0; i<gp->n_indiv; ++i) { indiv_destroy(gp->individuals[i]); } pfree(gp->individuals); pfree(gp); } void gp_add_trio(pgenped gp, const unsigned int fi, const unsigned int mi, const unsigned int ci) { my_assert(gp!=NULL); assert_ulim(fi, gp->n_indiv); assert_ulim(mi, gp->n_indiv); assert_ulim(ci, gp->n_indiv); pindiv f= gp->individuals[fi]; pindiv m= gp->individuals[mi]; pindiv c= gp->individuals[ci]; c->fi= fi; c->f= f; c->mi= mi; c->m= m; f->children[f->n_children]= c; f->n_children++; m->children[m->n_children]= c; m->n_children++; } static int char2gen(const char g) { switch (g) { case '0': return 0; case '1': return 1; case '2': return 2; default: ERROR("Read an invalid genotype symbol >%c<. Terminating.", g); fail(); } } pgenped gp_read_from_file(FILE* fin) { my_assert(fin!=NULL); int row= 0; int n_loci; int n_indiv; size_t size= LEN_BUFFER; char * BUFF= c_palloc(size); int len; bool read_n_loci= false; bool read_n_indiv= false; while (!read_n_loci) { len= my_getline(&BUFF, &size, fin); ++row; if (len>0 && BUFF[0]!='#') { read_n_loci= sscanf(BUFF, "%d", &n_loci) > 0 && n_loci>0; } } while (!read_n_indiv) { len= my_getline(&BUFF, &size, fin); ++row; if (len>0 && BUFF[0]!='#') { read_n_indiv= sscanf(BUFF, "%d", &n_indiv) > 0 && n_indiv>0; } } DEBUG("The genotyped pedigree has %d loci and %d individuals.", n_loci, n_indiv); pgenped gp= gp_create(n_loci, n_indiv); // Reading the genotypes int i= 0; while (i<n_indiv) { len= my_getline(&BUFF, &size, fin); ++row; if (len>0 && BUFF[0]!='#') { if (len!=n_loci) { ERROR("Read a genotype at line %d with a number of characters different to the number of loci. Read >%s<.", row, BUFF); ERROR("Terminating."); fail(); } else { for (int j= 0; j<n_loci; ++j) { gp->individuals[i]->g[j]= char2gen(BUFF[j]); } ++i; } } } while (!feof(fin)) { len= my_getline(&BUFF, &size, fin); ++row; if (len>0 && BUFF[0]!='#') { int fi, mi, ci; int el= sscanf(BUFF, "%d %d %d", &fi, &mi, &ci); if (el<3) { ERROR("The trio read at line %d is invalid. Read >%s<. Terminating.", row, BUFF); fail(); } else { gp_add_trio(gp, fi, mi, ci); TRACE("Added trio (F, M, C)= (%4d, %4d, %4d).", fi, mi, ci); } } } pfree(BUFF); return gp; } #undef LEN_BUFFER
gabrieloliva/GOStack
GOStack/GOStack.h
// // GOStack.h // GOStackExample // // Created by <NAME> on 28/02/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "GOStackCell.h" @interface GOStack : NSObject @property (nonatomic, strong, readonly) GOStackCell *top; @property (nonatomic, assign, readonly) int numberOfElements; // Check if the stack is empty - (BOOL)isEmpty; // Inserts a new element on the top of the stack - (void)push:(id)item; // Remove and returns the item from the top of the stack - (id)pop; // Check if the stack contains the item - (BOOL)contains:(id)item; // Inserts a new element on the bottom of the stack - (void)insertAtBottom:(id)item; // Returns the number of items in stack - (int)numberOfElementsInStack; @end
gabrieloliva/GOStack
GOStack/GOStackCell.h
<gh_stars>1-10 // // GOStackCell.h // GOStackExample // // Created by <NAME> on 28/02/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "GOStackCell.h" @interface GOStackCell : NSObject @property (nonatomic, strong) id item; // Value of the cell @property (nonatomic, strong) GOStackCell *nextCell; // Next cell that is referenced // Constructor class - (id)init; - (id)initWithItem:(id)item; - (id)initWithItem:(id)item andNextCell:(GOStackCell *)cell; @end
gabrieloliva/GOStack
GOStack/NSMutableArray+GOStack.h
<gh_stars>1-10 // // NSMutableArray+GOStack.h // GOStackExample // // Created by <NAME> on 28/02/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "GOStack.h" @interface NSMutableArray (GOStack) - (id)initWithGOStack:(GOStack *)stack; @end
gabrieloliva/GOStack
GOStackExample/GOStackExample/AppDelegate.h
<reponame>gabrieloliva/GOStack // // AppDelegate.h // GOStackExample // // Created by <NAME> on 28/02/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
gabrieloliva/GOStack
GOStackExample/GOStackExample/ViewController.h
// // ViewController.h // GOStackExample // // Created by <NAME> on 28/02/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/Pods-SpriteKitUniversalMenus-Mac/Pods-SpriteKitUniversalMenus-Mac-umbrella.h
<gh_stars>10-100 #import <Cocoa/Cocoa.h> FOUNDATION_EXPORT double Pods_SpriteKitUniversalMenus_MacVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SpriteKitUniversalMenus_MacVersionString[];
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/Pods-SpriteKitUniversalMenus_Tests-iOS/Pods-SpriteKitUniversalMenus_Tests-iOS-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SpriteKitUniversalMenus_Tests_iOSVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SpriteKitUniversalMenus_Tests_iOSVersionString[];
Dzamir/SpriteKitUniversalVerticalMenus
Example/SpriteKitUniversalMenus-tvOS/GameViewController.h
// // GameViewController.h // SpriteKitUniversalMenus-tvOS // // Copyright (c) 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @import SpriteKit; @import GameController; @interface GameViewController : GCEventViewController @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/SpriteKitUniversalMenus-OSX/SpriteKitUniversalMenus-OSX-umbrella.h
#import <Cocoa/Cocoa.h> #import "Bridges.h" #import "Directions.h" #import "DZAControlInputDirection.h" #import "DZAMenuNode.h" #import "DZAMenuVoiceNode.h" FOUNDATION_EXPORT double SpriteKitUniversalMenusVersionNumber; FOUNDATION_EXPORT const unsigned char SpriteKitUniversalMenusVersionString[];
Dzamir/SpriteKitUniversalVerticalMenus
Example/SpriteKiUniversalMenus-Mac/AppDelegate.h
// // AppDelegate.h // SpriteKiUniversalMenus-Mac // // Created by <NAME> on 08/01/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <Cocoa/Cocoa.h> @interface AppDelegate : NSObject <NSApplicationDelegate> @end
Dzamir/SpriteKitUniversalVerticalMenus
Pod/Classes/DZAMenuVoiceNode.h
// // DZAMenuVoiceNode.h // Based on AGSpriteButton // // Created by <NAME> on 18/06/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <SpriteKit/SpriteKit.h> #import "Bridges.h" #import "Directions.h" typedef NS_OPTIONS(NSInteger, AGButtonControlEvent) { AGButtonControlEventTouchDown = 1, //When button is held down. AGButtonControlEventTouchUp, //When button is released. AGButtonControlEventTouchUpInside, //When button is tapped. AGButtonControlEventAllEvents, //Convenience event for deletion of selector, block or actio }; @interface DZAMenuVoiceNode : SKSpriteNode @property (setter = setExclusiveTouch:, getter = isExclusiveTouch) BOOL exclusiveTouch; @property (strong, nonatomic) SKLabelNode *label; @property (readonly, nonatomic) CGPoint originalPosition; @property (readwrite, nonatomic) int tag; //CLASS METHODS FOR CREATING BUTTON +(instancetype)buttonWithImageNamed:(NSString*)image; +(instancetype)buttonWithColor:(SKColor*)color andSize:(CGSize)size; +(instancetype)buttonWithTexture:(SKTexture*)texture andSize:(CGSize)size; +(instancetype)buttonWithTexture:(SKTexture *)texture; -(instancetype)initWithImageNamed:(NSString *)name; -(instancetype)initWithColor:(SKColor *)color size:(CGSize)size; -(instancetype)initWithTexture:(SKTexture *)texture color:(SKColor *)color size:(CGSize)size; -(instancetype)initWithTexture:(SKTexture *)texture; -(id)init; //LABEL METHOD -(void)setLabelWithText:(NSString*)text andFont:(DZAFont*)font withColor:(SKColor*)fontColor; //TARGET HANDLER METHODS (Similar to UIButton) -(void)addTarget:(id)target selector:(SEL)selector withObject:(id)object forControlEvent:(AGButtonControlEvent)controlEvent; -(void)removeTarget:(id)target selector:(SEL)selector forControlEvent:(AGButtonControlEvent)controlEvent; -(void)removeAllTargets; //EXECUTE BLOCKS ON EVENTS -(void)performBlock:(void (^)())block onEvent:(AGButtonControlEvent)event; //EXECUTE ACTIONS ON EVENTS -(void)performAction:(SKAction*)action onNode:(SKNode*)object withEvent:(AGButtonControlEvent)event; //Set animation actions for touchDown and touchUp -(void)setTouchDownAction:(SKAction*)action; -(void)setTouchUpAction:(SKAction*)action; //Explicit Transform method. Call these methods to transform the button using code. -(void)transformForTouchDown; -(void)transformForTouchUp; -(void) forceTouchUpInside; @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/SpriteKitUniversalMenus-iOS/DZAAppDelegate.h
// // DZAAppDelegate.h // SpriteKitUniversalVerticalMenus // // Created by <NAME> on 01/04/2016. // Copyright (c) 2016 <NAME>. All rights reserved. // @import UIKit; @interface DZAAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/Pods-SpriteKitUniversalMenus-iOS/Pods-SpriteKitUniversalMenus-iOS-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SpriteKitUniversalMenus_iOSVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SpriteKitUniversalMenus_iOSVersionString[];
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/Pods-SpriteKitUniversalMenus-tvOS/Pods-SpriteKitUniversalMenus-tvOS-umbrella.h
<reponame>Dzamir/SpriteKitUniversalVerticalMenus #import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SpriteKitUniversalMenus_tvOSVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SpriteKitUniversalMenus_tvOSVersionString[];
Dzamir/SpriteKitUniversalVerticalMenus
Pod/Classes/Bridges.h
<filename>Pod/Classes/Bridges.h // // Bridges.h // Pods // // Created by <NAME> on 09/01/16. // // #ifndef Bridges_h #define Bridges_h #if TARGET_OS_IPHONE #define DZAFont UIFont #define DZATouch UITouch #define DZAColor UIColor #define DZATapGestureRecognizer UITapGestureRecognizer #define DZAPanGestureRecognizer UIPanGestureRecognizer #define DZAGestureRecognizerStateBegan UIGestureRecognizerStateBegan #define DZAGestureRecognizerStateChanged UIGestureRecognizerStateChanged #else #define UIFont NSFont #define DZAFont NSFont #define DZATouch NSTouch #define DZAColor NSColor #define DZATapGestureRecognizer NSClickGestureRecognizer #define DZAPanGestureRecognizer NSPanGestureRecognizer #define DZAGestureRecognizerStateBegan NSGestureRecognizerStateBegan #define DZAGestureRecognizerStateChanged NSGestureRecognizerStateChanged #endif #endif /* Bridges_h */
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/Pods-SpriteKitUniversalMenus-tvOSUITests/Pods-SpriteKitUniversalMenus-tvOSUITests-umbrella.h
<gh_stars>10-100 #import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_SpriteKitUniversalMenus_tvOSUITestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SpriteKitUniversalMenus_tvOSUITestsVersionString[];
Dzamir/SpriteKitUniversalVerticalMenus
Pod/Classes/DZAControlInputDirection.h
// // ControlInputDirection.h // Sbindulin // // Created by <NAME> on 18/10/15. // Copyright © 2015 Dzamir. All rights reserved. // #import <Foundation/Foundation.h> #import <simd/simd.h> typedef enum : NSUInteger { DZAControlInputDirectionUp, DZAControlInputDirectionDown, DZAControlInputDirectionLeft, DZAControlInputDirectionRight, DZAControlInputDirectionNone } DZAControlInputDirectionEnum; @interface DZAControlInputDirection : NSObject -(id) initWithVector:(vector_float2) vector; @property (readwrite, nonatomic) DZAControlInputDirectionEnum controlInputDirectionEnum; @property (readwrite, nonatomic) vector_float2 vector; @end
Dzamir/SpriteKitUniversalVerticalMenus
Pod/Classes/DZAMenuNode.h
// // DZAMenuNode.h // Pods // // Created by <NAME> on 06/01/16. // // @import SpriteKit; @import GameController; #import "DZAMenuVoiceNode.h" #define THREESHOLD 10.0f @class DZAMenuNode; @protocol DZAMenuNodeDelegate <NSObject> // for tvOS: menu button pressed // for macOS: esc button pressed // for iOS you will need to add a button into your scene to map the back action -(void) menuNodeDidPressBack:(DZAMenuNode *) menuNode; @end @interface DZAMenuNode : SKNode @property (readwrite, nonatomic) DZAMenuAxis allowedAxis; @property (weak, nonatomic) id<DZAMenuNodeDelegate> delegate; //@property (strong, nonatomic) NSMutableArray * menuVoices; @property (strong, nonatomic) DZAMenuVoiceNode * currentMenuVoice; // sound to use when a menu is selected on tvOS @property (strong, nonatomic) NSString * selectSoundName; // sound to use when a menu is opened on tvOS @property (strong, nonatomic) NSString * openSoundName; // set to NO to disable input processing for this menu @property (readwrite, nonatomic) BOOL enabled; // call this method after adding all the DZAMenuVoiceNode objects as child nodes -(void) reloadMenu; -(DZAMenuVoiceNode *) moveSelection:(DZAMenuDirection) direction; -(void) pressSelection; -(void) setupGameController:(GCController *) controller; @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/SpriteKitUniversalMenus-iOS/DZAViewController.h
<reponame>Dzamir/SpriteKitUniversalVerticalMenus // // DZAViewController.h // SpriteKitUniversalVerticalMenus // // Created by <NAME> on 01/04/2016. // Copyright (c) 2016 <NAME>. All rights reserved. // @import UIKit; @interface DZAViewController : UIViewController @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/SpriteKitUniversalMenus-tvOS/SpriteKitUniversalMenus-tvOS-umbrella.h
<filename>Example/Pods/Target Support Files/SpriteKitUniversalMenus-tvOS/SpriteKitUniversalMenus-tvOS-umbrella.h #import <UIKit/UIKit.h> #import "Bridges.h" #import "Directions.h" #import "DZAControlInputDirection.h" #import "DZAMenuNode.h" #import "DZAMenuVoiceNode.h" FOUNDATION_EXPORT double SpriteKitUniversalMenusVersionNumber; FOUNDATION_EXPORT const unsigned char SpriteKitUniversalMenusVersionString[];
Dzamir/SpriteKitUniversalVerticalMenus
Example/SpriteKiUniversalMenus-Mac/ViewController.h
<filename>Example/SpriteKiUniversalMenus-Mac/ViewController.h // // ViewController.h // SpriteKiUniversalMenus-Mac // // Created by <NAME> on 08/01/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <Cocoa/Cocoa.h> @interface ViewController : NSViewController @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/SpriteKitUniversalMenus-Shared/DZASpriteKitMenuScene.h
// // DZASpriteKitMenuView.h // SpriteKitUniversalVerticalMenus // // Created by <NAME> on 05/01/16. // Copyright © 2016 <NAME>. All rights reserved. // @import SpriteKit; @import GameController; @interface DZASpriteKitMenuScene : SKScene @end
Dzamir/SpriteKitUniversalVerticalMenus
Example/SpriteKitUniversalMenus-tvOS/GameScene.h
<reponame>Dzamir/SpriteKitUniversalVerticalMenus // // GameScene.h // SpriteKitUniversalMenus-tvOS // // Copyright (c) 2016 <NAME>. All rights reserved. // #import <SpriteKit/SpriteKit.h> @interface GameScene : SKScene @end
Dzamir/SpriteKitUniversalVerticalMenus
Pod/Classes/Directions.h
// // Directions.h // Pods // // Created by <NAME> on 09/01/16. // // #ifndef Directions_h #define Directions_h typedef enum : NSUInteger { DZAMenuDirectionUp, DZAMenuDirectionRight, DZAMenuDirectionDown, DZAMenuDirectionLeft } DZAMenuDirection; typedef enum : NSUInteger { DZAMenuAxisVertical, DZAMenuAxisHorizontal } DZAMenuAxis; #endif /* Directions_h */
Dzamir/SpriteKitUniversalVerticalMenus
Example/Pods/Target Support Files/Pods-SpriteKiUniversalMenus-MacUITests/Pods-SpriteKiUniversalMenus-MacUITests-umbrella.h
<gh_stars>10-100 #import <Cocoa/Cocoa.h> FOUNDATION_EXPORT double Pods_SpriteKiUniversalMenus_MacUITestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SpriteKiUniversalMenus_MacUITestsVersionString[];
Zippen-Huang/lane_detection-
src/helpers.h
<gh_stars>10-100 #ifndef HELPERS_H #define HELPERS_H #include <string> #include <algorithm> std::string rem_whitespace(std::string path); std::string get_dir(std::string path); std::string abs_path(std::string path, std::string relative_to); #endif
Zippen-Huang/lane_detection-
src/detector.h
<filename>src/detector.h #ifndef DETECTOR_H #define DETECTOR_H using namespace std; #include "opencv2/opencv.hpp" #include "lane.h" #include <string> #include <cmath> #include <vector> using namespace cv; class Detector { private: int threshold; int row_step; int col_step; int l_start; int r_start; int img_threshold; Mat matrix_transform_birdseye; Mat matrix_transform_fiperson; double vehicle_length; double vehicle_width; double cam_angle; int frame_width; int frame_height; double m_per_px; Mat getTransformMatrix(int height, int width, double angle, double perc_low, double perc_high, bool undo=false); public: Detector(string config_path, int cam_height, int cam_width); void getLanes(const Mat &img, Lane &lane); void drawLane(Mat &img, Lane &lane); double getTurningRadius(Lane &lane); std::vector<double> getAckermannSteering(Lane &lane); std::vector<double> getDifferentialSteering(Lane &lane, double speed); }; #endif
Zippen-Huang/lane_detection-
src/logger.h
<reponame>Zippen-Huang/lane_detection- #include<string> #include "boost/log/trivial.hpp" #include <vector> enum Levels{TRACE, DEBUG, INFO, WARNING, ERROR, FATAL}; using namespace std; class Logger { private: static string file; static bool console; static bool is_init; static Levels severity; Logger(); // Logger(Logger const&); // void operator=(Logger const&); public: void log(string src, string msg, Levels severity, const vector<string> &tags); static Logger getLogger(); static void init(bool console, string file, Levels severity); static string append_tag(vector<string> tags); //Logger(Logger const&) = delete; //void operator=(Logger const&) = delete; };
Zippen-Huang/lane_detection-
src/polifitgsl.h
/** * Provides function to fit a polynomial curve to a set of data. * Source: https://rosettacode.org/wiki/Polynomial_regression#C */ #ifndef _POLIFITGSL_H #define _POLIFITGSL_H #include <gsl/gsl_multifit.h> #include <stdbool.h> #include <math.h> bool polynomialfit(int obs, int degree, const double *dx, const double *dy, double *store); /* n, p */ #endif
Zippen-Huang/lane_detection-
src/lane.h
#ifndef LANE_H #define LANE_H #include <vector> #include <cmath> #include <string> class Lane { private: int n; //number of parameters that define the lane (degree + 1) std::vector<double> params; //array of size degree. Defines coefficients for left lane curve. std::vector<double> lparams; std::vector<double> rparams; double filter; //filter for curve to remove jitter. lane = old_lane*filter + new_lane*(1-filter). double curvature; //positive curvature is right, negative is left double width; double camera_height; double vehicle_length; double vehicle_width; public: Lane(std::string config_path); int getN(); std::vector<double> getParams(); std::vector<double> getLParams(); std::vector<double> getRParams(); double getFilter(); double getCurvature(); double getWidth(); void update(std::vector<double> l, std::vector<double> r); }; #endif
Rhyman/CheckBoxC
CheckBoxC/ViewController.h
// // ViewController.h // CheckBoxC // // Created by <NAME> on 2/14/19. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "RAHCheckbox.h" @interface ViewController : UIViewController <RAHCheckboxDelegate> { RAHCheckbox *checkbox1; RAHCheckbox *checkbox3; } @property (weak, nonatomic) IBOutlet UILabel *checkBoxLabel; @property (weak, nonatomic) IBOutlet RAHCheckbox *checkbox2; @end
Rhyman/CheckBoxC
CheckBoxC/RAHCheckbox.h
// // RAHCheckbox.h // testLayers // // Created by <NAME> on 8/27/11. // Copyright 2011-2019 R.A.Hyman. All rights reserved. // #import <UIKit/UIKit.h> // protocol below lets the parent viewController know // when the checkbox value changes @protocol RAHCheckboxDelegate; @interface RAHCheckbox : UIControl { double ifullRectW; // taken from the width of the rect used to init this view // used as characteristic length for all layer sizing/drawing // Based on the width of the defined box containing this // control; the height is ignored, and a square box // is constructed. CALayer *iBackground; CALayer *iCheckBox; CAShapeLayer *iCheckMark; // checkbox UIColor *colorForBackground; UIColor *checkboxColor; CGFloat checkboxBorderWidth; // checkmark UIColor *checkmarkColor; CGFloat checkmarkWidth; BOOL useXMark; BOOL on; // animation CGFloat checkmarkAnimationDuration; BOOL animateCheckMark; } @property (nonatomic, weak) id <RAHCheckboxDelegate> delegate; // Init the checkbox control in the defined rect; the width is // used to create a square space; the height is ignored // The visible checkbox is 15% smaller on each side than this rect. // In use, a typical width of this rect is 40 to 50 points // The full rect reacts to user touches, including the small, invisible // area outside of the checkbox - (id)initWithRect:(CGRect)fullRect; // adjust the frame that encompasses the entire control - (void)adjustFrame:(CGRect)rect; // Determine if the control is currently set on or off - (BOOL)isOn; // When created, the checkmark can be on or off; default is off - (void)setOn:(BOOL)setOn animated:(BOOL)animated; // Indicate if the animated checkmark should be used, when checkmark is // drawn; when animated, the checkmark is a simple line of constant width // When not animated, the static checkmark is a little more stylish // The default is YES - (void)animateMark:(BOOL)animate; // set duration of animation, when checkmark is animated; default is 0.5 secs - (void)setAnimaDuration:(CGFloat)aDuration; // checkbox characteristics // Set the checkbox background color; default is white // Set the checkbox border color; default is medium gray // Set the checkbox border width; default is 4% of the full control width - (void)setBackgroundColor:(UIColor *)aColor; - (void)setBoxBorderColor:(UIColor *)aColor; - (void)setBoxBorderWidth:(CGFloat)aWidth; // checkmark characteristics // Set the checkmark color; default is black // Set width of pen that draws checkmark; default is 10% of full control width // Use the X mark in the checkbox, rather than the checkmark; default is NO - (void)setCheckmarkColor:(UIColor *)aColor; - (void)setCheckmarkStrokeWidth:(CGFloat)aWidth; - (void)useXMark:(BOOL)useXcheckmark; @end @protocol RAHCheckboxDelegate // the delegate protocol is called when the checkbox is tapped @optional - (void)checkboxChangedValue:(BOOL)isOn; @end
fireae/nhocr
include/imgobj.h
/*-------------------------------------------------------------- Image object class Include File Rev.980108 Written by H.Goto , May 1994 Modified by H.Goto , Jan. 1998 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994-1998 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef imgobjp_h #define imgobjp_h #include <CRect.h> #include <ORect.h> #endif /* imgobjp_h */
fireae/nhocr
O2-tools-2.01/libsrc/siplib/lpsmooth.c
<filename>O2-tools-2.01/libsrc/siplib/lpsmooth.c /*-------------------------------------------------------------- Image Processing function library libsip (Line-preserving smoothing Rev.020208) Written by H.Goto , Apr 2000 Modified by H.Goto , July 2000 Modified by H.Goto , Oct 2000 Modified by H.Goto , Dec 2000 Modified by H.Goto , Feb 2002 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 2000-2002 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #define GrayLevels 256 #include <stdio.h> #include <stdlib.h> #include <string.h> #include "utypes.h" #include "siplib.h" static int sip_2NNsmooth (SIPImage *src,SIPImage *dst,int ctweight); static int sip_kNNsmoothc(SIPImage *src,SIPImage *dst,int pixels,int ctweight); /*------------------------------------------------------ Line preserving smoothing Note: The thin line is never blurred in the direction orthogonal to the line only when pixels=3. Line segments may get shorter by at most 2 pixels. If pixels=9 and ctweight=1, the processing is identical to the moving average by 3x3 mask. If pixels=1, this function does nothing except consuming some memory and enormous CPU power. Available ranges of the parameters: 1 <= pixels <= 9 0 <= ctweight Note: (pixels,ctweight)=(1,0) is prohibited. ------------------------------------------------------*/ int sip_kNNsmooth(SIPImage *src,SIPImage *dst,int pixels,int ctweight){ int x,y,i; uchar *pu,*p,*pd,*ptmp; uchar *dp; uchar *lbuf; int c,d; int width,height; int vtbl[8]; int dt[8]; int minpos; if ( src->depth != 8 ){ return( sip_kNNsmoothc(src,dst,pixels,ctweight) ); } if ( pixels == 3 ){ return( sip_2NNsmooth(src,dst,ctweight) ); } width = src->width; height = src->height; if ( 0 == (lbuf = (uchar *)malloc( sizeof(uchar) * 3 * (width+2)) ) ) return(-1); pu = lbuf; p = pu + (width+2); pd = p + (width+2); /* copy the first line to the line buffer */ memcpy((void *)(p+1),(void *)sip_getimgptr(src,0),width); p[0] = p[1]; p[width+1] = p[width]; /* the first upper line is as same as the first line */ memcpy((void *)pu, (void *)p, width +2); for ( y=0 ; y<height ; y++ ){ /* if the next line exists, copy it to the line buffer */ if ( y < height -1 ){ memcpy((void *)(pd+1),(void *)sip_getimgptr(src,y+1),width); pd[0] = pd[1]; pd[width+1] = pd[width]; } else{ pd = p; /* if bottom, use current line instead */ } dp = (uchar *)sip_getimgptr(dst,y); for ( x=0 ; x < dst->width ; x++ ){ c = (int)((uint)p [x+1]); d = c - (vtbl[0] = (int)((uint)pu[x ])); dt[0] = d * d; d = c - (vtbl[1] = (int)((uint)pu[x+1])); dt[1] = d * d; d = c - (vtbl[2] = (int)((uint)pu[x+2])); dt[2] = d * d; d = c - (vtbl[3] = (int)((uint)p [x ])); dt[3] = d * d; d = c - (vtbl[4] = (int)((uint)p [x+2])); dt[4] = d * d; d = c - (vtbl[5] = (int)((uint)pd[x ])); dt[5] = d * d; d = c - (vtbl[6] = (int)((uint)pd[x+1])); dt[6] = d * d; d = c - (vtbl[7] = (int)((uint)pd[x+2])); dt[7] = d * d; c *= ctweight; for ( i=0 ; i<pixels-1 ; i++ ){ d = dt[0]; minpos = 0; if ( d > dt[1] ){ d = dt[1]; minpos = 1; } if ( d > dt[2] ){ d = dt[2]; minpos = 2; } if ( d > dt[3] ){ d = dt[3]; minpos = 3; } if ( d > dt[4] ){ d = dt[4]; minpos = 4; } if ( d > dt[5] ){ d = dt[5]; minpos = 5; } if ( d > dt[6] ){ d = dt[6]; minpos = 6; } if ( d > dt[7] ){ d = dt[7]; minpos = 7; } c += vtbl[minpos]; dt[minpos] = 0x7fffffff; /* cancel */ } dp[x] = (uchar)(c / (ctweight + pixels -1)); /* Note that we don't need any limiter. */ } /* rotate the line buffers */ ptmp = pu; pu = p; p = pd; pd = ptmp; } free((void *)lbuf); return(0); } static int sip_2NNsmooth(SIPImage *src,SIPImage *dst,int ctweight){ int x,y,i; uchar *pu,*p,*pd,*ptmp; uchar *dp; uchar *lbuf; int c,d; int width,height; int vtbl[8]; int dt[8]; int minpos; width = src->width; height = src->height; if ( 0 == (lbuf = (uchar *)malloc( sizeof(uchar) * 3 * (width+2)) ) ) return(-1); pu = lbuf; p = pu + (width+2); pd = p + (width+2); /* copy the first line to the line buffer */ memcpy((void *)(p+1),(void *)sip_getimgptr(src,0),width); p[0] = p[1]; p[width+1] = p[width]; /* the first upper line is as same as the first line */ memcpy((void *)pu, (void *)p, width +2); for ( y=0 ; y<height ; y++ ){ /* if the next line exists, copy it to the line buffer */ if ( y < height -1 ){ memcpy((void *)(pd+1),(void *)sip_getimgptr(src,y+1),width); pd[0] = pd[1]; pd[width+1] = pd[width]; } else{ pd = p; /* if bottom, use current line instead */ } dp = (uchar *)sip_getimgptr(dst,y); for ( x=0 ; x < dst->width ; x++ ){ c = (int)((uint)p [x+1]); d = c - (vtbl[0] = (int)((uint)pu[x ])); dt[0] = d * d; d = c - (vtbl[1] = (int)((uint)pu[x+1])); dt[1] = d * d; d = c - (vtbl[2] = (int)((uint)pu[x+2])); dt[2] = d * d; d = c - (vtbl[3] = (int)((uint)p [x ])); dt[3] = d * d; d = c - (vtbl[4] = (int)((uint)p [x+2])); dt[4] = d * d; d = c - (vtbl[5] = (int)((uint)pd[x ])); dt[5] = d * d; d = c - (vtbl[6] = (int)((uint)pd[x+1])); dt[6] = d * d; d = c - (vtbl[7] = (int)((uint)pd[x+2])); dt[7] = d * d; c *= ctweight; for ( i=0 ; i<2 ; i++ ){ d = dt[0]; minpos = 0; if ( d > dt[1] ){ d = dt[1]; minpos = 1; } if ( d > dt[2] ){ d = dt[2]; minpos = 2; } if ( d > dt[3] ){ d = dt[3]; minpos = 3; } if ( d > dt[4] ){ d = dt[4]; minpos = 4; } if ( d > dt[5] ){ d = dt[5]; minpos = 5; } if ( d > dt[6] ){ d = dt[6]; minpos = 6; } if ( d > dt[7] ){ d = dt[7]; minpos = 7; } c += vtbl[minpos]; dt[minpos] = 0x7fffffff; /* cancel */ } dp[x] = (uchar)(c / (ctweight + 2)); /* Note that we don't need any limiter. */ } /* rotate the line buffers */ ptmp = pu; pu = p; p = pd; pd = ptmp; } free((void *)lbuf); return(0); } static int sip_kNNsmoothc(SIPImage *src,SIPImage *dst,int pixels,int ctweight){ int x,y,x4,i; uchar *pu,*p,*pd,*ptmp; uchar *dp; uchar *lbuf; int r,g,b,d; int width,height; uchar *vtblp[8]; int dt[8]; int minpos; if ( src->depth != 32 ) return(-1); width = src->width; height = src->height; if ( 0 == (lbuf = (uchar *)malloc( 3 * 4 * (width+2)) ) ) return(-1); pu = lbuf; p = pu + 4 * (width+2); pd = p + 4 * (width+2); /* copy the first line to the line buffer */ memcpy((void *)(p+4),(void *)sip_getimgptr(src,0),4 * width); for ( i=0 ; i<4 ; i++ ){ p[i] = p[4+i]; p[4*(width+1) +i] = p[4*width +i]; } /* the first upper line is as same as the first line */ memcpy((void *)pu, (void *)p, 4 * (width +2)); for ( y=0 ; y<height ; y++ ){ /* if the next line exists, copy it to the line buffer */ if ( y < height -1 ){ memcpy((void *)(pd+4),(void *)sip_getimgptr(src,y+1),4 * width); for ( i=0 ; i<4 ; i++ ){ pd[i] = pd[4+i]; pd[4*(width+1) +i] = pd[4*width +i]; } } else{ pd = p; /* if bottom, use current line instead */ } dp = (uchar *)sip_getimgptr(dst,y); for ( x=0 ; x < dst->width ; x++ ){ x4 = 4 * x; r = (int)((uint)p [x4+4]); g = (int)((uint)p [x4+5]); b = (int)((uint)p [x4+6]); vtblp[0] = &pu[x4 ]; vtblp[1] = &pu[x4+4]; vtblp[2] = &pu[x4+8]; vtblp[3] = &p [x4 ]; vtblp[4] = &p [x4+8]; vtblp[5] = &pd[x4 ]; vtblp[6] = &pd[x4+4]; vtblp[7] = &pd[x4+8]; for ( i=0 ; i<8 ; i++ ){ d = r - (int)((uint)vtblp[i][0]); dt[i] = d * d; d = g - (int)((uint)vtblp[i][1]); dt[i] += d * d; d = b - (int)((uint)vtblp[i][2]); dt[i] += d * d; } r *= ctweight; g *= ctweight; b *= ctweight; for ( i=0 ; i<pixels-1 ; i++ ){ d = dt[0]; minpos = 0; if ( d > dt[1] ){ d = dt[1]; minpos = 1; } if ( d > dt[2] ){ d = dt[2]; minpos = 2; } if ( d > dt[3] ){ d = dt[3]; minpos = 3; } if ( d > dt[4] ){ d = dt[4]; minpos = 4; } if ( d > dt[5] ){ d = dt[5]; minpos = 5; } if ( d > dt[6] ){ d = dt[6]; minpos = 6; } if ( d > dt[7] ){ d = dt[7]; minpos = 7; } r += (int)((uint)vtblp[minpos][0]); g += (int)((uint)vtblp[minpos][1]); b += (int)((uint)vtblp[minpos][2]); dt[minpos] = 0x7fffffff; /* cancel */ } dp[x4 ] = (uchar)((uint)(r / (ctweight + pixels -1))); dp[x4+1] = (uchar)((uint)(g / (ctweight + pixels -1))); dp[x4+2] = (uchar)((uint)(b / (ctweight + pixels -1))); /* Note that we don't need any limiter. */ } /* rotate the line buffers */ ptmp = pu; pu = p; p = pd; pd = ptmp; } free((void *)lbuf); return(0); }
fireae/nhocr
O2-tools-2.01/libsrc/siplib/tenneib.h
/* Image Thinning by Ten Neighbor Method */ /* Original Code by <NAME> */ /* Library version by <NAME> , Oct. 1994 */ /*-------------------------------------------------------------------- Copyright (C) 1994 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, Hirotomo Aso, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ /* Thinning Reference Table for Ten Neighbor Method */ /* 0 neighborhood 123 thin pattern: 4567 ---> new 6 , (MSB)fedcba9876543210(LSB) 89a 00000*********** : tenneib */ #define TWO11 2048 /* 2**11 */ char thinreftable[TWO11] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,0, 1,1,1,1,1,0,1,0,1,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,0,0,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,0, 0,0,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1 }; int thin(tenneib) int tenneib; /* Assumed 0 <= tenneib < TWO11 */ { return((int)(thinreftable[tenneib])); }
fireae/nhocr
O2-tools-2.01/libsrc/libufp/comlib.c
<filename>O2-tools-2.01/libsrc/libufp/comlib.c /*-------------------------------------------------------------- Common Library for libufp Written by H.Goto , Jan. 1995 Revised by H.Goto , Feb. 1996 Revised by H.Goto , July 1996 Revised by H.Goto , Feb. 1997 Revised by H.Goto , Apr. 2000 Revised by H.Goto , Nov. 2008 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1995-2008 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include "comlib.h" void _uf_wordswap(ushort *d){ unsigned char H,L; L = (uchar)*d; H = (uchar)(*d >> 8); *d = ((ushort)L << 8) | (ushort)H; } void _uf_dwordswap(uint32 *d){ unsigned char B0,B1,B2,B3; B0 = (uchar)*d; B1 = (uchar)(*d >> 8); B2 = (uchar)(*d >> 16); B3 = (uchar)(*d >> 24); *d = ((ushort)B0 << 24) | ((ushort)B1 << 16) | ((ushort)B2 << 8) | (ushort)B3; } void _uf_convert_1to8(uchar *src,uchar *dst,int size,uchar fg,uchar bg){ int size2; int cc; size2 = size % 8; size /= 8; for( ; size > 0 ; --size ){ cc = (int)*(src++); if((cc&0x80)==0) *(dst++)=bg; else *(dst++)=fg; if((cc&0x40)==0) *(dst++)=bg; else *(dst++)=fg; if((cc&0x20)==0) *(dst++)=bg; else *(dst++)=fg; if((cc&0x10)==0) *(dst++)=bg; else *(dst++)=fg; if((cc&0x08)==0) *(dst++)=bg; else *(dst++)=fg; if((cc&0x04)==0) *(dst++)=bg; else *(dst++)=fg; if((cc&0x02)==0) *(dst++)=bg; else *(dst++)=fg; if((cc&0x01)==0) *(dst++)=bg; else *(dst++)=fg; } if ( size2 != 0 ){ cc = (int)*src; for ( ; size2 > 0 ; --size2 ){ if((cc&0x80)==0) *(dst++)=bg; else *(dst++)=fg; cc <<= 1; } } } void _uf_convert_8to1(uchar *src,uchar *dst,int size,uchar threshold){ int i,i2,th; uchar d,tm; th = (int)threshold; for ( i=0 ; i<(size/8) ; i++ ){ d = 0; tm = 0x80; for ( i2=0 ; i2<8 ; i2++ ){ if ( (int)*(src++) < th ) d |= tm; tm >>= 1; } *(dst++) = d; } i = size % 8; if ( i != 0 ){ d = 0; tm = 0x80; for ( i2=0 ; i2<i ; i2++ ){ if ( (int)*(src++) < th ) d |= tm; tm >>= 1; } *(dst++) = d; } } int uf_GetLittleWORD(FILE *fp){ ushort w; if ( 2 != fread((void *)&w,1,2,fp) ) return(EOF); ifMSB _uf_wordswap(&w); return( (int)((uint)w) ); } int uf_GetLittleDWORD(FILE *fp){ uint32 dw; /* EOF conflicts with a possible data. */ if ( 4 != fread((void *)&dw,1,4,fp) ) return(EOF); ifMSB _uf_dwordswap(&dw); return( (int)dw ); } int uf_GetBigWORD(FILE *fp){ ushort w; if ( 2 != fread((void *)&w,1,2,fp) ) return(EOF); ifLSB _uf_wordswap(&w); return( (int)((uint)w) ); } int uf_GetBigDWORD(FILE *fp){ uint32 dw; /* EOF conflicts with a possible data. */ if ( 4 != fread((void *)&dw,1,4,fp) ) return(EOF); ifLSB _uf_dwordswap(&dw); return( (int)dw ); }
fireae/nhocr
O2-tools-2.01/include/ipIO.h
<reponame>fireae/nhocr /*-------------------------------------------------------------- IP-format file I/O class Header Include File Written by H.Goto , Jan. 1994 Modified by H.Goto , Feb. 1997 Modified by H.Goto , Apr. 2000 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994-2000 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef ipIO_h #define ipIO_h #include "utypes.h" /*------------------------------------------------------ IP-format file Load Class ------------------------------------------------------*/ class IPLOAD { private: FILE *fp; int line; int width,height,pixel; int linebytes; int byteorder,headersize; uchar *linebuffer; struct { ushort width_bytes; ushort height; } ip_header; struct { uint32 width_bytes; uint32 height; } ip_header4; int filetype; /* = 0 : 1bit/pixel */ /* 1 : 8bit grayscale */ uchar fgcol,bgcol; void wordswap(ushort *d); protected: void convert_1to8(uchar *src,uchar *dst,int size); public: int setmode(int byteorder,int headersize); /* byteorder = 0 : MSB First */ /* 1 : LSB First */ /* headersize = 2 : WORD */ /* 4 : DWORD */ int fileopen(char *path); int fileclose(void); int readLine(void *buf); int readLine_gray(void *buf); int getWidth(void) { return width; } int getHeight(void) { return height; } int getFiletype(void) { return filetype; } IPLOAD(void); virtual ~IPLOAD(void); }; /*------------------------------------------------------ IP-format file Save Class ------------------------------------------------------*/ class IPSAVE { private: FILE *fp; char wfname[256]; int width,height,pixel; int linebytes; int byteorder,headersize; uchar *linebuffer; struct { ushort width_bytes; ushort height; } ip_header; int filetype; /* = 0 : 1bit/pixel */ /* 1 : 8bit grayscale */ protected: void convert_8to1(uchar *src,uchar *dst,int size,uchar threshold); public: int setmode(int byteorder,int headersize); /* This function is now dummy. */ int filecreat(char *path,int filetype,int width,int height); int fileclose(void); int writeLine(void *buf); int writeLine_mono(void *buf,int threshold); IPSAVE(void); virtual ~IPSAVE(void); }; #endif // ipIO_h
fireae/nhocr
O2-tools-2.01/libsrc/libsgp/getpeak.c
/*-------------------------------------------------------------- Signal processing function library libsgp ( Get peaks in sequence Rev.960229) Written by H.Goto , May 1994 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, Hideaki Goto, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include "sgplib.h" /*------------------------------------------------------ Get peaks ------------------------------------------------------*/ int sgp_getpeaksuc(uchar *src,peaklisti *pks, \ int size,int listsize,int thlow,int thhigh){ int ix,l; int dx,dx0,x0; int count; count = 0; l = 0; x0 = dx0 = 0; for ( ix=0 ; ix<size ; ++ix ){ dx = (int)((uint)src[ix]) - x0; if ( dx == 0 ){ if ( dx0 > 0 ) ++l; else l = 0; } else{ if ( dx < 0 ){ if ( l != 0 ){ if ( (x0 >= thlow) && (x0 <= thhigh) ){ if ( (++count) > listsize ) break; pks->pos = ix - ((l+1)/2) -1; pks->value = (int)((uint)x0); ++pks; } l = 0; } else{ if ( dx0 > 0 ){ if ( (x0 >= thlow) && (x0 <= thhigh) ){ if ( (++count) > listsize ) break; pks->pos = ix -1; pks->value = (int)((uint)x0); ++pks; } } } } else{ l = 0; } dx0 = dx; } x0 = (int)((uint)src[ix]); } return (count); } int sgp_getpeaksi(int *src,peaklisti *pks, \ int size,int listsize,int thlow,int thhigh){ int ix,l; int dx,dx0,x0; int count; count = 0; l = 0; x0 = dx0 = 0; for ( ix=0 ; ix<size ; ++ix ){ dx = src[ix] - x0; if ( dx == 0 ){ if ( dx0 > 0 ) ++l; else l = 0; } else{ if ( dx < 0 ){ if ( l != 0 ){ if ( (x0 >= thlow) && (x0 <= thhigh) ){ if ( (++count) > listsize ) break; pks->pos = ix - ((l+1)/2) -1; pks->value = x0; ++pks; } l = 0; } else{ if ( dx0 > 0 ){ if ( (x0 >= thlow) && (x0 <= thhigh) ){ if ( (++count) > listsize ) break; pks->pos = ix -1; pks->value = x0; ++pks; } } } } else{ l = 0; } dx0 = dx; } x0 = src[ix]; } return (count); }
fireae/nhocr
libnhocr/codelist.h
<gh_stars>10-100 /*---------------------------------------------------------------------- Character code table management function codetable.h Written by H.Goto, Feb. 2008 Revised by H.Goto, Sep. 2008 Revised by H.Goto, Jan. 2009 Revised by H.Goto, May 2009 Revised by H.Goto, July 2009 Revised by H.Goto, Oct. 2009 Revised by H.Goto, Aug. 2014 ----------------------------------------------------------------------*/ /*-------------- Copyright 2008-2014 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------*/ #ifndef _codetable_h #define _codetable_h #define CharCodeSize 16 #define CCLineLength 80 #define CCFontNameLen 16 class CharCode { public: char ccode[CharCodeSize]; char ccode_dic[CharCodeSize]; int poshint, sizehint, wdir; int alphamode; char charclass; char fontname[CCFontNameLen]; }; #ifdef __cplusplus extern "C" { #endif int load_codelist(char *file, CharCode **cclist, int debug); int load_codelist_bydiccodes(char *dir, char *diccodes, CharCode **cclist, int debug); #ifdef __cplusplus } #endif #endif
fireae/nhocr
O2-tools-2.01/libsrc/siplib/projprof.c
/*-------------------------------------------------------------- Image Processing function library libsip (Projection profile Rev.081230) Written by H.Goto , Nov 1995 Revised by H.Goto , Sep 1997 Revised by H.Goto , May 2002 Revised by H.Goto , Dec 2008 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1995-2008 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include "siplib.h" long sip_projprofile(SIPImage *image,long *rden,long *cden){ int x,y; int width,height,depth; ulong rsum,total; ulong d; uchar *line; uchar mask,dc; width = image->width; height = image->height; switch ( depth = image->depth ){ case 1: case 8: break; default: return(-1); } total = 0; if ( cden != 0 ){ for ( x=0 ; x<width ; x++ ) cden[x] = 0; for ( y=0 ; y<height ; y++ ){ line = (uchar *)sip_getimgptr(image,y); rsum = 0; mask = dc = 0; if ( depth == 1 ){ for ( x=0 ; x<width ; x++ ){ if ( mask == 0 ){ mask = 0x80; dc = *line++; } if ( (mask & dc) != 0 ){ ++rsum; ++cden[x]; } mask >>= 1; } } else{ for ( x=0 ; x<width ; x++ ){ d = (ulong)*line++; rsum += d; cden[x] += d; } } if ( rden != 0 ) rden[y] = rsum; total += rsum; } } else{ for ( y=0 ; y<height ; y++ ){ line = (uchar *)sip_getimgptr(image,y); rsum = 0; mask = dc = 0; if ( depth == 1 ){ for ( x=0 ; x<width ; x++ ){ if ( mask == 0 ){ mask = 0x80; dc = *line++; } if ( (mask & dc) != 0 ) ++rsum; mask >>= 1; } } else{ for ( x=0 ; x<width ; x++ ){ rsum += (ulong)*line++; } } if ( rden != 0 ) rden[y] = rsum; total += rsum; } } return(total); } long sip_projprofile_area(SIPImage *image,long *rden, \ long *cden,SIPRectangle *area){ int x,y; int width,height,depth; ulong rsum,total; ulong d; uchar *line; uchar mask,dc; int xoffb; width = area->width; height = area->height; xoffb = area->x; switch ( depth = image->depth ){ case 1: xoffb >>= 3; case 8: break; default: return(-1); } total = 0; if ( cden != 0 ){ for ( x=0 ; x<width ; x++ ) cden[x] = 0; for ( y=0 ; y<height ; y++ ){ line = (uchar *)sip_getimgptr(image,y) + xoffb; rsum = 0; if ( depth == 1 ){ mask = 0x80; dc = *line++; mask >>= (area->x & 0x07); for ( x=0 ; x<width ; x++ ){ if ( mask == 0 ){ mask = 0x80; dc = *line++; } if ( (mask & dc) != 0 ){ ++rsum; ++cden[x]; } mask >>= 1; } } else{ for ( x=0 ; x<width ; x++ ){ d = (ulong)*line++; rsum += d; cden[x] += d; } } if ( rden != 0 ) rden[y] = rsum; total += rsum; } } else{ for ( y=0 ; y<height ; y++ ){ line = (uchar *)sip_getimgptr(image,y) + xoffb; rsum = 0; if ( depth == 1 ){ mask = 0x80; dc = *line++; mask >>= (area->x & 0x07); for ( x=0 ; x<width ; x++ ){ if ( mask == 0 ){ mask = 0x80; dc = *line++; } if ( (mask & dc) != 0 ) ++rsum; mask >>= 1; } } else{ for ( x=0 ; x<width ; x++ ){ rsum += (ulong)*line++; } } if ( rden != 0 ) rden[y] = rsum; total += rsum; } } return(total); }
fireae/nhocr
O2-tools-2.01/libsrc/libsgp/walsh.c
<filename>O2-tools-2.01/libsrc/libsgp/walsh.c /*-------------------------------------------------------------- Signal processing function library libsgp ( Walsh transform functions Rev.020527 ) Written by H.Goto , May 1993 Modified by H.Goto , May 2002 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1993-2002 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <memory.h> #include "sgplib.h" /*------------------------------------------------------ Get Walsh sequences ------------------------------------------------------*/ int sgp_wal(int n,int m,int nn){ if ( m == 0 ) return(1); n = n % nn; if ( m == 1 ){ if ( n < (nn/2) ) return(1); else return(-1); } if ( m & 0x02 ) return ( sgp_wal(2 * n, (m/2), nn) * sgp_wal(n, 1-(m & 0x01), nn) ); return ( sgp_wal(2 * n, (m/2), nn) * sgp_wal(n, m & 0x01, nn) ); } void sgp_walseq(int *buf,int m,int nn){ int i; for ( i=0 ; i<nn ; i++ ) *buf++ = sgp_wal(i,m,nn); } void sgp_walseqb(char *buf,int m,int nn){ int i; for ( i=0 ; i<nn ; i++ ) if ( sgp_wal(i,m,nn) +1 ) *buf++ = 0xff; else *buf++ = 0; } /*------------------------------------------------------ Create Walsh Matrix ------------------------------------------------------*/ void sgp_walmatrix(int *buf,int nn){ int i; for ( i=0 ; i<nn ; i++ ){ sgp_walseq(buf,i,nn); buf += nn; } } void sgp_walmatrixb(char *buf,int nn){ int i; for ( i=0 ; i<nn ; i++ ){ sgp_walseqb(buf,i,nn); buf += nn; } } /*------------------------------------------------------ Walsh Transform ------------------------------------------------------*/ int sgp_WHT(int *data,int *sequency,int len,int *wmtx){ int m,n,sum; int *wal,*wp; if ( 0 == (wal = wmtx) ){ if ( 0 == (wal = (int *)malloc(len * len * sizeof(int))) ) return(-1); sgp_walmatrix(wal,len); } for ( m=0 ; m<len ; m++ ){ sum = 0; wp = &wal[len * m]; for ( n=0 ; n<len ; n++ ) sum += data[n] * (*wp++); *sequency++ = sum; } if ( 0 != wmtx ) free(wal); return(0); } int sgp_WHTb(char *data,int *sequency,int len,char *wmtx){ int m,n,sum; char *wal,*wp; if ( 0 == (wal = wmtx) ){ if ( 0 == (wal = (char *)malloc(len * len * sizeof(char))) ) return(-1); sgp_walmatrixb(wal,len); } for ( m=0 ; m<len ; m++ ){ sum = 0; wp = &wal[len * m]; for ( n=0 ; n<len ; n++ ) if ( ! (data[n] ^ (*wp++)) ) ++sum; *sequency++ = (2 * sum) - len; } if ( 0 != wmtx ) free(wal); return(0); } void sgp_WHTpower(int *wseries,int *pow,int len){ int i; *pow++ = *wseries * *wseries; ++wseries; for ( i=1 ; i<(len/2) ; i++ ){ *pow++ = (wseries[0] * wseries[0]) + (wseries[1] * wseries[1]); wseries += 2; } *pow++ = *wseries * *wseries; }
fireae/nhocr
O2-tools-2.01/libsrc/objgrp/objgrp.h
/*-------------------------------------------------------------- Object Group Class Header File Rev.030729 Written by H.Goto , Mar 1994 Modified by H.Goto , Oct 1994 Rewrote by H.Goto , Sep 1997 Modified by H.Goto , Dec 1998 Modified by H.Goto , May 2002 Modified by H.Goto , Jul 2003 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994-2003 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef objgrp_h #define objgrp_h typedef struct { int stat; int counts; int *id; void *attr; } grppac; class GRPLST { private: int bufsize; grppac **grplist; inline grppac *_getgp(int grpid); public: int groups; int realloc(int grps); int alloc(int grps){ return( realloc(grps) ); } int newgrp(int objid); int addgrp(int grpid,int objid); int deletegrp(int grpid); int clearall(void); int mergegrps(int dstgrpid,int srcgrpid); int getidcounts(int grpid); int setidcounts(int grpid,int idcounts); int *getidlist(int grpid); int setattr(int grpid,void *attr); void *getattr(int grpid); GRPLST(void); virtual ~GRPLST(void); }; inline grppac * GRPLST :: _getgp(int grpid){ if ( (grpid < 0) || (grpid >= bufsize) ) return(0); return(grplist[grpid]); } #endif /* objgrp_h */
fireae/nhocr
O2-tools-2.01/libsrc/libsgp/corr.c
<reponame>fireae/nhocr /*-------------------------------------------------------------- Signal processing function library libsgp ( Correlation Functions Rev.941214) Written by H.Goto , Dec.1994 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <memory.h> #include "sgplib.h" /*------------------------------------------------------ Get Correlation factor ------------------------------------------------------*/ int sgp_correlations(short *d1,short *d2,int len,short *corr, \ int maxmove,int periodic,short zero){ int i,mv; short sum; for ( mv=0 ; mv<maxmove ; mv++ ){ sum = 0; for ( i=0 ; i < (len - mv) ; i++ ){ sum += d1[i] * d2[i + mv]; } for ( i = (len - mv) ; i<len ; i++ ){ if ( periodic ) sum += d1[i] * d2[i + mv - len]; else sum += d1[i] * zero; } *corr++ = sum; } return(0); } int sgp_correlationi(int *d1,int *d2,int len,int *corr, \ int maxmove,int periodic,int zero){ int i,mv; int sum; for ( mv=0 ; mv<maxmove ; mv++ ){ sum = 0; for ( i=0 ; i < (len - mv) ; i++ ){ sum += d1[i] * d2[i + mv]; } if ( periodic ){ for ( i = (len - mv) ; i<len ; i++ ) sum += d1[i] * d2[i + mv - len]; } else{ for ( i = (len - mv) ; i<len ; i++ ) sum += d1[i] * zero; } *corr++ = sum; } return(0); } int sgp_correlationb(char *d1,char *d2,int len,int *corr, \ int maxmove,int periodic,char zero){ int i,mv; int sum; for ( mv=0 ; mv<maxmove ; mv++ ){ sum = 0; for ( i=0 ; i < (len - mv) ; i++ ){ if ( ! (d1[i] ^ d2[i + mv]) ) ++sum; } if ( periodic ){ for ( i = (len - mv) ; i<len ; i++ ) if ( ! (d1[i] ^ d2[i + mv - len]) ) ++sum; } else{ for ( i = (len - mv) ; i<len ; i++ ) if ( ! (d1[i] ^ (char)zero) ) ++sum; } *corr++ = (2 * sum) -len; } return(0); }
fireae/nhocr
O2-tools-2.01/libsrc/siplib/rotate.c
<gh_stars>10-100 /*-------------------------------------------------------------- Image Processing function library libsip (Rotate image Rev.081230) Written by H.Goto , Nov 1995 Revised by H.Goto , May 1996 Revised by H.Goto , May 2002 Revised by H.Goto , Dec 2008 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1995-2008 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "siplib.h" /*------------------------------------------------------ Rotate image ------------------------------------------------------*/ int sip_rotate1(SIPImage *src,SIPImage *dst,int x0,int y0,double angle,int mode){ /* mode = BOP_XXX */ int sx,sy,dx,dy; int sx0,sy0; int dx1,dy1,dx2,dy2,dx10; double rc,rs,rsy,rcy; double *ctbl,*stbl; int lnlen; if ( src->depth != 1 ) return(-1); if ( dst->depth != 1 ) return(-1); rc = cos(-angle); rs = sin(-angle); sx0 = (unsigned int)(src->width +1) /2; sy0 = (unsigned int)(src->height +1) /2; dx2 = (int)((double)sx0 * fabs(rc) + (double)sy0 * fabs(rs)); if ( 0 > (dx1 = x0 - dx2) ) dx1 = 0; if ( dst->width <= (dx2 += x0) ) dx2 = dst->width -1; dy2 = (int)((double)sx0 * fabs(rs) + (double)sy0 * fabs(rc)); if ( 0 > (dy1 = y0 - dy2) ) dy1 = 0; if ( dst->height <= (dy2 += y0) ) dy2 = dst->height -1; dx10 = dx1; dx1 -= x0; dx2 -= x0; lnlen = dx2 - dx1 +1; if ( NULL == (ctbl = (double *)malloc(2 * lnlen * sizeof(double))) ) return(-1); stbl = ctbl + lnlen; for ( dx=0 ; dx<lnlen ; dx++ ){ ctbl[dx] = rc * (double)(dx + dx1); stbl[dx] = rs * (double)(dx + dx1); } for ( dy=dy1 ; dy<=dy2 ; dy++ ){ rsy = rs * (double)(dy - y0); rcy = rc * (double)(dy - y0); switch ( mode ){ case BOP_PUT: for ( dx=0 ; dx<lnlen ; dx++ ){ sx = sx0 + (int)(ctbl[dx] + rsy); if ( sx < 0 ) continue; if ( sx >= src->width ) continue; sy = sy0 - (int)(stbl[dx] - rcy); if ( sy < 0 ) continue; if ( sy >= src->height ) continue; sip_putbit(dst,(dx + dx10),dy,_sip_getbit(src,sx,sy)); } break; case BOP_OR: for ( dx=0 ; dx<lnlen ; dx++ ){ sx = sx0 + (int)(ctbl[dx] + rsy); if ( sx < 0 ) continue; if ( sx >= src->width ) continue; sy = sy0 - (int)(stbl[dx] - rcy); if ( sy < 0 ) continue; if ( sy >= src->height ) continue; sip_orbit(dst,(dx + dx10),dy,_sip_getbit(src,sx,sy)); } break; case BOP_AND: for ( dx=0 ; dx<lnlen ; dx++ ){ sx = sx0 + (int)(ctbl[dx] + rsy); if ( sx < 0 ) continue; if ( sx >= src->width ) continue; sy = sy0 - (int)(stbl[dx] - rcy); if ( sy < 0 ) continue; if ( sy >= src->height ) continue; sip_andbit(dst,(dx + dx10),dy,_sip_getbit(src,sx,sy)); } break; } } free((char *)ctbl); return(0); } int sip_rotate8(SIPImage *src,SIPImage *dst,int x0,int y0,double angle,int mode){ /* mode = BOP_XXX */ int sx,sy,dx,dy; int sx0,sy0; int dx1,dy1,dx2,dy2; double rc,rs,rsy,rcy; double *ctbl,*stbl; uchar *dstp; int lnlen; if ( src->depth != 8 ) return(-1); if ( dst->depth != 8 ) return(-1); rc = cos(-angle); rs = sin(-angle); sx0 = (unsigned int)(src->width +1) /2; sy0 = (unsigned int)(src->height +1) /2; dx2 = (int)((double)sx0 * fabs(rc) + (double)sy0 * fabs(rs)); if ( 0 > (dx1 = x0 - dx2) ) dx1 = 0; if ( dst->width <= (dx2 += x0) ) dx2 = dst->width -1; dy2 = (int)((double)sx0 * fabs(rs) + (double)sy0 * fabs(rc)); if ( 0 > (dy1 = y0 - dy2) ) dy1 = 0; if ( dst->height <= (dy2 += y0) ) dy2 = dst->height -1; dx1 -= x0; dx2 -= x0; lnlen = dx2 - dx1 +1; if ( NULL == (ctbl = (double *)malloc(2 * lnlen * sizeof(double))) ) return(-1); stbl = ctbl + lnlen; for ( dx=0 ; dx<lnlen ; dx++ ){ ctbl[dx] = rc * (double)(dx + dx1); stbl[dx] = rs * (double)(dx + dx1); } for ( dy=dy1 ; dy<=dy2 ; dy++ ){ dstp = (uchar *)sip_getimgptr(dst,dy) + x0 + dx1; rsy = rs * (double)(dy - y0); rcy = rc * (double)(dy - y0); switch ( mode ){ case BOP_PUT: for ( dx=0 ; dx<lnlen ; dx++ ){ sx = sx0 + (int)(ctbl[dx] + rsy); if ( sx < 0 ) continue; if ( sx >= src->width ) continue; sy = sy0 - (int)(stbl[dx] - rcy); if ( sy < 0 ) continue; if ( sy >= src->height ) continue; dstp[dx] = sip_getimgptr(src,sy)[sx]; } break; case BOP_OR: for ( dx=0 ; dx<lnlen ; dx++ ){ sx = sx0 + (int)(ctbl[dx] + rsy); if ( sx < 0 ) continue; if ( sx >= src->width ) continue; sy = sy0 - (int)(stbl[dx] - rcy); if ( sy < 0 ) continue; if ( sy >= src->height ) continue; dstp[dx] |= sip_getimgptr(src,sy)[sx]; } break; case BOP_AND: for ( dx=0 ; dx<lnlen ; dx++ ){ sx = sx0 + (int)(ctbl[dx] + rsy); if ( sx < 0 ) continue; if ( sx >= src->width ) continue; sy = sy0 - (int)(stbl[dx] - rcy); if ( sy < 0 ) continue; if ( sy >= src->height ) continue; dstp[dx] &= sip_getimgptr(src,sy)[sx]; } break; } } free((char *)ctbl); return(0); }
fireae/nhocr
include/comlib.h
/*-------------------------------------------------------------- Common Library for libufp Written by H.Goto , Jan. 1995 Revised by H.Goto , Feb. 1996 Revised by H.Goto , May 1996 Revised by H.Goto , July 1996 Revised by H.Goto , Feb. 1997 Revised by H.Goto , Apr. 2000 Revised by H.Goto , Apr. 2000 Revised by H.Goto , Nov. 2008 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1995-2008 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef comlib_h #define comlib_h #include <utypes.h> // for endian check static int _endian1 = 1; static char *_endianLSB = (char*)&_endian1; #define ifLSB if ( *_endianLSB == 1 ) #define ifMSB if ( *_endianLSB == 0 ) void _uf_wordswap(ushort *d); void _uf_dwordswap(uint32 *d); void _uf_convert_1to8(uchar *src,uchar *dst,int size,uchar fg,uchar bg); void _uf_convert_8to1(uchar *src,uchar *dst,int size,uchar threshold); #endif /* comlib_h */ #ifdef __cplusplus } #endif
fireae/nhocr
include/CRect.h
/*-------------------------------------------------------------- Image object library libimgo , H.Goto Dec.1995 Class: CRects Last modified Nov. 1997 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1995-1997 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef CRect_h #define CRect_h #define CRSTAT_Active 0x8000 #define CRSTAT_NonLink -1 class CRect { public: int stat; int link; int attr; void* attrp; int x1,y1; int x2,y2; inline int width (){ return(abs(x2-x1)+1); } inline int height(){ return(abs(y2-y1)+1); } inline void enable(){ stat |= CRSTAT_Active; } inline void disable(){ stat &= ~CRSTAT_Active; } inline int isactive(){ return( stat & CRSTAT_Active ); } inline void init(); void init(int x1,int y1,int x2,int y2); void set (int x1,int y1,int x2,int y2); /* CRect should not have constructor for SPEED reason. */ }; inline void CRect :: init(){ stat = 0; link = CRSTAT_NonLink; attr = 0; attrp = 0; x1 = y1 = x2 = y2 = 0; } /*------------------------------------------------------ Rectangle Object List ------------------------------------------------------*/ class CRects { private: int maxcrs; int inc_step; int incalloc(); protected: CRect* crlist; public: int counts; CRect* alloc(int size); CRect* realloc(int size); int clear(void); int truncate(void); void set_incstep(int step){ inc_step = step; } int create(int x1,int y1,int x2,int y2); int destroy(int crn); int findparent(int crn); int cat(int cr1,int cr2); int set(int crn,int x1,int y1,int x2,int y2); int expand(int crn,int x1,int y1,int x2,int y2); int setstat(int crn,int stat); int getstat(int crn); int setlink(int crn,int stat); int getlink(int crn); int setattrp(int crn,void *attr); void* getattrp(int crn); int setattr(int crn,int attr); int getattr(int crn); CRect* getrect(int crn){ return(&crlist[crn]); } int isactive(int crn); int width(int crn); int height(int crn); CRects(void); CRects(int incstep); virtual ~CRects(void); }; #endif /* CRect_h */
fireae/nhocr
O2-tools-2.01/libsrc/siplib/distimage.c
/*-------------------------------------------------------------- Image Processing function library libsip ( Convert binary image into distance image Rev.020208 ) Written by H.Goto , Oct 1999 Modified by H.Goto , Feb 2002 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1999-2002 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include "siplib.h" /*------------------------------------------------------ Create Distance Image (4-neighbor mode) ------------------------------------------------------*/ int sip_distimage(SIPImage *image,SIPImage *distimage,int maxdist){ int x,y,n,n0; int width,height; uchar d0; uchar *pi,*pd; uchar *lbuf; int *len; width = image->width; height = image->height; if ( image->depth != 8 || distimage->depth != 8 ) return(-1); if ( NULL == (lbuf = malloc(width * sizeof(uchar))) ) return(-1); if ( NULL == (len = malloc(width * sizeof(int))) ){ free((void *)lbuf); return(-1); } sip_ClearImage(distimage,maxdist); /* scan forward */ pi = (uchar *)sip_getimgptr(image,0); for ( x=0 ; x<width ; x++ ){ lbuf[x] = pi[x] +1; len[x] = maxdist; } for ( y=n=0 ; y<height ; y++ ){ pi = (uchar *)sip_getimgptr(image,y); pd = (uchar *)sip_getimgptr(distimage,y); d0 = *pi +1; n0 = maxdist; for ( x=0 ; x<width ; x++ ){ if ( pi[x] != d0 || pi[x] != lbuf[x] ) n = 0; n++; if ( n > n0+1 ) n = n0+1; if ( n > len[x] +1 ) n = len[x] +1; if ( (uchar)n > pd[x] ) n = pd[x]; n0 = len[x] = pd[x] = (uchar)n; d0 = lbuf[x] = pi[x]; } } /* scan backward */ pi = (uchar *)sip_getimgptr(image,height -1); for ( x=0 ; x<width ; x++ ){ lbuf[x] = pi[x] +1; len[x] = maxdist; } for ( y=height -1 ; y>=0 ; y-- ){ pi = (uchar *)sip_getimgptr(image,y); pd = (uchar *)sip_getimgptr(distimage,y); d0 = pi[width -1] +1; n0 = maxdist; for ( x=width -1 ; x>=0 ; x-- ){ if ( pi[x] != d0 || pi[x] != lbuf[x] ) n = 0; n++; if ( n > n0+1 ) n = n0+1; if ( n > len[x] +1 ) n = len[x] +1; if ( (uchar)n > pd[x] ) n = pd[x]; n0 = len[x] = pd[x] = (uchar)n; d0 = lbuf[x] = pi[x]; } } free((void *)len); free((void *)lbuf); return(0); }
fireae/nhocr
O2-tools-2.01/libsrc/siplib/thin10.c
<gh_stars>10-100 /*-------------------------------------------------------------- Image Processing function library libsip ( Thinning by 10-neighbor method Rev.081230) Written by H.Goto , Oct 1994 Revised by H.Goto , Sep 1997 Revised by H.Goto , Feb 2002 Revised by H.Goto , Dec 2008 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994-2008 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include "siplib.h" #include "tenneib.h" /*------------------------------------------------------ Thinning by 10-neighbor method ------------------------------------------------------*/ int sip_thin10neib(SIPImage *image,char *cflag,char *rflag){ int i,x,y,y1,y2; int width,height; char *lb1,*lb2,*lb3,*lb4; char *lbuf,*lt1,*lt2,*lbo,*lttmp; int tn,tf,tfa; char *cf,*rf; lb1 = lb2 = lb3 = lb4 = 0; /* (just supress compiler warning) */ if ( image->depth != 8 ) return(-1); width = image->width; height = image->height; if ( NULL == (lbuf = (char *)malloc(width * 3)) ) return(-1); lt1 = lbuf; lt2 = lbuf + width; lbo = lbuf + (2 * width); if ( NULL == (cf = (char *)malloc(width + height)) ){ free(lbuf); return(-1); } rf = cf + width; for ( x=0 ; x < (3 * width) ; x++ ) lbuf[x] = (char)0xff; if ( rflag != 0 ){ for ( y=0 ; y<height ; y++ ){ rf[y] = rflag[y]; rflag[y] = 0; } } else{ for ( y=0 ; y<height ; y++ ) rf[y] = 1; } /* if ( cflag != 0 ){ for ( x=0 ; x<width ; x++ ){ cf[x] = cflag[x]; cflag[x] = 0; } } else{ for ( x=0 ; x<width ; x++ ) cf[x] = 1; } */ tfa = 0; for ( y=2 ; y < (height -1) ; y++ ){ lb1 = (char *)sip_getimgptr(image, y-2); lb2 = (char *)sip_getimgptr(image, y-1); lb3 = (char *)sip_getimgptr(image, y); lb4 = (char *)sip_getimgptr(image, y+1); tf = 0; if ( rf[y] ){ for ( x=0 ; x<width ; x++ ) lbo[x] = (char)0xff; for ( x=2 ; x < (width -1) ; x++ ){ tn = 0; if ( ! lb1[x] ) tn |= 0x01; if ( ! lb2[x-1] ) tn |= 0x02; if ( ! lb2[x] ) tn |= 0x04; if ( ! lb2[x+1] ) tn |= 0x08; if ( ! lb3[x-2] ) tn |= 0x10; if ( ! lb3[x-1] ) tn |= 0x20; if ( ! lb3[x] ) tn |= 0x40; if ( ! lb3[x+1] ) tn |= 0x80; if ( ! lb4[x-1] ) tn |= 0x100; if ( ! lb4[x] ) tn |= 0x200; if ( ! lb4[x+1] ) tn |= 0x400; if ( thin(tn) ){ lbo[x] = 0; } else{ if ( tn & 0x40 ) tf = 1; } } } else{ for ( x=0 ; x<width ; x++ ) lbo[x] = lb3[x]; } if ( (rflag != 0) && (tf != 0) ){ if ( (y1 = y - 2) < 0 ) y1 = 0; if ( (y2 = y + 2) >= height ) y2 = height -1; for ( i=y1 ; i<=y2 ; i++ ) rflag[i] = 1; } tfa |= tf; for ( x=0 ; x<width ; x++ ) lb1[x] = lt1[x]; lttmp = lt1; lt1 = lt2; lt2 = lbo; lbo = lttmp; } if ( y > 2 ){ for ( x=0 ; x<width ; x++ ) lb1[x] = lt1[x]; for ( x=0 ; x<width ; x++ ) lb2[x] = lt2[x]; for ( x=0 ; x<width ; x++ ) lb3[x] = lbo[x]; } free(cf); free(lbuf); return(tfa); }
fireae/nhocr
O2-tools-2.01/libsrc/libsgp/histgram.c
<filename>O2-tools-2.01/libsrc/libsgp/histgram.c /*-------------------------------------------------------------- Signal processing function library libsgp ( Histogram analysis Rev.20000711 ) Written by H.Goto , Feb. 1995 Modified by H.Goto, July 2000 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1995-2000 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <math.h> #include "sgplib.h" double sgp_gethistmeani(int *hist,int len){ /* Get mean posision */ int i,sum,hsum; sum = hsum = 0; for ( i=0 ; i<len ; i++ ){ sum += hist[i]; hsum += i * hist[i]; } if ( !sum ) return(0); return( (double)hsum / (double)sum ); } double sgp_gethistsdi(int *hist,int len,double mean){ int i,h,sum; double d,sd; sd = 0; sum = 0; for ( i=0 ; i<len ; i++ ){ h = *hist++; sum += h; d = (double)i - mean; sd += (double)h * (d * d); } if ( !sum ) return(0); return ( sqrt(sd / sum) ); } double sgp_gethistmdi(int *hist,int len,double mean){ int i,h,sum; double md; md = 0; sum = 0; for ( i=0 ; i<len ; i++ ){ h = *hist++; sum += h; md += (double)h * fabs((double)i - mean); } if ( !sum ) return(0); return ( md / sum ); }
fireae/nhocr
libnhocr/ocrbase.h
<gh_stars>10-100 /*-------------------------------------------------------------- OCR base library (C) 2005-2014 <NAME> (see accompanying LICENSE file) Written by H.Goto, Dec. 2005 Revised by H.Goto, Feb. 2008 Revised by H.Goto, Apr. 2008 Revised by H.Goto, Sep. 2008 Revised by H.Goto, May 2009 Revised by H.Goto, Oct. 2009 Revised by H.Goto, Dec. 2009 Revised by H.Goto, Aug. 2014 --------------------------------------------------------------*/ #ifndef ocrbase_h #define ocrbase_h // Position hint #define PosHint_Mask 0x00ff #define PosHint_None 0x00 #define PosHint_Left 0x40 #define PosHint_Center 0x20 #define PosHint_Right 0x10 #define PosHint_Top 0x04 #define PosHint_Middle 0x02 #define PosHint_Bottom 0x01 // Geometry hint #define SizeHint_Mask 0x0f00 #define SizeHint_None 0x0000 #define SizeHint_Normal 0x0100 #define SizeHint_Small 0x0200 #define SizeHint_Tiny 0x0400 #define SizeHint_Ascender 0x0100 #define SizeHint_Descender 0x0200 #define SizeHint_Wide 0x8000 // Writing direction (Horizontal/Vertical font specification) #define WrtDir_Mask 0x0f0000 #define WrtDir_None 0x000000 #define WrtDir_H 0x010000 #define WrtDir_V 0x020000 class OCRPrep { public: int edge(SIPImage *src, SIPImage *dst); int thin(SIPImage *src, SIPImage *dst){ return( thin(src,dst,0) ); } int thin(SIPImage *src, SIPImage *dst, int maxiter); int normalize(SIPImage *src, SIPImage *dst, double alimit); }; class FeatureVector { public: int dim; double *e; int gHint; int alloc(int dim); int zeroVector(); int setVector(double *vec); int getVector(double *vec); double distEuclidean2(FeatureVector& vec); double distEuclidean2(FeatureVector& vec, double limit); double distEuclidean(FeatureVector& vec){ return(sqrt(distEuclidean2(vec))); } double distManhattan(FeatureVector& vec); double distChessboard(FeatureVector& vec); int write_vector(FILE *fp); int read_vector(FILE *fp); FeatureVector& operator=(FeatureVector& obj); FeatureVector& operator+=(FeatureVector& obj); FeatureVector(); FeatureVector(int dim); ~FeatureVector(); }; class RecResultItem { public: int id; double dist; }; class RecBase { protected: void initResultTable(); public: int n_top; int n_cat; FeatureVector *dic; RecResultItem *resultTable; int dealloc(); int alloc(int n_cat, int dim, int n_top); int recognizeEuclidean(FeatureVector& charvec, int gHint); // int recognizeManhattan(FeatureVector& charvec, int gHint); // int recognizeChessboard(FeatureVector& charvec, int gHint); RecBase(){ n_cat = n_top = 0; }; ~RecBase(); }; typedef int (*feature_fn_t)(SIPImage*, FeatureVector*); #ifdef __cplusplus extern "C" { #endif int ocrbase_loaddic(RecBase *Rec, char *dicfile, int dim, int n_top, int debug); int ocrbase_loaddic_bydiccodes(RecBase *Rec, char *dir, char *diccodes, int dim, int n_top, int debug); #ifdef __cplusplus } #endif #endif /* ocrbase_h */
fireae/nhocr
O2-tools-2.01/include/rasterfile.h
<reponame>fireae/nhocr<filename>O2-tools-2.01/include/rasterfile.h<gh_stars>10-100 /* rasterfile.h --- Sun Raster File Header Definitions */ #ifndef rasterfile_h #define rasterfile_h #define RAS_MAGIC 0x59a66a95 #define RT_OLD 0 #define RT_STANDARD 1 #define RT_BYTE_ENCODED 2 #define RT_FORMAT_RGB 3 #define RT_FORMAT_TIFF 4 #define RT_FORMAT_IFF 5 #define RT_EXPERIMENTAL 0xffff #define RMT_RAW 2 #define RMT_NONE 0 #define RMT_EQUAL_RGB 1 struct rasterfile { int ras_magic; int ras_width; int ras_height; int ras_depth; int ras_length; int ras_type; int ras_maptype; int ras_maplength; }; #endif /* rasterfile_h */
fireae/nhocr
O2-tools-2.01/include/siplib.h
<filename>O2-tools-2.01/include/siplib.h /*-------------------------------------------------------------- Image Processing functions v2.4 Written by H.Goto , Jul 1994 Revised by H.Goto , Nov 1995 Revised by H.Goto , May 1996 Revised by H.Goto , Sep 1997 Revised by H.Goto , Oct 1999 Revised by H.Goto , Apr 2000 Revised by H.Goto , Jul 2000 Revised by H.Goto , Sep 2000 Revised by H.Goto , Feb 2002 Revised by H.Goto , May 2002 Revised by H.Goto , Dec 2005 Revised by H.Goto , Apr 2007 Revised by H.Goto , Dec 2008 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994-2008 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef siplib_h #define siplib_h #include <utypes.h> /* define unsigned variables */ /*------------------------------------------------------ Common constants ------------------------------------------------------*/ #define BOP_NOP 0 #define BOP_PUT 1 #define BOP_OR 2 #define BOP_NOT 3 #define BOP_AND 4 #define BOP_XOR 5 #define BOP_SET 6 #define BOP_CLR 7 /*------------------------------------------------------ Structure definitions for Mask-Op. ------------------------------------------------------*/ typedef struct { int masksize; /* odd integer required */ /* ex. 5 for 5x5 matrix */ int depth; /* = 16 */ short div; /* normalize factor */ short *mask; } SIPMASKs; typedef struct { int masksize; int depth; /* = 32 */ int32 div; int32 *mask; } SIPMASKl; typedef struct { int masksize; int depth; /* = 32 | 0x8000 */ float div; float *mask; } SIPMASKf; typedef union { SIPMASKs s; SIPMASKl l; SIPMASKf f; } SIPMASK; /*------------------------------------------------------ Primitives ------------------------------------------------------*/ typedef struct { /* Rectangle */ int x,y; int width,height; } SIPRectangle; typedef struct { /* Line Segment */ int x1,y1,x2,y2; } SIPSegment; /*------------------------------------------------------ Image object ------------------------------------------------------*/ typedef struct { /* Image (Array) Object */ int width,height; int depth; /* 1,8,16,32 */ int bitmap_pad; /* 8,16,32 */ int bytes_per_line; char *data; void **pdata; } SIPImage; #ifndef siplib_c extern SIPImage SIPImage0; /* Skelton of SIPImage */ #endif extern SIPImage* sip_CreateImage(int width,int height,int depth); extern int sip_DestroyImage(SIPImage *image); extern SIPImage* sip_DuplicateImage(SIPImage *image); /*------------------------------------------------------ Image Data Manipulation ------------------------------------------------------*/ extern int sip_rawClearLine(char *buf,int len,int depth,int32 data); extern int sip_ClearLine(SIPImage *image,int y,int32 data); extern int sip_ClearImage(SIPImage *image,int32 data); extern int sip_CopyArea(SIPImage *src,SIPRectangle *srect,SIPImage *dst,SIPRectangle *drect); extern int sip_GetScanLine(SIPImage *image,void *buf,int x,int y,int len,int depth); extern int sip_PutScanLine(SIPImage *image,void *buf,int x,int y,int len,int depth); extern int sip_GetVertLine(SIPImage *image,void *buf,int x,int y,int len,int depth); extern int sip_PutVertLine(SIPImage *image,void *buf,int x,int y,int len,int depth); extern uchar sip_getbit(SIPImage *image,int x,int y); extern uchar sip_putbit(SIPImage *image,int x,int y,uchar b); extern uchar sip_orbit(SIPImage *image,int x,int y,uchar b); extern uchar sip_andbit(SIPImage *image,int x,int y,uchar b); extern uchar sip_xorbit(SIPImage *image,int x,int y,uchar b); #define _sip_getbit(image,x,y) \ (uchar)(( *((image)->data + (int32)(( (uint)(x) )>>3) \ + (int32)((uint)(y)) * (image)->bytes_per_line) \ & (0x01 << (7 - ((uint)(x) & 0x07))) ) != 0) /*------------------------------------------------------ Miscellaneous ------------------------------------------------------*/ extern char* sip_getimgptr(SIPImage *image,int y); extern int sip_getlinebytes(int len,int depth,int pad); extern void sip_CopyLine(char *src,char *dst,int width,int depth); /*------------------------------------------------------ Data conversion ------------------------------------------------------*/ extern void sip_cvt1to8(char *src,int bitoff,char *dst,int len,char fc,char bc); extern void sip_cvt1to16(char *src,int bitoff,short *dst,int len,short fc,short bc); extern void sip_cvt1to32(char *src,int bitoff,int32 *dst,int len,int32 fc,int32 bc); extern void sip_cvt8to16u(uchar *src,ushort *dst,int len,ushort mul); extern void sip_cvt8to16(char *src,short *dst,int len,short mul); extern void sip_cvt8to32u(uchar *src,uint32 *dst,int len,uint32 mul); extern void sip_cvt8to32(char *src,int32 *dst,int len,int32 mul); extern void sip_cvt16to32u(ushort *src,uint32 *dst,int len,uint32 mul); extern void sip_cvt16to32(short *src,int32 *dst,int len,int32 mul); extern void sip_cvt8to1(char *src,char *dst,int bitoff,int len,char th); extern void sip_cvt8to1u(uchar *src,uchar *dst,int bitoff,int len,uchar th); extern void sip_cvt16to1(short *src,char *dst,int bitoff,int len,short th); extern void sip_cvt16to8u(ushort *src,uchar *dst,int len,ushort mul,ushort div); /*------------------------------------------------------ Clipping ------------------------------------------------------*/ extern void clip8(char *src,char *dst,int len,char lo,char hi); extern void clip8u(uchar *src,uchar *dst,int len,uchar lo,uchar hi); extern void clip16(short *src,short *dst,int len,short lo,short hi); extern void clip16u(ushort *src,ushort *dst,int len,ushort lo,ushort hi); extern void clipint(int *src,int *dst,int len,int lo,int hi); extern void clipuint(uint *src,uint *dst,int len,uint lo,uint hi); /*------------------------------------------------------ Image rotation ------------------------------------------------------*/ extern int sip_rotate1(SIPImage *src,SIPImage *dst, \ int x0,int y0,double angle,int mode); extern int sip_rotate8(SIPImage *src,SIPImage *dst, \ int x0,int y0,double angle,int mode); /*------------------------------------------------------ Some useful functions ------------------------------------------------------*/ extern int sip_thin10neib(SIPImage *image,char *cflag,char *rflag); extern int sip_distimage(SIPImage *image,SIPImage *distimage,int maxdist); extern long sip_projprofile(SIPImage *image,long *rden,long *cden); extern long sip_projprofile_area(SIPImage *image, \ long *rden,long *cden,SIPRectangle *cbox); extern int sip_kNNsmooth(SIPImage *src,SIPImage *dst,int pixels,int ctweight); #endif /* siplib_h */ #ifdef __cplusplus } #endif
fireae/nhocr
O2-tools-2.01/libsrc/libufp/d8IO.h
<filename>O2-tools-2.01/libsrc/libufp/d8IO.h /*-------------------------------------------------------------- 8(4)-dim Data I/O class Header Include File Written by H.Goto , Sep. 1993 Modified by H.Goto , Feb. 1997 Modified by H.Goto , Apr. 2000 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1993-2000 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef d8IO_h #define d8IO_h #include <utypes.h> /*------------------------------------------------------ 8-dim Data Load/Save Definitions ------------------------------------------------------*/ #ifndef d8_BUFFERS #define d8_BUFFERS 512 #endif struct d8pac { short d8_data[8]; }; struct d8file { char d8_magic[8]; int32 d8_attrb; int32 d8_count; short d8_llimit[8]; short d8_hlimit[8]; short d8_spc[40]; }; #ifndef d8IO_c extern d8pac d8pac0; #endif /*------------------------------------------------------ 8-dim Data Load Class ------------------------------------------------------*/ class D8LOAD { private: FILE *fp; int count; int bufferptr; int flag_eof; int ndim; void *buffer; struct d8file header; public: int open(char *path); int close(void); int getdim(void){ return ndim; }; int getdata(d8pac *buf); int getlower(d8pac *buf); int getupper(d8pac *buf); int rewind(void); D8LOAD(void); virtual ~D8LOAD(void); }; /*------------------------------------------------------ 8-dim Data Save Class ------------------------------------------------------*/ class D8SAVE { private: FILE *fp; char wfname[256]; int count; void *buffer; struct d8file header; public: int creat(char *path,d8file *d8_info); int close(void); int putdata(d8pac *buf); D8SAVE(void); virtual ~D8SAVE(void); }; /*------------------------------------------------------ 4-dim Data Load/Save Definitions ------------------------------------------------------*/ #ifndef d4_BUFFERS #define d4_BUFFERS 1024 #endif struct d4pac { short d4_data[4]; }; struct d4file { char d4_magic[8]; int32 d4_attrb; int32 d4_count; short d4_llimit[4]; short d4_hlimit[4]; short d4_spc[48]; }; /*------------------------------------------------------ 4-dim Data Load Class ------------------------------------------------------*/ class D4LOAD { private: FILE *fp; int count; int bufferptr; int flag_eof; int ndim; void *buffer; struct d4file header; struct d8file *header8; public: int fileopen(char *path); int fileclose(void); int getdata(d4pac *buf); int getlower(d4pac *buf); int getupper(d4pac *buf); int rewind(void); D4LOAD(void); virtual ~D4LOAD(void); }; /*------------------------------------------------------ 4-dim Data Save Class ------------------------------------------------------*/ class D4SAVE { private: FILE *fp; char wfname[256]; int count; void *buffer; struct d4file header; public: int filecreat(char *path,d4file *d4_info); int fileclose(void); int putdata(d4pac *buf); D4SAVE(void); virtual ~D4SAVE(void); }; #endif // _d8IO_h
fireae/nhocr
include/sgplib.h
<filename>include/sgplib.h<gh_stars>10-100 /*-------------------------------------------------------------- Signal processing function library libsgp Written by H.Goto , Jan.1994 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif #ifndef sgplib_h #define sgplib_h #include "utypes.h" /*------------------------------------------------------ Walsh Transform functions ------------------------------------------------------*/ int sgp_wal(int n,int m,int nn); void sgp_walseq(int *buf,int m,int nn); void sgp_walseqb(char *buf,int m,int nn); void sgp_walmatrix(int *buf,int nn); void sgp_walmatrixb(char *buf,int nn); int sgp_WHT(int *data,int *sequency,int len,int *wmtx); int sgp_WHTb(char *data,int *sequency,int len,char *wmtx); void sgp_WHTpower(int *wseries,int *pow,int len); /*------------------------------------------------------ Get peaks ------------------------------------------------------*/ typedef struct { int pos; int value; } peaklisti; int sgp_getpeaksuc(uchar *src,peaklisti *pks, \ int size,int listsize,int thlow,int thhigh); int sgp_getpeaksi(int *src,peaklisti *pks, \ int size,int listsize,int thlow,int thhigh); /*------------------------------------------------------ Convolution ------------------------------------------------------*/ int sgp_convolutec(char *src,char *dst,int len,char sdata, \ char *mask,char div,int masklen); int sgp_convolutei(int *src,int *dst,int len,int sdata, \ int *mask,int div,int masklen); /*------------------------------------------------------ Get Correlation factor ------------------------------------------------------*/ int sgp_correlations(short *d1,short *d2,int len,short *corr, \ int maxmove,int periodic,short zero); int sgp_correlationi(int *d1,int *d2,int len,int *corr, \ int maxmove,int periodic,int zero); int sgp_correlationb(char *d1,char *d2,int len,int *corr, \ int maxmove,int periodic,char zero); /*------------------------------------------------------ Histogram analysis ------------------------------------------------------*/ double sgp_gethistmeani(int *hist,int len); double sgp_gethistsdi(int *hist,int len,double mean); double sgp_gethistmdi(int *hist,int len,double mean); #endif /* sgplib_h */ #ifdef __cplusplus } #endif
fireae/nhocr
O2-tools-2.01/include/xiplib.h
/*-------------------------------------------------------------- Extended Image Processing functions v1.1 Written by H.Goto , Dec 1998 Modified by H.Goto , May 2002 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1998-2002 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef xiplib_h #define xiplib_h #include <utypes.h> /* define unsigned variables */ #include <siplib.h> #include <imgobj.h> #include <objgrp.h> #include <ufilep.h> #ifdef __cplusplus extern "C" { #endif /*------------------------------------------------------ Load / Save Image File depthconv = 0: use file type = 8: convert image to 8bit ------------------------------------------------------*/ extern int xip_LoadImage(char *fname,SIPImage **image,int depthconv, \ int fgcol,int bgcol); extern int xip_SaveImage(char *fname,SIPImage *image); /*------------------------------------------------------ Create Connected Components (multilevel) mode = 0: 4-connection mode = 1: 8-connection mode ------------------------------------------------------*/ /* Note: The function xip_CreateCC() does not create 4-connected components and 8-connected components simultaneously. As well known, 4-connected components for foreground are not complements of 4-connected components for background topologically. 8-connected components for foreground are not complements of 8-connected components for background as well. Users are encouraged to use another function, xip_CreateCC2(), if topology analysis is required in bilevel images. */ extern int xip_CreateCC(SIPImage *image,GRPLST *ccpool,\ CRects *runpool,int mode); /*------------------------------------------------------ Create Connected Components (bilevel) mode = 0: 8-connection for background 4-connection for foreground = 1: 4-connection for background 8-connection for foreground ------------------------------------------------------*/ /* Note: The function xip_CreateCC2() creates 8-connected components and 4-connected components simultaneously. Mode for foreground and background images can be swapped by setting mode=1. The function xip_CreateCC2() assumes that the input image is bilevel. */ extern int xip_CreateCC2(SIPImage *image,GRPLST *ccpool,\ CRects *runpool,int mode); /*------------------------------------------------------ Create Connected Components (monolevel) mode = 0: 4-connection for foreground = 1: 8-connection for foreground ------------------------------------------------------*/ /* Note: The function xip_CreateCC1() creates only connected components for foreground image. Background image is ignored. This function is far faster and more convenient than xip_CreateCC2() when we use only connected components for foreground image. */ extern int xip_CreateCC1(SIPImage *image,GRPLST *ccpool,\ CRects *runpool,int mode); #ifdef __cplusplus } #endif #endif /* xiplib_h */
fireae/nhocr
include/pbmIO.h
<filename>include/pbmIO.h /*-------------------------------------------------------------- PBM (raw) file I/O class Header Include File Rev.970218 Written by H.Goto , Jan. 1995 Modified by H.Goto , July 1996 Modified by H.Goto , Feb. 1997 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1995-1997 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef pbmIO_h #define pbmIO_h #include <utypes.h> /*------------------------------------------------------ PBM (raw) file I/O Class ------------------------------------------------------*/ class PBMFILE { private: FILE *fp; char *wfname; int mode; int cline; int width,height,pixel; int flbytes,linebytes; uchar *linebuffer; int filetype; /* = 0 : 1bit/pixel */ /* 1 : 8bit grayscale */ /* 2 : 24bit color */ uchar fgcol,bgcol; int checksize(); int write_header(); int read_header(); int seekto(int line); public: int open(char *path,char *type); int close(void); int setpal_fb(uchar fg,uchar bg); int readline(int line,void *buf); int readline_gray(int line,void *buf); int getwidth(void) { return width; } int getheight(void) { return height; } int getfiletype(void) { return filetype; } int writeline(int line,void *buf); int writeline_bilevel(int line,void *buf,int threshold); int setsize(int width,int height,int pixel); PBMFILE(void); virtual ~PBMFILE(void); }; #endif // pbmIO_h
fireae/nhocr
O2-tools-2.01/libsrc/siplib/siplib.c
<reponame>fireae/nhocr<gh_stars>10-100 /*-------------------------------------------------------------- Image Processing functions Written by H.Goto , Jul 1994 Revised by H.Goto , Nov 1995 Revised by H.Goto , May 1996 Revised by H.Goto , Sep 1997 Revised by H.Goto , Oct 1998 Revised by H.Goto , Apr 2000 Revised by H.Goto , Nov 2001 Revised by H.Goto , Nov 2001 Revised by H.Goto , Feb 2002 Revised by H.Goto , May 2002 Revised by H.Goto , Jul 2003 Revised by H.Goto , Dec 2005 Revised by H.Goto , Apr 2007 Revised by H.Goto , Dec 2008 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994-2008 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <memory.h> #define siplib_c #include "siplib.h" /*------------------------------------------------------ Miscellaneous ------------------------------------------------------*/ /* Get pointer to the specific scanline */ char *sip_getimgptr(SIPImage *image,int y){ return((char *)image->pdata[y]); } /* Get line size in bytes */ int sip_getlinebytes(int len,int depth,int pad){ int l; pad /= 8; if ( depth == 1 ){ switch (pad){ case 2: return( ((len +15) /16) *2 ); case 4: return( ((len +31) /32) *4 ); default: return( (len +7) /8 ); } } l = len * (depth >> 3); switch (pad){ case 2: return( ((l +1) /2) *2 ); case 4: return( ((l +3) /4) *4 ); default: return(l); } } /* Copy ScanLine */ void sip_CopyLine(char *src,char *dst,int width,int depth){ int i; short *sps,*dps; int32 *spl,*dpl; i = (int)width; if ( width < 8 ){ switch (depth){ case 1: i = (i + 7) /8; case 8: for ( ; i>0 ; i-- ) *dst++ = *src++; break; case 16: sps = (short *)src; dps = (short *)dst; for ( ; i>0 ; i-- ) *dps++ = *sps++; break; case 32: spl = (int32 *)src; dpl = (int32 *)dst; for ( ; i>0 ; i-- ) *dpl++ = *spl++; break; } return; } switch (depth){ case 1: i = (i + 7) /8; break; case 8: break; case 16: i *= 2; break; case 32: i *= 4; break; } memcpy(dst,src,i); return; } /*------------------------------------------------------ Image object manipulation ------------------------------------------------------*/ SIPImage SIPImage0 = { 0,0,8,16,0,NULL }; /* Create image */ SIPImage *sip_CreateImage(int width,int height,int depth){ SIPImage *imgtmp; long linesize; long bufsize; void **pdata; int i; linesize = (long)((ulong)sip_getlinebytes(width,depth,16)); bufsize = linesize * (long)((ulong)height); if ( bufsize <= 0 ) return(NULL); if ( NULL == (imgtmp = (SIPImage *)malloc(sizeof(SIPImage))) ){ return(NULL); } if ( NULL == (pdata = (void **)malloc(sizeof(void *) * height)) ){ free((void *)imgtmp); return(NULL); } imgtmp->pdata = pdata; imgtmp->width = width; imgtmp->height = height; imgtmp->depth = depth; imgtmp->bitmap_pad = 16; imgtmp->bytes_per_line = linesize; if ( NULL == (imgtmp->data = (char *)malloc(bufsize)) ){ free((void *)pdata); free((void *)imgtmp); return(NULL); } for ( i=0 ; i<height ; i++ ){ pdata[i] = (void *)(imgtmp->data + i*linesize); } return(imgtmp); } /* Destroy image */ int sip_DestroyImage(SIPImage *image){ if ( NULL != image ){ if ( NULL != image->data ){ free((void *)image->pdata); free((void *)image->data); image->data = NULL; } free((void *)image); } return(0); } /* Duplicate image */ SIPImage *sip_DuplicateImage(SIPImage *image){ SIPImage *imgtmp; int y; if ( 0 == (imgtmp = sip_CreateImage(image->width,image->height,image->depth)) ) return(0); for ( y=0 ; y<image->height ; y++ ){ memcpy((void*)imgtmp->pdata[y], \ (void*)image->pdata[y], image->bytes_per_line); } return(imgtmp); } /* Fill a line by specified data (raw mode) */ int sip_rawClearLine(char *buf,int len,int depth,int32 data){ int c; char db; char *pc; short *ps; int32 *pl; if ( data ) db = (char)0xff; else db = 0; pl = (int32 *)( ps = (short *)( pc = buf ) ); c = len; switch ( depth ){ case 1: c = (c +7) /8; for ( ; c>0 ; c-- ) *pc++ = db; break; case 8: for ( ; c>0 ; c-- ) *pc++ = (char)data; break; case 16: for ( ; c>0 ; c-- ) *ps++ = (short)data; break; case 32: for ( ; c>0 ; c-- ) *pl++ = (int32)data; break; } return(0); } /* Fill a line by specified data */ int sip_ClearLine(SIPImage *image,int y,int32 data){ char *p; if ( NULL == image->data ) return(-1); if ( NULL == (p = sip_getimgptr(image,y)) ) return(-1); return( sip_rawClearLine(p,image->width,image->depth,data) ); } /* Fill image by specified data */ int sip_ClearImage(SIPImage *image,int32 data){ int c,y; char db; char *p,*pc; short *ps; int32 *pl; if ( data ) db = (char)0xff; else db = 0; if ( NULL == image->data ) return(-1); if ( NULL == (p = sip_getimgptr(image,0)) ) return(-1); for ( y=0 ; y < image->height ; y++ ){ pl = (int32 *)( ps = (short *)(pc = p) ); c = image->width; switch ( image->depth ){ case 1: c = (c +7) /8; for ( ; c>0 ; c-- ) *pc++ = db; break; case 8: for ( ; c>0 ; c-- ) *pc++ = (char)data; break; case 16: for ( ; c>0 ; c-- ) *ps++ = (short)data; break; case 32: for ( ; c>0 ; c-- ) *pl++ = (int32)data; break; } p += image->bytes_per_line; } return(0); } /* Copy area from src_image to dst_image */ /* 1. depth,width,height must match */ /* 2. x,y,width,height must be */ /* multiples of 8 for 1bit-image */ int sip_CopyArea(SIPImage *src,SIPRectangle *srect, SIPImage *dst,SIPRectangle *drect){ ushort x,y; char *sp,*dp; char *spb,*dpb; short *sps,*dps; int32 *spl,*dpl; int depth; if ( src->depth != dst->depth ) return(-2); depth = src->depth; if ( srect->width != drect->width ) return(-2); if ( srect->height != drect->height ) return(-2); if ( (srect->x < 0) || (srect->y < 0) ) return(-1); if ( (drect->x < 0) || (drect->y < 0) ) return(-1); if ( (srect->x + srect->width ) > src->width ) return(0); if ( (srect->y + srect->height) > src->height ) return(0); if ( (drect->x + drect->width ) > dst->width ) return(0); if ( (drect->y + drect->height) > dst->height ) return(0); if ( NULL == (sp = sip_getimgptr(src,srect->y)) ) return(-1); if ( NULL == (dp = sip_getimgptr(dst,drect->y)) ) return(-1); if ( depth == 1 ){ if ( srect->width & 0x07 ) return(-1); if ( srect->x & 0x07 ) return(-1); if ( drect->x & 0x07 ) return(-1); sp += srect->x >> 3; dp += drect->x >> 3; } else{ sp += (depth >> 3) * srect->x; dp += (depth >> 3) * drect->x; } for ( y=0 ; y < srect->height ; y++ ){ spl = (int32 *)( sps = (short *)( spb = sp ) ); dpl = (int32 *)( dps = (short *)( dpb = dp ) ); switch (depth){ case 1: for ( x=0 ; x < (srect->width >> 3) ; x++ ) *dpb++ = *spb++; break; case 8: for ( x=0 ; x < srect->width ; x++ ) *dpb++ = *spb++; break; case 16: for ( x=0 ; x < srect->width ; x++ ) *dps++ = *sps++; break; case 32: for ( x=0 ; x < srect->width ; x++ ) *dpl++ = *spl++; break; } sp += src->bytes_per_line; dp += dst->bytes_per_line; } return(0); } /* Get a scan line data */ /* len = -1 means "to end of line" */ int sip_GetScanLine(SIPImage *image, \ void *buf,int x,int y,int len,int depth){ int i; char *p; int direct = 0; char *buf8; short *buf16, *p16; int32 *buf32, *p32; if ( (x < 0) || (x >= image->width ) ) return(-1); if ( (y < 0) || (y >= image->height) ) return(-1); if ( (len < 0) || (x + len) > image->width ) len = image->width - x; if ( NULL == (p = sip_getimgptr(image,y)) ) return(-1); if ( depth == image->depth ) direct = 1; if ( ! direct ){ return(-2); } else{ switch (image->depth){ case 1: if ( x & 0x07 ) return(-1); p += x >> 3; if ( len & 0x07 ) return(-1); len >>= 3; buf8 = (char *)buf; for ( i=0 ; i<len ; i++ ) *buf8++ = *p++; break; case 8: p += x; buf8 = (char *)buf; for ( i=0 ; i<len ; i++ ) *buf8++ = *p++; break; case 16: p += 2 * x; buf16 = (short *)buf; p16 = (short *)p; for ( i=0 ; i<len ; i++ ) *buf16++ = *p16++; break; case 32: p += 4 * x; buf32 = (int32 *)buf; p32 = (int32 *)p; for ( i=0 ; i<len ; i++ ) *buf32++ = *p32++; break; } } return(0); } /* Put a scan line data */ /* len = -1 means "to end of line" */ int sip_PutScanLine(SIPImage *image, \ void *buf,int x,int y,int len,int depth){ int i; char *p; int direct = 0; char *buf8; short *buf16, *p16; int32 *buf32, *p32; if ( (x < 0) || (x >= image->width ) ) return(-1); if ( (y < 0) || (y >= image->height) ) return(-1); if ( (len < 0) || (x + len) > image->width ) len = image->width - x; if ( NULL == (p = sip_getimgptr(image,y)) ) return(-1); if ( depth == image->depth ) direct = 1; if ( ! direct ){ return(-2); } else{ switch (image->depth){ case 1: if ( x & 0x07 ) return(-1); p += x >> 3; if ( len & 0x07 ) return(-1); len >>= 3; buf8 = (char *)buf; for ( i=0 ; i<len ; i++ ) *p++ = *buf8++; break; case 8: p += x; memcpy(p,buf,len); break; case 16: p += 2 * x; buf16 = (short *)buf; p16 = (short *)p; for ( i=0 ; i<len ; i++ ) *p16++ = *buf16++; break; case 32: p += 4 * x; buf32 = (int32 *)buf; p32 = (int32 *)p; for ( i=0 ; i<len ; i++ ) *p32++ = *buf32++; break; } } return(0); } /* Get a vertical scan line data */ /* len = -1 means "to end of line" */ int sip_GetVertLine(SIPImage *image, \ void *buf,int x,int y,int len,int depth){ int i; char *p; int direct = 0; uchar mask0,mask,d; char *buf8; short *buf16; int32 *buf32; if ( (x < 0) || (x >= image->width ) ) return(-1); if ( (y < 0) || (y >= image->height) ) return(-1); if ( (len < 0) || (y + len) > image->height ) len = image->height - y; if ( NULL == (p = sip_getimgptr(image,y)) ) return(-1); if ( depth == image->depth ) direct = 1; if ( ! direct ){ return(-2); } else{ switch (image->depth){ case 1: mask0 = (mask = (uchar)0x80) >> (x & 0x07); d = 0; if ( y & 0x07 ) return(-1); p += (x >> 3); buf8 = (char *)buf; for ( i=0 ; i<len ; i++ ){ if ( mask0 & *p ) d |= mask; p += image->bytes_per_line; if ( 0 == (mask >>= 1) ){ *(++buf8) = d; mask = (uchar)0x80; } } if ( mask != (uchar)0x80 ) *buf8++ = d; break; case 8: p += x; buf8 = (char *)buf; for ( i=0 ; i<len ; i++ ){ *buf8++ = *p; p += image->bytes_per_line; } break; case 16: p += 2 * x; buf16 = (short *)buf; for ( i=0 ; i<len ; i++ ){ *buf16++ = *((short *)p); p += image->bytes_per_line; } break; case 32: p += 4 * x; buf32 = (int32 *)buf; for ( i=0 ; i<len ; i++ ){ *buf32++ = *((int32 *)p); p += image->bytes_per_line; } break; } } return(0); } /* Put a vertical scan line data */ /* len = -1 means "to end of line" */ int sip_PutVertLine(SIPImage *image, \ void *buf,int x,int y,int len,int depth){ int i; char *p; int direct = 0; uchar mask0,mask,d0,d; char *buf8; short *buf16; int32 *buf32; if ( (x < 0) || (x >= image->width ) ) return(-1); if ( (y < 0) || (y >= image->height) ) return(-1); if ( (len < 0) || (y + len) > image->height ) len = image->height - y; if ( NULL == (p = sip_getimgptr(image,y)) ) return(-1); if ( depth == image->depth ) direct = 1; if ( ! direct ){ return(-2); } else{ switch (image->depth){ case 1: mask0 = (mask = (uchar)0x80) >> (x & 0x07); d = *((char *)buf); if ( y & 0x07 ) return(-1); p += (x >> 3); buf8 = (char *)buf; for ( i=0 ; i<len ; i++ ){ d0 = *p & ~mask0; if ( mask & d ) d0 |= mask0; *p = d0; p += image->bytes_per_line; if ( 0 == (mask >>= 1) ){ d = *(++buf8); mask = (uchar)0x80; } } break; case 8: p += x; buf8 = (char *)buf; for ( i=0 ; i<len ; i++ ){ *p = *buf8++; p += image->bytes_per_line; } break; case 16: p += 2 * x; buf16 = (short *)buf; for ( i=0 ; i<len ; i++ ){ *((short *)p) = *buf16++; p += image->bytes_per_line; } break; case 32: p += 4 * x; buf32 = (int32 *)buf; for ( i=0 ; i<len ; i++ ){ *((int32 *)p) = *buf32++; p += image->bytes_per_line; } break; } } return(0); } /* Get pixel value on bitmap image */ uchar sip_getbit(SIPImage *image,int x,int y){ uchar b; uchar mask; mask = 0x01 << (7 - (x & 0x07)); b = *(image->data + (int32)(x>>3) + (int32)y * image->bytes_per_line) & mask; return( (uchar)(b != 0) ); } /* Put pixel value on bitmap image */ uchar sip_putbit(SIPImage *image,int x,int y,uchar b){ uchar *p; uchar mask; mask = 0x01 << (7 - (x & 0x07)); if ( b != 0 ) b = (uchar)0xff; p = (uchar *)image->data + (int32)(x>>3) + (int32)y * image->bytes_per_line; *p = (*p & ~mask) | (b & mask); return(b); } /* OR & put pixel value on bitmap image */ uchar sip_orbit(SIPImage *image,int x,int y,uchar b){ uchar *p; uchar mask; mask = 0x01 << (7 - (x & 0x07)); if ( b != 0 ) b = (uchar)0xff; p = (uchar *)image->data + (int32)(x>>3) + (int32)y * image->bytes_per_line; *p = *p | (b & mask); return(b); } /* AND & put pixel value on bitmap image */ uchar sip_andbit(SIPImage *image,int x,int y,uchar b){ uchar *p; uchar mask; mask = 0x01 << (7 - (x & 0x07)); if ( b != 0 ) b = (uchar)0xff; p = (uchar *)image->data + (int32)(x>>3) + (int32)y * image->bytes_per_line; *p = *p & (b & mask); return(b); } /* XOR & put pixel value on bitmap image */ uchar sip_xorbit(SIPImage *image,int x,int y,uchar b){ uchar *p; uchar mask; mask = 0x01 << (7 - (x & 0x07)); if ( b != 0 ) b = (uchar)0xff; p = (uchar *)image->data + (int32)(x>>3) + (int32)y * image->bytes_per_line; *p = *p ^ (b & mask); return(b); } /*------------------------------------------------------ Data conversion ------------------------------------------------------*/ /* Depth conversion from 1bit to 8bit */ void sip_cvt1to8(char *src,int bitoff,char *dst,int len,char fc,char bc){ int i; uchar d; uchar mask; if ( bitoff ){ mask = 0x80 >> bitoff; bitoff = 8 - bitoff; d = (uchar)*src++; for ( i=0 ; (i < bitoff) && (len > 0) ; i++, len--, mask >>= 1 ){ if ( d & mask ) *dst++ = fc; else *dst++ = bc; } } for ( i = len >> 3 ; i>0 ; i-- ){ d = (uchar)*src++; if ( d & 0x80 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x40 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x20 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x10 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x08 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x04 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x02 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x01 ) *dst++ = fc; else *dst++ = bc; } mask = (uchar)0x80; d = (uchar)*src++; for ( i = len & 0x07 ; i>0 ; i-- ){ if ( d & mask ) *dst++ = fc; else *dst++ = bc; mask >>= 1; } } /* Depth conversion from 1bit to 16bit */ void sip_cvt1to16(char *src,int bitoff,short *dst,int len,short fc,short bc){ int i; uchar d; uchar mask; if ( bitoff ){ mask = 0x80 >> bitoff; bitoff = 8 - bitoff; d = (uchar)*src++; for ( i=0 ; (i < bitoff) && (len > 0) ; i++, len--, mask >>= 1 ){ if ( d & mask ) *dst++ = fc; else *dst++ = bc; } } for ( i = len >> 3 ; i>0 ; i-- ){ d = (uchar)*src++; if ( d & 0x80 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x40 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x20 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x10 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x08 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x04 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x02 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x01 ) *dst++ = fc; else *dst++ = bc; } mask = (uchar)0x80; d = (uchar)*src++; for ( i = len & 0x07 ; i>0 ; i-- ){ if ( d & mask ) *dst++ = fc; else *dst++ = bc; mask >>= 1; } } /* Depth conversion from 1bit to 32bit */ void sip_cvt1to32(char *src,int bitoff,int32 *dst,int len,int32 fc,int32 bc){ int i; uchar d; uchar mask; if ( bitoff ){ mask = 0x80 >> bitoff; bitoff = 8 - bitoff; d = (uchar)*src++; for ( i=0 ; (i < bitoff) && (len > 0) ; i++, len--, mask >>= 1 ){ if ( d & mask ) *dst++ = fc; else *dst++ = bc; } } for ( i = len >> 3 ; i>0 ; i-- ){ d = (uchar)*src++; if ( d & 0x80 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x40 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x20 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x10 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x08 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x04 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x02 ) *dst++ = fc; else *dst++ = bc; if ( d & 0x01 ) *dst++ = fc; else *dst++ = bc; } mask = (uchar)0x80; d = (uchar)*src++; for ( i = len & 0x07 ; i>0 ; i-- ){ if ( d & mask ) *dst++ = fc; else *dst++ = bc; mask >>= 1; } } /* Depth conversion from 8bit to 16bit */ /* (unsigned) */ void sip_cvt8to16u(uchar *src,ushort *dst,int len,ushort mul){ int i; if ( mul == 1 ){ for ( i=0 ; i<len ; i++ ) *dst++ = (ushort)*src++; } else{ for ( i=0 ; i<len ; i++ ) *dst++ = (ushort)*src++ * mul; } } /* Depth conversion from 8bit to 16bit */ /* (signed) */ void sip_cvt8to16(char *src,short *dst,int len,short mul){ int i; if ( mul == 1 ){ for ( i=0 ; i<len ; i++ ) *dst++ = (short)*src++; } else{ for ( i=0 ; i<len ; i++ ) *dst++ = (short)*src++ * mul; } } /* Depth conversion from 8bit to 32bit */ /* (unsigned) */ void sip_cvt8to32u(uchar *src,uint32 *dst,int len,uint32 mul){ int i; if ( mul == 1 ){ for ( i=0 ; i<len ; i++ ) *dst++ = (uint32)*src++; } else{ for ( i=0 ; i<len ; i++ ) *dst++ = (uint32)*src++ * mul; } } /* Depth conversion from 8bit to 32bit */ /* (signed) */ void sip_cvt8to32(char *src,int32 *dst,int len,int32 mul){ int i; if ( mul == 1 ){ for ( i=0 ; i<len ; i++ ) *dst++ = (int32)*src++; } else{ for ( i=0 ; i<len ; i++ ) *dst++ = (int32)*src++ * mul; } } /* Depth conversion from 16bit to 32bit */ /* (unsigned) */ void sip_cvt16to32u(ushort *src,uint32 *dst,int len,uint32 mul){ int i; if ( mul == 1 ){ for ( i=0 ; i<len ; i++ ) *dst++ = (uint32)*src++; } else{ for ( i=0 ; i<len ; i++ ) *dst++ = (uint32)*src++ * mul; } } /* Depth conversion from 16bit to 32bit */ /* (signed) */ void sip_cvt16to32(short *src,int32 *dst,int len,int32 mul){ int i; if ( mul == 1 ){ for ( i=0 ; i<len ; i++ ) *dst++ = (int32)*src++; } else{ for ( i=0 ; i<len ; i++ ) *dst++ = (int32)*src++ * mul; } } /* Depth conversion from 8bit to 1bit */ /* (signed) */ void sip_cvt8to1(char *src,char *dst,int bitoff,int len,char th){ int i,len8; char d; uchar m; if ( bitoff != 0 ){ m = (uchar)((int)0x80 >> bitoff); d = *dst; for ( i = 8 - bitoff ; i > 0 && len > 0 ; i--, len-- ){ if ( *src > th ) d |= m; else d &= ~m; ++src; m >>= 1; } *dst++ = d; } len8 = len / 8; len = len - len8 * 8; for ( ; len8 > 0 ; len8-- ){ d = 0; if ( *src > th ) d |= (char)0x80; ++src; if ( *src > th ) d |= (char)0x40; ++src; if ( *src > th ) d |= (char)0x20; ++src; if ( *src > th ) d |= (char)0x10; ++src; if ( *src > th ) d |= (char)0x08; ++src; if ( *src > th ) d |= (char)0x04; ++src; if ( *src > th ) d |= (char)0x02; ++src; if ( *src > th ) d |= (char)0x01; ++src; *dst++ = d; } if ( len != 0 ){ d = *dst; m = 0x80; for ( ; len > 0 ; len-- ){ if ( *src > th ) d |= m; else d &= ~m; ++src; m >>= 1; } *dst++ = d; } } /* Depth conversion from 8bit to 1bit */ /* (unsigned) */ void sip_cvt8to1u(uchar *src,uchar *dst,int bitoff,int len,uchar th){ int i,len8; uchar d; uchar m; if ( bitoff != 0 ){ m = 0x80 >> bitoff; d = *dst; for ( i = 8 - bitoff ; i > 0 && len > 0 ; i--, len-- ){ if ( *src > th ) d |= m; else d &= ~m; ++src; m >>= 1; } *dst++ = d; } len8 = len / 8; len = len - len8 * 8; for ( ; len8 > 0 ; len8-- ){ d = 0; if ( *src > th ) d |= (uchar)0x80; ++src; if ( *src > th ) d |= (uchar)0x40; ++src; if ( *src > th ) d |= (uchar)0x20; ++src; if ( *src > th ) d |= (uchar)0x10; ++src; if ( *src > th ) d |= (uchar)0x08; ++src; if ( *src > th ) d |= (uchar)0x04; ++src; if ( *src > th ) d |= (uchar)0x02; ++src; if ( *src > th ) d |= (uchar)0x01; ++src; *dst++ = d; } if ( len != 0 ){ d = *dst; m = 0x80; for ( ; len > 0 ; len-- ){ if ( *src > th ) d |= m; else d &= ~m; ++src; m >>= 1; } *dst++ = d; } } /* Depth conversion from 16bit to 1bit */ /* (signed) */ void sip_cvt16to1(short *src,char *dst,int bitoff,int len,short th){ int i,len8; char d; char m; if ( bitoff != 0 ){ m = 0x80 >> bitoff; d = *dst; for ( i = 8 - bitoff ; i > 0 && len > 0 ; i--, len-- ){ if ( *src > th ) d |= m; else d &= ~m; ++src; m >>= 1; } *dst++ = d; } len8 = len / 8; len = len - len8 * 8; for ( ; len8 > 0 ; len8-- ){ d = 0; if ( *src > th ) d |= (char)0x80; ++src; if ( *src > th ) d |= (char)0x40; ++src; if ( *src > th ) d |= (char)0x20; ++src; if ( *src > th ) d |= (char)0x10; ++src; if ( *src > th ) d |= (char)0x08; ++src; if ( *src > th ) d |= (char)0x04; ++src; if ( *src > th ) d |= (char)0x02; ++src; if ( *src > th ) d |= (char)0x01; ++src; *dst++ = d; } if ( len != 0 ){ d = *dst; m = (char)0x80; for ( ; len > 0 ; len-- ){ if ( *src > th ) d |= m; else d &= ~m; ++src; m >>= 1; } *dst++ = d; } } /* Depth conversion from 16bit to 8bit */ /* (unsigned) */ void sip_cvt16to8u(ushort *src,uchar *dst,int len,ushort mul,ushort div){ int i; if ( mul == 1 ){ if ( div == 1 ) for ( i=0 ; i<len ; i++ ) *dst++ = (uchar)*src++; else for ( i=0 ; i<len ; i++ ) *dst++ = (uchar)(*src++ / div); } else{ if ( div == 1 ) for ( i=0 ; i<len ; i++ ) *dst++ = (uchar)(*src++ * mul); else for ( i=0 ; i<len ; i++ ) *dst++ = (uchar)((*src++ * mul) / div); } } /*------------------------------------------------------ Clipping ------------------------------------------------------*/ void clip8(char *src,char *dst,int len,char lo,char hi){ char d; for ( ; len > 0 ; len-- ){ d = *src++; if ( d < lo ) d = lo; if ( d > hi ) d = hi; *dst++ = d; } } void clip8u(uchar *src,uchar *dst,int len,uchar lo,uchar hi){ uchar d; for ( ; len > 0 ; len-- ){ d = *src++; if ( d < lo ) d = lo; if ( d > hi ) d = hi; *dst++ = d; } } void clip16(short *src,short *dst,int len,short lo,short hi){ short d; for ( ; len > 0 ; len-- ){ d = *src++; if ( d < lo ) d = lo; if ( d > hi ) d = hi; *dst++ = d; } } void clip16u(ushort *src,ushort *dst,int len,ushort lo,ushort hi){ ushort d; for ( ; len > 0 ; len-- ){ d = *src++; if ( d < lo ) d = lo; if ( d > hi ) d = hi; *dst++ = d; } } void clipint(int *src,int *dst,int len,int lo,int hi){ int d; for ( ; len > 0 ; len-- ){ d = *src++; if ( d < lo ) d = lo; if ( d > hi ) d = hi; *dst++ = d; } } void clipuint(uint *src,uint *dst,int len,uint lo,uint hi){ uint d; for ( ; len > 0 ; len-- ){ d = *src++; if ( d < lo ) d = lo; if ( d > hi ) d = hi; *dst++ = d; } }
fireae/nhocr
O2-tools-2.01/libsrc/libimgo/ORect.h
<filename>O2-tools-2.01/libsrc/libimgo/ORect.h /*-------------------------------------------------------------- Image object library libimgo , H.Goto Nov.1997 Class: ORects Last modified Nov. 1997 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1997 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef ORect_h #define ORect_h #define ORSTAT_Active 0x8000 #define ORSTAT_NonLink -1 /*------------------------------------------------------ Oriented Rectangle ------------------------------------------------------*/ class ORect { private: int stat; public: int prev,next; /* Note: Don't use pointer, because the data will be relocated. */ int link; int attr,attr1,attr2; double attrd,attrd1,attrd2; void *attrp; int x,y,x1,y1; int w,h; double a; /* Note: attr1-2,attrd1-2,x1 and y1 are optional members. */ inline void setstat(int stat); inline int getstat(){ return( stat & ~ORSTAT_Active ); } inline void enable(){ stat |= ORSTAT_Active; } inline void disable(){ stat &= ~ORSTAT_Active; } inline int isactive(){ return( stat & ORSTAT_Active ); } inline void init(); void init(int x,int y,int w,int h,double a); /* ORect should not have constructor for SPEED reason. */ }; inline void ORect :: setstat(int stat){ stat &= ~ORSTAT_Active; ORect::stat = (ORect::stat & ORSTAT_Active) | stat; } inline void ORect :: init(){ stat = 0; prev = next = ORSTAT_NonLink; link = ORSTAT_NonLink; attr = 0; attrd = 0; attrp = 0; x = y = w = h = 0; a = 0; /* Note: The optional members aren't initialized. */ } /*------------------------------------------------------ Rectangle Object List ------------------------------------------------------*/ class ORects { private: int maxrects; int inc_step; int incalloc(); protected: ORect* rectlist; public: int counts; int alloc(int size); int realloc(int size); int clear(void); int truncate(void); void set_incstep(int step){ inc_step = step; } int create(int x,int y,int w,int h,double a); int destroy(int rid); /* Warning: Functions truncate() and destroy() don't update */ /* prev or next. You should not call any of these */ /* if you're using linked-list. */ int set(int rid,int x,int y,int w,int h,double a); int setstat(int rid,int stat); int getstat(int rid); ORect* getrect(int rid){ return(&rectlist[rid]); } int setlink(int rid,int link); int getlink(int rid); int setattrp(int rid,void *attr); void* getattrp(int rid); int setattr(int rid,int attr); int getattr(int rid); int setattrd(int rid,double attr); double getattrd(int rid); int isactive(int rid); ORects(void); ORects(int incstep); virtual ~ORects(void); }; #endif /* ORect_h */
fireae/nhocr
O2-tools-2.01/include/rasIO.h
/*-------------------------------------------------------------- Rasterfile I/O class Header Include File Rev.970218 Written by H.Goto , Jan. 1993 Modified by H.Goto , Feb. 1997 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1993-1997 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef rasIO_h #define rasIO_h #include "rasterfile.h" #include "utypes.h" /*------------------------------------------------------ Rasterfile Load Class ------------------------------------------------------*/ class RASLOAD { private: FILE *fp; int line; int width,height,pixel; int linebytes; uchar *linebuffer; struct rasterfile raster_header; int filetype; /* = 0 : 1bit/pixel */ /* 1 : 8bit grayscale */ uchar fgcol,bgcol; protected: void convert_1to8(uchar *src,uchar *dst,int size); public: int fileopen(char *path); int fileclose(void); int readLine(void *buf); int readLine_gray(void *buf); int getWidth(void) { return width; } int getHeight(void) { return height; } int getFiletype(void) { return filetype; } void setfgcolor(uchar fgcol,uchar bgcol); RASLOAD(void); virtual ~RASLOAD(void); }; /*------------------------------------------------------ Rasterfile Save Class ------------------------------------------------------*/ class RASSAVE { private: FILE *fp; char wfname[256]; int line; int width,height,pixel; int width2,height2; int linebytes; uchar *linebuffer; struct rasterfile raster_header; int filetype; /* = 0 : 1bit/pixel */ /* 1 : 8bit grayscale */ protected: void convert_8to1(uchar *src,uchar *dst,int size,uchar threshold); public: int filecreat(char *path,int filetype,int width,int height); int fileclose(void); int writeLine(void *buf); int writeLine_mono(void *buf,int threshold); RASSAVE(void); virtual ~RASSAVE(void); }; #endif // rasIO_h
fireae/nhocr
libnhocr/segchar_adhoc.h
<reponame>fireae/nhocr<filename>libnhocr/segchar_adhoc.h /*---------------------------------------------------------------------- Character segmentation function segchar_adhoc.h (an Ad-hoc version) Written by H.Goto, Jan. 2008 Revised by H.Goto, Feb. 2008 Revised by H.Goto, Apr. 2008 Revised by H.Goto, Sep. 2008 Revised by H.Goto, Jan. 2009 Revised by H.Goto, May 2009 Revised by H.Goto, July 2009 Revised by H.Goto, Oct. 2009 Revised by H.Goto, Jan. 2013 Revised by H.Goto, Aug. 2014 ----------------------------------------------------------------------*/ /*-------------- Copyright 2008-2014 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------*/ #ifndef _segchar_adhoc_h #define _segchar_adhoc_h #include "utypes.h" #include "siplib.h" #include "nhocr.h" extern "C" { int segmentchars(SIPImage *lineimage, \ CharBox *cba, CharBox *cba_raw, \ double *avrcwidth, double *lineheight, double *charpitch, \ int force_alpha, int wdir, int debug); //void delete_cblist(CharBox *cblist); } #endif // _segchar_adhoc_h
fireae/nhocr
include/utypes.h
/*-------------------------------------------------------------- User's type definitions Rev.020527 Written by H.Goto , May 1996 Modified by H.Goto , Sep 1997 Modified by H.Goto , Apr 2000 Modified by H.Goto , Jan 2001 Modified by H.Goto , May 2002 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1996-2002 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of modification is specified in cases where modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #ifndef utypes_h #define utypes_h #if !defined(AIXV3) && !defined(AIXV4) && !defined(__alpha) typedef unsigned char uchar; typedef unsigned long ulong; #endif #if !defined(AIXV4) && !defined(__alpha) typedef unsigned short ushort; typedef unsigned int uint; #endif #if defined(__alpha) || defined(__ia64__) || (defined(__sgi) && (_MIPS_SZLONG == 64)) #if !defined(LONG64) #define LONG64 #endif #endif typedef unsigned int uint32; typedef int int32; #endif /* utypes_h */
fireae/nhocr
O2-tools-2.01/libsrc/libsgp/convol.c
/*-------------------------------------------------------------- Signal processing function library libsgp ( Convolution Rev.940809) Written by H.Goto , Aug.1994 --------------------------------------------------------------*/ /*-------------------------------------------------------------------- Copyright (C) 1994 <NAME> All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose is hereby granted without fee, provided that (i) the above copyright notice and this permission notice appear in all copies and in supporting documentation, (ii) the name of the author, <NAME>, may not be used in any advertising or otherwise to promote the sale, use or other dealings in this software without prior written authorization from the author, (iii) this software may not be used for commercial products without prior written permission from the author, and (iv) the notice of the modification is specified in case of that the modified copies of this software are distributed. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. THE AUTHOR WILL NOT BE RESPONSIBLE FOR ANY DAMAGE CAUSED BY THIS SOFTWARE. --------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <memory.h> #include "sgplib.h" /*------------------------------------------------------ Convolution ------------------------------------------------------*/ int sgp_convolutec(char *src,char *dst,int len,char sdata, \ char *mask,char div,int masklen){ char *buf,sum; int i,j,off; off = (masklen -1) /2; if ( NULL == (buf = (char *)malloc(len + masklen)) ) return(-1); for ( i=0 ; i<off ; i++ ) buf[i] = sdata; for ( i=(off + masklen) ; i<(len + masklen) ; i++ ) buf[i] = sdata; memcpy((char *)&buf[off],(char *)src,len * sizeof(char)); if ( div == 1 ){ for ( i=0 ; i<len ; i++ ){ sum = 0; for ( j=0 ; j<masklen ; j++ ) sum += mask[j] * buf[i + j]; *dst++ = sum; } } else{ for ( i=0 ; i<len ; i++ ){ sum = 0; for ( j=0 ; j<masklen ; j++ ) sum += mask[j] * buf[i + j]; *dst++ = sum / div; } } free(buf); return(0); } int sgp_convolutei(int *src,int *dst,int len,int sdata, \ int *mask,int div,int masklen){ int *buf,sum; int i,j,off; off = (masklen -1) /2; if ( NULL == (buf = (int *)malloc((len + masklen) * sizeof(int))) ) return(-1); for ( i=0 ; i<off ; i++ ) buf[i] = sdata; for ( i=(off + masklen) ; i<(len + masklen) ; i++ ) buf[i] = sdata; memcpy((char *)&buf[off],(char *)src,len * sizeof(int)); if ( div == 1 ){ for ( i=0 ; i<len ; i++ ){ sum = 0; for ( j=0 ; j<masklen ; j++ ) sum += mask[j] * buf[i + j]; *dst++ = sum; } } else{ for ( i=0 ; i<len ; i++ ){ sum = 0; for ( j=0 ; j<masklen ; j++ ) sum += mask[j] * buf[i + j]; *dst++ = sum / div; } } free(buf); return(0); }
edgexfoundry-holding/protocol-ezmq-c
samples/csubscriber.c
<reponame>edgexfoundry-holding/protocol-ezmq-c<filename>samples/csubscriber.c<gh_stars>0 /******************************************************************************* * Copyright 2017 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include<stdint.h> #include "cezmqapi.h" #include "cezmqsubscriber.h" #include "cezmqevent.h" #include "cezmqbytedata.h" #include "cezmqreading.h" #include "cezmqerrorcodes.h" int g_isStarted = 0; pthread_cond_t g_cv; pthread_mutex_t g_mutex; pthread_condattr_t g_cattr; /* The commented lines is written for reference purpose. * Uncomment the lines in case you want to see all the fields of * received event and readings. */ void printEvent(ezmqMsgHandle_t event) { /* long value; ezmqEventGetID(event, &value2); printf("\nid: %s",value2); ezmqEventGetCreated(event, &value); printf("\ncreated: %ld", value); ezmqEventGetModified(event, &value); printf("\nmodified: %ld", value); ezmqEventGetOrigin(event, &value); printf("\norigin: %ld", value); ezmqEventGetPushed(event, &value); printf("\npushed: %ld", value);*/ char *value2; ezmqEventGetDevice(event, &value2); printf("\nDevice : %s", value2); int count; ezmqEventGetReadingCount(event, &count); printf("\nReadigs:"); for (int i =0 ; i <count; i++) { ezmqReadingHandle_t readingData; ezmqEventGetReading(event, i, &readingData); /*ezmqReadingGetID(readingData, &value2); printf("\nid: %s", value2); ezmqReadingGetCreated(readingData, &value); printf("\ncreated: %ld", value); ezmqReadingGetModified(readingData, &value); printf("\nmodified: %ld", value); ezmqReadingGetOrigin(readingData, &value); printf("\norigin: %ld", value); ezmqReadingGetPushed(readingData, &value); printf("\npushed: %ld", value); ezmqReadingGetDevice(readingData, &value2); printf("\ndevice: %s\n", value2);*/ fflush(stdout); ezmqReadingGetName(readingData, &value2); printf("\nKey: %s", value2); ezmqReadingGetValue(readingData, &value2); printf("\nValue: %s", value2); fflush(stdout); } } void printByteData(ezmqMsgHandle_t byteData) { printf("\n--------------------------------------\n"); size_t size; ezmqGetDataLength(byteData, &size); printf("Byte data length: %zd\n", size); uint8_t *mData; ezmqGetByteData(byteData, &mData); size_t i=0; while (i<size) { printf("%04x ", mData[i]); i++; } printf("\n----------------------------------------\n"); } void subCB(ezmqMsgHandle_t event, CEZMQContentType contentType) { printf("\n------ [App] SUB callback -----\n"); if(CEZMQ_CONTENT_TYPE_PROTOBUF == contentType) { printf("Content-Type: CEZMQ_CONTENT_TYPE_PROTOBUF"); printEvent(event); } else if(CEZMQ_CONTENT_TYPE_BYTEDATA == contentType) { printf("Content-Type: CEZMQ_CONTENT_TYPE_BYTEDATA"); printByteData(event); } } void subTopicCB(const char * topic, ezmqMsgHandle_t event, CEZMQContentType contentType) { printf("\n----- [App] SUB topic callback -----\n"); printf("\nTopic: %s\n", topic); if(CEZMQ_CONTENT_TYPE_PROTOBUF == contentType) { printf("Content-Type: CEZMQ_CONTENT_TYPE_PROTOBUF"); printEvent(event); } else if(CEZMQ_CONTENT_TYPE_BYTEDATA == contentType) { printf("Content-Type: CEZMQ_CONTENT_TYPE_BYTEDATA"); printByteData(event); } } void printError() { printf("\nRe-run the application as shown in below examples: \n"); printf("\n (1) For subscribing without topic: \n"); printf(" ./csubscriber -ip 192.168.1.1 -port 5562 \n"); printf("\n (2) For subscribing without topic [Secured]: \n"); printf(" ./csubscriber -ip 192.168.1.1 -port 5562 -secured 1\n"); printf("\n (3) For subscribing with topic: \n"); printf(" ./csubscriber -ip 192.168.1.1 -port 5562 -t topic1 \n"); printf("\n (4) For subscribing with topic [Secured]: \n"); printf(" ./csubscriber -ip 192.168.1.1 -port 5562 -t topic1 -secured 1\n"); } void sigint(int signal) { printf("\nInterupt signal: %d\n", signal); if (g_isStarted) { //signal all condition variables pthread_mutex_lock(&g_mutex); pthread_cond_broadcast(&g_cv); pthread_mutex_unlock(&g_mutex); } else { exit(0); } } int main(int argc, char* argv[]) { char *ip = NULL; int port = 5562; char *topic= NULL; int secured = 0; CEZMQErrorCode result; g_isStarted = 0; // initialize a condition variable to its default value pthread_cond_init(&g_cv, NULL); //initialize a condition variable pthread_cond_init(&g_cv, &g_cattr); // get ip, port and topic from command line arguments if(argc != 5 && argc != 7 && argc != 9) { printError(); return -1; } int n = 1; while (n < argc) { if (0 == strcmp(argv[n],"-ip")) { ip = argv[n + 1]; printf("\nGiven Ip is : %s", ip); n = n + 2; } else if (0 == strcmp(argv[n],"-port")) { port = atoi(argv[n + 1]); printf("\nGiven Port: %d", port); n = n + 2; } else if (0 == strcmp(argv[n],"-t")) { topic = argv[n + 1]; printf("\nGiven Topic is : %s", topic); n = n + 2; } else if (0 == strcmp(argv[n],"-secured")) { secured = atoi(argv[n + 1]); printf("\nIs Securedi: %d\n", secured); n = n + 2; } else { printError(); } } //this handler is added to check stop API signal(SIGINT, sigint); //initialize ezmq service result = ezmqInitialize(); printf("\nInitialize API [result]: %d", result); if(result != CEZMQ_OK) { return -1; } //Create EZMQ Subscriber ezmqSubHandle_t subscriber; result = ezmqCreateSubscriber(ip, port, subCB, subTopicCB, &subscriber); if(result != CEZMQ_OK) { printf("\nSubscriber creation failed [result] : %d\n", result); return -1; } if(1 == secured) { const char *serverPublicKey = "<KEY>"; result = ezmqSetServerPublicKey(subscriber, serverPublicKey); if(result != CEZMQ_OK) { printf("\nezmqSetServerPrivateKey failed: %d\n", result); return -1; } const char *clientSecretKey = "<KEY>"; const char *clientPublicKey = "-QW?Ved(f:<::3d5tJ$[4Er&]6#9yr=vha/caBc("; result = ezmqSetClientKeys(subscriber, clientSecretKey, clientPublicKey); if(result != CEZMQ_OK) { printf("\nezmqSetClientKeys failed: %d\n", result); return -1; } } //Start EZMQ Subscriber result= emzqStartSubscriber(subscriber); printf("\nSubscriber start [result]: %d", result); if(result != CEZMQ_OK) { return -1; } g_isStarted = 1; //subscribe for events if (NULL == topic) { result = ezmqSubscribe(subscriber); } else { result = ezmqSubscribeForTopic(subscriber, topic); } if(result != CEZMQ_OK) { printf("\nsubscribe API: error occured\n"); return -1; } printf("\nSuscribed to publisher.. -- Waiting for Events --\n"); // conditional wait to prevent main loop from exit pthread_mutex_lock(&g_mutex); pthread_cond_wait(&g_cv, &g_mutex); pthread_mutex_unlock(&g_mutex); //destroy subscriber result = ezmqDestroySubscriber(&subscriber); printf("\nDestroy Subscriber [result]: %d\n", result); return 0; }
edgexfoundry-holding/protocol-ezmq-c
samples/cpublisher.c
/******************************************************************************* * Copyright 2017 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include<stdint.h> #include <signal.h> #include "cezmqapi.h" #include "cezmqpublisher.h" #include "cezmqevent.h" #include "cezmqbytedata.h" #include "cezmqreading.h" #include "cezmqerrorcodes.h" ezmqPubHandle_t gPublisher; ezmqEventHandle_t gEventHandle; int gIsStarted = 0; void startCB(CEZMQErrorCode code) { printf("\nstartCB: %d\n", code); } void stopCB(CEZMQErrorCode code) { printf("\nstopCB: %d\n", code); } void errorCB(CEZMQErrorCode code) { printf("\nerrorCB: %d\n", code); } ezmqEventHandle_t createEvent() { const char *id = "id"; const char *device = "device"; const char *readingId1 = "id1"; const char *readingName1 = "reading1"; const char *readingValue1 = "25"; const char *readingDevice1 = "device"; const char *readingId2 = "id2"; const char *readingName2 = "reading2"; const char *readingValue2 = "20"; const char *readingDevice2 = "device"; ezmqEventHandle_t eventHandle; //creation and set event fields CEZMQErrorCode result = ezmqCreateEvent(&eventHandle); if(result != CEZMQ_OK) { printf("\nEvent initialization [Result]: %d\n", result); return NULL; } ezmqEventSetID(eventHandle, id); ezmqEventSetCreated(eventHandle, 10); ezmqEventSetModified(eventHandle, 20); ezmqEventSetOrigin(eventHandle, 20); ezmqEventSetPushed(eventHandle, 10); ezmqEventSetDevice(eventHandle, device); ezmqReadingHandle_t reading1Handle; //creation and set first reading fields ezmqCreateReading(eventHandle, &reading1Handle); ezmqReadingSetID(reading1Handle, readingId1 ); ezmqReadingSetCreated(reading1Handle, 25); ezmqReadingSetModified(reading1Handle, 20); ezmqReadingSetOrigin(reading1Handle, 25); ezmqReadingSetPushed(reading1Handle, 1); ezmqReadingSetName(reading1Handle, readingName1); ezmqReadingSetValue(reading1Handle, readingValue1); ezmqReadingSetDevice(reading1Handle, readingDevice1); ezmqReadingHandle_t reading2Handle; //creation and set second reading fields ezmqCreateReading(eventHandle, &reading2Handle); ezmqReadingSetID(reading2Handle, readingId2); ezmqReadingSetCreated(reading2Handle, 30); ezmqReadingSetModified(reading2Handle, 20); ezmqReadingSetOrigin(reading2Handle, 25); ezmqReadingSetPushed(reading2Handle, 1); ezmqReadingSetName(reading2Handle, readingName2); ezmqReadingSetValue(reading2Handle, readingValue2); ezmqReadingSetDevice(reading2Handle, readingDevice2); return eventHandle; } void printError() { printf("\nRe-run the application as shown in below examples: \n"); printf("\n (1) For publishing without topic: \n"); printf(" ./cpublisher -port 5562\n"); printf("\n (2) For publishing without topic [Secured]: \n"); printf(" ./cpublisher -port 5562 -secured 1\n"); printf("\n (3) For publishing with topic:\n"); printf(" ./cpublisher -port 5562 -t topic1\n"); printf("\n (4) For publishing with topic [Secured]:\n"); printf(" ./cpublisher -port 5562 -t topic1 -secured 1\n"); } void sigint(int signal) { printf("\nInterupt signal: %d\n", signal); if(0 == gIsStarted) { exit(0); } gIsStarted = 0; } int main(int argc, char* argv[]) { int port = 5562; CEZMQErrorCode result; char *topic= NULL; int secured = 0; // get ip, port and topic from command line arguments if(argc != 3 && argc != 5 && argc != 7) { printError(); return -1; } int n = 1; while (n < argc) { if (0 == strcmp(argv[n],"-port")) { port = atoi(argv[n + 1]); printf("\nGiven Port: %d", port); n = n + 2; } else if (0 == strcmp(argv[n],"-t")) { topic = argv[n + 1]; printf("\nGiven Topic is : %s", topic); n = n + 2; } else if (0 == strcmp(argv[n],"-secured")) { secured = atoi(argv[n + 1]); printf("\nIs Securedi: %d\n", secured); n = n + 2; } else { printError(); } } //this handler is added to check stop API signal(SIGINT, sigint); gIsStarted = 0; //initialize ezmq service result = ezmqInitialize(); printf("\nInitialize API [result]: %d\n", result); if(result != CEZMQ_OK) { return -1; } //Create EZMQ Publisher result = ezmqCreatePublisher(port, startCB, stopCB, errorCB, &gPublisher); printf("\nCreate Publisher [result]: %d\n", result); if(result != CEZMQ_OK) { return -1; } // set the server key if(1 == secured) { const char *serverSecretKey = "[:<KEY>"; result = ezmqSetServerPrivateKey(gPublisher, serverSecretKey); if(result != CEZMQ_OK) { printf("\nezmqSetServerPrivateKey failed: %d\n", result); return -1; } } //Start EZMQ Publisher result= ezmqStartPublisher(gPublisher); printf("\nPublisher start [result]: %d\n", result); if(result != CEZMQ_OK) { return -1; } //form an event to publish gEventHandle = createEvent(); // This delay is added to prevent ZeroMQ first packet drop during // initial connection of publisher and subscriber. sleep(1); //Publish events printf("\n--------- Will Publish 15 events at interval of 2 seconds --------- \n"); gIsStarted = 1; int i = 1; while(i <= 15 && 1 == gIsStarted) { if (NULL == topic) { result = ezmqPublish(gPublisher, gEventHandle); } else { result = ezmqPublishOnTopic(gPublisher, topic, gEventHandle); } if(result != CEZMQ_OK) { printf("\npublish API: error occured\n"); return -1; } printf("\nEvent %d Published", i ); sleep(2); i++; } // stop publisher result = ezmqStopPublisher(gPublisher); if(result != CEZMQ_OK) { printf("\npublish API: error occured\n"); return -1; } printf("\nstop API [result]: %d", result); //Destroy publisher result = ezmqDestroyPublisher(&gPublisher); if(result != CEZMQ_OK) { printf("\nDestroy publisher: error occured\n"); return -1; } printf("\nDestroy publisher [result]: %d", result); //Destroy event result = ezmqDestroyEvent(&gEventHandle); if(result != CEZMQ_OK) { printf("\nDestroy event: error occured\n"); return -1; } printf("\nDestroy event [result]: %d\n", result); return 0; }
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/compressor_factory.h
//compressor_factory.h #ifndef _COMPRESSOR_FACTORY_H_ #define _COMPRESSOR_FACTORY_H_ #include <memory> #include "model.h" #include "dictionary_model.h" #include "encoder.h" #include "fresh_encoder.h" #include "number_encoder.h" #include "compressor_config.h" using std::shared_ptr; class CompressorFactory{ public: static shared_ptr<Model> createModel(const ModelType& modelType); static shared_ptr<Model> createModel(const string& modelName); static shared_ptr<Model> createColumnModel(const ColumnModelType& columnModelType); static shared_ptr<Model> createColumnModel(const string& columnModelName); static shared_ptr<DictionaryModel> createDictColumnModel(const DictColumnModelType& modelType); static shared_ptr<DictionaryModel> createDictColumnModel(const string& dictModelName); static shared_ptr<Encoder> createDictEncoder(const DictEncoderType& encoderType); static shared_ptr<NumberEncoder> createNumberEncoder(const NumberEncoderType& encoderType); static shared_ptr<FreshEncoder> createFreshEncoder(const FreshEncoderType& encoderType); // The following read config to decide the object to create static shared_ptr<Model> createModel(); static shared_ptr<Encoder> createDictEncoder(); static shared_ptr<NumberEncoder> createNumberEncoder(); static shared_ptr<FreshEncoder> createFreshEncoder(); static shared_ptr<Model> createColumnModel(int column); static shared_ptr<Model> createSpecifyColumnModel(const SpecifyConfig& specifyConfig, const shared_ptr<DictionaryModel>& defaultColumnModelPtr); private: }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/phrase_dict_model.h
/* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //phrase_dict_model.h #ifndef _PHRASE_DICT_MODEL_H_ #define _PHRASE_DICT_MODEL_H_ #include "dictionary_model.h" class PhraseDictModel : public DictionaryModel{ public: PhraseDictModel(); bool isWordInDict(const string& word) const; bool isWordInFreshEncoder(const string& word) const; void updateColumn(const string& columnStr, int column); BitArray compressColumn(const string& columnStr, int column); string getModelName() const; private: void findLongestMatch(const vector<string>& words, vector<string>::const_iterator& wordIt, string& match, bool (PhraseDictModel::*checkWordExistFunc)(const string&) const); }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/cowic.h
<filename>baselines/1_CCGrid15/src/model/cowic.h /* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //cowic.h #ifndef _COWIC_H #define _COWIC_H #include <string> #include <vector> #include <memory> #include "model.h" #include "helper.h" using std::string; using std::vector; using std::shared_ptr; class Cowic{ public: Cowic(); void train(const string& seedFile, const string& modelFile); void loadModel(const string& modelFile); string compress(const string& entry); string decompress(const string& compressedEntry); private: void initModelPtr(); void trainModel(const vector<string>& lines); void saveModel(const string& filename) const; BitArray doCompress(const string& line); string doDecompress(BitArray& code); shared_ptr<Model> modelPtr; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/abstract_number_model.h
//abstract_number_model.h #ifndef _ABSTRACT_NUMBER_MODEL_H_ #define _ABSTRACT_NUMBER_MODEL_H_ #include <memory> #include "abstract_number.h" #include "model.h" #include "dictionary_model.h" #include "huffman_encoder.h" using std::shared_ptr; class AbstractNumberModel : public Model{ public: AbstractNumberModel(); AbstractNumberModel(const shared_ptr<DictionaryModel>& dictModelPtrVal); /* <MODEL_NAME> * <#MODEL_BYTE_LEN> * <MODEL_DUMP_STR> * */ virtual string dump() const; virtual void parse(string& dumpStr); void updateColumn(const string& columnStr, int column); BitArray compressColumn(const string& columnStr, int column); int decompressColumn(BinaryCode& code, string& columnStr, int column) const; virtual BitArray compressNumber(unsigned int num); virtual int decompressNumber(BinaryCode& code, unsigned int& num) const; virtual shared_ptr<AbstractNumber> parseColumnStr(const string& columnStr) = 0; virtual string toPlainStr(unsigned int num, const string& before, const string& after) const = 0; static int legalBit; static int beforeBit; static int afterBit; protected: /* The model used to process string when the timestamp cannot be parsed successfully. */ shared_ptr<DictionaryModel> dictModelPtr; BitArray compressBeforeAfter(const string& beforeAfter); int decompressBeforeAfter(BinaryCode& code, string& beforeAfter) const; /* The model used to encode illegal bit, before bit, after bit. * */ unordered_map<int, int> flag2FreqDict; shared_ptr<Encoder> flagEncoderPtr; void initFlag2FreqDict(); string dumpFlagEncoder() const; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/number_model.h
//number_model.h #ifndef _NUMBER_MODEL_H_ #define _NUMBER_MODEL_H_ #include "abstract_number_model.h" class NumberModel : public AbstractNumberModel{ public: NumberModel(); NumberModel(const shared_ptr<DictionaryModel>& dictModelPtrVal); shared_ptr<AbstractNumber> parseColumnStr(const string& columnStr); string toPlainStr(unsigned int num, const string& before, const string& after) const; string getModelName() const; private: }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/encoder/variable_byte_encoder.h
<filename>baselines/1_CCGrid15/src/encoder/variable_byte_encoder.h /* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //variable_byte_encoder.h #ifndef _VARIABLE_BYTE_ENCODER_H_ #define _VARIABLE_BYTE_ENCODER_H_ #include "number_encoder.h" /* Variable byte (VB) encoding uses an integral number of bytes to encode a gap. * The last 7 bits of a byte are ``payload'' and encode part of the gap. * The first bit of the byte is a continuation bit . It is set to 1 for the last byte * of the encoded gap and to 0 otherwise. * */ class VariableByteEncoder : public NumberEncoder{ public: BitArray encode(unsigned int num) const; int decode(BinaryCode& code, unsigned int& num) const; private: }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/fix_precision_number.h
/* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //fix_precision_number.h #ifndef _FIX_PRECISION_NUMBER_H_ #define _FIX_PRECISION_NUMBER_H_ #include <regex.h> #include "abstract_number.h" class FixPrecisionNumber : public AbstractNumber<unsigned int>{ public: FixPrecisionNumber(unsigned int numericVal, const string& beforeVal, const string& afterVal, const unsigned int precisionVal); bool isIllegal() const; static FixPrecisionNumber parse(const string& ipStr, unsigned int precision); string to_plain_str() const; bool operator ==(const FixPrecisionNumber& other) const; bool operator !=(const FixPrecisionNumber& other) const; static const FixPrecisionNumber illegal; private: unsigned int precision; static void initRegex(unsigned int precision); static int regex_initialized; static regex_t decimal_regex; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/spliter.h
<filename>baselines/1_CCGrid15/include/cowic/spliter.h<gh_stars>1-10 //spliter.h #ifndef _SPLITER_H #define _SPLITER_H #include <string> #include <vector> using std::string; using std::vector; class Spliter{ public: static void splitLine2Columns(const string& line, vector<string>& columns); static void splitColumn2Words(const string& column, vector<string>& words); static bool isNewColumn(size_t& lastOpenPos, const string& word); private: }; extern const string EOL_STR; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/word_dict_model.h
<gh_stars>1-10 /* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //word_dict_model.h #ifndef _WORD_DICT_MODEL_H_ #define _WORD_DICT_MODEL_H_ #include "dictionary_model.h" class WordDictModel : public DictionaryModel{ public: WordDictModel(); void updateColumn(const string& columnStr, int column); BitArray compressColumn(const string& columnStr, int column); string getModelName() const; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/encoder/delta_encoder.h
/* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //delta_encoder.h #ifndef _DELTA_ENCODER_H_ #define _DELTA_ENCODER_H_ #include "gamma_encoder.h" class DeltaEncoder : public NumberEncoder{ public: BitArray encode(unsigned int num) const; int decode(BinaryCode& code, unsigned int& num) const; private: GammaEncoder gamma; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/huffman_encoder.h
//huffman_encoder.h #ifndef _HUFFMAN_ENCODRE_H #define _HUFFMAN_ENCODRE_H #include "encoder.h" #include "tree_node.h" class SymbolLen{ public: SymbolLen(string symbolVal, int codeLenVal) : symbol(symbolVal), codeLen(codeLenVal){} string dump() const; static SymbolLen parse(const string& dumpStr); string symbol; int codeLen; }; class HuffmanEncoder : public Encoder{ public: HuffmanEncoder(); void buildCoder(const unordered_map<string, int>& wordFreqDict); bool isFresh(const string& word) const; /* The caller must gurantee word exists, * Otherwise the behavior is undefined. * */ BitArray encode(const string& word) const; int decode(BinaryCode& code, string& word) const; void parse(string& dumpStr); /** Dump the huffman encoder into a string. So we can save it and rebuild it in future. * We will write words and its frequncy, then we will rebuild the huffman tree. * Format: * <WORD1> <#FREQ1> * ... * <WORDN> <#FREQN> * Explanation: * Each line is a word and its frequncy split by a space. Note the word itself can be a space * so we shall use the last space to split word and frequncy. */ string dump() const; /* Used in canonical huffman encoder only * */ void buildSymoblLenVec(vector<SymbolLen>& symbolLenVec) const; ~HuffmanEncoder(); private: TreeNodePtr root; // accelerate encode speed unordered_map<string, BitArray> word2CodeDict; /** Assign huffman code to each leave node, left branch with code 0, right branch with code 1 */ void assignHuffmanCode(TreeNodePtr node, string pathCode); int traverseTreeParseCode(const TreeNodePtr& node, BinaryCode& code, string& word) const; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/spliter.h
<gh_stars>1-10 /* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //spliter.h #ifndef _SPLITER_H #define _SPLITER_H #include <string> #include <vector> using std::string; using std::vector; class Spliter{ public: static void splitLine2Columns(const string& line, vector<string>& columns); static void splitColumn2Words(const string& column, vector<string>& words); static bool isNewColumn(size_t& lastOpenPos, const string& word); private: }; extern const string EOL_STR; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/gamma_encoder.h
//gamma_encoder.h #ifndef _GAMMA_ENCODER_H_ #define _GAMMA_ENCODER_H_ #include "unary_encoder.h" class GammaEncoder : public NumberEncoder{ public: BitArray encode(unsigned int num) const; int decode(BinaryCode& code, unsigned int& num) const; private: UnaryEncoder unary; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/ip.h
<reponame>JinYang88/LogZip //ip.h #ifndef _IP_H_ #define _IP_H_ #include <regex> #include <stdlib.h> #include <regex.h> #include "abstract_number.h" class IP : public AbstractNumber{ public: IP(unsigned int numericVal, const string& beforeVal, const string& afterVal); string to_plain_str() const; bool isIllegal() const; static IP parse(const string& ipStr); static const IP illegal; private: static void initRegex(); static bool regex_initialized; static regex_t dot_decimal_regex; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/abstract_number_model.h
<filename>baselines/1_CCGrid15/src/model/abstract_number_model.h /* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //abstract_number_model.h #ifndef _ABSTRACT_NUMBER_MODEL_H_ #define _ABSTRACT_NUMBER_MODEL_H_ #include <memory> #include "abstract_number.h" #include "model.h" #include "dictionary_model.h" #include "huffman_encoder.h" using std::shared_ptr; template <typename T> class AbstractNumberModel : public Model{ public: AbstractNumberModel(); AbstractNumberModel(const shared_ptr<DictionaryModel>& dictModelPtrVal); /* <MODEL_NAME> * <#MODEL_BYTE_LEN> * <MODEL_DUMP_STR> * */ virtual string dump() const; virtual void parse(string& dumpStr); void updateColumn(const string& columnStr, int column); BitArray compressColumn(const string& columnStr, int column); int decompressColumn(BinaryCode& code, string& columnStr, int column) const; virtual BitArray compressNumber(unsigned int num); virtual int decompressNumber(BinaryCode& code, unsigned int& num) const; virtual shared_ptr<AbstractNumber<T> > parseColumnStr(const string& columnStr) = 0; virtual string toPlainStr(T num, const string& before, const string& after) const = 0; static const int legalBit; static const int beforeBit; static const int afterBit; protected: /* The model used to process string when the timestamp cannot be parsed successfully. */ shared_ptr<DictionaryModel> dictModelPtr; BitArray compressBeforeAfter(const string& beforeAfter); int decompressBeforeAfter(BinaryCode& code, string& beforeAfter) const; /* The model used to encode illegal bit, before bit, after bit. * */ unordered_map<int, int> flag2FreqDict; shared_ptr<Encoder> flagEncoderPtr; void initFlag2FreqDict(); string dumpFlagEncoder() const; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/fix_precision_number.h
//fix_precision_number.h #ifndef _FIX_PRECISION_NUMBER_H_ #define _FIX_PRECISION_NUMBER_H_ #include <regex.h> #include "abstract_number.h" class FixPrecisionNumber : public AbstractNumber{ public: FixPrecisionNumber(unsigned int numericVal, const string& beforeVal, const string& afterVal, const unsigned int precisionVal); bool isIllegal() const; static FixPrecisionNumber parse(const string& ipStr, unsigned int precision); string to_plain_str() const; bool operator ==(const FixPrecisionNumber& other) const; bool operator !=(const FixPrecisionNumber& other) const; static const FixPrecisionNumber illegal; private: unsigned int precision; static void initRegex(unsigned int precision); static int regex_initialized; static regex_t decimal_regex; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/ip.h
/* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //ip.h #ifndef _IP_H_ #define _IP_H_ #include <regex> #include <stdlib.h> #include <regex.h> #include "abstract_number.h" class IP : public AbstractNumber<unsigned int>{ public: IP(unsigned int numericVal, const string& beforeVal, const string& afterVal); string to_plain_str() const; bool isIllegal() const; static IP parse(const string& ipStr); static const IP illegal; private: static void initRegex(); static bool regex_initialized; static regex_t dot_decimal_regex; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/common/helper.h
/* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //helper.h #ifndef _HELPER_H_ #define _HELPER_H_ #include <string> #include <vector> #include <fstream> #include <unordered_map> #include "bit_array.h" using std::string; using std::vector; using std::ifstream; using std::unordered_map; void split(const string &s, char delim, vector<string> &elems); vector<string> split(const string &s, char delim); string int2Str(int num); void replaceAll(std::string& str, const std::string& from, const std::string& to); void parseDict(const string& str, unordered_map<string, int>& dict); string cutFirstLine(string& dumpStr); int parseFirstLine2Int(string& dumpStr); string cutNByte(string& str, int byteLen); string cutParseDatafile(int& offset, int byteNum, ifstream& datafile); /* Index file mark the begin and len info of each entry. * Each line contains info of one entry. * Format: * <BITNUM> * */ string formatIndex(int byteNum); class AuxiliaryFilename{ public: static void initFilename(const string& filename); static string getNextFilename(); static string baseFilename; static int column; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/number.h
<gh_stars>1-10 /* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //number.h #ifndef _NUMBER_H_ #define _NUMBER_H_ #include <regex.h> #include "abstract_number.h" template <typename T> class Number : public AbstractNumber<T>{ public: Number(T numericVal, const string& beforeVal, const string& afterVal); bool isIllegal() const; static Number parse(const string& ipStr); static const Number illegal; private: static void initRegex(); static bool regex_initialized; static regex_t decimal_regex; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/word_dict_model.h
//word_dict_model.h #ifndef _WORD_DICT_MODEL_H_ #define _WORD_DICT_MODEL_H_ #include "dictionary_model.h" class WordDictModel : public DictionaryModel{ public: WordDictModel(); void updateColumn(const string& columnStr, int column); BitArray compressColumn(const string& columnStr, int column); string getModelName() const; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/unary_encoder.h
//unary_encoder.h #ifndef _UNARY_ENCODER_H_ #define _UNARY_ENCODER_H_ #include "number_encoder.h" class UnaryEncoder : public NumberEncoder{ public: BitArray encode(unsigned int num) const; int decode(BinaryCode& code, unsigned int& num) const; private: }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/delta_encoder.h
<filename>baselines/1_CCGrid15/include/cowic/delta_encoder.h //delta_encoder.h #ifndef _DELTA_ENCODER_H_ #define _DELTA_ENCODER_H_ #include "gamma_encoder.h" class DeltaEncoder : public NumberEncoder{ public: BitArray encode(unsigned int num) const; int decode(BinaryCode& code, unsigned int& num) const; private: GammaEncoder gamma; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/plain_encoder.h
//plain_encoder.h #ifndef _PLAIN_ENCODER_H_ #define _PLAIN_ENCODER_H_ #include "fresh_encoder.h" class PlainEncoder : public FreshEncoder{ public: bool isFresh(const string& word) const; /* Fresh word is represent by a fresh mark followed by word length, then plain word * An empty string is used as word of fresh mark. Its frequncy will be estimated by * words that appears once only. Those word appears once only will be filterd when build * huffman tree and will be treated as fresh word when decode. * */ BitArray encode(const string& word) const; /* Reach here when we meet a FreshMarkCode. The following shall be an 8 bits number, * which is length of the fresh word. Then there are 8 * length of bits, which is * the fresh word in ascii. * */ int decode(BinaryCode& code, string& word) const; int decodeFresh(BinaryCode& code, string& word, bool isAuxiliary = false) const; void parse(string& dumpStr); string dump() const; private: }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/column_wised_model.h
//column_wised_model.h #ifndef _COLUMN_WISED_MODEL_H_ #define _COLUMN_WISED_MODEL_H_ #include <memory> #include "model.h" typedef std::shared_ptr<Model> ModelPtr; class ColumnWisedModel : public Model{ public: ColumnWisedModel(); void updateColumn(const string& columnStr, int column); /* Dump each model in order. * Format: * <MODEL_NAME> * <#MODEL_NUM> * <#MODEL1_BYTE_LEN> * <MODEL1_DUMP_STR> * ... * <#MODELN_BYTE_LEN> * <MODELN_DUMP_STR> * */ string dump() const; void parse(string& dumpStr); BitArray compressColumn(const string& columnStr, int column); int decompressColumn(BinaryCode& code, string& columnStr, int column) const; string getModelName() const; private: ModelPtr& getModel(int column); const ModelPtr& getModel(int column) const; ModelPtr& getModelCreateIfNotExist(unsigned int column); vector<ModelPtr> modelPtrs; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/tree_node.h
<gh_stars>1-10 //tree_node.h #ifndef _TREE_NODE_H_ #define _TREE_NODE_H_ #include <memory> #include "bit_array.h" class TreeNode; typedef std::shared_ptr<TreeNode> TreeNodePtr; class TreeNode{ public: TreeNode(string wordValue, int freqValue); TreeNode(TreeNodePtr leftValue, TreeNodePtr rightValue); int getFreq() const; TreeNodePtr getLeft() const; TreeNodePtr getRight() const; string getWord() const; BitArray getCode() const; void setCode(const string& plainStr); ~TreeNode(); private: TreeNodePtr left; TreeNodePtr right; string word; int freq; BitArray code; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/encoder/unary_encoder.h
<gh_stars>1-10 /* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //unary_encoder.h #ifndef _UNARY_ENCODER_H_ #define _UNARY_ENCODER_H_ #include "number_encoder.h" class UnaryEncoder : public NumberEncoder{ public: BitArray encode(unsigned int num) const; int decode(BinaryCode& code, unsigned int& num) const; private: }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/src/model/number_model.h
/* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //number_model.h #ifndef _NUMBER_MODEL_H_ #define _NUMBER_MODEL_H_ #include "abstract_number_model.h" template <typename T> class NumberModel : public AbstractNumberModel<T>{ public: NumberModel(); NumberModel(const shared_ptr<DictionaryModel>& dictModelPtrVal); shared_ptr<AbstractNumber<T> > parseColumnStr(const string& columnStr); string toPlainStr(T num, const string& before, const string& after) const; string getModelName() const; private: static const string name; }; #endif
JinYang88/LogZip
baselines/1_CCGrid15/include/cowic/ip_model.h
<filename>baselines/1_CCGrid15/include/cowic/ip_model.h //ip_model.h #ifndef _IP_MODEL_H_ #define _IP_MODEL_H_ #include "abstract_number_model.h" class IPModel : public AbstractNumberModel{ public: IPModel(); IPModel(const shared_ptr<DictionaryModel>& dictModelPtrVal); shared_ptr<AbstractNumber> parseColumnStr(const string& columnStr); string toPlainStr(unsigned int num, const string& before, const string& after) const; string getModelName() const; private: }; #endif