<commit_before>//
// File generated by c:\Devel\root_working\code\root.vc8\utils\src\rootcint_tmp.exe at Wed May 16 23:07:42 2007

// Do NOT change. Changes will be lost next time file is generated
//

#include "RConfig.h"
#if !defined(R__ACCESS_IN_SYMBOL)
//Break the privacy of classes -- Disabled for the moment
#define private public
#define protected public
#endif

// Since CINT ignores the std namespace, we need to do so in this file.
namespace std {} using namespace std;
#include "ManualTree2.h"

#include "TClass.h"
#include "TBuffer.h"
#include "TMemberInspector.h"
#include "TError.h"

#ifndef G__ROOT
#define G__ROOT
#endif

#include "RtypesImp.h"
#include "TIsAProxy.h"

// START OF SHADOWS

namespace ROOT {
   namespace Shadow {
   } // of namespace Shadow
} // of namespace ROOT
// END OF SHADOWS

/********************************************************
* tree/src/ManualTree2.cxx
* CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED
*          FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX().
*          CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE.
********************************************************/

#ifdef G__MEMTEST
#undef malloc
#undef free
#endif

extern "C" void G__cpp_reset_tagtableManualTree2();

extern "C" void G__set_cpp_environmentManualTree2() {
   G__add_compiledheader("TTree.h");
   G__cpp_reset_tagtableManualTree2();
}
#include <new>
extern "C" int G__cpp_dllrevManualTree2() { return(30051515); }

/*********************************************************
* Member function Interface Method
*********************************************************/

/* TTree */
#include "ManualTree2Body.h"

/* Setting up global function */

/*********************************************************
* Member function Stub
*********************************************************/

/*********************************************************
* Global function Stub
*********************************************************/

/*********************************************************
* Get size of pointer to member function
*********************************************************/
class G__Sizep2memfuncManualTree2 {
public:
   G__Sizep2memfuncManualTree2(): p(&G__Sizep2memfuncManualTree2::sizep2memfunc) {}
   size_t sizep2memfunc() { return(sizeof(p)); }
private:
   size_t (G__Sizep2memfuncManualTree2::*p)();
};

size_t G__get_sizep2memfuncManualTree2()
{
   G__Sizep2memfuncManualTree2 a;
   G__setsizep2memfunc((int)a.sizep2memfunc());
   return((size_t)a.sizep2memfunc());
}

/*********************************************************
* virtual base class offset calculation interface
*********************************************************/

/* Setting up class inheritance */

/*********************************************************
* Inheritance information setup/
*********************************************************/
extern "C" void G__cpp_setup_inheritanceManualTree2() {

   /* Setting up class inheritance */
}

/*********************************************************
* typedef information setup/
*********************************************************/
extern "C" void G__cpp_setup_typetableManualTree2() {

   /* Setting up typedef entry */
   G__search_typename2("Int_t",105,-1,0,-1);
   G__setnewtype(-1,"Signed integer 4 bytes (int)",0);
   G__search_typename2("Option_t",99,-1,256,-1);
   G__setnewtype(-1,"Option string (const char)",0);
   G__search_typename2("Long64_t",110,-1,0,-1);
   G__setnewtype(-1,"Portable signed long integer 8 bytes",0);
}

/*********************************************************
* Data Member information setup/
*********************************************************/

/* Setting up class,struct,union tag member variable */
extern "C" void G__cpp_setup_memvarManualTree2() {
}
/***********************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
***********************************************************/

/*********************************************************
* Member function information setup for each class
*********************************************************/
static void G__setup_memfuncTTree(void) {
   /* TTree */
   G__tag_memfunc_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree));
   G__memfunc_setup("Process",735,G__ManualTree2_126_0_132, 110, -1, G__defined_typename("Long64_t"), 0, 4, 1, 1, 0,
      "Y - - 0 - selector C - 'Option_t' 10 '\"\"' option "
      "n - 'Long64_t' 0 '1000000000' nentries n - 'Long64_t' 0 '0' firstentry", (char*)NULL, (void*) NULL, 1);
   G__memfunc_setup("Branch",590,G__ManualTree2_126_0_187, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 5, 1, 1, 0,
      "C - - 10 - name C - - 10 - classname "
      "Y - - 3 - addobj i - 'Int_t' 0 '32000' bufsize "
      "i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0);
   G__memfunc_setup("Branch",590,G__ManualTree2_126_0_188, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 4, 1, 1, 0,
      "C - - 10 - name Y - - 3 - addobj "
      "i - 'Int_t' 0 '32000' bufsize i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0);
   G__memfunc_setup("SetBranchAddress",1600,G__ManualTree2_126_0_190, 121, -1, -1, 0, 3, 1, 1, 0,
      "C - - 10 - bname Y - - 2 - add "
      "U 'TBranch' - 2 '0' ptr", (char*)NULL, (void*) NULL, 0);
   G__tag_memfunc_reset();
}

/*********************************************************
* Member function information setup
*********************************************************/
extern "C" void G__cpp_setup_memfuncManualTree2() {
}

/*********************************************************
* Global variable information setup for each class
*********************************************************/
static void G__cpp_setup_global0() {

   /* Setting up global variables */
   G__resetplocal();

}

static void G__cpp_setup_global1() {
}

static void G__cpp_setup_global2() {

   G__resetglobalenv();
}
extern "C" void G__cpp_setup_globalManualTree2() {
   G__cpp_setup_global0();
   G__cpp_setup_global1();
   G__cpp_setup_global2();
}

/*********************************************************
* Global function information setup for each class
*********************************************************/
static void G__cpp_setup_func0() {
   G__lastifuncposition();

}

static void G__cpp_setup_func1() {
}

static void G__cpp_setup_func2() {

   G__resetifuncposition();
}

extern "C" void G__cpp_setup_funcManualTree2() {
   G__cpp_setup_func0();
   G__cpp_setup_func1();
   G__cpp_setup_func2();
}

/*********************************************************
* Class,struct,union,enum tag information setup
*********************************************************/
/* Setup class/struct taginfo */
G__linked_taginfo G__ManualTree2LN_TTree = { "TTree" , 99 , -1 };
G__linked_taginfo G__ManualTree2LN_TBranch = { "TBranch" , 99 , -1 };
G__linked_taginfo G__ManualTree2LN_TSelector = { "TSelector" , 99 , -1 };

/* Reset class/struct taginfo */
extern "C" void G__cpp_reset_tagtableManualTree2() {
   G__ManualTree2LN_TTree.tagnum = -1 ;
   G__ManualTree2LN_TBranch.tagnum = -1 ;
   G__ManualTree2LN_TSelector.tagnum = -1 ;
}

extern "C" void G__cpp_setup_tagtableManualTree2() {

   /* Setting up class,struct,union tag entry */
   G__tagtable_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree),sizeof(TTree),-1,65280,"Tree descriptor (the main ROOT I/O class)",NULL,G__setup_memfuncTTree);
   G__get_linked_tagnum_fwd(&G__ManualTree2LN_TBranch);
   G__get_linked_tagnum_fwd(&G__ManualTree2LN_TSelector);
}
extern "C" void G__cpp_setupManualTree2(void) {
   G__check_setup_version(30051515,"G__cpp_setupManualTree2()");
   G__set_cpp_environmentManualTree2();
   G__cpp_setup_tagtableManualTree2();

   G__cpp_setup_inheritanceManualTree2();

   G__cpp_setup_typetableManualTree2();

   G__cpp_setup_memvarManualTree2();

   G__cpp_setup_memfuncManualTree2();
   G__cpp_setup_globalManualTree2();
   G__cpp_setup_funcManualTree2();

   if(0==G__getsizep2memfunc()) G__get_sizep2memfuncManualTree2();
   return;
}
class G__cpp_setup_initManualTree2 {
public:
   G__cpp_setup_initManualTree2() { G__add_setup_func("ManualTree2",(G__incsetup)(&G__cpp_setupManualTree2)); G__call_setup_funcs(); }
   ~G__cpp_setup_initManualTree2() { G__remove_setup_func("ManualTree2"); }
};
G__cpp_setup_initManualTree2 G__cpp_setup_initializerManualTree2;

<commit_msg>fix the pointer level of the void* parameter to Branch<commit_after>//
// File generated by c:\Devel\root_working\code\root.vc8\utils\src\rootcint_tmp.exe at Wed May 16 23:07:42 2007

// Do NOT change. Changes will be lost next time file is generated
//

#include "RConfig.h"
#if !defined(R__ACCESS_IN_SYMBOL)
//Break the privacy of classes -- Disabled for the moment
#define private public
#define protected public
#endif

// Since CINT ignores the std namespace, we need to do so in this file.
namespace std {} using namespace std;
#include "ManualTree2.h"

#include "TClass.h"
#include "TBuffer.h"
#include "TMemberInspector.h"
#include "TError.h"

#ifndef G__ROOT
#define G__ROOT
#endif

#include "RtypesImp.h"
#include "TIsAProxy.h"

// START OF SHADOWS

namespace ROOT {
   namespace Shadow {
   } // of namespace Shadow
} // of namespace ROOT
// END OF SHADOWS

/********************************************************
* tree/src/ManualTree2.cxx
* CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED
*          FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX().
*          CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE.
********************************************************/

#ifdef G__MEMTEST
#undef malloc
#undef free
#endif

extern "C" void G__cpp_reset_tagtableManualTree2();

extern "C" void G__set_cpp_environmentManualTree2() {
   G__add_compiledheader("TTree.h");
   G__cpp_reset_tagtableManualTree2();
}
#include <new>
extern "C" int G__cpp_dllrevManualTree2() { return(30051515); }

/*********************************************************
* Member function Interface Method
*********************************************************/

/* TTree */
#include "ManualTree2Body.h"

/* Setting up global function */

/*********************************************************
* Member function Stub
*********************************************************/

/*********************************************************
* Global function Stub
*********************************************************/

/*********************************************************
* Get size of pointer to member function
*********************************************************/
class G__Sizep2memfuncManualTree2 {
public:
   G__Sizep2memfuncManualTree2(): p(&G__Sizep2memfuncManualTree2::sizep2memfunc) {}
   size_t sizep2memfunc() { return(sizeof(p)); }
private:
   size_t (G__Sizep2memfuncManualTree2::*p)();
};

