<commit_before>
/*
 * This program source code file is part of KICAD, a free EDA CAD application.
 *
 * Copyright (C) 2007-2010 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
 * Copyright (C) 2007 Kicad Developers, see change_log.txt for contributors.
 *
 * This program 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 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include <cstdarg>

#include "richio.h"

// This file defines 3 classes useful for working with DSN text files and is named
// "richio" after its author, Richard Hollenbeck, aka Dick Hollenbeck.

//-----<LINE_READER>------------------------------------------------------

LINE_READER::LINE_READER( unsigned aMaxLineLength )
{
    lineNum = 0;

    if( aMaxLineLength == 0 )       // caller is goofed up.
        aMaxLineLength = LINE_READER_LINE_DEFAULT_MAX;

    maxLineLength = aMaxLineLength;

    // start at the INITIAL size, expand as needed up to the MAX size in maxLineLength
    capacity = LINE_READER_LINE_INITIAL_SIZE;

    // but never go above user's aMaxLineLength, and leave space for trailing nul
    if( capacity > aMaxLineLength-1 )
        capacity = aMaxLineLength-1;

    line = new char[capacity];

    line[0] = '\0';
    length  = 0;
}

void LINE_READER::expandCapacity( unsigned newsize )
{
    // length can equal maxLineLength and nothing breaks, there's room for
    // the terminating nul. cannot go over this.
    if( newsize > maxLineLength+1 )
        newsize = maxLineLength+1;

    if( newsize > capacity )
    {
        capacity = newsize;

        // resize the buffer, and copy the original data
        char* bigger = new char[capacity];

        memcpy( bigger, line, length );

        delete line;
        line = bigger;
    }
}

FILE_LINE_READER::FILE_LINE_READER( FILE* aFile, const wxString& aFileName, unsigned aMaxLineLength ) :
    LINE_READER( aMaxLineLength ),
    fp( aFile )
{
    source = aFileName;
}

unsigned FILE_LINE_READER::ReadLine() throw (IOError)
{
    length  = 0;
    line[0] = 0;

    // fgets always put a terminating nul at end of its read.
    while( fgets( line + length, capacity - length, fp ) )
    {
        length += strlen( line + length );

        if( length == maxLineLength )
            throw IOError( _("Line length exceeded") );

        // a normal line breaks here, once through
        if( length < capacity-1 || line[length-1] == '\n' )
            break;

        expandCapacity( capacity * 2 );
    }

    if( length )
        ++lineNum;

    return length;
}

unsigned STRING_LINE_READER::ReadLine() throw (IOError)
{
    size_t      nlOffset = lines.find( '\n', ndx );

    if( nlOffset == std::string::npos )
        length = lines.length() - ndx;
    else
        length = nlOffset - ndx + 1;     // include the newline, so +1

    if( length )
    {
        if( length >= maxLineLength )
            throw IOError( _("Line length exceeded") );

        if( length > capacity )
            expandCapacity( length );

        wxASSERT( ndx + length <= lines.length() );

        memcpy( line, &source[ndx], length );

        ++lineNum;
        ndx += length;
    }

    line[length] = 0;

    return length;
}

//-----<OUTPUTFORMATTER>----------------------------------------------------

// factor out a common GetQuoteChar

const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee, const char* quote_char )
{
    // Include '#' so a symbol is not confused with a comment.  We intend
    // to wrap any symbol starting with a '#'.
    // Our LEXER class handles comments, and comments appear to be an extension
    // to the SPECCTRA DSN specification.
    if( *wrapee == '#' )
        return quote_char;

    if( strlen(wrapee)==0 )
        return quote_char;

    bool isFirst = true;

    for(  ; *wrapee;  ++wrapee, isFirst=false )
    {
        static const char quoteThese[] = "\t ()"
            "%"     // per Alfons of freerouting.net, he does not like this unquoted as of 1-Feb-2008
            "{}"    // guessing that these are problems too
            ;

        // if the string to be wrapped (wrapee) has a delimiter in it,
        // return the quote_char so caller wraps the wrapee.
        if( strchr( quoteThese, *wrapee ) )
            return quote_char;

        if( !isFirst  &&  '-' == *wrapee )
            return quote_char;
    }

    return "";  // caller does not need to wrap, can use an unwrapped string.
}

int OUTPUTFORMATTER::vprint( const char* fmt,  va_list ap )  throw( IOError )
{
    int ret = vsnprintf( &buffer[0], buffer.size(), fmt, ap );
    if( ret >= (int) buffer.size() )
    {
        buffer.reserve( ret+200 );
        ret = vsnprintf( &buffer[0], buffer.size(), fmt, ap );
    }

    if( ret > 0 )
        write( &buffer[0], ret );

    return ret;
}

int OUTPUTFORMATTER::sprint( const char* fmt, ... )  throw( IOError )
{
    va_list     args;

    va_start( args, fmt );
    int ret = vprint( fmt, args);
    va_end( args );

    return ret;
}

int OUTPUTFORMATTER::Print( int nestLevel, const char* fmt, ... ) throw( IOError )
{
#define NESTWIDTH           2   ///< how many spaces per nestLevel

    va_list     args;

    va_start( args, fmt );

    int result = 0;
    int total  = 0;

    for( int i=0; i<nestLevel;  ++i )
    {
        // no error checking needed, an exception indicates an error.
        result = sprint( "%*c", NESTWIDTH, ' ' );

        total += result;
    }

    // no error checking needed, an exception indicates an error.
    result = vprint( fmt, args );

    va_end( args );

    total += result;
    return total;
}

const char* OUTPUTFORMATTER::Quoted( std::string* aWrapee ) throw( IOError )
{
    // derived class's notion of what a quote character is
    char quote          = *GetQuoteChar( "(" );

    // Will the string be wrapped based on its interior content?
    const char* squote  = GetQuoteChar( aWrapee->c_str() );

    // Search the interior of the string for 'quote' chars
    // and replace them as found with duplicated quotes.
    // Note that necessarily any string which has internal quotes will
    // also be wrapped in quotes later in this function.
    for( unsigned i=0;  i<aWrapee->size();  ++i )
    {
        if( (*aWrapee)[i] == quote )
        {
            aWrapee->insert( aWrapee->begin()+i, quote );
            ++i;
        }
        else if( (*aWrapee)[0]=='\r' || (*aWrapee)[0]=='\n' )
        {
            // In a desire to maintain accurate line number reporting within DSNLEXER
            // a decision was made to make all S-expression strings be on a single
            // line.  You can embedd \n (human readable) in the text but not
            // '\n' which is 0x0a.
            throw IOError( _( "S-expression string has newline" ) );
        }
    }

    if( *squote )
    {
        // wrap the beginning and end of the string in a quote.
        aWrapee->insert( aWrapee->begin(), quote );
        aWrapee->insert( aWrapee->end(), quote );
    }

    return aWrapee->c_str();
}

//-----<STRING_FORMATTER>----------------------------------------------------

void STRING_FORMATTER::write( const char* aOutBuf, int aCount ) throw( IOError )
{
    mystring.append( aOutBuf, aCount );
}

void STRING_FORMATTER::StripUseless()
{
    std::string  copy = mystring;

    mystring.clear();

    for( std::string::iterator i=copy.begin();  i!=copy.end();  ++i )
    {
        if( !isspace( *i ) && *i!=')' && *i!='(' && *i!='"' )
        {
            mystring += *i;
        }
    }
}

//-----<STREAM_OUTPUTFORMATTER>--------------------------------------

const char* STREAM_OUTPUTFORMATTER::GetQuoteChar( const char* wrapee )
{
    return OUTPUTFORMATTER::GetQuoteChar( wrapee, quoteChar );
}

void STREAM_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount ) throw( IOError )
{
    int lastWrite;

    // This might delay awhile if you were writing to say a socket, but for
    // a file it should only go through the loop once.
    for( int total = 0;  total<aCount;  total += lastWrite )
    {
        lastWrite = os.Write( aOutBuf, aCount ).LastWrite();

        if( !os.IsOk() )
        {
            throw IOError( _( "OUTPUTSTREAM_OUTPUTFORMATTER write error" ) );
        }
    }
}

<commit_msg>use delete[], add assert<commit_after>
/*
 * This program source code file is part of KICAD, a free EDA CAD application.
 *
 * Copyright (C) 2007-2010 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
 * Copyright (C) 2007 Kicad Developers, see change_log.txt for contributors.
 *
 * This program 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 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include <cstdarg>

#include "richio.h"

// This file defines 3 classes useful for working with DSN text files and is named
// "richio" after its author, Richard Hollenbeck, aka Dick Hollenbeck.

//-----<LINE_READER>------------------------------------------------------

LINE_READER::LINE_READER( unsigned aMaxLineLength )
{
    lineNum = 0;

    if( aMaxLineLength == 0 )       // caller is goofed up.
        aMaxLineLength = LINE_READER_LINE_DEFAULT_MAX;

    maxLineLength = aMaxLineLength;

    // start at the INITIAL size, expand as needed up to the MAX size in maxLineLength
    capacity = LINE_READER_LINE_INITIAL_SIZE;

    // but never go above user's aMaxLineLength, and leave space for trailing nul
    if( capacity > aMaxLineLength-1 )
        capacity = aMaxLineLength-1;

    line = new char[capacity];

    line[0] = '\0';
    length  = 0;
}

void LINE_READER::expandCapacity( unsigned newsize )
{
    // length can equal maxLineLength and nothing breaks, there's room for
    // the terminating nul. cannot go over this.
    if( newsize > maxLineLength+1 )
        newsize = maxLineLength+1;

    if( newsize > capacity )
    {
        capacity = newsize;

        // resize the buffer, and copy the original data
        char* bigger = new char[capacity];

        wxASSERT( capacity >= length );

        memcpy( bigger, line, length );

        delete[] line;
        line = bigger;
    }
}

FILE_LINE_READER::FILE_LINE_READER( FILE* aFile, const wxString& aFileName, unsigned aMaxLineLength ) :
    LINE_READER( aMaxLineLength ),
    fp( aFile )
{
    source = aFileName;
}

unsigned FILE_LINE_READER::ReadLine() throw (IOError)
{
    length  = 0;
    line[0] = 0;

    // fgets always put a terminating nul at end of its read.
    while( fgets( line + length, capacity - length, fp ) )
    {
        length += strlen( line + length );

        if( length == maxLineLength )
            throw IOError( _("Line length exceeded") );

        // a normal line breaks here, once through
        if( length < capacity-1 || line[length-1] == '\n' )
            break;

        expandCapacity( capacity * 2 );
    }

    if( length )
        ++lineNum;

    return length;
}

unsigned STRING_LINE_READER::ReadLine() throw (IOError)
{
    size_t      nlOffset = lines.find( '\n', ndx );

    if( nlOffset == std::string::npos )
        length = lines.length() - ndx;
    else
        length = nlOffset - ndx + 1;     // include the newline, so +1

    if( length )
    {
        if( length >= maxLineLength )
            throw IOError( _("Line length exceeded") );

        if( length > capacity )
            expandCapacity( length );

        wxASSERT( ndx + length <= lines.length() );

        memcpy( line, &source[ndx], length );

        ++lineNum;
        ndx += length;
    }

    line[length] = 0;

    return length;
}

//-----<OUTPUTFORMATTER>----------------------------------------------------

// factor out a common GetQuoteChar

const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee, const char* quote_char )
{
    // Include '#' so a symbol is not confused with a comment.  We intend
    // to wrap any symbol starting with a '#'.
    // Our LEXER class handles comments, and comments appear to be an extension
    // to the SPECCTRA DSN specification.
    if( *wrapee == '#' )
        return quote_char;

    if( strlen(wrapee)==0 )
        return quote_char;

    bool isFirst = true;

    for(  ; *wrapee;  ++wrapee, isFirst=false )
    {
        static const char quoteThese[] = "\t ()"
            "%"     // per Alfons of freerouting.net, he does not like this unquoted as of 1-Feb-2008
            "{}"    // guessing that these are problems too
            ;

        // if the string to be wrapped (wrapee) has a delimiter in it,
        // return the quote_char so caller wraps the wrapee.
        if( strchr( quoteThese, *wrapee ) )
            return quote_char;

        if( !isFirst  &&  '-' == *wrapee )
            return quote_char;
    }

    return "";  // caller does not need to wrap, can use an unwrapped string.
}

int OUTPUTFORMATTER::vprint( const char* fmt,  va_list ap )  throw( IOError )
{
    int ret = vsnprintf( &buffer[0], buffer.size(), fmt, ap );
    if( ret >= (int) buffer.size() )
    {
        buffer.reserve( ret+200 );
        ret = vsnprintf( &buffer[0], buffer.size(), fmt, ap );
    }

    if( ret > 0 )
        write( &buffer[0], ret );

    return ret;
}

int OUTPUTFORMATTER::sprint( const char* fmt, ... )  throw( IOError )
{
    va_list     args;

    va_start( args, fmt );
    int ret = vprint( fmt, args);
    va_end( args );

    return ret;
}

int OUTPUTFORMATTER::Print( int nestLevel, const char* fmt, ... ) throw( IOError )
{
#define NESTWIDTH           2   ///< how many spaces per nestLevel

    va_list     args;

    va_start( args, fmt );

    int result = 0;
    int total  = 0;

    for( int i=0; i<nestLevel;  ++i )
    {
        // no error checking needed, an exception indicates an error.
        result = sprint( "%*c", NESTWIDTH, ' ' );

        total += result;
    }

    // no error checking needed, an exception indicates an error.
    result = vprint( fmt, args );

    va_end( args );

    total += result;
    return total;
}

const char* OUTPUTFORMATTER::Quoted( std::string* aWrapee ) throw( IOError )
{
    // derived class's notion of what a quote character is
    char quote          = *GetQuoteChar( "(" );

    // Will the string be wrapped based on its interior content?
    const char* squote  = GetQuoteChar( aWrapee->c_str() );

    // Search the interior of the string for 'quote' chars
    // and replace them as found with duplicated quotes.
    // Note that necessarily any string which has internal quotes will
    // also be wrapped in quotes later in this function.
    for( unsigned i=0;  i<aWrapee->size();  ++i )
    {
        if( (*aWrapee)[i] == quote )
        {
            aWrapee->insert( aWrapee->begin()+i, quote );
            ++i;
        }
        else if( (*aWrapee)[0]=='\r' || (*aWrapee)[0]=='\n' )
        {
            // In a desire to maintain accurate line number reporting within DSNLEXER
            // a decision was made to make all S-expression strings be on a single
            // line.  You can embedd \n (human readable) in the text but not
            // '\n' which is 0x0a.
            throw IOError( _( "S-expression string has newline" ) );
        }
    }

    if( *squote )
    {
        // wrap the beginning and end of the string in a quote.
        aWrapee->insert( aWrapee->begin(), quote );
        aWrapee->insert( aWrapee->end(), quote );
    }

    return aWrapee->c_str();
}

//-----<STRING_FORMATTER>----------------------------------------------------

void STRING_FORMATTER::write( const char* aOutBuf, int aCount ) throw( IOError )
{
    mystring.append( aOutBuf, aCount );
}

void STRING_FORMATTER::StripUseless()
{
    std::string  copy = mystring;

    mystring.clear();

    for( std::string::iterator i=copy.begin();  i!=copy.end();  ++i )
    {
        if( !isspace( *i ) && *i!=')' && *i!='(' && *i!='"' )
        {
            mystring += *i;
        }
    }
}

//-----<STREAM_OUTPUTFORMATTER>--------------------------------------

const char* STREAM_OUTPUTFORMATTER::GetQuoteChar( const char* wrapee )
{
    return OUTPUTFORMATTER::GetQuoteChar( wrapee, quoteChar );
}

void STREAM_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount ) throw( IOError )
{
    int lastWrite;

    // This might delay awhile if you were writing to say a socket, but for
    // a file it should only go through the loop once.
    for( int total = 0;  total<aCount;  total += lastWrite )
    {
        lastWrite = os.Write( aOutBuf, aCount ).LastWrite();

        if( !os.IsOk() )
        {
            throw IOError( _( "OUTPUTSTREAM_OUTPUTFORMATTER write error" ) );
        }
    }
}

<|endoftext|>


<commit_before>//=====================================================================//
/*!	@file
	@brief	stdc++ ライブラリの補助 @n
			libsupc++ ランタイムが最低限必要な関数、定義など
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/glfw_app/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdlib>

namespace std {

    void __throw_bad_function_call()
    {
        abort();
    }

}
<commit_msg>Update: cleanup<commit_after>//=====================================================================//
/*!	@file
	@brief	stdc++ ライブラリの補助 @n
			libsupc++ ランタイムが最低限必要な関数、定義など
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/glfw_app/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdlib>

extern "C" { void sci_puts(const char*); }

namespace std {

    void __throw_bad_function_call()
    {
		sci_puts("bad_function_call\n");
        abort();
    }

	void __throw_bad_alloc()
	{
		sci_puts("bad_alloc\n");
		abort();
	}

#if 0
	void __throw_length_error(char const*e)
	{
		Serial.print("Length Error :");
		Serial.println(e);
	}
#endif
}
<|endoftext|>


<commit_before>/*-------------FDTD.cpp-------------------------------------------------------//
*
*              Finite Difference Time Domain
*
* Purpose: To replicate the results of our invisible lense raytracer with
*          FDTD. Woo!
*
*   Notes: Most of this is coming from the following link:
*             http://www.eecs.wsu.edu/~schneidj/ufdtd/chap3.pdf
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>

// This is the function we writes the bulk of the code in
void FDTD(std::vector<double>& Ez, std::vector<double>& Hy,
          const int final_time, const double eps, const int space,
          std::ofstream& output);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(){

    // defines output
    std::ofstream output("FDTD.dat", std::ofstream::out);

    int space = 200, final_time = 500;
    double eps = 377.0;

    // define initial E and H fields
    std::vector<double> Ez(space, 0.0), Hy(space, 0.0);

    FDTD(Ez, Hy, final_time, eps, space, output);

}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// This is the function we writs the bulk of the code in
void FDTD(std::vector<double>& Ez, std::vector<double>& Hy,
          const int final_time, const double eps, const int space,
          std::ofstream& output){

    // For magnetic field:
    // double offset = 0.00005;

    // for electric field:
    double offset = 0.05;

    // Relative permittivity
    std::vector<double> epsP(space, 0);
    for (int dx= 0; dx < space; dx++){
        if (dx < 100){
            epsP[dx] = 1.0;
        }
        else{
            epsP[dx] = 9.0;
        }
    }

    // Time looping
    for (int t = 0; t < final_time; t++){

        // Linking the final two elements for an ABC
        Hy[space - 1] = Hy[space - 2];

        // update magnetic field
        for (int dx = 0; dx < space - 1; dx++){
            Hy[dx] = Hy[dx] + (Ez[dx + 1] - Ez[dx]) / eps;
            /*
            if (t % 10 == 0){
                output << Hy[dx] + (t * offset) << '\n';
            }
            */

        }

        // Correction to the H field for the TFSF boundary
        Hy[49] -= exp(-(t - 40.) * (t - 40.)/100.0) / eps;

        // Linking the first two elements in the electric field
        Ez[0] = Ez[1];
        Ez[space - 1] = Ez[space - 2];

        // update electric field
        for (int dx = 1; dx < space; dx++){
            Ez[dx] = Ez[dx] + (Hy[dx] - Hy[dx-1]) * eps / epsP[dx];
        }

        // set src for next step
        Ez[50] += exp(-((t +1 - 40.) * (t + 1 - 40.))/100.0);

        //Ez[50] = sin(0.01 * t);
