<commit_before>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Note : the buffer must be given in ONE call
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_SPEEX_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Speex.h"
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Speex::File_Speex()
:File__Analyze()
{
    //Internal
    Identification_Done=false;
}

//***************************************************************************
// Buffer - Per element
//***************************************************************************

//---------------------------------------------------------------------------
void File_Speex::Header_Parse()
{
    //Filling
    Header_Fill_Code(0, "Speex");
    Header_Fill_Size(Element_Size);
}

//---------------------------------------------------------------------------
void File_Speex::Data_Parse()
{
    //Parsing
    if (Identification_Done)
        Comment();
    else
        Identification();
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Speex::Identification()
{
    Element_Name("Identification");

    //Parsing
    Ztring speex_version;
    int32u Speex_version_id, header_size, rate, nb_channels, bitrate, vbr;
    Skip_Local(8,                                               "speex_string");
    Get_Local(20, speex_version,                                "speex_version");
    Get_L4 (Speex_version_id,                                   "Speex_version_id");
    if (Speex_version_id==1)
    {
        Get_L4 (header_size,                                    "header_size");
        Get_L4 (rate,                                           "rate");
        Skip_L4(                                                "mode");
        Skip_L4(                                                "mode_bitstream_version");
        Get_L4 (nb_channels,                                    "nb_channels");
        Get_L4 (bitrate,                                        "bitrate");
        Skip_L4(                                                "frame_size");
        Get_L4 (vbr,                                            "vbr");
        Skip_L4(                                                "frames_per_packet");
        Skip_L4(                                                "extra_headers");
        Skip_L4(                                                "reserved1");
        Skip_L4(                                                "reserved2");
        if (header_size<Element_Size)
            Skip_XX(Element_Size-header_size,                   "Unknown");

        //Filling
        FILLING_BEGIN();
            Accept("Speex");

            Stream_Prepare(Stream_Audio);
            Fill(Stream_Audio, 0, Audio_Format, "Speex");
            Fill(Stream_Audio, 0, Audio_Codec, "Speex");
            if (Speex_version_id==1)
            {
                if (!speex_version.empty())
                    Fill(Stream_Audio, 0, Audio_Encoded_Library, speex_version);
                Fill(Stream_Audio, 0, Audio_SamplingRate, rate);
                Fill(Stream_Audio, 0, Audio_Channel_s_, nb_channels);
                if (bitrate!=(int32u)-1)
                    Fill(Stream_Audio, 0, Audio_BitRate, bitrate);
                Fill(Stream_Audio, 0, Audio_BitRate_Mode, vbr?"VBR":"CBR");
            }
        FILLING_END();
    }

    //Filling
    Identification_Done=true;
}

//---------------------------------------------------------------------------
void File_Speex::Comment()
{
    Element_Name("Comment?");

    while (Element_Offset<Element_Size)
    {
        Ztring value;
        int32u size;
        Get_L4(size,                                            "size");
        if (size)
            Get_Local(size, value,                              "value");

        //Filling
        if (!value.empty())
            Fill(Stream_Audio, 0, "Comment", value);
    }

    Finish("Speex");
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_SPEEX_YES
<commit_msg>x Speex: provide information also if version_id is more than 1<commit_after>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Note : the buffer must be given in ONE call
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_SPEEX_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Speex.h"
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Speex::File_Speex()
:File__Analyze()
{
    //Internal
    Identification_Done=false;
}

//***************************************************************************
// Buffer - Per element
//***************************************************************************

//---------------------------------------------------------------------------
void File_Speex::Header_Parse()
{
    //Filling
    Header_Fill_Code(0, "Speex");
    Header_Fill_Size(Element_Size);
}

//---------------------------------------------------------------------------
void File_Speex::Data_Parse()
{
    //Parsing
    if (Identification_Done)
        Comment();
    else
        Identification();
}

//***************************************************************************
// Elements
//***************************************************************************

//---------------------------------------------------------------------------
void File_Speex::Identification()
{
    Element_Name("Identification");

    //Parsing
    Ztring speex_version;
    int32u Speex_version_id, header_size, rate, nb_channels, bitrate, vbr;
    Skip_Local(8,                                               "speex_string");
    Get_Local(20, speex_version,                                "speex_version");
    Get_L4 (Speex_version_id,                                   "Speex_version_id");
    if (Speex_version_id==1)
    {
        Get_L4 (header_size,                                    "header_size");
        Get_L4 (rate,                                           "rate");
        Skip_L4(                                                "mode");
        Skip_L4(                                                "mode_bitstream_version");
        Get_L4 (nb_channels,                                    "nb_channels");
        Get_L4 (bitrate,                                        "bitrate");
        Skip_L4(                                                "frame_size");
        Get_L4 (vbr,                                            "vbr");
        Skip_L4(                                                "frames_per_packet");
        Skip_L4(                                                "extra_headers");
        Skip_L4(                                                "reserved1");
        Skip_L4(                                                "reserved2");
        if (header_size<Element_Size)
            Skip_XX(Element_Size-header_size,                   "Unknown");
    }

    FILLING_BEGIN();
        Accept("Speex");

        Stream_Prepare(Stream_Audio);
        Fill(Stream_Audio, 0, Audio_Format, "Speex");
        Fill(Stream_Audio, 0, Audio_Codec, "Speex");
        if (Speex_version_id==1)
        {
            if (!speex_version.empty())
                Fill(Stream_Audio, 0, Audio_Encoded_Library, speex_version);
            Fill(Stream_Audio, 0, Audio_SamplingRate, rate);
            Fill(Stream_Audio, 0, Audio_Channel_s_, nb_channels);
            if (bitrate!=(int32u)-1)
                Fill(Stream_Audio, 0, Audio_BitRate, bitrate);
            Fill(Stream_Audio, 0, Audio_BitRate_Mode, vbr?"VBR":"CBR");
        }

        Identification_Done=true;
    FILLING_END();
}

//---------------------------------------------------------------------------
void File_Speex::Comment()
{
    Element_Name("Comment?");

    while (Element_Offset<Element_Size)
    {
        Ztring value;
        int32u size;
        Get_L4(size,                                            "size");
        if (size)
            Get_Local(size, value,                              "value");

        //Filling
        if (!value.empty())
            Fill(Stream_Audio, 0, "Comment", value);
    }

    Finish("Speex");
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_SPEEX_YES
<|endoftext|>


<commit_before>// Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "Token.h"
#include "Literals.h"

using namespace CPlusPlus;

static const char *token_names[] = {
    (""), ("<error>"),

    ("<C++ comment>"), ("<C++ doxy comment>"),
    ("<comment>"), ("<doxy comment>"),

    ("<identifier>"), ("<numeric literal>"), ("<char literal>"),
    ("<wide char literal>"), ("<string literal>"), ("<wide char literal>"),
    ("<@string literal>"), ("<angle string literal>"),

    ("&"), ("&&"), ("&="), ("->"), ("->*"), ("^"), ("^="), (":"), ("::"),
    (","), ("/"), ("/="), ("."), ("..."), (".*"), ("="), ("=="), ("!"),
    ("!="), (">"), (">="), (">>"), (">>="), ("{"), ("["), ("<"), ("<="),
    ("<<"), ("<<="), ("("), ("-"), ("-="), ("--"), ("%"), ("%="), ("|"),
    ("|="), ("||"), ("+"), ("+="), ("++"), ("#"), ("##"), ("?"), ("}"),
    ("]"), (")"), (";"), ("*"), ("*="), ("~"), ("~="),

    ("asm"), ("auto"), ("bool"), ("break"), ("case"), ("catch"), ("char"),
    ("class"), ("const"), ("const_cast"), ("continue"), ("default"),
    ("delete"), ("do"), ("double"), ("dynamic_cast"), ("else"), ("enum"),
    ("explicit"), ("export"), ("extern"), ("false"), ("float"), ("for"),
    ("friend"), ("goto"), ("if"), ("inline"), ("int"), ("long"),
    ("mutable"), ("namespace"), ("new"), ("operator"), ("private"),
    ("protected"), ("public"), ("register"), ("reinterpret_cast"),
    ("return"), ("short"), ("signed"), ("sizeof"), ("static"),
    ("static_cast"), ("struct"), ("switch"), ("template"), ("this"),
    ("throw"), ("true"), ("try"), ("typedef"), ("typeid"), ("typename"),
    ("union"), ("unsigned"), ("using"), ("virtual"), ("void"),
    ("volatile"), ("wchar_t"), ("while"),

    // gnu
    ("__attribute__"), ("__typeof__"),

    // objc @keywords
    ("@catch"), ("@class"), ("@compatibility_alias"), ("@defs"), ("@dynamic"),
    ("@encode"), ("@end"), ("@finally"), ("@implementation"), ("@interface"),
    ("@not_keyword"), ("@optional"), ("@package"), ("@private"), ("@property"),
    ("@protected"), ("@protocol"), ("@public"), ("@required"), ("@selector"),
    ("@synchronized"), ("@synthesize"), ("@throw"), ("@try"),

    // Qt keywords
    ("SIGNAL"), ("SLOT"), ("Q_SIGNAL"), ("Q_SLOT"), ("signals"), ("slots"),
    ("Q_FOREACH"), ("Q_D"), ("Q_Q"),
    ("Q_INVOKABLE"), ("Q_PROPERTY"), ("T_Q_PRIVATE_PROPERTY"),
    ("Q_INTERFACES"), ("Q_ENUMS"), ("Q_FLAGS"),
    ("Q_PRIVATE_SLOT"), ("Q_DECLARE_INTERFACE"), ("Q_OBJECT"), ("Q_GADGET"),

};

Token::Token() :
    flags(0), offset(0), ptr(0)
{
}

Token::~Token()
{
}

void Token::reset()
{
    flags = 0;
    offset = 0;
    ptr = 0;
}

const char *Token::name(int kind)
{ return token_names[kind]; }

const char *Token::spell() const
{
    switch (f.kind) {
    case T_IDENTIFIER:
        return identifier->chars();

    case T_NUMERIC_LITERAL:
    case T_CHAR_LITERAL:
    case T_STRING_LITERAL:
    case T_AT_STRING_LITERAL:
    case T_ANGLE_STRING_LITERAL:
    case T_WIDE_CHAR_LITERAL:
    case T_WIDE_STRING_LITERAL:
        return literal->chars();

    default:
        return token_names[f.kind];
    } // switch
}

<commit_msg>C++: Add names for tokens constexpr and nullptr<commit_after>// Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "Token.h"
#include "Literals.h"

using namespace CPlusPlus;

static const char *token_names[] = {
    (""), ("<error>"),

    ("<C++ comment>"), ("<C++ doxy comment>"),
    ("<comment>"), ("<doxy comment>"),

    ("<identifier>"), ("<numeric literal>"), ("<char literal>"),
    ("<wide char literal>"), ("<string literal>"), ("<wide char literal>"),
    ("<@string literal>"), ("<angle string literal>"),

    ("&"), ("&&"), ("&="), ("->"), ("->*"), ("^"), ("^="), (":"), ("::"),
    (","), ("/"), ("/="), ("."), ("..."), (".*"), ("="), ("=="), ("!"),
    ("!="), (">"), (">="), (">>"), (">>="), ("{"), ("["), ("<"), ("<="),
    ("<<"), ("<<="), ("("), ("-"), ("-="), ("--"), ("%"), ("%="), ("|"),
    ("|="), ("||"), ("+"), ("+="), ("++"), ("#"), ("##"), ("?"), ("}"),
    ("]"), (")"), (";"), ("*"), ("*="), ("~"), ("~="),

    ("asm"), ("auto"), ("bool"), ("break"), ("case"), ("catch"), ("char"),
    ("class"), ("const"), ("const_cast"), ("constexpr"), ("continue"), ("default"),
    ("delete"), ("do"), ("double"), ("dynamic_cast"), ("else"), ("enum"),
    ("explicit"), ("export"), ("extern"), ("false"), ("float"), ("for"),
    ("friend"), ("goto"), ("if"), ("inline"), ("int"), ("long"),
    ("mutable"), ("namespace"), ("new"), ("nullptr"), ("operator"), ("private"),
    ("protected"), ("public"), ("register"), ("reinterpret_cast"),
    ("return"), ("short"), ("signed"), ("sizeof"), ("static"),
    ("static_cast"), ("struct"), ("switch"), ("template"), ("this"),
    ("throw"), ("true"), ("try"), ("typedef"), ("typeid"), ("typename"),
    ("union"), ("unsigned"), ("using"), ("virtual"), ("void"),
    ("volatile"), ("wchar_t"), ("while"),

    // gnu
    ("__attribute__"), ("__typeof__"),

    // objc @keywords
    ("@catch"), ("@class"), ("@compatibility_alias"), ("@defs"), ("@dynamic"),
    ("@encode"), ("@end"), ("@finally"), ("@implementation"), ("@interface"),
    ("@not_keyword"), ("@optional"), ("@package"), ("@private"), ("@property"),
    ("@protected"), ("@protocol"), ("@public"), ("@required"), ("@selector"),
    ("@synchronized"), ("@synthesize"), ("@throw"), ("@try"),

    // Qt keywords
    ("SIGNAL"), ("SLOT"), ("Q_SIGNAL"), ("Q_SLOT"), ("signals"), ("slots"),
    ("Q_FOREACH"), ("Q_D"), ("Q_Q"),
    ("Q_INVOKABLE"), ("Q_PROPERTY"), ("T_Q_PRIVATE_PROPERTY"),
    ("Q_INTERFACES"), ("Q_ENUMS"), ("Q_FLAGS"),
    ("Q_PRIVATE_SLOT"), ("Q_DECLARE_INTERFACE"), ("Q_OBJECT"), ("Q_GADGET"),

};

Token::Token() :
    flags(0), offset(0), ptr(0)
{
}

Token::~Token()
{
}

void Token::reset()
{
    flags = 0;
    offset = 0;
    ptr = 0;
}

const char *Token::name(int kind)
{ return token_names[kind]; }

const char *Token::spell() const
{
    switch (f.kind) {
    case T_IDENTIFIER:
        return identifier->chars();

    case T_NUMERIC_LITERAL:
    case T_CHAR_LITERAL:
    case T_STRING_LITERAL:
    case T_AT_STRING_LITERAL:
    case T_ANGLE_STRING_LITERAL:
    case T_WIDE_CHAR_LITERAL:
    case T_WIDE_STRING_LITERAL:
        return literal->chars();

    default:
        return token_names[f.kind];
    } // switch
}

<|endoftext|>


<commit_before>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2004 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>

                                 // xxx
#include <lac/petsc_vector.h>
#include <lac/petsc_sparse_matrix.h>
#include <lac/petsc_solver.h>
#include <lac/petsc_precondition.h>

#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/grid_refinement.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/fe_values.h>
#include <fe/fe_system.h>
#include <fe/fe_q.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>
#include <dofs/dof_constraints.h>
#include <numerics/error_estimator.h>

                                 // xxx
#include <grid/grid_tools.h>

#include <fstream>
#include <iostream>

template <int dim>
class ElasticProblem
{
  public:
    ElasticProblem ();
    ~ElasticProblem ();
    void run ();

  private:
    void setup_system ();
    void assemble_system ();
    void solve ();
    void refine_grid ();
    void output_results (const unsigned int cycle) const;

    Triangulation<dim>   triangulation;
    DoFHandler<dim>      dof_handler;

    FESystem<dim>        fe;

    ConstraintMatrix     hanging_node_constraints;

                                     // xxx no sparsity
    PETScWrappers::SparseMatrix system_matrix;

    PETScWrappers::Vector       solution;
    PETScWrappers::Vector       system_rhs;

                                     // xxx
    const unsigned int n_partitions;
    const unsigned int this_partition;
};

template <int dim>
class RightHandSide :  public Function<dim>
{
  public:
    RightHandSide ();

    virtual void vector_value (const Point<dim> &p,
			       Vector<double>   &values) const;

    virtual void vector_value_list (const std::vector<Point<dim> > &points,
				    std::vector<Vector<double> >   &value_list) const;
};

template <int dim>
RightHandSide<dim>::RightHandSide () :
		Function<dim> (dim)
{}

template <int dim>
inline
void RightHandSide<dim>::vector_value (const Point<dim> &p,
				       Vector<double>   &values) const
{
  Assert (values.size() == dim,
	  ExcDimensionMismatch (values.size(), dim));
  Assert (dim >= 2, ExcInternalError());

  Point<dim> point_1, point_2;
  point_1(0) = 0.5;
  point_2(0) = -0.5;

  if (((p-point_1).square() < 0.2*0.2) ||
      ((p-point_2).square() < 0.2*0.2))
    values(0) = 1;
  else
    values(0) = 0;

  if (p.square() < 0.2*0.2)
    values(1) = 1;
  else
    values(1) = 0;
}

template <int dim>
void RightHandSide<dim>::vector_value_list (const std::vector<Point<dim> > &points,
					    std::vector<Vector<double> >   &value_list) const
{
  const unsigned int n_points = points.size();

  Assert (value_list.size() == n_points,
	  ExcDimensionMismatch (value_list.size(), n_points));

  for (unsigned int p=0; p<n_points; ++p)
    RightHandSide<dim>::vector_value (points[p],
				      value_list[p]);
}

template <int dim>
ElasticProblem<dim>::ElasticProblem ()
                :
		dof_handler (triangulation),
		fe (FE_Q<dim>(1), dim),
                                                 // xxx
                n_partitions (8),
                this_partition (0)
{}

template <int dim>
ElasticProblem<dim>::~ElasticProblem ()
{
  dof_handler.clear ();
}

template <int dim>
void ElasticProblem<dim>::setup_system ()
{
  dof_handler.distribute_dofs (fe);
  hanging_node_constraints.clear ();
  DoFTools::make_hanging_node_constraints (dof_handler,
					   hanging_node_constraints);
  hanging_node_constraints.close ();

                                   // no sparsity pattern
  system_matrix.reinit (dof_handler.n_dofs(),
                        dof_handler.n_dofs(),
                        dof_handler.max_couplings_between_dofs());

  solution.reinit (dof_handler.n_dofs());
  system_rhs.reinit (dof_handler.n_dofs());
}

template <int dim>
void ElasticProblem<dim>::assemble_system ()
{
                                   // move to front
  std::map<unsigned int,double> boundary_values;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(dim),
					    boundary_values);

  QGauss2<dim>  quadrature_formula;
  FEValues<dim> fe_values (fe, quadrature_formula,
			   UpdateFlags(update_values    |
				       update_gradients |
				       update_q_points  |
				       update_JxW_values));

  const unsigned int   dofs_per_cell = fe.dofs_per_cell;
  const unsigned int   n_q_points    = quadrature_formula.n_quadrature_points;

  FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);
  Vector<double>       cell_rhs (dofs_per_cell);

  std::vector<unsigned int> local_dof_indices (dofs_per_cell);

  std::vector<double>     lambda_values (n_q_points);
  std::vector<double>     mu_values (n_q_points);

  ConstantFunction<dim> lambda(1.), mu(1.);

  RightHandSide<dim>      right_hand_side;
  std::vector<Vector<double> > rhs_values (n_q_points,
					   Vector<double>(dim));

  typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),
						 endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      cell_matrix.clear ();
      cell_rhs.clear ();

      fe_values.reinit (cell);

      lambda.value_list (fe_values.get_quadrature_points(), lambda_values);
      mu.value_list     (fe_values.get_quadrature_points(), mu_values);

      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  const unsigned int
	    component_i = fe.system_to_component_index(i).first;

	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    {
	      const unsigned int
		component_j = fe.system_to_component_index(j).first;

	      for (unsigned int q_point=0; q_point<n_q_points;
		   ++q_point)
		{
		  cell_matrix(i,j)
		    +=
		    (
		      (fe_values.shape_grad(i,q_point)[component_i] *
		       fe_values.shape_grad(j,q_point)[component_j] *
		       lambda_values[q_point])
		      +
		      (fe_values.shape_grad(i,q_point)[component_j] *
		       fe_values.shape_grad(j,q_point)[component_i] *
		       mu_values[q_point])
		      +
		      ((component_i == component_j) ?
		       (fe_values.shape_grad(i,q_point) *
			fe_values.shape_grad(j,q_point) *
			mu_values[q_point])  :
		       0)
		    )
		    *
		    fe_values.JxW(q_point);
		};
	    };
	};

      right_hand_side.vector_value_list (fe_values.get_quadrature_points(),
					 rhs_values);
      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  const unsigned int
	    component_i = fe.system_to_component_index(i).first;

	  for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
	    cell_rhs(i) += fe_values.shape_value(i,q_point) *
			   rhs_values[q_point](component_i) *
			   fe_values.JxW(q_point);
	};

      cell->get_dof_indices (local_dof_indices);

                                       //xxx
      MatrixTools::local_apply_boundary_values (boundary_values,
                                                local_dof_indices,
                                                cell_matrix,
                                                cell_rhs,
                                                false);

                                       // xxx
      hanging_node_constraints
        .distribute_local_to_global (cell_matrix,
                                     local_dof_indices,
                                     system_matrix);

      hanging_node_constraints
        .distribute_local_to_global (cell_rhs,
                                     local_dof_indices,
                                     system_rhs);
    }

                                   //xxx no condense necessary, no apply_b_v
                                   //either

                                   // xxx
  system_matrix.compress ();
  system_rhs.compress ();
}