size_t G__get_sizep2memfuncManualTree2()
{
   G__Sizep2memfuncManualTree2 a;
   G__setsizep2memfunc((int)a.sizep2memfunc());
   return((size_t)a.sizep2memfunc());
}

/*********************************************************
* virtual base class offset calculation interface
*********************************************************/

/* Setting up class inheritance */

/*********************************************************
* Inheritance information setup/
*********************************************************/
extern "C" void G__cpp_setup_inheritanceManualTree2() {

   /* Setting up class inheritance */
}

/*********************************************************
* typedef information setup/
*********************************************************/
extern "C" void G__cpp_setup_typetableManualTree2() {

   /* Setting up typedef entry */
   G__search_typename2("Int_t",105,-1,0,-1);
   G__setnewtype(-1,"Signed integer 4 bytes (int)",0);
   G__search_typename2("Option_t",99,-1,256,-1);
   G__setnewtype(-1,"Option string (const char)",0);
   G__search_typename2("Long64_t",110,-1,0,-1);
   G__setnewtype(-1,"Portable signed long integer 8 bytes",0);
}

/*********************************************************
* Data Member information setup/
*********************************************************/

/* Setting up class,struct,union tag member variable */
extern "C" void G__cpp_setup_memvarManualTree2() {
}
/***********************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
***********************************************************/

/*********************************************************
* Member function information setup for each class
*********************************************************/
static void G__setup_memfuncTTree(void) {
   /* TTree */
   G__tag_memfunc_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree));
   G__memfunc_setup("Process",735,G__ManualTree2_126_0_132, 110, -1, G__defined_typename("Long64_t"), 0, 4, 1, 1, 0,
      "Y - - 0 - selector C - 'Option_t' 10 '\"\"' option "
      "n - 'Long64_t' 0 '1000000000' nentries n - 'Long64_t' 0 '0' firstentry", (char*)NULL, (void*) NULL, 1);
   G__memfunc_setup("Branch",590,G__ManualTree2_126_0_187, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 5, 1, 1, 0,
      "C - - 10 - name C - - 10 - classname "
      "Y - - 0 - addobj i - 'Int_t' 0 '32000' bufsize "
      "i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0);
   G__memfunc_setup("Branch",590,G__ManualTree2_126_0_188, 85, G__get_linked_tagnum(&G__ManualTree2LN_TBranch), -1, 0, 4, 1, 1, 0,
      "C - - 10 - name Y - - 0 - addobj "
      "i - 'Int_t' 0 '32000' bufsize i - 'Int_t' 0 '99' splitlevel", (char*)NULL, (void*) NULL, 0);
   G__memfunc_setup("SetBranchAddress",1600,G__ManualTree2_126_0_190, 121, -1, -1, 0, 3, 1, 1, 0,
      "C - - 10 - bname Y - - 2 - add "
      "U 'TBranch' - 2 '0' ptr", (char*)NULL, (void*) NULL, 0);
   G__tag_memfunc_reset();
}

/*********************************************************
* Member function information setup
*********************************************************/
extern "C" void G__cpp_setup_memfuncManualTree2() {
}

/*********************************************************
* Global variable information setup for each class
*********************************************************/
static void G__cpp_setup_global0() {

   /* Setting up global variables */
   G__resetplocal();

}

static void G__cpp_setup_global1() {
}

static void G__cpp_setup_global2() {

   G__resetglobalenv();
}
extern "C" void G__cpp_setup_globalManualTree2() {
   G__cpp_setup_global0();
   G__cpp_setup_global1();
   G__cpp_setup_global2();
}

/*********************************************************
* Global function information setup for each class
*********************************************************/
static void G__cpp_setup_func0() {
   G__lastifuncposition();

}

static void G__cpp_setup_func1() {
}

static void G__cpp_setup_func2() {

   G__resetifuncposition();
}

extern "C" void G__cpp_setup_funcManualTree2() {
   G__cpp_setup_func0();
   G__cpp_setup_func1();
   G__cpp_setup_func2();
}

/*********************************************************
* Class,struct,union,enum tag information setup
*********************************************************/
/* Setup class/struct taginfo */
G__linked_taginfo G__ManualTree2LN_TTree = { "TTree" , 99 , -1 };
G__linked_taginfo G__ManualTree2LN_TBranch = { "TBranch" , 99 , -1 };
G__linked_taginfo G__ManualTree2LN_TSelector = { "TSelector" , 99 , -1 };

/* Reset class/struct taginfo */
extern "C" void G__cpp_reset_tagtableManualTree2() {
   G__ManualTree2LN_TTree.tagnum = -1 ;
   G__ManualTree2LN_TBranch.tagnum = -1 ;
   G__ManualTree2LN_TSelector.tagnum = -1 ;
}

extern "C" void G__cpp_setup_tagtableManualTree2() {

   /* Setting up class,struct,union tag entry */
   G__tagtable_setup(G__get_linked_tagnum(&G__ManualTree2LN_TTree),sizeof(TTree),-1,65280,"Tree descriptor (the main ROOT I/O class)",NULL,G__setup_memfuncTTree);
   G__get_linked_tagnum_fwd(&G__ManualTree2LN_TBranch);
   G__get_linked_tagnum_fwd(&G__ManualTree2LN_TSelector);
}
extern "C" void G__cpp_setupManualTree2(void) {
   G__check_setup_version(30051515,"G__cpp_setupManualTree2()");
   G__set_cpp_environmentManualTree2();
   G__cpp_setup_tagtableManualTree2();

   G__cpp_setup_inheritanceManualTree2();

   G__cpp_setup_typetableManualTree2();

   G__cpp_setup_memvarManualTree2();

   G__cpp_setup_memfuncManualTree2();
   G__cpp_setup_globalManualTree2();
   G__cpp_setup_funcManualTree2();

   if(0==G__getsizep2memfunc()) G__get_sizep2memfuncManualTree2();
   return;
}
class G__cpp_setup_initManualTree2 {
public:
   G__cpp_setup_initManualTree2() { G__add_setup_func("ManualTree2",(G__incsetup)(&G__cpp_setupManualTree2)); G__call_setup_funcs(); }
   ~G__cpp_setup_initManualTree2() { G__remove_setup_func("ManualTree2"); }
};
G__cpp_setup_initManualTree2 G__cpp_setup_initializerManualTree2;

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* @file
 * EventQueue interfaces
 */

#ifndef __EVENTQ_HH__
#define __EVENTQ_HH__

#include <assert.h>

#include <algorithm>
#include <map>
#include <string>
#include <vector>

#include "sim/host.hh"	// for Tick

#include "base/fast_alloc.hh"
#include "sim/serialize.hh"
#include "base/trace.hh"

class EventQueue;	// forward declaration

/*
 * An item on an event queue.  The action caused by a given
 * event is specified by deriving a subclass and overriding the
 * process() member function.
 */
class Event : public Serializable, public FastAlloc
{
    friend class EventQueue;

  private:
    /// queue to which this event belongs (though it may or may not be
    /// scheduled on this queue yet)
    EventQueue *queue;

    Event *next;

    Tick _when;	//!< timestamp when event should be processed
    int _priority;	//!< event priority
    char _flags;

  protected:
    enum Flags {
        None = 0x0,
        Squashed = 0x1,
        Scheduled = 0x2,
        AutoDelete = 0x4,
        AutoSerialize = 0x8
    };

    bool getFlags(Flags f) const { return (_flags & f) == f; }
    void setFlags(Flags f) { _flags |= f; }
    void clearFlags(Flags f) { _flags &= ~f; }

  protected:
    EventQueue *theQueue() const { return queue; }

#if TRACING_ON
    Tick when_created;	//!< Keep track of creation time For debugging
    Tick when_scheduled;	//!< Keep track of creation time For debugging

    virtual void trace(const char *action);	//!< trace event activity
#else
    void trace(const char *) {}
#endif

    unsigned annotated_value;

  public:

    /// Event priorities, to provide tie-breakers for events scheduled
    /// at the same cycle.  Most events are scheduled at the default
    /// priority; these values are used to control events that need to
    /// be ordered within a cycle.
    enum Priority {
        /// Breakpoints should happen before anything else, so we
        /// don't miss any action when debugging.
        Debug_Break_Pri		= -100,

        /// For some reason "delayed" inter-cluster writebacks are
        /// scheduled before regular writebacks (which have default
        /// priority).  Steve?
        Delayed_Writeback_Pri	=   -1,

        /// Default is zero for historical reasons.
        Default_Pri		=    0,

        /// CPU switches schedule the new CPU's tick event for the
        /// same cycle (after unscheduling the old CPU's tick event).
        /// The switch needs to come before any tick events to make
        /// sure we don't tick both CPUs in the same cycle.
        CPU_Switch_Pri		=   31,

        /// Serailization needs to occur before tick events also, so
        /// that a serialize/unserialize is identical to an on-line
        /// CPU switch.
        Serialize_Pri		=   32,

        /// CPU ticks must come after other associated CPU events
        /// (such as writebacks).
        CPU_Tick_Pri		=   50,

        /// Statistics events (dump, reset, etc.) come after
        /// everything else, but before exit.
        Stat_Event_Pri		=   90,

        /// If we want to exit on this cycle, it's the very last thing
        /// we do.
        Sim_Exit_Pri		=  100
    };

    /*
     * Event constructor
     * @param queue that the event gets scheduled on
     */
    Event(EventQueue *q, Priority p = Default_Pri)
        : queue(q), next(NULL), _priority(p), _flags(None),
#if TRACING_ON
          when_created(curTick), when_scheduled(0),
#endif
          annotated_value(0)
    {
    }

    ~Event() {}

    virtual const std::string name() const {
        return csprintf("Event_%x", (uintptr_t)this);
    }

    /// Determine if the current event is scheduled
    bool scheduled() const { return getFlags(Scheduled); }

    /// Schedule the event with the current priority or default priority
    void schedule(Tick t);

    /// Reschedule the event with the current priority
    void reschedule(Tick t);

    /// Remove the event from the current schedule
    void deschedule();

    /// Return a C string describing the event.  This string should
    /// *not* be dynamically allocated; just a const char array
    /// describing the event class.
    virtual const char *description();

    /// Dump the current event data
    void dump();