/*
        if (t > 0){
            Ez[50] = sin(0.1 * t) / (0.1 * t);
        }
        else{
            Ez[50] = 1;
        }
*/
        if (t % 10 == 0){
            for (int dx = 0; dx < space; dx++){
                output << Ez[dx] + (t * offset) << '\n';
                //output << Hy[dx] + (t * offset) << '\n';
            }

            output << '\n' << '\n';
        }

    }
}
<commit_msg>removed unnecessary lines<commit_after>/*-------------FDTD.cpp-------------------------------------------------------//
*
*              Finite Difference Time Domain
*
* Purpose: To replicate the results of our invisible lense raytracer with
*          FDTD. Woo!
*
*   Notes: Most of this is coming from the following link:
*             http://www.eecs.wsu.edu/~schneidj/ufdtd/chap3.pdf
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>

// This is the function we writes the bulk of the code in
void FDTD(std::vector<double>& Ez, std::vector<double>& Hy,
          const int final_time, const double eps, const int space,
          std::ofstream& output);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(){

    // defines output
    std::ofstream output("FDTD.dat", std::ofstream::out);

    int space = 200, final_time = 500;
    double eps = 377.0;

    // define initial E and H fields
    std::vector<double> Ez(space, 0.0), Hy(space, 0.0);

    FDTD(Ez, Hy, final_time, eps, space, output);

}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// This is the function we writs the bulk of the code in
void FDTD(std::vector<double>& Ez, std::vector<double>& Hy,
          const int final_time, const double eps, const int space,
          std::ofstream& output){

    // For magnetic field:
    // double offset = 0.00005;

    // for electric field:
    double offset = 0.05;

    // Relative permittivity
    std::vector<double> epsP(space, 0);
    for (int dx= 0; dx < space; dx++){
        if (dx < 100){
            epsP[dx] = 1.0;
        }
        else{
            epsP[dx] = 9.0;
        }
    }

    // Time looping
    for (int t = 0; t < final_time; t++){

        // Linking the final two elements for an ABC
        Hy[space - 1] = Hy[space - 2];

        // update magnetic field
        for (int dx = 0; dx < space - 1; dx++){
            Hy[dx] = Hy[dx] + (Ez[dx + 1] - Ez[dx]) / eps;

        }

        // Correction to the H field for the TFSF boundary
        Hy[49] -= exp(-(t - 40.) * (t - 40.)/100.0) / eps;

        // Linking the first two elements in the electric field
        Ez[0] = Ez[1];
        Ez[space - 1] = Ez[space - 2];

        // update electric field
        for (int dx = 1; dx < space; dx++){
            Ez[dx] = Ez[dx] + (Hy[dx] - Hy[dx-1]) * eps / epsP[dx];
        }

        // set src for next step
        Ez[50] += exp(-((t +1 - 40.) * (t + 1 - 40.))/100.0);

        //Ez[50] = sin(0.01 * t);
/*
        if (t > 0){
            Ez[50] = sin(0.1 * t) / (0.1 * t);
        }
        else{
            Ez[50] = 1;
        }
*/
        if (t % 10 == 0){
            for (int dx = 0; dx < space; dx++){
                output << Ez[dx] + (t * offset) << '\n';
                //output << Hy[dx] + (t * offset) << '\n';
            }

            output << '\n' << '\n';
        }

    }
}
<|endoftext|>


<commit_before>/**
 * OpenGL/SDL widgets example for Guichan.
 */

// Include all necessary headers.
#include <iostream>
#include <guichan.hpp>
#include <guichan/sdl.hpp>
#include <guichan/opengl.hpp>
// A class used to load images for OpenGL using SDL
#include <guichan/opengl/openglsdlimageloader.hpp>
#include "SDL.h"

#ifdef _WIN32
#include <windows.h>
#endif

#include <GL/gl.h>

/*
 * Common stuff we need
 */
bool running = true;

/*
 * SDL Stuff we need
 */
SDL_Surface* screen;
SDL_Event event;

/*
 * Guichan OpenGL/SDL stuff we need
 */
gcn::SDLInput* input;                    // Input driver
gcn::OpenGLGraphics* graphics;           // Graphics driver
gcn::OpenGLSDLImageLoader* imageLoader;  // For loading images

/*
 * Guichan stuff we need
 */
gcn::Gui* gui;            // A Gui object - binds it all together
gcn::ImageFont* font;     // A font

/*
 * All of the default widgets
 */
gcn::Container* top;                 // A top container
gcn::Label* label;                   // A label
gcn::Icon* icon;                     // An icon (image)
gcn::Button* button;                 // A button
gcn::TextField* textField;           // One-line text field
gcn::TextBox* textBox;               // Multi-line text box
gcn::ScrollArea* textBoxScrollArea;  // Scroll area for the text box
gcn::ListBox* listBox;               // A list box
gcn::DropDown* dropDown;             // Drop down
gcn::CheckBox* checkBox1;            // Two checkboxes
gcn::CheckBox* checkBox2;
gcn::RadioButton* radioButton1;      // Three radio buttons
gcn::RadioButton* radioButton2;
gcn::RadioButton* radioButton3;
gcn::Slider* slider;                 // A slider
gcn::Image *image;                   // An image for the icon
gcn::Window *window;
gcn::Image *darkbitsImage;
gcn::Icon* darkbitsIcon;

/*
 * List boxes and dropdowns needs an instance of a listmodel
 * to know what elements they have.
 */
class DemoListModel : public gcn::ListModel
{
public:
	int getNumberOfElements()
	{
		return 5;
	}

	std::string getElementAt(int i)
	{
		switch(i)
		{
            case 0:
                return std::string("zero");
            case 1:
                return std::string("one");
            case 2:
                return std::string("two");
            case 3:
                return std::string("three");
            case 4:
                return std::string("four");
            default: // Just to keep warnings away
                return std::string("");
		}
	}
};

DemoListModel demoListModel;

