<commit_before>
#ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
#define HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H

#include "FFmpegDecoderAudio.hpp"
#include "FFmpegDecoderVideo.hpp"

#include <osg/Notify>

namespace osgFFmpeg {

class FormatContextPtr
{
    public:

        typedef AVFormatContext T;

        explicit FormatContextPtr() : _ptr(0) {}
        explicit FormatContextPtr(T* ptr) : _ptr(ptr) {}

        ~FormatContextPtr()
        {
            cleanup();
        }

        T* get() { return _ptr; }

        T * operator-> () const // never throws
        {
            return _ptr;
        }

        void reset(T* ptr)
        {
            if (ptr==_ptr) return;
            cleanup();
            _ptr = ptr;
        }

        void cleanup()
        {
            if (_ptr)
            {
                osg::notify(osg::NOTICE)<<"Calling av_close_input_file("<<_ptr<<")"<<std::endl;
                av_close_input_file(_ptr);
            }
            _ptr = 0;
        }

    protected:

        T* _ptr;
};

class FFmpegDecoder : public osg::Referenced
{
public:

    FFmpegDecoder();
    ~FFmpegDecoder();

    bool open(const std::string & filename);
    void close(bool waitForThreadToExit);

    bool readNextPacket();
    void rewind();

    void loop(bool loop);
    bool loop() const;

    double duration() const;

    FFmpegDecoderAudio & audio_decoder();
    FFmpegDecoderVideo & video_decoder();
    FFmpegDecoderAudio const & audio_decoder() const;
    FFmpegDecoderVideo const & video_decoder() const;

protected:

    enum State
    {
        NORMAL,
        END_OF_STREAM,
        REWINDING
    };

    typedef BoundedMessageQueue<FFmpegPacket> PacketQueue;

    void findAudioStream();
    void findVideoStream();
    void flushAudioQueue();
    void flushVideoQueue();
    bool readNextPacketNormal();
    bool readNextPacketEndOfStream();
    bool readNextPacketRewinding();
    void rewindButDontFlushQueues();

    FormatContextPtr    m_format_context;
    AVStream *            m_audio_stream;
    AVStream *            m_video_stream;

    unsigned int        m_audio_index;
    unsigned int        m_video_index;

    FFmpegClocks        m_clocks;
    FFmpegPacket        m_pending_packet;
    PacketQueue            m_audio_queue;
    PacketQueue            m_video_queue;

    FFmpegDecoderAudio    m_audio_decoder;
    FFmpegDecoderVideo    m_video_decoder;

    double                m_duration;
    double                m_start;

    State                m_state;
    bool                m_loop;
};

inline void FFmpegDecoder::loop(const bool loop)
{
    m_loop = loop;
}

inline bool FFmpegDecoder::loop() const
{
    return m_loop;
}

inline double FFmpegDecoder::duration() const
{
    return double(m_format_context->duration) / AV_TIME_BASE;
}

inline FFmpegDecoderAudio & FFmpegDecoder::audio_decoder()
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo & FFmpegDecoder::video_decoder()
{
    return m_video_decoder;
}

inline FFmpegDecoderAudio const & FFmpegDecoder::audio_decoder() const
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo const & FFmpegDecoder::video_decoder() const
{
    return m_video_decoder;
}

} // namespace osgFFmpeg

#endif // HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
<commit_msg>Fixed warning<commit_after>
#ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
#define HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H

#include "FFmpegDecoderAudio.hpp"
#include "FFmpegDecoderVideo.hpp"

#include <osg/Notify>

namespace osgFFmpeg {

class FormatContextPtr
{
    public:

        typedef AVFormatContext T;

        explicit FormatContextPtr() : _ptr(0) {}
        explicit FormatContextPtr(T* ptr) : _ptr(ptr) {}

        ~FormatContextPtr()
        {
            cleanup();
        }

        T* get() { return _ptr; }

        T * operator-> () const // never throws
        {
            return _ptr;
        }

        void reset(T* ptr)
        {
            if (ptr==_ptr) return;
            cleanup();
            _ptr = ptr;
        }

        void cleanup()
        {
            if (_ptr)
            {
                osg::notify(osg::NOTICE)<<"Calling av_close_input_file("<<_ptr<<")"<<std::endl;
                av_close_input_file(_ptr);
            }
            _ptr = 0;
        }

    protected:

        T* _ptr;
};

class FFmpegDecoder : public osg::Referenced
{
public:

    FFmpegDecoder();
    ~FFmpegDecoder();

    bool open(const std::string & filename);
    void close(bool waitForThreadToExit);

    bool readNextPacket();
    void rewind();

    void loop(bool loop);
    bool loop() const;

    double duration() const;

    FFmpegDecoderAudio & audio_decoder();
    FFmpegDecoderVideo & video_decoder();
    FFmpegDecoderAudio const & audio_decoder() const;
    FFmpegDecoderVideo const & video_decoder() const;

protected:

    enum State
    {
        NORMAL,
        END_OF_STREAM,
        REWINDING
    };

    typedef BoundedMessageQueue<FFmpegPacket> PacketQueue;

    void findAudioStream();
    void findVideoStream();
    void flushAudioQueue();
    void flushVideoQueue();
    bool readNextPacketNormal();
    bool readNextPacketEndOfStream();
    bool readNextPacketRewinding();
    void rewindButDontFlushQueues();

    FormatContextPtr    m_format_context;
    AVStream *            m_audio_stream;
    AVStream *            m_video_stream;

    int                 m_audio_index;
    int                 m_video_index;

    FFmpegClocks        m_clocks;
    FFmpegPacket        m_pending_packet;
    PacketQueue            m_audio_queue;
    PacketQueue            m_video_queue;

    FFmpegDecoderAudio    m_audio_decoder;
    FFmpegDecoderVideo    m_video_decoder;

    double                m_duration;
    double                m_start;

    State                m_state;
    bool                m_loop;
};

inline void FFmpegDecoder::loop(const bool loop)
{
    m_loop = loop;
}

inline bool FFmpegDecoder::loop() const
{
    return m_loop;
}

inline double FFmpegDecoder::duration() const
{
    return double(m_format_context->duration) / AV_TIME_BASE;
}

inline FFmpegDecoderAudio & FFmpegDecoder::audio_decoder()
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo & FFmpegDecoder::video_decoder()
{
    return m_video_decoder;
}

inline FFmpegDecoderAudio const & FFmpegDecoder::audio_decoder() const
{
    return m_audio_decoder;
}

inline FFmpegDecoderVideo const & FFmpegDecoder::video_decoder() const
{
    return m_video_decoder;
}

} // namespace osgFFmpeg

#endif // HEADER_GUARD_OSGFFMPEG_FFMPEG_DECODER_H
<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>

/* This is another example of working with classes. Illustrates static
   variables and friends. */

class some_class; /* You can declare a class before you define it. This is
                     called a forward declaration and sometimes neccessary
                     to avoid circles. */

class employee {
  int id;         // By default a member is private.
  char name[80];
  float wage;
 public:             // These member are public.
  employee() {};     // Short functions can be implemented on the fly.
  int mood;
  static int company_id; // Static members only exist once for the whole class.
  static int helper_function(int x); // and are shared between all objects.
 private:           // Again private.
  void calc_wage();
 public:           // Again public.
  void set_name(char *c);
  char *get_name();
  friend void reset_id(employee e); // A friend function has access to private members.
  friend class some_class;  // You can also friend a class (= all of its functions).
};

/* Although it is possible to switch between private and public members as
   often as you want, this is discouraged. Choose one order and stick
   to it. */

// Now we define the class we declared earlier.
class some_class {
  int a;
 public:
  void do_something(employee e);
};

void some_class::do_something(employee e) {
    e.id=-1;  // Only possible because some_class is a friend of employee.
}

int employee::company_id; // Define the static variable (now ready for use).

// We could have initalized the static variable like this:
// int employee::company_id=0;

int employee::helper_function(int x) {
    return x*x;
}

void reset_id(employee e) {
    e.id=0;
}

void employee::set_name(char *c) {
    strcpy(name, c);
}

char *employee::get_name() {
    return name;
}

employee replace_bob(employee e) {
    if (strcmp(e.get_name(), "Bob")) {
        employee new_guy;
        return new_guy;
    }
}

int main(int argc, char *argv[]) {
    employee bob, alice;

    bob.set_name("Bob");

    std::cout << bob.get_name() << std::endl;

    reset_id(bob);  // Now bob.id is 0.

    bob.company_id=1;
    alice.company_id=2;
    std::cout << bob.company_id << std::endl; // Prints '2', because 'company_id' is static.

    std::cout << bob.helper_function(2) << std::endl;

    alice = replace_bob(bob);   // Deep copy by default.
    std::cout << alice.get_name() << std::endl; // Will be uninitialized.

    system("PAUSE");
    return EXIT_SUCCESS;
}
<commit_msg>bugfix<commit_after>#include <cstdlib>
#include <iostream>

/* This is another example of working with classes. Illustrates static
   variables and friends. */

class some_class; /* You can declare a class before you define it. This is
                     called a forward declaration and sometimes neccessary
                     to avoid circles. */

class employee {
  int id;         // By default a member is private.
  char name[80];
  float wage;
 public:             // These member are public.
  employee() {};     // Short functions can be implemented on the fly.
  int mood;
  static int company_id; // Static members only exist once for the whole class.
  static int helper_function(int x); // and are shared between all objects.
 private:           // Again private.
  void calc_wage();
 public:           // Again public.
  void set_name(char *c);
  char *get_name();
  friend void reset_id(employee e); // A friend function has access to private members.
  friend class some_class;  // You can also friend a class (= all of its functions).
};

/* Although it is possible to switch between private and public members as
   often as you want, this is discouraged. Choose one order and stick
   to it. */

// Now we define the class we declared earlier.
class some_class {
  int a;
 public:
  void do_something(employee e);
};

void some_class::do_something(employee e) {
    e.id=-1;  // Only possible because some_class is a friend of employee.
}

int employee::company_id; // Define the static variable (now ready for use).

// We could have initalized the static variable like this:
// int employee::company_id=0;

int employee::helper_function(int x) {
    return x*x;
}

void reset_id(employee e) {
    e.id=0;
}

void employee::set_name(char *c) {
    strcpy_s(name, c);
}