    /*
     * This member function is invoked when the event is processed
     * (occurs).  There is no default implementation; each subclass
     * must provide its own implementation.  The event is not
     * automatically deleted after it is processed (to allow for
     * statically allocated event objects).
     *
     * If the AutoDestroy flag is set, the object is deleted once it
     * is processed.
     */
    virtual void process() = 0;

    void annotate(unsigned value) { annotated_value = value; };
    unsigned annotation() { return annotated_value; }

    /// Squash the current event
    void squash() { setFlags(Squashed); }

    /// Check whether the event is squashed
    bool squashed() { return getFlags(Squashed); }

    /// Get the time that the event is scheduled
    Tick when() const { return _when; }

    /// Get the event priority
    int priority() const { return _priority; }

    struct priority_compare :
    public std::binary_function<Event *, Event *, bool>
    {
        bool operator()(const Event *l, const Event *r) const {
            return l->when() >= r->when() || l->priority() >= r->priority();
        }
    };

    virtual void serialize(std::ostream &os);
    virtual void unserialize(Checkpoint *cp, const std::string &section);
};

template <class T, void (T::* F)()>
void
DelayFunction(Tick when, T *object)
{
    class DelayEvent : public Event
    {
      private:
        T *object;

      public:
        DelayEvent(Tick when, T *o)
            : Event(&mainEventQueue), object(o)
            { setFlags(AutoDestroy); schedule(when); }
        void process() { (object->*F)(); }
        const char *description() { return "delay"; }
    };

    new DelayEvent(when, object);
}

/*
 * Queue of events sorted in time order
 */
class EventQueue : public Serializable
{
  protected:
    std::string objName;

  private:
    Event *head;

    void insert(Event *event);
    void remove(Event *event);

  public:

    // constructor
    EventQueue(const std::string &n)
        : objName(n), head(NULL)
    {}

    virtual const std::string name() const { return objName; }

    // schedule the given event on this queue
    void schedule(Event *ev);
    void deschedule(Event *ev);
    void reschedule(Event *ev);

    Tick nextTick() { return head->when(); }
    void serviceOne();

    // process all events up to the given timestamp.  we inline a
    // quick test to see if there are any events to process; if so,
    // call the internal out-of-line version to process them all.
    void serviceEvents(Tick when) {
        while (!empty()) {
            if (nextTick() > when)
                break;

            assert(head->when() >= when && "event scheduled in the past");
            serviceOne();
        }
    }

    // default: process all events up to 'now' (curTick)
    void serviceEvents() { serviceEvents(curTick); }

    // return true if no events are queued
    bool empty() { return head == NULL; }

    void dump();

    Tick nextEventTime() { return empty() ? curTick : head->when(); }

    virtual void serialize(std::ostream &os);
    virtual void unserialize(Checkpoint *cp, const std::string &section);
};

//////////////////////
//
// inline functions
//
// can't put these inside declaration due to circular dependence
// between Event and EventQueue classes.
//
//////////////////////

// schedule at specified time (place on event queue specified via
// constructor)
inline void
Event::schedule(Tick t)
{
    assert(!scheduled());
    setFlags(Scheduled);
#if TRACING_ON
    when_scheduled = curTick;
#endif
    _when = t;
    queue->schedule(this);
}

inline void
Event::deschedule()
{
    assert(scheduled());

    clearFlags(Squashed);
    clearFlags(Scheduled);
    queue->deschedule(this);
}

inline void
Event::reschedule(Tick t)
{
    assert(scheduled());
    clearFlags(Squashed);

#if TRACING_ON
    when_scheduled = curTick;
#endif
    _when = t;
    queue->reschedule(this);
}

inline void
EventQueue::schedule(Event *event)
{
    insert(event);
    if (DTRACE(Event))
        event->trace("scheduled");
}

inline void
EventQueue::deschedule(Event *event)
{
    remove(event);
    if (DTRACE(Event))
        event->trace("descheduled");
}

inline void
EventQueue::reschedule(Event *event)
{
    remove(event);
    insert(event);
    if (DTRACE(Event))
        event->trace("rescheduled");
}

//////////////////////
//
// Main Event Queue
//
// Events on this queue are processed at the *beginning* of each
// cycle, before the pipeline simulation is performed.
//
// defined in eventq.cc
//
//////////////////////
extern EventQueue mainEventQueue;

#endif // __EVENTQ_HH__
<commit_msg>Add a simple event wrapper class that takes a class pointer and member function and will schedule it for the future.<commit_after>/*
 * Copyright (c) 2003 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/* @file
 * EventQueue interfaces
 */

#ifndef __EVENTQ_HH__
#define __EVENTQ_HH__

#include <assert.h>

#include <algorithm>
#include <map>
#include <string>
#include <vector>

#include "sim/host.hh"	// for Tick

#include "base/fast_alloc.hh"
#include "sim/serialize.hh"
#include "base/trace.hh"

class EventQueue;	// forward declaration

/*
 * An item on an event queue.  The action caused by a given
 * event is specified by deriving a subclass and overriding the
 * process() member function.
 */
class Event : public Serializable, public FastAlloc
{
    friend class EventQueue;

  private:
    /// queue to which this event belongs (though it may or may not be
    /// scheduled on this queue yet)
    EventQueue *queue;

    Event *next;

    Tick _when;	//!< timestamp when event should be processed
    int _priority;	//!< event priority
    char _flags;

  protected:
    enum Flags {
        None = 0x0,
        Squashed = 0x1,
        Scheduled = 0x2,
        AutoDelete = 0x4,
        AutoSerialize = 0x8
    };

    bool getFlags(Flags f) const { return (_flags & f) == f; }
    void setFlags(Flags f) { _flags |= f; }
    void clearFlags(Flags f) { _flags &= ~f; }

  protected:
    EventQueue *theQueue() const { return queue; }

#if TRACING_ON
    Tick when_created;	//!< Keep track of creation time For debugging
    Tick when_scheduled;	//!< Keep track of creation time For debugging

    virtual void trace(const char *action);	//!< trace event activity
#else
    void trace(const char *) {}
#endif

    unsigned annotated_value;

  public:

    /// Event priorities, to provide tie-breakers for events scheduled
    /// at the same cycle.  Most events are scheduled at the default
    /// priority; these values are used to control events that need to
    /// be ordered within a cycle.
    enum Priority {
        /// Breakpoints should happen before anything else, so we
        /// don't miss any action when debugging.
        Debug_Break_Pri		= -100,

        /// For some reason "delayed" inter-cluster writebacks are
        /// scheduled before regular writebacks (which have default
        /// priority).  Steve?
        Delayed_Writeback_Pri	=   -1,

        /// Default is zero for historical reasons.
        Default_Pri		=    0,

        /// CPU switches schedule the new CPU's tick event for the
        /// same cycle (after unscheduling the old CPU's tick event).
        /// The switch needs to come before any tick events to make
        /// sure we don't tick both CPUs in the same cycle.
        CPU_Switch_Pri		=   31,

        /// Serailization needs to occur before tick events also, so
        /// that a serialize/unserialize is identical to an on-line
        /// CPU switch.
        Serialize_Pri		=   32,

        /// CPU ticks must come after other associated CPU events
        /// (such as writebacks).
        CPU_Tick_Pri		=   50,

        /// Statistics events (dump, reset, etc.) come after
        /// everything else, but before exit.
        Stat_Event_Pri		=   90,

        /// If we want to exit on this cycle, it's the very last thing
        /// we do.
        Sim_Exit_Pri		=  100
    };

    /*
     * Event constructor
     * @param queue that the event gets scheduled on
     */
    Event(EventQueue *q, Priority p = Default_Pri)
        : queue(q), next(NULL), _priority(p), _flags(None),
#if TRACING_ON
          when_created(curTick), when_scheduled(0),
#endif
          annotated_value(0)
    {
    }

    ~Event() {}

    virtual const std::string name() const {
        return csprintf("Event_%x", (uintptr_t)this);
    }

    /// Determine if the current event is scheduled
    bool scheduled() const { return getFlags(Scheduled); }

    /// Schedule the event with the current priority or default priority
    void schedule(Tick t);

    /// Reschedule the event with the current priority
    void reschedule(Tick t);

    /// Remove the event from the current schedule
    void deschedule();

    /// Return a C string describing the event.  This string should
    /// *not* be dynamically allocated; just a const char array
    /// describing the event class.
    virtual const char *description();

    /// Dump the current event data
    void dump();

    /*
     * This member function is invoked when the event is processed
     * (occurs).  There is no default implementation; each subclass
     * must provide its own implementation.  The event is not
     * automatically deleted after it is processed (to allow for
     * statically allocated event objects).
     *
     * If the AutoDestroy flag is set, the object is deleted once it
     * is processed.
     */
    virtual void process() = 0;

    void annotate(unsigned value) { annotated_value = value; };
    unsigned annotation() { return annotated_value; }

    /// Squash the current event
    void squash() { setFlags(Squashed); }

    /// Check whether the event is squashed
    bool squashed() { return getFlags(Squashed); }

    /// Get the time that the event is scheduled
    Tick when() const { return _when; }

    /// Get the event priority
    int priority() const { return _priority; }

    struct priority_compare :
    public std::binary_function<Event *, Event *, bool>
    {
        bool operator()(const Event *l, const Event *r) const {
            return l->when() >= r->when() || l->priority() >= r->priority();
        }
    };

    virtual void serialize(std::ostream &os);
    virtual void unserialize(Checkpoint *cp, const std::string &section);
};

template <class T, void (T::* F)()>
void
DelayFunction(Tick when, T *object)
{
    class DelayEvent : public Event
    {
      private:
        T *object;

      public:
        DelayEvent(Tick when, T *o)
            : Event(&mainEventQueue), object(o)
            { setFlags(AutoDestroy); schedule(when); }
        void process() { (object->*F)(); }
        const char *description() { return "delay"; }
    };

    new DelayEvent(when, object);
}

template <class T, void (T::* F)()>
class EventWrapper : public Event
{
  private:
    T *object;

  public:
    EventWrapper(T *obj, EventQueue *q = &mainEventQueue,
                 Priority p = Default_Pri)
        : Event(q, p), object(obj)
    {}
    void process() { (object->*F)(); }
};

