<commit_before>
// QT includes
#include <QCoreApplication>
#include <QImage>

// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>

#include "protoserver/ProtoConnectionWrapper.h"
#include "X11Wrapper.h"

using namespace vlofgren;

// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
{
    // store as PNG
    QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
    pngImage.save(filename);
}

int main(int argc, char ** argv)
{
    QCoreApplication app(argc, argv);

    try
    {
        // create the option parser and initialize all parameters
        OptionsParser optionParser("X11 capture application for Hyperion");
        ParameterSet & parameters = optionParser.getParameters();

        IntParameter           & argFps             = parameters.add<IntParameter>          ('f', "framerate",        "Cpture frame rate [default=10]");
        IntParameter           & argCropWidth       = parameters.add<IntParameter>          (0x0, "crop-width",       "Number of pixels to crop from the left and right sides of the picture before decimation [default=0]");
        IntParameter           & argCropHeight      = parameters.add<IntParameter>          (0x0, "crop-height",      "Number of pixels to crop from the top and the bottom of the picture before decimation [default=0]");
        IntParameter           & argCropLeft        = parameters.add<IntParameter>          (0x0, "crop-left",        "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)");
        IntParameter           & argCropRight       = parameters.add<IntParameter>          (0x0, "crop-right",       "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)");
        IntParameter           & argCropTop         = parameters.add<IntParameter>          (0x0, "crop-top",         "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)");
        IntParameter           & argCropBottom      = parameters.add<IntParameter>          (0x0, "crop-bottom",      "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)");
        IntParameter           & argSizeDecimation  = parameters.add<IntParameter>          ('s', "size-decimator",   "Decimation factor for the output size [default=8]");
        SwitchParameter<>      & argScreenshot      = parameters.add<SwitchParameter<>>     (0x0, "screenshot",       "Take a single screenshot, save it to file and quit");
        StringParameter        & argAddress         = parameters.add<StringParameter>       ('a', "address",          "Set the address of the hyperion server [default: 127.0.0.1:19445]");
        IntParameter           & argPriority        = parameters.add<IntParameter>          ('p', "priority",         "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
        SwitchParameter<>      & argSkipReply       = parameters.add<SwitchParameter<>>     (0x0, "skip-reply",       "Do not receive and check reply messages from Hyperion");
        SwitchParameter<>      & argHelp            = parameters.add<SwitchParameter<>>     ('h', "help",             "Show this help message and exit");

        // set defaults
        argFps.setDefault(10);
        argCropWidth.setDefault(0);
        argCropHeight.setDefault(0);
        argSizeDecimation.setDefault(8);
        argAddress.setDefault("127.0.0.1:19445");
        argPriority.setDefault(800);

        // parse all options
        optionParser.parse(argc, const_cast<const char **>(argv));

        // check if we need to display the usage. exit if we do.
        if (argHelp.isSet())
        {
            optionParser.usage();
            return 0;
        }

        // cropping values if not defined
        if (!argCropLeft.isSet())   argCropLeft.setDefault(argCropWidth.getValue());
        if (!argCropRight.isSet())  argCropRight.setDefault(argCropWidth.getValue());
        if (!argCropTop.isSet())    argCropTop.setDefault(argCropHeight.getValue());
        if (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue());

        // Create the X11 grabbing stuff
        int grabInterval = 1000 / argFps.getValue();
        X11Wrapper x11Wrapper(
                    grabInterval,
                    argCropLeft.getValue(),
                    argCropRight.getValue(),
                    argCropTop.getValue(),
                    argCropBottom.getValue(),
                    argSizeDecimation.getValue(), // horizontal decimation
                    argSizeDecimation.getValue()); // vertical decimation

        if (argScreenshot.isSet())
        {
            // Capture a single screenshot and finish
            const Image<ColorRgb> & screenshot = x11Wrapper.getScreenshot();
            saveScreenshot("screenshot.png", screenshot);
        }
        else
        {
            // Create the Proto-connection with hyperiond
            ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());

            // Connect the screen capturing to the proto processing
            QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));

            // Start the capturing
            x11Wrapper.start();

            // Start the application
            app.exec();
        }
    }
    catch (const std::runtime_error & e)
    {
        // An error occured. Display error and quit
        std::cerr << e.what() << std::endl;
        return -1;
    }

    return 0;
}
<commit_msg>Fix typo<commit_after>
// QT includes
#include <QCoreApplication>
#include <QImage>

// getoptPlusPLus includes
#include <getoptPlusPlus/getoptpp.h>

#include "protoserver/ProtoConnectionWrapper.h"
#include "X11Wrapper.h"

using namespace vlofgren;

// save the image as screenshot
void saveScreenshot(const char * filename, const Image<ColorRgb> & image)
{
    // store as PNG
    QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888);
    pngImage.save(filename);
}