char *employee::get_name() {
    return name;
}

employee replace_bob(employee e) {
    if (!strcmp(e.get_name(), "Bob")) {
        employee new_guy;
		new_guy.set_name("new_guy");
        return new_guy;
    }
}

int main(int argc, char *argv[]) {
    employee bob, alice;

    bob.set_name("Bob");

    std::cout << bob.get_name() << std::endl;

    reset_id(bob);  // Now bob.id is 0.

    bob.company_id=1;
    alice.company_id=2;
    std::cout << bob.company_id << std::endl; // Prints '2', because 'company_id' is static.

    std::cout << bob.helper_function(2) << std::endl;

    alice = replace_bob(bob);   // Deep copy by default.
    std::cout << alice.get_name() << std::endl; // Will be uninitialized.

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <iomanip>
#include <memory>

#include "assert.hpp"
#include "variant.hpp"
#include "Utils.hpp"

#include "mtac/Program.hpp"

#include "ltac/Printer.hpp"

using namespace eddic;

namespace {

std::string to_string(ltac::Operator op){
    switch(op){
        case ltac::Operator::MOV:
            return "MOV";
        case ltac::Operator::ENTER:
            return "ENTER";
        case ltac::Operator::FMOV:
            return "FMOV";
        case ltac::Operator::LEAVE:
            return "LEAVE";
        case ltac::Operator::RET:
            return "RET";
        case ltac::Operator::PRE_RET:
            return "PRE_RET";
        case ltac::Operator::CMP_INT:
            return "CMP_INT";
        case ltac::Operator::CMP_FLOAT:
            return "CMP_FLOAT";
        case ltac::Operator::OR:
            return "OR";
        case ltac::Operator::XOR:
            return "XOR";
        case ltac::Operator::PUSH:
            return "PUSH";
        case ltac::Operator::POP:
            return "POP";
        case ltac::Operator::LEA:
            return "LEA";
        case ltac::Operator::SHIFT_LEFT:
            return "SHIFT_LEFT";
        case ltac::Operator::SHIFT_RIGHT:
            return "SHIFT_RIGHT";
        case ltac::Operator::ADD:
            return "ADD";
        case ltac::Operator::SUB:
            return "SUB";
        case ltac::Operator::MUL2:
        case ltac::Operator::MUL3:
            return "MUL";
        case ltac::Operator::DIV:
            return "DIV";
        case ltac::Operator::FADD:
            return "FADD";
        case ltac::Operator::FSUB:
            return "FSUB";
        case ltac::Operator::FMUL:
            return "FMUL";
        case ltac::Operator::FDIV:
            return "FDIV";
        case ltac::Operator::INC:
            return "INC";
        case ltac::Operator::DEC:
            return "DEC";
        case ltac::Operator::NEG:
            return "NEG";
        case ltac::Operator::NOT:
            return "NOT";
        case ltac::Operator::AND:
            return "AND";
        case ltac::Operator::I2F:
            return "I2F";
        case ltac::Operator::F2I:
            return "F2I";
        case ltac::Operator::CMOVE:
            return "CMOVE";
        case ltac::Operator::CMOVNE:
            return "CMOVNE";
        case ltac::Operator::CMOVA:
            return "CMOVA";
        case ltac::Operator::CMOVAE:
            return "CMOVAE";
        case ltac::Operator::CMOVB:
            return "CMOVB";
        case ltac::Operator::CMOVBE:
            return "CMOVBE";
        case ltac::Operator::CMOVG:
            return "CMOVG";
        case ltac::Operator::CMOVGE:
            return "CMOVGE";
        case ltac::Operator::CMOVL:
            return "CMOVL";
        case ltac::Operator::CMOVLE:
            return "CMOVLE";
        case ltac::Operator::PRE_PARAM:
            return "PRE_PARAM";
        case ltac::Operator::NOP:
            return "NOP";
        case ltac::Operator::XORPS:
            return "XORPS";
        case ltac::Operator::MOVDQU:
            return "MOVDQU";
        case ltac::Operator::CALL:
            return "call";
        case ltac::Operator::ALWAYS:
            return "always";
        case ltac::Operator::NE:
            return "ne";
        case ltac::Operator::E:
            return "e";
        case ltac::Operator::GE:
            return "ge";
        case ltac::Operator::G:
            return "g";
        case ltac::Operator::LE:
            return "le";
        case ltac::Operator::L:
            return "l";
        case ltac::Operator::AE:
            return "ae";
        case ltac::Operator::A:
            return "a";
        case ltac::Operator::BE:
            return "be";
        case ltac::Operator::B:
            return "b";
        case ltac::Operator::P:
            return "p";
        case ltac::Operator::Z:
            return "z";
        case ltac::Operator::NZ:
            return "nz";
        default:
            eddic_unreachable("The instruction operator is not supported");
    }
}

struct DebugVisitor {
    std::ostream& out;

    DebugVisitor(std::ostream& out) : out(out) {}

    void operator()(mtac::Program& program){
        out << "LTAC Program " << std::endl << std::endl;

        for(auto& function : program){
            (*this)(function);
        }
    }

    void operator()(mtac::Function& function){
        out << "Function " << function.get_name() << std::endl;

        for(auto& bb : function){
            (*this)(bb);
        }

        out << std::endl;
    }

    void operator()(mtac::basic_block_p bb){
        pretty_print(bb, out);

        for(auto& statement : bb->l_statements){
            (*this)(statement);
        }
    }

    void operator()(const ltac::Instruction& quadruple){
        out << "\t" ;

        if(quadruple.is_jump()){
            out << "jmp (" << to_string(quadruple.op) << ") " << quadruple.label << std::endl;
        } else if(quadruple.is_label()){
            out << quadruple.label << ":" << std::endl;
        } else {
            out << to_string(quadruple.op);

            if(quadruple.size != ltac::Size::DEFAULT){
                switch(quadruple.size){
                    case ltac::Size::BYTE:
                        out << " BYTE";
                        break;
                    case ltac::Size::WORD:
                        out << " WORD";
                        break;
                    case ltac::Size::DOUBLE_WORD:
                        out << " DWORD";
                        break;
                    default:
                        out << " QWORD";
                        break;
                }
            }

            if(quadruple.arg1){
                out << " " << *quadruple.arg1;

                if(quadruple.arg2){
                    out << ", " << *quadruple.arg2;

                    if(quadruple.arg3){
                        out << ", " << *quadruple.arg3;
                    }
                }
            }

            out << std::endl;
        }
    }
};

} //end of anonymous namespace

void ltac::print_statement(const ltac::Instruction& statement, std::ostream& out){
   DebugVisitor visitor(out);
   visitor(statement);
}

void ltac::Printer::print(mtac::Program& program) const {
   DebugVisitor visitor(std::cout);
   visitor(program);
}

void ltac::Printer::print(mtac::Function& function) const {
   DebugVisitor visitor(std::cout);
   visitor(function);
}

void ltac::Printer::print(ltac::Instruction& statement) const {
   DebugVisitor visitor(std::cout);
   visitor(statement);
}
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <iomanip>
#include <memory>

#include "assert.hpp"
#include "variant.hpp"
#include "Utils.hpp"

#include "mtac/Program.hpp"

#include "ltac/Printer.hpp"

using namespace eddic;

namespace {

std::string to_string(ltac::Operator op){
    switch(op){
        case ltac::Operator::MOV:
            return "MOV";
        case ltac::Operator::ENTER:
            return "ENTER";
        case ltac::Operator::FMOV:
            return "FMOV";
        case ltac::Operator::LEAVE:
            return "LEAVE";
        case ltac::Operator::RET:
            return "RET";
        case ltac::Operator::PRE_RET:
            return "PRE_RET";
        case ltac::Operator::CMP_INT:
            return "CMP_INT";
        case ltac::Operator::CMP_FLOAT:
            return "CMP_FLOAT";
        case ltac::Operator::OR:
            return "OR";
        case ltac::Operator::XOR:
            return "XOR";
        case ltac::Operator::PUSH:
            return "PUSH";
        case ltac::Operator::POP:
            return "POP";
        case ltac::Operator::LEA:
            return "LEA";
        case ltac::Operator::SHIFT_LEFT:
            return "SHIFT_LEFT";
        case ltac::Operator::SHIFT_RIGHT:
            return "SHIFT_RIGHT";
        case ltac::Operator::ADD:
            return "ADD";
        case ltac::Operator::SUB:
            return "SUB";
        case ltac::Operator::MUL2:
        case ltac::Operator::MUL3:
            return "MUL";
        case ltac::Operator::DIV:
            return "DIV";
        case ltac::Operator::FADD:
            return "FADD";
        case ltac::Operator::FSUB:
            return "FSUB";
        case ltac::Operator::FMUL:
            return "FMUL";
        case ltac::Operator::FDIV:
            return "FDIV";
        case ltac::Operator::INC:
            return "INC";
        case ltac::Operator::DEC:
            return "DEC";
        case ltac::Operator::NEG:
            return "NEG";
        case ltac::Operator::NOT:
            return "NOT";
        case ltac::Operator::AND:
            return "AND";
        case ltac::Operator::I2F:
            return "I2F";
        case ltac::Operator::F2I:
            return "F2I";
        case ltac::Operator::CMOVE:
            return "CMOVE";
        case ltac::Operator::CMOVNE:
            return "CMOVNE";
        case ltac::Operator::CMOVA:
            return "CMOVA";
        case ltac::Operator::CMOVAE:
            return "CMOVAE";
        case ltac::Operator::CMOVB:
            return "CMOVB";
        case ltac::Operator::CMOVBE:
            return "CMOVBE";
        case ltac::Operator::CMOVG:
            return "CMOVG";
        case ltac::Operator::CMOVGE:
            return "CMOVGE";
        case ltac::Operator::CMOVL:
            return "CMOVL";
        case ltac::Operator::CMOVLE:
            return "CMOVLE";
        case ltac::Operator::PRE_PARAM:
            return "PRE_PARAM";
        case ltac::Operator::NOP:
            return "NOP";
        case ltac::Operator::XORPS:
            return "XORPS";
        case ltac::Operator::MOVDQU:
            return "MOVDQU";
        case ltac::Operator::CALL:
            return "call";
        case ltac::Operator::ALWAYS:
            return "always";
        case ltac::Operator::NE:
            return "ne";
        case ltac::Operator::E:
            return "e";
        case ltac::Operator::GE:
            return "ge";
        case ltac::Operator::G:
            return "g";
        case ltac::Operator::LE:
            return "le";
        case ltac::Operator::L:
            return "l";
        case ltac::Operator::AE:
            return "ae";
        case ltac::Operator::A:
            return "a";
        case ltac::Operator::BE:
            return "be";
        case ltac::Operator::B:
            return "b";
        case ltac::Operator::P:
            return "p";
        case ltac::Operator::Z:
            return "z";
        case ltac::Operator::NZ:
            return "nz";
        default:
            eddic_unreachable("The instruction operator is not supported");
    }
}

struct DebugVisitor {
    std::ostream& out;

    DebugVisitor(std::ostream& out) : out(out) {}

    void operator()(mtac::Program& program){
        out << "LTAC Program " << std::endl << std::endl;

        for(auto& function : program){
            (*this)(function);
        }
    }

    void operator()(mtac::Function& function){
        out << "Function " << function.get_name() << std::endl;

        for(auto& bb : function){
            (*this)(bb);
        }

        out << std::endl;
    }

    void operator()(mtac::basic_block_p bb){
        pretty_print(bb, out);

        for(auto& statement : bb->l_statements){
            (*this)(statement);
        }
    }

    void operator()(const ltac::Instruction& quadruple){
        out << "\t";

        if(quadruple.is_jump()){
            out << "jmp (" << to_string(quadruple.op) << ") " << quadruple.label << std::endl;
        } else if(quadruple.is_label()){
            out << quadruple.label << ":" << std::endl;
        } else {
            out << to_string(quadruple.op);

            if(quadruple.size != ltac::Size::DEFAULT){
                switch(quadruple.size){
                    case ltac::Size::BYTE:
                        out << " BYTE";
                        break;
                    case ltac::Size::WORD:
                        out << " WORD";
                        break;
                    case ltac::Size::DOUBLE_WORD:
                        out << " DWORD";
                        break;
                    default:
                        out << " QWORD";
                        break;
                }
            }

            if(quadruple.arg1){
                out << " " << *quadruple.arg1;

                if(quadruple.arg2){
                    out << ", " << *quadruple.arg2;

                    if(quadruple.arg3){
                        out << ", " << *quadruple.arg3;
                    }
                }
            }

            out << std::endl;
        }
    }
};

} //end of anonymous namespace

void ltac::print_statement(const ltac::Instruction& statement, std::ostream& out){
   DebugVisitor visitor(out);
   visitor(statement);
}

void ltac::Printer::print(mtac::Program& program) const {
   DebugVisitor visitor(std::cout);
   visitor(program);
}

void ltac::Printer::print(mtac::Function& function) const {
   DebugVisitor visitor(std::cout);
   visitor(function);
}

void ltac::Printer::print(ltac::Instruction& statement) const {
   DebugVisitor visitor(std::cout);
   visitor(statement);
}
<|endoftext|>


<commit_before>#include "common.h"

#include <iostream>

#include <boost/math/special_functions/binomial.hpp>

// probability of equality of two calls of the SAME reference position
double p_equal_calls = 0.0;

// probability of 'sequenced position' which represents the probability of a read
// starting at a given position of the reference
double p_read_start = 0.0;

// after initializations this matrix will contain the probability of two random
// generated reads showing a overlap of s bases with dh discrepancies
double** p_rand_read_olap;

// after initializations this matrix will contain in position [s][d] the probability
// of two consecutive reads showing an overlap of 's' bases with 'd' hamming
// distance
double** p_cons_read_olap;

void initProbabilities() {
// convenience variables
  double p_err = Options::opts.pe;
  double q_err = 1.0 - p_err;
  size_t N = Options::opts.N;
  size_t m = Options::opts.m;

  // init p_equal_calls
  p_equal_calls = q_err * q_err + (1.0 / 3.0) * ( p_err * p_err );

  // init p_read_start
  p_read_start = (double)Options::opts.M / (double)Options::opts.N;

  // init rand_read_olap matrix
  p_rand_read_olap = new double*[m];
  for (size_t i = 0;  i < m; ++i) {
    p_rand_read_olap[i] = new double[m+1];
    for (size_t j = 0; j <= i; ++j) {
      double binom = boost::math::binomial_coefficient<double>(i,j);
      double p_s = (pow(p_equal_calls,j) * pow(1.0 - p_equal_calls, i - j)  * binom ) /  ((double)N * pow(4,i) );

      double p_not_s = ((double)N-m+1)* pow((3.0/4.0),j) / ( (double)N * pow(4,i-j) ) ;
      p_rand_read_olap[i][j] = p_s + p_not_s;
    }
  }

  // init cons_read_olap matrix
  p_cons_read_olap  = new double*[m];
  for (size_t i = 0; i < m; ++i) {
    p_cons_read_olap[i] = new double[m+1];
    for (size_t j = 0; j <= i ; ++j) {
      double p_s = 0.0;
      double p_not_s = 0.0;

      p_cons_read_olap[i][j] = p_s + p_not_s;
    }
  }
}

void clearProbabilities() {
for (size_t i = 0; i < Options::opts.m; ++i) {
  delete[] p_rand_read_olap[i];
  delete[] p_cons_read_olap[i];
 }
 delete[] p_rand_read_olap;
 delete[] p_cons_read_olap;
}

/**
 * Compute
 *  \sum_{s}{I(A,B,s)4^s}
 */
double overlappingStringsSum(const std::string & s1, const std::string& s2) {
  size_t m = Options::opts.m;
  double sum = 0.0;
  for (size_t s = 1; s <= m-1; ++s) {
    size_t indicator_ab = (prefixSuffixHammingDistance(s2,s1,s) == 0) ? 1 : 0;
    size_t indicator_ba = (prefixSuffixHammingDistance(s1,s2,s) == 0) ? 1 : 0;
    sum += pow(4,s) * ( indicator_ab + indicator_ba );
  }
  size_t indic_m = (prefixSuffixHammingDistance(s2,s1,m) == 0) ? 1 : 0;
  sum += indic_m * pow(4,m);
  return sum;
}

/**
 * Computes probability of a random overlap of 's' bases with an hamming distance dh
 */
double randomReadsOverlapProbNoErr(const std::string& s1, const std::string& s2, size_t s) {
  size_t dh_for_s = prefixSuffixHammingDistance(s1,s2,s);
  if (dh_for_s != 0) {
    return 0;
  }
  double olap_p = overlappingStringsSum(s1,s2) + (double)Options::opts.N - 2 * (double)Options::opts.m + 1.0;
  return ( pow(4,s) / ( olap_p) ) ;
}
<commit_msg>Cleaned prob.cpp file of old parts<commit_after>#include "common.h"

#include <iostream>

#include <boost/math/special_functions/binomial.hpp>

// probability of equality of two calls of the SAME reference position
double p_equal_calls = 0.0;

// probability of 'sequenced position' which represents the probability of a read
// starting at a given position of the reference
double p_read_start = 0.0;

void initProbabilities() {
// convenience variables
  double p_err = Options::opts.pe;
  double q_err = 1.0 - p_err;

  // init p_equal_calls
  p_equal_calls = q_err * q_err + (1.0 / 3.0) * ( p_err * p_err );

  // init p_read_start
  p_read_start = (double)Options::opts.M / (double)Options::opts.N;
}

void clearProbabilities() {

}

/**
 * Compute
 *  \sum_{s}{I(A,B,s)4^s}
 */
double overlappingStringsSum(const std::string & s1, const std::string& s2) {
  size_t m = Options::opts.m;
  double sum = 0.0;
  for (size_t s = 1; s <= m-1; ++s) {
    size_t indicator_ab = (prefixSuffixHammingDistance(s2,s1,s) == 0) ? 1 : 0;
    size_t indicator_ba = (prefixSuffixHammingDistance(s1,s2,s) == 0) ? 1 : 0;
    sum += pow(4,s) * ( indicator_ab + indicator_ba );
  }
  size_t indic_m = (prefixSuffixHammingDistance(s2,s1,m) == 0) ? 1 : 0;
  sum += indic_m * pow(4,m);
  return sum;
}

/**
 * Computes probability of a random overlap of 's' bases with an hamming distance dh
 */
double randomReadsOverlapProbNoErr(const std::string& s1, const std::string& s2, size_t s) {
  size_t dh_for_s = prefixSuffixHammingDistance(s1,s2,s);
  if (dh_for_s != 0) {
    return 0;
  }
  double olap_p = overlappingStringsSum(s1,s2) + (double)Options::opts.N - 2 * (double)Options::opts.m + 1.0;
  return ( pow(4,s) / ( olap_p) ) ;
}
<|endoftext|>


<commit_before>#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__

#include <aleph/topology/Intersections.hh>

#include <algorithm>
#include <unordered_map>
#include <set>
#include <vector>

namespace aleph
{

namespace topology
{

/**
  Stores coface relationships in a simplicial complex. Given a simplex
  \f$\sigma\f$, the map contains all of its cofaces. Note that the map
  will be updated upon every elementary collapse.
*/

template <class Simplex> using CofaceMap = std::unordered_map<Simplex, std::unordered_set<Simplex> >;

template <class SimplicialComplex> CofaceMap<typename SimplicialComplex::ValueType> buildCofaceMap( const SimplicialComplex& K )
{
  using Simplex   = typename SimplicialComplex::ValueType;
  using CofaceMap = CofaceMap<Simplex>;

  CofaceMap cofaces;
  for( auto&& s : K )
  {
    // Adding an *empty* list of cofaces (so far) for this simplex
    // simplifies the rest of the code because there is no need to
    // check for the existence of a simplex.
    if( cofaces.find(s) == cofaces.end() )
      cofaces[s] = {};

    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
      cofaces[ *itFace ].insert( s );
  }

  return cofaces;
}

template <class Simplex> bool isPrincipal( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
  return cofaces.at( s ).empty();
}

template <class Simplex> Simplex getFreeFace( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
  if( !isPrincipal( cofaces, s ) )
    return Simplex();

  // Check whether a free face exists ----------------------------------

  for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
  {
    auto&& allCofaces = cofaces.at( *itFace );
    if( allCofaces.size() == 1 && allCofaces.find( s ) != allCofaces.end() )
      return *itFace;
  }

  return Simplex();
}

/**
  Checks whether a simplex in a simplicial complex is principal, i.e.
  whether it is not a proper face of any other simplex in K.
*/

template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
  // Individual vertices cannot be considered to be principal because
  // they do not have a free face.
  if( s.dimension() == 0 )
    return false;

  bool principal = true;
  auto itPair    = K.range( s.dimension() + 1 );

  for( auto it = itPair.first; it != itPair.second; ++it )
  {
    auto&& t = *it;

    // This check assumes that the simplicial complex is valid, so it
    // suffices to search faces in one dimension _below_ s. Note that
    // the check only has to evaluate the *size* of the intersection,
    // as this is sufficient to determine whether a simplex is a face
    // of another simplex.
    if( sizeOfIntersection(s,t) == s.size() )
      principal = false;
  }

  return principal;
}

/**
  Checks whether a simplex in a simplicial complex is admissible, i.e.
  the simplex is *principal* and has at least one free face.
*/

template <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
  if( !isPrincipal(s,K) )
    return Simplex();

  // Check whether a free face exists ----------------------------------

  std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
  std::vector<bool> admissible( faces.size(), true );

  std::size_t i = 0;
  auto itPair   = K.range( s.dimension() ); // valid range for searches, viz. *all*
                                            // faces in "one dimension up"

  for( auto&& face : faces )
  {
    for( auto it = itPair.first; it != itPair.second; ++it )
    {
      auto&& t = *it;

      // We do not have to check for intersections with the original
      // simplex from which we started---we already know that we are
      // a face.
      if( t != s )
      {
        if( sizeOfIntersection(face,t) == face.size() )
        {
          admissible[i] = false;
          break;
        }
      }
    }

    ++i;
  }

  auto pos = std::find( admissible.begin(), admissible.end(), true );
  if( pos == admissible.end() )
    return Simplex();
  else
    return faces.at( std::distance( admissible.begin(), pos ) );
}

/**
  Calculates all principal faces of a given simplicial complex and
  returns them.
*/

template <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )
{
  using Simplex = typename SimplicialComplex::value_type;
  auto L        = K;

  std::unordered_map<Simplex, Simplex> admissible;

  // Step 1: determine free faces --------------------------------------
  //
  // This first checks which simplices have at least one free face,
  // meaning that they may be potentially admissible.

  for( auto it = L.begin(); it != L.end(); ++it )
  {
    if( it->dimension() == 0 )
      continue;

    // The range of the complex M is sufficient because we have
    // already encountered all lower-dimensional simplices that
    // precede the current one given by `it`.
    //
    // This complex will be used for testing free faces.
    SimplicialComplex M( L.begin(), it );

    // FIXME:
    //
    // In case of equal data values, the assignment from above does
    // *not* work and will result in incorrect candidates.
    M = L;

    bool hasFreeFace = false;
    Simplex freeFace = Simplex();

    for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )
    {
      bool isFace = false;
      for( auto&& simplex : M )
      {
        if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )
        {
          // The current face must *not* be a face of another simplex in
          // the simplicial complex.
          if( intersect( *itFace, simplex ) == *itFace )
          {
            isFace = true;
            break;
          }
        }
      }

      hasFreeFace = !isFace;
      if( hasFreeFace )
      {
        freeFace = *itFace;
        break;
      }
    }

    if( hasFreeFace )
      admissible.insert( std::make_pair( *it, freeFace ) );
  }

  // Step 2: determine principality ------------------------------------
  //
  // All simplices that are faces of higher-dimensional simplices are
  // now removed from the map of admissible simplices.

  for( auto&& s : L )
  {
    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
      admissible.erase( *itFace );
  }

  return admissible;
}