void initWidgets()
{
	/*
	 * Create all the widgets
	 */
	label = new gcn::Label("Label");

	image = gcn::Image::load("gui-chan.bmp");
	icon = new gcn::Icon(image);

	button = new gcn::Button("Button");

	textField = new gcn::TextField("Text field");

	textBox = new gcn::TextBox("Multiline\nText box");
	textBoxScrollArea = new gcn::ScrollArea(textBox);
	textBoxScrollArea->setWidth(200);
	textBoxScrollArea->setHeight(100);
	textBoxScrollArea->setBorderSize(1);

	listBox = new gcn::ListBox(&demoListModel);
	listBox->setBorderSize(1);

	dropDown = new gcn::DropDown(&demoListModel);

	checkBox1 = new gcn::CheckBox("Checkbox 1");
	checkBox2 = new gcn::CheckBox("Checkbox 2");

	radioButton1 = new gcn::RadioButton("RadioButton 1", "radiogroup", true);
	radioButton2 = new gcn::RadioButton("RadioButton 2", "radiogroup");
	radioButton3 = new gcn::RadioButton("RadioButton 3", "radiogroup");

	slider = new gcn::Slider(0, 10);
	slider->setSize(100, 10);

    window = new gcn::Window("I am a window  Drag me");
    window->setBaseColor(gcn::Color(255, 150, 200, 190));

    darkbitsImage = gcn::Image::load("darkbitslogo_by_haiko.bmp");
    darkbitsIcon = new gcn::Icon(darkbitsImage);
    window->add(darkbitsIcon);
    window->resizeToContent();

    /*
	 * Add them to the top container
	 */
    top->add(label, 10, 10);
    top->add(icon, 10, 30);
    top->add(button, 200, 10);
    top->add(textField, 250, 10);
    top->add(textBoxScrollArea, 200, 50);
    top->add(listBox, 200, 200);
    top->add(dropDown, 500, 10);
    top->add(checkBox1, 500, 130);
	top->add(checkBox2, 500, 150);
	top->add(radioButton1, 500, 200);
	top->add(radioButton2, 500, 220);
	top->add(radioButton3, 500, 240);
	top->add(slider, 500, 300);
    top->add(window, 100, 350);
}

/**
 * Initializes the application
 */
void init()
{
	/*
	 * Here we initialize SDL as we would do with any SDL application.
	 */
	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_OPENGL | SDL_HWACCEL);

	// Setup OpenGL
	glViewport(0, 0, 640, 480);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

	// We want unicode
	SDL_EnableUNICODE(1);
	// We want to enable key repeat
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

	/*
	 * Now it's time for Guichan OpenGL/SDL stuff
	 */
	imageLoader = new gcn::OpenGLSDLImageLoader();

	// The ImageLoader in use is static and must be set to be
	// able to load images
	gcn::Image::setImageLoader(imageLoader);
	graphics = new gcn::OpenGLGraphics();
	// We need to tell OpenGL graphics how big the screen is.
	graphics->setTargetPlane(640, 480);
	input = new gcn::SDLInput();

	/*
	 * Last but not least it's time to initialize and create the gui
	 * with Guichan stuff.
	 */
	top = new gcn::Container();
	// Set the dimension of the top container to match the screen.
	top->setDimension(gcn::Rectangle(0, 0, 640, 480));
	gui = new gcn::Gui();
	// Set gui to use the SDLGraphics object.
	gui->setGraphics(graphics);
	// Set gui to use the SDLInput object
	gui->setInput(input);
	// Set the top container
	gui->setTop(top);
	// Load the image font.
	font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
	// The global font is static and must be set.
	gcn::Widget::setGlobalFont(font);

	initWidgets();
}

/**
 * Halts the application
 */
void halt()
{
	/*
	 * Destroy Guichan stuff
	 */
	delete font;
	delete gui;

	/*
	 * Widgets
	 */
	delete top;
	delete label;
	delete icon;
	delete button;
	delete textField;
	delete textBox;
	delete textBoxScrollArea;
	delete listBox;
	delete dropDown;
	delete checkBox1;
	delete checkBox2;
	delete radioButton1;
	delete radioButton2;
	delete radioButton3;
	delete slider;
    delete window;
    delete darkbitsIcon;
	delete darkbitsImage;

	/*
	 * Destroy Guichan SDL stuff
	 */
	delete input;
	delete graphics;
	delete imageLoader;

	/*
	 * Destroy SDL stuff
	 */
	SDL_Quit();
}

/**
 * Checks input. On escape halt the application.
 */
void checkInput()
{
	/*
	 * Poll SDL events
	 */
	while(SDL_PollEvent(&event))
	{
		if (event.type == SDL_KEYDOWN)
		{
			if (event.key.keysym.sym == SDLK_ESCAPE)
			{
				running = false;
			}
			if (event.key.keysym.sym == SDLK_f)
			{
				if (event.key.keysym.mod & KMOD_CTRL)
				{
					// Works with X11 only
					SDL_WM_ToggleFullScreen(screen);
				}
			}
		}
		else if(event.type == SDL_QUIT)
		{
			running = false;
		}

		/*
		 * Now that we are done polling and using SDL events we pass
		 * the leftovers to the SDLInput object to later be handled by
		 * the Gui.
		 */
		input->pushInput(event);
	}
}

/**
 * Runs the application
 */
void run()
{
	while(running)
	{
		// Poll input
		checkInput();
		// Let the gui perform it's logic (like handle input)
		gui->logic();
		// Draw the gui
		gui->draw();
		// Update the screen
		SDL_GL_SwapBuffers();
	}
}

int main(int argc, char **argv)
{
	try
	{
 		init();
		run();
		halt();
	}
	/*
	 * Catch all Guichan exceptions
	 */
	catch (gcn::Exception e)
	{
		std::cerr << e.getMessage() << std::endl;
		return 1;
	}
	/*
	 * Catch all Std exceptions
	 */
	catch (std::exception e)
	{
		std::cerr << "Std exception: " << e.what() << std::endl;
		return 1;
	}
	/*
	 * Catch all Unknown exceptions
	 */
	catch (...)
	{
		std::cerr << "Unknown exception" << std::endl;
		return 1;
	}

	return 0;
}
<commit_msg>Undef of DELETE has been added.<commit_after>/**
 * OpenGL/SDL widgets example for Guichan.
 */

// Include all necessary headers.
#include <iostream>
#include <guichan.hpp>
#include <guichan/sdl.hpp>
#include <guichan/opengl.hpp>
// A class used to load images for OpenGL using SDL
#include <guichan/opengl/openglsdlimageloader.hpp>
#include "SDL.h"

#ifdef _WIN32
#include <windows.h>
#ifdef DELETE
#undef DELETE
#endif
#endif

#include <GL/gl.h>

/*
 * Common stuff we need
 */
bool running = true;

/*
 * SDL Stuff we need
 */
SDL_Surface* screen;
SDL_Event event;

/*
 * Guichan OpenGL/SDL stuff we need
 */
gcn::SDLInput* input;                    // Input driver
gcn::OpenGLGraphics* graphics;           // Graphics driver
gcn::OpenGLSDLImageLoader* imageLoader;  // For loading images

/*
 * Guichan stuff we need
 */
gcn::Gui* gui;            // A Gui object - binds it all together
gcn::ImageFont* font;     // A font

/*
 * All of the default widgets
 */
gcn::Container* top;                 // A top container
gcn::Label* label;                   // A label
gcn::Icon* icon;                     // An icon (image)
gcn::Button* button;                 // A button
gcn::TextField* textField;           // One-line text field
gcn::TextBox* textBox;               // Multi-line text box
gcn::ScrollArea* textBoxScrollArea;  // Scroll area for the text box
gcn::ListBox* listBox;               // A list box
gcn::DropDown* dropDown;             // Drop down
gcn::CheckBox* checkBox1;            // Two checkboxes
gcn::CheckBox* checkBox2;
gcn::RadioButton* radioButton1;      // Three radio buttons
gcn::RadioButton* radioButton2;
gcn::RadioButton* radioButton3;
gcn::Slider* slider;                 // A slider
gcn::Image *image;                   // An image for the icon
gcn::Window *window;
gcn::Image *darkbitsImage;
gcn::Icon* darkbitsIcon;

/*
 * List boxes and dropdowns needs an instance of a listmodel
 * to know what elements they have.
 */
class DemoListModel : public gcn::ListModel
{
public:
	int getNumberOfElements()
	{
		return 5;
	}

	std::string getElementAt(int i)
	{
		switch(i)
		{
            case 0:
                return std::string("zero");
            case 1:
                return std::string("one");
            case 2:
                return std::string("two");
            case 3:
                return std::string("three");
            case 4:
                return std::string("four");
            default: // Just to keep warnings away
                return std::string("");
		}
	}
};

DemoListModel demoListModel;

void initWidgets()
{
	/*
	 * Create all the widgets
	 */
	label = new gcn::Label("Label");

	image = gcn::Image::load("gui-chan.bmp");
	icon = new gcn::Icon(image);

	button = new gcn::Button("Button");

	textField = new gcn::TextField("Text field");

	textBox = new gcn::TextBox("Multiline\nText box");
	textBoxScrollArea = new gcn::ScrollArea(textBox);
	textBoxScrollArea->setWidth(200);
	textBoxScrollArea->setHeight(100);
	textBoxScrollArea->setBorderSize(1);

	listBox = new gcn::ListBox(&demoListModel);
	listBox->setBorderSize(1);

	dropDown = new gcn::DropDown(&demoListModel);

	checkBox1 = new gcn::CheckBox("Checkbox 1");
	checkBox2 = new gcn::CheckBox("Checkbox 2");

	radioButton1 = new gcn::RadioButton("RadioButton 1", "radiogroup", true);
	radioButton2 = new gcn::RadioButton("RadioButton 2", "radiogroup");
	radioButton3 = new gcn::RadioButton("RadioButton 3", "radiogroup");

	slider = new gcn::Slider(0, 10);
	slider->setSize(100, 10);

    window = new gcn::Window("I am a window  Drag me");
    window->setBaseColor(gcn::Color(255, 150, 200, 190));

    darkbitsImage = gcn::Image::load("darkbitslogo_by_haiko.bmp");
    darkbitsIcon = new gcn::Icon(darkbitsImage);
    window->add(darkbitsIcon);
    window->resizeToContent();

    /*
	 * Add them to the top container
	 */
    top->add(label, 10, 10);
    top->add(icon, 10, 30);
    top->add(button, 200, 10);
    top->add(textField, 250, 10);
    top->add(textBoxScrollArea, 200, 50);
    top->add(listBox, 200, 200);
    top->add(dropDown, 500, 10);
    top->add(checkBox1, 500, 130);
	top->add(checkBox2, 500, 150);
	top->add(radioButton1, 500, 200);
	top->add(radioButton2, 500, 220);
	top->add(radioButton3, 500, 240);
	top->add(slider, 500, 300);
    top->add(window, 100, 350);
}

/**
 * Initializes the application
 */
void init()
{
	/*
	 * Here we initialize SDL as we would do with any SDL application.
	 */
	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_OPENGL | SDL_HWACCEL);

	// Setup OpenGL
	glViewport(0, 0, 640, 480);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

	// We want unicode
	SDL_EnableUNICODE(1);
	// We want to enable key repeat
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

	/*
	 * Now it's time for Guichan OpenGL/SDL stuff
	 */
	imageLoader = new gcn::OpenGLSDLImageLoader();

	// The ImageLoader in use is static and must be set to be
	// able to load images
	gcn::Image::setImageLoader(imageLoader);
	graphics = new gcn::OpenGLGraphics();
	// We need to tell OpenGL graphics how big the screen is.
	graphics->setTargetPlane(640, 480);
	input = new gcn::SDLInput();

	/*
	 * Last but not least it's time to initialize and create the gui
	 * with Guichan stuff.
	 */
	top = new gcn::Container();
	// Set the dimension of the top container to match the screen.
	top->setDimension(gcn::Rectangle(0, 0, 640, 480));
	gui = new gcn::Gui();
	// Set gui to use the SDLGraphics object.
	gui->setGraphics(graphics);
	// Set gui to use the SDLInput object
	gui->setInput(input);
	// Set the top container
	gui->setTop(top);
	// Load the image font.
	font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
	// The global font is static and must be set.
	gcn::Widget::setGlobalFont(font);

	initWidgets();
}

/**
 * Halts the application
 */