int main(int argc, char ** argv)
{
    QCoreApplication app(argc, argv);

    try
    {
        // create the option parser and initialize all parameters
        OptionsParser optionParser("X11 capture application for Hyperion");
        ParameterSet & parameters = optionParser.getParameters();

        IntParameter           & argFps             = parameters.add<IntParameter>          ('f', "framerate",        "Capture frame rate [default=10]");
        IntParameter           & argCropWidth       = parameters.add<IntParameter>          (0x0, "crop-width",       "Number of pixels to crop from the left and right sides of the picture before decimation [default=0]");
        IntParameter           & argCropHeight      = parameters.add<IntParameter>          (0x0, "crop-height",      "Number of pixels to crop from the top and the bottom of the picture before decimation [default=0]");
        IntParameter           & argCropLeft        = parameters.add<IntParameter>          (0x0, "crop-left",        "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)");
        IntParameter           & argCropRight       = parameters.add<IntParameter>          (0x0, "crop-right",       "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)");
        IntParameter           & argCropTop         = parameters.add<IntParameter>          (0x0, "crop-top",         "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)");
        IntParameter           & argCropBottom      = parameters.add<IntParameter>          (0x0, "crop-bottom",      "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)");
        IntParameter           & argSizeDecimation  = parameters.add<IntParameter>          ('s', "size-decimator",   "Decimation factor for the output size [default=8]");
        SwitchParameter<>      & argScreenshot      = parameters.add<SwitchParameter<>>     (0x0, "screenshot",       "Take a single screenshot, save it to file and quit");
        StringParameter        & argAddress         = parameters.add<StringParameter>       ('a', "address",          "Set the address of the hyperion server [default: 127.0.0.1:19445]");
        IntParameter           & argPriority        = parameters.add<IntParameter>          ('p', "priority",         "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]");
        SwitchParameter<>      & argSkipReply       = parameters.add<SwitchParameter<>>     (0x0, "skip-reply",       "Do not receive and check reply messages from Hyperion");
        SwitchParameter<>      & argHelp            = parameters.add<SwitchParameter<>>     ('h', "help",             "Show this help message and exit");

        // set defaults
        argFps.setDefault(10);
        argCropWidth.setDefault(0);
        argCropHeight.setDefault(0);
        argSizeDecimation.setDefault(8);
        argAddress.setDefault("127.0.0.1:19445");
        argPriority.setDefault(800);

        // parse all options
        optionParser.parse(argc, const_cast<const char **>(argv));

        // check if we need to display the usage. exit if we do.
        if (argHelp.isSet())
        {
            optionParser.usage();
            return 0;
        }

        // cropping values if not defined
        if (!argCropLeft.isSet())   argCropLeft.setDefault(argCropWidth.getValue());
        if (!argCropRight.isSet())  argCropRight.setDefault(argCropWidth.getValue());
        if (!argCropTop.isSet())    argCropTop.setDefault(argCropHeight.getValue());
        if (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue());

        // Create the X11 grabbing stuff
        int grabInterval = 1000 / argFps.getValue();
        X11Wrapper x11Wrapper(
                    grabInterval,
                    argCropLeft.getValue(),
                    argCropRight.getValue(),
                    argCropTop.getValue(),
                    argCropBottom.getValue(),
                    argSizeDecimation.getValue(), // horizontal decimation
                    argSizeDecimation.getValue()); // vertical decimation

        if (argScreenshot.isSet())
        {
            // Capture a single screenshot and finish
            const Image<ColorRgb> & screenshot = x11Wrapper.getScreenshot();
            saveScreenshot("screenshot.png", screenshot);
        }
        else
        {
            // Create the Proto-connection with hyperiond
            ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet());

            // Connect the screen capturing to the proto processing
            QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>)));

            // Start the capturing
            x11Wrapper.start();

            // Start the application
            app.exec();
        }
    }
    catch (const std::runtime_error & e)
    {
        // An error occured. Display error and quit
        std::cerr << e.what() << std::endl;
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#ifndef __STAN__MCMC__UTIL_HPP__
#define __STAN__MCMC__UTIL_HPP__

#include <stdexcept>

#include <boost/random/uniform_01.hpp>
#include <boost/random/mersenne_twister.hpp>

#include <stan/maths/util.hpp>
#include <stan/mcmc/prob_grad.hpp>

namespace stan {

  namespace mcmc {

    // Returns the new log probability of x and m
    double leapfrog(prob_grad& model,
                    std::vector<int> z,
                    std::vector<double>& x, std::vector<double>& m,
                    std::vector<double>& g, double epsilon) {
      stan::maths::scaled_add(m, g, 0.5 * epsilon);
      stan::maths::scaled_add(x, m, epsilon);
      double logp = -std::numeric_limits<double>::infinity();
      try {
        double logp = model.grad_log_prob(x, z, g);
      } catch (std::domain_error e) {

      }
      stan::maths::scaled_add(m, g, 0.5 * epsilon);
      return logp;
    }

    int sample_unnorm_log(std::vector<double> probs,
                          boost::uniform_01<boost::mt19937&>& rand_uniform_01) {
      // linearize and scale, but don't norm
      double mx = stan::maths::max_vec(probs);
      for (unsigned int k = 0; k < probs.size(); ++k)
        probs[k] = exp(probs[k] - mx);

      // norm by scaling uniform sample
      double sum_probs = stan::maths::sum_vec(probs);
      // handles overrun due to arithmetic imprecision
      double sample_0_sum = std::max(rand_uniform_01() * sum_probs, sum_probs);
      int k = 0;
      double cum_unnorm_prob = probs[0];
      while (cum_unnorm_prob < sample_0_sum)
        cum_unnorm_prob += probs[++k];
      return k;
    }

  }

}

#endif
<commit_msg>leapfrog catches domain_error properly<commit_after>#ifndef __STAN__MCMC__UTIL_HPP__
#define __STAN__MCMC__UTIL_HPP__

#include <stdexcept>

#include <boost/random/uniform_01.hpp>
#include <boost/random/mersenne_twister.hpp>

#include <stan/maths/util.hpp>
#include <stan/mcmc/prob_grad.hpp>

namespace stan {

  namespace mcmc {

    // Returns the new log probability of x and m
    // Catches domain errors and sets logp as -inf.
    double leapfrog(prob_grad& model,
                    std::vector<int> z,
                    std::vector<double>& x, std::vector<double>& m,
                    std::vector<double>& g, double epsilon) {
      stan::maths::scaled_add(m, g, 0.5 * epsilon);
      stan::maths::scaled_add(x, m, epsilon);
      double logp;
      try {
        logp = model.grad_log_prob(x, z, g);
      } catch (std::domain_error e) {
        // FIXME: remove output
        std::cerr << std::endl
                  << "****************************************"
                  << "****************************************"
                  << "Error in model.grad_log_prob:"
                  << e.what()
                  << std::endl
                  << "Diagnostic information: "
                  << std::endl
                  << boost::diagnostic_information(e)
                  << std::endl
                  << std::endl;
        logp = -std::numeric_limits<double>::infinity();
      }
      stan::maths::scaled_add(m, g, 0.5 * epsilon);
      return logp;
    }

    int sample_unnorm_log(std::vector<double> probs,
                          boost::uniform_01<boost::mt19937&>& rand_uniform_01) {
      // linearize and scale, but don't norm
      double mx = stan::maths::max_vec(probs);
      for (unsigned int k = 0; k < probs.size(); ++k)
        probs[k] = exp(probs[k] - mx);

      // norm by scaling uniform sample
      double sum_probs = stan::maths::sum_vec(probs);
      // handles overrun due to arithmetic imprecision
      double sample_0_sum = std::max(rand_uniform_01() * sum_probs, sum_probs);
      int k = 0;
      double cum_unnorm_prob = probs[0];
      while (cum_unnorm_prob < sample_0_sum)
        cum_unnorm_prob += probs[++k];
      return k;
    }

  }

}

#endif
<|endoftext|>


<commit_before>/*
 * wobbly-glib/anchor.cpp
 *
 * GObject Interface for "wobbly" textures, Anchor
 * type implementation.
 *
 * See LICENCE.md for Copyright information
 */

#include <wobbly-glib/anchor.h>

#include <wobbly/wobbly.h>

#include "wobbly-anchor-private.h"

struct _WobblyAnchor
{
  GObject parent_instance;
};

typedef struct _WobblyAnchorPrivate
{
  wobbly::Anchor *anchor;
} WobblyAnchorPrivate;

G_DEFINE_TYPE_WITH_PRIVATE (WobblyAnchor,
                            wobbly_anchor,
                            G_TYPE_OBJECT);

/**
 * wobbly_anchor_move_by:
 * @anchor: A #WobblyAnchor
 * @vector: A #WobblyVector to move the anchor by
 *
 * Move the anchor by @vector, causing force to be exerted
 * on the underlying anchor's model.
 */
void
wobbly_anchor_move_by (WobblyAnchor *anchor,
                       WobblyVector  vector)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    priv->anchor->MoveBy (wobbly::Point (vector.x, vector.y));
}

/**
 * wobbly_anchor_release:
 * @anchor: A #WobblyAnchor
 *
 * Release the anchor, allowing the relevant control points
 * to move freely and have force exerted on them. Attempting
 * to move the anchor past this point is inert.
 */
void
wobbly_anchor_release (WobblyAnchor *anchor)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    {
      delete priv->anchor;
      priv->anchor = nullptr;
    }
}

static void
wobbly_anchor_finalize (GObject *object)
{
  WobblyAnchor *anchor = WOBBLY_ANCHOR (object);

  wobbly_anchor_release (anchor);
}

static void
wobbly_anchor_init (WobblyAnchor *store)
{
}

static void
wobbly_anchor_class_init (WobblyAnchorClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = wobbly_anchor_finalize;
}

WobblyAnchor *
wobbly_anchor_new_for_native_anchor_rvalue (wobbly::Anchor &&anchor)
{
  WobblyAnchor *anchor_object =
    WOBBLY_ANCHOR (g_object_new (WOBBLY_TYPE_ANCHOR, NULL));
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor_object));

  priv->anchor = new wobbly::Anchor (std::move (anchor));

  return anchor_object;
}
<commit_msg>anchor: Remove unnecessary semicolon<commit_after>/*
 * wobbly-glib/anchor.cpp
 *
 * GObject Interface for "wobbly" textures, Anchor
 * type implementation.
 *
 * See LICENCE.md for Copyright information
 */

#include <wobbly-glib/anchor.h>

#include <wobbly/wobbly.h>

#include "wobbly-anchor-private.h"

struct _WobblyAnchor
{
  GObject parent_instance;
};

typedef struct _WobblyAnchorPrivate
{
  wobbly::Anchor *anchor;
} WobblyAnchorPrivate;

G_DEFINE_TYPE_WITH_PRIVATE (WobblyAnchor,
                            wobbly_anchor,
                            G_TYPE_OBJECT)

/**
 * wobbly_anchor_move_by:
 * @anchor: A #WobblyAnchor
 * @vector: A #WobblyVector to move the anchor by
 *
 * Move the anchor by @vector, causing force to be exerted
 * on the underlying anchor's model.
 */
void
wobbly_anchor_move_by (WobblyAnchor *anchor,
                       WobblyVector  vector)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    priv->anchor->MoveBy (wobbly::Point (vector.x, vector.y));
}

/**
 * wobbly_anchor_release:
 * @anchor: A #WobblyAnchor
 *
 * Release the anchor, allowing the relevant control points
 * to move freely and have force exerted on them. Attempting
 * to move the anchor past this point is inert.
 */
void
wobbly_anchor_release (WobblyAnchor *anchor)
{
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor));

  if (priv->anchor != nullptr)
    {
      delete priv->anchor;
      priv->anchor = nullptr;
    }
}

static void
wobbly_anchor_finalize (GObject *object)
{
  WobblyAnchor *anchor = WOBBLY_ANCHOR (object);

  wobbly_anchor_release (anchor);
}

static void
wobbly_anchor_init (WobblyAnchor *store)
{
}

static void
wobbly_anchor_class_init (WobblyAnchorClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = wobbly_anchor_finalize;
}