/*
 * Queue of events sorted in time order
 */
class EventQueue : public Serializable
{
  protected:
    std::string objName;

  private:
    Event *head;

    void insert(Event *event);
    void remove(Event *event);

  public:

    // constructor
    EventQueue(const std::string &n)
        : objName(n), head(NULL)
    {}

    virtual const std::string name() const { return objName; }

    // schedule the given event on this queue
    void schedule(Event *ev);
    void deschedule(Event *ev);
    void reschedule(Event *ev);

    Tick nextTick() { return head->when(); }
    void serviceOne();

    // process all events up to the given timestamp.  we inline a
    // quick test to see if there are any events to process; if so,
    // call the internal out-of-line version to process them all.
    void serviceEvents(Tick when) {
        while (!empty()) {
            if (nextTick() > when)
                break;

            assert(head->when() >= when && "event scheduled in the past");
            serviceOne();
        }
    }

    // default: process all events up to 'now' (curTick)
    void serviceEvents() { serviceEvents(curTick); }

    // return true if no events are queued
    bool empty() { return head == NULL; }

    void dump();

    Tick nextEventTime() { return empty() ? curTick : head->when(); }

    virtual void serialize(std::ostream &os);
    virtual void unserialize(Checkpoint *cp, const std::string &section);
};

//////////////////////
//
// inline functions
//
// can't put these inside declaration due to circular dependence
// between Event and EventQueue classes.
//
//////////////////////

// schedule at specified time (place on event queue specified via
// constructor)
inline void
Event::schedule(Tick t)
{
    assert(!scheduled());
    setFlags(Scheduled);
#if TRACING_ON
    when_scheduled = curTick;
#endif
    _when = t;
    queue->schedule(this);
}

inline void
Event::deschedule()
{
    assert(scheduled());

    clearFlags(Squashed);
    clearFlags(Scheduled);
    queue->deschedule(this);
}

inline void
Event::reschedule(Tick t)
{
    assert(scheduled());
    clearFlags(Squashed);

#if TRACING_ON
    when_scheduled = curTick;
#endif
    _when = t;
    queue->reschedule(this);
}

inline void
EventQueue::schedule(Event *event)
{
    insert(event);
    if (DTRACE(Event))
        event->trace("scheduled");
}

inline void
EventQueue::deschedule(Event *event)
{
    remove(event);
    if (DTRACE(Event))
        event->trace("descheduled");
}

inline void
EventQueue::reschedule(Event *event)
{
    remove(event);
    insert(event);
    if (DTRACE(Event))
        event->trace("rescheduled");
}

//////////////////////
//
// Main Event Queue
//
// Events on this queue are processed at the *beginning* of each
// cycle, before the pipeline simulation is performed.
//
// defined in eventq.cc
//
//////////////////////
extern EventQueue mainEventQueue;

#endif // __EVENTQ_HH__
<|endoftext|>


<commit_before>/* Copyright 2013 Roman Kurbatov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime
 * project. See git revision history for detailed changes. */

#include "fileManagerWidget.h"

#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtGui/QKeyEvent>

using namespace trikGui;

FileManagerWidget::FileManagerWidget(Controller &controller, MainWidget::FileManagerRootType fileManagerRoot
		, QWidget *parent)
	: TrikGuiDialog(parent)
	, mController(controller)
{
	if (fileManagerRoot == MainWidget::FileManagerRootType::allFS) {
		mRootDirPath = QDir::rootPath();
	} else { // if (fileManagerRoot == MainWidget::FileManagerRootType::scriptsDir)
		mRootDirPath = mController.scriptsDirPath();
	}

	QDir::setCurrent(mController.startDirPath());
	QDir dir;
	dir.mkdir(mController.scriptsDirName());
	QDir::setCurrent(mController.scriptsDirPath());

	mFileSystemModel.setRootPath(mRootDirPath);
	mFileSystemModel.setFilter(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDot);

	connect(&mFileSystemModel
			, SIGNAL(directoryLoaded(QString))
			, this
			, SLOT(onDirectoryLoaded(QString))
			);

	mFileSystemView.setModel(&mFileSystemModel);

	mLayout.addWidget(&mCurrentPathLabel);
	mLayout.addWidget(&mFileSystemView);
	setLayout(&mLayout);

	mFileSystemView.setSelectionMode(QAbstractItemView::SingleSelection);
	mFileSystemView.setFocus();

	showCurrentDir();
}

FileManagerWidget::~FileManagerWidget()
{
}

QString FileManagerWidget::menuEntry()
{
	return tr("File Manager");
}

void FileManagerWidget::renewFocus()
{
	mFileSystemView.setFocus();
}

void FileManagerWidget::open()
{
	QModelIndex const &index = mFileSystemView.currentIndex();
	if (mFileSystemModel.isDir(index)) {
		if (QDir::setCurrent(mFileSystemModel.filePath(index))) {
			showCurrentDir();
		}
	} else {
		mOpenDeleteBox.showMessage();
		FileManagerMessageBox::FileState const choice = mOpenDeleteBox.userAnswer();
		switch (choice) {
		case FileManagerMessageBox::FileState::Open:
			mController.runFile(mFileSystemModel.filePath(index));
			break;
		case FileManagerMessageBox::FileState::Delete:
			mFileSystemModel.remove(index);
			break;
		default:
			break;
		}
	}
}

void FileManagerWidget::keyPressEvent(QKeyEvent *event)
{
	switch (event->key()) {
		case Qt::Key_Return: {
			open();
			break;
		}
		default: {
			TrikGuiDialog::keyPressEvent(event);
			break;
		}
	}
}

QString FileManagerWidget::showCurrentPath()
{
	QString result = QDir::currentPath();
	result.remove(mRootDirPath);

	if (result.isEmpty()) {
		result = "/";
	}

	return result;
}

void FileManagerWidget::showCurrentDir()
{
	mCurrentPathLabel.setText(showCurrentPath());

	QDir::Filters filters = mFileSystemModel.filter();
	if (QDir::currentPath() == mRootDirPath) {
		filters |= QDir::NoDotDot;
	} else {
		filters &= ~QDir::NoDotDot;
	}
	filters &= ~QDir::Hidden;

	mFileSystemModel.setFilter(filters);

	mFileSystemView.setRootIndex(mFileSystemModel.index(QDir::currentPath()));

	/// @todo Here and several lines down we use QTimer
	/// to fix a bug with selecting first item. Rewrite it.
	QTimer::singleShot(200, this, SLOT(renewCurrentIndex()));
}

void FileManagerWidget::onDirectoryLoaded(QString const &path)
{
	if (QDir::currentPath() != path) {
		return;
	}

	QTimer::singleShot(200, this, SLOT(renewCurrentIndex()));
}

void FileManagerWidget::renewCurrentIndex()
{
	mFileSystemView.setFocus();

	QModelIndex const currentIndex = mFileSystemModel.index(
			0
			, 0
			, mFileSystemModel.index(QDir::currentPath())
			);

	mFileSystemView.selectionModel()->select(currentIndex, QItemSelectionModel::ClearAndSelect);
	mFileSystemView.setCurrentIndex(currentIndex);
}
<commit_msg>fixed mCurrentPathLabel-path (now with '/')<commit_after>/* Copyright 2013 Roman Kurbatov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime
 * project. See git revision history for detailed changes. */

#include "fileManagerWidget.h"

#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtGui/QKeyEvent>

using namespace trikGui;

FileManagerWidget::FileManagerWidget(Controller &controller, MainWidget::FileManagerRootType fileManagerRoot
		, QWidget *parent)
	: TrikGuiDialog(parent)
	, mController(controller)
{
	if (fileManagerRoot == MainWidget::FileManagerRootType::allFS) {
		mRootDirPath = QDir::rootPath();
	} else { // if (fileManagerRoot == MainWidget::FileManagerRootType::scriptsDir)
		mRootDirPath = mController.scriptsDirPath();
	}

	QDir::setCurrent(mController.startDirPath());
	QDir dir;
	dir.mkdir(mController.scriptsDirName());
	QDir::setCurrent(mController.scriptsDirPath());

	mFileSystemModel.setRootPath(mRootDirPath);
	mFileSystemModel.setFilter(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDot);

	connect(&mFileSystemModel
			, SIGNAL(directoryLoaded(QString))
			, this
			, SLOT(onDirectoryLoaded(QString))
			);

	mFileSystemView.setModel(&mFileSystemModel);

	mLayout.addWidget(&mCurrentPathLabel);
	mLayout.addWidget(&mFileSystemView);
	setLayout(&mLayout);

	mFileSystemView.setSelectionMode(QAbstractItemView::SingleSelection);
	mFileSystemView.setFocus();

	showCurrentDir();
}

FileManagerWidget::~FileManagerWidget()
{
}

QString FileManagerWidget::menuEntry()
{
	return tr("File Manager");
}

void FileManagerWidget::renewFocus()
{
	mFileSystemView.setFocus();
}

void FileManagerWidget::open()
{
	QModelIndex const &index = mFileSystemView.currentIndex();
	if (mFileSystemModel.isDir(index)) {
		if (QDir::setCurrent(mFileSystemModel.filePath(index))) {
			showCurrentDir();
		}
	} else {
		mOpenDeleteBox.showMessage();
		FileManagerMessageBox::FileState const choice = mOpenDeleteBox.userAnswer();
		switch (choice) {
		case FileManagerMessageBox::FileState::Open:
			mController.runFile(mFileSystemModel.filePath(index));
			break;
		case FileManagerMessageBox::FileState::Delete:
			mFileSystemModel.remove(index);
			break;
		default:
			break;
		}
	}
}

void FileManagerWidget::keyPressEvent(QKeyEvent *event)
{
	switch (event->key()) {
		case Qt::Key_Return: {
			open();
			break;
		}
		default: {
			TrikGuiDialog::keyPressEvent(event);
			break;
		}
	}
}

QString FileManagerWidget::showCurrentPath()
{
	QString result = QDir::currentPath();
	if (mRootDirPath != "/") {
		result.remove(mRootDirPath);
	}

	if (result.isEmpty()) {
		result = "/";
	}

	return result;
}