/**
  Performs an iterated elementary simplicial collapse until *all* of the
  admissible simplices have been collapsed. This leads to the *spine* of
  the simplicial complex.

  @see S. Matveev, "Algorithmic Topology and Classification of 3-Manifolds"
*/

template <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )
{
  using Simplex = typename SimplicialComplex::value_type;
  auto L        = K;

  // Step 1: obtain initial set of principal faces to start the process
  // of collapsing the complex.
  auto admissible = principalFaces( L );

  // Step 2: collapse until no admissible simplices are left -----------

  while( !admissible.empty() )
  {
    auto s = admissible.begin()->first;
    auto t = admissible.begin()->second;

    L.remove_without_validation( s );
    L.remove_without_validation( t );

    admissible.erase( s );

    // New simplices ---------------------------------------------------
    //
    // Add new admissible simplices that may potentially have been
    // spawned by the removal of s.

    // 1. Add all faces of the principal simplex, as they may
    //    potentially become admissible again.
    std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );

    std::for_each( faces.begin(), faces.end(),
      [&t, &L, &admissible] ( const Simplex& s )
      {
        // TODO: rename function
        auto face = isAdmissible( s, L );

        if( t != s && face )
          admissible.insert( std::make_pair( s, face ) );
      }
    );

    // 2. Add all faces othe free face, as they may now themselves
    //    become admissible.
    faces.assign( t.begin_boundary(), t.end_boundary() );

    std::for_each( faces.begin(), faces.end(),
      [&L, &admissible] ( const Simplex& s )
      {
        // TODO: rename function
        auto face = isAdmissible( s, L );

        if( face )
          admissible.insert( std::make_pair( s, face ) );
      }
    );

#if 0
    // TODO: this check could be simplified by *storing* the free face
    // along with the given simplex
    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
    {
      auto t = *itFace;

      if( isAdmissible( s, t, L ) )
      {
        L.remove_without_validation( s );
        L.remove_without_validation( t );

        admissible.erase( s );

        // New simplices -----------------------------------------------
        //
        // Add new admissible simplices that may potentially have been
        // spawned by the removal of s.

        // 1. Add all faces of the principal simplex, as they may
        //    potentially become admissible again.
        std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );

        std::for_each( faces.begin(), faces.end(),
          [&t, &L, &admissible] ( const Simplex& s )
          {
            if( t != s && isAdmissible( s, L ) )
              admissible.insert( s );
          }
        );

        // 2. Add all faces othe free face, as they may now themselves
        //    become admissible.
        faces.assign( t.begin_boundary(), t.end_boundary() );

        std::for_each( faces.begin(), faces.end(),
          [&L, &admissible] ( const Simplex& s )
          {
            if( isAdmissible( s, L ) )
              admissible.insert( s );
          }
        );

        hasFreeFace = true;
        break;
      }
    }

    // The admissible simplex does not have a free face, so it must not
    // be used.
    if( !hasFreeFace )
      admissible.erase( s );