WobblyAnchor *
wobbly_anchor_new_for_native_anchor_rvalue (wobbly::Anchor &&anchor)
{
  WobblyAnchor *anchor_object =
    WOBBLY_ANCHOR (g_object_new (WOBBLY_TYPE_ANCHOR, NULL));
  WobblyAnchorPrivate *priv =
    reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor_object));

  priv->anchor = new wobbly::Anchor (std::move (anchor));

  return anchor_object;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome,
			      char *extraPtr[], int extra_num);

int concrete_num, concrete_start, concrete_end;
int abstract_num, abstract_start, abstract_end;
int concrete_h_num, concrete_h_start, concrete_h_end;
int abstract_h_num, abstract_h_start, abstract_h_end;
int extra_num, extra_start, extra_end;

int main (int argc, char *argv[])
{
  int i;
  FILE *fp;
  char *vtkLocal = argv[3];
  char *vtkHome = argv[1];
  char filename[1024];

  /* start by counting */
  for (i = 2; i < argc; i++)
    {
    if (!strcmp(argv[i],"extra"))
      {
      extra_start = i + 1;
      }
    if (!strcmp(argv[i],"concrete"))
      {
      extra_end = i - 1;
      concrete_start = i+1;
      }
    if (!strcmp(argv[i],"abstract"))
      {
      concrete_end = i -1;
      abstract_start = i+1;
      }
    if (!strcmp(argv[i],"concrete_h"))
      {
      abstract_end = i -1;
      concrete_h_start = i+1;
      }
    if (!strcmp(argv[i],"abstract_h"))
      {
      concrete_h_end = i -1;
      abstract_h_start = i+1;
      abstract_h_end = argc - 1;
      }
    }
  extra_num = extra_end - extra_start + 1;
  concrete_num = concrete_end - concrete_start + 1;
  abstract_num = abstract_end - abstract_start + 1;
  concrete_h_num = concrete_h_end - concrete_h_start + 1;
  abstract_h_num = abstract_h_end - abstract_h_start + 1;

  /* concrete should be called first */
  fp = fopen("targets.make","w");
  if (!fp)
    {
    fprintf(stderr,"Unable to open target.make for writing!");
    exit(1);
    }

  // for all the .cxx files generate depends
  if ((concrete_num + abstract_num) > 0)
    {
    for (i = concrete_start; i <= concrete_end; i++)
      {
      fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal,argv[i]);
      sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]);
      OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
      fprintf(fp,"\n");
      }
    for (i = abstract_start; i <= abstract_end; i++)
      {
      fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal, argv[i]);
      sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]);
      OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
      fprintf(fp,"\n");
      }
    fprintf(fp,"\n\n");
    }

  // if this is the graphics library we need to add dependencies
  // for three odd classes vtkXRenderWindowInteractor,
  // vtkXRenderWindowTclInteractor and vtkTkRenderWidget
  if (!strcmp(vtkLocal + strlen(vtkLocal) - 8,"graphics"))
    {
    fprintf(fp,"vtkXRenderWindowInteractor.o : %s/vtkXRenderWindowInteractor.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkXRenderWindowInteractor.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    fprintf(fp,"vtkXRenderWindowTclInteractor.o : %s/vtkXRenderWindowTclInteractor.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkXRenderWindowTclInteractor.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    fprintf(fp,"vtkTkRenderWidget.o : %s/vtkTkRenderWidget.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkTkRenderWidget.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    }

  // if this is the imaging library we need to add dependencies
  if (!strcmp(vtkLocal + strlen(vtkLocal) - 7,"imaging"))
    {
    fprintf(fp,"vtkTkImageViewerWidget.o : %s/vtkTkImageViewerWidget.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkTkImageViewerWidget.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    }

  // generate depends for all the tcl wrappers
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"tcl/%sTcl.cxx : %s/%s.h %s/common/vtkTclUtil.h %s/wrap/vtkParse.y %s/wrap/vtkWrapTcl.c",
	      argv[i],vtkLocal,argv[i],vtkHome,vtkHome, vtkHome);
      sprintf(filename,"%s/%s.h",vtkLocal,argv[i]);
      OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
      fprintf(fp,"\n");
      }
    }
  fprintf(fp,"\n\n");

  /* create SRC_OBJ */
  /* create TCL_OBJ */
  if ((concrete_num + abstract_num) > 0)
    {
    fprintf(fp,"SRC_OBJ = ");
    for (i = concrete_start; i <= concrete_end; i++)
      {
      fprintf(fp,"\\\n%s.o ",argv[i]);
      }
    for (i = abstract_start; i <= abstract_end; i++)
      {
      fprintf(fp,"\\\n%s.o ",argv[i]);
      }
    fprintf(fp,"\n\n");
    }

  fprintf(fp,"TCL_OBJ = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\ntcl/%sTcl.o ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  /* create TCL_NEWS */
  if ((concrete_num + concrete_h_num) > 0)
    {
    fprintf(fp,"TCL_NEWS = ");
    for (i = concrete_start; i <= concrete_end; i++)
      {
      fprintf(fp,"\\\n%s.h ",argv[i]);
      }
    for (i = concrete_h_start; i <= concrete_h_end; i++)
      {
      fprintf(fp,"\\\n%s.h ",argv[i]);
      }
    fprintf(fp,"\n\n");
    }

  /* some more tcl rules */
  for (i = concrete_start; i <= concrete_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);
    }
  for (i = abstract_start; i <= abstract_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);
    }
  for (i = concrete_h_start; i <= concrete_h_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);
    }
  for (i = abstract_h_start; i <= abstract_h_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);
    }

  /* create JAVA_CLASSES */
  fprintf(fp,"JAVA_CLASSES = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\n../java/vtk/%s.java ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  /* create JAVA_CODE */
  fprintf(fp,"JAVA_CODE = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\n../java/vtk/%s.class ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  /* create JAVA_WRAP */
  fprintf(fp,"JAVA_WRAP = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\njava/%sJava.o ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  for (i = concrete_start; i <= concrete_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }
  for (i = abstract_start; i <= abstract_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }
  for (i = concrete_h_start; i <= concrete_h_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }
  for (i = abstract_h_start; i <= abstract_h_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }

  /* create PYTHON_WRAP */
  fprintf(fp,"PYTHON_WRAP = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\npython/%sPython.o ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"python/%sPython.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapPython ../wrap/hints\n\trm -f python/%sPython.cxx; ${VTK_OBJ}/wrap/vtkWrapPython ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > python/%sPython.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      }
    }

  return 0;
}

<commit_msg>ERR: Was not generating dependencies for vtkTkImageWindowWidget.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome,
			      char *extraPtr[], int extra_num);

int concrete_num, concrete_start, concrete_end;
int abstract_num, abstract_start, abstract_end;
int concrete_h_num, concrete_h_start, concrete_h_end;
int abstract_h_num, abstract_h_start, abstract_h_end;
int extra_num, extra_start, extra_end;