void FileManagerWidget::showCurrentDir()
{
	mCurrentPathLabel.setText(showCurrentPath());

	QDir::Filters filters = mFileSystemModel.filter();
	if (QDir::currentPath() == mRootDirPath) {
		filters |= QDir::NoDotDot;
	} else {
		filters &= ~QDir::NoDotDot;
	}
	filters &= ~QDir::Hidden;

	mFileSystemModel.setFilter(filters);

	mFileSystemView.setRootIndex(mFileSystemModel.index(QDir::currentPath()));

	/// @todo Here and several lines down we use QTimer
	/// to fix a bug with selecting first item. Rewrite it.
	QTimer::singleShot(200, this, SLOT(renewCurrentIndex()));
}

void FileManagerWidget::onDirectoryLoaded(QString const &path)
{
	if (QDir::currentPath() != path) {
		return;
	}

	QTimer::singleShot(200, this, SLOT(renewCurrentIndex()));
}

void FileManagerWidget::renewCurrentIndex()
{
	mFileSystemView.setFocus();

	QModelIndex const currentIndex = mFileSystemModel.index(
			0
			, 0
			, mFileSystemModel.index(QDir::currentPath())
			);

	mFileSystemView.selectionModel()->select(currentIndex, QItemSelectionModel::ClearAndSelect);
	mFileSystemView.setCurrentIndex(currentIndex);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperParameterList.h"
#include "otbWrapperQtWidgetListEditItemModel.h"
#include "otbWrapperQtWidgetListEditWidget.h"
#include "otbWrapperQtWidgetParameterList.h"

namespace otb
{

namespace Wrapper
{

/*****************************************************************************/
QtWidgetParameterList
::QtWidgetParameterList( AbstractParameterList * param, QtWidgetModel * m ) :
  QtWidgetParameterBase( param, m )
{
  assert( m!=nullptr );

  QObject::connect(
    this, SIGNAL( NotifyUpdate() ),
    m, SLOT( NotifyUpdate() )
  );
}

/*****************************************************************************/
QtWidgetParameterList
::~QtWidgetParameterList()
{
}

/*****************************************************************************/
void
QtWidgetParameterList
::DoUpdateGUI()
{
}

/*****************************************************************************/
void
QtWidgetParameterList
::DoCreateWidget()
{
  //
  // List-edit widget.
  ListEditWidget * widget = new ListEditWidget();

  assert( widget->GetItemModel()!=nullptr );
  assert( dynamic_cast< StringListInterface * >( GetParam() )!=nullptr );

  widget->GetItemModel()->SetStringList(
    dynamic_cast< StringListInterface * >( GetParam() )
  );

  //
  // Global Layout
  QGridLayout * layout = new QGridLayout();

  layout->setSpacing( 1 );
  layout->setContentsMargins( 2, 2, 2, 2 );

  layout->addWidget( widget );

  setLayout( layout );

  //
  // Connections.
  {
    QAbstractItemModel * model = widget->GetItemModel();
    assert( model!=nullptr );

    QObject::connect(
      model, SIGNAL( dataChanged( const QModelIndex &, const QModelIndex & ) ),
      this, SLOT( OnDataChanged( const QModelIndex &, const QModelIndex & ) )
    );

    QObject::connect(
      model, SIGNAL( modelReset() ),
      this, SLOT( OnModelReset() )
    );

    QObject::connect(
      model, SIGNAL( rowsInserted( const QModelIndex &, int, int ) ),
      this, SLOT( OnRowsInserted( const QModelIndex &, int, int ) )
    );

    QObject::connect(
      model, SIGNAL( rowsRemoved( const QModelIndex &, int, int ) ),
      this, SLOT( OnRowsRemoved( const QModelIndex &, int, int ) )
    );
  }
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnDataChanged( const QModelIndex &, const QModelIndex & )
{
  qDebug() << this << "::OnDataChanged()";

  assert( GetModel()!=nullptr );

  emit NotifyUpdate();
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnModelReset()
{
  qDebug() << this << "::OnModelReset()";

  emit NotifyUpdate();
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnRowsInserted( const QModelIndex &, int, int )
{
  qDebug() << this << "::OnRowsInserted()";

  emit NotifyUpdate();
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnRowsRemoved( const QModelIndex &, int, int )
{
  qDebug() << this << "::OnRowsRemoved()";

  emit NotifyUpdate();
}

}

}
<commit_msg>ENH: Disabled debug traces.<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperParameterList.h"
#include "otbWrapperQtWidgetListEditItemModel.h"
#include "otbWrapperQtWidgetListEditWidget.h"
#include "otbWrapperQtWidgetParameterList.h"

namespace otb
{

namespace Wrapper
{

/*****************************************************************************/
QtWidgetParameterList
::QtWidgetParameterList( AbstractParameterList * param, QtWidgetModel * m ) :
  QtWidgetParameterBase( param, m )
{
  assert( m!=nullptr );

  QObject::connect(
    this, SIGNAL( NotifyUpdate() ),
    m, SLOT( NotifyUpdate() )
  );
}

/*****************************************************************************/
QtWidgetParameterList
::~QtWidgetParameterList()
{
}

/*****************************************************************************/
void
QtWidgetParameterList
::DoUpdateGUI()
{
}

/*****************************************************************************/
void
QtWidgetParameterList
::DoCreateWidget()
{
  //
  // List-edit widget.
  ListEditWidget * widget = new ListEditWidget();

  assert( widget->GetItemModel()!=nullptr );
  assert( dynamic_cast< StringListInterface * >( GetParam() )!=nullptr );

  widget->GetItemModel()->SetStringList(
    dynamic_cast< StringListInterface * >( GetParam() )
  );

  //
  // Global Layout
  QGridLayout * layout = new QGridLayout();

  layout->setSpacing( 1 );
  layout->setContentsMargins( 2, 2, 2, 2 );

  layout->addWidget( widget );

  setLayout( layout );

  //
  // Connections.
  {
    QAbstractItemModel * model = widget->GetItemModel();
    assert( model!=nullptr );

    QObject::connect(
      model, SIGNAL( dataChanged( const QModelIndex &, const QModelIndex & ) ),
      this, SLOT( OnDataChanged( const QModelIndex &, const QModelIndex & ) )
    );

    QObject::connect(
      model, SIGNAL( modelReset() ),
      this, SLOT( OnModelReset() )
    );

    QObject::connect(
      model, SIGNAL( rowsInserted( const QModelIndex &, int, int ) ),
      this, SLOT( OnRowsInserted( const QModelIndex &, int, int ) )
    );

    QObject::connect(
      model, SIGNAL( rowsRemoved( const QModelIndex &, int, int ) ),
      this, SLOT( OnRowsRemoved( const QModelIndex &, int, int ) )
    );
  }
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnDataChanged( const QModelIndex &, const QModelIndex & )
{
  // qDebug() << this << "::OnDataChanged()";

  assert( GetModel()!=nullptr );

  emit NotifyUpdate();
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnModelReset()
{
  // qDebug() << this << "::OnModelReset()";

  emit NotifyUpdate();
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnRowsInserted( const QModelIndex &, int, int )
{
  // qDebug() << this << "::OnRowsInserted()";

  emit NotifyUpdate();
}

/*****************************************************************************/
void
QtWidgetParameterList
::OnRowsRemoved( const QModelIndex &, int, int )
{
  // qDebug() << this << "::OnRowsRemoved()";

  emit NotifyUpdate();
}

}

}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "itkImageToImageFilter.h"

#include "otbMaximumAutocorrelationFactorImageFilter.h"
#include "otbPCAImageFilter.h"
#include "otbNAPCAImageFilter.h"
#include "otbLocalActivityVectorImageFilter.h"
#include "otbMaximumAutocorrelationFactorImageFilter.h"
#include "otbFastICAImageFilter.h"
#include "otbFastICAInternalOptimizerVectorImageFilter.h"

//#include "otbVirtualDimensionality.h"

#include "otbStreamingMinMaxVectorImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"

namespace otb
{
namespace Wrapper
{

class DimensionalityReduction: public Application
{
public:
  /** Standard class typedefs. */
  typedef DimensionalityReduction Self;
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  // Dimensionality reduction typedef
  typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFFilterType;

  typedef itk::ImageToImageFilter<FloatVectorImageType, FloatVectorImageType> DimensionalityReductionFilter;

  // Reduction dimensio filters
  typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> PCAForwardFilterType;
  typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> PCAInverseFilterType;
  //typedef otb::PCAImageFilter< FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD >

  typedef otb::LocalActivityVectorImageFilter<FloatVectorImageType, FloatVectorImageType> NoiseFilterType;

  typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::FORWARD>
      NAPCAForwardFilterType;
  typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::INVERSE>
      NAPCAInverseFilterType;

  typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFForwardFilterType;

  typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD>
      ICAForwardFilterType;
  typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE>
      ICAInverseFilterType;

  typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVectorImageFilterType;

  typedef StreamingStatisticsVectorImageFilterType::MatrixObjectType::ComponentType                 MatrixType;
  //typedef otb::VirtualDimensionality<double> VDFilterType;

  // output rescale
  typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;
  typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;

  /** Standard macro */
  itkNewMacro(Self)
;

  itkTypeMacro(DimensionalityReduction, otb::Wrapper::Application)
;

private:
  void DoInit()
  {
    SetName("DimensionalityReduction");
    SetDescription("Perform Dimension reduction of the input image.");
    SetDocName("Dimensionality reduction");
    SetDocLongDescription("Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available.");
    SetDocLimitations(
                      "Though the inverse transform can be computed, this application only provides the forward transform for now.");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(
                  "\"Kernel maximum autocorrelation factor and minimum noise fraction transformations,\" IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)");

    AddDocTag(Tags::DimensionReduction);
    AddDocTag(Tags::Filter);

    AddParameter(ParameterType_InputImage, "in", "Input Image");
    SetParameterDescription("in", "The input image to apply dimensionality reduction.");
    AddParameter(ParameterType_OutputImage, "out", "Output Image");
    SetParameterDescription("out", "output image. Components are ordered by decreasing eigenvalues.");
    AddParameter(ParameterType_Group, "rescale", "Rescale Output.");

    MandatoryOff("rescale");
    //  AddChoice("rescale.no","No rescale");
    // AddChoice("rescale.minmax","rescale to min max value");

    AddParameter(ParameterType_Float, "rescale.outmin", "Output min value");
    AddParameter(ParameterType_Float, "rescale.outmax", "Output max value");
    SetDefaultParameterFloat("rescale.outmin", 0.0);
    SetParameterDescription("rescale.outmin", "Minimum value of the output image.");
    SetDefaultParameterFloat("rescale.outmax", 255.0);
    SetParameterDescription("rescale.outmax", "Maximum value of the output image.");

    AddParameter(ParameterType_OutputImage, "outinv", " Inverse Output Image");
    SetParameterDescription("outinv", "reconstruct output image.");
    MandatoryOff("outinv");

    AddParameter(ParameterType_Choice, "method", "Algorithm");
    SetParameterDescription("method", "Selection of the reduction dimension method.");

    AddChoice("method.pca", "PCA");
    SetParameterDescription("method.pca", "Principal Component Analysis.");
    AddChoice("method.napca", "NA-PCA");
    SetParameterDescription("method.napca", "Noise Adjusted Principal Component Analysis.");
    AddParameter(ParameterType_Int, "method.napca.radiusx", "Set the x radius of the sliding window.");
    SetMinimumParameterIntValue("method.napca.radiusx", 1);
    SetDefaultParameterInt("method.napca.radiusx", 1);
    AddParameter(ParameterType_Int, "method.napca.radiusy", "Set the y radius of the sliding window.");
    SetMinimumParameterIntValue("method.napca.radiusy", 1);
    SetDefaultParameterInt("method.napca.radiusy", 1);

    AddChoice("method.maf", "MAF");
    SetParameterDescription("method.maf", "Maximum Autocorrelation Factor.");
    AddChoice("method.ica", "ICA");
    SetParameterDescription("method.ica", "Independant Component Analysis.");
    AddParameter(ParameterType_Int, "method.ica.iter", "number of iterations ");
    SetMinimumParameterIntValue("method.ica.iter", 1);
    SetDefaultParameterInt("method.ica.iter", 20);
    MandatoryOff("method.ica.iter");

    AddParameter(ParameterType_Float, "method.ica.mu", "Give the increment weight of W in [0, 1]");
    SetMinimumParameterFloatValue("method.ica.mu", 0.);
    SetMaximumParameterFloatValue("method.ica.mu", 1.);
    SetDefaultParameterFloat("method.ica.mu", 1.);
    MandatoryOff("method.ica.mu");

    //AddChoice("method.vd","virual Dimension");
    //SetParameterDescription("method.vd","Virtual Dimension.");
    //MandatoryOff("method");

    AddParameter(ParameterType_Int, "nbcomp", "Number of Components.");
    SetParameterDescription("nbcomp", "Number of relevant components kept. By default all components are kept.");
    SetDefaultParameterInt("nbcomp", 0);
    MandatoryOff("nbcomp");
    SetMinimumParameterIntValue("nbcomp", 0);

    AddParameter(ParameterType_Empty, "normalize", "Normalize.");
    SetParameterDescription("normalize", "center AND reduce data before Dimensionality reduction.");
    MandatoryOff("normalize");

    AddParameter(ParameterType_OutputFilename, "outmatrix", "Transformation matrix output");
    SetParameterDescription("outmatrix", "Filename to store the transformation matrix (csv format)");
    MandatoryOff("outmatrix");

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
    SetDocExampleParameterValue("out", "FilterOutput.tif");
    SetDocExampleParameterValue("method", "pca");
  }

  void DoUpdateParameters()
  {
  }

  void DoExecute()
  {

    // Get Parameters
    int nbComp = GetParameterInt("nbcomp");
    bool normalize = HasValue("normalize");
    bool rescale = IsParameterEnabled("rescale");

    bool invTransform = HasValue("outinv");
    switch (GetParameterInt("method"))
      {
      // PCA Algorithm
      case 0:
        {
        otbAppLogDEBUG( << "PCA Algorithm ");
        PCAForwardFilterType::Pointer filter = PCAForwardFilterType::New();
        m_ForwardFilter = filter;
        PCAInverseFilterType::Pointer invFilter = PCAInverseFilterType::New();
        m_InverseFilter = invFilter;

        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetUseNormalization(normalize);
        m_ForwardFilter->Update();

        if (invTransform)
          {
          invFilter->SetInput(m_ForwardFilter->GetOutput());
          if (normalize)
            {
            otbAppLogINFO( << "Normalization MeanValue :"<<filter->GetMeanValues()<<
                "StdValue :" <<filter->GetStdDevValues() );
            invFilter->SetMeanValues(filter->GetMeanValues());
            invFilter->SetStdDevValues(filter->GetStdDevValues());
            }

          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
          m_TransformationMatrix = invFilter->GetTransformationMatrix();
          }

        m_TransformationMatrix = filter->GetTransformationMatrix();

        break;
        }
      case 1:
        {
        otbAppLogDEBUG( << "NA-PCA Algorithm ");

        // NA-PCA

        unsigned int radiusX = static_cast<unsigned int> (GetParameterInt("method.napca.radiusx"));
        unsigned int radiusY = static_cast<unsigned int> (GetParameterInt("method.napca.radiusy"));

        // Noise filtering
        NoiseFilterType::RadiusType radius = { { radiusX, radiusY } };

        NAPCAForwardFilterType::Pointer filter = NAPCAForwardFilterType::New();
        m_ForwardFilter = filter;
        NAPCAInverseFilterType::Pointer invFilter = NAPCAInverseFilterType::New();
        m_InverseFilter = invFilter;

        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetUseNormalization(normalize);
        filter->GetNoiseImageFilter()->SetRadius(radius);
        m_ForwardFilter->Update();
        if (invTransform)
          {
          otbAppLogDEBUG( << "Compute Inverse Transform");
          invFilter->SetInput(m_ForwardFilter->GetOutput());
          invFilter->SetMeanValues(filter->GetMeanValues());
          if (normalize)
            {
            invFilter->SetStdDevValues(filter->GetStdDevValues());
            }

          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
          m_TransformationMatrix = invFilter->GetTransformationMatrix();
          }

        m_TransformationMatrix = filter->GetTransformationMatrix();

        break;
        }
      case 2:
        {
        otbAppLogDEBUG( << "MAF Algorithm ");
        MAFForwardFilterType::Pointer filter = MAFForwardFilterType::New();
        m_ForwardFilter = filter;
        filter->SetInput(GetParameterFloatVectorImage("in"));
        m_ForwardFilter->Update();

        otbAppLogINFO( << "V :"<<std::endl<<filter->GetV()<<"Auto-Correlation :"<<std::endl <<filter->GetAutoCorrelation() );

        break;
        }
      case 3:
        {
        otbAppLogDEBUG( << "Fast ICA Algorithm ");

        unsigned int nbIterations = static_cast<unsigned int> (GetParameterInt("method.ica.iter"));
        double mu = static_cast<double> (GetParameterFloat("method.ica.mu"));

        ICAForwardFilterType::Pointer filter = ICAForwardFilterType::New();
        m_ForwardFilter = filter;
        ICAInverseFilterType::Pointer invFilter = ICAInverseFilterType::New();
        m_InverseFilter = invFilter;

        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetNumberOfIterations(nbIterations);
        filter->SetMu(mu);
        m_ForwardFilter->Update();

        if (invTransform)
          {
          otbAppLogDEBUG( << "Compute Inverse Transform");
          invFilter->SetInput(m_ForwardFilter->GetOutput());

          if (normalize)
            {
            invFilter->SetMeanValues(filter->GetMeanValues());
            invFilter->SetStdDevValues(filter->GetStdDevValues());
            }
          invFilter->SetPCATransformationMatrix(filter->GetPCATransformationMatrix());
          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
          }

        m_TransformationMatrix = filter->GetTransformationMatrix();

        break;
        }
        /* case 4:
         {
         otbAppLogDEBUG( << "VD Algorithm");

         break;
         }*/

      default:
        {
        otbAppLogFATAL(<<"non defined method "<<GetParameterInt("method")<<std::endl);
        break;

        }
        return;
      }

    if (invTransform)
      {
      if (GetParameterInt("method") == 2) //MAF or VD
        {
        otbAppLogWARNING(<<"This application only provides the forward transform .");
        }
      else SetParameterOutputImage("outinv", m_InverseFilter->GetOutput());
      }

    //Write transformation matrix
    if (this->GetParameterString("outmatrix").c_str())
      {
      if (GetParameterInt("method") == 2) //MAF or VD
        {
        otbAppLogWARNING(<<"No transformation matrix available for MAF.");
        }
      else
        {
        //Write transformation matrix
        std::ofstream outFile;
        outFile.open(this->GetParameterString("outmatrix").c_str());
        outFile << std::fixed;
        outFile.precision(10);

        outFile << m_TransformationMatrix;
        // if (invTransform)
        //   {
        //   outFile << m_InverseFilter->GetTransformationMatrix();
        //   }
        // else
        //   {
        //   outFile << m_ForwardFilter->GetTransformationMatrix();
        //   }

        //outFile << std::endl;
        outFile.close();
        }
      }

    if (!rescale)
      {
      SetParameterOutputImage("out", m_ForwardFilter->GetOutput());
      }
    else
      {
      otbAppLogDEBUG( << "Rescaling " )
      otbAppLogDEBUG( << "Starting Min/Max computation" )

      m_MinMaxFilter = MinMaxFilterType::New();
      m_MinMaxFilter->SetInput(m_ForwardFilter->GetOutput());
      m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming(50);

      AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing");
      m_MinMaxFilter->Update();

      otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum()
          << " max=" << m_MinMaxFilter->GetMaximum() )

      FloatVectorImageType::PixelType inMin, inMax;

      m_RescaleFilter = RescaleImageFilterType::New();
      m_RescaleFilter->SetInput(m_ForwardFilter->GetOutput());
      m_RescaleFilter->SetInputMinimum(m_MinMaxFilter->GetMinimum());
      m_RescaleFilter->SetInputMaximum(m_MinMaxFilter->GetMaximum());

      FloatVectorImageType::PixelType outMin, outMax;
      outMin.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel());
      outMax.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel());
      outMin.Fill(GetParameterFloat("rescale.outmin"));
      outMax.Fill(GetParameterFloat("rescale.outmax"));

      m_RescaleFilter->SetOutputMinimum(outMin);
      m_RescaleFilter->SetOutputMaximum(outMax);
      m_RescaleFilter->UpdateOutputInformation();

      SetParameterOutputImage("out", m_RescaleFilter->GetOutput());
      }

  }

  MinMaxFilterType::Pointer               m_MinMaxFilter;
  RescaleImageFilterType::Pointer         m_RescaleFilter;
  DimensionalityReductionFilter::Pointer  m_ForwardFilter;
  DimensionalityReductionFilter::Pointer  m_InverseFilter;
  MatrixType                              m_TransformationMatrix;
};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::DimensionalityReduction)
<commit_msg>ENH: remove useless call to c_str<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "itkImageToImageFilter.h"

#include "otbMaximumAutocorrelationFactorImageFilter.h"
#include "otbPCAImageFilter.h"
#include "otbNAPCAImageFilter.h"
#include "otbLocalActivityVectorImageFilter.h"
#include "otbMaximumAutocorrelationFactorImageFilter.h"
#include "otbFastICAImageFilter.h"
#include "otbFastICAInternalOptimizerVectorImageFilter.h"

//#include "otbVirtualDimensionality.h"

#include "otbStreamingMinMaxVectorImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"

namespace otb
{
namespace Wrapper
{

class DimensionalityReduction: public Application
{
public:
  /** Standard class typedefs. */
  typedef DimensionalityReduction Self;
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  // Dimensionality reduction typedef
  typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFFilterType;

  typedef itk::ImageToImageFilter<FloatVectorImageType, FloatVectorImageType> DimensionalityReductionFilter;

  // Reduction dimensio filters
  typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD> PCAForwardFilterType;
  typedef otb::PCAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE> PCAInverseFilterType;
  //typedef otb::PCAImageFilter< FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD >

  typedef otb::LocalActivityVectorImageFilter<FloatVectorImageType, FloatVectorImageType> NoiseFilterType;

  typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::FORWARD>
      NAPCAForwardFilterType;
  typedef otb::NAPCAImageFilter<FloatVectorImageType, FloatVectorImageType, NoiseFilterType, otb::Transform::INVERSE>
      NAPCAInverseFilterType;

  typedef otb::MaximumAutocorrelationFactorImageFilter<FloatVectorImageType, FloatVectorImageType> MAFForwardFilterType;

  typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::FORWARD>
      ICAForwardFilterType;
  typedef otb::FastICAImageFilter<FloatVectorImageType, FloatVectorImageType, otb::Transform::INVERSE>
      ICAInverseFilterType;

  typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType> StreamingStatisticsVectorImageFilterType;

  typedef StreamingStatisticsVectorImageFilterType::MatrixObjectType::ComponentType                 MatrixType;
  //typedef otb::VirtualDimensionality<double> VDFilterType;

  // output rescale
  typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;
  typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;

  /** Standard macro */
  itkNewMacro(Self)
;

  itkTypeMacro(DimensionalityReduction, otb::Wrapper::Application)
;

private:
  void DoInit()
  {
    SetName("DimensionalityReduction");
    SetDescription("Perform Dimension reduction of the input image.");
    SetDocName("Dimensionality reduction");
    SetDocLongDescription("Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available.");
    SetDocLimitations(
                      "Though the inverse transform can be computed, this application only provides the forward transform for now.");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(
                  "\"Kernel maximum autocorrelation factor and minimum noise fraction transformations,\" IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)");

    AddDocTag(Tags::DimensionReduction);
    AddDocTag(Tags::Filter);

    AddParameter(ParameterType_InputImage, "in", "Input Image");
    SetParameterDescription("in", "The input image to apply dimensionality reduction.");
    AddParameter(ParameterType_OutputImage, "out", "Output Image");
    SetParameterDescription("out", "output image. Components are ordered by decreasing eigenvalues.");
    AddParameter(ParameterType_Group, "rescale", "Rescale Output.");

    MandatoryOff("rescale");
    //  AddChoice("rescale.no","No rescale");
    // AddChoice("rescale.minmax","rescale to min max value");

    AddParameter(ParameterType_Float, "rescale.outmin", "Output min value");
    AddParameter(ParameterType_Float, "rescale.outmax", "Output max value");
    SetDefaultParameterFloat("rescale.outmin", 0.0);
    SetParameterDescription("rescale.outmin", "Minimum value of the output image.");
    SetDefaultParameterFloat("rescale.outmax", 255.0);
    SetParameterDescription("rescale.outmax", "Maximum value of the output image.");

    AddParameter(ParameterType_OutputImage, "outinv", " Inverse Output Image");
    SetParameterDescription("outinv", "reconstruct output image.");
    MandatoryOff("outinv");

    AddParameter(ParameterType_Choice, "method", "Algorithm");
    SetParameterDescription("method", "Selection of the reduction dimension method.");

    AddChoice("method.pca", "PCA");
    SetParameterDescription("method.pca", "Principal Component Analysis.");
    AddChoice("method.napca", "NA-PCA");
    SetParameterDescription("method.napca", "Noise Adjusted Principal Component Analysis.");
    AddParameter(ParameterType_Int, "method.napca.radiusx", "Set the x radius of the sliding window.");
    SetMinimumParameterIntValue("method.napca.radiusx", 1);
    SetDefaultParameterInt("method.napca.radiusx", 1);
    AddParameter(ParameterType_Int, "method.napca.radiusy", "Set the y radius of the sliding window.");
    SetMinimumParameterIntValue("method.napca.radiusy", 1);
    SetDefaultParameterInt("method.napca.radiusy", 1);

    AddChoice("method.maf", "MAF");
    SetParameterDescription("method.maf", "Maximum Autocorrelation Factor.");
    AddChoice("method.ica", "ICA");
    SetParameterDescription("method.ica", "Independant Component Analysis.");
    AddParameter(ParameterType_Int, "method.ica.iter", "number of iterations ");
    SetMinimumParameterIntValue("method.ica.iter", 1);
    SetDefaultParameterInt("method.ica.iter", 20);
    MandatoryOff("method.ica.iter");

    AddParameter(ParameterType_Float, "method.ica.mu", "Give the increment weight of W in [0, 1]");
    SetMinimumParameterFloatValue("method.ica.mu", 0.);
    SetMaximumParameterFloatValue("method.ica.mu", 1.);
    SetDefaultParameterFloat("method.ica.mu", 1.);
    MandatoryOff("method.ica.mu");

    //AddChoice("method.vd","virual Dimension");
    //SetParameterDescription("method.vd","Virtual Dimension.");
    //MandatoryOff("method");

    AddParameter(ParameterType_Int, "nbcomp", "Number of Components.");
    SetParameterDescription("nbcomp", "Number of relevant components kept. By default all components are kept.");
    SetDefaultParameterInt("nbcomp", 0);
    MandatoryOff("nbcomp");
    SetMinimumParameterIntValue("nbcomp", 0);

    AddParameter(ParameterType_Empty, "normalize", "Normalize.");
    SetParameterDescription("normalize", "center AND reduce data before Dimensionality reduction.");
    MandatoryOff("normalize");

    AddParameter(ParameterType_OutputFilename, "outmatrix", "Transformation matrix output");
    SetParameterDescription("outmatrix", "Filename to store the transformation matrix (csv format)");
    MandatoryOff("outmatrix");

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
    SetDocExampleParameterValue("out", "FilterOutput.tif");
    SetDocExampleParameterValue("method", "pca");
  }

  void DoUpdateParameters()
  {
  }

  void DoExecute()
  {

    // Get Parameters
    int nbComp = GetParameterInt("nbcomp");
    bool normalize = HasValue("normalize");
    bool rescale = IsParameterEnabled("rescale");

    bool invTransform = HasValue("outinv");
    switch (GetParameterInt("method"))
      {
      // PCA Algorithm
      case 0:
        {
        otbAppLogDEBUG( << "PCA Algorithm ");
        PCAForwardFilterType::Pointer filter = PCAForwardFilterType::New();
        m_ForwardFilter = filter;
        PCAInverseFilterType::Pointer invFilter = PCAInverseFilterType::New();
        m_InverseFilter = invFilter;

        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetUseNormalization(normalize);
        m_ForwardFilter->Update();

        if (invTransform)
          {
          invFilter->SetInput(m_ForwardFilter->GetOutput());
          if (normalize)
            {
            otbAppLogINFO( << "Normalization MeanValue :"<<filter->GetMeanValues()<<
                "StdValue :" <<filter->GetStdDevValues() );
            invFilter->SetMeanValues(filter->GetMeanValues());
            invFilter->SetStdDevValues(filter->GetStdDevValues());
            }

          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
          m_TransformationMatrix = invFilter->GetTransformationMatrix();
          }

        m_TransformationMatrix = filter->GetTransformationMatrix();

        break;
        }
      case 1:
        {
        otbAppLogDEBUG( << "NA-PCA Algorithm ");

        // NA-PCA

        unsigned int radiusX = static_cast<unsigned int> (GetParameterInt("method.napca.radiusx"));
        unsigned int radiusY = static_cast<unsigned int> (GetParameterInt("method.napca.radiusy"));

        // Noise filtering
        NoiseFilterType::RadiusType radius = { { radiusX, radiusY } };

        NAPCAForwardFilterType::Pointer filter = NAPCAForwardFilterType::New();
        m_ForwardFilter = filter;
        NAPCAInverseFilterType::Pointer invFilter = NAPCAInverseFilterType::New();
        m_InverseFilter = invFilter;

        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetUseNormalization(normalize);
        filter->GetNoiseImageFilter()->SetRadius(radius);
        m_ForwardFilter->Update();
        if (invTransform)
          {
          otbAppLogDEBUG( << "Compute Inverse Transform");
          invFilter->SetInput(m_ForwardFilter->GetOutput());
          invFilter->SetMeanValues(filter->GetMeanValues());
          if (normalize)
            {
            invFilter->SetStdDevValues(filter->GetStdDevValues());
            }

          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
          m_TransformationMatrix = invFilter->GetTransformationMatrix();
          }

        m_TransformationMatrix = filter->GetTransformationMatrix();

        break;
        }
      case 2:
        {
        otbAppLogDEBUG( << "MAF Algorithm ");
        MAFForwardFilterType::Pointer filter = MAFForwardFilterType::New();
        m_ForwardFilter = filter;
        filter->SetInput(GetParameterFloatVectorImage("in"));
        m_ForwardFilter->Update();

        otbAppLogINFO( << "V :"<<std::endl<<filter->GetV()<<"Auto-Correlation :"<<std::endl <<filter->GetAutoCorrelation() );

        break;
        }
      case 3:
        {
        otbAppLogDEBUG( << "Fast ICA Algorithm ");

        unsigned int nbIterations = static_cast<unsigned int> (GetParameterInt("method.ica.iter"));
        double mu = static_cast<double> (GetParameterFloat("method.ica.mu"));

        ICAForwardFilterType::Pointer filter = ICAForwardFilterType::New();
        m_ForwardFilter = filter;
        ICAInverseFilterType::Pointer invFilter = ICAInverseFilterType::New();
        m_InverseFilter = invFilter;

        filter->SetInput(GetParameterFloatVectorImage("in"));
        filter->SetNumberOfPrincipalComponentsRequired(nbComp);
        filter->SetNumberOfIterations(nbIterations);
        filter->SetMu(mu);
        m_ForwardFilter->Update();

        if (invTransform)
          {
          otbAppLogDEBUG( << "Compute Inverse Transform");
          invFilter->SetInput(m_ForwardFilter->GetOutput());

          if (normalize)
            {
            invFilter->SetMeanValues(filter->GetMeanValues());
            invFilter->SetStdDevValues(filter->GetStdDevValues());
            }
          invFilter->SetPCATransformationMatrix(filter->GetPCATransformationMatrix());
          invFilter->SetTransformationMatrix(filter->GetTransformationMatrix());
          }

        m_TransformationMatrix = filter->GetTransformationMatrix();

        break;
        }
        /* case 4:
         {
         otbAppLogDEBUG( << "VD Algorithm");

         break;
         }*/

      default:
        {
        otbAppLogFATAL(<<"non defined method "<<GetParameterInt("method")<<std::endl);
        break;

        }
        return;
      }

    if (invTransform)
      {
      if (GetParameterInt("method") == 2) //MAF or VD
        {
        otbAppLogWARNING(<<"This application only provides the forward transform .");
        }
      else SetParameterOutputImage("outinv", m_InverseFilter->GetOutput());
      }

    //Write transformation matrix
    if (this->GetParameterString("outmatrix").size() != 0)
      {
      if (GetParameterInt("method") == 2) //MAF or VD
        {
        otbAppLogWARNING(<<"No transformation matrix available for MAF.");
        }
      else
        {
        //Write transformation matrix
        std::ofstream outFile;
        outFile.open(this->GetParameterString("outmatrix").c_str());
        outFile << std::fixed;
        outFile.precision(10);

        outFile << m_TransformationMatrix;
        outFile.close();
        }
      }

    if (!rescale)
      {
      SetParameterOutputImage("out", m_ForwardFilter->GetOutput());
      }
    else
      {
      otbAppLogDEBUG( << "Rescaling " )
      otbAppLogDEBUG( << "Starting Min/Max computation" )

      m_MinMaxFilter = MinMaxFilterType::New();
      m_MinMaxFilter->SetInput(m_ForwardFilter->GetOutput());
      m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming(50);

      AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing");
      m_MinMaxFilter->Update();

      otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum()
          << " max=" << m_MinMaxFilter->GetMaximum() )

      FloatVectorImageType::PixelType inMin, inMax;

      m_RescaleFilter = RescaleImageFilterType::New();
      m_RescaleFilter->SetInput(m_ForwardFilter->GetOutput());
      m_RescaleFilter->SetInputMinimum(m_MinMaxFilter->GetMinimum());
      m_RescaleFilter->SetInputMaximum(m_MinMaxFilter->GetMaximum());

      FloatVectorImageType::PixelType outMin, outMax;
      outMin.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel());
      outMax.SetSize(m_ForwardFilter->GetOutput()->GetNumberOfComponentsPerPixel());
      outMin.Fill(GetParameterFloat("rescale.outmin"));
      outMax.Fill(GetParameterFloat("rescale.outmax"));

      m_RescaleFilter->SetOutputMinimum(outMin);
      m_RescaleFilter->SetOutputMaximum(outMax);
      m_RescaleFilter->UpdateOutputInformation();

      SetParameterOutputImage("out", m_RescaleFilter->GetOutput());
      }

  }

  MinMaxFilterType::Pointer               m_MinMaxFilter;
  RescaleImageFilterType::Pointer         m_RescaleFilter;
  DimensionalityReductionFilter::Pointer  m_ForwardFilter;
  DimensionalityReductionFilter::Pointer  m_InverseFilter;
  MatrixType                              m_TransformationMatrix;
};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::DimensionalityReduction)
<|endoftext|>


<commit_before>// Copyright (c) 2012-2020 FRC Team 3512. All Rights Reserved.

#include "Robot.hpp"

#include <cmath>

Robot::Robot() {
    autonSelector.AddAutoMethod("Bridge",
                                std::bind(&Robot::AutonBridgeInit, this),
                                std::bind(&Robot::AutonBridgePeriodic, this));
    autonSelector.AddAutoMethod("Shoot",
                                std::bind(&Robot::AutonShootInit, this),
                                std::bind(&Robot::AutonShootPeriodic, this));
}

void Robot::DisabledInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); }

void Robot::AutonomousInit() {
    autonTimer.Reset();
    autonTimer.Start();

    autonSelector.ExecAutonomousInit();

    autonTimer.Stop();
}

void Robot::TeleopInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); }

void Robot::RobotPeriodic() { shooter.Update(); }

void Robot::AutonomousPeriodic() { autonSelector.ExecAutonomousPeriodic(); }

void Robot::TeleopPeriodic() {
    // Aim
    if (std::abs(turretStick.GetX()) > 0.06) {  // manual turret movement
        // Squaring gives finer control with a smaller joystick movement
        // while retaining max speed
        turretMotor.Set(-turretStick.GetX() * std::abs(turretStick.GetX()));
    }

    // Turns shooter on/off
    if (turretStick.GetRawButtonPressed(1)) {
        if (shooter.IsEnabled()) {
            shooter.Disable();
        } else {
            shooter.Disable();
        }
    }

    // Ball intake/conveyor
    if (turretStick.GetRawButton(6)) {
        lift.Set(frc::Relay::kForward);  // move lift up
    } else if (turretStick.GetRawButton(7)) {
        lift.Set(frc::Relay::kReverse);  // move lift down
    } else {
        lift.Set(frc::Relay::kOff);  // turn off lift
    }

    // Bridge arm
    if (driveStick2.GetRawButtonPressed(1)) {
        auto armState = bridgeArm.Get();

        /* Toggles state of bridge arm between Retracted and Deployed
         * (Doesn't toggle if the arm is transitioning)
         */
        if (armState == LockSolenoid::State::kRetracted) {
            bridgeArm.Set(LockSolenoid::State::kDeployed);
        } else if (armState == LockSolenoid::State::kDeployed) {
            bridgeArm.Set(LockSolenoid::State::kRetracted);
        }
    }

    // Makes sure bridge arm completed transitioning between states
    bridgeArm.Update();

    drivetrain.CurvatureDrive(driveStick1.GetY(), driveStick2.GetX(),
                              driveStick2.GetRawButton(2));
}

#ifndef RUNNING_FRC_TESTS
int main() { return frc::StartRobot<Robot>(); }
#endif
<commit_msg>Use lambdas instead of std::bind()<commit_after>// Copyright (c) 2012-2020 FRC Team 3512. All Rights Reserved.

#include "Robot.hpp"

#include <cmath>

Robot::Robot() {
    autonSelector.AddAutoMethod(
        "Bridge", [=] { AutonBridgeInit(); }, [=] { AutonBridgePeriodic(); });
    autonSelector.AddAutoMethod(
        "Shoot", [=] { AutonShootInit(); }, [=] { AutonShootPeriodic(); });
}

void Robot::DisabledInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); }