template <int dim>
void ElasticProblem<dim>::solve ()
{
                                   // xxx
  SolverControl           solver_control (1000, 1e-10);
  PETScWrappers::SolverCG cg (solver_control);

  PETScWrappers::PreconditionSSOR preconditioner(system_matrix, 1.2);

  cg.solve (system_matrix, solution, system_rhs,
	    preconditioner);

  hanging_node_constraints.distribute (solution);
}

template <int dim>
void ElasticProblem<dim>::refine_grid ()
{
  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());

  typename FunctionMap<dim>::type neumann_boundary;
  KellyErrorEstimator<dim>::estimate (dof_handler,
				      QGauss2<dim-1>(),
				      neumann_boundary,
				      solution,
				      estimated_error_per_cell);

  GridRefinement::refine_and_coarsen_fixed_number (triangulation,
						   estimated_error_per_cell,
						   0.3, 0.03);

  triangulation.execute_coarsening_and_refinement ();

                                   // xxx
  GridTools::partition_triangulation (n_partitions, triangulation);
}

template <int dim>
void ElasticProblem<dim>::output_results (const unsigned int cycle) const
{
  std::string filename = "solution-";
  filename += ('0' + cycle);
  Assert (cycle < 10, ExcInternalError());

  filename += ".gmv";
  std::ofstream output (filename.c_str());

  DataOut<dim> data_out;
  data_out.attach_dof_handler (dof_handler);

  std::vector<std::string> solution_names;
  switch (dim)
    {
      case 1:
	    solution_names.push_back ("displacement");
	    break;
      case 2:
	    solution_names.push_back ("x_displacement");
	    solution_names.push_back ("y_displacement");
	    break;
      case 3:
	    solution_names.push_back ("x_displacement");
	    solution_names.push_back ("y_displacement");
	    solution_names.push_back ("z_displacement");
	    break;
      default:
	    Assert (false, ExcInternalError());
    };

  data_out.add_data_vector (solution, solution_names);
  data_out.build_patches ();
  data_out.write_gmv (output);
}