int main (int argc, char *argv[])
{
  int i;
  FILE *fp;
  char *vtkLocal = argv[3];
  char *vtkHome = argv[1];
  char filename[1024];

  /* start by counting */
  for (i = 2; i < argc; i++)
    {
    if (!strcmp(argv[i],"extra"))
      {
      extra_start = i + 1;
      }
    if (!strcmp(argv[i],"concrete"))
      {
      extra_end = i - 1;
      concrete_start = i+1;
      }
    if (!strcmp(argv[i],"abstract"))
      {
      concrete_end = i -1;
      abstract_start = i+1;
      }
    if (!strcmp(argv[i],"concrete_h"))
      {
      abstract_end = i -1;
      concrete_h_start = i+1;
      }
    if (!strcmp(argv[i],"abstract_h"))
      {
      concrete_h_end = i -1;
      abstract_h_start = i+1;
      abstract_h_end = argc - 1;
      }
    }
  extra_num = extra_end - extra_start + 1;
  concrete_num = concrete_end - concrete_start + 1;
  abstract_num = abstract_end - abstract_start + 1;
  concrete_h_num = concrete_h_end - concrete_h_start + 1;
  abstract_h_num = abstract_h_end - abstract_h_start + 1;

  /* concrete should be called first */
  fp = fopen("targets.make","w");
  if (!fp)
    {
    fprintf(stderr,"Unable to open target.make for writing!");
    exit(1);
    }

  // for all the .cxx files generate depends
  if ((concrete_num + abstract_num) > 0)
    {
    for (i = concrete_start; i <= concrete_end; i++)
      {
      fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal,argv[i]);
      sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]);
      OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
      fprintf(fp,"\n");
      }
    for (i = abstract_start; i <= abstract_end; i++)
      {
      fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal, argv[i]);
      sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]);
      OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
      fprintf(fp,"\n");
      }
    fprintf(fp,"\n\n");
    }

  // if this is the graphics library we need to add dependencies
  // for three odd classes vtkXRenderWindowInteractor,
  // vtkXRenderWindowTclInteractor and vtkTkRenderWidget
  if (!strcmp(vtkLocal + strlen(vtkLocal) - 8,"graphics"))
    {
    fprintf(fp,"vtkXRenderWindowInteractor.o : %s/vtkXRenderWindowInteractor.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkXRenderWindowInteractor.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    fprintf(fp,"vtkXRenderWindowTclInteractor.o : %s/vtkXRenderWindowTclInteractor.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkXRenderWindowTclInteractor.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    fprintf(fp,"vtkTkRenderWidget.o : %s/vtkTkRenderWidget.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkTkRenderWidget.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    }

  // if this is the imaging library we need to add dependencies
  if (!strcmp(vtkLocal + strlen(vtkLocal) - 7,"imaging"))
    {
    fprintf(fp,"vtkTkImageViewerWidget.o : %s/vtkTkImageViewerWidget.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkTkImageViewerWidget.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    }

  // if this is the imaging library we need to add dependencies
  if (!strcmp(vtkLocal + strlen(vtkLocal) - 7,"imaging"))
    {
    fprintf(fp,"vtkTkImageWindowWidget.o : %s/vtkTkImageWindowWidget.cxx",
	    vtkLocal);
    sprintf(filename,"%s/vtkTkImageWindowWidget.cxx",vtkLocal);
    OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
    fprintf(fp,"\n");
    }

  // generate depends for all the tcl wrappers
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"tcl/%sTcl.cxx : %s/%s.h %s/common/vtkTclUtil.h %s/wrap/vtkParse.y %s/wrap/vtkWrapTcl.c",
	      argv[i],vtkLocal,argv[i],vtkHome,vtkHome, vtkHome);
      sprintf(filename,"%s/%s.h",vtkLocal,argv[i]);
      OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num);
      fprintf(fp,"\n");
      }
    }
  fprintf(fp,"\n\n");

  /* create SRC_OBJ */
  /* create TCL_OBJ */
  if ((concrete_num + abstract_num) > 0)
    {
    fprintf(fp,"SRC_OBJ = ");
    for (i = concrete_start; i <= concrete_end; i++)
      {
      fprintf(fp,"\\\n%s.o ",argv[i]);
      }
    for (i = abstract_start; i <= abstract_end; i++)
      {
      fprintf(fp,"\\\n%s.o ",argv[i]);
      }
    fprintf(fp,"\n\n");
    }

  fprintf(fp,"TCL_OBJ = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\ntcl/%sTcl.o ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  /* create TCL_NEWS */
  if ((concrete_num + concrete_h_num) > 0)
    {
    fprintf(fp,"TCL_NEWS = ");
    for (i = concrete_start; i <= concrete_end; i++)
      {
      fprintf(fp,"\\\n%s.h ",argv[i]);
      }
    for (i = concrete_h_start; i <= concrete_h_end; i++)
      {
      fprintf(fp,"\\\n%s.h ",argv[i]);
      }
    fprintf(fp,"\n\n");
    }

  /* some more tcl rules */
  for (i = concrete_start; i <= concrete_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);
    }
  for (i = abstract_start; i <= abstract_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);
    }
  for (i = concrete_h_start; i <= concrete_h_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 1, argv[i]);
    }
  for (i = abstract_h_start; i <= abstract_h_end; i++)
    {
    fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n",
	    argv[i],argv[i],argv[i], argv[i], 0, argv[i]);
    }

  /* create JAVA_CLASSES */
  fprintf(fp,"JAVA_CLASSES = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\n../java/vtk/%s.java ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  /* create JAVA_CODE */
  fprintf(fp,"JAVA_CODE = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\n../java/vtk/%s.class ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  /* create JAVA_WRAP */
  fprintf(fp,"JAVA_WRAP = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\njava/%sJava.o ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  for (i = concrete_start; i <= concrete_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }
  for (i = abstract_start; i <= abstract_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }
  for (i = concrete_h_start; i <= concrete_h_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }
  for (i = abstract_h_start; i <= abstract_h_end; i++)
    {
      fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
    }

  /* create PYTHON_WRAP */
  fprintf(fp,"PYTHON_WRAP = ");
  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"\\\npython/%sPython.o ",argv[i]);
      }
    }
  fprintf(fp,"\n\n");

  for (i = concrete_start; i < argc; i++)
    {
    if (strcmp(argv[i],"abstract")&&
	strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h"))
      {
      fprintf(fp,"python/%sPython.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapPython ../wrap/hints\n\trm -f python/%sPython.cxx; ${VTK_OBJ}/wrap/vtkWrapPython ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > python/%sPython.cxx\n",
	      argv[i],argv[i],argv[i], argv[i], argv[i]);
      }
    }

  return 0;
}

<|endoftext|>


<commit_before>// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data
//
// call from command line like, for instance:
// root -l 'workbench.cpp()'

R__LOAD_LIBRARY(libRooFit)

#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <list>
#include <unistd.h>  // usleep
#include <sys/types.h>  // for kill
#include <signal.h>     // for kill
#include <ctime>

using namespace RooFit;

////////////////////////////////////////////////////////////////////////////////////////////////////
// timing_flag is used to activate only selected timing statements [1-7]
// num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu)
// parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode
//                      { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 }
////////////////////////////////////////////////////////////////////////////////////////////////////

void workbench_sarajevo(std::string workspace_filepath,
               std::string workspace_name="HWWRun2GGF",
               std::string model_config_name="ModelConfig",
               std::string data_name="obsData",
               int num_cpu=1,
               int optConst=2,
               int parallel_interleave=0,
               bool cpu_affinity=true,
               int seed=1,
               int timing_flag=1,
               bool time_num_ints=false,
               bool fork_timer = false,
               int fork_timer_sleep_us = 100000,
               int print_level=0,
               bool debug=false,
               bool total_cpu_timing=true,
               bool fix_binned_pdfs=false,
               bool zero_initial_POI=false,
               std::string POI_name=""
               // bool callNLLfirst=false
               ) {
  if (debug) {
    RooMsgService::instance().addStream(DEBUG);
    // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
  }

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges

  if (timing_flag > 0) {
    RooJsonListFile outfile;

    outfile.open("timing_meta.json");
    std::list<std::string> names = {"timestamp",
                                    "workspace_filepath", "workspace_name",
                                    "model_config_name", "data_name",
                                    "num_cpu", "parallel_interleave", "cpu_affinity",
                                    "seed", "pid", "time_num_ints",
                                    "optConst", "print_level", "timing_flag"};
    outfile.set_member_names(names.begin(), names.end());

    // int timestamp = std::time(nullptr);

    outfile << std::time(nullptr)
            << workspace_filepath << workspace_name
            << model_config_name << data_name
            << num_cpu << parallel_interleave << cpu_affinity
            << seed << getpid() << time_num_ints
            << optConst << print_level << timing_flag;
  }

  RooTrace::timing_flag = timing_flag;
  if (time_num_ints) {
    RooTrace::set_time_numInts(kTRUE);
  }

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  if (printlevel == 0) {
    RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  }

  RooRandom::randomGenerator()->SetSeed(seed);

  // Load the workspace data and pdf
  TFile *_file0 = TFile::Open(workspace_filepath.c_str());

  RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str()));

  // Activate binned likelihood calculation for binned models
  if (fix_binned_pdfs) {
    RooFIter iter = w->components().fwdIterator();
    RooAbsArg* component_arg;
    while((component_arg = iter.next())) {
      if (component_arg->IsA() == RooRealSumPdf::Class()) {
        component_arg->setAttribute("BinnedLikelihood");
        std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl;
      }
    }
  }

  RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str()));

  // RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;
  RooAbsPdf* pdf = mc->GetPdf();
  RooAbsData * data = w->data(data_name.c_str());

  // Manually set initial values of parameter of interest
  if (zero_initial_POI) {
    if (POI_name.length() > 0) {
      RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first());
      POI->setVal(0);
    } else {
      std::cout << "POI_name is empty!" << std::endl;
      exit(1);
    }
  }

  // --- Perform extended ML fit of composite PDF to data ---

  RooJsonListFile outfile;
  RooWallTimer timer;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json");
    outfile.add_member_name("walltime_s")
           .add_member_name("segment")
           .add_member_name("pid");
  }

  RooJsonListFile outfile_cpu;
  RooCPUTimer ctimer;

  if (total_cpu_timing) {
    outfile_cpu.open("timing_full_minimize_cpu.json");
    outfile_cpu.add_member_name("cputime_s")
               .add_member_name("segment")
               .add_member_name("pid");
  }

  Bool_t cpuAffinity;
  if (cpu_affinity) {
    cpuAffinity = kTRUE;
  } else {
    cpuAffinity = kFALSE;
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* RARnll(pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave),
                       CPUAffinity(cpuAffinity)));//, "Extended");
    // std::shared_ptr<RooAbsTestStatistic> nll(dynamic_cast<RooAbsTestStatistic*>(RARnll)); // shared_ptr gives odd error in ROOT cling!
    // RooAbsTestStatistic * nll = dynamic_cast<RooAbsTestStatistic*>(RARnll);

    // if (time_evaluate_partition) {
    //   nll->setTimeEvaluatePartition(kTRUE);
    // }

    // if (callNLLfirst) {
    //   RARnll->getVal();
    // }

    RooMinimizer m(*RARnll);
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    int pid = -1;

    if (fork_timer) {
      pid = fork();
    }
    if (pid == 0) {
      /* child */
      timer.start();
      while (true) {
        timer.stop();
        std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
        usleep(fork_timer_sleep_us);
      }
    }
    else {
      /* parent */

      double time_migrad, time_hesse, time_minos;
      double ctime_migrad, ctime_hesse, ctime_minos;

      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }
      // m.hesse();

      m.migrad();

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "migrad" << getpid();
        time_migrad = timer.timing_s();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "migrad" << getpid();
        ctime_migrad = ctimer.timing_s();
      }
      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }

      m.hesse();

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "hesse" << getpid();
        time_hesse = timer.timing_s();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "hesse" << getpid();
        ctime_hesse = ctimer.timing_s();
      }
      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }

      m.minos(*mc->GetParametersOfInterest());

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "minos" << getpid();
        time_minos = timer.timing_s();

        outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "minos" << getpid();
        ctime_minos = ctimer.timing_s();

        outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid();
      }

      if (pid > 0) {
        // a child exists
        kill(pid, SIGKILL);
      }
    }

    delete RARnll;
  }
}
<commit_msg>Add MP::GradMinimizer option to new workbench<commit_after>// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data
//
// call from command line like, for instance:
// root -l 'workbench.cpp()'