void halt()
{
	/*
	 * Destroy Guichan stuff
	 */
	delete font;
	delete gui;

	/*
	 * Widgets
	 */
	delete top;
	delete label;
	delete icon;
	delete button;
	delete textField;
	delete textBox;
	delete textBoxScrollArea;
	delete listBox;
	delete dropDown;
	delete checkBox1;
	delete checkBox2;
	delete radioButton1;
	delete radioButton2;
	delete radioButton3;
	delete slider;
    delete window;
    delete darkbitsIcon;
	delete darkbitsImage;

	/*
	 * Destroy Guichan SDL stuff
	 */
	delete input;
	delete graphics;
	delete imageLoader;

	/*
	 * Destroy SDL stuff
	 */
	SDL_Quit();
}

/**
 * Checks input. On escape halt the application.
 */
void checkInput()
{
	/*
	 * Poll SDL events
	 */
	while(SDL_PollEvent(&event))
	{
		if (event.type == SDL_KEYDOWN)
		{
			if (event.key.keysym.sym == SDLK_ESCAPE)
			{
				running = false;
			}
			if (event.key.keysym.sym == SDLK_f)
			{
				if (event.key.keysym.mod & KMOD_CTRL)
				{
					// Works with X11 only
					SDL_WM_ToggleFullScreen(screen);
				}
			}
		}
		else if(event.type == SDL_QUIT)
		{
			running = false;
		}

		/*
		 * Now that we are done polling and using SDL events we pass
		 * the leftovers to the SDLInput object to later be handled by
		 * the Gui.
		 */
		input->pushInput(event);
	}
}

/**
 * Runs the application
 */
void run()
{
	while(running)
	{
		// Poll input
		checkInput();
		// Let the gui perform it's logic (like handle input)
		gui->logic();
		// Draw the gui
		gui->draw();
		// Update the screen
		SDL_GL_SwapBuffers();
	}
}

int main(int argc, char **argv)
{
	try
	{
 		init();
		run();
		halt();
	}
	/*
	 * Catch all Guichan exceptions
	 */
	catch (gcn::Exception e)
	{
		std::cerr << e.getMessage() << std::endl;
		return 1;
	}
	/*
	 * Catch all Std exceptions
	 */
	catch (std::exception e)
	{
		std::cerr << "Std exception: " << e.what() << std::endl;
		return 1;
	}
	/*
	 * Catch all Unknown exceptions
	 */
	catch (...)
	{
		std::cerr << "Unknown exception" << std::endl;
		return 1;
	}

	return 0;
}
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file KeyWords.cxx
 ** Colourise for particular languages.
 **/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "WordList.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

/**
 * Creates an array that points into each word in the string and puts \0 terminators
 * after each word.
 */
static char **ArrayFromWordList(char *wordlist, int *len, bool onlyLineEnds = false) {
	int prev = '\n';
	int words = 0;
	// For rapid determination of whether a character is a separator, build
	// a look up table.
	bool wordSeparator[256];
	for (int i=0; i<256; i++) {
		wordSeparator[i] = false;
	}
	wordSeparator['\r'] = true;
	wordSeparator['\n'] = true;
	if (!onlyLineEnds) {
		wordSeparator[' '] = true;
		wordSeparator['\t'] = true;
	}
	for (int j = 0; wordlist[j]; j++) {
		int curr = static_cast<unsigned char>(wordlist[j]);
		if (!wordSeparator[curr] && wordSeparator[prev])
			words++;
		prev = curr;
	}
	char **keywords = new char *[words + 1];
	if (keywords) {
		words = 0;
		prev = '\0';
		size_t slen = strlen(wordlist);
		for (size_t k = 0; k < slen; k++) {
			if (!wordSeparator[static_cast<unsigned char>(wordlist[k])]) {
				if (!prev) {
					keywords[words] = &wordlist[k];
					words++;
				}
			} else {
				wordlist[k] = '\0';
			}
			prev = wordlist[k];
		}
		keywords[words] = &wordlist[slen];
		*len = words;
	} else {
		*len = 0;
	}
	return keywords;
}

bool WordList::operator!=(const WordList &other) const {
	if (len != other.len)
		return true;
	for (int i=0; i<len; i++) {
		if (strcmp(words[i], other.words[i]) != 0)
			return true;
	}
	return false;
}

void WordList::Clear() {
	if (words) {
		delete []list;
		delete []words;
	}
	words = 0;
	list = 0;
	len = 0;
}

extern "C" int cmpString(const void *a1, const void *a2) {
	// Can't work out the correct incantation to use modern casts here
	return strcmp(*(char **)(a1), *(char **)(a2));
}

static void SortWordList(char **words, unsigned int len) {
	qsort(reinterpret_cast<void *>(words), len, sizeof(*words),
	      cmpString);
}

void WordList::Set(const char *s) {
	Clear();
	list = new char[strlen(s) + 1];
	strcpy(list, s);
	words = ArrayFromWordList(list, &len, onlyLineEnds);
	SortWordList(words, len);
	for (unsigned int k = 0; k < (sizeof(starts) / sizeof(starts[0])); k++)
		starts[k] = -1;
	for (int l = len - 1; l >= 0; l--) {
		unsigned char indexChar = words[l][0];
		starts[indexChar] = l;
	}
}

/** Check whether a string is in the list.
 * List elements are either exact matches or prefixes.
 * Prefix elements start with '^' and match all strings that start with the rest of the element
 * so '^GTK_' matches 'GTK_X', 'GTK_MAJOR_VERSION', and 'GTK_'.
 */
bool WordList::InList(const char *s) const {
	if (0 == words)
		return false;
	unsigned char firstChar = s[0];
	int j = starts[firstChar];
	if (j >= 0) {
		while ((unsigned char)words[j][0] == firstChar) {
			if (s[1] == words[j][1]) {
				const char *a = words[j] + 1;
				const char *b = s + 1;
				while (*a && *a == *b) {
					a++;
					b++;
				}
				if (!*a && !*b)
					return true;
			}
			j++;
		}
	}
	j = starts['^'];
	if (j >= 0) {
		while (words[j][0] == '^') {
			const char *a = words[j] + 1;
			const char *b = s;
			while (*a && *a == *b) {
				a++;
				b++;
			}
			if (!*a)
				return true;
			j++;
		}
	}
	return false;
}

/** similar to InList, but word s can be a substring of keyword.
 * eg. the keyword define is defined as def~ine. This means the word must start
 * with def to be a keyword, but also defi, defin and define are valid.
 * The marker is ~ in this case.
 */
bool WordList::InListAbbreviated(const char *s, const char marker) const {
	if (0 == words)
		return false;
	unsigned char firstChar = s[0];
	int j = starts[firstChar];
	if (j >= 0) {
		while (words[j][0] == firstChar) {
			bool isSubword = false;
			int start = 1;
			if (words[j][1] == marker) {
				isSubword = true;
				start++;
			}
			if (s[1] == words[j][start]) {
				const char *a = words[j] + start;
				const char *b = s + 1;
				while (*a && *a == *b) {
					a++;
					if (*a == marker) {
						isSubword = true;
						a++;
					}
					b++;
				}
				if ((!*a || isSubword) && !*b)
					return true;
			}
			j++;
		}
	}
	j = starts['^'];
	if (j >= 0) {
		while (words[j][0] == '^') {
			const char *a = words[j] + 1;
			const char *b = s;
			while (*a && *a == *b) {
				a++;
				b++;
			}
			if (!*a)
				return true;
			j++;
		}
	}
	return false;
}
<commit_msg>Switch to STL sort algorithm on MSVC. Feature #3376826.<commit_after>// Scintilla source code edit control
/** @file KeyWords.cxx
 ** Colourise for particular languages.
 **/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include <algorithm>

#include "WordList.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

/**
 * Creates an array that points into each word in the string and puts \0 terminators
 * after each word.
 */
static char **ArrayFromWordList(char *wordlist, int *len, bool onlyLineEnds = false) {
	int prev = '\n';
	int words = 0;
	// For rapid determination of whether a character is a separator, build
	// a look up table.
	bool wordSeparator[256];
	for (int i=0; i<256; i++) {
		wordSeparator[i] = false;
	}
	wordSeparator['\r'] = true;
	wordSeparator['\n'] = true;
	if (!onlyLineEnds) {
		wordSeparator[' '] = true;
		wordSeparator['\t'] = true;
	}
	for (int j = 0; wordlist[j]; j++) {
		int curr = static_cast<unsigned char>(wordlist[j]);
		if (!wordSeparator[curr] && wordSeparator[prev])
			words++;
		prev = curr;
	}
	char **keywords = new char *[words + 1];
	if (keywords) {
		words = 0;
		prev = '\0';
		size_t slen = strlen(wordlist);
		for (size_t k = 0; k < slen; k++) {
			if (!wordSeparator[static_cast<unsigned char>(wordlist[k])]) {
				if (!prev) {
					keywords[words] = &wordlist[k];
					words++;
				}
			} else {
				wordlist[k] = '\0';
			}
			prev = wordlist[k];
		}
		keywords[words] = &wordlist[slen];
		*len = words;
	} else {
		*len = 0;
	}
	return keywords;
}

bool WordList::operator!=(const WordList &other) const {
	if (len != other.len)
		return true;
	for (int i=0; i<len; i++) {
		if (strcmp(words[i], other.words[i]) != 0)
			return true;
	}
	return false;
}

void WordList::Clear() {
	if (words) {
		delete []list;
		delete []words;
	}
	words = 0;
	list = 0;
	len = 0;
}

#ifdef _MSC_VER

static bool cmpWords(const char *a, const char *b) {
	return strcmp(a, b) == -1;
}

#else

static int cmpWords(const void *a, const void *b) {
	return strcmp(*static_cast<const char * const *>(a), *static_cast<const char * const *>(b));
}

static void SortWordList(char **words, unsigned int len) {
	qsort(reinterpret_cast<void *>(words), len, sizeof(*words), cmpWords);
}

#endif

void WordList::Set(const char *s) {
	Clear();
	list = new char[strlen(s) + 1];
	strcpy(list, s);
	words = ArrayFromWordList(list, &len, onlyLineEnds);
#ifdef _MSC_VER
	std::sort(words, words + len, cmpWords);
#else
	SortWordList(words, len);
#endif
	for (unsigned int k = 0; k < (sizeof(starts) / sizeof(starts[0])); k++)
		starts[k] = -1;
	for (int l = len - 1; l >= 0; l--) {
		unsigned char indexChar = words[l][0];
		starts[indexChar] = l;
	}
}

/** Check whether a string is in the list.
 * List elements are either exact matches or prefixes.
 * Prefix elements start with '^' and match all strings that start with the rest of the element
 * so '^GTK_' matches 'GTK_X', 'GTK_MAJOR_VERSION', and 'GTK_'.
 */
bool WordList::InList(const char *s) const {
	if (0 == words)
		return false;
	unsigned char firstChar = s[0];
	int j = starts[firstChar];
	if (j >= 0) {
		while (static_cast<unsigned char>(words[j][0]) == firstChar) {
			if (s[1] == words[j][1]) {
				const char *a = words[j] + 1;
				const char *b = s + 1;
				while (*a && *a == *b) {
					a++;
					b++;
				}
				if (!*a && !*b)
					return true;
			}
			j++;
		}
	}
	j = starts['^'];
	if (j >= 0) {
		while (words[j][0] == '^') {
			const char *a = words[j] + 1;
			const char *b = s;
			while (*a && *a == *b) {
				a++;
				b++;
			}
			if (!*a)
				return true;
			j++;
		}
	}
	return false;
}

/** similar to InList, but word s can be a substring of keyword.
 * eg. the keyword define is defined as def~ine. This means the word must start
 * with def to be a keyword, but also defi, defin and define are valid.
 * The marker is ~ in this case.
 */
bool WordList::InListAbbreviated(const char *s, const char marker) const {
	if (0 == words)
		return false;
	unsigned char firstChar = s[0];
	int j = starts[firstChar];
	if (j >= 0) {
		while (static_cast<unsigned char>(words[j][0]) == firstChar) {
			bool isSubword = false;
			int start = 1;
			if (words[j][1] == marker) {
				isSubword = true;
				start++;
			}
			if (s[1] == words[j][start]) {
				const char *a = words[j] + start;
				const char *b = s + 1;
				while (*a && *a == *b) {
					a++;
					if (*a == marker) {
						isSubword = true;
						a++;
					}
					b++;
				}
				if ((!*a || isSubword) && !*b)
					return true;
			}
			j++;
		}
	}
	j = starts['^'];
	if (j >= 0) {
		while (words[j][0] == '^') {
			const char *a = words[j] + 1;
			const char *b = s;
			while (*a && *a == *b) {
				a++;
				b++;
			}
			if (!*a)
				return true;
			j++;
		}
	}
	return false;
}
<|endoftext|>


<commit_before>// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.

#include <QPainter>
#include <QGraphicsScene>
#include "StaffGraphicsItem.h"
#include "NoteGraphicsItem.h"
#include "Utils/Utils.h"