template <int dim>
void ElasticProblem<dim>::run ()
{
  for (unsigned int cycle=0; cycle<12; ++cycle)
    {
      std::cout << "Cycle " << cycle << ':' << std::endl;

      if (cycle == 0)
	{
	  GridGenerator::hyper_cube (triangulation, -1, 1);
	  triangulation.refine_global (2);

                                           // xxx
          GridTools::partition_triangulation (n_partitions, triangulation);
	}
      else
	refine_grid ();

      std::cout << "   Number of active cells:       "
		<< triangulation.n_active_cells()
		<< std::endl;

      setup_system ();

      std::cout << "   Number of degrees of freedom: "
		<< dof_handler.n_dofs()
		<< std::endl;

      assemble_system ();
      solve ();
      output_results (cycle);
    };
}

int main (int argc, char **argv)
{
  try
    {
                                       // xxx
      PetscInitialize(&argc,&argv,0,0);
      deallog.depth_console (0);

                                       // xxx localize scope
      {
        ElasticProblem<2> elastic_problem_2d;
        elastic_problem_2d.run ();
      }

                                       // xxx
      PetscFinalize();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    };

  return 0;
}
<commit_msg>Inch forward.<commit_after>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2004 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>

                                 // xxx
#include <lac/petsc_vector.h>
#include <lac/petsc_parallel_vector.h>
#include <lac/petsc_parallel_sparse_matrix.h>
#include <lac/petsc_solver.h>
#include <lac/petsc_precondition.h>

#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/grid_refinement.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>

                                 // xxx
#include <dofs/dof_renumbering.h>

#include <fe/fe_values.h>
#include <fe/fe_system.h>
#include <fe/fe_q.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>
#include <dofs/dof_constraints.h>
#include <numerics/error_estimator.h>

                                 // xxx
#include <grid/grid_tools.h>

#include <fstream>
#include <iostream>

template <int dim>
class ElasticProblem
{
  public:
    ElasticProblem ();
    ~ElasticProblem ();
    void run ();

  private:
    void setup_system ();
    void assemble_system ();
    void solve ();
    void refine_grid ();
    void output_results (const unsigned int cycle) const;

    Triangulation<dim>   triangulation;
    DoFHandler<dim>      dof_handler;

    FESystem<dim>        fe;

    ConstraintMatrix     hanging_node_constraints;

                                     // xxx no sparsity
    PETScWrappers::MPI::SparseMatrix system_matrix;

    PETScWrappers::MPI::Vector       solution;
    PETScWrappers::MPI::Vector       system_rhs;

    MPI_Comm mpi_communicator;

                                     // xxx
    const unsigned int n_partitions;
    const unsigned int this_partition;

    unsigned int local_dofs;

    static unsigned int get_n_partitions (const MPI_Comm &mpi_communicator);
    static unsigned int get_this_partition (const MPI_Comm &mpi_communicator);
};

template <int dim>
class RightHandSide :  public Function<dim>
{
  public:
    RightHandSide ();

    virtual void vector_value (const Point<dim> &p,
			       Vector<double>   &values) const;

    virtual void vector_value_list (const std::vector<Point<dim> > &points,
				    std::vector<Vector<double> >   &value_list) const;
};

template <int dim>
RightHandSide<dim>::RightHandSide () :
		Function<dim> (dim)
{}

template <int dim>
inline
void RightHandSide<dim>::vector_value (const Point<dim> &p,
				       Vector<double>   &values) const
{
  Assert (values.size() == dim,
	  ExcDimensionMismatch (values.size(), dim));
  Assert (dim >= 2, ExcInternalError());

  Point<dim> point_1, point_2;
  point_1(0) = 0.5;
  point_2(0) = -0.5;

  if (((p-point_1).square() < 0.2*0.2) ||
      ((p-point_2).square() < 0.2*0.2))
    values(0) = 1;
  else
    values(0) = 0;

  if (p.square() < 0.2*0.2)
    values(1) = 1;
  else
    values(1) = 0;
}

template <int dim>
void RightHandSide<dim>::vector_value_list (const std::vector<Point<dim> > &points,
					    std::vector<Vector<double> >   &value_list) const
{
  const unsigned int n_points = points.size();

  Assert (value_list.size() == n_points,
	  ExcDimensionMismatch (value_list.size(), n_points));

  for (unsigned int p=0; p<n_points; ++p)
    RightHandSide<dim>::vector_value (points[p],
				      value_list[p]);
}

                                 // xxx
template <int dim>
unsigned int
ElasticProblem<dim>::get_n_partitions (const MPI_Comm &mpi_communicator)
{
                                   // xxx int vs uint
  int n_jobs;
  MPI_Comm_size (mpi_communicator, &n_jobs);

  return n_jobs;
}

template <int dim>
unsigned int
ElasticProblem<dim>::get_this_partition (const MPI_Comm &mpi_communicator)
{
  int rank;
  MPI_Comm_rank (mpi_communicator, &rank);

  return rank;
}

template <int dim>
ElasticProblem<dim>::ElasticProblem ()
                :
		dof_handler (triangulation),
		fe (FE_Q<dim>(1), dim),
                                                 // xxx
                mpi_communicator (MPI_COMM_WORLD),
                n_partitions (get_n_partitions(mpi_communicator)),
                this_partition (get_this_partition(mpi_communicator))
{}

template <int dim>
ElasticProblem<dim>::~ElasticProblem ()
{
  dof_handler.clear ();
}

template <int dim>
void ElasticProblem<dim>::setup_system ()
{
                                   // xxx
  dof_handler.distribute_dofs (fe);
  DoFRenumbering::subdomain_wise (dof_handler);

  local_dofs
    = DoFTools::count_dofs_with_subdomain_association (dof_handler,
                                                       this_partition);

  hanging_node_constraints.clear ();
  DoFTools::make_hanging_node_constraints (dof_handler,
					   hanging_node_constraints);
  hanging_node_constraints.close ();

                                   // no sparsity pattern
  system_matrix.reinit (mpi_communicator,
                        dof_handler.n_dofs(),
                        dof_handler.n_dofs(),
                        local_dofs,
                        dof_handler.max_couplings_between_dofs());

  solution.reinit (dof_handler.n_dofs(), local_dofs, mpi_communicator);
  system_rhs.reinit (dof_handler.n_dofs(), local_dofs, mpi_communicator);
}