R__LOAD_LIBRARY(libRooFit)

#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <list>
#include <unistd.h>  // usleep
#include <sys/types.h>  // for kill
#include <signal.h>     // for kill
#include <ctime>

using namespace RooFit;

////////////////////////////////////////////////////////////////////////////////////////////////////
// timing_flag is used to activate only selected timing statements [1-7]
// num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu)
// parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode
//                      { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 }
////////////////////////////////////////////////////////////////////////////////////////////////////

void workbench_sarajevo(std::string workspace_filepath,
               bool with_MPGradMinimizer=false,
               std::string workspace_name="HWWRun2GGF",
               std::string model_config_name="ModelConfig",
               std::string data_name="obsData",
               int num_cpu=1,
               int optConst=2,
               int parallel_interleave=0,
               bool cpu_affinity=true,
               int seed=1,
               int timing_flag=1,
               bool time_num_ints=false,
               bool fork_timer = false,
               int fork_timer_sleep_us = 100000,
               int print_level=0,
               bool debug=false,
               bool total_cpu_timing=true,
               bool fix_binned_pdfs=false,
               bool zero_initial_POI=false,
               std::string POI_name=""
               // bool callNLLfirst=false
               ) {
  if (debug) {
    RooMsgService::instance().addStream(DEBUG);
    // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
  }

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges

  if (timing_flag > 0) {
    RooJsonListFile outfile;

    outfile.open("timing_meta.json");
    std::list<std::string> names = {"timestamp",
                                    "workspace_filepath", "workspace_name",
                                    "model_config_name", "data_name",
                                    "num_cpu", "parallel_interleave", "cpu_affinity",
                                    "seed", "pid", "time_num_ints",
                                    "optConst", "print_level", "timing_flag"};
    outfile.set_member_names(names.begin(), names.end());

    // int timestamp = std::time(nullptr);

    outfile << std::time(nullptr)
            << workspace_filepath << workspace_name
            << model_config_name << data_name
            << num_cpu << parallel_interleave << cpu_affinity
            << seed << getpid() << time_num_ints
            << optConst << print_level << timing_flag;
  }

  RooTrace::timing_flag = timing_flag;
  if (time_num_ints) {
    RooTrace::set_time_numInts(kTRUE);
  }

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  if (printlevel == 0) {
    RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  }

  RooRandom::randomGenerator()->SetSeed(seed);

  // Load the workspace data and pdf
  TFile *_file0 = TFile::Open(workspace_filepath.c_str());

  RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str()));

  // Activate binned likelihood calculation for binned models
  if (fix_binned_pdfs) {
    RooFIter iter = w->components().fwdIterator();
    RooAbsArg* component_arg;
    while((component_arg = iter.next())) {
      if (component_arg->IsA() == RooRealSumPdf::Class()) {
        component_arg->setAttribute("BinnedLikelihood");
        std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl;
      }
    }
  }

  RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str()));

  // RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;
  RooAbsPdf* pdf = mc->GetPdf();
  RooAbsData * data = w->data(data_name.c_str());

  // Manually set initial values of parameter of interest
  if (zero_initial_POI) {
    if (POI_name.length() > 0) {
      RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first());
      POI->setVal(0);
    } else {
      std::cout << "POI_name is empty!" << std::endl;
      exit(1);
    }
  }

  // --- Perform extended ML fit of composite PDF to data ---

  RooJsonListFile outfile;
  RooWallTimer timer;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json");
    outfile.add_member_name("walltime_s")
           .add_member_name("segment")
           .add_member_name("pid");
  }

  RooJsonListFile outfile_cpu;
  RooCPUTimer ctimer;

  if (total_cpu_timing) {
    outfile_cpu.open("timing_full_minimize_cpu.json");
    outfile_cpu.add_member_name("cputime_s")
               .add_member_name("segment")
               .add_member_name("pid");
  }

  Bool_t cpuAffinity;
  if (cpu_affinity) {
    cpuAffinity = kTRUE;
  } else {
    cpuAffinity = kFALSE;
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* RARnll;

    if (!with_MPGradMinimizer) {
      RARnll = pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave),
                       CPUAffinity(cpuAffinity));
      RooMinimizer m(*RARnll);
    } else {
      RARnll = pdf->createNLL(*data);

      RooFit::MultiProcess::GradMinimizer m(*RARnll, num_cpu);
    }
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    int pid = -1;

    if (fork_timer) {
      pid = fork();
    }
    if (pid == 0) {
      /* child */
      timer.start();
      while (true) {
        timer.stop();
        std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
        usleep(fork_timer_sleep_us);
      }
    }
    else {
      /* parent */

      double time_migrad, time_hesse, time_minos;
      double ctime_migrad, ctime_hesse, ctime_minos;

      if (timing_flag == 1) {
        timer.start();
      }
      if (total_cpu_timing) {
        ctimer.start();
      }
      // m.hesse();

      m.migrad();

      if (timing_flag == 1) {
        timer.stop();
      }
      if (total_cpu_timing) {
        ctimer.stop();
      }
      if (timing_flag == 1) {
        std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << "migrad" << getpid();
        time_migrad = timer.timing_s();
      }
      if (total_cpu_timing) {
        std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl;
        outfile_cpu << ctimer.timing_s() << "migrad" << getpid();
        ctime_migrad = ctimer.timing_s();
      }

      if (!with_MPGradMinimizer) {

        if (timing_flag == 1) {
          timer.start();
        }
        if (total_cpu_timing) {
          ctimer.start();
        }

        m.hesse();

        if (timing_flag == 1) {
          timer.stop();
        }
        if (total_cpu_timing) {
          ctimer.stop();
        }
        if (timing_flag == 1) {
          std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl;
          outfile << timer.timing_s() << "hesse" << getpid();
          time_hesse = timer.timing_s();
        }
        if (total_cpu_timing) {
          std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl;
          outfile_cpu << ctimer.timing_s() << "hesse" << getpid();
          ctime_hesse = ctimer.timing_s();
        }
        if (timing_flag == 1) {
          timer.start();
        }
        if (total_cpu_timing) {
          ctimer.start();
        }

        m.minos(*mc->GetParametersOfInterest());

        if (timing_flag == 1) {
          timer.stop();
        }
        if (total_cpu_timing) {
          ctimer.stop();
        }
        if (timing_flag == 1) {
          std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl;
          outfile << timer.timing_s() << "minos" << getpid();
          time_minos = timer.timing_s();

          outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid();
        }
        if (total_cpu_timing) {
          std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl;
          outfile_cpu << ctimer.timing_s() << "minos" << getpid();
          ctime_minos = ctimer.timing_s();

          outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid();
        }

      }

      if (pid > 0) {
        // a child exists
        kill(pid, SIGKILL);
      }
    }

    delete RARnll;
  }
}
<|endoftext|>