#endif

    // The heuristic above is incapable of detecting *all* principal
    // faces of the complex because this may involve searching *all*
    // co-faces. Instead, it is easier to fill up the admissible set
    // here.
    if( admissible.empty() )
      admissible = principalFaces( L );
  }

  return L;
}

} // namespace topology

} // namespace aleph

#endif
<commit_msg>New function for obtaining and storing cofaces<commit_after>#ifndef ALEPH_TOPOLOGY_SPINE_HH__
#define ALEPH_TOPOLOGY_SPINE_HH__

#include <aleph/topology/Intersections.hh>

#include <algorithm>
#include <unordered_map>
#include <set>
#include <vector>

namespace aleph
{

namespace topology
{

/**
  Stores coface relationships in a simplicial complex. Given a simplex
  \f$\sigma\f$, the map contains all of its cofaces. Note that the map
  will be updated upon every elementary collapse.
*/

template <class Simplex> using CofaceMap = std::unordered_map<Simplex, std::unordered_set<Simplex> >;

template <class SimplicialComplex> CofaceMap<typename SimplicialComplex::ValueType> buildCofaceMap( const SimplicialComplex& K )
{
  using Simplex   = typename SimplicialComplex::ValueType;
  using CofaceMap = CofaceMap<Simplex>;

  CofaceMap cofaces;
  for( auto&& s : K )
  {
    // Adding an *empty* list of cofaces (so far) for this simplex
    // simplifies the rest of the code because there is no need to
    // check for the existence of a simplex.
    if( cofaces.find(s) == cofaces.end() )
      cofaces[s] = {};

    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
      cofaces[ *itFace ].insert( s );
  }

  return cofaces;
}

template <class Simplex> bool isPrincipal( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
  return cofaces.at( s ).empty();
}

template <class Simplex> Simplex getFreeFace( const CofaceMap<Simplex>& cofaces, const Simplex& s )
{
  if( !isPrincipal( cofaces, s ) )
    return Simplex();

  // Check whether a free face exists ----------------------------------

  for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
  {
    auto&& allCofaces = cofaces.at( *itFace );
    if( allCofaces.size() == 1 && allCofaces.find( s ) != allCofaces.end() )
      return *itFace;
  }

  return Simplex();
}

template <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> getPrincipalFaces( const CofaceMap<typename SimplicialComplex::ValueType>& cofaces, const SimplicialComplex& K )
{
  using Simplex = typename SimplicialComplex::value_type;
  auto L        = K;

  std::unordered_map<Simplex, Simplex> admissible;

  for( auto&& s : K )
  {
    auto freeFace = getFreeFace( cofaces, s );
    if( freeFace )
      admissible.insert( std::make_pair( s, freeFace ) );
  }

  return admissible;
}

/**
  Checks whether a simplex in a simplicial complex is principal, i.e.
  whether it is not a proper face of any other simplex in K.
*/

template <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )
{
  // Individual vertices cannot be considered to be principal because
  // they do not have a free face.
  if( s.dimension() == 0 )
    return false;

  bool principal = true;
  auto itPair    = K.range( s.dimension() + 1 );

  for( auto it = itPair.first; it != itPair.second; ++it )
  {
    auto&& t = *it;

    // This check assumes that the simplicial complex is valid, so it
    // suffices to search faces in one dimension _below_ s. Note that
    // the check only has to evaluate the *size* of the intersection,
    // as this is sufficient to determine whether a simplex is a face
    // of another simplex.
    if( sizeOfIntersection(s,t) == s.size() )
      principal = false;
  }

  return principal;
}

/**
  Checks whether a simplex in a simplicial complex is admissible, i.e.
  the simplex is *principal* and has at least one free face.
*/

template <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )
{
  if( !isPrincipal(s,K) )
    return Simplex();

  // Check whether a free face exists ----------------------------------

  std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );
  std::vector<bool> admissible( faces.size(), true );

  std::size_t i = 0;
  auto itPair   = K.range( s.dimension() ); // valid range for searches, viz. *all*
                                            // faces in "one dimension up"

  for( auto&& face : faces )
  {
    for( auto it = itPair.first; it != itPair.second; ++it )
    {
      auto&& t = *it;

      // We do not have to check for intersections with the original
      // simplex from which we started---we already know that we are
      // a face.
      if( t != s )
      {
        if( sizeOfIntersection(face,t) == face.size() )
        {
          admissible[i] = false;
          break;
        }
      }
    }

    ++i;
  }

  auto pos = std::find( admissible.begin(), admissible.end(), true );
  if( pos == admissible.end() )
    return Simplex();
  else
    return faces.at( std::distance( admissible.begin(), pos ) );
}