template <int dim>
void ElasticProblem<dim>::assemble_system ()
{
                                   // move to front
  std::map<unsigned int,double> boundary_values;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(dim),
					    boundary_values);

  QGauss2<dim>  quadrature_formula;
  FEValues<dim> fe_values (fe, quadrature_formula,
			   UpdateFlags(update_values    |
				       update_gradients |
				       update_q_points  |
				       update_JxW_values));

  const unsigned int   dofs_per_cell = fe.dofs_per_cell;
  const unsigned int   n_q_points    = quadrature_formula.n_quadrature_points;

  FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);
  Vector<double>       cell_rhs (dofs_per_cell);

  std::vector<unsigned int> local_dof_indices (dofs_per_cell);

  std::vector<double>     lambda_values (n_q_points);
  std::vector<double>     mu_values (n_q_points);

  ConstantFunction<dim> lambda(1.), mu(1.);

  RightHandSide<dim>      right_hand_side;
  std::vector<Vector<double> > rhs_values (n_q_points,
					   Vector<double>(dim));

  typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),
						 endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      cell_matrix.clear ();
      cell_rhs.clear ();

      fe_values.reinit (cell);

      lambda.value_list (fe_values.get_quadrature_points(), lambda_values);
      mu.value_list     (fe_values.get_quadrature_points(), mu_values);

      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  const unsigned int
	    component_i = fe.system_to_component_index(i).first;

	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    {
	      const unsigned int
		component_j = fe.system_to_component_index(j).first;

	      for (unsigned int q_point=0; q_point<n_q_points;
		   ++q_point)
		{
		  cell_matrix(i,j)
		    +=
		    (
		      (fe_values.shape_grad(i,q_point)[component_i] *
		       fe_values.shape_grad(j,q_point)[component_j] *
		       lambda_values[q_point])
		      +
		      (fe_values.shape_grad(i,q_point)[component_j] *
		       fe_values.shape_grad(j,q_point)[component_i] *
		       mu_values[q_point])
		      +
		      ((component_i == component_j) ?
		       (fe_values.shape_grad(i,q_point) *
			fe_values.shape_grad(j,q_point) *
			mu_values[q_point])  :
		       0)
		    )
		    *
		    fe_values.JxW(q_point);
		};
	    };
	};

      right_hand_side.vector_value_list (fe_values.get_quadrature_points(),
					 rhs_values);
      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  const unsigned int
	    component_i = fe.system_to_component_index(i).first;

	  for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
	    cell_rhs(i) += fe_values.shape_value(i,q_point) *
			   rhs_values[q_point](component_i) *
			   fe_values.JxW(q_point);
	};

      cell->get_dof_indices (local_dof_indices);

                                       //xxx
      MatrixTools::local_apply_boundary_values (boundary_values,
                                                local_dof_indices,
                                                cell_matrix,
                                                cell_rhs,
                                                false);

                                       // xxx
      hanging_node_constraints
        .distribute_local_to_global (cell_matrix,
                                     local_dof_indices,
                                     system_matrix);

      hanging_node_constraints
        .distribute_local_to_global (cell_rhs,
                                     local_dof_indices,
                                     system_rhs);
    }

                                   //xxx no condense necessary, no apply_b_v
                                   //either

                                   // xxx
  system_matrix.compress ();
  system_rhs.compress ();
}

template <int dim>
void ElasticProblem<dim>::solve ()
{
                                   // xxx
  SolverControl           solver_control (1000, 1e-10);
  PETScWrappers::SolverCG cg (solver_control);

  PETScWrappers::PreconditionSSOR preconditioner(system_matrix, 1.2);

  cg.solve (system_matrix, solution, system_rhs,
	    preconditioner);

  hanging_node_constraints.distribute (solution);
}

template <int dim>
void ElasticProblem<dim>::refine_grid ()
{
  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());

                                   // XXX
  typename FunctionMap<dim>::type neumann_boundary;
  Assert (false, ExcNotImplemented());
//   KellyErrorEstimator<dim>::estimate (dof_handler,
// 				      QGauss2<dim-1>(),
// 				      neumann_boundary,
// 				      solution,
// 				      estimated_error_per_cell);

  GridRefinement::refine_and_coarsen_fixed_number (triangulation,
						   estimated_error_per_cell,
						   0.3, 0.03);

  triangulation.execute_coarsening_and_refinement ();

                                   // xxx
  GridTools::partition_triangulation (n_partitions, triangulation);
}

template <int dim>
void ElasticProblem<dim>::output_results (const unsigned int cycle) const
{
                                   // xxx
  PETScWrappers::Vector global_solution;
  global_solution = solution;

  if (this_partition == 0)
    {
      std::string filename = "solution-";
      filename += ('0' + cycle);
      Assert (cycle < 10, ExcInternalError());

      filename += ".gmv";
      std::ofstream output (filename.c_str());

      DataOut<dim> data_out;
      data_out.attach_dof_handler (dof_handler);

      std::vector<std::string> solution_names;
      switch (dim)
        {
          case 1:
                solution_names.push_back ("displacement");
                break;
          case 2:
                solution_names.push_back ("x_displacement");
                solution_names.push_back ("y_displacement");
                break;
          case 3:
                solution_names.push_back ("x_displacement");
                solution_names.push_back ("y_displacement");
                solution_names.push_back ("z_displacement");
                break;
          default:
                Assert (false, ExcInternalError());
        };

      data_out.add_data_vector (global_solution, solution_names);
      data_out.build_patches ();
      data_out.write_gmv (output);
    }
}

template <int dim>
void ElasticProblem<dim>::run ()
{
  for (unsigned int cycle=0; cycle<12; ++cycle)
    {
                                       // xxx
      if (this_partition == 0)
        std::cout << "Cycle " << cycle << ':' << std::endl;

      if (cycle == 0)
	{
	  GridGenerator::hyper_cube (triangulation, -1, 1);
	  triangulation.refine_global (2);

                                           // xxx
          GridTools::partition_triangulation (n_partitions, triangulation);
	}
      else
	refine_grid ();

                                       // xxx
      if (this_partition == 0)
        std::cout << "   Number of active cells:       "
                  << triangulation.n_active_cells()
                  << std::endl;

      setup_system ();

                                       // xxx
      if (this_partition == 0)
        std::cout << "   Number of degrees of freedom: "
                  << dof_handler.n_dofs()
                  << std::endl;

      assemble_system ();
      solve ();
      output_results (cycle);
    };
}

int main (int argc, char **argv)
{
  try
    {
                                       // xxx
      PetscInitialize(&argc,&argv,0,0);
      deallog.depth_console (0);

                                       // xxx localize scope
      {
        ElasticProblem<2> elastic_problem_2d;
        elastic_problem_2d.run ();
      }

                                       // xxx
      PetscFinalize();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    };

  return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/predictor/predictor_manager.h"

#include <list>
#include <memory>
#include <unordered_map>

#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_thread_pool.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/predictor/extrapolation/extrapolation_predictor.h"
#include "modules/prediction/predictor/free_move/free_move_predictor.h"
#include "modules/prediction/predictor/interaction/interaction_predictor.h"
#include "modules/prediction/predictor/junction/junction_predictor.h"
#include "modules/prediction/predictor/lane_sequence/lane_sequence_predictor.h"
#include "modules/prediction/predictor/move_sequence/move_sequence_predictor.h"
#include "modules/prediction/predictor/regional/regional_predictor.h"
#include "modules/prediction/predictor/single_lane/single_lane_predictor.h"

namespace apollo {
namespace prediction {

using apollo::common::adapter::AdapterConfig;
using apollo::perception::PerceptionObstacle;
using IdObstacleListMap = std::unordered_map<int, std::list<Obstacle*>>;
using IdPredictionObstacleMap =
    std::unordered_map<int, std::shared_ptr<PredictionObstacle>>;

namespace {

void GroupObstaclesByObstacleId(const int obstacle_id,
                                ObstaclesContainer* const obstacles_container,
                                IdObstacleListMap* const id_obstacle_map) {
  Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id);
  if (obstacle_ptr == nullptr) {
    AERROR << "Null obstacle [" << obstacle_id << "] found";
    return;
  }
  int id_mod = obstacle_id % FLAGS_max_thread_num;
  (*id_obstacle_map)[id_mod].push_back(obstacle_ptr);
}

}  // namespace

PredictorManager::PredictorManager() { RegisterPredictors(); }

void PredictorManager::RegisterPredictors() {
  RegisterPredictor(ObstacleConf::LANE_SEQUENCE_PREDICTOR);
  RegisterPredictor(ObstacleConf::MOVE_SEQUENCE_PREDICTOR);
  RegisterPredictor(ObstacleConf::SINGLE_LANE_PREDICTOR);
  RegisterPredictor(ObstacleConf::FREE_MOVE_PREDICTOR);
  RegisterPredictor(ObstacleConf::REGIONAL_PREDICTOR);
  RegisterPredictor(ObstacleConf::EMPTY_PREDICTOR);
  RegisterPredictor(ObstacleConf::JUNCTION_PREDICTOR);
  RegisterPredictor(ObstacleConf::EXTRAPOLATION_PREDICTOR);
  RegisterPredictor(ObstacleConf::INTERACTION_PREDICTOR);
}

void PredictorManager::Init(const PredictionConf& config) {
  for (const auto& obstacle_conf : config.obstacle_conf()) {
    if (!obstacle_conf.has_obstacle_type()) {
      AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
             << "] has not defined obstacle type.";
      continue;
    }

    if (!obstacle_conf.has_predictor_type()) {
      AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
             << "] has not defined predictor type.";
      continue;
    }

    switch (obstacle_conf.obstacle_type()) {
      case PerceptionObstacle::VEHICLE: {
        if (obstacle_conf.has_obstacle_status()) {
          if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
            vehicle_on_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::OFF_LANE) {
            vehicle_off_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::IN_JUNCTION) {
            vehicle_in_junction_predictor_ = obstacle_conf.predictor_type();
          }
        }
        break;
      }
      case PerceptionObstacle::BICYCLE: {
        if (obstacle_conf.has_obstacle_status()) {
          if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
            cyclist_on_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::OFF_LANE) {
            cyclist_off_lane_predictor_ = obstacle_conf.predictor_type();
          }
        }
        break;
      }
      case PerceptionObstacle::PEDESTRIAN: {
        pedestrian_predictor_ = obstacle_conf.predictor_type();
        break;
      }
      case PerceptionObstacle::UNKNOWN: {
        if (obstacle_conf.has_obstacle_status()) {
          if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
            default_on_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::OFF_LANE) {
            default_off_lane_predictor_ = obstacle_conf.predictor_type();
          }
        }
        break;
      }
      default: {
        break;
      }
    }
  }

  AINFO << "Defined vehicle on lane obstacle predictor ["
        << vehicle_on_lane_predictor_ << "].";
  AINFO << "Defined vehicle off lane obstacle predictor ["
        << vehicle_off_lane_predictor_ << "].";
  AINFO << "Defined bicycle on lane obstacle predictor ["
        << cyclist_on_lane_predictor_ << "].";
  AINFO << "Defined bicycle off lane obstacle predictor ["
        << cyclist_off_lane_predictor_ << "].";
  AINFO << "Defined pedestrian obstacle predictor [" << pedestrian_predictor_
        << "].";
  AINFO << "Defined default on lane obstacle predictor ["
        << default_on_lane_predictor_ << "].";
  AINFO << "Defined default off lane obstacle predictor ["
        << default_off_lane_predictor_ << "].";
}

Predictor* PredictorManager::GetPredictor(
    const ObstacleConf::PredictorType& type) {
  auto it = predictors_.find(type);
  return it != predictors_.end() ? it->second.get() : nullptr;
}