const int staffExtraWidth = 100;
const int noteHorizontalInterval = 40;
const int ledgerInterval = 20;
const int octaveHeight = ledgerInterval * 3;
const int extraLedgerWidth = 30;

StaffGraphicsItem::StaffGraphicsItem(QGraphicsItem *parent)
    : QGraphicsItem(parent)
{
    contentMargins_ = QMargins(10, 10, 10, 10);
}

void StaffGraphicsItem::setOctaveRange(int fromOctave, int toOctave)
{
    if (fromOctave_ != fromOctave || toOctave_ != toOctave)
        prepareGeometryChange();

    fromOctave_ = fromOctave;
    toOctave_ = toOctave;
}

bool StaffGraphicsItem::showNoteNames() const
{
    return showNoteNames_;
}

void StaffGraphicsItem::setShowNoteNames(bool showNoteNames)
{
    showNoteNames_ = showNoteNames;
}

void StaffGraphicsItem::addNote(int queueIndex, const Note &note, int group)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return;
    if (fromOctave_ > note.octave())
        return;
    if (toOctave_ < note.octave())
        return;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    Notes &notes = noteGroups[group];
    Notes::iterator i = notes.find(note);
    if (i != notes.end())
        return;
    NoteGraphicsItem *noteItem = new NoteGraphicsItem;
    notes[note] = noteItem;
    noteItem->setNote(note);
    noteItem->setParentItem(this);
    updateNotePositions();
}

bool StaffGraphicsItem::hasNote(int queueIndex, const Note &note, int group)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return false;
    if (fromOctave_ > note.octave())
        return false;
    if (toOctave_ < note.octave())
        return false;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    Notes &notes = noteGroups[group];
    Notes::iterator i = notes.find(note);
    if (i == notes.end())
        return false;
    return true;
}

bool StaffGraphicsItem::hasNote(int queueIndex, const Note &note)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return false;
    if (fromOctave_ > note.octave())
        return false;
    if (toOctave_ < note.octave())
        return false;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    foreach (const Notes &notes, noteGroups) {
        Notes::const_iterator i = notes.find(note);
        if (i != notes.end())
            return true;
    }
    return false;
}

void StaffGraphicsItem::queuePop()
{
    if (noteGroupsQueue_.isEmpty())
        return;
    NoteGroups &noteGroups = noteGroupsQueue_[0];
    foreach (const Notes &notes, noteGroups.values()) {
        foreach (NoteGraphicsItem *noteItem, notes.values()) {
            scene()->removeItem(noteItem);
        }
    }
    noteGroupsQueue_.remove(0);
}

int StaffGraphicsItem::queueLength()
{
    return noteGroupsQueue_.size();
}

void StaffGraphicsItem::queuePushNote(const Note &note, int group)
{
    int queueIndex = noteGroupsQueue_.size();
    noteGroupsQueue_.resize(queueIndex + 1);
    addNote(queueIndex, note, group);
    prepareGeometryChange();
}

void StaffGraphicsItem::removeNote(int queueIndex, const Note &note, int group)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    Notes &notes = noteGroups[group];
    Notes::iterator i = notes.find(note);
    if (i == notes.end())
        return;
    NoteGraphicsItem *noteItem = i.value();
    notes.erase(i);
    scene()->removeItem(noteItem);
}

void StaffGraphicsItem::removeAllNotes()
{
    foreach (QGraphicsItem *item, childItems()) {
        NoteGraphicsItem *noteItem = dynamic_cast<NoteGraphicsItem *>(item);
        if (!noteItem)
            continue;
        scene()->removeItem(noteItem);
    }
    noteGroupsQueue_.clear();
}

QRectF StaffGraphicsItem::boundingRect() const
{
    QSize size;
    size.setWidth(notesAreaWidth() + staffExtraWidth);
    int octaveCount = toOctave_ - fromOctave_ + 1;
    size.setHeight(octaveCount * ledgerInterval * 3);
    return QRectF(-size.width() / 2, -size.height() / 2,
                  size.width(), size.height()).marginsAdded(contentMargins_);
}

void StaffGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    QRectF rect = boundingRect();
    int leftX = rect.x() + contentMargins_.left();
    int rightX = rect.x() + rect.width() - contentMargins_.right();
    int startY = rect.y() + contentMargins_.top() + ledgerInterval;
    int atY = startY;
    painter->save();
    painter->setPen(Qt::black);

    for (int octave = fromOctave_; octave <= toOctave_; ++octave) {
        for (int ledger = 0; ledger < 3; ++ledger) {
            if (ledger < 2) {
                painter->drawLine(leftX,
                                  atY,
                                  rightX,
                                  atY);
            } //else {
//                painter->drawLine(rect.center().x() - 20,
//                                  atY,
//                                  rect.center().x() + 20,
//                                  atY);
//            }
            atY += ledgerInterval;
        }
    }
    painter->drawLine(leftX,
                      startY,
                      leftX,
                      atY - ledgerInterval * 2);
    painter->drawLine(rightX,
                      startY,
                      rightX,
                      atY - ledgerInterval * 2);

    int len = queueLength();
    int atX = rect.center().x() - notesAreaWidth() / 2;
    for (int queueIndex = 0; queueIndex < len; ++queueIndex) {
        atY = startY - 3 * ledgerInterval;
        for (int octave = toOctave_ + 1; octave >= fromOctave_; --octave) {
            atY += 2 * ledgerInterval;
            Note noteCis(Note::Pitch::Cis, octave);
            Note noteC(Note::Pitch::C, octave);
            Note noteB(Note::Pitch::B, octave - 1);
            if (hasNote(queueIndex, noteCis) ||
                    hasNote(queueIndex, noteC) ||
                    hasNote(queueIndex, noteB)) {
                painter->drawLine(atX - extraLedgerWidth / 2,
                                  atY,
                                  atX + extraLedgerWidth / 2,
                                  atY);
            }
            atY += ledgerInterval;
        }
        atX += noteHorizontalInterval;
    }

    painter->restore();
}

int StaffGraphicsItem::notesAreaWidth() const
{
    int horizontalIntervalCount = (int)noteGroupsQueue_.size() - 1;
    if (horizontalIntervalCount < 0)
        horizontalIntervalCount = 0;
    return noteHorizontalInterval * horizontalIntervalCount;
}

void StaffGraphicsItem::updateNotePositions()
{
    QRectF rect = boundingRect();

    int octaveCount = toOctave_ - fromOctave_ + 1;

    int len = queueLength();
    int atX = rect.center().x() - notesAreaWidth() / 2;
    for (int i = 0; i < len; ++i) {
        NoteGroups &noteGroups = noteGroupsQueue_[i];
        foreach (const Notes &notes, noteGroups.values()) {
            foreach (NoteGraphicsItem *noteItem, notes.values()) {
                Note note = noteItem->note();
                int spacePerNote = octaveHeight / 12;
                int octaveIndex = octaveCount - (note.octave() - fromOctave_) - 1;
                int bottomY = rect.y() + contentMargins_.top() +
                        (octaveIndex + 1) * octaveHeight;
                int atY = bottomY - spacePerNote * (int)note.pitch();
                noteItem->setPos(atX, atY);
            }
        }
        atX += noteHorizontalInterval;
    }
}
<commit_msg>prepareGeometryChanged minor fix<commit_after>// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.

#include <QPainter>
#include <QGraphicsScene>
#include "StaffGraphicsItem.h"
#include "NoteGraphicsItem.h"
#include "Utils/Utils.h"

const int staffExtraWidth = 100;
const int noteHorizontalInterval = 40;
const int ledgerInterval = 20;
const int octaveHeight = ledgerInterval * 3;
const int extraLedgerWidth = 30;

StaffGraphicsItem::StaffGraphicsItem(QGraphicsItem *parent)
    : QGraphicsItem(parent)
{
    contentMargins_ = QMargins(10, 10, 10, 10);
}

void StaffGraphicsItem::setOctaveRange(int fromOctave, int toOctave)
{
    if (fromOctave_ != fromOctave || toOctave_ != toOctave)
        prepareGeometryChange();

    fromOctave_ = fromOctave;
    toOctave_ = toOctave;
}

bool StaffGraphicsItem::showNoteNames() const
{
    return showNoteNames_;
}

void StaffGraphicsItem::setShowNoteNames(bool showNoteNames)
{
    showNoteNames_ = showNoteNames;
}

void StaffGraphicsItem::addNote(int queueIndex, const Note &note, int group)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return;
    if (fromOctave_ > note.octave())
        return;
    if (toOctave_ < note.octave())
        return;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    Notes &notes = noteGroups[group];
    Notes::iterator i = notes.find(note);
    if (i != notes.end())
        return;
    NoteGraphicsItem *noteItem = new NoteGraphicsItem;
    notes[note] = noteItem;
    noteItem->setNote(note);
    noteItem->setParentItem(this);
    updateNotePositions();
}

bool StaffGraphicsItem::hasNote(int queueIndex, const Note &note, int group)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return false;
    if (fromOctave_ > note.octave())
        return false;
    if (toOctave_ < note.octave())
        return false;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    Notes &notes = noteGroups[group];
    Notes::iterator i = notes.find(note);
    if (i == notes.end())
        return false;
    return true;
}

bool StaffGraphicsItem::hasNote(int queueIndex, const Note &note)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return false;
    if (fromOctave_ > note.octave())
        return false;
    if (toOctave_ < note.octave())
        return false;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    foreach (const Notes &notes, noteGroups) {
        Notes::const_iterator i = notes.find(note);
        if (i != notes.end())
            return true;
    }
    return false;
}

void StaffGraphicsItem::queuePop()
{
    if (noteGroupsQueue_.isEmpty())
        return;
    NoteGroups &noteGroups = noteGroupsQueue_[0];
    foreach (const Notes &notes, noteGroups.values()) {
        foreach (NoteGraphicsItem *noteItem, notes.values()) {
            scene()->removeItem(noteItem);
        }
    }
    noteGroupsQueue_.remove(0);
}

int StaffGraphicsItem::queueLength()
{
    return noteGroupsQueue_.size();
}

void StaffGraphicsItem::queuePushNote(const Note &note, int group)
{
    prepareGeometryChange();
    int queueIndex = noteGroupsQueue_.size();
    noteGroupsQueue_.resize(queueIndex + 1);
    addNote(queueIndex, note, group);
}

void StaffGraphicsItem::removeNote(int queueIndex, const Note &note, int group)
{
    if (queueIndex < 0 || queueIndex >= noteGroupsQueue_.size())
        return;
    NoteGroups &noteGroups = noteGroupsQueue_[queueIndex];
    Notes &notes = noteGroups[group];
    Notes::iterator i = notes.find(note);
    if (i == notes.end())
        return;
    NoteGraphicsItem *noteItem = i.value();
    notes.erase(i);
    scene()->removeItem(noteItem);
}

void StaffGraphicsItem::removeAllNotes()
{
    foreach (QGraphicsItem *item, childItems()) {
        NoteGraphicsItem *noteItem = dynamic_cast<NoteGraphicsItem *>(item);
        if (!noteItem)
            continue;
        scene()->removeItem(noteItem);
    }
    noteGroupsQueue_.clear();
}

QRectF StaffGraphicsItem::boundingRect() const
{
    QSize size;
    size.setWidth(notesAreaWidth() + staffExtraWidth);
    int octaveCount = toOctave_ - fromOctave_ + 1;
    size.setHeight(octaveCount * ledgerInterval * 3);
    return QRectF(-size.width() / 2, -size.height() / 2,
                  size.width(), size.height()).marginsAdded(contentMargins_);
}

void StaffGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    QRectF rect = boundingRect();
    int leftX = rect.x() + contentMargins_.left();
    int rightX = rect.x() + rect.width() - contentMargins_.right();
    int startY = rect.y() + contentMargins_.top() + ledgerInterval;
    int atY = startY;
    painter->save();
    painter->setPen(Qt::black);

    for (int octave = fromOctave_; octave <= toOctave_; ++octave) {
        for (int ledger = 0; ledger < 3; ++ledger) {
            if (ledger < 2) {
                painter->drawLine(leftX,
                                  atY,
                                  rightX,
                                  atY);
            } //else {
//                painter->drawLine(rect.center().x() - 20,
//                                  atY,
//                                  rect.center().x() + 20,
//                                  atY);
//            }
            atY += ledgerInterval;
        }
    }
    painter->drawLine(leftX,
                      startY,
                      leftX,
                      atY - ledgerInterval * 2);
    painter->drawLine(rightX,
                      startY,
                      rightX,
                      atY - ledgerInterval * 2);

    int len = queueLength();
    int atX = rect.center().x() - notesAreaWidth() / 2;
    for (int queueIndex = 0; queueIndex < len; ++queueIndex) {
        atY = startY - 3 * ledgerInterval;
        for (int octave = toOctave_ + 1; octave >= fromOctave_; --octave) {
            atY += 2 * ledgerInterval;
            Note noteCis(Note::Pitch::Cis, octave);
            Note noteC(Note::Pitch::C, octave);
            Note noteB(Note::Pitch::B, octave - 1);
            if (hasNote(queueIndex, noteCis) ||
                    hasNote(queueIndex, noteC) ||
                    hasNote(queueIndex, noteB)) {
                painter->drawLine(atX - extraLedgerWidth / 2,
                                  atY,
                                  atX + extraLedgerWidth / 2,
                                  atY);
            }
            atY += ledgerInterval;
        }
        atX += noteHorizontalInterval;
    }

    painter->restore();
}