/**
  Calculates all principal faces of a given simplicial complex and
  returns them.
*/

template <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )
{
  using Simplex = typename SimplicialComplex::value_type;
  auto L        = K;

  std::unordered_map<Simplex, Simplex> admissible;

  // Step 1: determine free faces --------------------------------------
  //
  // This first checks which simplices have at least one free face,
  // meaning that they may be potentially admissible.

  for( auto it = L.begin(); it != L.end(); ++it )
  {
    if( it->dimension() == 0 )
      continue;

    // The range of the complex M is sufficient because we have
    // already encountered all lower-dimensional simplices that
    // precede the current one given by `it`.
    //
    // This complex will be used for testing free faces.
    SimplicialComplex M( L.begin(), it );

    // FIXME:
    //
    // In case of equal data values, the assignment from above does
    // *not* work and will result in incorrect candidates.
    M = L;

    bool hasFreeFace = false;
    Simplex freeFace = Simplex();

    for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )
    {
      bool isFace = false;
      for( auto&& simplex : M )
      {
        if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )
        {
          // The current face must *not* be a face of another simplex in
          // the simplicial complex.
          if( intersect( *itFace, simplex ) == *itFace )
          {
            isFace = true;
            break;
          }
        }
      }

      hasFreeFace = !isFace;
      if( hasFreeFace )
      {
        freeFace = *itFace;
        break;
      }
    }

    if( hasFreeFace )
      admissible.insert( std::make_pair( *it, freeFace ) );
  }

  // Step 2: determine principality ------------------------------------
  //
  // All simplices that are faces of higher-dimensional simplices are
  // now removed from the map of admissible simplices.

  for( auto&& s : L )
  {
    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
      admissible.erase( *itFace );
  }

  return admissible;
}

/**
  Performs an iterated elementary simplicial collapse until *all* of the
  admissible simplices have been collapsed. This leads to the *spine* of
  the simplicial complex.

  @see S. Matveev, "Algorithmic Topology and Classification of 3-Manifolds"
*/

template <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )
{
  using Simplex = typename SimplicialComplex::value_type;
  auto L        = K;

  // Step 1: obtain initial set of principal faces to start the process
  // of collapsing the complex.
  auto admissible = principalFaces( L );

  // Step 2: collapse until no admissible simplices are left -----------

  while( !admissible.empty() )
  {
    auto s = admissible.begin()->first;
    auto t = admissible.begin()->second;

    L.remove_without_validation( s );
    L.remove_without_validation( t );

    admissible.erase( s );

    // New simplices ---------------------------------------------------
    //
    // Add new admissible simplices that may potentially have been
    // spawned by the removal of s.

    // 1. Add all faces of the principal simplex, as they may
    //    potentially become admissible again.
    std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );

    std::for_each( faces.begin(), faces.end(),
      [&t, &L, &admissible] ( const Simplex& s )
      {
        // TODO: rename function
        auto face = isAdmissible( s, L );

        if( t != s && face )
          admissible.insert( std::make_pair( s, face ) );
      }
    );

    // 2. Add all faces othe free face, as they may now themselves
    //    become admissible.
    faces.assign( t.begin_boundary(), t.end_boundary() );

    std::for_each( faces.begin(), faces.end(),
      [&L, &admissible] ( const Simplex& s )
      {
        // TODO: rename function
        auto face = isAdmissible( s, L );

        if( face )
          admissible.insert( std::make_pair( s, face ) );
      }
    );

#if 0
    // TODO: this check could be simplified by *storing* the free face
    // along with the given simplex
    for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )
    {
      auto t = *itFace;

      if( isAdmissible( s, t, L ) )
      {
        L.remove_without_validation( s );
        L.remove_without_validation( t );

        admissible.erase( s );

        // New simplices -----------------------------------------------
        //
        // Add new admissible simplices that may potentially have been
        // spawned by the removal of s.

        // 1. Add all faces of the principal simplex, as they may
        //    potentially become admissible again.
        std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );

        std::for_each( faces.begin(), faces.end(),
          [&t, &L, &admissible] ( const Simplex& s )
          {
            if( t != s && isAdmissible( s, L ) )
              admissible.insert( s );
          }
        );

        // 2. Add all faces othe free face, as they may now themselves
        //    become admissible.
        faces.assign( t.begin_boundary(), t.end_boundary() );

        std::for_each( faces.begin(), faces.end(),
          [&L, &admissible] ( const Simplex& s )
          {
            if( isAdmissible( s, L ) )
              admissible.insert( s );
          }
        );

        hasFreeFace = true;
        break;
      }
    }

    // The admissible simplex does not have a free face, so it must not
    // be used.
    if( !hasFreeFace )
      admissible.erase( s );
#endif

    // The heuristic above is incapable of detecting *all* principal
    // faces of the complex because this may involve searching *all*
    // co-faces. Instead, it is easier to fill up the admissible set
    // here.
    if( admissible.empty() )
      admissible = principalFaces( L );
  }

  return L;
}

} // namespace topology

} // namespace aleph

#endif
<|endoftext|>


<commit_before>/*
 *  caosVM_flow.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Sun May 30 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 */

#include "caosVM.h"
#include <iostream>
#include "openc2e.h"
#include "World.h" // enum
#include <cmath>   // sqrt
#include <sstream>

/**
 DOIF (command) condition (condition)
 %pragma parser new DoifParser()
 %status maybe

 Part of a DOIF/ELIF/ELSE/ENDI block. Jump to the next part of the block if condition is false, otherwise continue executing.
*/

/**
 ELIF (command) condition (condition)
 %pragma parser new DoifParser()
 %status maybe

 Part of a DOIF/ELIF/ELSE/ENDI block. If none of the previous DOIF/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed.
 If found outside a DOIF block, it is equivalent to a DOIF. If you take advantage of this behavior, you should be shot.
*/

/**
 ELSE (command)
 %pragma noparse
 %status maybe

 Part of a DOIF/ELIF/ELSE/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF/ELIF conditions are true.
*/

/**
 ENDI (command)
 %pragma noparse
 %status maybe

 The end of a DOIF/ELIF/ELSE/ENDI block.
*/

/**
 REPS (command) reps (integer)
 %pragma parser new parseREPS()
 %status maybe

 The start of a REPS...REPE loop. The body of the loop will be executed (reps)
 times.
*/

/**
 REPE (command)
 %pragma noparse
 %status maybe

 The end of a REPS...REPE loop.
*/

/**
 LOOP (command)
 %pragma parser new parseLOOP()
 %status maybe

 The start of a LOOP..EVER or LOOP..UNTL loop.
*/

/**
 EVER (command)
 %pragma noparse
 %status maybe

 Jump back to the matching LOOP, no matter what.
*/

/**
 UNTL (command) condition (condition)
 %pragma noparse
 %status maybe

 Jump back to the matching LOOP unless the condition evaluates to true.
*/

/**
 GSUB (command) label (label)
 %pragma parser new parseGSUB()
 %pragma retc -1
 %status maybe

 Jump to a subroutine defined by SUBR with label 'label'.
*/

/**
 SUBR (command) label (label)
 %pragma parser new parseSUBR()
 %status maybe

 Define the start of a subroute to be called with GSUB, with label 'label'.
 If the command is encountered during execution, it acts like a STOP.
*/

/**
 RETN (command)
 %pragma retc -1
 %status maybe

 Return from a subroutine called with GSUB.
*/
void caosVM::c_RETN() {
	if (callStack.empty())
		throw creaturesException("RETN with an empty callstack");
	nip = callStack.back().nip;
	valueStack = callStack.back().valueStack;
	callStack.pop_back();
}

/**
 NEXT (command)
 %pragma noparse
 %status maybe

*/

/**
 ENUM (command) family (integer) genus (integer) species (integer)
 %status maybe
 %pragma parserclass ENUMhelper
 %pragma retc -1

 Loop through all agents with the given classifier. 0 on any field is a
 wildcard. The loop body is terminated by a NEXT.
*/
void caosVM::c_ENUM() {
	VM_VERIFY_SIZE(3)
	VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535);
	VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255);
	VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255);

	caosVar nullv;
	nullv.reset();
	valueStack.push_back(nullv);

	for (std::list<Agent *>::iterator i
			= world.agents.begin(); i != world.agents.end(); i++) {
		Agent *a = (*i);
		if (species && species != a->species) continue;
		if (genus && genus != a->genus) continue;
		if (family && family != a->family) continue;

		caosVar v; v.setAgent(a);
		valueStack.push_back(v);
	}
}

/**
 ESEE (command) family (integer) genus (integer) species (integer)
 %status maybe
 %pragma parserclass ENUMhelper
 %pragma retc -1

 like ENUM, but iterate through agents OWNR can see (todo: document exact rules)
*/
void caosVM::c_ESEE() {
	VM_VERIFY_SIZE(3)
	VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535);
	VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255);
	VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255);

	caosVar nullv;
	nullv.reset();
	valueStack.push_back(nullv);

	for (std::list<Agent *>::iterator i
			= world.agents.begin(); i != world.agents.end(); i++) {
		Agent *a = (*i);
		if (species && species != a->species) continue;
		if (genus && genus != a->genus) continue;
		if (family && family != a->family) continue;

		// XXX: measure from center?
		double deltax = (*i)->x - owner->x;
		double deltay = (*i)->y - owner->y;
		deltax *= deltax;
		deltay *= deltay;

		double distance = sqrt(deltax + deltay);
		if (distance > owner->range) continue;

		caosVar v; v.setAgent(a);
		valueStack.push_back(v);
	}
}