void PredictorManager::Run() {
  prediction_obstacles_.Clear();
  auto obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);

  auto adc_trajectory_container =
      ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
          AdapterConfig::PLANNING_TRAJECTORY);

  CHECK_NOTNULL(obstacles_container);

  if (FLAGS_enable_multi_thread) {
    PredictObstaclesInParallel(obstacles_container, adc_trajectory_container);
  } else {
    PredictObstacles(obstacles_container, adc_trajectory_container);
  }
}

void PredictorManager::PredictObstacles(
    ObstaclesContainer* obstacles_container,
    ADCTrajectoryContainer* adc_trajectory_container) {
  for (const int id : obstacles_container->curr_frame_obstacle_ids()) {
    if (id < 0) {
      ADEBUG << "The obstacle has invalid id [" << id << "].";
      continue;
    }

    PredictionObstacle prediction_obstacle;
    Obstacle* obstacle = obstacles_container->GetObstacle(id);

    PerceptionObstacle perception_obstacle =
        obstacles_container->GetPerceptionObstacle(id);
    // if obstacle == nullptr, that means obstacle is unmovable
    // Checkout the logic of unmovable in obstacle.cc
    if (obstacle != nullptr) {
      PredictObstacle(obstacle, &prediction_obstacle, adc_trajectory_container);
    } else {  // obstacle == nullptr
      prediction_obstacle.set_timestamp(perception_obstacle.timestamp());
      prediction_obstacle.set_is_static(true);
    }

    prediction_obstacle.set_predicted_period(
        FLAGS_prediction_trajectory_time_length);
    prediction_obstacle.mutable_perception_obstacle()->CopyFrom(
        perception_obstacle);

    prediction_obstacles_.add_prediction_obstacle()->CopyFrom(
        prediction_obstacle);
  }
}

void PredictorManager::PredictObstaclesInParallel(
    ObstaclesContainer* obstacles_container,
    ADCTrajectoryContainer* adc_trajectory_container) {
  IdPredictionObstacleMap id_prediction_obstacle_map;
  for (int id : obstacles_container->curr_frame_obstacle_ids()) {
    id_prediction_obstacle_map[id] = std::make_shared<PredictionObstacle>();
  }
  IdObstacleListMap id_obstacle_map;
  for (int id : obstacles_container->curr_frame_obstacle_ids()) {
    Obstacle* obstacle = obstacles_container->GetObstacle(id);
    const PerceptionObstacle& perception_obstacle =
        obstacles_container->GetPerceptionObstacle(id);
    if (obstacle == nullptr) {
      std::shared_ptr<PredictionObstacle> prediction_obstacle_ptr =
          id_prediction_obstacle_map[id];
      prediction_obstacle_ptr->set_is_static(true);
      prediction_obstacle_ptr->set_timestamp(perception_obstacle.timestamp());
    } else {
      GroupObstaclesByObstacleId(id, obstacles_container, &id_obstacle_map);
    }
  }
  PredictionThreadPool::ForEach(
      id_obstacle_map.begin(), id_obstacle_map.end(),
      [&](IdObstacleListMap::iterator::value_type& obstacles_iter) {
        for (auto obstacle_ptr : obstacles_iter.second) {
          int id = obstacle_ptr->id();
          PredictObstacle(obstacle_ptr, id_prediction_obstacle_map[id].get(),
                          adc_trajectory_container);
        }
      });
  for (auto& item : id_prediction_obstacle_map) {
    int id = item.first;
    auto prediction_obstacle_ptr = item.second;
    const PerceptionObstacle& perception_obstacle =
        obstacles_container->GetPerceptionObstacle(id);
    prediction_obstacle_ptr->set_predicted_period(
        FLAGS_prediction_trajectory_time_length);
    prediction_obstacle_ptr->mutable_perception_obstacle()->CopyFrom(
        perception_obstacle);
    prediction_obstacles_.add_prediction_obstacle()->CopyFrom(
        *prediction_obstacle_ptr);
  }
}

void PredictorManager::PredictObstacle(
    Obstacle* obstacle, PredictionObstacle* const prediction_obstacle,
    ADCTrajectoryContainer* adc_trajectory_container) {
  CHECK_NOTNULL(obstacle);
  Predictor* predictor = nullptr;
  prediction_obstacle->set_timestamp(obstacle->timestamp());
  if (obstacle->ToIgnore()) {
    ADEBUG << "Ignore obstacle [" << obstacle->id() << "]";
    predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
    prediction_obstacle->mutable_priority()->set_priority(
        ObstaclePriority::IGNORE);
  } else if (obstacle->IsStill()) {
    ADEBUG << "Still obstacle [" << obstacle->id() << "]";
    predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
  } else {
    switch (obstacle->type()) {
      case PerceptionObstacle::VEHICLE: {
        if (obstacle->HasJunctionFeatureWithExits() &&
            !obstacle->IsCloseToJunctionExit()) {
          predictor = GetPredictor(vehicle_in_junction_predictor_);
          CHECK_NOTNULL(predictor);
        } else if (obstacle->IsOnLane()) {
          predictor = GetPredictor(vehicle_on_lane_predictor_);
          CHECK_NOTNULL(predictor);
        } else {
          predictor = GetPredictor(vehicle_off_lane_predictor_);
          CHECK_NOTNULL(predictor);
        }
        break;
      }
      case PerceptionObstacle::PEDESTRIAN: {
        predictor = GetPredictor(pedestrian_predictor_);
        break;
      }
      case PerceptionObstacle::BICYCLE: {
        if (obstacle->IsOnLane()) {
          predictor = GetPredictor(cyclist_on_lane_predictor_);
          // TODO(kechxu) add a specific predictor in junction
        } else {
          predictor = GetPredictor(cyclist_off_lane_predictor_);
        }
        break;
      }
      default: {
        if (obstacle->IsOnLane()) {
          predictor = GetPredictor(default_on_lane_predictor_);
        } else {
          predictor = GetPredictor(default_off_lane_predictor_);
        }
        break;
      }
    }
  }

  if (predictor != nullptr) {
    predictor->Predict(obstacle);
    if (FLAGS_enable_trim_prediction_trajectory &&
        obstacle->type() == PerceptionObstacle::VEHICLE) {
      CHECK_NOTNULL(adc_trajectory_container);
      predictor->TrimTrajectories(*adc_trajectory_container, obstacle);
    }
    for (const auto& trajectory :
         obstacle->latest_feature().predicted_trajectory()) {
      prediction_obstacle->add_trajectory()->CopyFrom(trajectory);
    }
  }
  prediction_obstacle->set_timestamp(obstacle->timestamp());
  prediction_obstacle->mutable_priority()->CopyFrom(
      obstacle->latest_feature().priority());
  prediction_obstacle->set_is_static(obstacle->IsStill());
  if (FLAGS_prediction_offline_mode == 3) {
    FeatureOutput::InsertPredictionResult(obstacle->id(), *prediction_obstacle);
  }
}

std::unique_ptr<Predictor> PredictorManager::CreatePredictor(
    const ObstacleConf::PredictorType& type) {
  std::unique_ptr<Predictor> predictor_ptr(nullptr);
  switch (type) {
    case ObstacleConf::LANE_SEQUENCE_PREDICTOR: {
      predictor_ptr.reset(new LaneSequencePredictor());
      break;
    }
    case ObstacleConf::MOVE_SEQUENCE_PREDICTOR: {
      predictor_ptr.reset(new MoveSequencePredictor());
      break;
    }
    case ObstacleConf::SINGLE_LANE_PREDICTOR: {
      predictor_ptr.reset(new SingleLanePredictor());
      break;
    }
    case ObstacleConf::FREE_MOVE_PREDICTOR: {
      predictor_ptr.reset(new FreeMovePredictor());
      break;
    }
    case ObstacleConf::REGIONAL_PREDICTOR: {
      predictor_ptr.reset(new RegionalPredictor());
      break;
    }
    case ObstacleConf::JUNCTION_PREDICTOR: {
      predictor_ptr.reset(new JunctionPredictor());
      break;
    }
    case ObstacleConf::EXTRAPOLATION_PREDICTOR: {
      predictor_ptr.reset(new ExtrapolationPredictor());
      break;
    }
    case ObstacleConf::INTERACTION_PREDICTOR: {
      predictor_ptr.reset(new InteractionPredictor());
      break;
    }
    default: {
      break;
    }
  }
  return predictor_ptr;
}

void PredictorManager::RegisterPredictor(
    const ObstacleConf::PredictorType& type) {
  predictors_[type] = CreatePredictor(type);
  AINFO << "Predictor [" << type << "] is registered.";
}