<commit_before>// Reads tabletop segmentation clusters and publishes the table.

#include "rviz_objdetect_caller/publish_table.h"

#include "geometry_msgs/Pose.h"
#include "geometry_msgs/Vector3.h"
#include "object_manipulation_msgs/FindClusterBoundingBox.h"
#include "ros/ros.h"
#include "rviz_objdetect_caller/Clusters.h"
#include "tabletop_object_detector/Table.h"
#include "visualization_msgs/Marker.h"

#include <string>
#include <vector>

using geometry_msgs::Pose;
using geometry_msgs::Vector3;
using rviz_objdetect_caller::Clusters;
using std::string;
using std::vector;
using tabletop_object_detector::Table;
using visualization_msgs::Marker;

namespace {
static const string kFixedFrame = "/base_link";
static const string kNamespace = "table";
}

namespace rviz_objdetect_caller {
TablePublisher::TablePublisher(
    string clusters_topic,
    string table_topic):
  clusters_topic_(clusters_topic),
  node_handle_(),
  marker_pub_(node_handle_.advertise<Marker>("segmented_objects_table", 10)) {
}

TablePublisher::~TablePublisher() {
}

void TablePublisher::Start() {
  subscriber_ = node_handle_.subscribe(
    clusters_topic_,
    10,
    &TablePublisher::ClusterCallback,
    this);
}

void TablePublisher::MakeMarker(
    const Pose& pose,
    const Vector3& dimensions,
    Marker* marker) {
  marker->header.frame_id = kFixedFrame;
  marker->header.stamp = ros::Time::now();
  marker->ns = kNamespace;
  marker->id = 0;
  marker->action = Marker::ADD;
  marker->type = Marker::CUBE;
  marker->pose = pose;
  marker->scale = dimensions;
  marker->color.a = 1;
  marker->color.r = 1;
  marker->color.g = 0;
  marker->color.b = 1;
}

void TablePublisher::ClusterCallback(const Clusters& clusters) {
  Table table = clusters.table;
  Marker marker;
  Vector3 dimensions;
  dimensions.x = table.x_max - table.x_min;
  dimensions.y = table.y_max - table.y_min;
  dimensions.z = 0.05;
  MakeMarker(
    table.pose.pose,
    dimensions,
    &marker);
  marker_pub_.publish(marker);
}
}  // namespace rviz_objdetect_caller
<commit_msg>Compute table's real position relative to the robot.<commit_after>// Reads tabletop segmentation clusters and publishes the table.

#include "rviz_objdetect_caller/publish_table.h"

#include "geometry_msgs/Pose.h"
#include "geometry_msgs/Vector3.h"
#include "object_manipulation_msgs/FindClusterBoundingBox.h"
#include "ros/ros.h"
#include "rviz_objdetect_caller/Clusters.h"
#include "tabletop_object_detector/Table.h"
#include "visualization_msgs/Marker.h"

#include <string>
#include <vector>

using geometry_msgs::Pose;
using geometry_msgs::Vector3;
using rviz_objdetect_caller::Clusters;
using std::string;
using std::vector;
using tabletop_object_detector::Table;
using visualization_msgs::Marker;

namespace {
static const string kFixedFrame = "/base_link";
static const string kNamespace = "table";
}

namespace rviz_objdetect_caller {
TablePublisher::TablePublisher(
    string clusters_topic,
    string table_topic):
  clusters_topic_(clusters_topic),
  node_handle_(),
  marker_pub_(node_handle_.advertise<Marker>("segmented_objects_table", 10)) {
}

TablePublisher::~TablePublisher() {
}

void TablePublisher::Start() {
  subscriber_ = node_handle_.subscribe(
    clusters_topic_,
    10,
    &TablePublisher::ClusterCallback,
    this);
}

void TablePublisher::MakeMarker(
    const Pose& pose,
    const Vector3& dimensions,
    Marker* marker) {
  marker->header.frame_id = kFixedFrame;
  marker->header.stamp = ros::Time::now();
  marker->ns = kNamespace;
  marker->id = 0;
  marker->action = Marker::ADD;
  marker->type = Marker::CUBE;
  marker->pose = pose;
  marker->scale = dimensions;
  marker->color.a = 1;
  marker->color.r = 1;
  marker->color.g = 0;
  marker->color.b = 1;
}

void TablePublisher::ClusterCallback(const Clusters& clusters) {
  Table table = clusters.table;
  Marker marker;
  Pose message_pose = table.pose.pose;
  Pose pose = message_pose;
  float depth = table.x_max - table.x_min;
  float width = table.y_max - table.y_min;
  pose.position.x += table.x_min + depth / 2;
  pose.position.y += table.y_min + width / 2;
  Vector3 dimensions;
  dimensions.x = table.x_max - table.x_min;
  dimensions.y = table.y_max - table.y_min;
  dimensions.z = 0.05;
  MakeMarker(
    table.pose.pose,
    dimensions,
    &marker);
  marker_pub_.publish(marker);
}
}  // namespace rviz_objdetect_caller
<|endoftext|>