/**
 ETCH (command) family (integer) genus (integer) species (integer)
 %pragma parserclass ENUMhelper
 %pragma retc -1
 %status stub

 like ENUM, but iterate through agents OWNR is touching
*/
void caosVM::c_ETCH() {
	VM_VERIFY_SIZE(3)
	VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535);
	VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255);
	VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255);

	// TODO: should probably implement this (ESEE)

	caosVar nullv; nullv.reset();
	valueStack.push_back(nullv);
}

/**
 EPAS (command) family (integer) genus (integer) species (integer)
 %pragma parserclass ENUMhelper
 %pragma retc -1
 %status stub

 like ENUM, but iterate through OWNR vehicle's passengers
*/
void caosVM::c_EPAS() {
	VM_VERIFY_SIZE(3)
	VM_PARAM_INTEGER(species) assert(species >= 0); assert(species <= 65535);
	VM_PARAM_INTEGER(genus) assert(genus >= 0); assert(genus <= 255);
	VM_PARAM_INTEGER(family) assert(family >= 0); assert(family <= 255);

	// TODO: should probably implement this (ESEE)

	caosVar nullv; nullv.reset();
	valueStack.push_back(nullv);
}

/**
 ECON (command) agent (agent)
 %pragma parserclass ENUMhelper
 %pragma retc -1
 %status stub

 like ECON, but iterate through OWNR vehicle's passengers
*/
void caosVM::c_ECON() {
	VM_VERIFY_SIZE(3)
	VM_PARAM_VALIDAGENT(agent)

	// TODO: should probably implement this (ESEE)

	caosVar nullv; nullv.reset();
	valueStack.push_back(nullv);
}

/**
 CALL (command) script_no (integer) p1 (any) p2 (any)
 %status maybe

Calls script_no on OWNR, then waits for it to return. The invoked script
 will inherit the caller's INST setting, but any changes it makes to it will
 be reversed once it returns - so eg if you call a script when in INST mode,
 it calls OVEr and returns, you'll still be in INST.

Script variables (VAxx) will not be preserved - you'll have to use OVxx
 for any parameters.

 */