const PredictionObstacles& PredictorManager::prediction_obstacles() {
  return prediction_obstacles_;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>Prediction: refactor predictor manager, move copy trajectory from feature to prediction obstacle outside<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/predictor/predictor_manager.h"

#include <list>
#include <memory>
#include <unordered_map>

#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_thread_pool.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/predictor/extrapolation/extrapolation_predictor.h"
#include "modules/prediction/predictor/free_move/free_move_predictor.h"
#include "modules/prediction/predictor/interaction/interaction_predictor.h"
#include "modules/prediction/predictor/junction/junction_predictor.h"
#include "modules/prediction/predictor/lane_sequence/lane_sequence_predictor.h"
#include "modules/prediction/predictor/move_sequence/move_sequence_predictor.h"
#include "modules/prediction/predictor/regional/regional_predictor.h"
#include "modules/prediction/predictor/single_lane/single_lane_predictor.h"

namespace apollo {
namespace prediction {

using apollo::common::adapter::AdapterConfig;
using apollo::perception::PerceptionObstacle;
using IdObstacleListMap = std::unordered_map<int, std::list<Obstacle*>>;
using IdPredictionObstacleMap =
    std::unordered_map<int, std::shared_ptr<PredictionObstacle>>;

namespace {

void GroupObstaclesByObstacleId(const int obstacle_id,
                                ObstaclesContainer* const obstacles_container,
                                IdObstacleListMap* const id_obstacle_map) {
  Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id);
  if (obstacle_ptr == nullptr) {
    AERROR << "Null obstacle [" << obstacle_id << "] found";
    return;
  }
  int id_mod = obstacle_id % FLAGS_max_thread_num;
  (*id_obstacle_map)[id_mod].push_back(obstacle_ptr);
}

}  // namespace

PredictorManager::PredictorManager() { RegisterPredictors(); }

void PredictorManager::RegisterPredictors() {
  RegisterPredictor(ObstacleConf::LANE_SEQUENCE_PREDICTOR);
  RegisterPredictor(ObstacleConf::MOVE_SEQUENCE_PREDICTOR);
  RegisterPredictor(ObstacleConf::SINGLE_LANE_PREDICTOR);
  RegisterPredictor(ObstacleConf::FREE_MOVE_PREDICTOR);
  RegisterPredictor(ObstacleConf::REGIONAL_PREDICTOR);
  RegisterPredictor(ObstacleConf::EMPTY_PREDICTOR);
  RegisterPredictor(ObstacleConf::JUNCTION_PREDICTOR);
  RegisterPredictor(ObstacleConf::EXTRAPOLATION_PREDICTOR);
  RegisterPredictor(ObstacleConf::INTERACTION_PREDICTOR);
}

void PredictorManager::Init(const PredictionConf& config) {
  for (const auto& obstacle_conf : config.obstacle_conf()) {
    if (!obstacle_conf.has_obstacle_type()) {
      AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
             << "] has not defined obstacle type.";
      continue;
    }

    if (!obstacle_conf.has_predictor_type()) {
      AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
             << "] has not defined predictor type.";
      continue;
    }

    switch (obstacle_conf.obstacle_type()) {
      case PerceptionObstacle::VEHICLE: {
        if (obstacle_conf.has_obstacle_status()) {
          if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
            vehicle_on_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::OFF_LANE) {
            vehicle_off_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::IN_JUNCTION) {
            vehicle_in_junction_predictor_ = obstacle_conf.predictor_type();
          }
        }
        break;
      }
      case PerceptionObstacle::BICYCLE: {
        if (obstacle_conf.has_obstacle_status()) {
          if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
            cyclist_on_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::OFF_LANE) {
            cyclist_off_lane_predictor_ = obstacle_conf.predictor_type();
          }
        }
        break;
      }
      case PerceptionObstacle::PEDESTRIAN: {
        pedestrian_predictor_ = obstacle_conf.predictor_type();
        break;
      }
      case PerceptionObstacle::UNKNOWN: {
        if (obstacle_conf.has_obstacle_status()) {
          if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
            default_on_lane_predictor_ = obstacle_conf.predictor_type();
          } else if (obstacle_conf.obstacle_status() ==
                     ObstacleConf::OFF_LANE) {
            default_off_lane_predictor_ = obstacle_conf.predictor_type();
          }
        }
        break;
      }
      default: {
        break;
      }
    }
  }

  AINFO << "Defined vehicle on lane obstacle predictor ["
        << vehicle_on_lane_predictor_ << "].";
  AINFO << "Defined vehicle off lane obstacle predictor ["
        << vehicle_off_lane_predictor_ << "].";
  AINFO << "Defined bicycle on lane obstacle predictor ["
        << cyclist_on_lane_predictor_ << "].";
  AINFO << "Defined bicycle off lane obstacle predictor ["
        << cyclist_off_lane_predictor_ << "].";
  AINFO << "Defined pedestrian obstacle predictor [" << pedestrian_predictor_
        << "].";
  AINFO << "Defined default on lane obstacle predictor ["
        << default_on_lane_predictor_ << "].";
  AINFO << "Defined default off lane obstacle predictor ["
        << default_off_lane_predictor_ << "].";
}

Predictor* PredictorManager::GetPredictor(
    const ObstacleConf::PredictorType& type) {
  auto it = predictors_.find(type);
  return it != predictors_.end() ? it->second.get() : nullptr;
}

void PredictorManager::Run() {
  prediction_obstacles_.Clear();
  auto obstacles_container =
      ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
          AdapterConfig::PERCEPTION_OBSTACLES);

  auto adc_trajectory_container =
      ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
          AdapterConfig::PLANNING_TRAJECTORY);

  CHECK_NOTNULL(obstacles_container);

  if (FLAGS_enable_multi_thread) {
    PredictObstaclesInParallel(obstacles_container, adc_trajectory_container);
  } else {
    PredictObstacles(obstacles_container, adc_trajectory_container);
  }
}

void PredictorManager::PredictObstacles(
    ObstaclesContainer* obstacles_container,
    ADCTrajectoryContainer* adc_trajectory_container) {
  for (const int id : obstacles_container->curr_frame_obstacle_ids()) {
    if (id < 0) {
      ADEBUG << "The obstacle has invalid id [" << id << "].";
      continue;
    }

    PredictionObstacle prediction_obstacle;
    Obstacle* obstacle = obstacles_container->GetObstacle(id);

    PerceptionObstacle perception_obstacle =
        obstacles_container->GetPerceptionObstacle(id);
    // if obstacle == nullptr, that means obstacle is unmovable
    // Checkout the logic of unmovable in obstacle.cc
    if (obstacle != nullptr) {
      PredictObstacle(obstacle, &prediction_obstacle, adc_trajectory_container);
    } else {  // obstacle == nullptr
      prediction_obstacle.set_timestamp(perception_obstacle.timestamp());
      prediction_obstacle.set_is_static(true);
    }

    prediction_obstacle.set_predicted_period(
        FLAGS_prediction_trajectory_time_length);
    prediction_obstacle.mutable_perception_obstacle()->CopyFrom(
        perception_obstacle);

    prediction_obstacles_.add_prediction_obstacle()->CopyFrom(
        prediction_obstacle);
  }
}

void PredictorManager::PredictObstaclesInParallel(
    ObstaclesContainer* obstacles_container,
    ADCTrajectoryContainer* adc_trajectory_container) {
  IdPredictionObstacleMap id_prediction_obstacle_map;
  for (int id : obstacles_container->curr_frame_obstacle_ids()) {
    id_prediction_obstacle_map[id] = std::make_shared<PredictionObstacle>();
  }
  IdObstacleListMap id_obstacle_map;
  for (int id : obstacles_container->curr_frame_obstacle_ids()) {
    Obstacle* obstacle = obstacles_container->GetObstacle(id);
    const PerceptionObstacle& perception_obstacle =
        obstacles_container->GetPerceptionObstacle(id);
    if (obstacle == nullptr) {
      std::shared_ptr<PredictionObstacle> prediction_obstacle_ptr =
          id_prediction_obstacle_map[id];
      prediction_obstacle_ptr->set_is_static(true);
      prediction_obstacle_ptr->set_timestamp(perception_obstacle.timestamp());
    } else {
      GroupObstaclesByObstacleId(id, obstacles_container, &id_obstacle_map);
    }
  }
  PredictionThreadPool::ForEach(
      id_obstacle_map.begin(), id_obstacle_map.end(),
      [&](IdObstacleListMap::iterator::value_type& obstacles_iter) {
        for (auto obstacle_ptr : obstacles_iter.second) {
          int id = obstacle_ptr->id();
          PredictObstacle(obstacle_ptr, id_prediction_obstacle_map[id].get(),
                          adc_trajectory_container);
        }
      });
  for (auto& item : id_prediction_obstacle_map) {
    int id = item.first;
    auto prediction_obstacle_ptr = item.second;
    const PerceptionObstacle& perception_obstacle =
        obstacles_container->GetPerceptionObstacle(id);
    prediction_obstacle_ptr->set_predicted_period(
        FLAGS_prediction_trajectory_time_length);
    prediction_obstacle_ptr->mutable_perception_obstacle()->CopyFrom(
        perception_obstacle);
    prediction_obstacles_.add_prediction_obstacle()->CopyFrom(
        *prediction_obstacle_ptr);
  }
}

void PredictorManager::PredictObstacle(
    Obstacle* obstacle, PredictionObstacle* const prediction_obstacle,
    ADCTrajectoryContainer* adc_trajectory_container) {
  CHECK_NOTNULL(obstacle);
  Predictor* predictor = nullptr;
  prediction_obstacle->set_timestamp(obstacle->timestamp());
  if (obstacle->ToIgnore()) {
    ADEBUG << "Ignore obstacle [" << obstacle->id() << "]";
    predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
    prediction_obstacle->mutable_priority()->set_priority(
        ObstaclePriority::IGNORE);
  } else if (obstacle->IsStill()) {
    ADEBUG << "Still obstacle [" << obstacle->id() << "]";
    predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
  } else {
    switch (obstacle->type()) {
      case PerceptionObstacle::VEHICLE: {
        if (obstacle->HasJunctionFeatureWithExits() &&
            !obstacle->IsCloseToJunctionExit()) {
          predictor = GetPredictor(vehicle_in_junction_predictor_);
          CHECK_NOTNULL(predictor);
        } else if (obstacle->IsOnLane()) {
          predictor = GetPredictor(vehicle_on_lane_predictor_);
          CHECK_NOTNULL(predictor);
        } else {
          predictor = GetPredictor(vehicle_off_lane_predictor_);
          CHECK_NOTNULL(predictor);
        }
        break;
      }
      case PerceptionObstacle::PEDESTRIAN: {
        predictor = GetPredictor(pedestrian_predictor_);
        break;
      }
      case PerceptionObstacle::BICYCLE: {
        if (obstacle->IsOnLane()) {
          predictor = GetPredictor(cyclist_on_lane_predictor_);
          // TODO(kechxu) add a specific predictor in junction
        } else {
          predictor = GetPredictor(cyclist_off_lane_predictor_);
        }
        break;
      }
      default: {
        if (obstacle->IsOnLane()) {
          predictor = GetPredictor(default_on_lane_predictor_);
        } else {
          predictor = GetPredictor(default_off_lane_predictor_);
        }
        break;
      }
    }
  }

  if (predictor != nullptr) {
    predictor->Predict(obstacle);
    if (FLAGS_enable_trim_prediction_trajectory &&
        obstacle->type() == PerceptionObstacle::VEHICLE) {
      CHECK_NOTNULL(adc_trajectory_container);
      predictor->TrimTrajectories(*adc_trajectory_container, obstacle);
    }
  }
  for (const auto& trajectory :
       obstacle->latest_feature().predicted_trajectory()) {
    prediction_obstacle->add_trajectory()->CopyFrom(trajectory);
  }
  prediction_obstacle->set_timestamp(obstacle->timestamp());
  prediction_obstacle->mutable_priority()->CopyFrom(
      obstacle->latest_feature().priority());
  prediction_obstacle->set_is_static(obstacle->IsStill());
  if (FLAGS_prediction_offline_mode == 3) {
    FeatureOutput::InsertPredictionResult(obstacle->id(), *prediction_obstacle);
  }
}

