/*
 * Main program.
 */
int main() {
    if (RANDOM_USE_SEED) {
        setRandomSeed(106);
    }

    setConsoleLocation(WINDOW_WIDTH + 6 * kMargin, 30);   // temporary
    setConsoleSize(450, 400);
    setConsoleEventOnClose(true);
    initializeGUI();
    Point guiLoc = gWindow->getLocation();
    GDimension guiSize = gWindow->getSize();
    setConsoleLocation(
        guiLoc.getX() + guiSize.getWidth() + kMargin,
        guiLoc.getY());

    // Main event loop to process events as they happen.
    while (true) {
        GEvent e = waitForEvent(ACTION_EVENT | MOUSE_EVENT | WINDOW_EVENT);
        if (e.getEventType() == MOUSE_CLICKED || e.getEventType() == MOUSE_MOVED) {
            processMouseEvent(GMouseEvent(e));
        } else if (e.getEventClass() == ACTION_EVENT) {
            processActionEvent(GActionEvent(e));
        } else if (e.getEventClass() == WINDOW_EVENT) {
            processWindowEvent(GWindowEvent(e));
        }
    }
    return 0;
}
/*
 * Main program.
 */
int main() {
    if (RANDOM_USE_SEED) {
        setRandomSeed(106);
    }
    
    intro();

    // create GUI window and position the console to its right
    setConsoleLocation(WorldGrid::WINDOW_WIDTH + 6 * WorldAbstract::WINDOW_MARGIN, 20);   // temporary
    // setConsoleSize(CONSOLE_WIDTH, CONSOLE_HEIGHT);
    setConsoleEventOnClose(true);
    
    TrailblazerGUI gui(WINDOW_TITLE);
    gui.snapConsoleLocation();

    // main event loop to process events as they happen
    while (true) {
        GEvent e = waitForEvent(ACTION_EVENT | MOUSE_EVENT | WINDOW_EVENT);
        if (e.getEventType() == MOUSE_CLICKED || e.getEventType() == MOUSE_MOVED) {
            gui.processMouseEvent(GMouseEvent(e));
        } else if (e.getEventClass() == ACTION_EVENT) {
            gui.processActionEvent(GActionEvent(e));
        } else if (e.getEventClass() == WINDOW_EVENT) {
            gui.processWindowEvent(GWindowEvent(e));
        }
    }
    return 0;
}
Beispiel #3
0
/***********************************************************************//**
 * @brief Return instrument response to diffuse source
 *
 * @param[in] event Observed event.
 * @param[in] source Source.
 * @param[in] obs Observation.
 * @return Instrument response to diffuse source.
 *
 * Returns the instrument response to a specified diffuse source.
 *
 * The method uses a pre-computation cache to store the instrument response
 * for the spatial model component. The pre-computation cache is initialised
 * if no cache has yet been allocated, or if at the beginning of a scan over
 * the events, the model parameters have changed. The beginning of a scan is
 * defined by an event bin index of 0.
 ***************************************************************************/
double GCTAResponseCube::irf_diffuse(const GEvent&       event,
                                     const GSource&      source,
                                     const GObservation& obs) const
{
    // Initialise IRF
    double irf = 0.0;

    // Get pointer to CTA event bin
    if (!event.is_bin()) {
        std::string msg = "The current event is not a CTA event bin. "
                          "This method only works on binned CTA data. Please "
                          "make sure that a CTA observation containing binned "
                          "CTA data is provided.";
        throw GException::invalid_value(G_IRF_DIFFUSE, msg);
    }
    const GCTAEventBin* bin = static_cast<const GCTAEventBin*>(&event);

    // Get pointer to source cache. We first search the cache for a model
    // with the source name. If no model was found we initialise a new
    // cache entry for that model. Otherwise, we simply return the actual
    // cache entry.
    GCTACubeSourceDiffuse* cache(NULL);
    int index = cache_index(source.name());
    if (index == -1) {
    
        // No cache entry was found, thus allocate and initialise a new one
        cache = new GCTACubeSourceDiffuse;
        cache->set(source.name(), *source.model(), obs);
        m_cache.push_back(cache);

    } // endif: no cache entry was found
    else {
    
        // Check that the cache entry is of the expected type
        if (m_cache[index]->code() != GCTA_CUBE_SOURCE_DIFFUSE) {
            std::string msg = "Cached model \""+source.name()+"\" is not "
                              "an extended source model. This method only "
                              "applies to extended source models.";
            throw GException::invalid_value(G_IRF_DIFFUSE, msg);
        }
        cache = static_cast<GCTACubeSourceDiffuse*>(m_cache[index]);

    } // endelse: there was a cache entry for this model

    // Determine IRF value
    irf = cache->irf(bin->ipix(), bin->ieng());

    // Compile option: Check for NaN/Inf
    #if defined(G_NAN_CHECK)
    if (gammalib::is_notanumber(irf) || gammalib::is_infinite(irf)) {
        std::cout << "*** ERROR: GCTAResponseCube::irf_diffuse:";
        std::cout << " NaN/Inf encountered";
        std::cout << " irf=" << irf;
        std::cout << std::endl;
    }
    #endif

    // Return IRF value
    return irf;
}
/* Main program. */
int main() {
  State state;
  initializeWindow();
  initializeState(state);
  drawWorld(state.world);
	
  /* Process events as they happen. */
  while (true) {
    GEvent e = waitForEvent(ACTION_EVENT | MOUSE_EVENT);
    if (e.getEventType() == MOUSE_CLICKED) {
      processMouseEvent(state, GMouseEvent(e));
    } else if (e.getEventClass() == ACTION_EVENT) {
      processActionEvent(state, GActionEvent(e));
    }
  }
}
void test_front_back() {
    string colors[3] = {"blue", "red", "green"};
    const int objWidth = 100;
    const int objHeight = 100;
    const int x0 = 100;
    const int y0 = 100;
    const int dx = 40;
    const int dy = 0;
    GButton *forward = new GButton("Cycle Forward");
    GButton *backward = new GButton("Cycle Backward");
    GButton *stepUp = new GButton("Backmost +1");
    GButton *stepDown = new GButton("Frontmost -1");
    Vector<GObject *> objects;
    gw->addToRegion(forward, "south");
    gw->addToRegion(backward, "south");
    gw->addToRegion(stepUp, "south");
    gw->addToRegion(stepDown, "south");
    GCompound *compound = new GCompound();
    for (int i = 0; i < 3; i++) {
        GOval *oval = new GOval(x0 + i*dx, y0 + i*dy, objWidth, objHeight);
        if (i == 1)
            oval->setLocation(oval->getLocation().getX(), oval->getLocation().getY() + 50);
        oval->setFilled(true);
        oval->setFillColor(colors[i]);
        objects.add(oval);
        compound->add(oval);
    }
    gw->add(new GLabel("Click in window to end test", 10, 30));
    gw->add(compound);
    while(true) {
        GEvent e = waitForEvent(ACTION_EVENT | CLICK_EVENT);
        if (e.getEventType() == MOUSE_CLICKED)
            break;
        else if (e.getEventType() == ACTION_PERFORMED) {
            string cmd = ((GActionEvent) e).getActionCommand();
            if (cmd == "Cycle Forward")
                cycleObjects(objects);
            if (cmd == "Cycle Backward")
                cycleObjects(objects, false);
            if (cmd == "Backmost +1")
                moveBottomUp(objects);
            if (cmd == "Frontmost -1")
                moveTopDown(objects);
        }
    }

}
Beispiel #6
0
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            Specified observation is not of the expected type.
 ***************************************************************************/