void caosVM::c_CALL() {
	VM_PARAM_VALUE(p2)
	VM_PARAM_VALUE(p1)
	VM_PARAM_INTEGER(script_no)

	caos_assert(owner);
	caos_assert(script_no > 0 && script_no < 65536);

	shared_ptr


<commit_before>#ifndef BOOST_COMPUTE_TEST_CONTEXT_SETUP_HPP
#define BOOST_COMPUTE_TEST_CONTEXT_SETUP_HPP

#include <boost/compute/system.hpp>
#include <boost/compute/command_queue.hpp>

#include "opencl_version_check.hpp"

struct Context {
    boost::compute::device        device;
    boost::compute::context       context;
    boost::compute::command_queue queue;

    Context() :
        device ( boost::compute::system::default_device() ),
        context( boost::compute::system::default_context() ),
        queue  ( boost::compute::system::default_queue() )
    {}
};

BOOST_FIXTURE_TEST_SUITE(compute_test, Context)

#endif
<commit_msg>modify context_setup<commit_after>#ifndef BOOST_COMPUTE_TEST_CONTEXT_SETUP_HPP
#define BOOST_COMPUTE_TEST_CONTEXT_SETUP_HPP

#include <boost/compute/system.hpp>
#include <boost/compute/command_queue.hpp>

#include "opencl_version_check.hpp"

struct Context {
    boost::compute::device        device;
    boost::compute::context       context;
    boost::compute::command_queue queue;

    Context() :
        device ( boost::compute::system::default_device() ),
        context( boost::compute::system::default_context() ),
        queue  ( boost::compute::system::default_queue() )
    {}
};

BOOST_FIXTURE_TEST_SUITE(neu_test, Context)

#endif
<|endoftext|>


<commit_before>#include <vector>

#include "lua.hpp"
#include "poly2tri.h"

#define luaL_check(c, ...)    if (!(c)) luaL_error(L, __VA_ARGS__)

static int api_triangulate(lua_State *L)
{
  int args = lua_gettop(L);
  luaL_check(args >= 6, "Pass at least 3 vertices to triangulate.", args);
  return 1;
}

static const struct luaL_Reg thislib[] = {
  {"triangulate", api_triangulate},
  {NULL, NULL}
};

extern "C" {
  LUALIB_API int luaopen_poly2tri (lua_State *L);
}

LUALIB_API int luaopen_poly2tri(lua_State * L) {
  lua_newtable(L);

  for (int i = 0; thislib[i].name != NULL; ++i)
  {
    luaL_Reg l = thislib[i];
    lua_pushcfunction(L, l.func);
    lua_setfield(L, -2, l.name);
  }

  lua_pushstring(L, "VERSION");
  lua_pushstring(L, "1.2");
  lua_settable(L, -3);

  return 1;
}
<commit_msg>more triangulation<commit_after>#include <vector>

#include "lua.hpp"
#include "poly2tri.h"

#define luaL_check(c, ...)    if (!(c)) luaL_error(L, __VA_ARGS__)

static int api_triangulate(lua_State *L)
{
  int args = lua_gettop(L);
  luaL_check(args >= 6, "need more vertices '%d'", args);

  std::vector<p2t::Point*> verts;
  for (int i = 1; i <= args; i += 2)
    verts.push_back(new p2t::Point(lua_tonumber(L, i), lua_tonumber(L, i + 1)));

  p2t::CDT* cdt = new p2t::CDT(verts);
  cdt->Triangulate();
  std::vector<p2t::Triangle*> tris = cdt->GetTriangles();
  lua_newtable(L);
  for (size_t i = 0; i < tris.size(); ++i)
  {
    lua_newtable(L);

    lua_pushnumber(L, tris[i]->GetPoint(0)->x);
    lua_rawseti(L, -2, 1);
    lua_pushnumber(L, tris[i]->GetPoint(0)->y);
    lua_rawseti(L, -2, 2);
    lua_pushnumber(L, tris[i]->GetPoint(1)->x);
    lua_rawseti(L, -2, 3);
    lua_pushnumber(L, tris[i]->GetPoint(1)->y);
    lua_rawseti(L, -2, 4);
    lua_pushnumber(L, tris[i]->GetPoint(2)->x);
    lua_rawseti(L, -2, 5);
    lua_pushnumber(L, tris[i]->GetPoint(2)->y);
    lua_rawseti(L, -2, 6);

    lua_rawseti(L, -2, i + 1);
  }
  for (size_t i = 0; i < verts.size(); ++i)
    delete verts[i];
  delete cdt;
  return 1;
}

static const struct luaL_Reg thislib[] = {
  {"triangulate", api_triangulate},
  {NULL, NULL}
};

extern "C" {
  LUALIB_API int luaopen_poly2tri (lua_State *L);
}

LUALIB_API int luaopen_poly2tri(lua_State * L) {
  lua_newtable(L);

  for (int i = 0; thislib[i].name != NULL; ++i)
  {
    luaL_Reg l = thislib[i];
    lua_pushcfunction(L, l.func);
    lua_setfield(L, -2, l.name);
  }

  lua_pushstring(L, "VERSION");
  lua_pushstring(L, "1.2");
  lua_settable(L, -3);

  return 1;
}
<|endoftext|>


<commit_before>// @(#)root/base:$Name:  $:$Id: TRegexp.cxx,v 1.5 2002/02/15 11:41:52 rdm Exp $
// Author: Fons Rademakers   04/08/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TRegexp                                                              //
//                                                                      //
// Regular expression class.                                            //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TRegexp.h"
#include "TString.h"
#include "TError.h"

const unsigned TRegexp::fgMaxpat = 2048;

ClassImp(TRegexp)

//______________________________________________________________________________
TRegexp::TRegexp(const char *re, Bool_t wildcard)
{
   // Create a regular expression from the input string. If wildcard is true
   // then the input string contains a wildcard expression (see MakeWildcard()).

   if (wildcard)
      GenPattern(MakeWildcard(re));
   else
      GenPattern(re);
}

//______________________________________________________________________________
TRegexp::TRegexp(const TString& re)
{
   // Create a regular expression from a TString.

   GenPattern(re.Data());
}

//______________________________________________________________________________
TRegexp::TRegexp(const TRegexp& r)
{
   // Copy ctor.

   CopyPattern(r);
}

//______________________________________________________________________________
TRegexp::~TRegexp()
{
   delete [] fPattern;
}

//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TRegexp& r)
{
   // Assignment operator.

   if (this != &r) {
      delete [] fPattern;
      CopyPattern(r);
   }
   return *this;
}

//______________________________________________________________________________
TRegexp& TRegexp::operator=(const char *str)
{
   // Assignment operator taking a char* and assigning it to a regexp.

   delete [] fPattern;
   GenPattern(str);
   return *this;
}

//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TString &str)
{
   // Assignment operator taking a TString.

   delete [] fPattern;
   GenPattern(str.Data());
   return *this;
}

//______________________________________________________________________________
void TRegexp::GenPattern(const char *str)
{
   // Generate the regular expression pattern.

   fPattern = new Pattern_t[fgMaxpat];
   int error = ::Makepat(str, fPattern, fgMaxpat);
   fStat = (error < 3) ? (EStatVal) error : kToolong;
}

//______________________________________________________________________________
void TRegexp::CopyPattern(const TRegexp& r)
{
   // Copy the regular expression pattern.

   fPattern = new Pattern_t[fgMaxpat];
   memcpy(fPattern, r.fPattern, fgMaxpat * sizeof(Pattern_t));
   fStat = r.fStat;
}

//______________________________________________________________________________
const char *TRegexp::MakeWildcard(const char *re)
{
   // This routine transforms a wildcarding regular expression into
   // a general regular expression used for pattern matching.
   // When using wildcards the regular expression is assumed to be
   // preceded by a "^" (BOL) and terminated by a "$" (EOL). Also, all
   // "*"'s (closures) are assumed to be preceded by a "." (i.e. any character,
   // except "/"'s) and all .'s are escaped (so *.ps is different from *.eps).
   // The special treatment of "/" allows the easy matching of pathnames, e.g.
   // "*.root" will match "aap.root", but not "pipo/aap.root".

   static char buf[fgMaxpat];
   char *s = buf;
   int   len = strlen(re);

   if (!re || !len) return "";

   for (int i = 0; i < len; i++) {
      if (i == 0 && re[i] != '^')
         *s++ = '^';
      if (re[i] == '*') {
         //*s++ = '.';
#ifndef R__WIN32
         const char *wc = "[a-zA-Z0-9_\\.,: -]";
#else
         const char *wc = "[a-zA-Z0-9_., -]";
#endif
         strcpy(s, wc);
         s += strlen(wc);
      }
      if (re[i] == '.')
         *s++ = '\\';
      *s++ = re[i];
      if (i == len-1 && re[i] != '$')
         *s++ = '$';
   }
   *s = '\0';
   return buf;
}

//______________________________________________________________________________
Ssiz_t TRegexp::Index(const TString& string, Ssiz_t* len, Ssiz_t i) const
{
   // Find the first occurance of the regexp in string and return the position.
   // Len is length of the matched string and i is the offset at which the
   // matching should start.

   if (fStat != kOK)
      Error("TRegexp::Index", "Bad Regular Expression");

   const char* startp;
   const char* s = string.Data();
   Ssiz_t slen = string.Length();
   if (slen < i) return kNPOS;
   const char* endp = ::Matchs(s+i, slen-i, fPattern, &startp);
   if (endp) {
      *len = endp - startp;
      return startp - s;
   } else {
      *len = 0;
      return kNPOS;
   }
}

//______________________________________________________________________________
TRegexp::EStatVal TRegexp::Status()
{
   // Check status of regexp.

   EStatVal temp = fStat;
   fStat = kOK;
   return temp;
}

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TString member functions, put here so the linker will include        //
// them only if regular expressions are used.                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t start) const
{
   // Find the first occurance of the regexp in string and return the position.
   // Start is the offset at which the search should start.

   Ssiz_t len;
   return r.Index(*this, &len, start); // len not used
}

//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t* extent, Ssiz_t start) const
{
   // Find the first occurance of the regexp in string and return the position.
   // Extent is length of the matched string and start is the offset at which
   // the matching should start.

   return r.Index(*this, extent, start);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start)
{
   // Return the substring found by applying the regexp starting at start.

   Ssiz_t len;
   Ssiz_t begin = Index(r, &len, start);
   return TSubString(*this, begin, len);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r)
{
   // Return the substring found by applying the regexp.

   return (*this)(r,0);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start) const
{
   // Return the substring found by applying the regexp starting at start.

   Ssiz_t len;
   Ssiz_t begin = Index(r, &len, start);
   return TSubString(*this, begin, len);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r) const
{
   // Return the substring found by applying the regexp.

   return (*this)(r,0);
}

<commit_msg>add + as legal file name character in case of wildcards. Fixes problem for Atlas data challenge.<commit_after>// @(#)root/base:$Name:  $:$Id: TRegexp.cxx,v 1.6 2002/07/05 22:11:00 brun Exp $
// Author: Fons Rademakers   04/08/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TRegexp                                                              //
//                                                                      //
// Regular expression class.                                            //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TRegexp.h"
#include "TString.h"
#include "TError.h"

const unsigned TRegexp::fgMaxpat = 2048;

ClassImp(TRegexp)

//______________________________________________________________________________
TRegexp::TRegexp(const char *re, Bool_t wildcard)
{
   // Create a regular expression from the input string. If wildcard is true
   // then the input string contains a wildcard expression (see MakeWildcard()).

   if (wildcard)
      GenPattern(MakeWildcard(re));
   else
      GenPattern(re);
}

//______________________________________________________________________________
TRegexp::TRegexp(const TString& re)
{
   // Create a regular expression from a TString.

   GenPattern(re.Data());
}

//______________________________________________________________________________
TRegexp::TRegexp(const TRegexp& r)
{
   // Copy ctor.

   CopyPattern(r);
}

//______________________________________________________________________________
TRegexp::~TRegexp()
{
   delete [] fPattern;
}

//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TRegexp& r)
{
   // Assignment operator.

   if (this != &r) {
      delete [] fPattern;
      CopyPattern(r);
   }
   return *this;
}

//______________________________________________________________________________
TRegexp& TRegexp::operator=(const char *str)
{
   // Assignment operator taking a char* and assigning it to a regexp.

   delete [] fPattern;
   GenPattern(str);
   return *this;
}

//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TString &str)
{
   // Assignment operator taking a TString.

   delete [] fPattern;
   GenPattern(str.Data());
   return *this;
}

//______________________________________________________________________________
void TRegexp::GenPattern(const char *str)
{
   // Generate the regular expression pattern.

   fPattern = new Pattern_t[fgMaxpat];
   int error = ::Makepat(str, fPattern, fgMaxpat);
   fStat = (error < 3) ? (EStatVal) error : kToolong;
}

//______________________________________________________________________________
void TRegexp::CopyPattern(const TRegexp& r)
{
   // Copy the regular expression pattern.

   fPattern = new Pattern_t[fgMaxpat];
   memcpy(fPattern, r.fPattern, fgMaxpat * sizeof(Pattern_t));
   fStat = r.fStat;
}

//______________________________________________________________________________
const char *TRegexp::MakeWildcard(const char *re)
{
   // This routine transforms a wildcarding regular expression into
   // a general regular expression used for pattern matching.
   // When using wildcards the regular expression is assumed to be
   // preceded by a "^" (BOL) and terminated by a "$" (EOL). Also, all
   // "*"'s (closures) are assumed to be preceded by a "." (i.e. any character,
   // except "/"'s) and all .'s are escaped (so *.ps is different from *.eps).
   // The special treatment of "/" allows the easy matching of pathnames, e.g.
   // "*.root" will match "aap.root", but not "pipo/aap.root".

   static char buf[fgMaxpat];
   char *s = buf;
   int   len = strlen(re);

   if (!re || !len) return "";

   for (int i = 0; i < len; i++) {
      if (i == 0 && re[i] != '^')
         *s++ = '^';
      if (re[i] == '*') {
         //*s++ = '.';
#ifndef R__WIN32
         const char *wc = "[a-zA-Z0-9_\\.,: +-]";
#else
         const char *wc = "[a-zA-Z0-9_., +-]";
#endif
         strcpy(s, wc);
         s += strlen(wc);
      }
      if (re[i] == '.')
         *s++ = '\\';
      *s++ = re[i];
      if (i == len-1 && re[i] != '$')
         *s++ = '$';
   }
   *s = '\0';
   return buf;
}

//______________________________________________________________________________
Ssiz_t TRegexp::Index(const TString& string, Ssiz_t* len, Ssiz_t i) const
{
   // Find the first occurance of the regexp in string and return the position.
   // Len is length of the matched string and i is the offset at which the
   // matching should start.

   if (fStat != kOK)
      Error("TRegexp::Index", "Bad Regular Expression");

   const char* startp;
   const char* s = string.Data();
   Ssiz_t slen = string.Length();
   if (slen < i) return kNPOS;
   const char* endp = ::Matchs(s+i, slen-i, fPattern, &startp);
   if (endp) {
      *len = endp - startp;
      return startp - s;
   } else {
      *len = 0;
      return kNPOS;
   }
}

//______________________________________________________________________________
TRegexp::EStatVal TRegexp::Status()
{
   // Check status of regexp.

   EStatVal temp = fStat;
   fStat = kOK;
   return temp;
}

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TString member functions, put here so the linker will include        //
// them only if regular expressions are used.                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t start) const
{
   // Find the first occurance of the regexp in string and return the position.
   // Start is the offset at which the search should start.

   Ssiz_t len;
   return r.Index(*this, &len, start); // len not used
}

//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t* extent, Ssiz_t start) const
{
   // Find the first occurance of the regexp in string and return the position.
   // Extent is length of the matched string and start is the offset at which
   // the matching should start.

   return r.Index(*this, extent, start);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start)
{
   // Return the substring found by applying the regexp starting at start.

   Ssiz_t len;
   Ssiz_t begin = Index(r, &len, start);
   return TSubString(*this, begin, len);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r)
{
   // Return the substring found by applying the regexp.

   return (*this)(r,0);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start) const
{
   // Return the substring found by applying the regexp starting at start.

   Ssiz_t len;
   Ssiz_t begin = Index(r, &len, start);
   return TSubString(*this, begin, len);
}

//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r) const
{
   // Return the substring found by applying the regexp.

   return (*this)(r,0);
}

<|endoftext|>


<commit_before>#include <iostream>
#include <stack>
#include <list>
#include <string>
#include <utility>
#include <limits>
#include <vector>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm>

#define INT_MAX std::numeric_limits<int>::max()
#define INT_MIN std::numeric_limits<int>::min()

using namespace std;

typedef unsigned long long ull;
typedef long double ld;
typedef pair<ld, ld> gem;

struct edge {
	int length = 1;
	int to;
};

void print_graph(vector< vector<edge> > graph, int nodes)
{
	for (int i = 0; i < nodes; i++) {
		for (auto j = graph[i].begin(); j != graph[i].end(); ++j) {
			cout << "EDGE: (" << i << ", " << j->to << ")" << endl;
		}
	}
}

ld slope(gem A, gem B)
{
	auto delta_x = B.first - A.first;
	auto delta_y = B.second - A.second;
	return delta_y / delta_x;
}

void topo_sort(int v, vector<bool> &visited, stack<int> &Stack,
		vector< vector<edge> > &Graph)
{
	visited[v] = true;

	for (auto i = Graph[v].begin(); i != Graph[v].end(); ++i) {
		if (!visited[i->to])
			topo_sort(i->to, visited, Stack, Graph);
	}

	Stack.push(v);
}

vector<gem> construct_gems(int N, ld h_start)
{
	vector<gem> gems(N + 1);
	gems[0] = make_pair(h_start, 0.0);

	for (int i = 1; i <= N; i++) {
		gem a;
		cin >> a.first >> a.second;
		gems[i] = a;
	}
	return gems;
}

vector< vector<edge> > construct_graph(int N, int R, vector<gem> &gems)
{
	vector< vector<edge> > graph(N + 1, vector<edge>());

	for (int i = 0; i <= N; i++) {
		for (int j = 0; j <= N; j++) {
			if (gems[j].second > gems[i].second &&
			    abs(slope(gems[j], gems[i])) >= R) {
				edge z;
				z.to = j;
				graph[i].push_back(z);
			}
		}
	}
	return graph;
}

int longest_path(int N, vector< vector<edge> > &graph)
{
	stack<int> Stack;
	vector<int> dist(N + 1, INT_MIN);
	vector<bool> visited(N + 1, false);

	dist[0] = 0;

	for (int i = 0; i <= N; i++) {
		if (visited[i] == false)
			topo_sort(i, visited, Stack, graph);
	}

	while (Stack.empty() == false) {
		int u = Stack.top();
		Stack.pop();

		if (dist[u] != INT_MIN) {
			for (auto i = graph[u].begin(); i != graph[u].end();
			     ++i) {
				dist[i->to] = max(dist[i->to],
						  (dist[u] + i->length));
			}
		}
	}

	auto ans = *max_element(dist.begin(), dist.end());
	return ans;
}

int solve(ld N, ld R, ld W, ld H, ld h_start)
{
	auto gems = construct_gems(N, 0.0);
	auto graph = construct_graph(N, R, gems);
	auto ans = longest_path(N, graph);
	return ans;
}

int main()
{
	ld N, R, W, H; /* gems, ratio, width, height */
	cin >> N >> R >> W >> H;

	cout << solve(N, R, W, H, 0.0) << endl;

	return 0;
}
<commit_msg>Final?<commit_after>#include <iostream>
#include <stack>
#include <list>
#include <string>
#include <utility>
#include <limits>
#include <vector>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm>

#define INT_MAX std::numeric_limits<int>::max()
#define INT_MIN std::numeric_limits<int>::min()

using namespace std;

typedef unsigned long long ull;
typedef long double ld;
typedef pair<ld, ld> gem;

struct edge {
	int length = 1;
	int to;
};

void print_graph(vector< vector<edge> > &graph, int nodes)
{
	for (int i = 0; i < nodes; i++) {
		for (auto j = graph[i].begin(); j != graph[i].end(); ++j) {
			cout << "EDGE: (" << i << ", " << j->to << ")" << endl;
		}
	}
}

ld slope(gem A, gem B)
{
	auto delta_x = B.first - A.first;
	auto delta_y = B.second - A.second;
	return delta_y / delta_x;
}

void topo_sort(int v, vector<bool> &visited, stack<int> &Stack,
		vector< vector<edge> > &Graph)
{
	visited[v] = true;

	for (auto i = Graph[v].begin(); i != Graph[v].end(); ++i) {
		if (!visited[i->to])
			topo_sort(i->to, visited, Stack, Graph);
	}

	Stack.push(v);
}

vector<gem> construct_gems(int N, ld h_start)
{
	vector<gem> gems(N + 1);
	gems[0] = make_pair(h_start, 0.0);

	for (int i = 1; i <= N; i++) {
		gem a;
		cin >> a.first >> a.second;
		gems[i] = a;
	}
	return gems;
}

vector< vector<edge> > construct_graph(int N, int R, vector<gem> &gems)
{
	vector< vector<edge> > graph(N + 1, vector<edge>());

	for (int i = 0; i <= N; i++) {
		for (int j = 0; j <= N; j++) {
			if (gems[j].second > gems[i].second &&
			    abs(slope(gems[j], gems[i])) >= R) {
				edge z;
				z.to = j;
				graph[i].push_back(z);
			}
		}
	}
	return graph;
}

int longest_path(int N, vector< vector<edge> > &graph)
{
	stack<int> Stack;
	vector<int> dist(N + 1, INT_MIN);
	vector<bool> visited(N + 1, false);

	dist[0] = 0;

	for (int i = 0; i <= N; i++) {
		if (visited[i] == false)
			topo_sort(i, visited, Stack, graph);
	}

	while (Stack.empty() == false) {
		int u = Stack.top();
		Stack.pop();

		if (dist[u] != INT_MIN) {
			for (auto i = graph[u].begin(); i != graph[u].end();
			     ++i) {
				dist[i->to] = max(dist[i->to],
						  (dist[u] + i->length));
			}
		}
	}

	auto ans = *max_element(dist.begin(), dist.end());
	return ans;
}

int solve(ld N, ld R, ld W, ld H, ld h_start, vector<gem> &gems)
{
	gems[0].first = h_start;
	auto graph = construct_graph(N, R, gems);
	auto ans = longest_path(N, graph);
	return ans;
}

int main()
{
	ld N, R, W, H; /* gems, ratio, width, height */
	cin >> N >> R >> W >> H;

	auto gems = construct_gems(N, 0.0);

	int max_ans = 0;

	for (ld i = 0; i <= W; ++i) {
		max_ans = max(max_ans, solve(N, R, W, H, i, gems));
	}

	cout << max_ans << endl;

	return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "id.h"
#include "coreconstants.h"

#include <utils/qtcassert.h>

#include <QByteArray>
#include <QHash>
#include <QVector>

#include <string.h>

namespace Core {

/*!
    \class Core::Id

    \brief The class Id encapsulates an identifier. It is used as a type-safe
    helper class instead of a \c QString or \c QByteArray. The internal
    representation of the id is assumed to be plain 7-bit-clean ASCII.

*/

class StringHolder
{
public:
    explicit StringHolder(const char *s)
        : str(s)
    {
        n = strlen(s);
        int m = n;
        h = 0;
        while (m--) {
            h = (h << 4) + *s++;
            h ^= (h & 0xf0000000) >> 23;
            h &= 0x0fffffff;
        }
    }
    int n;
    const char *str;
    uint h;
};

static bool operator==(const StringHolder &sh1, const StringHolder &sh2)
{
    // sh.n is unlikely to discriminate better than the hash.
    return sh1.h == sh2.h && strcmp(sh1.str, sh1.str) == 0;
}

static uint qHash(const StringHolder &sh)
{
    return sh.h;
}

struct IdCache : public QHash<StringHolder, int>
{
#ifndef QTC_ALLOW_STATIC_LEAKS
    ~IdCache()
    {
        for (IdCache::iterator it = begin(); it != end(); ++it)
            free(const_cast<char *>(it.key().str));
    }
#endif
};

static int lastUid = 0;
static QVector<QByteArray> stringFromId;
static IdCache idFromString;

static int theId(const char *str)
{
    QTC_ASSERT(str && *str, return 0);
    StringHolder sh(str);
    int res = idFromString.value(sh, 0);
    if (res == 0) {
        if (lastUid == 0)
            stringFromId.append(QByteArray());
        res = ++lastUid;
        sh.str = qstrdup(sh.str);
        idFromString[sh] = res;
        stringFromId.append(QByteArray::fromRawData(sh.str, sh.n));
    }
    return res;
}

Id::Id(const char *name)
    : m_id(theId(name))
{}

Id::Id(const QString &name)
   : m_id(theId(name.toUtf8()))
{}

QByteArray Id::name() const
{
    return stringFromId.at(m_id);
}

QString Id::toString() const
{
    return QString::fromUtf8(stringFromId.at(m_id));
}

bool Id::operator==(const char *name) const
{
    return strcmp(stringFromId.at(m_id).constData(), name) == 0;
}

// For debugging purposes
CORE_EXPORT const char *nameForId(int id)
{
    return (stringFromId.constData() + id)->constData();
}

} // namespace Core
<commit_msg>IdCache: Use delete[] for memory qstrdup allocated<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "id.h"
#include "coreconstants.h"

#include <utils/qtcassert.h>

#include <QByteArray>
#include <QHash>
#include <QVector>

#include <string.h>

namespace Core {

/*!
    \class Core::Id

    \brief The class Id encapsulates an identifier. It is used as a type-safe
    helper class instead of a \c QString or \c QByteArray. The internal
    representation of the id is assumed to be plain 7-bit-clean ASCII.

*/

class StringHolder
{
public:
    explicit StringHolder(const char *s)
        : str(s)
    {
        n = strlen(s);
        int m = n;
        h = 0;
        while (m--) {
            h = (h << 4) + *s++;
            h ^= (h & 0xf0000000) >> 23;
            h &= 0x0fffffff;
        }
    }
    int n;
    const char *str;
    uint h;
};

static bool operator==(const StringHolder &sh1, const StringHolder &sh2)
{
    // sh.n is unlikely to discriminate better than the hash.
    return sh1.h == sh2.h && strcmp(sh1.str, sh1.str) == 0;
}

static uint qHash(const StringHolder &sh)
{
    return sh.h;
}

struct IdCache : public QHash<StringHolder, int>
{
#ifndef QTC_ALLOW_STATIC_LEAKS
    ~IdCache()
    {
        for (IdCache::iterator it = begin(); it != end(); ++it)
            delete[](const_cast<char *>(it.key().str));
    }
#endif
};

static int lastUid = 0;
static QVector<QByteArray> stringFromId;
static IdCache idFromString;

static int theId(const char *str)
{
    QTC_ASSERT(str && *str, return 0);
    StringHolder sh(str);
    int res = idFromString.value(sh, 0);
    if (res == 0) {
        if (lastUid == 0)
            stringFromId.append(QByteArray());
        res = ++lastUid;
        sh.str = qstrdup(sh.str);
        idFromString[sh] = res;
        stringFromId.append(QByteArray::fromRawData(sh.str, sh.n));
    }
    return res;
}

Id::Id(const char *name)
    : m_id(theId(name))
{}

Id::Id(const QString &name)
   : m_id(theId(name.toUtf8()))
{}

QByteArray Id::name() const
{
    return stringFromId.at(m_id);
}

QString Id::toString() const
{
    return QString::fromUtf8(stringFromId.at(m_id));
}

bool Id::operator==(const char *name) const
{
    return strcmp(stringFromId.at(m_id).constData(), name) == 0;
}

// For debugging purposes
CORE_EXPORT const char *nameForId(int id)
{
    return (stringFromId.constData() + id)->constData();
}

} // namespace Core
<|endoftext|>