std::unique_ptr<Predictor> PredictorManager::CreatePredictor(
    const ObstacleConf::PredictorType& type) {
  std::unique_ptr<Predictor> predictor_ptr(nullptr);
  switch (type) {
    case ObstacleConf::LANE_SEQUENCE_PREDICTOR: {
      predictor_ptr.reset(new LaneSequencePredictor());
      break;
    }
    case ObstacleConf::MOVE_SEQUENCE_PREDICTOR: {
      predictor_ptr.reset(new MoveSequencePredictor());
      break;
    }
    case ObstacleConf::SINGLE_LANE_PREDICTOR: {
      predictor_ptr.reset(new SingleLanePredictor());
      break;
    }
    case ObstacleConf::FREE_MOVE_PREDICTOR: {
      predictor_ptr.reset(new FreeMovePredictor());
      break;
    }
    case ObstacleConf::REGIONAL_PREDICTOR: {
      predictor_ptr.reset(new RegionalPredictor());
      break;
    }
    case ObstacleConf::JUNCTION_PREDICTOR: {
      predictor_ptr.reset(new JunctionPredictor());
      break;
    }
    case ObstacleConf::EXTRAPOLATION_PREDICTOR: {
      predictor_ptr.reset(new ExtrapolationPredictor());
      break;
    }
    case ObstacleConf::INTERACTION_PREDICTOR: {
      predictor_ptr.reset(new InteractionPredictor());
      break;
    }
    default: {
      break;
    }
  }
  return predictor_ptr;
}

void PredictorManager::RegisterPredictor(
    const ObstacleConf::PredictorType& type) {
  predictors_[type] = CreatePredictor(type);
  AINFO << "Predictor [" << type << "] is registered.";
}

const PredictionObstacles& PredictorManager::prediction_obstacles() {
  return prediction_obstacles_;
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

                                 // @sect3{Include files}

				 // The first few files have already
				 // been covered in previous examples
				 // and will thus not be further
				 // commented on.
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <base/utilities.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <dofs/hp_dof_handler.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/hp_fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>

#include <fstream>
#include <iostream>

#include <fe/fe_q.h>
#include <grid/grid_out.h>
#include <dofs/dof_constraints.h>
#include <grid/grid_refinement.h>
#include <numerics/error_estimator.h>

				 // Finally, this is as in previous
				 // programs:
using namespace dealii;

template <int dim>
class LaplaceProblem
{
  public:
    LaplaceProblem ();
    ~LaplaceProblem ();

    void run ();

  private:
    void setup_system ();
    void assemble_system ();
    void solve ();
    void refine_grid ();
    void output_results (const unsigned int cycle) const;

    Triangulation<dim>   triangulation;

    hp::DoFHandler<dim>      dof_handler;
    hp::FECollection<dim>    fe_collection;
    hp::QCollection<dim>     quadrature_collection;

    ConstraintMatrix     hanging_node_constraints;

    SparsityPattern      sparsity_pattern;
    SparseMatrix<double> system_matrix;

    Vector<double>       solution;
    Vector<double>       system_rhs;
};

template <int dim>
LaplaceProblem<dim>::LaplaceProblem () :
		dof_handler (triangulation)
{
  for (unsigned int degree=1; degree<5; ++degree)
    {
      fe_collection.push_back (FE_Q<dim>(degree));
      quadrature_collection.push_back (QGauss<dim>(degree+2));
    }
}

template <int dim>
LaplaceProblem<dim>::~LaplaceProblem ()
{
  dof_handler.clear ();
}

template <int dim>
void LaplaceProblem<dim>::setup_system ()
{
  dof_handler.distribute_dofs (fe_collection);

  sparsity_pattern.reinit (dof_handler.n_dofs(),
			   dof_handler.n_dofs(),
			   dof_handler.max_couplings_between_dofs());
  DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);

  solution.reinit (dof_handler.n_dofs());
  system_rhs.reinit (dof_handler.n_dofs());

  hanging_node_constraints.clear ();
  DoFTools::make_hanging_node_constraints (dof_handler,
					   hanging_node_constraints);

  hanging_node_constraints.close ();

  hanging_node_constraints.condense (sparsity_pattern);
  sparsity_pattern.compress();

  system_matrix.reinit (sparsity_pattern);
}

template <int dim>
void LaplaceProblem<dim>::assemble_system ()
{
  hp::FEValues<dim> hp_fe_values (fe_collection,
				  quadrature_collection,
				  update_values    |  update_gradients |
				  update_q_points  |  update_JxW_values);

  typename hp::DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      const unsigned int   dofs_per_cell = cell->get_fe().dofs_per_cell;
      FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);
      Vector<double>       cell_rhs (dofs_per_cell);

      std::vector<unsigned int> local_dof_indices (dofs_per_cell);

      cell_matrix = 0;
      cell_rhs = 0;

      hp_fe_values.reinit (cell);

      const FEValues<dim> &fe_values = hp_fe_values.get_present_fe_values ();

      for (unsigned int q_point=0; q_point<fe_values.n_quadrature_points; ++q_point)
	for (unsigned int i=0; i<dofs_per_cell; ++i)
	  {
	    for (unsigned int j=0; j<dofs_per_cell; ++j)
	      cell_matrix(i,j) += (fe_values.shape_grad(i,q_point) *
				   fe_values.shape_grad(j,q_point) *
				   fe_values.JxW(q_point));

	    cell_rhs(i) += (fe_values.shape_value(i,q_point) *
			    1.0 *
			    fe_values.JxW(q_point));
	  }

      cell->get_dof_indices (local_dof_indices);
      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    system_matrix.add (local_dof_indices[i],
			       local_dof_indices[j],
			       cell_matrix(i,j));

	  system_rhs(local_dof_indices[i]) += cell_rhs(i);
	}
    }

  hanging_node_constraints.condense (system_matrix);
  hanging_node_constraints.condense (system_rhs);
  std::map<unsigned int,double> boundary_values;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(),
					    boundary_values);
  MatrixTools::apply_boundary_values (boundary_values,
				      system_matrix,
				      solution,
				      system_rhs);
}

template <int dim>
void LaplaceProblem<dim>::solve ()
{
  SolverControl           solver_control (1000, 1e-12);
  SolverCG<>              cg (solver_control);

  PreconditionSSOR<> preconditioner;
  preconditioner.initialize(system_matrix, 1.2);

  cg.solve (system_matrix, solution, system_rhs,
	    preconditioner);

  hanging_node_constraints.distribute (solution);
}

template <int dim>
void LaplaceProblem<dim>::refine_grid ()
{
  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());

  KellyErrorEstimator<dim>::estimate (dof_handler,
				      QGauss<dim-1>(3),
				      typename FunctionMap<dim>::type(),
				      solution,
				      estimated_error_per_cell);

  GridRefinement::refine_and_coarsen_fixed_number (triangulation,
						   estimated_error_per_cell,
						   0.3, 0.03);

  triangulation.execute_coarsening_and_refinement ();
}

template <int dim>
void LaplaceProblem<dim>::output_results (const unsigned int cycle) const
{
  Assert (cycle < 10, ExcNotImplemented());

  {
    const std::string filename = "grid-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".eps";
    std::ofstream output (filename.c_str());

    GridOut grid_out;
    grid_out.write_eps (triangulation, output);
  }

  {
    const std::string filename = "solution-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".gnuplot";
    DataOut<dim,hp::DoFHandler<dim> > data_out;

    data_out.attach_dof_handler (dof_handler);
    data_out.add_data_vector (solution, "solution");
    data_out.build_patches ();

    std::ofstream output (filename.c_str());
    data_out.write_gnuplot (output);
  }
}

void
create_coarse_grid (Triangulation<2> &coarse_grid)
{
  const unsigned int dim = 2;
  static const Point<2> vertices_1[]
    = {  Point<2> (-1.,   -1.),
         Point<2> (-1./2, -1.),
         Point<2> (0.,    -1.),
         Point<2> (+1./2, -1.),
         Point<2> (+1,    -1.),

         Point<2> (-1.,   -1./2.),
         Point<2> (-1./2, -1./2.),
         Point<2> (0.,    -1./2.),
         Point<2> (+1./2, -1./2.),
         Point<2> (+1,    -1./2.),

         Point<2> (-1.,   0.),
         Point<2> (-1./2, 0.),
         Point<2> (+1./2, 0.),
         Point<2> (+1,    0.),

         Point<2> (-1.,   1./2.),
         Point<2> (-1./2, 1./2.),
         Point<2> (0.,    1./2.),
         Point<2> (+1./2, 1./2.),
         Point<2> (+1,    1./2.),

         Point<2> (-1.,   1.),
         Point<2> (-1./2, 1.),
         Point<2> (0.,    1.),
         Point<2> (+1./2, 1.),
         Point<2> (+1,    1.)    };
  const unsigned int
    n_vertices = sizeof(vertices_1) / sizeof(vertices_1[0]);
  const std::vector<Point<dim> > vertices (&vertices_1[0],
                                           &vertices_1[n_vertices]);
  static const int cell_vertices[][GeometryInfo<dim>::vertices_per_cell]
    = {{0, 1, 5, 6},
       {1, 2, 6, 7},
       {2, 3, 7, 8},
       {3, 4, 8, 9},
       {5, 6, 10, 11},
       {8, 9, 12, 13},
       {10, 11, 14, 15},
       {12, 13, 17, 18},
       {14, 15, 19, 20},
       {15, 16, 20, 21},
       {16, 17, 21, 22},
       {17, 18, 22, 23}};
  const unsigned int
    n_cells = sizeof(cell_vertices) / sizeof(cell_vertices[0]);

  std::vector<CellData<dim> > cells (n_cells, CellData<dim>());
  for (unsigned int i=0; i<n_cells; ++i)
    {
      for (unsigned int j=0;
           j<GeometryInfo<dim>::vertices_per_cell;
           ++j)
        cells[i].vertices[j] = cell_vertices[i][j];
      cells[i].material_id = 0;
    }

  coarse_grid.create_triangulation (vertices,
                                    cells,
                                    SubCellData());
  coarse_grid.refine_global (1);
}