void Robot::AutonomousInit() {
    autonTimer.Reset();
    autonTimer.Start();

    autonSelector.ExecAutonomousInit();

    autonTimer.Stop();
}

void Robot::TeleopInit() { bridgeArm.Set(LockSolenoid::State::kRetracted); }

void Robot::RobotPeriodic() { shooter.Update(); }

void Robot::AutonomousPeriodic() { autonSelector.ExecAutonomousPeriodic(); }

void Robot::TeleopPeriodic() {
    // Aim
    if (std::abs(turretStick.GetX()) > 0.06) {  // manual turret movement
        // Squaring gives finer control with a smaller joystick movement
        // while retaining max speed
        turretMotor.Set(-turretStick.GetX() * std::abs(turretStick.GetX()));
    }

    // Turns shooter on/off
    if (turretStick.GetRawButtonPressed(1)) {
        if (shooter.IsEnabled()) {
            shooter.Disable();
        } else {
            shooter.Disable();
        }
    }

    // Ball intake/conveyor
    if (turretStick.GetRawButton(6)) {
        lift.Set(frc::Relay::kForward);  // move lift up
    } else if (turretStick.GetRawButton(7)) {
        lift.Set(frc::Relay::kReverse);  // move lift down
    } else {
        lift.Set(frc::Relay::kOff);  // turn off lift
    }

    // Bridge arm
    if (driveStick2.GetRawButtonPressed(1)) {
        auto armState = bridgeArm.Get();

        /* Toggles state of bridge arm between Retracted and Deployed
         * (Doesn't toggle if the arm is transitioning)
         */
        if (armState == LockSolenoid::State::kRetracted) {
            bridgeArm.Set(LockSolenoid::State::kDeployed);
        } else if (armState == LockSolenoid::State::kDeployed) {
            bridgeArm.Set(LockSolenoid::State::kRetracted);
        }
    }

    // Makes sure bridge arm completed transitioning between states
    bridgeArm.Update();

    drivetrain.CurvatureDrive(driveStick1.GetY(), driveStick2.GetX(),
                              driveStick2.GetRawButton(2));
}

#ifndef RUNNING_FRC_TESTS
int main() { return frc::StartRobot<Robot>(); }
#endif
<|endoftext|>