int StaffGraphicsItem::notesAreaWidth() const
{
    int horizontalIntervalCount = (int)noteGroupsQueue_.size() - 1;
    if (horizontalIntervalCount < 0)
        horizontalIntervalCount = 0;
    return noteHorizontalInterval * horizontalIntervalCount;
}

void StaffGraphicsItem::updateNotePositions()
{
    QRectF rect = boundingRect();

    int octaveCount = toOctave_ - fromOctave_ + 1;

    int len = queueLength();
    int atX = rect.center().x() - notesAreaWidth() / 2;
    for (int i = 0; i < len; ++i) {
        NoteGroups &noteGroups = noteGroupsQueue_[i];
        foreach (const Notes &notes, noteGroups.values()) {
            foreach (NoteGraphicsItem *noteItem, notes.values()) {
                Note note = noteItem->note();
                int spacePerNote = octaveHeight / 12;
                int octaveIndex = octaveCount - (note.octave() - fromOctave_) - 1;
                int bottomY = rect.y() + contentMargins_.top() +
                        (octaveIndex + 1) * octaveHeight;
                int atY = bottomY - spacePerNote * (int)note.pitch();
                noteItem->setPos(atX, atY);
            }
        }
        atX += noteHorizontalInterval;
    }
}
<|endoftext|>


<commit_before>// $Id$
/*
 * Drawing macro for reading the THnSparse output of the
 * HLT/QA/tasks/AliAnalysisTaskHLTCentralBarrel.cxx task.
 *
 * The cuts are user defined as arguments of the function.
 * The input file contains information about the run number
 * and date that will appear in the canvas title.
 *
 * The cuts are turned into strings and incorporated in the
 * name of the output file, which contains canvases with event
 * and track properties for HLT and offline.
 *
 * Since the run information is available, there will be a new
 * folder created and the canvas ROOT files will be saved in there.
 *
 * @ingroup alihlt_qa
 * @author Kalliopi.Kanaki@ift.uib.no
 */

void drawTHnSparse( TString inputFile,
            	    double minEta=-2,   double maxEta=2,
	    	    int minTrackMult=0, int maxTrackMult=20000,
            	    double minPt=0,     double maxPt=200,
	    	    double minDCAr=-80, double maxDCAr=80,
	    	    double minDCAz=-80, double maxDCAz=80,
	    	    int minTPCclus=0,   int maxTPCclus=200,
	    	    int minITSclus=1,   int maxITSclus=6,
		    int vertexStatus=2
            	  )
{
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetOptStat(10);
  TH1::AddDirectory(kFALSE);

  TFile *file = TFile::Open(inputFile);
  if(!file){
    printf("Error: No file %s in folder.\n", inputFile);
    return;
  }

  TList *list = static_cast<TList*>(file->Get("esd_thnsparse"));
  if(!list){
    printf("Error: No List contained in file %s.\n", inputFile);
    return;
  }

  THnSparseF *heventHLT = (THnSparse*)list->FindObject("fEventHLT");
  if(!heventHLT){
      printf("Error: There is no HLT THnSparse object in file %s\n", inputFile);
  }
  THnSparseF *heventOFF = (THnSparse*)list->FindObject("fEventOFF");
  if(!heventOFF){
      printf("Error: There is no OFF THnSparse object in file %s\n", inputFile);
  }
  THnSparseF *htrackHLT = (THnSparse*)list->FindObject("fTrackHLT");
  if(!htrackHLT){
      printf("Error: No HLT THnSparse object found\n");
      return;
  }
  THnSparseF *htrackOFF = (THnSparse*)list->FindObject("fTrackOFF");
  if(!htrackOFF){
      printf("Error: No OFF THnSparse object found\n");
      return;
  }

  TText *hText = list->FindObject("text");
  if(!hText) printf("No hText\n");

  TString t = "event properties for ";
  t+=hText->GetTitle();

  TCanvas *can0 = new TCanvas("can0",t,900,600);
  can0->Divide(3,2);
  plotEventQuantities(can0,heventOFF,heventHLT,hText);

  TCanvas *can1 = new TCanvas("can1","track properties",1100,900);
  can1->Divide(4,3);
  plotTrackQuantities(can1, htrackOFF, htrackHLT, hText,
                      minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult, vertexStatus);

  TCanvas *can2 = new TCanvas("can2","2-D HLT track correlations",1200,800);
  can2->Divide(4,2);
  plot2D(can2, htrackHLT, minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult);

  TCanvas *can3 = new TCanvas("can3","2-D OFF track correlations",1200,800);
  can3->Divide(4,2);
  plot2D(can3, htrackOFF, minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult);

  TString folder = hText->GetTitle();
  folder.ReplaceAll(" ","");
  folder.Remove(0,3);
  folder.Remove(6,15);

  gSystem->Exec("mkdir "+folder);
  can0->SaveAs(folder+"/event_properties.root");

  stringstream sMinEta, sMaxEta;
  sMinEta << minEta; sMaxEta << maxEta;

  stringstream sMinTM, sMaxTM;
  sMinTM << minTrackMult; sMaxTM << maxTrackMult;

  stringstream sMinPt, sMaxPt;
  sMinPt << minPt; sMaxPt << maxPt;

  stringstream sMinDCAr, sMaxDCAr;
  sMinDCAr << minDCAr; sMaxDCAr << maxDCAr;

  stringstream sMinDCAz, sMaxDCAz;
  sMinDCAz << minDCAz; sMaxDCAz << maxDCAz;

  stringstream sMinTPCclus, sMaxTPCclus;
  sMinTPCclus << minTPCclus; sMaxTPCclus << maxTPCclus;

  stringstream sMinITSclus, sMaxITSclus;
  sMinITSclus << minITSclus; sMaxITSclus << maxITSclus;

  stringstream sVS; sVS << vertexStatus;

  TString trackName = "track_properties_";
  trackName += "eta"+sMinEta.str()+"_"+sMaxEta.str()+"_";
  trackName += "Pt"+sMinPt.str()+"_"+sMaxPt.str()+"_";
  trackName += "TM"+sMinTM.str()+"_"+sMaxTM.str()+"_";
  trackName += "DCAr"+sMinDCAr.str()+"_"+sMaxDCAr.str()+"_";
  trackName += "DCAz"+sMinDCAz.str()+"_"+sMaxDCAz.str()+"_";
  trackName += "TPCclus"+sMinTPCclus.str()+"_"+sMaxTPCclus.str()+"_";
  trackName += "ITSclus"+sMinITSclus.str()+"_"+sMaxITSclus.str()+"_";
  if(vertexStatus==2){
     trackName.Chop(); trackName += ".root";
  }
  else {
     trackName += "VS"+sVS.str();
     trackName += ".root";
  }
  can1->SaveAs(folder+"/"+trackName);

  can2->SaveAs(folder+"/HLT_2D_track_correlations.root");
  can3->SaveAs(folder+"/OFF_2D_track_correlations.root");

  return;
}

void printStats(TH1D *hlt, TH1D *off){
  gPad->Update();
  TPaveStats *st1 = (TPaveStats*)hlt->FindObject("stats");
  st1->SetLineColor(0);

  gPad->Update();
  TPaveStats *st2 = (TPaveStats*)off->FindObject("stats");
  st2->SetY2NDC(st1->GetY1NDC()-0.05);
  st2->SetY1NDC(st2->GetY2NDC()-TMath::Abs(st1->GetY1NDC()-st1->GetY2NDC()));
  st2->SetLineColor(0);
  st2->SetTextColor(off->GetLineColor());
  st2->SetFillStyle(0);
  st2->Draw();
}

void defineYaxisMax(TH1D *hlt, TH1D *off){
  if(hlt->GetMaximum() > off->GetMaximum()) off->SetMaximum(1.1*hlt->GetMaximum());
  else hlt->SetMaximum(1.1*off->GetMaximum());
}

void printLegend(TLegend *l, TH1D *hlt, TH1D *off){
  l->SetFillColor(10);
  l->SetLineColor(10);
  l->AddEntry(hlt, "HLT", "l");
  l->AddEntry(off, "OFF", "l");
  l->Draw("same");
}

//====================== for 1D distributions ===============================//

void plotAid(TCanvas* can, THnSparse* hOFF, THnSparse* hHLT, TText* hText, TH1D *hlt, TH1D *off, TLegend *l, int size,
             double minEta,    double maxEta,
             double minPt,     double maxPt,
	     double minDCAr,   double maxDCAr,
	     double minDCAz,   double maxDCAz,
	     int minTPCclus,   int maxTPCclus,
	     int minITSclus,   int maxITSclus,
 	     int minTrackMult, int maxTrackMult,
	     int VS
           )
{
   hHLT->GetAxis(0)->SetRangeUser(minPt,maxPt);
   hHLT->GetAxis(1)->SetRangeUser(minTPCclus,maxTPCclus);
   hHLT->GetAxis(3)->SetRangeUser(minEta, maxEta);
   hHLT->GetAxis(5)->SetRangeUser(minDCAr, maxDCAr);
   hHLT->GetAxis(6)->SetRangeUser(minDCAz, maxDCAz);
   hHLT->GetAxis(10)->SetRangeUser(minITSclus, maxITSclus);
   hHLT->GetAxis(11)->SetRangeUser(minTrackMult, maxTrackMult);
   if(VS!=2) hHLT->GetAxis(12)->SetRangeUser(VS,VS);

   hOFF->GetAxis(0)->SetRangeUser(minPt,maxPt);
   hOFF->GetAxis(1)->SetRangeUser(minTPCclus,maxTPCclus);
   hOFF->GetAxis(3)->SetRangeUser(minEta, maxEta);
   hOFF->GetAxis(5)->SetRangeUser(minDCAr, maxDCAr);
   hOFF->GetAxis(6)->SetRangeUser(minDCAz, maxDCAz);
   hOFF->GetAxis(10)->SetRangeUser(minITSclus, maxITSclus);
   hOFF->GetAxis(11)->SetRangeUser(minTrackMult, maxTrackMult);
   if(VS!=2) hOFF->GetAxis(12)->SetRangeUser(VS,VS);

   for(int i=0; i<size; i++){

      hlt = hHLT->Projection(i);
      off = hOFF->Projection(i);
      hlt->SetTitle(hHLT->Projection(i)->GetTitle());
      defineYaxisMax(hlt, off);
      off->SetLineColor(2);

      can->cd(i+1);
      hlt->Draw();
      off->Draw("sames");
      printStats(hlt, off);
   }
   printLegend(l,hlt,off);
}

//====================== for 2D distributions ===============================//

void plot2D(TCanvas* can, THnSparse* h,
            double minEta,    double maxEta,
            double minPt,     double maxPt,
	    double minDCAr,   double maxDCAr,
	    double minDCAz,   double maxDCAz,
	    int minTPCclus,   int maxTPCclus,
	    int minITSclus,   int maxITSclus,
 	    int minTrackMult, int maxTrackMult
           )
{

  h->GetAxis(0)->SetRangeUser(minPt,maxPt);
  h->GetAxis(1)->SetRangeUser(minTPCclus,maxTPCclus);
  h->GetAxis(3)->SetRangeUser(minEta, maxEta);
  h->GetAxis(5)->SetRangeUser(minDCAr, maxDCAr);
  h->GetAxis(6)->SetRangeUser(minDCAz, maxDCAz);
  h->GetAxis(10)->SetRangeUser(minITSclus, maxITSclus);
  h->GetAxis(11)->SetRangeUser(minTrackMult, maxTrackMult);

  can->cd(1);
  h->Projection(1,0)->Draw("colz");
  can->cd(2);
  h->Projection(1,3)->Draw("colz");
  can->cd(3);
  h->Projection(1,5)->Draw("colz");
  can->cd(4);
  h->Projection(1,6)->Draw("colz");

  can->cd(5);
  h->Projection(6,0)->Draw("colz");
  can->cd(6);
  h->Projection(6,3)->Draw("colz");
  can->cd(7);
  h->Projection(3,0)->Draw("colz");
  can->cd(8);
  h->Projection(3,4)->Draw("colz");

}