template <int dim>
void LaplaceProblem<dim>::run ()
{
  for (unsigned int cycle=0; cycle<5; ++cycle)
    {
      std::cout << "Cycle " << cycle << ':' << std::endl;

      if (cycle == 0)
	create_coarse_grid (triangulation);
      else
	refine_grid ();

      std::cout << "   Number of active cells:       "
		<< triangulation.n_active_cells()
		<< std::endl;

      setup_system ();

      std::cout << "   Number of degrees of freedom: "
		<< dof_handler.n_dofs()
		<< std::endl;

      assemble_system ();
      solve ();
      output_results (cycle);
    }
}

int main ()
{
  try
    {
      deallog.depth_console (0);

      LaplaceProblem<2> laplace_problem_2d;
      laplace_problem_2d.run ();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    }

  return 0;
}
<commit_msg>Simplify code a bit.<commit_after>/* $Id$ */
/* Author: Wolfgang Bangerth, University of Heidelberg, 2000 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

                                 // @sect3{Include files}

				 // The first few files have already
				 // been covered in previous examples
				 // and will thus not be further
				 // commented on.
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/logstream.h>
#include <base/utilities.h>
#include <lac/vector.h>
#include <lac/full_matrix.h>
#include <lac/sparse_matrix.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <grid/tria.h>
#include <dofs/hp_dof_handler.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/hp_fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>

#include <fstream>
#include <iostream>

#include <fe/fe_q.h>
#include <grid/grid_out.h>
#include <dofs/dof_constraints.h>
#include <grid/grid_refinement.h>
#include <numerics/error_estimator.h>

				 // Finally, this is as in previous
				 // programs:
using namespace dealii;

template <int dim>
class LaplaceProblem
{
  public:
    LaplaceProblem ();
    ~LaplaceProblem ();

    void run ();

  private:
    void setup_system ();
    void assemble_system ();
    void solve ();
    void create_coarse_grid ();
    void refine_grid ();
    void output_results (const unsigned int cycle) const;

    Triangulation<dim>   triangulation;

    hp::DoFHandler<dim>      dof_handler;
    hp::FECollection<dim>    fe_collection;
    hp::QCollection<dim>     quadrature_collection;

    ConstraintMatrix     hanging_node_constraints;

    SparsityPattern      sparsity_pattern;
    SparseMatrix<double> system_matrix;

    Vector<double>       solution;
    Vector<double>       system_rhs;
};

template <int dim>
LaplaceProblem<dim>::LaplaceProblem () :
		dof_handler (triangulation)
{
  for (unsigned int degree=1; degree<5; ++degree)
    {
      fe_collection.push_back (FE_Q<dim>(degree));
      quadrature_collection.push_back (QGauss<dim>(degree+2));
    }
}

template <int dim>
LaplaceProblem<dim>::~LaplaceProblem ()
{
  dof_handler.clear ();
}

template <int dim>
void LaplaceProblem<dim>::setup_system ()
{
  dof_handler.distribute_dofs (fe_collection);

  sparsity_pattern.reinit (dof_handler.n_dofs(),
			   dof_handler.n_dofs(),
			   dof_handler.max_couplings_between_dofs());
  DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);

  solution.reinit (dof_handler.n_dofs());
  system_rhs.reinit (dof_handler.n_dofs());

  hanging_node_constraints.clear ();
  DoFTools::make_hanging_node_constraints (dof_handler,
					   hanging_node_constraints);

  hanging_node_constraints.close ();

  hanging_node_constraints.condense (sparsity_pattern);
  sparsity_pattern.compress();

  system_matrix.reinit (sparsity_pattern);
}

template <int dim>
void LaplaceProblem<dim>::assemble_system ()
{
  hp::FEValues<dim> hp_fe_values (fe_collection,
				  quadrature_collection,
				  update_values    |  update_gradients |
				  update_q_points  |  update_JxW_values);

  typename hp::DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      const unsigned int   dofs_per_cell = cell->get_fe().dofs_per_cell;
      FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);
      Vector<double>       cell_rhs (dofs_per_cell);

      std::vector<unsigned int> local_dof_indices (dofs_per_cell);

      cell_matrix = 0;
      cell_rhs = 0;

      hp_fe_values.reinit (cell);

      const FEValues<dim> &fe_values = hp_fe_values.get_present_fe_values ();

      for (unsigned int q_point=0; q_point<fe_values.n_quadrature_points; ++q_point)
	for (unsigned int i=0; i<dofs_per_cell; ++i)
	  {
	    for (unsigned int j=0; j<dofs_per_cell; ++j)
	      cell_matrix(i,j) += (fe_values.shape_grad(i,q_point) *
				   fe_values.shape_grad(j,q_point) *
				   fe_values.JxW(q_point));

	    cell_rhs(i) += (fe_values.shape_value(i,q_point) *
			    1.0 *
			    fe_values.JxW(q_point));
	  }

      cell->get_dof_indices (local_dof_indices);
      for (unsigned int i=0; i<dofs_per_cell; ++i)
	{
	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    system_matrix.add (local_dof_indices[i],
			       local_dof_indices[j],
			       cell_matrix(i,j));

	  system_rhs(local_dof_indices[i]) += cell_rhs(i);
	}
    }

  hanging_node_constraints.condense (system_matrix);
  hanging_node_constraints.condense (system_rhs);
  std::map<unsigned int,double> boundary_values;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(),
					    boundary_values);
  MatrixTools::apply_boundary_values (boundary_values,
				      system_matrix,
				      solution,
				      system_rhs);
}

template <int dim>
void LaplaceProblem<dim>::solve ()
{
  SolverControl           solver_control (1000, 1e-12);
  SolverCG<>              cg (solver_control);

  PreconditionSSOR<> preconditioner;
  preconditioner.initialize(system_matrix, 1.2);

  cg.solve (system_matrix, solution, system_rhs,
	    preconditioner);

  hanging_node_constraints.distribute (solution);
}

template <int dim>
void LaplaceProblem<dim>::refine_grid ()
{
  Vector<float> estimated_error_per_cell (triangulation.n_active_cells());

  KellyErrorEstimator<dim>::estimate (dof_handler,
				      QGauss<dim-1>(3),
				      typename FunctionMap<dim>::type(),
				      solution,
				      estimated_error_per_cell);

  GridRefinement::refine_and_coarsen_fixed_number (triangulation,
						   estimated_error_per_cell,
						   0.3, 0.03);

  triangulation.execute_coarsening_and_refinement ();
}

template <int dim>
void LaplaceProblem<dim>::output_results (const unsigned int cycle) const
{
  Assert (cycle < 10, ExcNotImplemented());

  {
    const std::string filename = "grid-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".eps";
    std::ofstream output (filename.c_str());

    GridOut grid_out;
    grid_out.write_eps (triangulation, output);
  }

  {
    const std::string filename = "solution-" +
				 Utilities::int_to_string (cycle, 2) +
				 ".gnuplot";
    DataOut<dim,hp::DoFHandler<dim> > data_out;

    data_out.attach_dof_handler (dof_handler);
    data_out.add_data_vector (solution, "solution");
    data_out.build_patches ();

    std::ofstream output (filename.c_str());
    data_out.write_gnuplot (output);
  }
}

template <>
void LaplaceProblem<2>::create_coarse_grid ()
{
  const unsigned int dim = 2;

  static const Point<2> vertices_1[]
    = {  Point<2> (-1.,   -1.),
         Point<2> (-1./2, -1.),
         Point<2> (0.,    -1.),
         Point<2> (+1./2, -1.),
         Point<2> (+1,    -1.),

         Point<2> (-1.,   -1./2.),
         Point<2> (-1./2, -1./2.),
         Point<2> (0.,    -1./2.),
         Point<2> (+1./2, -1./2.),
         Point<2> (+1,    -1./2.),

         Point<2> (-1.,   0.),
         Point<2> (-1./2, 0.),
         Point<2> (+1./2, 0.),
         Point<2> (+1,    0.),

         Point<2> (-1.,   1./2.),
         Point<2> (-1./2, 1./2.),
         Point<2> (0.,    1./2.),
         Point<2> (+1./2, 1./2.),
         Point<2> (+1,    1./2.),

         Point<2> (-1.,   1.),
         Point<2> (-1./2, 1.),
         Point<2> (0.,    1.),
         Point<2> (+1./2, 1.),
         Point<2> (+1,    1.)    };
  const unsigned int
    n_vertices = sizeof(vertices_1) / sizeof(vertices_1[0]);
  const std::vector<Point<dim> > vertices (&vertices_1[0],
                                           &vertices_1[n_vertices]);
  static const int cell_vertices[][GeometryInfo<dim>::vertices_per_cell]
    = {{0, 1, 5, 6},
       {1, 2, 6, 7},
       {2, 3, 7, 8},
       {3, 4, 8, 9},
       {5, 6, 10, 11},
       {8, 9, 12, 13},
       {10, 11, 14, 15},
       {12, 13, 17, 18},
       {14, 15, 19, 20},
       {15, 16, 20, 21},
       {16, 17, 21, 22},
       {17, 18, 22, 23}};
  const unsigned int
    n_cells = sizeof(cell_vertices) / sizeof(cell_vertices[0]);

  std::vector<CellData<dim> > cells (n_cells, CellData<dim>());
  for (unsigned int i=0; i<n_cells; ++i)
    {
      for (unsigned int j=0;
           j<GeometryInfo<dim>::vertices_per_cell;
           ++j)
        cells[i].vertices[j] = cell_vertices[i][j];
      cells[i].material_id = 0;
    }

  triangulation.create_triangulation (vertices,
                                    cells,
                                    SubCellData());
  triangulation.refine_global (1);
}

template <int dim>
void LaplaceProblem<dim>::run ()
{
  for (unsigned int cycle=0; cycle<5; ++cycle)
    {
      std::cout << "Cycle " << cycle << ':' << std::endl;

      if (cycle == 0)
	create_coarse_grid ();
      else
	refine_grid ();

      std::cout << "   Number of active cells:       "
		<< triangulation.n_active_cells()
		<< std::endl;

      setup_system ();

      std::cout << "   Number of degrees of freedom: "
		<< dof_handler.n_dofs()
		<< std::endl;

      assemble_system ();
      solve ();
      output_results (cycle);
    }
}

int main ()
{
  try
    {
      deallog.depth_console (0);

      LaplaceProblem<2> laplace_problem_2d;
      laplace_problem_2d.run ();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    }

  return 0;
}
<|endoftext|>