double GCTAModelCubeBackground::eval(const GEvent&       event,
                                     const GObservation& obs) const
{
    // Get pointer on CTA observation
    const GCTAObservation* cta = dynamic_cast<const GCTAObservation*>(&obs);
    if (cta == NULL) {
        std::string msg = "Specified observation is not a CTA observation.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Get pointer on CTA IRF response
    const GCTAResponseCube* rsp = dynamic_cast<const GCTAResponseCube*>(cta->response());
    if (rsp == NULL) {
        std::string msg = "Specified observation does not contain a cube response.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Extract CTA instrument direction from event
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Retrieve reference to CTA cube background
    const GCTACubeBackground& bgd = rsp->background();

    // Evaluate function
    //double logE = event.energy().log10TeV();
    double spat = bgd((*dir), event.energy());
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time()) : 1.0;

    // Compute value. Note that background rates are already per
    // livetime, hence no deadtime correction is needed here.
    double value = spat * spec * temp;

    // Return value
    return value;
}
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            Specified observation is not of the expected type.
 *
 * @todo Make sure that DETX and DETY are always set in GCTAInstDir.
 ***************************************************************************/
double GCTAModelIrfBackground::eval(const GEvent& event,
                                    const GObservation& obs) const
{
    // Get pointer on CTA observation
    const GCTAObservation* cta = dynamic_cast<const GCTAObservation*>(&obs);
    if (cta == NULL) {
        std::string msg = "Specified observation is not a CTA observation.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Get pointer on CTA IRF response
    const GCTAResponseIrf* rsp = dynamic_cast<const GCTAResponseIrf*>(cta->response());
    if (rsp == NULL) {
        std::string msg = "Specified observation does not contain an IRF response.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Retrieve pointer to CTA background
    const GCTABackground* bgd = rsp->background();
    if (bgd == NULL) {
        std::string msg = "Specified observation contains no background"
                          " information.\n" + obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Extract CTA instrument direction from event
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Set DETX and DETY in instrument direction
    GCTAInstDir inst_dir = cta->pointing().instdir(dir->dir());

    // Evaluate function
    double logE = event.energy().log10TeV();
    double spat = (*bgd)(logE, inst_dir.detx(), inst_dir.dety());
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time()) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    value *= obs.deadc(event.time());

    // Return value
    return value;
}
Beispiel #8
0
/***********************************************************************//**
 * @brief Perform integration over spectral component
 *
 * @param[in] event Observed event.
 * @param[in] srcTime True photon arrival time.
 * @param[in] obs Observation.
 * @param[in] grad Evaluate gradients.
 *
 * @exception GException::no_response
 *            Observation has no valid instrument response
 * @exception GException::feature_not_implemented
 *            Energy integration not yet implemented
 *
 * This method integrates the source model over the spectral component. If
 * the response function has no energy dispersion then no spectral
 * integration is needed and the observed photon energy is identical to the
 * true photon energy.
 *
 * @todo Needs implementation of spectral integration to handle energy
 *       dispersion.
 ***************************************************************************/
double GModelSky::spectral(const GEvent& event, const GTime& srcTime,
                           const GObservation& obs, bool grad) const
{
    // Initialise result
    double value = 0.0;

    // Get response function
    GResponse* rsp = obs.response();
    if (rsp == NULL) {
        throw GException::no_response(G_SPECTRAL);
    }

    // Determine if energy integration is needed
    bool integrate = rsp->hasedisp();

    // Case A: Integraion
    if (integrate) {
        throw GException::feature_not_implemented(G_SPECTRAL);
    }

    // Case B: No integration (assume no energy dispersion)
    else {
        value = spatial(event, event.energy(), srcTime, obs, grad);
    }

    // Compile option: Check for NaN/Inf
#if defined(G_NAN_CHECK)
    if (isnotanumber(value) || isinfinite(value)) {
        std::cout << "*** ERROR: GModelSky::spectral:";
        std::cout << " NaN/Inf encountered";
        std::cout << " (value=" << value;
        std::cout << ", event=" << event;
        std::cout << ", srcTime=" << srcTime;
        std::cout << ")" << std::endl;
    }
#endif

    // Return value
    return value;
}
Beispiel #9
0
bool EventViewer::onEvent(const GEvent& e, App* app) {
    if (e.type == GEventType::MOUSE_MOTION) {
        if (! m_showMouseMoveEvents) {
            // Don't print this event
            return false;
        } else {
            // Condense mouse move events
            if (m_lastEventWasMouseMove) {
                // Replace the last event
                eventQueue.popBack();
            }

            m_lastEventWasMouseMove = true;
        }
    } else {
        m_lastEventWasMouseMove = false;
    }

    eventQueue.pushBack("[" + System::currentTimeString() + "]  " + e.toString());
    
    return false;
}
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            No CTA instrument direction found in event.
 *
 * Evaluates tha CTA background model which is a factorization of a
 * spatial, spectral and temporal model component. This method also applies
 * a deadtime correction factor, so that the normalization of the model is
 * a real rate (counts/exposure time).
 *
 * @todo Add bookkeeping of last value and evaluate only if argument 
 *       changed
 ***************************************************************************/
double GCTAModelBackground::eval(const GEvent& event,
                                 const GObservation& obs) const
{
    // Get pointer on CTA observation
    const GCTAObservation* ctaobs = dynamic_cast<const GCTAObservation*>(&obs);
    if (ctaobs == NULL) {
        std::string msg = "Specified observation is not a CTA observation.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Extract CTA instrument direction
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Create a Photon from the event.
    // We need the GPhoton to evaluate the spatial model.
    // For the background, GEvent and GPhoton are identical
    // since the IRFs are not folded in
    GPhoton photon(dir->dir(), event.energy(), event.time());

    // Evaluate function and gradients
    double spat = (spatial() != NULL)
                  ? spatial()->eval(photon) : 1.0;
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time()) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    value *= obs.deadc(event.time());

    // Return
    return value;
}
Beispiel #11
0
bool GuiButton::onEvent(const GEvent& event) {
    switch (event.type) {
    case GEventType::MOUSE_BUTTON_DOWN:
        m_down = true;
        // invoke the pre-event handler
        m_callback.execute();
        fireEvent(GEventType::GUI_DOWN);
        return true;
    
    case GEventType::MOUSE_BUTTON_UP:
        fireEvent(GEventType::GUI_UP);

        // Only trigger an action if the mouse was still over the control
        if (m_down && m_rect.contains(event.mousePosition())) {
            fireEvent(GEventType::GUI_ACTION);
        }

        m_down = false;
        return true;
    }

    return false;
}
void gtableTest() {
    GWindow gw;
    gw.setTitle("GTable Test");
    
    GTable* table = new GTable(5, 3);
    // table->setColor("#0000cc");
    // table->setFont("Monospaced-Bold-20");
    // table->setHorizontalAlignment(GTable::Alignment::RIGHT);
    table->select(0, 1);
    gw.addToRegion(table, "NORTH");
    
//    GTable* table2 = new GTable(4, 2, 0, 0, 100, 400);
//    gw.addToRegion(table2, "EAST");
    
    GButton* buttget = new GButton("Get All");
    gw.addToRegion(buttget, "SOUTH");
    
    GButton* buttset = new GButton("Set All");
    gw.addToRegion(buttset, "SOUTH");
    
    GButton* buttclear = new GButton("Clear");
    gw.addToRegion(buttclear, "SOUTH");
    
    GButton* buttrowadd = new GButton("+R");
    gw.addToRegion(buttrowadd, "SOUTH");
    
    GButton* buttrowrem = new GButton("-R");
    gw.addToRegion(buttrowrem, "SOUTH");
    
    GButton* buttcoladd = new GButton("+C");
    gw.addToRegion(buttcoladd, "SOUTH");
    
    GButton* buttcolrem = new GButton("-C");
    gw.addToRegion(buttcolrem, "SOUTH");
    
    GButton* buttwidthadd = new GButton("+W");
    gw.addToRegion(buttwidthadd, "SOUTH");
    
    GButton* buttwidthrem = new GButton("-W");
    gw.addToRegion(buttwidthrem, "SOUTH");
    
    gw.setVisible(true);
    
    while (true) {
        GEvent event = waitForEvent(ACTION_EVENT | TABLE_EVENT | WINDOW_EVENT);
        if (event.getEventClass() == ACTION_EVENT) {
            GActionEvent actionEvent(event);
            if (actionEvent.getSource() == buttget) {
                for (int row = 0; row < table->numRows(); row++) {
                    for (int col = 0; col < table->numCols(); col++) {
                        cout << "R" << row << "C" << col << "=\"" << table->get(row, col) << "\" ";
                    }
                    cout << endl;
                }
                int row, col;
                table->getSelectedCell(row, col);
                cout << "selected: R" << row << "C" << col << endl;
            } else if (actionEvent.getSource() == buttset) {
                for (int row = 0; row < table->numRows(); row++) {
                    for (int col = 0; col < table->numCols(); col++) {
                        std::string value = "R" + integerToString(row) + "C" + integerToString(col);
                        table->set(row, col, value);
                    }
                }
                table->select(1, 2);
            } else if (actionEvent.getSource() == buttclear) {
                table->clear();
            } else if (actionEvent.getSource() == buttrowadd) {
                table->resize(table->numRows() + 1, table->numCols());
            } else if (actionEvent.getSource() == buttrowrem) {
                table->resize(table->numRows() - 1, table->numCols());
            } else if (actionEvent.getSource() == buttcoladd) {
                table->resize(table->numRows(), table->numCols() + 1);
            } else if (actionEvent.getSource() == buttcolrem) {
                table->resize(table->numRows(), table->numCols() - 1);
            } else if (actionEvent.getSource() == buttwidthadd) {
                table->setColumnWidth(1, table->getColumnWidth(1) + 20);
            } else if (actionEvent.getSource() == buttwidthrem) {
                table->setColumnWidth(1, table->getColumnWidth(1) - 20);
            }
        } else if (event.getEventClass() == WINDOW_EVENT) {
            if (event.getEventType() == WINDOW_CLOSED) {
                break;
            }
        } else if (event.getEventClass() == TABLE_EVENT) {
            GTableEvent tableEvent(event);
            std::cout << "cell updated: " << tableEvent.toString() << std::endl;
        }
    }
}
Beispiel #13
0
/***********************************************************************//**
 * @brief Convolve sky model with the instrument response
 *
 * @param[in] model Sky model.
 * @param[in] event Event.
 * @param[in] obs Observation.
 * @param[in] grad Should model gradients be computed? (default: true)
 * @return Event probability.
 *
 * Computes the event probability
 *
 * \f[
 *    P(p',E',t') = \int \int \int
 *                  S(p,E,t) \times R(p',E',t'|p,E,t) \, dp \, dE \, dt
 * \f]
 *
 * without taking into account any time dispersion. Energy dispersion is
 * correctly handled by this method. If time dispersion is indeed needed,
 * an instrument specific method needs to be provided.
 ***************************************************************************/
double GResponse::convolve(const GModelSky&    model,
                           const GEvent&       event,
                           const GObservation& obs,
                           const bool&         grad) const
{
    // Set number of iterations for Romberg integration.
    static const int iter = 6;

    // Initialise result
    double prob = 0.0;

    // Continue only if the model has a spatial component
    if (model.spatial() != NULL) {

        // Get source time (no dispersion)
        GTime srcTime = event.time();

        // Case A: Integration
        if (use_edisp()) {
    
            // Retrieve true energy boundaries
            GEbounds ebounds = this->ebounds(event.energy());
    
            // Loop over all boundaries
            for (int i = 0; i < ebounds.size(); ++i) {

                // Get boundaries in MeV
                double emin = ebounds.emin(i).MeV();
                double emax = ebounds.emax(i).MeV();

                // Continue only if valid
                if (emax > emin) {

                    // Setup integration function
                    edisp_kern integrand(this, &obs, &model, &event, srcTime, grad);
                    GIntegral  integral(&integrand);

                    // Set number of iterations
                    integral.fixed_iter(iter);

                    // Do Romberg integration
                    emin  = std::log(emin);
                    emax  = std::log(emax);
                    prob += integral.romberg(emin, emax);
    
                } // endif: interval was valid

            } // endfor: looped over intervals

        }

        // Case B: No integration (assume no energy dispersion)
        else {
    
            // Get source energy (no dispersion)
            GEnergy srcEng  = event.energy();

            // Evaluate probability
            prob = eval_prob(model, event, srcEng, srcTime, obs, grad);

        }

        // Compile option: Check for NaN/Inf
        #if defined(G_NAN_CHECK)
        if (gammalib::is_notanumber(prob) || gammalib::is_infinite(prob)) {
            std::cout << "*** ERROR: GResponse::convolve:";
            std::cout << " NaN/Inf encountered";
            std::cout << " (prob=" << prob;
            std::cout << ", event=" << event;
            std::cout << ", srcTime=" << srcTime;
            std::cout << ")" << std::endl;
        }
        #endif

    } // endif: spatial component valid

    // Return probability
    return prob;
}
Beispiel #14
0
 virtual double          eval_gradients(const GEvent& event,
                                        const GObservation& obs) const {
                             double result = m_modelTps->eval_gradients(event.time());
                             return result;
                         }
void test_contains_and_getBounds() {
    bool useCompounds = false;
    int x0 = 350;
    int y0 = 300;
    Map<string, GObject*> shapeMap;
    GOval *oval = new GOval(x0, y0, 200, 100);
    GRoundRect *roundRect = new GRoundRect(x0, y0, 200, 100, 300);
    roundRect->setLineWidth(20);
    G3DRect *rect3d = new G3DRect(x0, y0, 200, 100, true);
    //rect3d->setLineWidth(5);
    rect3d->setFillColor("green");
    rect3d->setFilled(true);
    GPolygon *poly = new GPolygon;
    poly->addVertex(0, 0);
    poly->addEdge(200, 100);
    poly->addEdge(-200, 0);
    poly->setLocation(x0, y0);
    GPolygon *cpoly = new GPolygon;
    cpoly->addVertex(0, 0);
    cpoly->addEdge(200, 100);
    cpoly->addEdge(0, -100);
    cpoly->addEdge(-200, 100);
    cpoly->setLocation(x0, y0);
    GRect *rect = new GRect(x0, y0, 200, 100);
    GLine *line = new GLine(x0, y0, x0 + 200, y0 + 100);
    GLabel *label = new GLabel("Ostromantus", x0, y0);
    GArc *arc = new GArc(x0, y0, 350, 350, 0, 90);
    //arc->setLineWidth(5);
    arc->setColor("#44000000");
    GArc *filledArc = new GArc(x0, y0, 350, 100, 45, 225);
    filledArc->setFillColor("#88e0e0e0");
    filledArc->setFilled(true);
    GCompound *comp1 = new GCompound;
    comp1->setLocation(x0, y0);
    comp1->add(new GLabel("compound", 0, 15));
    GRect *bgRect1 = new GRect(0, 0);
    gw->add(bgRect1);
    bgRect1->setFillColor("#55dddddd");
    bgRect1->setFilled(true);
    GImage *image = new GImage("homer-transparent.png");
    image->setLocation(x0, y0);
    GCompound *comp = new GCompound;
    comp->setLocation(x0, y0);
    GRect *compRect = new GRect(20, 20, 100, 100);
    GOval *compOval = new GOval(90, 90, 150, 70);
    comp->add(compRect);
    comp->add(compOval);
    GButton *button = new GButton("Testo");
    button->setSize(200, 100);
    button->setLocation(x0, y0);
    shapeMap.put("oval", oval);
    shapeMap.put("rounded rectangle", roundRect);
    shapeMap.put("3D rectangle", rect3d);
    shapeMap.put("polygon", poly);
    shapeMap.put("crazy polygon", cpoly);
    shapeMap.put("rectangle", rect);
    shapeMap.put("line", line);
    shapeMap.put("arc", arc);
    shapeMap.put("filled arc", filledArc);
    shapeMap.put("label", label);
    shapeMap.put("image", image);
    shapeMap.put("compound", comp);
    shapeMap.put("button", button);

    GObject *currObj;
    GChooser *ch = new GChooser;
    ch->setActionCommand("chooser");
    ch->addItem("oval");
    ch->addItem("rounded rectangle");
    ch->addItem(("3D rectangle"));
    ch->addItem("polygon");
    ch->addItem("crazy polygon");
    ch->addItem("rectangle");
    ch->addItem("line");
    ch->addItem("arc");
    ch->addItem("filled arc");
    ch->addItem("label");
    ch->addItem("image");
    ch->addItem("compound");
    ch->addItem("button");
    ch->setSelectedItem("rectangle");
    currObj = rect;

    GButton *endButton = new GButton("End test");
    GButton *fillButton = new GButton("Auto-fill");
    GButton *rotateButton = new GButton("Rotate");
    GButton *scaleButton = new GButton("Scale");

    GCheckBox *compCheckbox = new GCheckBox("compounds");
    compCheckbox->setActionCommand("compounds");
    gw->addToRegion(compCheckbox, "north");
    gw->addToRegion(ch, "north");
    gw->addToRegion(rotateButton, "north");
    gw->addToRegion(scaleButton, "north");
    gw->addToRegion(fillButton, "north");
    gw->addToRegion(endButton, "north");

    while (true) {
        GEvent e = waitForEvent(ACTION_EVENT | MOUSE_EVENT);
        if (!e.isValid())
            continue;
        if (e.getEventClass() == ACTION_EVENT) {
            if (((GActionEvent) e).getActionCommand() == "End test")
                break;
            if (((GActionEvent) e).getActionCommand() == "compounds") {
                bgRect1->setVisible(compCheckbox->isSelected());
                useCompounds = compCheckbox->isSelected();
            }
            if (((GActionEvent) e).getActionCommand() == "Testo") {
                GPoint pt = button->getLocation();
                button->setLocation(pt.getX()-button->getWidth()-10, pt.getY());
                pause(1000);
                button->setLocation(pt);
            }
            if (((GActionEvent) e).getActionCommand() == "Auto-fill") {
                GRectangle bds = currObj->getBounds();
                int xmin = bds.getX();
                int ymin = bds.getY();
                int xmax = bds.getX() + bds.getWidth();
                int ymax = bds.getY() + bds.getHeight();
                int dx = useCompounds ? comp1->getX(): 0;
                int dy = useCompounds ? comp1->getY(): 0;
                for (int y = ymin; y < ymax; y+=1)
                    for (int x = xmin; x < xmax; x+=1) {
                        if (currObj->contains(x, y)) {
                            gw->setColor("red");
                            gw->fillOval(x + dx, y + dy, 1, 1);
                        } else {
                            gw->setColor("green");
                            gw->fillOval(x + dx, y + dy, 1, 1);
                        }
                    }
            }

            if (((GActionEvent) e).getActionCommand() == "Rotate") {
                currObj->rotate(45);
                if (useCompounds) {
                    bgRect1->setBounds(comp1->getBounds());
                }
            }
            if (((GActionEvent) e).getActionCommand() == "Scale") {
                currObj->scale(1.2, 0.8);
                if (useCompounds) {
                    bgRect1->setBounds(comp1->getBounds());
                }
            }
            if (((GActionEvent) e).getActionCommand() == "chooser") {
                string shape = ch->getSelectedItem();
                if (useCompounds) {
                    comp1->remove(currObj);
                    gw->remove(comp1);
                } else {
                    gw->remove(currObj);
                }
                gw->setColor("white");
                gw->fillRect(0, 0, gw->getCanvasWidth(), gw->getCanvasHeight());
                //drawGrid();
                gw->setColor("black");
                currObj = shapeMap.get(shape);
                if (useCompounds) {
                    gw->add(comp1);
                    comp1->add(currObj, 50, 50);
                    bgRect1->setBounds(comp1->getBounds());
                } else {
                    gw->add(currObj);
                }
                gw->drawOval(currObj->getX()-2, currObj->getY()-2, 4, 4);
            }
        } else if (e.getEventType() == MOUSE_CLICKED) {
            double x = ((GMouseEvent) e).getX();
            double y = ((GMouseEvent) e).getY();
            if (currObj->contains(x, y)) {
                gw->setColor("red");
                gw->fillOval(x, y, 1, 1);
            }
        }
    }
}
/*
 * Runs and tests your floodFill function.
 */
void test_floodFill() {
    GObject::setAntiAliasing(false);
    floodFillWindow = new GWindow(FLOOD_WINDOW_WIDTH, FLOOD_WINDOW_HEIGHT);
    floodFillWindow->setWindowTitle("CS 106X Flood Fill");
    // floodFillWindow->center();
    // floodFillWindow->setRepaintImmediately(false);

    Map<string, int> colorMap;
    colorMap["Red"]    = 0x8c1515;   // Stanford red
    colorMap["Yellow"] = 0xeeee00;   // yellow
    colorMap["Blue"]   = 0x0000cc;   // blue
    colorMap["Green"]  = 0x00cc00;   // green
    colorMap["Purple"] = 0xcc00cc;   // purple
    colorMap["Orange"] = 0xff8800;   // orange
    Vector<string> colorVector = colorMap.keys();

    GLabel* fillLabel = new GLabel("Fill color:");
    GChooser* colorList = new GChooser();
    for (string key : colorMap) {
        colorList->addItem(key);
    }
    floodFillWindow->addToRegion(fillLabel, "SOUTH");
    floodFillWindow->addToRegion(colorList, "SOUTH");

    // use buffered image to store individual pixels
    if (floodFillPixels) {
        delete floodFillPixels;
        floodFillPixels = NULL;
    }
    floodFillPixels = new GBufferedImage(
                /* x */ 0,
                /* y */ 0,
                /* width */ FLOOD_WINDOW_WIDTH,
                /* height */ FLOOD_WINDOW_HEIGHT,
                /* rgb fill */ 0xffffff);

    // draw several random shapes
#ifdef FLOOD_FILL_RANDOM_SEED
    setRandomSeed(FLOOD_FILL_RANDOM_SEED);
#endif // FLOOD_FILL_RANDOM_SEED

    for (int i = 0; i < FLOOD_FILL_NUM_SHAPES; i++) {
        double x = randomInteger(0, FLOOD_WINDOW_WIDTH  - 100);
        double y = randomInteger(0, FLOOD_WINDOW_HEIGHT - 100);
        double w = randomInteger(20, 100);
        double h = randomInteger(20, 100);
        int color = colorMap[colorVector[randomInteger(0, colorVector.size() - 1)]];
        floodFillPixels->fillRegion(x, y, w, h, color);
    }
    floodFillWindow->add(floodFillPixels);

    // main event loop to process events as they happen
    while (true) {
        GEvent e = waitForEvent(MOUSE_EVENT | WINDOW_EVENT);
        if (e.getEventClass() == MOUSE_EVENT) {
            if (e.getEventType() != MOUSE_CLICKED) { continue; }
            colorList->setEnabled(false);
            GMouseEvent mouseEvent(e);
            string colorStr = colorList->getSelectedItem();
            int color = colorMap[colorStr];
            int mx = (int) mouseEvent.getX();
            int my = (int) mouseEvent.getY();
            cout << "Flood fill at (x=" << dec << mx << ", y=" << my << ")"
                 << " with color " << hex << setw(6) << setfill('0') << color
                 << dec << endl;
            floodFill(*floodFillPixels, mx, my, color);
            colorList->setEnabled(true);
            // floodFillWindow->repaint();
        } else if (e.getEventClass() == WINDOW_EVENT) {
            if (e.getEventType() == WINDOW_CLOSED) {
                // make sure that it was the flood fill window that got closed
                if (!floodFillWindow->isOpen() || !floodFillWindow->isVisible()) {
                    break;
                }
            }
        }
    }
    cout << resetiosflags(ios::fixed | ios::floatfield);
}
int main()
{
    int consoleX = 10;
    int consoleY = 10;
    setConsoleSize(600, 400);
    setConsoleFont("Monospaced-14");
    setConsoleExitProgramOnClose(true);
    setConsolePrintExceptions(true);

    extern int _mainFlags;
    if (_mainFlags & CONSOLE_FLAG) cout << "CONSOLE_FLAG set" << endl;
    if (_mainFlags & GRAPHICS_FLAG) cout << "GRAPHICS_FLAG set" << endl;
    if (_mainFlags & JBEMISC_FLAG) cout << "JBEMISC_FLAG set" << endl;

    GWindow gw(800, 300);

    setConsoleLocation(0, 300 + 50);
    gw.setColor("red");
    double winWidth = gw.getWidth();
    double winHeight = gw.getHeight();
    for (int i = 0; i < winWidth; i += 100)
        gw.drawLine(i, 0, i, winHeight);
    for (int j = 0; j < winHeight; j += 100)
        gw.drawLine(0, j, winWidth, j);
    gw.setColor("black");

    cout << "Screen size: " << getScreenWidth() << "x" << getScreenHeight() << endl;
    cout << "GWindow size: " << gw.getWidth() << "x" << gw.getHeight() << endl;
    cout << "Canvas size before adding interactors: " << gw.getCanvasWidth()
         << "x" << gw.getCanvasHeight() << endl;

    gw.setWindowTitle("Silly GUI Events Tester");

    GButton *button = new GButton("Shift Rectangle and Console");
    GButton *quitButton = new GButton("Quit");
    GCheckBox *cb = new GCheckBox("check here");
    GChooser *chooser = new GChooser();
    GSlider *slider = new GSlider(0, 100, 30);
    GTextField *textField = new GTextField();
    chooser->addItem("Up");
    chooser->addItem("Down");
    chooser->setSelectedItem("Up");
    chooser->setActionCommand("choosey");
    cb->setActionCommand("gurgle");
    slider->setActionCommand("slidey");
    textField->setActionCommand("texty");
    gw.setColor("red");

    GRect rect = GRect(40, 40, 60, 30);
    rect.setColor("#aa00cc98");
    cout << "rect.getColor(): " << rect.getColor() << endl;
    cout << "2309667788: " << convertRGBToColor(2309667788) << endl;
    cout << "magenta: " << hex << (unsigned) convertColorToRGB("gray") << endl;
    cout << "convertColorToRGB(#66ffc800): " << convertColorToRGB("#66ffc800") << endl;
    cout << "convertColorToRGB(#ffc800): " << convertColorToRGB("#ffc800") << endl;
    rect.setLineWidth(10);
    gw.add(&rect);

    gw.addToRegion(textField, "NORTH");
    gw.addToRegion(button, "SOUTH");
    gw.addToRegion(cb, "EAST");
    gw.addToRegion(chooser, "SOUTH");
    gw.addToRegion(quitButton, "south");
    gw.addToRegion(slider, "WEST");

    cout << "Canvas size after adding interactors: " << gw.getCanvasWidth()
         << "x" << gw.getCanvasHeight() << endl;

    gw.add(new GLabel("Click in here and type!", 300, 20));

    // Draw background grid for calibration
    for (int i = 0; i < winWidth; i += 100)
        gw.drawLine(i, 0, i, winHeight);
    for (int j = 0; j < winHeight; j += 100)
        gw.drawLine(0, j, winWidth, j);

    double cx = gw.getCanvasWidth() / 2;
    double cy = gw.getCanvasHeight() / 2;
    double r = 25;
    GArc *pacman = new GArc(cx - r, cy - r, 2 * r, 2 * r, 45, 270);
    pacman->setFilled(true);
    pacman->setFillColor(0x20cccccc); // fairly transparent gray
    gw.add(pacman);

    string ans = getLine("remove checkbox? (y/n) ");
    if (startsWith(ans, "y"))
        gw.removeFromRegion(cb, "EAST");

    ans = getLine("Clear console? (y/n) ");
    if (startsWith(ans, "y"))
        clearConsole();

    GButton *naked = new GButton("naked");
    gw.add(naked, 200, 180);

    cout.setf(ios::fixed);
    cout << dec;
    while (true)
    {
        GEvent e = waitForEvent();
        EventType type = e.getEventType();
        if (type == KEY_RELEASED || type == MOUSE_MOVED
                ||type == MOUSE_PRESSED||type == MOUSE_RELEASED)
            continue; // ignore these
        int eclass = e.getEventClass();
        int mods = e.getModifiers();
        string modstr = "";
        if (mods & SHIFT_DOWN) modstr += "SHIFT ";
        if (mods & CTRL_DOWN) modstr += "CTRL ";
        if (mods & META_DOWN) modstr += "META ";
        if (mods & ALT_DOWN) modstr += "ALT ";
        if (mods & ALT_GRAPH_DOWN) modstr += "ALTGRAPH ";
        if (mods & BUTTON1_DOWN) modstr += "BUT1 ";
        if (mods & BUTTON2_DOWN) modstr += "BUT2 ";
        if (mods & BUTTON3_DOWN) modstr += "BUT3 ";

        cout << e.toString() << endl;
        cout << "\tTime: " << setprecision(0) << e.getEventTime() << endl;
        cout << "\tModifiers: " << modstr << endl;

        if (eclass==ACTION_EVENT)
        {
            GActionEvent ae(e);
            string cmd = ae.getActionCommand();
            if (ae.getSource() == quitButton)
                exitGraphics();
            cout << "\tSource: " << ae.getSource()->toString() << " @ " << ae.getSource() << endl;
            cout << "\tActionCommand: " << cmd << endl;
            if (cmd == "choosey")
            {
                cout << "\tItem Selected: " << chooser->getSelectedItem() << endl;
            }
            if (cmd == "slidey")
            {
                cout << "\tCurrent Value: " << slider->getValue() << endl;
            }
            if (cmd == "texty")
            {
                cout << "\tText: " << textField->getText() << endl;
            }
            if (cmd == "gurgle")
            {
                cout << "\tSelected: " << boolToString(cb->isSelected()) << endl;
            }
            if (ae.getSource() == button)
            {
                GPoint p = rect.getLocation();
                if (chooser->getSelectedItem()=="Up")
                {
                    rect.setLocation(p.getX(), p.getY() - 5);
                    consoleX -= 10;
                    consoleY -= 10;
                    setConsoleLocation(consoleX, consoleY);
                    cout << "up" << endl;
                }
                else
                {
                    rect.setLocation(p.getX(), p.getY() + 5);
                    consoleX += 10;
                    consoleY += 10;
                    setConsoleLocation(consoleX, consoleY);
                    cout << "down" << endl;
                }
            }
        }
        if (eclass==WINDOW_EVENT)
        {
            GWindowEvent we(e);
            cout << "\tTitle: " << we.getGWindow().getWindowTitle() << endl;
            if (we.getEventType() == WINDOW_CLOSED) {
                break;
            }
        }
        if (eclass==MOUSE_EVENT)
        {
            GMouseEvent me(e);
            cout << "\tWindow Title: " << me.getGWindow().getWindowTitle() << endl;
            cout << "\t(x, y): " << "(" << me.getX() << ", " << me.getY() << ")" << endl;
        }
        if (eclass==KEY_EVENT)
        {
            GKeyEvent ke(e);
            cout << "\tWindow Title: " << ke.getGWindow().getWindowTitle() << endl;
            char keyChar = ke.getKeyChar();
            int keyCode = ke.getKeyCode();
            ostringstream oss;
            oss << "'";
            if (isprint(keyChar)) oss << keyChar;
            else oss << '\\' << oct << int(keyChar);
            oss << "'";
            cout << "\tKeyChar: " << oss.str() << endl;

            oss.str("");
            switch(keyCode)
            {
            case BACKSPACE_KEY:
                oss << "BACKSPACE_KEY";
                break;
            case TAB_KEY:
                oss << "TAB_KEY";
                break;
            case ENTER_KEY:
                oss << "ENTER_KEY";
                break;
            case CLEAR_KEY:
                oss << "CLEAR_KEY";
                break;
            case ESCAPE_KEY:
                oss << "ESCAPE_KEY";
                break;
            case PAGE_UP_KEY:
                oss << "PAGE_UP_KEY";
                break;
            case PAGE_DOWN_KEY:
                oss << "PAGE_DOWN_KEY";
                break;
            case END_KEY:
                oss << "END_KEY";
                break;
            case HOME_KEY:
                oss << "HOME_KEY";
                break;
            case LEFT_ARROW_KEY:
                oss << "LEFT_ARROW_KEY";
                break;
            case UP_ARROW_KEY:
                oss << "UP_ARROW_KEY";
                break;
            case RIGHT_ARROW_KEY:
                oss << "RIGHT_ARROW_KEY";
                break;
            case DOWN_ARROW_KEY:
                oss << "DOWN_ARROW_KEY";
                break;
            case F1_KEY:
                oss << "F1_KEY";
                break;
            case F2_KEY:
                oss << "F2_KEY";
                break;
            case F3_KEY:
                oss << "F3_KEY";
                break;
            case F4_KEY:
                oss << "F4_KEY";
                break;
            case F5_KEY:
                oss << "F5_KEY";
                break;
            case F6_KEY:
                oss << "F6_KEY";
                break;
            case F7_KEY:
                oss << "F7_KEY";
                break;
            case F8_KEY:
                oss << "F8_KEY";
                break;
            case F9_KEY:
                oss << "F9_KEY";
                break;
            case F10_KEY:
                oss << "F10_KEY";
                break;
            case F11_KEY:
                oss << "F11_KEY";
                break;
            case F12_KEY:
                oss << "F12_KEY";
                break;
            case DELETE_KEY:
                oss << "DELETE_KEY";
                break;
            case HELP_KEY:
                oss << "HELP_KEY";
                break;
            default:
                oss << "'";
                if (isprint(keyCode)) oss << char(keyCode);
                else oss << '\\' << oct << keyCode;
                oss << "'";
            }
            cout << "\tKeyCode: " << oss.str() << endl;
        }
    }
    return 0;
}
Beispiel #18
0
/*
 * Runs and tests your floodFill function.
 */
void test_floodFill() {
    GObject::setAntiAliasing(false);
    GWindow floodFillWindow(FLOOD_FILL_WINDOW_WIDTH, FLOOD_FILL_WINDOW_HEIGHT);
    floodFillWindow.setWindowTitle(FLOOD_FILL_WINDOW_TITLE);

    Map<string, int> colorMap;
    colorMap["Red"]    = 0x8c1515;   // Stanford red
    colorMap["Yellow"] = 0xeeee00;   // yellow
    colorMap["Blue"]   = 0x0000cc;   // blue
    colorMap["Green"]  = 0x00cc00;   // green
    colorMap["Purple"] = 0xcc00cc;   // purple
    colorMap["Orange"] = 0xff8800;   // orange
    Vector<string> colorVector = colorMap.keys();

    GLabel fillLabel("Fill color:");
    GChooser colorList;
    for (string key : colorMap) {
        colorList.addItem(key);
    }
    floodFillWindow.addToRegion(&fillLabel, "SOUTH");
    floodFillWindow.addToRegion(&colorList, "SOUTH");

    // use buffered image to store individual pixels
    GBufferedImage floodFillPixels(
                /* x */ 0,
                /* y */ 0,
                /* width */ FLOOD_FILL_WINDOW_WIDTH,
                /* height */ FLOOD_FILL_WINDOW_HEIGHT,
                /* rgb fill */ 0xffffff);
    
    // draw several random shapes
#ifdef FLOOD_FILL_RANDOM_SEED
    setRandomSeed(FLOOD_FILL_RANDOM_SEED);
#endif // FLOOD_FILL_RANDOM_SEED

    for (int i = 0; i < FLOOD_FILL_NUM_SHAPES; i++) {
        double w = randomInteger(FLOOD_FILL_MIN_RECT_SIZE, FLOOD_FILL_MAX_RECT_SIZE);
        double h = randomInteger(FLOOD_FILL_MIN_RECT_SIZE, FLOOD_FILL_MAX_RECT_SIZE);
        double x = randomInteger(0, FLOOD_FILL_WINDOW_WIDTH  - w);
        double y = randomInteger(0, FLOOD_FILL_WINDOW_HEIGHT - h - colorList.getHeight());
        int color = colorMap[colorVector[randomInteger(0, colorVector.size() - 1)]];
        floodFillPixels.fillRegion(x, y, w, h, color);
    }
    floodFillWindow.add(&floodFillPixels);

    // main event loop to process events as they happen
    while (true) {
        GEvent e = waitForEvent(MOUSE_EVENT | WINDOW_EVENT);
        if (e.getEventClass() == MOUSE_EVENT) {
            if (e.getEventType() != MOUSE_CLICKED) { continue; }
            colorList.setEnabled(false);
            GMouseEvent mouseEvent(e);
            string colorStr = colorList.getSelectedItem();
            int color = colorMap[colorStr];
            int mx = (int) mouseEvent.getX();
            int my = (int) mouseEvent.getY();
            cout << "Flood fill (x=" << dec << mx << ", y=" << my << "),"
                 << " color " << hex << setw(6) << setfill('0') << color
                 << dec << ": ";
            cout.flush();
            int pixelsColored = floodFill(floodFillPixels, mx, my, color);
            cout << pixelsColored << " pixels colored." << endl;
            colorList.setEnabled(true);
        } else if (e.getEventClass() == WINDOW_EVENT) {
            if (e.getEventType() == WINDOW_CLOSED) {
                // make sure that it was the flood fill window that got closed
                if (!floodFillWindow.isOpen() || !floodFillWindow.isVisible()) {
                    break;
                }
            }
        }
    }
    cout << resetiosflags(ios::fixed | ios::floatfield);
    
    cout << endl;
    cout << "Going to test flood fill exception handling." << endl;
    try {
        floodFill(floodFillPixels, -1, -2, 0x0);
        cout << "Fill (-1, -2) did not throw a proper exception." << endl;
    } catch (string) {
        cout << "Fill (-1, -2) threw an exception!" << endl;
    } catch (const char*) {
        cout << "Fill (-1, -2) threw an exception!" << endl;
    } catch (ErrorException) {
        cout << "Fill (-1, -2) threw an exception!" << endl;
    }
    try {
        floodFill(floodFillPixels, 3210, 4567, 0x0);
        cout << "Fill (3210, 4567) did not throw a proper exception." << endl;
    } catch (string) {
        cout << "Fill (3210, 4567) threw an exception!" << endl;
    } catch (const char*) {
        cout << "Fill (3210, 4567) threw an exception!" << endl;
    } catch (ErrorException) {
        cout << "Fill (3210, 4567) threw an exception!" << endl;
    }
}
/***********************************************************************//**
 * @brief Evaluate function and gradients
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            No CTA instrument direction found in event.
 *
 * Evaluates tha CTA background model and parameter gradients. The CTA
 * background model is a factorization of a spatial, spectral and
 * temporal model component. This method also applies a deadtime correction
 * factor, so that the normalization of the model is a real rate
 * (counts/exposure time).
 *
 * @todo Add bookkeeping of last value and evaluate only if argument 
 *       changed
 ***************************************************************************/
double GCTAModelBackground::eval_gradients(const GEvent& event,
                                           const GObservation& obs) const
{
    // Get pointer on CTA observation
    const GCTAObservation* ctaobs = dynamic_cast<const GCTAObservation*>(&obs);
    if (ctaobs == NULL) {
        std::string msg = "Specified observation is not a CTA observation.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL_GRADIENTS, msg);
    }

    // Extract CTA instrument direction
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL_GRADIENTS, msg);
    }

    // Create a Photon from the event
    // We need the photon to evaluate the spatial model
    // For the background, GEvent and GPhoton are identical
    // since the IRFs are not folded in
    GPhoton photon = GPhoton(dir->dir(), event.energy(),event.time());

    // Evaluate function and gradients
    double spat = (spatial() != NULL)
                  ? spatial()->eval_gradients(photon) : 1.0;
    double spec = (spectral() != NULL)
                  ? spectral()->eval_gradients(event.energy(), event.time()) : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval_gradients(event.time()) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    double deadc = obs.deadc(event.time());
    value       *= deadc;

    // Multiply factors to spatial gradients
    if (spatial() != NULL) {
        double fact = spec * temp * deadc;
        if (fact != 1.0) {
            for (int i = 0; i < spatial()->size(); ++i)
                (*spatial())[i].factor_gradient( (*spatial())[i].factor_gradient() * fact );
        }
    }

    // Multiply factors to spectral gradients
    if (spectral() != NULL) {
        double fact = spat * temp * deadc;
        if (fact != 1.0) {
            for (int i = 0; i < spectral()->size(); ++i)
                (*spectral())[i].factor_gradient( (*spectral())[i].factor_gradient() * fact );
        }
    }

    // Multiply factors to temporal gradients
    if (temporal() != NULL) {
        double fact = spat * spec * deadc;
        if (fact != 1.0) {
            for (int i = 0; i < temporal()->size(); ++i)
                (*temporal())[i].factor_gradient( (*temporal())[i].factor_gradient() * fact );
        }
    }

    // Return value
    return value;
}
Beispiel #20
0
/***********************************************************************//**
 * @brief Return instrument response to elliptical source
 *
 * @param[in] event Observed event.
 * @param[in] source Source.
 * @param[in] obs Observation (not used).
 * @return Instrument response to elliptical source.
 *
 * Returns the instrument response to a specified elliptical source.
 ***************************************************************************/
double GCTAResponseCube::irf_elliptical(const GEvent&       event,
                                        const GSource&      source,
                                        const GObservation& obs) const
{
    // Initialise IRF
    double irf = 0.0;

    // Get pointer to CTA event bin
    if (!event.is_bin()) {
        std::string msg = "The current event is not a CTA event bin. "
                          "This method only works on binned CTA data. Please "
                          "make sure that a CTA observation containing binned "
                          "CTA data is provided.";
        throw GException::invalid_value(G_IRF_RADIAL, msg);
    }
    const GCTAEventBin* bin = static_cast<const GCTAEventBin*>(&event);

    // Get event attribute references
    const GSkyDir& obsDir  = bin->dir().dir();
    const GEnergy& obsEng  = bin->energy();
    const GTime&   obsTime = bin->time();

    // Get pointer to elliptical model
    const GModelSpatialElliptical* model = static_cast<const GModelSpatialElliptical*>(source.model());

    // Compute angle between model centre and measured photon direction and
    // position angle (radians)
    double rho_obs      = model->dir().dist(obsDir);
    double posangle_obs = model->dir().posang(obsDir);

    // Get livetime (in seconds)
    double livetime = exposure().livetime();

    // Continue only if livetime is >0 and if we're sufficiently close to
    // the model centre to get a non-zero response
    if ((livetime > 0.0) && (rho_obs <= model->theta_max()+psf().delta_max())) {

        // Get exposure
        irf = exposure()(obsDir, obsEng);

        // Continue only if exposure is positive
        if (irf > 0.0) {

            // Recover effective area from exposure
            irf /= livetime;

            // Get PSF component
            irf *= psf_elliptical(model, rho_obs, posangle_obs, obsDir, obsEng, obsTime);

            // Apply deadtime correction
            irf *= exposure().deadc();

        } // endif: exposure was positive
        
    } // endif: we were sufficiently close and livetime >0

    // Compile option: Check for NaN/Inf
    #if defined(G_NAN_CHECK)
    if (gammalib::is_notanumber(irf) || gammalib::is_infinite(irf)) {
        std::cout << "*** ERROR: GCTAResponseCube::irf_elliptical:";
        std::cout << " NaN/Inf encountered";
        std::cout << " irf=" << irf;
        std::cout << std::endl;
    }
    #endif

    // Return IRF value
    return irf;
}
int autograderGraphicalMain(int argc, char** argv) {
    GWindow gui(500, 300, /* visible */ false);
    gui.setTitle(STATIC_VARIABLE(FLAGS).assignmentName + " Autograder");
    gui.setCanvasSize(0, 0);
    gui.setExitOnClose(true);
    
    GLabel startLabel("");
    if (!STATIC_VARIABLE(FLAGS).startMessage.empty()) {
        std::string startMessage = STATIC_VARIABLE(FLAGS).startMessage;
        if (!stringContains(startMessage, "<html>")) {
            startMessage = stringReplace(startMessage, "Note:", "<b>Note:</b>");
            startMessage = stringReplace(startMessage, "NOTE:", "<b>NOTE:</b>");
            startMessage = "<html><body style='width: 500px; max-width: 500px;'>"
                    + startMessage
                    + "</body></html>";
        }
        
        startLabel.setLabel(startMessage);
        gui.addToRegion(&startLabel, "NORTH");
    }
    
    std::string autogradeText = addAutograderButton(gui, "Automated\ntests", "check.gif");
    std::string manualText = addAutograderButton(gui, "Run\nmanually", "play.gif");
    std::string styleCheckText = addAutograderButton(gui, "Style\nchecker", "magnifier.gif");
    for (int i = 0; i < STATIC_VARIABLE(FLAGS).callbackButtons.size(); i++) {
        STATIC_VARIABLE(FLAGS).callbackButtons[i].text = addAutograderButton(gui, STATIC_VARIABLE(FLAGS).callbackButtons[i].text, STATIC_VARIABLE(FLAGS).callbackButtons[i].icon);
    }
    std::string lateDayText = addAutograderButton(gui, "Late days\ninfo", "calendar.gif");
    std::string aboutText = addAutograderButton(gui, "About\nGrader", "help.gif");
    std::string exitText = addAutograderButton(gui, "Exit\nGrader", "stop.gif");
    gui.pack();
    gui.setVisible(true);
    
    int result = 0;
    while (true) {
        GEvent event = waitForEvent(ACTION_EVENT);
        if (event.getEventClass() == ACTION_EVENT) {
            GActionEvent actionEvent(event);
            std::string cmd = actionEvent.getActionCommand();
            if (cmd == autogradeText) {
                if (STATIC_VARIABLE(FLAGS).callbackStart) {
                    STATIC_VARIABLE(FLAGS).callbackStart();
                }
                
                // stanfordcpplib::getPlatform()->autograderunittest_clearTests();
                stanfordcpplib::getPlatform()->autograderunittest_clearTestResults();
                stanfordcpplib::getPlatform()->autograderunittest_setTestingCompleted(false);
                stanfordcpplib::getPlatform()->autograderunittest_setVisible(true);
                result = mainRunAutograderTestCases(argc, argv);
                stanfordcpplib::getPlatform()->autograderunittest_setTestingCompleted(true);
                
                // if style checker is merged, also run it now
                if (stylecheck::isStyleCheckMergedWithUnitTests()) {
                    mainRunStyleChecker();
                }

                if (STATIC_VARIABLE(FLAGS).callbackEnd) {
                    STATIC_VARIABLE(FLAGS).callbackEnd();
                }
            } else if (cmd == manualText) {
                // set up buttons to automatically enter user input
                if (STATIC_VARIABLE(FLAGS).showInputPanel) {
                    inputpanel::load(STATIC_VARIABLE(FLAGS).inputPanelFilename);
                }
                
                // actually run the student's program
                // (While program is running, if we close console, exit entire
                // autograder program because we might be blocked on console I/O.
                // But after it's done running, set behavior to just hide the
                // console, since the grader will probably try to close it and then
                // proceed with more grading and tests afterward.
                // A little wonky, but it avoids most of the surprise cases of
                // "I closed the student's console and it killed the autograder".
                stanfordcpplib::getPlatform()->jbeconsole_clear();
                stanfordcpplib::getPlatform()->jbeconsole_setVisible(true);
                stanfordcpplib::getPlatform()->jbeconsole_toFront();
                // setConsoleCloseOperation(ConsoleCloseOperation::CONSOLE_EXIT_ON_CLOSE);
                autograder::setExitEnabled(false);   // block exit() call
                setConsoleCloseOperation(ConsoleCloseOperation::CONSOLE_HIDE_ON_CLOSE);

                studentMain();

                // gwindowSetExitGraphicsEnabled(true);
            } else if (cmd == styleCheckText) {
                mainRunStyleChecker();
            } else if (cmd == lateDayText) {
                showLateDays();
            } else if (cmd == aboutText) {
                GOptionPane::showMessageDialog(STATIC_VARIABLE(FLAGS).aboutText, "About Autograder",
                                               GOptionPane::MessageType::INFORMATION);
            } else if (cmd == exitText) {
                autograder::setExitEnabled(true);   // don't block exit() call

                // free up memory used by graphical interactors
                for (GButton* button : STATIC_VARIABLE(AUTOGRADER_BUTTONS)) {
                    delete button;
                }
                STATIC_VARIABLE(AUTOGRADER_BUTTONS).clear();

                gui.close();   // exits program; will not return
                break;
            } else {
                for (CallbackButtonInfo buttonInfo : STATIC_VARIABLE(FLAGS).callbackButtons) {
                    if (cmd == buttonInfo.text) {
                        buttonInfo.func();
                        break;
                    }
                }
            }
        }
    }

    // free up memory used by graphical interactors
    for (GButton* button : STATIC_VARIABLE(AUTOGRADER_BUTTONS)) {
        delete button;
    }
    STATIC_VARIABLE(AUTOGRADER_BUTTONS).clear();
    
    return result;
}
Beispiel #22
0
bool WidgetManager::onEvent(const GEvent& event) {
    const bool motionEvent = 
        (event.type == GEventType::MOUSE_MOTION) ||
        (event.type == GEventType::JOY_AXIS_MOTION) ||
        (event.type == GEventType::JOY_HAT_MOTION) ||
        (event.type == GEventType::JOY_BALL_MOTION);

    const bool positionalEvent = 
        (event.type == GEventType::MOUSE_BUTTON_CLICK) ||
        (event.type == GEventType::MOUSE_BUTTON_DOWN) ||
        (event.type == GEventType::MOUSE_BUTTON_UP) ||
        (event.type == GEventType::MOUSE_MOTION);

    beginLock(); {
        // Deliver positional events in order of widget's depth preference
        if (positionalEvent) {
            const Point2& P = event.mousePosition();

            // Find the distance at which object believes that it is for this event. By default, this is
            // the focus array position.
            Array<SortWrapper<shared_ptr<Widget> > > widgetWithZ;
            widgetWithZ.resize(m_moduleArray.size());
            for (int i = 0; i < m_moduleArray.size(); ++i) {
                const shared_ptr<Widget>& w = m_moduleArray[i];
                SortWrapper<shared_ptr<Widget> >& s = widgetWithZ[i];

                s.value = w;
                s.key = w->positionalEventZ(P);

                if (isNaN(s.key)) {
                    // The module wishes to use its focus position as a "Depth"
                    if (w == m_focusedModule) {
                        // Focused module gets priority and pretends that it is 
                        // higher than the first one
                        s.key = float(m_moduleArray.size());
                    } else {
                        s.key = float(i);
                    }
                } // if default key
            } // for each widget

            widgetWithZ.sort(SORT_DECREASING);
                
            for (int i = 0; i < widgetWithZ.size(); ++i) {        
                if (widgetWithZ[i].value->onEvent(event)) {
                    // End the manager lock began at the top of this method before returning abruptly
                    endLock();
                    return true;
                }
            }

        } else {

            // Except for motion events, ensure that the focused module gets each event first
            if (m_focusedModule && ! motionEvent) {
                if (m_focusedModule->onEvent(event)) { 
                    // End the manager lock began at the top of this method before returning abruptly
                    endLock(); 
                    return true;
                }
            }

            for (int i = m_moduleArray.size() - 1; i >=0; --i) {
                // Don't double-deliver to the focused module
                if (motionEvent || (m_moduleArray[i] != m_focusedModule)) {
                    if (m_moduleArray[i]->onEvent(event) && ! motionEvent) {
                        // End the manager lock began at the top of this method before returning abruptly
                        endLock(); 
                        return true;
                    }
                }
            }
        }
    } endLock();

    return false;
}
/***********************************************************************//**
 * @brief Evaluate function
 *
 * @param[in] event Observed event.
 * @param[in] obs Observation.
 * @param[in] gradients Compute gradients?
 * @return Function value.
 *
 * @exception GException::invalid_argument
 *            Specified observation is not of the expected type.
 *
 * If the @p gradients flag is true the method will also set the parameter
 * gradients of the model parameters.
 *
 * @todo Make sure that DETX and DETY are always set in GCTAInstDir.
 ***************************************************************************/
double GCTAModelAeffBackground::eval(const GEvent&       event,
                                     const GObservation& obs,
                                     const bool&         gradients) const
{
    // Get pointer on CTA observation
    const GCTAObservation* cta = dynamic_cast<const GCTAObservation*>(&obs);
    if (cta == NULL) {
        std::string msg = "Specified observation is not a CTA observation.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Get pointer on CTA IRF response
    const GCTAResponseIrf* rsp = dynamic_cast<const GCTAResponseIrf*>(cta->response());
    if (rsp == NULL) {
        std::string msg = "Specified observation does not contain an IRF response.\n" +
                          obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Retrieve pointer to CTA Effective Area
    const GCTAAeff* aeff = rsp->aeff();
    if (aeff == NULL) {
        std::string msg = "Specified observation contains no effective area"
                          " information.\n" + obs.print();
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Extract CTA instrument direction from event
    const GCTAInstDir* dir  = dynamic_cast<const GCTAInstDir*>(&(event.dir()));
    if (dir == NULL) {
        std::string msg = "No CTA instrument direction found in event.";
        throw GException::invalid_argument(G_EVAL, msg);
    }

    // Set DETX and DETY in instrument direction
    GCTAInstDir inst_dir = cta->pointing().instdir(dir->dir());

    // Set theta and phi from instrument coordinates
    double theta = std::sqrt(inst_dir.detx() * inst_dir.detx() +
                             inst_dir.dety() * inst_dir.dety());
    double phi   = gammalib::atan2d(inst_dir.dety(), inst_dir.detx()) *
                   gammalib::deg2rad;

    // Evaluate function
    double logE = event.energy().log10TeV();
    double spat = (*aeff)(logE, theta, phi,
                          cta->pointing().zenith(),
                          cta->pointing().azimuth(), false);
    double spec = (spectral() != NULL)
                  ? spectral()->eval(event.energy(), event.time(), gradients)
                  : 1.0;
    double temp = (temporal() != NULL)
                  ? temporal()->eval(event.time(), gradients) : 1.0;

    // Compute value
    double value = spat * spec * temp;

    // Apply deadtime correction
    double deadc = obs.deadc(event.time());
    value       *= deadc;

    // Optionally compute partial derivatives
    if (gradients) {

        // Multiply factors to spectral gradients
        if (spectral() != NULL) {
            double fact = spat * temp * deadc;
            if (fact != 1.0) {
                for (int i = 0; i < spectral()->size(); ++i)
                    (*spectral())[i].factor_gradient((*spectral())[i].factor_gradient() * fact );
            }
        }

        // Multiply factors to temporal gradients
        if (temporal() != NULL) {
            double fact = spat * spec * deadc;
            if (fact != 1.0) {
                for (int i = 0; i < temporal()->size(); ++i)
                    (*temporal())[i].factor_gradient((*temporal())[i].factor_gradient() * fact );
            }
        }

    } // endif: computed partial derivatives

    // Return value
    return value;
}
Beispiel #24
0
/***********************************************************************//**
 * @brief Return instrument response to point source
 *
 * @param[in] event Observed event.
 * @param[in] source Source.
 * @param[in] obs Observation (not used).
 * @return Instrument response to point source.
 *
 * Returns the instrument response to a specified point source.
 ***************************************************************************/
double GCTAResponseCube::irf_ptsrc(const GEvent&       event,
                                   const GSource&      source,
                                   const GObservation& obs) const
{
    // Initialise IRF
    double irf = 0.0;

    // Get pointer to model source model
    const GModelSpatialPointSource* ptsrc = static_cast<const GModelSpatialPointSource*>(source.model());

    // Get point source direction
    GSkyDir srcDir = ptsrc->dir();

    // Get pointer on CTA event bin
    if (!event.is_bin()) {
        std::string msg = "The current event is not a CTA event bin. "
                          "This method only works on binned CTA data. Please "
                          "make sure that a CTA observation containing binned "
                          "CTA data is provided.";
        throw GException::invalid_value(G_IRF_PTSRC, msg);
    }
    const GCTAEventBin* bin = static_cast<const GCTAEventBin*>(&event);
    
    // Determine angular separation between true and measured photon
    // direction in radians
    double delta = bin->dir().dir().dist(srcDir);

    // Get maximum angular separation for PSF (in radians)
    double delta_max = psf().delta_max();

    // Get livetime (in seconds)
    double livetime = exposure().livetime();

    // Continue only if livetime is >0 and if we're sufficiently close
    // to the PSF
    if ((livetime > 0.0) && (delta <= delta_max)) {

        // Get exposure
        irf = exposure()(srcDir, source.energy());

        // Multiply-in PSF
        if (irf > 0.0) {

            // Recover effective area from exposure
            irf /= livetime;

            // Get PSF component
            irf *= psf()(srcDir, delta, source.energy());

            // Apply deadtime correction
            irf *= exposure().deadc();

        } // endif: exposure was non-zero

    } // endif: we were sufficiently close to PSF and livetime >0

    // Compile option: Check for NaN/Inf
    #if defined(G_NAN_CHECK)
    if (gammalib::is_notanumber(irf) || gammalib::is_infinite(irf)) {
        std::cout << "*** ERROR: GCTAResponseCube::irf_ptsrc:";
        std::cout << " NaN/Inf encountered";
        std::cout << " irf=" << irf;
        std::cout << std::endl;
    }
    #endif

    // Return IRF value
    return irf;
}
Beispiel #25
0
int main() {
	GWindow gw(width, height);
    
     while(true){
         
         /*Button Setup*/
         
         GButton *button = new GButton("Draw");
         gw.addToRegion(button, "South");
    
         GChooser *timeChooser = new GChooser();
         timeChooser->addItem("Dusk");
         timeChooser->addItem("Day");
         timeChooser->addItem("Night");
         gw.addToRegion(timeChooser, "South");
    
         GCheckBox *fg = new GCheckBox("Terrain");
         gw.addToRegion(fg, "West");
    
         GCheckBox *sun = new GCheckBox("Sun/Moon");
         gw.addToRegion(sun, "West");
    
         GCheckBox *bg = new GCheckBox("Mountain");
         gw.addToRegion(bg, "West");
    
    
         GCheckBox *lightning = new GCheckBox("Lightning");
         gw.addToRegion(lightning, "West");
         
         GCheckBox *tree = new GCheckBox("Tree");
         gw.addToRegion(tree, "West");
    
        /*Listen for click*/
         while(true){
            GEvent e = waitForEvent(ACTION_EVENT | CLICK_EVENT);
            if(e.getEventClass() == ACTION_EVENT) break;
        }
        string selectedTime = timeChooser->getSelectedItem();
         if(selectedTime=="Dusk"){
             dusk=true;
             day=false;
             night=false;
         }
         if(selectedTime=="Day"){
            day=true;
            dusk=false;
            night=false;
        }
        if(selectedTime=="Night"){
            night=true;
            dusk=false;
            day=false;
        }
         /*Drawing selected items*/
        gw.clear();
        closePoints.clear();
        drawSky(gw);
        if(sun->isSelected()) drawSun(gw,MAX_SUN_RADIUS,(dusk?DUSK_SUN_COLOR:DAY_SUN_COLOR));
        if(bg->isSelected()) drawBackGroundMountain(gw);
        if(lightning->isSelected()) drawLightning(gw, GPoint(width*randomReal(.2, .8), 0), GPoint(width*randomReal(.2, .8), height));
        if(tree->isSelected()) drawTree(gw);
        if(fg->isSelected()) drawTerrain(gw);
        }

	return 0;
}