void plotAid(TCanvas* can, THnSparse* hOFF, THnSparse* hHLT, TText* hText, TH1D *hlt, TH1D *off, TLegend *l, int size){

  for(int i=0; i<size; i++){
      hlt = hHLT->Projection(i);
      off = hOFF->Projection(i);
      hlt->SetTitle(hHLT->Projection(i)->GetTitle());
      defineYaxisMax(hlt, off);
      off->SetLineColor(2);

      can->cd(i+1);
      hlt->Draw();
      off->Draw("sames");
      printStats(hlt, off);
   }
   printLegend(l,hlt,off);
}

void plotEventQuantities(TCanvas* can, THnSparse* heventOFF, THnSparse* heventHLT, TText* hText){

  TH1D *hlt = NULL;
  TH1D *off = NULL;

  TLegend *leg1 = new TLegend(0.6,0.6,0.8,0.8);

  plotAid(can, heventOFF, heventHLT, hText, hlt, off, leg1, 6);
  return;
}

void plotTrackQuantities( TCanvas* can, THnSparse* htrackOFF, THnSparse* htrackHLT, TText* hText,
           	    	  double minEta,    double maxEta,
 	                  double minPt,     double maxPt,
	   	    	  double minDCAr,   double maxDCAr,
	   	    	  double minDCAz,   double maxDCAz,
	   	    	  int minTPCclus,   int maxTPCclus,
	   	    	  int minITSclus,   int maxITSclus,
	                  int minTrackMult, int maxTrackMult,
			  int VS
                        )
{
  TH1D *hlt = NULL;
  TH1D *off = NULL;

  TLegend *leg1 = new TLegend(0.6,0.6,0.8,0.8);
  plotAid(can, htrackOFF, htrackHLT, hText, hlt, off, leg1, 11,
          minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult, VS);
return;
}
<commit_msg>- correct initialization value for the number of ITS clusters per track<commit_after>// $Id$
/*
 * Drawing macro for reading the THnSparse output of the
 * HLT/QA/tasks/AliAnalysisTaskHLTCentralBarrel.cxx task.
 *
 * The cuts are user defined as arguments of the function.
 * The input file contains information about the run number
 * and date that will appear in the canvas title.
 *
 * The cuts are turned into strings and incorporated in the
 * name of the output file, which contains canvases with event
 * and track properties for HLT and offline.
 *
 * Since the run information is available, there will be a new
 * folder created and the canvas ROOT files will be saved in there.
 *
 * @ingroup alihlt_qa
 * @author Kalliopi.Kanaki@ift.uib.no
 */

void drawTHnSparse( TString inputFile,
            	    double minEta=-2,   double maxEta=2,
	    	    int minTrackMult=0, int maxTrackMult=20000,
            	    double minPt=0,     double maxPt=200,
	    	    double minDCAr=-80, double maxDCAr=80,
	    	    double minDCAz=-80, double maxDCAz=80,
	    	    int minTPCclus=0,   int maxTPCclus=200,
	    	    int minITSclus=0,   int maxITSclus=6,
		    int vertexStatus=2
            	  )
{
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetOptStat(10);
  TH1::AddDirectory(kFALSE);

  TFile *file = TFile::Open(inputFile);
  if(!file){
    printf("Error: No file %s in folder.\n", inputFile);
    return;
  }

  TList *list = static_cast<TList*>(file->Get("esd_thnsparse"));
  if(!list){
    printf("Error: No List contained in file %s.\n", inputFile);
    return;
  }

  THnSparseF *heventHLT = (THnSparse*)list->FindObject("fEventHLT");
  if(!heventHLT){
      printf("Error: There is no HLT THnSparse object in file %s\n", inputFile);
  }
  THnSparseF *heventOFF = (THnSparse*)list->FindObject("fEventOFF");
  if(!heventOFF){
      printf("Error: There is no OFF THnSparse object in file %s\n", inputFile);
  }
  THnSparseF *htrackHLT = (THnSparse*)list->FindObject("fTrackHLT");
  if(!htrackHLT){
      printf("Error: No HLT THnSparse object found\n");
      return;
  }
  THnSparseF *htrackOFF = (THnSparse*)list->FindObject("fTrackOFF");
  if(!htrackOFF){
      printf("Error: No OFF THnSparse object found\n");
      return;
  }

  TText *hText = list->FindObject("text");
  if(!hText) printf("No hText\n");

  TString t = "event properties for ";
  t+=hText->GetTitle();

  TCanvas *can0 = new TCanvas("can0",t,900,600);
  can0->Divide(3,2);
  plotEventQuantities(can0,heventOFF,heventHLT,hText);

  TCanvas *can1 = new TCanvas("can1","track properties",1100,900);
  can1->Divide(4,3);
  plotTrackQuantities(can1, htrackOFF, htrackHLT, hText,
                      minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult, vertexStatus);

  TCanvas *can2 = new TCanvas("can2","2-D HLT track correlations",1200,800);
  can2->Divide(4,2);
  plot2D(can2, htrackHLT, minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult);

  TCanvas *can3 = new TCanvas("can3","2-D OFF track correlations",1200,800);
  can3->Divide(4,2);
  plot2D(can3, htrackOFF, minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult);

  TString folder = hText->GetTitle();
  folder.ReplaceAll(" ","");
  folder.Remove(0,3);
  folder.Remove(6,15);

  gSystem->Exec("mkdir "+folder);
  can0->SaveAs(folder+"/event_properties.root");

  stringstream sMinEta, sMaxEta;
  sMinEta << minEta; sMaxEta << maxEta;

  stringstream sMinTM, sMaxTM;
  sMinTM << minTrackMult; sMaxTM << maxTrackMult;

  stringstream sMinPt, sMaxPt;
  sMinPt << minPt; sMaxPt << maxPt;

  stringstream sMinDCAr, sMaxDCAr;
  sMinDCAr << minDCAr; sMaxDCAr << maxDCAr;

  stringstream sMinDCAz, sMaxDCAz;
  sMinDCAz << minDCAz; sMaxDCAz << maxDCAz;

  stringstream sMinTPCclus, sMaxTPCclus;
  sMinTPCclus << minTPCclus; sMaxTPCclus << maxTPCclus;

  stringstream sMinITSclus, sMaxITSclus;
  sMinITSclus << minITSclus; sMaxITSclus << maxITSclus;

  stringstream sVS; sVS << vertexStatus;

  TString trackName = "track_properties_";
  trackName += "eta"+sMinEta.str()+"_"+sMaxEta.str()+"_";
  trackName += "Pt"+sMinPt.str()+"_"+sMaxPt.str()+"_";
  trackName += "TM"+sMinTM.str()+"_"+sMaxTM.str()+"_";
  trackName += "DCAr"+sMinDCAr.str()+"_"+sMaxDCAr.str()+"_";
  trackName += "DCAz"+sMinDCAz.str()+"_"+sMaxDCAz.str()+"_";
  trackName += "TPCclus"+sMinTPCclus.str()+"_"+sMaxTPCclus.str()+"_";
  trackName += "ITSclus"+sMinITSclus.str()+"_"+sMaxITSclus.str()+"_";
  if(vertexStatus==2){
     trackName.Chop(); trackName += ".root";
  }
  else {
     trackName += "VS"+sVS.str();
     trackName += ".root";
  }
  can1->SaveAs(folder+"/"+trackName);

  can2->SaveAs(folder+"/HLT_2D_track_correlations.root");
  can3->SaveAs(folder+"/OFF_2D_track_correlations.root");

  return;
}

void printStats(TH1D *hlt, TH1D *off){
  gPad->Update();
  TPaveStats *st1 = (TPaveStats*)hlt->FindObject("stats");
  st1->SetLineColor(0);

  gPad->Update();
  TPaveStats *st2 = (TPaveStats*)off->FindObject("stats");
  st2->SetY2NDC(st1->GetY1NDC()-0.05);
  st2->SetY1NDC(st2->GetY2NDC()-TMath::Abs(st1->GetY1NDC()-st1->GetY2NDC()));
  st2->SetLineColor(0);
  st2->SetTextColor(off->GetLineColor());
  st2->SetFillStyle(0);
  st2->Draw();
}

void defineYaxisMax(TH1D *hlt, TH1D *off){
  if(hlt->GetMaximum() > off->GetMaximum()) off->SetMaximum(1.1*hlt->GetMaximum());
  else hlt->SetMaximum(1.1*off->GetMaximum());
}

void printLegend(TLegend *l, TH1D *hlt, TH1D *off){
  l->SetFillColor(10);
  l->SetLineColor(10);
  l->AddEntry(hlt, "HLT", "l");
  l->AddEntry(off, "OFF", "l");
  l->Draw("same");
}

//====================== for 1D distributions ===============================//

void plotAid(TCanvas* can, THnSparse* hOFF, THnSparse* hHLT, TText* hText, TH1D *hlt, TH1D *off, TLegend *l, int size,
             double minEta,    double maxEta,
             double minPt,     double maxPt,
	     double minDCAr,   double maxDCAr,
	     double minDCAz,   double maxDCAz,
	     int minTPCclus,   int maxTPCclus,
	     int minITSclus,   int maxITSclus,
 	     int minTrackMult, int maxTrackMult,
	     int VS
           )
{
   hHLT->GetAxis(0)->SetRangeUser(minPt,maxPt);
   hHLT->GetAxis(1)->SetRangeUser(minTPCclus,maxTPCclus);
   hHLT->GetAxis(3)->SetRangeUser(minEta, maxEta);
   hHLT->GetAxis(5)->SetRangeUser(minDCAr, maxDCAr);
   hHLT->GetAxis(6)->SetRangeUser(minDCAz, maxDCAz);
   hHLT->GetAxis(10)->SetRangeUser(minITSclus, maxITSclus);
   hHLT->GetAxis(11)->SetRangeUser(minTrackMult, maxTrackMult);
   if(VS!=2) hHLT->GetAxis(12)->SetRangeUser(VS,VS);

   hOFF->GetAxis(0)->SetRangeUser(minPt,maxPt);
   hOFF->GetAxis(1)->SetRangeUser(minTPCclus,maxTPCclus);
   hOFF->GetAxis(3)->SetRangeUser(minEta, maxEta);
   hOFF->GetAxis(5)->SetRangeUser(minDCAr, maxDCAr);
   hOFF->GetAxis(6)->SetRangeUser(minDCAz, maxDCAz);
   hOFF->GetAxis(10)->SetRangeUser(minITSclus, maxITSclus);
   hOFF->GetAxis(11)->SetRangeUser(minTrackMult, maxTrackMult);
   if(VS!=2) hOFF->GetAxis(12)->SetRangeUser(VS,VS);

   for(int i=0; i<size; i++){

      hlt = hHLT->Projection(i);
      off = hOFF->Projection(i);
      hlt->SetTitle(hHLT->Projection(i)->GetTitle());
      defineYaxisMax(hlt, off);
      off->SetLineColor(2);

      can->cd(i+1);
      hlt->Draw();
      off->Draw("sames");
      printStats(hlt, off);
   }
   printLegend(l,hlt,off);
}

//====================== for 2D distributions ===============================//

void plot2D(TCanvas* can, THnSparse* h,
            double minEta,    double maxEta,
            double minPt,     double maxPt,
	    double minDCAr,   double maxDCAr,
	    double minDCAz,   double maxDCAz,
	    int minTPCclus,   int maxTPCclus,
	    int minITSclus,   int maxITSclus,
 	    int minTrackMult, int maxTrackMult
           )
{

  h->GetAxis(0)->SetRangeUser(minPt,maxPt);
  h->GetAxis(1)->SetRangeUser(minTPCclus,maxTPCclus);
  h->GetAxis(3)->SetRangeUser(minEta, maxEta);
  h->GetAxis(5)->SetRangeUser(minDCAr, maxDCAr);
  h->GetAxis(6)->SetRangeUser(minDCAz, maxDCAz);
  h->GetAxis(10)->SetRangeUser(minITSclus, maxITSclus);
  h->GetAxis(11)->SetRangeUser(minTrackMult, maxTrackMult);

  can->cd(1);
  h->Projection(1,0)->Draw("colz");
  can->cd(2);
  h->Projection(1,3)->Draw("colz");
  can->cd(3);
  h->Projection(1,5)->Draw("colz");
  can->cd(4);
  h->Projection(1,6)->Draw("colz");

  can->cd(5);
  h->Projection(6,0)->Draw("colz");
  can->cd(6);
  h->Projection(6,3)->Draw("colz");
  can->cd(7);
  h->Projection(3,0)->Draw("colz");
  can->cd(8);
  h->Projection(3,4)->Draw("colz");

}

