Example #1
0
void program::

define_stage(std::shared_ptr<stage> & stage_ptr)
{
  switch(stage_ptr->type())
  {
    case GL_VERTEX_SHADER :

    stages_[0].swap(stage_ptr);
    break;

    case GL_GEOMETRY_SHADER :

    stages_[3].swap(stage_ptr);
    break;

    case GL_FRAGMENT_SHADER :

    stages_[4].swap(stage_ptr);
    break;
  }
}
void SpatialConvolution::init(std::shared_ptr<TorchData> input) {
  RASSERT(input->type() == TorchDataType::TENSOR_DATA);

  Tensor<float>* in = TO_TENSOR_PTR(input.get());
  RASSERT(in->dim() == 3);
  RASSERT(in->size()[2] == feats_in_);

  if (output != nullptr) {
    uint32_t owidth = in->size()[0] - filt_width_ + 1 + 2 * padding_;
    uint32_t oheight = in->size()[1] - filt_height_ + 1 + 2 * padding_;
    const uint32_t* out_size = TO_TENSOR_PTR(output.get())->size();
    if (out_size[0] != owidth || out_size[1] != oheight ||
        out_size[2] != feats_out_) {
      output = nullptr;
    }
  }
  if (output == nullptr) {
    uint32_t out_dim[3];
    out_dim[0] = in->size()[0] - filt_width_ + 1 + 2 * padding_;
    out_dim[1] = in->size()[1] - filt_height_ + 1 + 2 * padding_;
    out_dim[2] = feats_out_;
    output.reset(new Tensor<float>(3, out_dim));
  }
}
Example #3
0
void FormFactorStrategy::execute(ParameterList &paras,
                                  std::shared_ptr<Parameter> &out) {
  if (out && checkType != out->type())
    throw BadParameter(
        "FormFactorStrat::execute() | Parameter type mismatch!");

#ifndef NDEBUG
  // Check parameter type
  if (checkType != out->type())
    throw(WrongParType("FormFactorStrat::execute() | "
                       "Output parameter is of type " +
                       std::string(ParNames[out->type()]) +
                       " and conflicts with expected type " +
                       std::string(ParNames[checkType])));

  // How many parameters do we expect?
  size_t check_nInt = 0;
  size_t nInt = paras.intValues().size();
  //L, MesonRadius, FFType, Daughter1Mass, Daughter2Mass
  size_t check_nDouble = 5;
  size_t nDouble = paras.doubleValues().size();
  nDouble += paras.doubleParameters().size();
  size_t check_nComplex = 0;
  size_t nComplex = paras.complexValues().size();
  size_t check_nMInteger = 0;
  size_t nMInteger = paras.mIntValues().size();
  // DataSample.mDoubleValue(pos) (mSq)
  size_t check_nMDouble = 1;
  size_t nMDouble = paras.mDoubleValues().size();
  size_t check_nMComplex = 0;
  size_t nMComplex = paras.mComplexValues().size();

  // Check size of parameter list
  if (nInt != check_nInt)
    throw(BadParameter("FormFactorStrat::execute() | "
                       "Number of IntParameters does not match: " +
                       std::to_string(nInt) + " given but " +
                       std::to_string(check_nInt) + " expected."));
  if (nDouble != check_nDouble)
    throw(BadParameter("FormFactorStrat::execute() | "
                       "Number of FitParameters does not match: " +
                       std::to_string(nDouble) + " given but " +
                       std::to_string(check_nDouble) + " expected."));
  if (nComplex != check_nComplex)
    throw(BadParameter("FormFactorStrat::execute() | "
                       "Number of ComplexParameters does not match: " +
                       std::to_string(nComplex) + " given but " +
                       std::to_string(check_nComplex) + " expected."));
  if (nMInteger != check_nMInteger)
    throw(BadParameter("FormFactorStrat::execute() | "
                       "Number of MultiInt does not match: " +
                       std::to_string(nMInteger) + " given but " +
                       std::to_string(check_nMInteger) + " expected."));
  if (nMDouble != check_nMDouble)
    throw(BadParameter("FormFactorStrat::execute() | "
                       "Number of MultiDoubles does not match: " +
                       std::to_string(nMDouble) + " given but " +
                       std::to_string(check_nMDouble) + " expected."));
  if (nMComplex != check_nMComplex)
    throw(BadParameter("FormFactorStrat::execute() | "
                       "Number of MultiComplexes does not match: " +
                       std::to_string(nMComplex) + " given but " +
                       std::to_string(check_nMComplex) + " expected."));
#endif

  size_t n = paras.mDoubleValue(0)->values().size();
  if (!out)
    out = MDouble("", n);
  auto par =
      std::static_pointer_cast<Value<std::vector<double>>>(out);
  auto &results = par->values(); // reference

  // Get parameters from ParameterList:
  // We use the same order of the parameters as was used during tree
  // construction.
  unsigned int orbitL = paras.doubleValue(0)->value();
  double MesonRadius = paras.doubleParameter(0)->value();
  FormFactorType ffType = FormFactorType(paras.doubleValue(1)->value());
  double ma = paras.doubleParameter(1)->value();
  double mb = paras.doubleParameter(2)->value();

  // calc function for each point
  for (unsigned int ele = 0; ele < n; ele++) {
    try {
      results.at(ele) = FormFactorDecorator::formFactor(
          paras.mDoubleValue(0)->values().at(ele), ma, mb, orbitL,
          MesonRadius, ffType);
    } catch (std::exception &ex) {
      LOG(ERROR) << "FormFactorStrategy::execute() | " << ex.what();
      throw(std::runtime_error("FormFactorStrategy::execute() | "
                               "Evaluation of dynamic function failed!"));
    }
  }
}
Example #4
0
std::shared_ptr<const Type> ast::GetTypeVisitor::operator()(const std::shared_ptr<Variable> value) const {
    return value->type();
}
Example #5
0
inline
If::If(std::shared_ptr<Expression> expr, std::shared_ptr<Statement> statement)
        : expr_(expr), statement_(statement) {
    if (expr_->type() != symbols::Type::boolean)
        expr->error("Boolean required in if");
}
Example #6
0
void
ActionWarehouse::addActionBlock(std::shared_ptr<Action> action)
{
  /**
   * Note: This routine uses the XTerm colors directly which is not advised for general purpose
   * output coloring. Most users should prefer using Problem::colorText() which respects the
   * "color_output" option for terminals that do not support coloring.  Since this routine is
   * intended for debugging only and runs before several objects exist in the system, we are just
   * using the constants directly.
   */
  std::string registered_identifier =
      action->parameters().get<std::string>("registered_identifier");
  std::set<std::string> tasks;

  if (_show_parser)
    Moose::err << COLOR_DEFAULT << "Parsing Syntax:        " << COLOR_GREEN << action->name()
               << '\n'
               << COLOR_DEFAULT << "Building Action:       " << COLOR_DEFAULT << action->type()
               << '\n'
               << COLOR_DEFAULT << "Registered Identifier: " << COLOR_GREEN << registered_identifier
               << '\n'
               << COLOR_DEFAULT << "Specific Task:         " << COLOR_CYAN
               << action->specificTaskName() << '\n';

  /**
   * We need to see if the current Action satisfies multiple tasks. There are a few cases to
   * consider:
   *
   * 1. The current Action is registered with multiple syntax blocks. In this case we can only use
   *    the current instance to satisfy the specific task listed for this syntax block.  We can
   *    detect this case by inspecting whether it has a "specific task name" set in the Action
   *    instance.
   *
   * 2. This action does not have a valid "registered identifier" set in the Action instance. This
   *    means that this Action was not built by the Parser.  It was most likely created through a
   *    Meta-Action (See Case 3 for exception). In this case, the ActionFactory itself would have
   *    already set the task it found from the build info used to construct the Action so we'd
   *    arbitrarily satisify a single task in this case.
   *
   * 3. The current Action is registered with only a single syntax block. In this case we can simply
   *    re-use the current instance to act and satisfy _all_ registered tasks. This is the normal
   *    case where we have a Parser-built Action that does not have a specific task name to satisfy.
   *    We will use the Action "type" to retrieve the list of tasks that this Action may satisfy.
   */
  if (action->specificTaskName() != "") // Case 1
    tasks.insert(action->specificTaskName());
  else if (registered_identifier == "" &&
           _syntax.getSyntaxByAction(action->type()).size() > 1) // Case 2
  {
    std::set<std::string> local_tasks = action->getAllTasks();
    mooseAssert(local_tasks.size() == 1, "More than one task inside of the " << action->name());
    tasks.insert(*local_tasks.begin());
  }
  else // Case 3
    tasks = _action_factory.getTasksByAction(action->type());

  // TODO: Now we need to weed out the double registrations!
  for (const auto & task : tasks)
  {
    // Some error checking
    if (!_syntax.hasTask(task))
      mooseError("A(n) ", task, " is not a registered task");

    // Make sure that the ObjectAction task and Action task are consistent
    // otherwise that means that is action was built by the wrong type
    std::shared_ptr<MooseObjectAction> moa = std::dynamic_pointer_cast<MooseObjectAction>(action);
    if (moa.get())
    {
      const InputParameters & mparams = moa->getObjectParams();

      if (mparams.have_parameter<std::string>("_moose_base"))
      {
        const std::string & base = mparams.get<std::string>("_moose_base");

        if (!_syntax.verifyMooseObjectTask(base, task))
          mooseError("Task ", task, " is not registered to build ", base, " derived objects");
      }
      else
        mooseError("Unable to locate registered base parameter for ", moa->getMooseObjectType());
    }

    // Add the current task to current action
    action->appendTask(task);

    if (_show_parser)
      Moose::err << COLOR_YELLOW << "Adding Action:         " << COLOR_DEFAULT << action->type()
                 << " (" << COLOR_YELLOW << task << COLOR_DEFAULT << ")\n";

    // Add it to the warehouse
    _action_blocks[task].push_back(action.get());
  }
  _all_ptrs.push_back(action);

  if (_show_parser)
    Moose::err << std::endl;
}
Example #7
0
void Unit::give_ability(std::shared_ptr<UnitAbility> ability) {
	this->ability_available.emplace(std::make_pair(ability->type(), ability));
}
Example #8
0
void Unit::give_ability(std::shared_ptr<UnitAbility> ability) {
	this->ability_available.insert({ability->type(), ability});
}
Example #9
0
static bool
CompileAsset(
    std::shared_ptr<xcassets::Asset::Asset> const &asset,
    std::shared_ptr<xcassets::Asset::Asset> const &parent,
    Filesystem *filesystem,
    Options const &options,
    Compile::Output *compileOutput,
    Result *result)
{
    std::string filename = FSUtil::GetBaseName(asset->path());
    std::string name = FSUtil::GetBaseNameWithoutExtension(filename);
    switch (asset->type()) {
        case xcassets::Asset::AssetType::AppIconSet: {
            auto appIconSet = std::static_pointer_cast<xcassets::Asset::AppIconSet>(asset);
            if (appIconSet->name().name() == options.appIcon()) {
                Compile::AppIconSet::Compile(appIconSet, filesystem, compileOutput, result);
            }
            break;
        }
        case xcassets::Asset::AssetType::BrandAssets: {
            auto brandAssets = std::static_pointer_cast<xcassets::Asset::BrandAssets>(asset);
            Compile::BrandAssets::Compile(brandAssets, filesystem, compileOutput, result);
            CompileChildren(brandAssets->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::Catalog: {
            auto catalog = std::static_pointer_cast<xcassets::Asset::Catalog>(asset);
            CompileChildren(catalog->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::ComplicationSet: {
            auto complicationSet = std::static_pointer_cast<xcassets::Asset::ComplicationSet>(asset);
            Compile::ComplicationSet::Compile(complicationSet, filesystem, compileOutput, result);
            CompileChildren(complicationSet->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::DataSet: {
            auto dataSet = std::static_pointer_cast<xcassets::Asset::DataSet>(asset);
            Compile::DataSet::Compile(dataSet, filesystem, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::GCDashboardImage: {
            auto dashboardImage = std::static_pointer_cast<xcassets::Asset::GCDashboardImage>(asset);
            Compile::GCDashboardImage::Compile(dashboardImage, filesystem, compileOutput, result);
            CompileChildren(dashboardImage->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::GCLeaderboard: {
            auto leaderboard = std::static_pointer_cast<xcassets::Asset::GCLeaderboard>(asset);
            Compile::GCLeaderboard::Compile(leaderboard, filesystem, compileOutput, result);
            CompileChildren(leaderboard->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::GCLeaderboardSet: {
            auto leaderboardSet = std::static_pointer_cast<xcassets::Asset::GCLeaderboardSet>(asset);
            Compile::GCLeaderboardSet::Compile(leaderboardSet, filesystem, compileOutput, result);
            CompileChildren(leaderboardSet->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::Group: {
            auto group = std::static_pointer_cast<xcassets::Asset::Group>(asset);
            CompileChildren(group->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::IconSet: {
            auto iconSet = std::static_pointer_cast<xcassets::Asset::IconSet>(asset);
            Compile::IconSet::Compile(iconSet, filesystem, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::ImageSet: {
            auto imageSet = std::static_pointer_cast<xcassets::Asset::ImageSet>(asset);
            Compile::ImageSet::Compile(imageSet, filesystem, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::ImageStack: {
            auto imageStack = std::static_pointer_cast<xcassets::Asset::ImageStack>(asset);
            Compile::ImageStack::Compile(imageStack, filesystem, compileOutput, result);
            CompileChildren(imageStack->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::ImageStackLayer: {
            auto imageStackLayer = std::static_pointer_cast<xcassets::Asset::ImageStackLayer>(asset);
            Compile::ImageStackLayer::Compile(imageStackLayer, filesystem, compileOutput, result);
            // TODO: CompileChildren(imageStackLayer->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
        case xcassets::Asset::AssetType::LaunchImage: {
            auto launchImage = std::static_pointer_cast<xcassets::Asset::LaunchImage>(asset);
            if (launchImage->name().name() == options.launchImage()) {
                Compile::LaunchImage::Compile(launchImage, filesystem, compileOutput, result);
            }
            break;
        }
        case xcassets::Asset::AssetType::SpriteAtlas: {
            auto spriteAtlas = std::static_pointer_cast<xcassets::Asset::SpriteAtlas>(asset);
            Compile::SpriteAtlas::Compile(spriteAtlas, filesystem, compileOutput, result);
            CompileChildren(spriteAtlas->children(), asset, filesystem, options, compileOutput, result);
            break;
        }
    }

    return true;
}
void ApplicationController::messageReceived(std::shared_ptr<Message> message)
{
    std::cout << "Message Type: " << static_cast<int32_t>(message->type()) << std::endl;
    _messageHandler.handleMessage(message.get());

}
Example #11
0
void DataEntryXDMF3::WriteDataItem(std::string const &url, std::string const &key, const index_box_type &idx_box,
                                 std::shared_ptr<data::DataEntry> const &data, int indent) {
    int fndims = 3;
    int dof = 1;
    std::string number_type;
    index_tuple lo, hi;
    std::tie(lo, hi) = idx_box;

    auto g_id = H5GroupTryOpen(m_h5_root_, url);

    if (auto array = std::dynamic_pointer_cast<ArrayBase>(data->GetEntity())) {
        number_type = XDMFNumberType(array->value_type_info());
        fndims = 3;
        dof = 1;
        index_type inner_lo[SP_ARRAY_MAX_NDIMS];
        index_type inner_hi[SP_ARRAY_MAX_NDIMS];
        index_type outer_lo[SP_ARRAY_MAX_NDIMS];
        index_type outer_hi[SP_ARRAY_MAX_NDIMS];

        array->GetShape(outer_lo, outer_hi);

        hsize_t m_shape[SP_ARRAY_MAX_NDIMS];
        hsize_t m_start[SP_ARRAY_MAX_NDIMS];
        hsize_t m_count[SP_ARRAY_MAX_NDIMS];
        hsize_t m_stride[SP_ARRAY_MAX_NDIMS];
        hsize_t m_block[SP_ARRAY_MAX_NDIMS];
        for (int i = 0; i < fndims; ++i) {
            inner_lo[i] = lo[i];
            inner_hi[i] = hi[i];
            ASSERT(inner_lo[i] >= outer_lo[i]);
            m_shape[i] = static_cast<hsize_t>(outer_hi[i] - outer_lo[i]);
            m_start[i] = static_cast<hsize_t>(inner_lo[i] - outer_lo[i]);
            m_count[i] = static_cast<hsize_t>(inner_hi[i] - inner_lo[i]);
            m_stride[i] = static_cast<hsize_t>(1);
            m_block[i] = static_cast<hsize_t>(1);
        }
        hid_t m_space = H5Screate_simple(fndims, &m_shape[0], nullptr);
        H5_ERROR(H5Sselect_hyperslab(m_space, H5S_SELECT_SET, &m_start[0], &m_stride[0], &m_count[0], &m_block[0]));
        hid_t f_space = H5Screate_simple(fndims, &m_count[0], nullptr);
        hid_t dset;
        hid_t d_type = H5NumberType(array->value_type_info());
        H5_ERROR(dset = H5Dcreate(g_id, key.c_str(), d_type, f_space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT));
        H5_ERROR(H5Dwrite(dset, d_type, m_space, f_space, H5P_DEFAULT, array->pointer()));

        H5_ERROR(H5Dclose(dset));
        if (m_space != H5S_ALL) H5_ERROR(H5Sclose(m_space));
        if (f_space != H5S_ALL) H5_ERROR(H5Sclose(f_space));
    } else if (data->type() == data::DataEntry::DN_ARRAY) {
        hid_t dset;
        fndims = 3;
        dof = data->size();
        hid_t d_type = H5NumberType(data->GetEntity(0)->value_type_info());

        //        for (int i = 0; i < dof; ++i) {
        //            if (auto array = std::dynamic_pointer_cast<ArrayBase>(data->GetEntity(i))) {
        //                if (d_type == H5T_NO_CLASS) { d_type = H5NumberType(array->value_type_info()); }
        //                auto t_ndims = array->GetNDIMS();
        //                index_type t_lo[SP_ARRAY_MAX_NDIMS], t_hi[SP_ARRAY_MAX_NDIMS];
        //                array->GetIndexBox(t_lo, t_hi);
        //                ndims = std::max(ndims, array->GetNDIMS());
        //                for (int n = 0; n < t_ndims; ++n) {
        //                    m_lo[n] = std::min(m_lo[n], t_lo[n]);
        //                    m_hi[n] = std::max(m_hi[n], t_hi[n]);
        //                }
        //            }
        //        }

        {
            hsize_t f_shape[SP_ARRAY_MAX_NDIMS];
            for (int i = 0; i < fndims; ++i) { f_shape[i] = static_cast<hsize_t>(hi[i] - lo[i]); }
            f_shape[fndims] = static_cast<hsize_t>(dof);
            hid_t f_space = H5Screate_simple(fndims + 1, &f_shape[0], nullptr);
            //        hid_t plist = H5P_DEFAULT;
            //        if (H5Tequal(d_type, H5T_NATIVE_DOUBLE)) {
            //            plist = H5Pcreate(H5P_DATASET_CREATE);
            //            double fillval = std::numeric_limits<double>::quiet_NaN();
            //            H5_ERROR(H5Pset_fill_value(plist, H5T_NATIVE_DOUBLE, &fillval));
            //        }
            H5_ERROR(dset = H5Dcreate(g_id, key.c_str(), d_type, f_space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT));
            //        H5_ERROR(H5Pclose(plist));
            H5_ERROR(H5Sclose(f_space));
        }
        for (int i = 0; i < dof; ++i) {
            if (auto array = std::dynamic_pointer_cast<ArrayBase>(data->GetEntity(i))) {
                ASSERT(array->pointer() != nullptr);

                index_type t_lo[SP_ARRAY_MAX_NDIMS], t_hi[SP_ARRAY_MAX_NDIMS];
                auto m_ndims = array->GetShape(t_lo, t_hi);

                hsize_t m_shape[SP_ARRAY_MAX_NDIMS];
                hsize_t m_start[SP_ARRAY_MAX_NDIMS];
                hsize_t m_count[SP_ARRAY_MAX_NDIMS];
                hsize_t m_stride[SP_ARRAY_MAX_NDIMS];
                hsize_t m_block[SP_ARRAY_MAX_NDIMS];

                hsize_t f_shape[SP_ARRAY_MAX_NDIMS];
                hsize_t f_start[SP_ARRAY_MAX_NDIMS];
                hsize_t f_count[SP_ARRAY_MAX_NDIMS];
                hsize_t f_stride[SP_ARRAY_MAX_NDIMS];
                hsize_t f_block[SP_ARRAY_MAX_NDIMS];
                for (int n = 0; n < m_ndims; ++n) {
                    m_shape[n] = static_cast<hsize_t>(t_hi[n] - t_lo[n]);
                    m_start[n] = static_cast<hsize_t>(lo[n] - t_lo[n]);
                    m_count[n] = static_cast<hsize_t>(hi[n] - lo[n]);
                    m_stride[n] = static_cast<hsize_t>(1);
                    m_block[n] = static_cast<hsize_t>(1);

                    f_stride[n] = static_cast<hsize_t>(1);
                    f_block[n] = static_cast<hsize_t>(1);

                    f_shape[n] = static_cast<hsize_t>(hi[n] - lo[n]);
                    f_start[n] = static_cast<hsize_t>(0);
                    f_count[n] = static_cast<hsize_t>(hi[n] - lo[n]);
                    f_stride[n] = static_cast<hsize_t>(1);
                    f_block[n] = static_cast<hsize_t>(1);
                }
                for (int n = m_ndims; n < fndims + 1; ++n) {
                    m_shape[n] = static_cast<hsize_t>(1);
                    m_start[n] = static_cast<hsize_t>(0);
                    m_count[n] = static_cast<hsize_t>(1);
                    m_stride[n] = static_cast<hsize_t>(1);
                    m_block[n] = static_cast<hsize_t>(1);

                    f_shape[n] = static_cast<hsize_t>(1);
                    f_start[n] = static_cast<hsize_t>(0);
                    f_count[n] = static_cast<hsize_t>(1);
                    f_stride[n] = static_cast<hsize_t>(1);
                    f_block[n] = static_cast<hsize_t>(1);
                }

                m_shape[fndims] = static_cast<hsize_t>(dof);
                m_start[fndims] = static_cast<hsize_t>(0);
                f_shape[fndims] = static_cast<hsize_t>(dof);
                f_start[fndims] = static_cast<hsize_t>(i);

                hid_t m_space = H5Screate_simple(m_ndims, &m_shape[0], nullptr);
                H5_ERROR(
                    H5Sselect_hyperslab(m_space, H5S_SELECT_SET, &m_start[0], &m_stride[0], &m_count[0], &m_block[0]));
                hid_t f_space = H5Screate_simple(fndims + 1, &f_shape[0], nullptr);
                H5_ERROR(
                    H5Sselect_hyperslab(f_space, H5S_SELECT_SET, &f_start[0], &f_stride[0], &f_count[0], &f_block[0]));
                H5_ERROR(H5Dwrite(dset, d_type, m_space, f_space, H5P_DEFAULT, array->pointer()));

                if (f_space != H5S_ALL) H5_ERROR(H5Sclose(f_space));
                if (m_space != H5S_ALL) H5_ERROR(H5Sclose(m_space));
            }
        }
        H5_ERROR(H5Dclose(dset));

    } else {
        UNIMPLEMENTED;
    }

    H5Gclose(g_id);

    os << std::setw(indent) << " "
       << "<DataItem Format=\"HDF\" " << number_type << " Dimensions=\"";

    for (int i = 0; i < fndims; ++i) { os << " " << hi[i] - lo[i]; };
    if (dof > 1) { os << " " << dof; }
    os << "\">" << m_h5_prefix_ << ":" << url << "/" << key << "</DataItem>" << std::endl;
}
void SpatialDivisiveNormalization::init(std::shared_ptr<TorchData> input) {
  RASSERT(input->type() == TorchDataType::TENSOR_DATA);
  Tensor<float>* in = TO_TENSOR_PTR(input.get());

  RASSERT(in->dim() == 3);

  if (output != nullptr) {
    if (!in->isSameSizeAs(*TO_TENSOR_PTR(output.get()))) {
      // Input dimension has changed!
      cleanup();
    }
  }

  if (output == nullptr) {
    output.reset(new Tensor<float>(in->dim(), in->size()));
    std_pass1_.reset(new Tensor<float>(in->dim(), in->size()));
    std_pass2_.reset(new Tensor<float>(in->dim(), in->size()));
  }
  if (kernel_norm_ == nullptr) {
    bool onedim_kernel = kernel_->dim() == 1;
    const float n_feats = (float)in->size()[2];

    // Clone and normalize the input kernel
    kernel_norm_.reset(Tensor<float>::clone(*kernel_));
    float sum = Tensor<float>::slowSum(*kernel_norm_);
    float div_val = onedim_kernel ? (sum * sqrtf(n_feats)) : (sum * n_feats);
    Tensor<float>::div(*kernel_norm_, div_val);
  }
  if (std_coef_ == nullptr) {
    uint32_t std_coeff_size[2];
    std_coeff_size[0] = TO_TENSOR_PTR(output.get())->size()[0];
    std_coeff_size[1] = TO_TENSOR_PTR(output.get())->size()[1];
    std_coef_.reset(new Tensor<float>(2, std_coeff_size));

    std::unique_ptr<float[]> std_coef_cpu(new float[std_coef_->nelems()]);
    std::unique_ptr<float[]> kernel_norm_cpu(new float[kernel_norm_->nelems()]);
    kernel_norm_->getData(kernel_norm_cpu.get());
    bool onedim_kernel = kernel_->dim() == 1;

    // Filter an image of all 1 values to create the normalization constants
    // See norm_test.lua for proof that this works as well as:
    // https://github.com/andresy/torch/blob/master/extra/nn/SpatialDivisiveNormalization.lua
    int32_t n_feats = TO_TENSOR_PTR(output.get())->size()[2];
    int32_t height = TO_TENSOR_PTR(output.get())->size()[1];
    int32_t width = TO_TENSOR_PTR(output.get())->size()[0];
    if (onedim_kernel) {
      // 1D case - The filter is seperable, but we'll just do the dumb 2D
      // version since we only do this once on startup.  --> O(n * m)
      int32_t kernel_size = kernel_norm_->size()[0];
      int32_t filt_rad = (kernel_size - 1) / 2;
      for (int32_t v = 0; v < height; v++) {
        for (int32_t u = 0; u < width; u++) {
          float tmp = 0.0f;
          for (int32_t v_filt = -filt_rad; v_filt <= filt_rad; v_filt++) {
            for (int32_t u_filt = -filt_rad; u_filt <= filt_rad; u_filt++) {
              int32_t u_in = u + u_filt;
              int32_t v_in = v + v_filt;
              if (u_in >= 0 && u_in < width && v_in >= 0 && v_in < height) {
                // Pixel is inside --> We'll effectively clamp zeros elsewhere.
                tmp += (kernel_norm_cpu[v_filt + filt_rad] *
                        kernel_norm_cpu[u_filt + filt_rad]);
              }
            }
          }
          std_coef_cpu[v * width + u] = tmp / n_feats;
        }
      }
    } else {
      // 2D case
      int32_t kernel_size_u = kernel_norm_->size()[0];
      int32_t kernel_size_v = kernel_norm_->size()[1];
      int32_t filt_rad_u = (kernel_size_u - 1) / 2;
      int32_t filt_rad_v = (kernel_size_v - 1) / 2;
      for (int32_t v = 0; v < height; v++) {
        for (int32_t u = 0; u < width; u++) {
          float tmp = 0.0f;
          for (int32_t v_filt = -filt_rad_v; v_filt <= filt_rad_v; v_filt++) {
            for (int32_t u_filt = -filt_rad_u; u_filt <= filt_rad_u; u_filt++) {
              int32_t u_in = u + u_filt;
              int32_t v_in = v + v_filt;
              if (u_in >= 0 && u_in < width && v_in >= 0 && v_in < height) {
                // Pixel is inside --> We'll effectively clamp zeros elsewhere.
                tmp += kernel_norm_cpu[(v_filt + filt_rad_v) * kernel_size_u +
                                       (u_filt + filt_rad_u)];
              }
            }
          }
          std_coef_cpu[v * width + u] = tmp / n_feats;
        }
      }
    }
    std_coef_->setData(std_coef_cpu.get());
  }
  if (std_ == nullptr) {
    uint32_t std_coeff_size[2];
    std_coeff_size[0] = TO_TENSOR_PTR(output.get())->size()[0];
    std_coeff_size[1] = TO_TENSOR_PTR(output.get())->size()[1];
    std_.reset(new Tensor<float>(2, std_coeff_size));
  }
}
Example #13
0
bool IPFIXFlowBridge::canExport (std::shared_ptr<const Msg>& m) {

    // for now we only can handle bog-standard Flows.
    return (m->type() == MSG_ID(Flow));
}
Example #14
0
bool
CRNTranscoder::transcode(std::shared_ptr<render::AbstractTexture>  texture,
                         const std::string&                        textureType,
                         std::shared_ptr<WriterOptions>            writerOptions,
                         render::TextureFormat                     outFormat,
                         std::vector<unsigned char>&               out)
{
#ifndef MINKO_NO_CRNLIB
    crnlib::console::disable_output();

    const auto textureFormatToCRNTextureFomat = std::unordered_map<TextureFormat, crn_format, Hash<TextureFormat>>
    {
        { TextureFormat::RGB_DXT1,      crn_format::cCRNFmtDXT1 },
        { TextureFormat::RGBA_DXT1,     crn_format::cCRNFmtDXT1 },
        { TextureFormat::RGBA_DXT3,     crn_format::cCRNFmtDXT3 },
        { TextureFormat::RGBA_DXT5,     crn_format::cCRNFmtDXT5 }
    };

    const auto startTimeStamp = std::clock();

    const auto generateMipmaps = writerOptions->generateMipmaps(textureType);

    switch (texture->type())
    {
    case TextureType::Texture2D:
    {
        auto texture2d = std::static_pointer_cast<Texture>(texture);

        auto texture2dData = std::vector<unsigned char>(
            texture2d->data().begin(),
            texture2d->data().end()
        );

        const auto useSRGBSpace = writerOptions->useTextureSRGBSpace(textureType);

        crn_comp_params compressorParameters;

        compressorParameters.m_width = texture2d->width();
        compressorParameters.m_height = texture2d->height();
        compressorParameters.m_pImages[0][0] = reinterpret_cast<const unsigned int*>(texture2dData.data());

        compressorParameters.set_flag(cCRNCompFlagDXT1AForTransparency, outFormat == TextureFormat::RGBA_DXT1);
        compressorParameters.set_flag(cCRNCompFlagHierarchical, false);
        compressorParameters.set_flag(cCRNCompFlagPerceptual, useSRGBSpace);

        compressorParameters.m_file_type = cCRNFileTypeDDS;
        compressorParameters.m_format = textureFormatToCRNTextureFomat.at(outFormat);
        compressorParameters.m_dxt_compressor_type = compressorTypeFromQualityFactor(
            outFormat,
            writerOptions->compressedTextureQualityFactor(textureType)
        );
        compressorParameters.m_dxt_quality = crn_dxt_quality::cCRNDXTQualityUber;
        compressorParameters.m_quality_level = cCRNMaxQualityLevel;

        crn_mipmap_params compressorMipParameters;
        compressorMipParameters.m_mode = generateMipmaps ? cCRNMipModeGenerateMips : cCRNMipModeNoMips;
        compressorMipParameters.m_gamma_filtering = useSRGBSpace;

        unsigned int actualQualityLevel;
        float actualBitrate;

        auto ddsTextureDataSize = 0u;

        auto ddsFileRawData = crn_compress(
            compressorParameters,
            compressorMipParameters,
            ddsTextureDataSize,
            &actualQualityLevel,
            &actualBitrate
        );

        const auto width = texture->width();
        const auto height = texture->height();
        const auto numMipmaps = generateMipmaps ? math::getp2(texture->width()) + 1u : 0u;

        auto ddsFileData = reinterpret_cast<const char*>(ddsFileRawData);

        unsigned int ddsFilecode = 0u;
        memcpy(&ddsFilecode, ddsFileData, 4u);

        if (ddsFilecode != crnlib::cDDSFileSignature)
            return false;

        crnlib::DDSURFACEDESC2 ddsHeader;
        memcpy(&ddsHeader, ddsFileData + 4u, crnlib::cDDSSizeofDDSurfaceDesc2);

        auto mipOffset = crnlib::cDDSSizeofDDSurfaceDesc2 + 4u;

        for (auto i = 0u; i < numMipmaps; ++i)
        {
            const auto mipWidth = width >> i;
            const auto mipHeight = height >> i;
            const auto mipBlocksX = (mipWidth + 3) >> 2;
            const auto mipBlocksY = (mipHeight + 3) >> 2;
            const auto mipRowPitch = mipBlocksX * crnd::crnd_get_bytes_per_dxt_block(compressorParameters.m_format);
            const auto mipDataSize = mipRowPitch * mipBlocksY;

            auto mipData = std::vector<unsigned char>(mipDataSize);

            std::copy(
                ddsFileData + mipOffset,
                ddsFileData + mipOffset + mipDataSize,
                mipData.begin()
            );

            mipOffset += mipDataSize;

            out.insert(
                out.end(),
                mipData.begin(),
                mipData.end()
            );
        }

        break;
    }
    case TextureType::CubeTexture:
    {
        // TODO
        // handle CubeTexture

        return false;
    }
    }

    const auto duration = (std::clock() - startTimeStamp) / static_cast<double>(CLOCKS_PER_SEC);

    LOG_INFO("compressing texture: "
        << texture->width()
        << "x"
        << texture->height()
        << " from "
        << TextureFormatInfo::name(texture->format())
        << " to "
        << TextureFormatInfo::name(outFormat)
        << " with duration of "
        << duration
    );

    return true;
#else
    return false;
#endif
}
Example #15
0
void NetworkConnection::QueueOutgoing(std::shared_ptr<Message> msg) {
  std::lock_guard<std::mutex> lock(m_pending_mutex);

  // Merge with previous.  One case we don't combine: delete/assign loop.
  switch (msg->type()) {
    case Message::kEntryAssign:
    case Message::kEntryUpdate: {
      // don't do this for unassigned id's
      unsigned int id = msg->id();
      if (id == 0xffff) {
        m_pending_outgoing.push_back(msg);
        break;
      }
      if (id < m_pending_update.size() && m_pending_update[id].first != 0) {
        // overwrite the previous one for this id
        auto& oldmsg = m_pending_outgoing[m_pending_update[id].first - 1];
        if (oldmsg && oldmsg->Is(Message::kEntryAssign) &&
            msg->Is(Message::kEntryUpdate)) {
          // need to update assignment with new seq_num and value
          oldmsg = Message::EntryAssign(oldmsg->str(), id, msg->seq_num_uid(),
                                        msg->value(), oldmsg->flags());
        } else
          oldmsg = msg;  // easy update
      } else {
        // new, but remember it
        std::size_t pos = m_pending_outgoing.size();
        m_pending_outgoing.push_back(msg);
        if (id >= m_pending_update.size()) m_pending_update.resize(id + 1);
        m_pending_update[id].first = pos + 1;
      }
      break;
    }
    case Message::kEntryDelete: {
      // don't do this for unassigned id's
      unsigned int id = msg->id();
      if (id == 0xffff) {
        m_pending_outgoing.push_back(msg);
        break;
      }

      // clear previous updates
      if (id < m_pending_update.size()) {
        if (m_pending_update[id].first != 0) {
          m_pending_outgoing[m_pending_update[id].first - 1].reset();
          m_pending_update[id].first = 0;
        }
        if (m_pending_update[id].second != 0) {
          m_pending_outgoing[m_pending_update[id].second - 1].reset();
          m_pending_update[id].second = 0;
        }
      }

      // add deletion
      m_pending_outgoing.push_back(msg);
      break;
    }
    case Message::kFlagsUpdate: {
      // don't do this for unassigned id's
      unsigned int id = msg->id();
      if (id == 0xffff) {
        m_pending_outgoing.push_back(msg);
        break;
      }
      if (id < m_pending_update.size() && m_pending_update[id].second != 0) {
        // overwrite the previous one for this id
        m_pending_outgoing[m_pending_update[id].second - 1] = msg;
      } else {
        // new, but remember it
        std::size_t pos = m_pending_outgoing.size();
        m_pending_outgoing.push_back(msg);
        if (id >= m_pending_update.size()) m_pending_update.resize(id + 1);
        m_pending_update[id].second = pos + 1;
      }
      break;
    }
    case Message::kClearEntries: {
      // knock out all previous assigns/updates!
      for (auto& i : m_pending_outgoing) {
        if (!i) continue;
        auto t = i->type();
        if (t == Message::kEntryAssign || t == Message::kEntryUpdate ||
            t == Message::kFlagsUpdate || t == Message::kEntryDelete ||
            t == Message::kClearEntries)
          i.reset();
      }
      m_pending_update.resize(0);
      m_pending_outgoing.push_back(msg);
      break;
    }
    default:
      m_pending_outgoing.push_back(msg);
      break;
  }
}
    CHECK(std::string("layer") == layer2.name());
    CHECK(1 == layer2.features_size());

    mapnik::layer lyr2("layer",map.srs());

    protozero::pbf_reader pbf_tile(buffer);
    pbf_tile.next();
    protozero::pbf_reader layer3 = pbf_tile.get_message();

    std::shared_ptr<mapnik::vector_tile_impl::tile_datasource_pbf> ds = std::make_shared<
                                    mapnik::vector_tile_impl::tile_datasource_pbf>(
                                        layer3,0,0,0);
    CHECK(ds->get_name() == "layer");
    mapnik::box2d<double> bbox(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789);
    ds->set_envelope(bbox);
    CHECK( ds->type() == mapnik::datasource::Vector );
    CHECK( ds->get_geometry_type() == mapnik::datasource_geometry_t::Collection );
    mapnik::layer_descriptor lay_desc = ds->get_descriptor();
    std::set<std::string> expected_names;
    expected_names.insert("bool");
    expected_names.insert("boolf");
    expected_names.insert("double");
    expected_names.insert("float");
    expected_names.insert("int");
    expected_names.insert("name");
    expected_names.insert("uint");
    std::size_t desc_count = 0;
    for (auto const& desc : lay_desc.get_descriptors())
    {
        ++desc_count;
        CHECK(expected_names.count(desc.get_name()) == 1);
Example #17
0
	/** Sends the response to the client. */
	void send() {
		m_response->type(m_content_type);
		m_response->status(m_status);
		m_response->send(m_body.str());
	}