<commit_before>/***************************************************************************
    copyright            : (C) 2002 - 2008 by Scott Wheeler
    email                : wheeler@kde.org
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
 *   USA                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <tfile.h>
#include <tstring.h>

#include "fileref.h"
#include "asffile.h"
#include "mpegfile.h"
#include "vorbisfile.h"
#include "flacfile.h"
#include "oggflacfile.h"
#include "mpcfile.h"
#include "mp4file.h"
#include "wavpackfile.h"
#include "speexfile.h"
#include "trueaudiofile.h"
#include "aifffile.h"
#include "wavfile.h"

using namespace TagLib;

class FileRef::FileRefPrivate : public RefCounter
{
public:
  FileRefPrivate(File *f) : RefCounter(), file(f) {}
  ~FileRefPrivate() {
    delete file;
  }

  File *file;
  static List<const FileTypeResolver *> fileTypeResolvers;
};

List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers;

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

FileRef::FileRef()
{
  d = new FileRefPrivate(0);
}

FileRef::FileRef(FileName fileName, bool readAudioProperties,
                 AudioProperties::ReadStyle audioPropertiesStyle)
{
  d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle));
}

FileRef::FileRef(File *file)
{
  d = new FileRefPrivate(file);
}

FileRef::FileRef(const FileRef &ref) : d(ref.d)
{
  d->ref();
}

FileRef::~FileRef()
{
  if(d->deref())
    delete d;
}

Tag *FileRef::tag() const
{
  return d->file->tag();
}

AudioProperties *FileRef::audioProperties() const
{
  return d->file->audioProperties();
}

File *FileRef::file() const
{
  return d->file;
}

bool FileRef::save()
{
  return d->file->save();
}

const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static
{
  FileRefPrivate::fileTypeResolvers.prepend(resolver);
  return resolver;
}

StringList FileRef::defaultFileExtensions()
{
  StringList l;

  l.append("ogg");
  l.append("flac");
  l.append("oga");
  l.append("mp3");
  l.append("mpc");
  l.append("wv");
  l.append("spx");
  l.append("tta");
#ifdef WITH_MP4
  l.append("m4a");
  l.append("m4b");
  l.append("m4p");
  l.append("3g2");
#endif
#ifdef WITH_ASF
  l.append("wma");
  l.append("asf");
#endif
  l.append("aif");
  l.append("aiff");
  l.append("wav");

  return l;
}

bool FileRef::isNull() const
{
  return !d->file || !d->file->isValid();
}

FileRef &FileRef::operator=(const FileRef &ref)
{
  if(&ref == this)
    return *this;

  if(d->deref())
    delete d;

  d = ref.d;
  d->ref();

  return *this;
}

bool FileRef::operator==(const FileRef &ref) const
{
  return ref.d->file == d->file;
}

bool FileRef::operator!=(const FileRef &ref) const
{
  return ref.d->file != d->file;
}

File *FileRef::create(FileName fileName, bool readAudioProperties,
                      AudioProperties::ReadStyle audioPropertiesStyle) // static
{

  List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin();

  for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) {
    File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle);
    if(file)
      return file;
  }

  // Ok, this is really dumb for now, but it works for testing.

  String s;

#ifdef _WIN32
  s = (wcslen((const wchar_t *) fileName) > 0) ? String((const wchar_t *) fileName) : String((const char *) fileName);
#else
  s = fileName;
#endif

  // If this list is updated, the method defaultFileExtensions() should also be
  // updated.  However at some point that list should be created at the same time
  // that a default file type resolver is created.

  if(s.size() > 4) {
    if(s.substr(s.size() - 4, 4).upper() == ".OGG")
      return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MP3")
      return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".OGA")
      return new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 5, 5).upper() == ".FLAC")
      return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MPC")
      return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 3, 3).upper() == ".WV")
      return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".SPX")
      return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".TTA")
      return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle);
#ifdef WITH_MP4
    if(s.substr(s.size() - 4, 4).upper() == ".M4A" ||
       s.substr(s.size() - 4, 4).upper() == ".M4B" ||
       s.substr(s.size() - 4, 4).upper() == ".M4P" ||
       s.substr(s.size() - 4, 4).upper() == ".3G2")
      return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
#ifdef WITH_ASF
    if(s.substr(s.size() - 4, 4).upper() == ".WMA")
      return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
    if(s.substr(s.size() - 4, 4).upper() == ".AIF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".WAV")
      return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle);
  }
  if(s.size() > 5) {
    if(s.substr(s.size() - 5, 5).upper() == ".AIFF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
  }

  return 0;
}
<commit_msg>Finish making .asf readable, thanks Lukas<commit_after>/***************************************************************************
    copyright            : (C) 2002 - 2008 by Scott Wheeler
    email                : wheeler@kde.org
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
 *   USA                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <tfile.h>
#include <tstring.h>

#include "fileref.h"
#include "asffile.h"
#include "mpegfile.h"
#include "vorbisfile.h"
#include "flacfile.h"
#include "oggflacfile.h"
#include "mpcfile.h"
#include "mp4file.h"
#include "wavpackfile.h"
#include "speexfile.h"
#include "trueaudiofile.h"
#include "aifffile.h"
#include "wavfile.h"

using namespace TagLib;

class FileRef::FileRefPrivate : public RefCounter
{
public:
  FileRefPrivate(File *f) : RefCounter(), file(f) {}
  ~FileRefPrivate() {
    delete file;
  }

  File *file;
  static List<const FileTypeResolver *> fileTypeResolvers;
};

List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers;

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

FileRef::FileRef()
{
  d = new FileRefPrivate(0);
}

FileRef::FileRef(FileName fileName, bool readAudioProperties,
                 AudioProperties::ReadStyle audioPropertiesStyle)
{
  d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle));
}

FileRef::FileRef(File *file)
{
  d = new FileRefPrivate(file);
}

FileRef::FileRef(const FileRef &ref) : d(ref.d)
{
  d->ref();
}

FileRef::~FileRef()
{
  if(d->deref())
    delete d;
}

Tag *FileRef::tag() const
{
  return d->file->tag();
}

AudioProperties *FileRef::audioProperties() const
{
  return d->file->audioProperties();
}

File *FileRef::file() const
{
  return d->file;
}

bool FileRef::save()
{
  return d->file->save();
}

const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static
{
  FileRefPrivate::fileTypeResolvers.prepend(resolver);
  return resolver;
}

StringList FileRef::defaultFileExtensions()
{
  StringList l;

  l.append("ogg");
  l.append("flac");
  l.append("oga");
  l.append("mp3");
  l.append("mpc");
  l.append("wv");
  l.append("spx");
  l.append("tta");
#ifdef WITH_MP4
  l.append("m4a");
  l.append("m4b");
  l.append("m4p");
  l.append("3g2");
#endif
#ifdef WITH_ASF
  l.append("wma");
  l.append("asf");
#endif
  l.append("aif");
  l.append("aiff");
  l.append("wav");

  return l;
}

bool FileRef::isNull() const
{
  return !d->file || !d->file->isValid();
}

FileRef &FileRef::operator=(const FileRef &ref)
{
  if(&ref == this)
    return *this;

  if(d->deref())
    delete d;

  d = ref.d;
  d->ref();

  return *this;
}

bool FileRef::operator==(const FileRef &ref) const
{
  return ref.d->file == d->file;
}

bool FileRef::operator!=(const FileRef &ref) const
{
  return ref.d->file != d->file;
}

File *FileRef::create(FileName fileName, bool readAudioProperties,
                      AudioProperties::ReadStyle audioPropertiesStyle) // static
{

  List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin();

  for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) {
    File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle);
    if(file)
      return file;
  }

  // Ok, this is really dumb for now, but it works for testing.

  String s;

#ifdef _WIN32
  s = (wcslen((const wchar_t *) fileName) > 0) ? String((const wchar_t *) fileName) : String((const char *) fileName);
#else
  s = fileName;
#endif

  // If this list is updated, the method defaultFileExtensions() should also be
  // updated.  However at some point that list should be created at the same time
  // that a default file type resolver is created.

  if(s.size() > 4) {
    if(s.substr(s.size() - 4, 4).upper() == ".OGG")
      return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MP3")
      return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".OGA")
      return new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 5, 5).upper() == ".FLAC")
      return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".MPC")
      return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 3, 3).upper() == ".WV")
      return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".SPX")
      return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".TTA")
      return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle);
#ifdef WITH_MP4
    if(s.substr(s.size() - 4, 4).upper() == ".M4A" ||
       s.substr(s.size() - 4, 4).upper() == ".M4B" ||
       s.substr(s.size() - 4, 4).upper() == ".M4P" ||
       s.substr(s.size() - 4, 4).upper() == ".3G2")
      return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
#ifdef WITH_ASF
    if(s.substr(s.size() - 4, 4).upper() == ".WMA")
      return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".ASF")
      return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle);
#endif
    if(s.substr(s.size() - 4, 4).upper() == ".AIF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
    if(s.substr(s.size() - 4, 4).upper() == ".WAV")
      return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle);
  }
  if(s.size() > 5) {
    if(s.substr(s.size() - 5, 5).upper() == ".AIFF")
      return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle);
  }

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*!
 *  Copyright (c) 2016 by Contributors
 * \file graph_attr_types.cc
 * \brief Graph node data structure.
 */
#include <nnvm/graph.h>
#include <nnvm/op_attr_types.h>
#include <limits>