void plotAid(TCanvas* can, THnSparse* hOFF, THnSparse* hHLT, TText* hText, TH1D *hlt, TH1D *off, TLegend *l, int size){

  for(int i=0; i<size; i++){
      hlt = hHLT->Projection(i);
      off = hOFF->Projection(i);
      hlt->SetTitle(hHLT->Projection(i)->GetTitle());
      defineYaxisMax(hlt, off);
      off->SetLineColor(2);

      can->cd(i+1);
      hlt->Draw();
      off->Draw("sames");
      printStats(hlt, off);
   }
   printLegend(l,hlt,off);
}

void plotEventQuantities(TCanvas* can, THnSparse* heventOFF, THnSparse* heventHLT, TText* hText){

  TH1D *hlt = NULL;
  TH1D *off = NULL;

  TLegend *leg1 = new TLegend(0.6,0.6,0.8,0.8);

  plotAid(can, heventOFF, heventHLT, hText, hlt, off, leg1, 6);
  return;
}

void plotTrackQuantities( TCanvas* can, THnSparse* htrackOFF, THnSparse* htrackHLT, TText* hText,
           	    	  double minEta,    double maxEta,
 	                  double minPt,     double maxPt,
	   	    	  double minDCAr,   double maxDCAr,
	   	    	  double minDCAz,   double maxDCAz,
	   	    	  int minTPCclus,   int maxTPCclus,
	   	    	  int minITSclus,   int maxITSclus,
	                  int minTrackMult, int maxTrackMult,
			  int VS
                        )
{
  TH1D *hlt = NULL;
  TH1D *off = NULL;

  TLegend *leg1 = new TLegend(0.6,0.6,0.8,0.8);
  plotAid(can, htrackOFF, htrackHLT, hText, hlt, off, leg1, 11,
          minEta, maxEta, minPt, maxPt, minDCAr, maxDCAr, minDCAz, maxDCAz, minTPCclus, maxTPCclus, minITSclus, maxITSclus, minTrackMult, maxTrackMult, VS);
return;
}
<|endoftext|>


<commit_before>// Compose a volume from the moving image slices
// at each progressive optimisation step

// boost
#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"

// itk
#include "itkRGBPixel.h"
#include "itkVectorResampleImageFilter.h"

// my files
#include "Stack.hpp"
#include "StackInitializers.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"

namespace po = boost::program_options;
using namespace boost::filesystem;

// function declarations
po::variables_map parse_arguments(int argc, char *argv[]);
vector< string > directoryContents(const string& directory);

int main(int argc, char *argv[]) {
  po::variables_map vm = parse_arguments(argc, argv);

	// Process command line arguments
  Dirs::SetDataSet( vm["dataSet"].as<string>() );
  Dirs::SetOutputDirName( vm["outputDir"].as<string>() );
  bool LoRes = vm.count("LoRes");
  string transform = vm["transform"].as<string>();
  string transformDirectory = Dirs::IntermediateTransformsDir() + transform + "/";
  vector< string > basenames = vm.count("basename") ?
                               vector< string >(1, vm["basename"].as<string>()) :
                               directoryContents(transformDirectory);

  for(vector<string>::const_iterator basename = basenames.begin(); basename != basenames.end(); ++basename)
  {
    // get image paths
    string HiResPath = Dirs::SliceDir() + *basename + ".bmp";

    // Load transforms from files
    string stepsDirectory = transformDirectory +
                            *basename + "/";

    vector< string > steps = directoryContents(stepsDirectory);

    // initialise stack with correct spacings, sizes, transforms etc
    cout << "Building HiRes progress volume for " << *basename << "...";
    typedef itk::RGBPixel< unsigned char > PixelType;
    typedef Stack< PixelType, itk::VectorResampleImageFilter, itk::VectorLinearInterpolateImageFunction > StackType;
    StackType::SliceVectorType HiResImage(steps.size(), readImage< StackType::SliceType >(HiResPath));
    boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImage);
    HiResStack->SetBasenames(steps);
    HiResStack->SetDefaultPixelValue( 255 );

    // load transform at each iteration
    Load(*HiResStack, stepsDirectory);

    // move stack origins to ROI
    // itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation("whole_heart");
    // if(LoRes) StackTransforms::Translate(*LoResStack, translation);
    // if(HiRes) StackTransforms::Translate(*HiResStack, translation);

    // generate images
    HiResStack->updateVolumes();

    // Write bmps
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), stepsDirectory + "HiRes.mha");

    cout << "done." << endl;

    // generate LoRes volume for comparison
    if(LoRes)
    {
      cout << "Building LoRes comparison volume...";
      string LoResPath = Dirs::BlockDir() + *basename + ".bmp";
      StackType::SliceVectorType LoResImage = StackType::SliceVectorType(steps.size(), readImage< StackType::SliceType >(LoResPath) );
      boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImage);
      LoResStack->SetBasenames(vector< string >(steps.size(), *basename));
      // load LoRes transforms
      StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") );
      ApplyAdjustments( *LoResStack, Dirs::ConfigDir() + "LoRes_adjustments/");
      LoResStack->updateVolumes();
      writeImage< StackType::VolumeType >( LoResStack->GetVolume(), stepsDirectory + "LoRes.mha");
      cout << "done." << endl;
    }
  }
  return EXIT_SUCCESS;
}

po::variables_map parse_arguments(int argc, char *argv[])
{
  // Declare the supported options.
  po::options_description opts("Options");
  opts.add_options()
      ("help,h", "produce help message")
      ("dataSet", po::value<string>(), "which rat to use")
      ("outputDir", po::value<string>(), "directory to place results")
      ("transform", po::value<string>(), "Type of ITK transform that was optimised")
      ("basename", po::value<string>(), "the particular slice identifier e.g. 0196")
      ("LoRes,L", po::value<bool>()->zero_tokens(), "generate LoRes image")
  ;

  po::positional_options_description p;
  p.add("dataSet", 1)
   .add("outputDir", 1)
   .add("transform", 1);

  // parse command line
  po::variables_map vm;
	try
	{
  po::store(po::command_line_parser(argc, argv)
            .options(opts)
            .positional(p)
            .run(),
            vm);
	}
	catch (std::exception& e)
	{
	  cerr << "caught command-line parsing error" << endl;
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
  po::notify(vm);

  // if help is specified, or positional args aren't present
  if(vm.count("help") ||
    !vm.count("dataSet") ||
    !vm.count("outputDir") ||
    !vm.count("transform") )
  {
    cerr << "Usage: "
      << argv[0]
      << " [--dataSet=]RatX [--outputDir=]my_dir"
      << " [--transform=]CenteredRigid2DTransform "
      << " [Options]"
      << endl << endl;
    cerr << opts << "\n";
    exit(EXIT_FAILURE);
  }

  return vm;
}

vector< string > directoryContents(const string& directory)
{
  // retrieve and sort paths
  vector< path > contents;
  copy(directory_iterator(directory), directory_iterator(), back_inserter(contents));
  sort(contents.begin(), contents.end());

  //
  vector< string > contents_strings;
  for(vector< path >::const_iterator it = contents.begin(); it != contents.end(); ++it)
  {
    contents_strings.push_back(it->leaf());
  }
  return contents_strings;
}
<commit_msg>Output message.<commit_after>// Compose a volume from the moving image slices
// at each progressive optimisation step

// boost
#include "boost/filesystem.hpp"
#include "boost/program_options.hpp"

// itk
#include "itkRGBPixel.h"
#include "itkVectorResampleImageFilter.h"

// my files
#include "Stack.hpp"
#include "StackInitializers.hpp"
#include "StackIOHelpers.hpp"
#include "IOHelpers.hpp"

namespace po = boost::program_options;
using namespace boost::filesystem;

// function declarations
po::variables_map parse_arguments(int argc, char *argv[]);
vector< string > directoryContents(const string& directory);

int main(int argc, char *argv[]) {
  po::variables_map vm = parse_arguments(argc, argv);

	// Process command line arguments
  Dirs::SetDataSet( vm["dataSet"].as<string>() );
  Dirs::SetOutputDirName( vm["outputDir"].as<string>() );
  bool LoRes = vm.count("LoRes");
  string transform = vm["transform"].as<string>();
  string transformDirectory = Dirs::IntermediateTransformsDir() + transform + "/";
  vector< string > basenames = vm.count("basename") ?
                               vector< string >(1, vm["basename"].as<string>()) :
                               directoryContents(transformDirectory);

  for(vector<string>::const_iterator basename = basenames.begin(); basename != basenames.end(); ++basename)
  {
    // get image paths
    string HiResPath = Dirs::SliceDir() + *basename + ".bmp";

    // Load transforms from files
    string stepsDirectory = transformDirectory +
                            *basename + "/";

    vector< string > steps = directoryContents(stepsDirectory);

    // initialise stack with correct spacings, sizes, transforms etc
    cout << "Building " << *basename << " HiRes progress volume...";
    typedef itk::RGBPixel< unsigned char > PixelType;
    typedef Stack< PixelType, itk::VectorResampleImageFilter, itk::VectorLinearInterpolateImageFunction > StackType;
    StackType::SliceVectorType HiResImage(steps.size(), readImage< StackType::SliceType >(HiResPath));
    boost::shared_ptr< StackType > HiResStack = InitializeHiResStack<StackType>(HiResImage);
    HiResStack->SetBasenames(steps);
    HiResStack->SetDefaultPixelValue( 255 );

    // load transform at each iteration
    Load(*HiResStack, stepsDirectory);

    // move stack origins to ROI
    // itk::Vector< double, 2 > translation = StackTransforms::GetLoResTranslation(roi) - StackTransforms::GetLoResTranslation("whole_heart");
    // if(LoRes) StackTransforms::Translate(*LoResStack, translation);
    // if(HiRes) StackTransforms::Translate(*HiResStack, translation);

    // generate images
    HiResStack->updateVolumes();

    // Write bmps
    writeImage< StackType::VolumeType >( HiResStack->GetVolume(), stepsDirectory + "HiRes.mha");

    cout << "done." << endl;

    // generate LoRes volume for comparison
    if(LoRes)
    {
      cout << "Building " << *basename << " LoRes comparison volume...";
      string LoResPath = Dirs::BlockDir() + *basename + ".bmp";
      StackType::SliceVectorType LoResImage = StackType::SliceVectorType(steps.size(), readImage< StackType::SliceType >(LoResPath) );
      boost::shared_ptr< StackType > LoResStack = InitializeLoResStack<StackType>(LoResImage);
      LoResStack->SetBasenames(vector< string >(steps.size(), *basename));
      // load LoRes transforms
      StackTransforms::InitializeWithTranslation( *LoResStack, StackTransforms::GetLoResTranslation("whole_heart") );
      ApplyAdjustments( *LoResStack, Dirs::ConfigDir() + "LoRes_adjustments/");
      LoResStack->updateVolumes();
      writeImage< StackType::VolumeType >( LoResStack->GetVolume(), stepsDirectory + "LoRes.mha");
      cout << "done." << endl;
    }
  }
  return EXIT_SUCCESS;
}

po::variables_map parse_arguments(int argc, char *argv[])
{
  // Declare the supported options.
  po::options_description opts("Options");
  opts.add_options()
      ("help,h", "produce help message")
      ("dataSet", po::value<string>(), "which rat to use")
      ("outputDir", po::value<string>(), "directory to place results")
      ("transform", po::value<string>(), "Type of ITK transform that was optimised")
      ("basename", po::value<string>(), "the particular slice identifier e.g. 0196")
      ("LoRes,L", po::value<bool>()->zero_tokens(), "generate LoRes image")
  ;

  po::positional_options_description p;
  p.add("dataSet", 1)
   .add("outputDir", 1)
   .add("transform", 1);

  // parse command line
  po::variables_map vm;
	try
	{
  po::store(po::command_line_parser(argc, argv)
            .options(opts)
            .positional(p)
            .run(),
            vm);
	}
	catch (std::exception& e)
	{
	  cerr << "caught command-line parsing error" << endl;
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
  po::notify(vm);

  // if help is specified, or positional args aren't present
  if(vm.count("help") ||
    !vm.count("dataSet") ||
    !vm.count("outputDir") ||
    !vm.count("transform") )
  {
    cerr << "Usage: "
      << argv[0]
      << " [--dataSet=]RatX [--outputDir=]my_dir"
      << " [--transform=]CenteredRigid2DTransform "
      << " [Options]"
      << endl << endl;
    cerr << opts << "\n";
    exit(EXIT_FAILURE);
  }

  return vm;
}

vector< string > directoryContents(const string& directory)
{
  // retrieve and sort paths
  vector< path > contents;
  copy(directory_iterator(directory), directory_iterator(), back_inserter(contents));
  sort(contents.begin(), contents.end());

  //
  vector< string > contents_strings;
  for(vector< path >::const_iterator it = contents.begin(); it != contents.end(); ++it)
  {
    contents_strings.push_back(it->leaf());
  }
  return contents_strings;
}
<|endoftext|>