namespace nnvm {

const IndexedGraph& Graph::indexed_graph() const {
  if (indexed_graph_ == nullptr) {
    indexed_graph_.reset(new IndexedGraph(*this));
  }
  return *indexed_graph_;
}

// a subgraph should not refer to any nodes with higher level
// where "level" refers to the nested depth of the subgraph
// e.g. the main graph is level 0
// subgraphs of the main graph is level 1
// subgraphs of the subgraphs of the main graph is level 2
static void SubgraphSanityCheck(const std::vector<std::shared_ptr<Symbol>> &subgraphs) {
  std::vector<const std::vector<nnvm::NodeEntry>*> curr_level;
  std::vector<const std::vector<nnvm::NodeEntry>*> next_level;
  std::unordered_map<nnvm::Node*, uint32_t> node2level;
  for (auto &subgraph : subgraphs)
    next_level.push_back(&subgraph->outputs);
  for (uint32_t level = 0; !next_level.empty(); ++level) {
    curr_level.swap(next_level);
    next_level.clear();
    for (const std::vector<NodeEntry> *graph_ptr : curr_level) {
      const std::vector<NodeEntry> &graph = *graph_ptr;
      DFSVisit(graph, [&next_level, &node2level, level](const NodePtr& n) {
        nnvm::Node *node = n.get();
        // if the node is visited, but on a different level, then check failed
        // if check failed here or before, we stop doing anything, but raise an error
        CHECK(!node2level.count(node) || node2level[node] == level)
          << "A subgraph should not depend on the outputs of nodes on higher levels";
        // otherwise, this node belongs to the current level
        node2level[node] = level;
        // subgraphs of current node belongs to next level
        for (const auto& subgraph : n->attrs.subgraphs) {
          next_level.push_back(&subgraph->outputs);
        }
      });
    }
  }
}

// implement constructor from graph
IndexedGraph::IndexedGraph(const Graph &g) {
  entry_rptr_.push_back(0);
  std::vector<size_t> inputs_rptr{0}, control_rptr{0};
  std::vector<std::shared_ptr<Symbol>> subgraphs;

  DFSVisit(g.outputs, [this, &inputs_rptr, &control_rptr, &subgraphs]
             (const NodePtr& n) {
      const auto& is_ghost = Op::GetAttr<TIsGhost>("TIsGhost");
      if (!n->is_variable() && is_ghost.get(n->op(), false)) return;
      CHECK_LT(nodes_.size(), std::numeric_limits<uint32_t>::max());
      uint32_t nid = static_cast<uint32_t>(nodes_.size());
      CHECK(n);
      for (const auto &subgraph : n->attrs.subgraphs)
        subgraphs.push_back(subgraph);
      // nodes_
      IndexedGraph::Node new_node;
      new_node.source = n.get();
      new_node.weak_ref = n;
      nodes_.emplace_back(std::move(new_node));
      // arg_nodes_
      if (n->is_variable()) {
        input_nodes_.push_back(nid);
      }
      // node2index_
      node2index_[n.get()] = nid;
      // entry rptr
      entry_rptr_.push_back(entry_rptr_.back() + n->num_outputs());
      // input entries
      for (const auto& e : n->inputs) {
        auto it = node2index_.find(e.node.get());
        CHECK(it != node2index_.end() && it->first == e.node.get());
        input_entries_.emplace_back(NodeEntry{it->second, e.index, e.version});
      }
      inputs_rptr.push_back(input_entries_.size());
      // control deps
      for (const auto& nptr : n->control_deps) {
        if (!nptr->is_variable() && is_ghost.get(nptr->op(), false)) continue;
        auto it = node2index_.find(nptr.get());
        CHECK(it != node2index_.end() && it->first == nptr.get());
        control_deps_.push_back(it->second);
      }
      control_rptr.push_back(control_deps_.size());
  });
  if (!subgraphs.empty())
    SubgraphSanityCheck(subgraphs);

  for (const auto& e : g.outputs) {
    outputs_.emplace_back(NodeEntry{
        node2index_.at(e.node.get()), e.index, e.version});
  }

  static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs");
  // setup array view
  // input_entries_ and control_rptr must not change after this step.
  const NodeEntry* iptr = dmlc::BeginPtr(input_entries_);
  for (size_t nid = 0; nid < nodes_.size(); ++nid) {
    nodes_[nid].inputs = array_view<NodeEntry>(
        iptr + inputs_rptr[nid], iptr + inputs_rptr[nid + 1]);
    if (nodes_[nid].source->op() != nullptr &&
        fmutate_inputs.count(nodes_[nid].source->op())) {
      for (uint32_t i : fmutate_inputs[nodes_[nid].source->op()](nodes_[nid].source->attrs)) {
        mutable_input_nodes_.insert(nodes_[nid].inputs[i].node_id);
      }
    }
  }
  const uint32_t* cptr = dmlc::BeginPtr(control_deps_);
  for (size_t nid = 0; nid < nodes_.size(); ++nid) {
    nodes_[nid].control_deps = array_view<uint32_t>(
        cptr + control_rptr[nid], cptr + control_rptr[nid + 1]);
  }
}

}  // namespace nnvm
<commit_msg>Minor improve to assertion (#3295)<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*!
 *  Copyright (c) 2016 by Contributors
 * \file graph_attr_types.cc
 * \brief Graph node data structure.
 */
#include <nnvm/graph.h>
#include <nnvm/op_attr_types.h>
#include <limits>

namespace nnvm {

const IndexedGraph& Graph::indexed_graph() const {
  if (indexed_graph_ == nullptr) {
    indexed_graph_.reset(new IndexedGraph(*this));
  }
  return *indexed_graph_;
}

// a subgraph should not refer to any nodes with higher level
// where "level" refers to the nested depth of the subgraph
// e.g. the main graph is level 0
// subgraphs of the main graph is level 1
// subgraphs of the subgraphs of the main graph is level 2
static void SubgraphSanityCheck(const std::vector<std::shared_ptr<Symbol>> &subgraphs) {
  std::vector<const std::vector<nnvm::NodeEntry>*> curr_level;
  std::vector<const std::vector<nnvm::NodeEntry>*> next_level;
  std::unordered_map<nnvm::Node*, uint32_t> node2level;
  for (auto &subgraph : subgraphs)
    next_level.push_back(&subgraph->outputs);
  for (uint32_t level = 0; !next_level.empty(); ++level) {
    curr_level.swap(next_level);
    next_level.clear();
    for (const std::vector<NodeEntry> *graph_ptr : curr_level) {
      const std::vector<NodeEntry> &graph = *graph_ptr;
      DFSVisit(graph, [&next_level, &node2level, level](const NodePtr& n) {
        nnvm::Node *node = n.get();
        // if the node is visited, but on a different level, then check failed
        // if check failed here or before, we stop doing anything, but raise an error
        CHECK(!node2level.count(node) || node2level[node] == level)
          << "A subgraph should not depend on the outputs of nodes on higher levels";
        // otherwise, this node belongs to the current level
        node2level[node] = level;
        // subgraphs of current node belongs to next level
        for (const auto& subgraph : n->attrs.subgraphs) {
          next_level.push_back(&subgraph->outputs);
        }
      });
    }
  }
}

// implement constructor from graph
IndexedGraph::IndexedGraph(const Graph &g) {
  entry_rptr_.push_back(0);
  std::vector<size_t> inputs_rptr{0}, control_rptr{0};
  std::vector<std::shared_ptr<Symbol>> subgraphs;

  DFSVisit(g.outputs, [this, &inputs_rptr, &control_rptr, &subgraphs]
             (const NodePtr& n) {
      const auto& is_ghost = Op::GetAttr<TIsGhost>("TIsGhost");
      if (!n->is_variable() && is_ghost.get(n->op(), false)) return;
      CHECK_LT(nodes_.size(), std::numeric_limits<uint32_t>::max());
      uint32_t nid = static_cast<uint32_t>(nodes_.size());
      CHECK(n);
      for (const auto &subgraph : n->attrs.subgraphs)
        subgraphs.push_back(subgraph);
      // nodes_
      IndexedGraph::Node new_node;
      new_node.source = n.get();
      new_node.weak_ref = n;
      nodes_.emplace_back(std::move(new_node));
      // arg_nodes_
      if (n->is_variable()) {
        input_nodes_.push_back(nid);
      }
      // node2index_
      node2index_[n.get()] = nid;
      // entry rptr
      entry_rptr_.push_back(entry_rptr_.back() + n->num_outputs());
      // input entries
      for (const auto& e : n->inputs) {
        auto it = node2index_.find(e.node.get());
        CHECK(it != node2index_.end() && it->first == e.node.get());
        input_entries_.emplace_back(NodeEntry{it->second, e.index, e.version});
      }
      inputs_rptr.push_back(input_entries_.size());
      // control deps
      for (const auto& nptr : n->control_deps) {
        if (!nptr->is_variable() && is_ghost.get(nptr->op(), false)) continue;
        auto it = node2index_.find(nptr.get());
        CHECK(it != node2index_.end()) << "control dep not found in graph";
        control_deps_.push_back(it->second);
      }
      control_rptr.push_back(control_deps_.size());
  });
  if (!subgraphs.empty())
    SubgraphSanityCheck(subgraphs);

  for (const auto& e : g.outputs) {
    outputs_.emplace_back(NodeEntry{
        node2index_.at(e.node.get()), e.index, e.version});
  }

  static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs");
  // setup array view
  // input_entries_ and control_rptr must not change after this step.
  const NodeEntry* iptr = dmlc::BeginPtr(input_entries_);
  for (size_t nid = 0; nid < nodes_.size(); ++nid) {
    nodes_[nid].inputs = array_view<NodeEntry>(
        iptr + inputs_rptr[nid], iptr + inputs_rptr[nid + 1]);
    if (nodes_[nid].source->op() != nullptr &&
        fmutate_inputs.count(nodes_[nid].source->op())) {
      for (uint32_t i : fmutate_inputs[nodes_[nid].source->op()](nodes_[nid].source->attrs)) {
        mutable_input_nodes_.insert(nodes_[nid].inputs[i].node_id);
      }
    }
  }
  const uint32_t* cptr = dmlc::BeginPtr(control_deps_);
  for (size_t nid = 0; nid < nodes_.size(); ++nid) {
    nodes_[nid].control_deps = array_view<uint32_t>(
        cptr + control_rptr[nid], cptr + control_rptr[nid + 1]);
  }
}

}  // namespace nnvm
<|endoftext|>