<commit_before>/***************************************************************************
 *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <qobject.h>
#endif

#include "Workbench.h"
#include <Gui/MenuManager.h>
#include <Gui/ToolBarManager.h>

using namespace TechDrawGui;

TYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)

Workbench::Workbench()
{
}

Workbench::~Workbench()
{
}

Gui::MenuItem* Workbench::setupMenuBar() const
{
    Gui::MenuItem* root = StdWorkbench::setupMenuBar();
    Gui::MenuItem* item = root->findItem("&Windows");
    Gui::MenuItem* draw = new Gui::MenuItem;
    root->insertItem(item, draw);

    // dimensions
    Gui::MenuItem* dimensions = new Gui::MenuItem;
    dimensions->setCommand("Dimensions");
    *dimensions << "TechDraw_LengthDimension";
    *dimensions << "TechDraw_HorizontalDimension";
    *dimensions << "TechDraw_VerticalDimension";
    *dimensions << "TechDraw_RadiusDimension";
    *dimensions << "TechDraw_DiameterDimension";
    *dimensions << "TechDraw_AngleDimension";
    *dimensions << "TechDraw_HorizontalExtentDimension";
    *dimensions << "TechDraw_VerticalExtentDimension";
    *dimensions << "TechDraw_LinkDimension";
    *dimensions << "TechDraw_LandmarkDimension";

    // annotations
    Gui::MenuItem* annotations = new Gui::MenuItem;
    annotations->setCommand("Annotations");
    *annotations << "TechDraw_Annotation";
    *annotations << "TechDraw_RichTextAnnotation";
    *annotations << "TechDraw_Balloon";

    // lines
    Gui::MenuItem* lines = new Gui::MenuItem;
    lines->setCommand("Add Lines");
    *lines << "TechDraw_LeaderLine";
    *lines << "TechDraw_FaceCenterLine";
    *lines << "TechDraw_2LineCenterLine";
    *lines << "TechDraw_2PointCenterLine";
    *lines << "TechDraw_2PointCosmeticLine";

    // vertices
    Gui::MenuItem* vertices = new Gui::MenuItem;
    vertices->setCommand("Add Vertices");
    *vertices << "TechDraw_CosmeticVertex";
    *vertices << "TechDraw_Midpoints";
    *vertices << "TechDraw_Quadrants";

    // main menu
    draw->setCommand("TechDraw");
    *draw << "TechDraw_PageDefault";
    *draw << "TechDraw_PageTemplate";
    *draw << "TechDraw_RedrawPage";
    *draw << "Separator";
    *draw << "TechDraw_View";
    *draw << "TechDraw_ActiveView";
    *draw << "TechDraw_ProjectionGroup";
    *draw << "TechDraw_SectionView";
    *draw << "TechDraw_DetailView";
    *draw << "Separator";
    *draw << "TechDraw_DraftView";
    *draw << "TechDraw_ArchView";
    *draw << "TechDraw_SpreadsheetView";
    *draw << "Separator";
    *draw << "TechDraw_ClipGroup";
    *draw << "TechDraw_ClipGroupAdd";
    *draw << "TechDraw_ClipGroupRemove";
    *draw << "Separator";
    *draw << dimensions;
    *draw << "Separator";
    *draw << "TechDraw_ExportPageSVG";
    *draw << "TechDraw_ExportPageDXF";
    *draw << "Separator";
    *draw << "TechDraw_Hatch";
    *draw << "TechDraw_GeometricHatch";
    *draw << "TechDraw_Symbol";
    *draw << "TechDraw_Image";
    *draw << "TechDraw_ToggleFrame";
    *draw << "Separator";
    *draw << annotations;
    *draw << lines;
    *draw << vertices;
    *draw << "TechDraw_CosmeticEraser";
    *draw << "TechDraw_DecorateLine";
    *draw << "TechDraw_ShowAll";
    *draw << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupToolBars() const
{
    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_PageDefault";
    *pages << "TechDraw_PageTemplate";
    *pages << "TechDraw_RedrawPage";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("TechDraw Views");
    *views << "TechDraw_View";
    *views << "TechDraw_ActiveView";
    *views << "TechDraw_ProjectionGroup";
    *views << "TechDraw_SectionView";
    *views << "TechDraw_DetailView";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_ArchView";
    *views << "TechDraw_SpreadsheetView";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_ClipGroup";
    *clips << "TechDraw_ClipGroupAdd";
    *clips << "TechDraw_ClipGroupRemove";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_LengthDimension";
    *dims << "TechDraw_HorizontalDimension";
    *dims << "TechDraw_VerticalDimension";
    *dims << "TechDraw_RadiusDimension";
    *dims << "TechDraw_DiameterDimension";
    *dims << "TechDraw_AngleDimension";
    *dims << "TechDraw_3PtAngleDimension";
    *dims << "TechDraw_ExtentGroup";
//    *dims << "TechDraw_HorizontalExtentDimension";
//    *dims << "TechDraw_VerticalExtentDimension";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_Balloon";
    *dims << "TechDraw_LandmarkDimension";
//    *dims << "TechDraw_Dimension"

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPageSVG";
    *file << "TechDraw_ExportPageDXF";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_Hatch";
    *decor << "TechDraw_GeometricHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichTextAnnotation";
    *anno << "TechDraw_CosmeticVertexGroup";
    *anno << "TechDraw_CenterLineGroup";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_2PointCosmeticLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupCommandBars() const
{
    Gui::ToolBarItem* root = new Gui::ToolBarItem;
    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_PageDefault";
    *pages << "TechDraw_PageTemplate";
    *pages << "TechDraw_RedrawPage";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("Views");
    *views << "TechDraw_View";
    *views << "TechDraw_ActiveView";
//    *views << "TechDraw_NewMulti";    //deprecated
    *views << "TechDraw_ProjectionGroup";
    *views << "TechDraw_SectionView";
    *views << "TechDraw_DetailView";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_SpreadsheetView";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_ClipGroup";
    *clips << "TechDraw_ClipGroupAdd";
    *clips << "TechDraw_ClipGroupRemove";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_LengthDimension";
    *dims << "TechDraw_HorizontalDimension";
    *dims << "TechDraw_VerticalDimension";
    *dims << "TechDraw_RadiusDimension";
    *dims << "TechDraw_DiameterDimension";
    *dims << "TechDraw_AngleDimension";
    *dims << "TechDraw_3PtAngleDimension";
    *dims << "TechDraw_ExtentGroup";
//    *dims << "TechDraw_HorizontalExtentDimension";
//    *dims << "TechDraw_VerticalExtentDimension";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_Balloon";
    *dims << "TechDraw_LandmarkDimension";
//    *dims << "TechDraw_Dimension";

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPageSVG";
    *file << "TechDraw_ExportPageDXF";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_Hatch";
    *decor << "TechDraw_GeometricHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichTextAnnotation";
    *anno << "TechDraw_CosmeticVertexGroup";
    *anno << "TechDraw_CenterLineGroup";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_2PointCosmeticLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";

    return root;
}
<commit_msg>TechDraw: Expose strings in Workbench.cpp to translators<commit_after>/***************************************************************************
 *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <qobject.h>
#endif

#include "Workbench.h"
#include <Gui/MenuManager.h>
#include <Gui/ToolBarManager.h>

using namespace TechDrawGui;

#if 0 // needed for Qt's lupdate utility
    qApp->translate("Workbench", "Dimensions");
    qApp->translate("Workbench", "Annotations");
    qApp->translate("Workbench", "Add Lines");
    qApp->translate("Workbench", "Add Vertices");
    qApp->translate("Workbench", "TechDraw");
    qApp->translate("Workbench", "TechDraw Pages");
    qApp->translate("Workbench", "TechDraw Views");
    qApp->translate("Workbench", "TechDraw Clips");
    qApp->translate("Workbench", "TechDraw Dimensions");
    qApp->translate("Workbench", "TechDraw File Access");
    qApp->translate("Workbench", "TechDraw Decoration");
    qApp->translate("Workbench", "TechDraw Annotation");
    qApp->translate("Workbench", "Views");
#endif

TYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)

Workbench::Workbench()
{
}

Workbench::~Workbench()
{
}

Gui::MenuItem* Workbench::setupMenuBar() const
{
    Gui::MenuItem* root = StdWorkbench::setupMenuBar();
    Gui::MenuItem* item = root->findItem("&Windows");
    Gui::MenuItem* draw = new Gui::MenuItem;
    root->insertItem(item, draw);

    // dimensions
    Gui::MenuItem* dimensions = new Gui::MenuItem;
    dimensions->setCommand("Dimensions");
    *dimensions << "TechDraw_LengthDimension";
    *dimensions << "TechDraw_HorizontalDimension";
    *dimensions << "TechDraw_VerticalDimension";
    *dimensions << "TechDraw_RadiusDimension";
    *dimensions << "TechDraw_DiameterDimension";
    *dimensions << "TechDraw_AngleDimension";
    *dimensions << "TechDraw_HorizontalExtentDimension";
    *dimensions << "TechDraw_VerticalExtentDimension";
    *dimensions << "TechDraw_LinkDimension";
    *dimensions << "TechDraw_LandmarkDimension";

    // annotations
    Gui::MenuItem* annotations = new Gui::MenuItem;
    annotations->setCommand("Annotations");
    *annotations << "TechDraw_Annotation";
    *annotations << "TechDraw_RichTextAnnotation";
    *annotations << "TechDraw_Balloon";

    // lines
    Gui::MenuItem* lines = new Gui::MenuItem;
    lines->setCommand("Add Lines");
    *lines << "TechDraw_LeaderLine";
    *lines << "TechDraw_FaceCenterLine";
    *lines << "TechDraw_2LineCenterLine";
    *lines << "TechDraw_2PointCenterLine";
    *lines << "TechDraw_2PointCosmeticLine";

    // vertices
    Gui::MenuItem* vertices = new Gui::MenuItem;
    vertices->setCommand("Add Vertices");
    *vertices << "TechDraw_CosmeticVertex";
    *vertices << "TechDraw_Midpoints";
    *vertices << "TechDraw_Quadrants";

    // main menu
    draw->setCommand("TechDraw");
    *draw << "TechDraw_PageDefault";
    *draw << "TechDraw_PageTemplate";
    *draw << "TechDraw_RedrawPage";
    *draw << "Separator";
    *draw << "TechDraw_View";
    *draw << "TechDraw_ActiveView";
    *draw << "TechDraw_ProjectionGroup";
    *draw << "TechDraw_SectionView";
    *draw << "TechDraw_DetailView";
    *draw << "Separator";
    *draw << "TechDraw_DraftView";
    *draw << "TechDraw_ArchView";
    *draw << "TechDraw_SpreadsheetView";
    *draw << "Separator";
    *draw << "TechDraw_ClipGroup";
    *draw << "TechDraw_ClipGroupAdd";
    *draw << "TechDraw_ClipGroupRemove";
    *draw << "Separator";
    *draw << dimensions;
    *draw << "Separator";
    *draw << "TechDraw_ExportPageSVG";
    *draw << "TechDraw_ExportPageDXF";
    *draw << "Separator";
    *draw << "TechDraw_Hatch";
    *draw << "TechDraw_GeometricHatch";
    *draw << "TechDraw_Symbol";
    *draw << "TechDraw_Image";
    *draw << "TechDraw_ToggleFrame";
    *draw << "Separator";
    *draw << annotations;
    *draw << lines;
    *draw << vertices;
    *draw << "TechDraw_CosmeticEraser";
    *draw << "TechDraw_DecorateLine";
    *draw << "TechDraw_ShowAll";
    *draw << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupToolBars() const
{
    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_PageDefault";
    *pages << "TechDraw_PageTemplate";
    *pages << "TechDraw_RedrawPage";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("TechDraw Views");
    *views << "TechDraw_View";
    *views << "TechDraw_ActiveView";
    *views << "TechDraw_ProjectionGroup";
    *views << "TechDraw_SectionView";
    *views << "TechDraw_DetailView";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_ArchView";
    *views << "TechDraw_SpreadsheetView";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_ClipGroup";
    *clips << "TechDraw_ClipGroupAdd";
    *clips << "TechDraw_ClipGroupRemove";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_LengthDimension";
    *dims << "TechDraw_HorizontalDimension";
    *dims << "TechDraw_VerticalDimension";
    *dims << "TechDraw_RadiusDimension";
    *dims << "TechDraw_DiameterDimension";
    *dims << "TechDraw_AngleDimension";
    *dims << "TechDraw_3PtAngleDimension";
    *dims << "TechDraw_ExtentGroup";
//    *dims << "TechDraw_HorizontalExtentDimension";
//    *dims << "TechDraw_VerticalExtentDimension";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_Balloon";
    *dims << "TechDraw_LandmarkDimension";
//    *dims << "TechDraw_Dimension"

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPageSVG";
    *file << "TechDraw_ExportPageDXF";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_Hatch";
    *decor << "TechDraw_GeometricHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichTextAnnotation";
    *anno << "TechDraw_CosmeticVertexGroup";
    *anno << "TechDraw_CenterLineGroup";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_2PointCosmeticLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupCommandBars() const
{
    Gui::ToolBarItem* root = new Gui::ToolBarItem;
    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_PageDefault";
    *pages << "TechDraw_PageTemplate";
    *pages << "TechDraw_RedrawPage";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("Views");
    *views << "TechDraw_View";
    *views << "TechDraw_ActiveView";
//    *views << "TechDraw_NewMulti";    //deprecated
    *views << "TechDraw_ProjectionGroup";
    *views << "TechDraw_SectionView";
    *views << "TechDraw_DetailView";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_SpreadsheetView";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_ClipGroup";
    *clips << "TechDraw_ClipGroupAdd";
    *clips << "TechDraw_ClipGroupRemove";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_LengthDimension";
    *dims << "TechDraw_HorizontalDimension";
    *dims << "TechDraw_VerticalDimension";
    *dims << "TechDraw_RadiusDimension";
    *dims << "TechDraw_DiameterDimension";
    *dims << "TechDraw_AngleDimension";
    *dims << "TechDraw_3PtAngleDimension";
    *dims << "TechDraw_ExtentGroup";
//    *dims << "TechDraw_HorizontalExtentDimension";
//    *dims << "TechDraw_VerticalExtentDimension";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_Balloon";
    *dims << "TechDraw_LandmarkDimension";
//    *dims << "TechDraw_Dimension";

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPageSVG";
    *file << "TechDraw_ExportPageDXF";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_Hatch";
    *decor << "TechDraw_GeometricHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichTextAnnotation";
    *anno << "TechDraw_CosmeticVertexGroup";
    *anno << "TechDraw_CenterLineGroup";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_2PointCosmeticLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";

    return root;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <qobject.h>
#endif

#include "Workbench.h"
#include <Gui/MenuManager.h>
#include <Gui/ToolBarManager.h>

using namespace TechDrawGui;

TYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)

Workbench::Workbench()
{
}

Workbench::~Workbench()
{
}

Gui::MenuItem* Workbench::setupMenuBar() const
{
    Gui::MenuItem* root = StdWorkbench::setupMenuBar();
    Gui::MenuItem* item = root->findItem("&Windows");

    Gui::MenuItem* draw = new Gui::MenuItem;
    root->insertItem(item, draw);
    draw->setCommand("TechDraw");
    *draw << "TechDraw_NewPageDef";
    *draw << "TechDraw_NewPage";
    *draw << "TechDraw_Redraw";
    *draw << "Separator";
    *draw << "TechDraw_NewView";
    *draw << "TechDraw_NewActiveView";
//    *draw << "TechDraw_NewMulti";     //deprecated
    *draw << "TechDraw_ProjGroup";
    *draw << "TechDraw_NewViewSection";
    *draw << "TechDraw_NewViewDetail";
    *draw << "Separator";
    *draw << "TechDraw_DraftView";
    *draw << "TechDraw_ArchView";
    *draw << "TechDraw_Spreadsheet";
    *draw << "Separator";
    *draw << "TechDraw_Clip";
    *draw << "TechDraw_ClipPlus";
    *draw << "TechDraw_ClipMinus";
    *draw << "Separator";
    *draw << "TechDraw_NewLengthDimension";
    *draw << "TechDraw_NewDistanceXDimension";
    *draw << "TechDraw_NewDistanceYDimension";
    *draw << "TechDraw_NewRadiusDimension";
    *draw << "TechDraw_NewDiameterDimension";
    *draw << "TechDraw_NewAngleDimension";
    *draw << "TechDraw_HorizontalExtent";
    *draw << "TechDraw_VerticalExtent";
    *draw << "TechDraw_LinkDimension";
    *draw << "TechDraw_NewBalloon";
    *draw << "Separator";
    *draw << "TechDraw_ExportPage";
    *draw << "TechDraw_ExportPageDxf";
    *draw << "Separator";
    *draw << "TechDraw_NewHatch";
    *draw << "TechDraw_NewGeomHatch";
    *draw << "TechDraw_Symbol";
    *draw << "TechDraw_Image";
    *draw << "TechDraw_ToggleFrame";
    *draw << "Separator";
    *draw << "TechDraw_Annotation";
    *draw << "TechDraw_LeaderLine";
    *draw << "TechDraw_RichAnno";
    *draw << "TechDraw_CosmeticVertex";
    *draw << "TechDraw_Midpoints";
    *draw << "TechDraw_Quadrant";
    *draw << "TechDraw_FaceCenterLine";
    *draw << "TechDraw_2LineCenterLine";
    *draw << "TechDraw_2PointCenterLine";
    *draw << "TechDraw_CosmeticEraser";
    *draw << "TechDraw_DecorateLine";
    *draw << "TechDraw_ShowAll";
    *draw << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupToolBars() const
{
    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_NewPageDef";
    *pages << "TechDraw_NewPage";
    *pages << "TechDraw_Redraw";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("TechDraw Views");
    *views << "TechDraw_NewView";
    *views << "TechDraw_NewActiveView";
//    *views << "TechDraw_NewMulti";    //deprecated
    *views << "TechDraw_ProjGroup";
    *views << "TechDraw_NewViewSection";
    *views << "TechDraw_NewViewDetail";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_ArchView";
    *views << "TechDraw_Spreadsheet";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_Clip";
    *clips << "TechDraw_ClipPlus";
    *clips << "TechDraw_ClipMinus";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_NewLengthDimension";
    *dims << "TechDraw_NewDistanceXDimension";
    *dims << "TechDraw_NewDistanceYDimension";
    *dims << "TechDraw_NewRadiusDimension";
    *dims << "TechDraw_NewDiameterDimension";
    *dims << "TechDraw_NewAngleDimension";
    *dims << "TechDraw_NewAngle3PtDimension";
    *dims << "TechDraw_ExtentGrp";
//    *dims << "TechDraw_HorizontalExtent";
//    *dims << "TechDraw_VerticalExtent";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_NewBalloon";
//    *dims << "TechDraw_NewDimension"

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPage";
    *file << "TechDraw_ExportPageDxf";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_NewHatch";
    *decor << "TechDraw_NewGeomHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichAnno";
    *anno << "TechDraw_CosmeticVertexGrp";
    *anno << "TechDraw_CenterLineGrp";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupCommandBars() const
{
    Gui::ToolBarItem* root = new Gui::ToolBarItem;
    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_NewPageDef";
    *pages << "TechDraw_NewPage";
    *pages << "TechDraw_Redraw";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("Views");
    *views << "TechDraw_NewView";
    *views << "TechDraw_NewActiveView";
//    *views << "TechDraw_NewMulti";    //deprecated
    *views << "TechDraw_ProjGroup";
    *views << "TechDraw_NewViewSection";
    *views << "TechDraw_NewViewDetail";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_Spreadsheet";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_Clip";
    *clips << "TechDraw_ClipPlus";
    *clips << "TechDraw_ClipMinus";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_NewLengthDimension";
    *dims << "TechDraw_NewDistanceXDimension";
    *dims << "TechDraw_NewDistanceYDimension";
    *dims << "TechDraw_NewRadiusDimension";
    *dims << "TechDraw_NewDiameterDimension";
    *dims << "TechDraw_NewAngleDimension";
    *dims << "TechDraw_NewAngle3PtDimension";
    *dims << "TechDraw_ExtentGrp";
//    *dims << "TechDraw_HorizontalExtent";
//    *dims << "TechDraw_VerticalExtent";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_NewBalloon";
//    *dims << "TechDraw_NewDimension";

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPage";
    *file << "TechDraw_ExportPageDxf";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_NewHatch";
    *decor << "TechDraw_NewGeomHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichAnno";
    *anno << "TechDraw_CosmeticVertexGrp";
    *anno << "TechDraw_CenterLineGrp";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";

    return root;
}
<commit_msg>TD Workbench.cpp: add submenus<commit_after>/***************************************************************************
 *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *   Copyright (c) 2013 Luke Parry <l.parry@warwick.ac.uk>                 *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <qobject.h>
#endif

#include "Workbench.h"
#include <Gui/MenuManager.h>
#include <Gui/ToolBarManager.h>

using namespace TechDrawGui;

TYPESYSTEM_SOURCE(TechDrawGui::Workbench, Gui::StdWorkbench)

Workbench::Workbench()
{
}

Workbench::~Workbench()
{
}

Gui::MenuItem* Workbench::setupMenuBar() const
{
    Gui::MenuItem* root = StdWorkbench::setupMenuBar();
    Gui::MenuItem* item = root->findItem("&Windows");
    Gui::MenuItem* draw = new Gui::MenuItem;
    root->insertItem(item, draw);

	// dimensions
	Gui::MenuItem* dimensions = new Gui::MenuItem;
	dimensions->setCommand("Dimensions");
	*dimensions << "TechDraw_NewLengthDimension" << "TechDraw_NewDistanceXDimension" << "TechDraw_NewDistanceYDimension"
		<< "TechDraw_NewRadiusDimension" << "TechDraw_NewDiameterDimension" << "TechDraw_NewAngleDimension"
		<< "TechDraw_HorizontalExtent" << "TechDraw_VerticalExtent" << "TechDraw_LinkDimension";

	// annotations
	Gui::MenuItem* annotations = new Gui::MenuItem;
	annotations->setCommand("Annotations");
	*annotations << "TechDraw_Annotation" << "TechDraw_RichAnno" << "TechDraw_NewBalloon";

	// lines
	Gui::MenuItem* lines = new Gui::MenuItem;
	lines->setCommand("Add Lines");
	*lines << "TechDraw_LeaderLine" << "TechDraw_FaceCenterLine"
		<< "TechDraw_2LineCenterLine" << "TechDraw_2PointCenterLine";

	// vertices
	Gui::MenuItem* vertices = new Gui::MenuItem;
	vertices->setCommand("Add Vertices");
	*vertices << "TechDraw_CosmeticVertex" << "TechDraw_Midpoints"
		<< "TechDraw_Quadrant";

	// main menu
	draw->setCommand("TechDraw");
    *draw << "TechDraw_NewPageDef";
    *draw << "TechDraw_NewPage";
    *draw << "TechDraw_Redraw";
    *draw << "Separator";
    *draw << "TechDraw_NewView";
    *draw << "TechDraw_NewActiveView";
    *draw << "TechDraw_ProjGroup";
    *draw << "TechDraw_NewViewSection";
    *draw << "TechDraw_NewViewDetail";
    *draw << "Separator";
    *draw << "TechDraw_DraftView";
    *draw << "TechDraw_ArchView";
    *draw << "TechDraw_Spreadsheet";
    *draw << "Separator";
    *draw << "TechDraw_Clip";
    *draw << "TechDraw_ClipPlus";
    *draw << "TechDraw_ClipMinus";
    *draw << "Separator";
	*draw << dimensions;
    *draw << "Separator";
    *draw << "TechDraw_ExportPage";
    *draw << "TechDraw_ExportPageDxf";
    *draw << "Separator";
    *draw << "TechDraw_NewHatch";
    *draw << "TechDraw_NewGeomHatch";
    *draw << "TechDraw_Symbol";
    *draw << "TechDraw_Image";
    *draw << "TechDraw_ToggleFrame";
    *draw << "Separator";
    *draw << annotations;
	*draw << lines;
    *draw << vertices;
    *draw << "TechDraw_CosmeticEraser";
    *draw << "TechDraw_DecorateLine";
    *draw << "TechDraw_ShowAll";
    *draw << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupToolBars() const
{
    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
    Gui::ToolBarItem* pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_NewPageDef";
    *pages << "TechDraw_NewPage";
    *pages << "TechDraw_Redraw";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("TechDraw Views");
    *views << "TechDraw_NewView";
    *views << "TechDraw_NewActiveView";
//    *views << "TechDraw_NewMulti";    //deprecated
    *views << "TechDraw_ProjGroup";
    *views << "TechDraw_NewViewSection";
    *views << "TechDraw_NewViewDetail";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_ArchView";
    *views << "TechDraw_Spreadsheet";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_Clip";
    *clips << "TechDraw_ClipPlus";
    *clips << "TechDraw_ClipMinus";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_NewLengthDimension";
    *dims << "TechDraw_NewDistanceXDimension";
    *dims << "TechDraw_NewDistanceYDimension";
    *dims << "TechDraw_NewRadiusDimension";
    *dims << "TechDraw_NewDiameterDimension";
    *dims << "TechDraw_NewAngleDimension";
    *dims << "TechDraw_NewAngle3PtDimension";
    *dims << "TechDraw_ExtentGrp";
//    *dims << "TechDraw_HorizontalExtent";
//    *dims << "TechDraw_VerticalExtent";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_NewBalloon";
//    *dims << "TechDraw_NewDimension"

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPage";
    *file << "TechDraw_ExportPageDxf";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_NewHatch";
    *decor << "TechDraw_NewGeomHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichAnno";
    *anno << "TechDraw_CosmeticVertexGrp";
    *anno << "TechDraw_CenterLineGrp";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";
    return root;
}

Gui::ToolBarItem* Workbench::setupCommandBars() const
{
    Gui::ToolBarItem* root = new Gui::ToolBarItem;
    Gui::ToolBarItem *pages = new Gui::ToolBarItem(root);
    pages->setCommand("TechDraw Pages");
    *pages << "TechDraw_NewPageDef";
    *pages << "TechDraw_NewPage";
    *pages << "TechDraw_Redraw";

    Gui::ToolBarItem *views = new Gui::ToolBarItem(root);
    views->setCommand("Views");
    *views << "TechDraw_NewView";
    *views << "TechDraw_NewActiveView";
//    *views << "TechDraw_NewMulti";    //deprecated
    *views << "TechDraw_ProjGroup";
    *views << "TechDraw_NewViewSection";
    *views << "TechDraw_NewViewDetail";
    *views << "TechDraw_DraftView";
    *views << "TechDraw_Spreadsheet";

    Gui::ToolBarItem *clips = new Gui::ToolBarItem(root);
    clips->setCommand("TechDraw Clips");
    *clips << "TechDraw_Clip";
    *clips << "TechDraw_ClipPlus";
    *clips << "TechDraw_ClipMinus";

    Gui::ToolBarItem *dims = new Gui::ToolBarItem(root);
    dims->setCommand("TechDraw Dimensions");
    *dims << "TechDraw_NewLengthDimension";
    *dims << "TechDraw_NewDistanceXDimension";
    *dims << "TechDraw_NewDistanceYDimension";
    *dims << "TechDraw_NewRadiusDimension";
    *dims << "TechDraw_NewDiameterDimension";
    *dims << "TechDraw_NewAngleDimension";
    *dims << "TechDraw_NewAngle3PtDimension";
    *dims << "TechDraw_ExtentGrp";
//    *dims << "TechDraw_HorizontalExtent";
//    *dims << "TechDraw_VerticalExtent";
    *dims << "TechDraw_LinkDimension";
    *dims << "TechDraw_NewBalloon";
//    *dims << "TechDraw_NewDimension";

    Gui::ToolBarItem *file = new Gui::ToolBarItem(root);
    file->setCommand("TechDraw File Access");
    *file << "TechDraw_ExportPage";
    *file << "TechDraw_ExportPageDxf";

    Gui::ToolBarItem *decor = new Gui::ToolBarItem(root);
    decor->setCommand("TechDraw Decoration");
    *decor << "TechDraw_NewHatch";
    *decor << "TechDraw_NewGeomHatch";
    *decor << "TechDraw_Symbol";
    *decor << "TechDraw_Image";
    *decor << "TechDraw_ToggleFrame";

    Gui::ToolBarItem *anno = new Gui::ToolBarItem(root);
    anno->setCommand("TechDraw Annotation");
    *anno << "TechDraw_Annotation";
    *anno << "TechDraw_LeaderLine";
    *anno << "TechDraw_RichAnno";
    *anno << "TechDraw_CosmeticVertexGrp";
    *anno << "TechDraw_CenterLineGrp";
//    *anno << "TechDraw_FaceCenterLine";
//    *anno << "TechDraw_2LineCenterLine";
//    *anno << "TechDraw_2PointCenterLine";
    *anno << "TechDraw_CosmeticEraser";
    *anno << "TechDraw_DecorateLine";
    *anno << "TechDraw_ShowAll";
    *anno << "TechDraw_WeldSymbol";

    return root;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <tr1/memory>
#include <queue>

#include <boost/multi_array.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "array2d.h"
#include "base_measures.h"
#include "monotonic_pseg.h"
#include "conditional_pseg.h"
#include "trule.h"
#include "tdict.h"
#include "stringlib.h"
#include "filelib.h"
#include "dict.h"
#include "sampler.h"
#include "ccrp_nt.h"
#include "corpus.h"
#include "ngram_base.h"

using namespace std;
using namespace tr1;
namespace po = boost::program_options;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("samples,s",po::value<unsigned>()->default_value(1000),"Number of samples")
        ("input,i",po::value<string>(),"Read parallel data from")
        ("random_seed,S",po::value<uint32_t>(), "Random seed");
  po::options_description clo("Command line options");
  clo.add_options()
        ("config", po::value<string>(), "Configuration file")
        ("help,h", "Print this help message and exit");
  po::options_description dconfig_options, dcmdline_options;
  dconfig_options.add(opts);
  dcmdline_options.add(opts).add(clo);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  if (conf->count("config")) {
    ifstream config((*conf)["config"].as<string>().c_str());
    po::store(po::parse_config_file(config, dconfig_options), *conf);
  }
  po::notify(*conf);

  if (conf->count("help") || (conf->count("input") == 0)) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
}

shared_ptr<MT19937> prng;

struct LexicalAlignment {
  unsigned char src_index;
  bool is_transliteration;
  vector<pair<short, short> > derivation;
};

struct AlignedSentencePair {
  vector<WordID> src;
  vector<WordID> trg;
  vector<LexicalAlignment> a;
  Array2D<short> posterior;
};

struct HierarchicalUnigramBase {
  explicit HierarchicalUnigramBase(const unsigned vocab_e_size) : r(5,5), u0(1.0 / vocab_e_size) {}

  // return p0 of rule.e_
  prob_t operator()(const TRule& rule) const {
    prob_t p = prob_t::One();
    prob_t q;
    for (unsigned i = 0; i < rule.e_.size(); ++i) {
      q.logeq(r.logprob(rule.e_[i], log(u0)));
      p *= q;
    }
    q.logeq(r.logprob(TD::Convert("</s>"), log(u0)));
    p *= q;
    return p;
  }

  void Increment(const TRule& rule) {
    for (unsigned i = 0; i < rule.e_.size(); ++i)
      r.increment(rule.e_[i]);
    r.increment(TD::Convert("</s>"));
  }

  void Decrement(const TRule& rule) {
    for (unsigned i = 0; i < rule.e_.size(); ++i)
      r.decrement(rule.e_[i]);
    r.decrement(TD::Convert("</s>"));
  }

  CCRP_NoTable<WordID> r;
  prob_t u0;
};

struct HierarchicalWordBase {
  explicit HierarchicalWordBase(const unsigned vocab_e_size) :
      base(prob_t::One()), r(15,15), u0(-log(vocab_e_size)) {}

  void ResampleHyperparameters(MT19937* rng) {
    r.resample_hyperparameters(rng);
  }

  inline double logp0(const vector<WordID>& s) const {
    return s.size() * u0;
  }

  // return p0 of rule.e_
  prob_t operator()(const TRule& rule) const {
    prob_t p; p.logeq(r.logprob(rule.e_, logp0(rule.e_)));
    return p;
  }

  void Increment(const TRule& rule) {
    if (r.increment(rule.e_)) {
      prob_t p; p.logeq(logp0(rule.e_));
      base *= p;
    }
  }

  void Decrement(const TRule& rule) {
    if (r.decrement(rule.e_)) {
      prob_t p; p.logeq(logp0(rule.e_));
      base /= p;
    }
  }

  prob_t Likelihood() const {
    prob_t p; p.logeq(r.log_crp_prob());
    p *= base;
    return p;
  }

  void Summary() const {
    cerr << "NUMBER OF CUSTOMERS: " << r.num_customers() << endl;
    for (CCRP_NoTable<vector<WordID> >::const_iterator it = r.begin(); it != r.end(); ++it)
      cerr << "   " << it->second << '\t' << TD::GetString(it->first) << endl;
  }

  prob_t base;
  CCRP_NoTable<vector<WordID> > r;
  const double u0;
};

struct BasicLexicalAlignment {
  explicit BasicLexicalAlignment(const vector<vector<WordID> >& lets,
                                 const unsigned letters_e,
                                 vector<AlignedSentencePair>* corp) :
      letters(lets),
      corpus(*corp),
      //up0("en.chars.1gram", letters_e),
      //up0("en.words.1gram"),
      up0(letters_e),
      //up0("en.chars.2gram"),
      tmodel(up0) {
  }

  void InstantiateRule(const WordID src,
                       const WordID trg,
                       TRule* rule) const {
    static const WordID kX = TD::Convert("X") * -1;
    rule->lhs_ = kX;
    rule->e_ = letters[trg];
    rule->f_ = letters[src];
  }

  void InitializeRandom() {
    const WordID kNULL = TD::Convert("NULL");
    cerr << "Initializing with random alignments ...\n";
    for (unsigned i = 0; i < corpus.size(); ++i) {
      AlignedSentencePair& asp = corpus[i];
      asp.a.resize(asp.trg.size());
      for (unsigned j = 0; j < asp.trg.size(); ++j) {
        const unsigned char a_j = prng->next() * (1 + asp.src.size());
        const WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
        TRule r;
        InstantiateRule(f_a_j, asp.trg[j], &r);
        asp.a[j].is_transliteration = false;
        asp.a[j].src_index = a_j;
        if (tmodel.IncrementRule(r))
          up0.Increment(r);
      }
    }
    cerr << "  LLH = " << Likelihood() << endl;
  }

  prob_t Likelihood() const {
    prob_t p = tmodel.Likelihood();
    p *= up0.Likelihood();
    return p;
  }

  void ResampleHyperparemeters() {
    cerr << "  LLH_prev = " << Likelihood() << flush;
    tmodel.ResampleHyperparameters(&*prng);
    up0.ResampleHyperparameters(&*prng);
    cerr << "\tLLH_post = " << Likelihood() << endl;
  }

  void ResampleCorpus();

  const vector<vector<WordID> >& letters; // spelling dictionary
  vector<AlignedSentencePair>& corpus;
  //PhraseConditionalUninformativeBase up0;
  //PhraseConditionalUninformativeUnigramBase up0;
  //UnigramWordBase up0;
  //HierarchicalUnigramBase up0;
  HierarchicalWordBase up0;
  //CompletelyUniformBase up0;
  //FixedNgramBase up0;
  //ConditionalTranslationModel<PhraseConditionalUninformativeBase> tmodel;
  //ConditionalTranslationModel<PhraseConditionalUninformativeUnigramBase> tmodel;
  //ConditionalTranslationModel<UnigramWordBase> tmodel;
  //ConditionalTranslationModel<HierarchicalUnigramBase> tmodel;
  ConditionalTranslationModel<HierarchicalWordBase> tmodel;
  //ConditionalTranslationModel<FixedNgramBase> tmodel;
  //ConditionalTranslationModel<CompletelyUniformBase> tmodel;
};

void BasicLexicalAlignment::ResampleCorpus() {
  static const WordID kNULL = TD::Convert("NULL");
  for (unsigned i = 0; i < corpus.size(); ++i) {
    AlignedSentencePair& asp = corpus[i];
    SampleSet<prob_t> ss; ss.resize(asp.src.size() + 1);
    for (unsigned j = 0; j < asp.trg.size(); ++j) {
      TRule r;
      unsigned char& a_j = asp.a[j].src_index;
      WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
      InstantiateRule(f_a_j, asp.trg[j], &r);
      if (tmodel.DecrementRule(r))
        up0.Decrement(r);

      for (unsigned prop_a_j = 0; prop_a_j <= asp.src.size(); ++prop_a_j) {
        const WordID prop_f = (prop_a_j ? asp.src[prop_a_j - 1] : kNULL);
        InstantiateRule(prop_f, asp.trg[j], &r);
        ss[prop_a_j] = tmodel.RuleProbability(r);
      }
      a_j = prng->SelectSample(ss);
      f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
      InstantiateRule(f_a_j, asp.trg[j], &r);
      if (tmodel.IncrementRule(r))
        up0.Increment(r);
    }
  }
  cerr << "  LLH = " << tmodel.Likelihood() << endl;
}

void ExtractLetters(const set<WordID>& v, vector<vector<WordID> >* l, set<WordID>* letset = NULL) {
  for (set<WordID>::const_iterator it = v.begin(); it != v.end(); ++it) {
    vector<WordID>& letters = (*l)[*it];
    if (letters.size()) continue;   // if e and f have the same word

    const string& w = TD::Convert(*it);

    size_t cur = 0;
    while (cur < w.size()) {
      const size_t len = UTF8Len(w[cur]);
      letters.push_back(TD::Convert(w.substr(cur, len)));
      if (letset) letset->insert(letters.back());
      cur += len;
    }
  }
}

void Debug(const AlignedSentencePair& asp) {
  cerr << TD::GetString(asp.src) << endl << TD::GetString(asp.trg) << endl;
  Array2D<bool> a(asp.src.size(), asp.trg.size());
  for (unsigned j = 0; j < asp.trg.size(); ++j)
    if (asp.a[j].src_index) a(asp.a[j].src_index - 1, j) = true;
  cerr << a << endl;
}

void AddSample(AlignedSentencePair* asp) {
  for (unsigned j = 0; j < asp->trg.size(); ++j)
    asp->posterior(asp->a[j].src_index, j)++;
}

void WriteAlignments(const AlignedSentencePair& asp) {
  bool first = true;
  for (unsigned j = 0; j < asp.trg.size(); ++j) {
    int src_index = -1;
    int mc = -1;
    for (unsigned i = 0; i <= asp.src.size(); ++i) {
      if (asp.posterior(i, j) > mc) {
        mc = asp.posterior(i, j);
        src_index = i;
      }
    }

    if (src_index) {
      if (first) first = false; else cout << ' ';
      cout << (src_index - 1) << '-' << j;
    }
  }
  cout << endl;
}

int main(int argc, char** argv) {
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);

  if (conf.count("random_seed"))
    prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
  else
    prng.reset(new MT19937);
//  MT19937& rng = *prng;

  vector<vector<int> > corpuse, corpusf;
  set<int> vocabe, vocabf;
  corpus::ReadParallelCorpus(conf["input"].as<string>(), &corpusf, &corpuse, &vocabf, &vocabe);
  cerr << "f-Corpus size: " << corpusf.size() << " sentences\n";
  cerr << "f-Vocabulary size: " << vocabf.size() << " types\n";
  cerr << "f-Corpus size: " << corpuse.size() << " sentences\n";
  cerr << "f-Vocabulary size: " << vocabe.size() << " types\n";
  assert(corpusf.size() == corpuse.size());

  vector<AlignedSentencePair> corpus(corpuse.size());
  for (unsigned i = 0; i < corpuse.size(); ++i) {
    corpus[i].src.swap(corpusf[i]);
    corpus[i].trg.swap(corpuse[i]);
    corpus[i].posterior.resize(corpus[i].src.size() + 1, corpus[i].trg.size());
  }
  corpusf.clear(); corpuse.clear();

  vocabf.insert(TD::Convert("NULL"));
  vector<vector<WordID> > letters(TD::NumWords());
  set<WordID> letset;
  ExtractLetters(vocabe, &letters, &letset);
  ExtractLetters(vocabf, &letters, NULL);
  letters[TD::Convert("NULL")].clear();

  BasicLexicalAlignment x(letters, letset.size(), &corpus);
  x.InitializeRandom();
  const unsigned samples = conf["samples"].as<unsigned>();
  for (int i = 0; i < samples; ++i) {
    for (int j = 431; j < 433; ++j) Debug(corpus[j]);
    cerr << i << "\t" << x.tmodel.r.size() << "\t";
    if (i % 10 == 0) x.ResampleHyperparemeters();
    x.ResampleCorpus();
    if (i > (samples / 5) && (i % 10 == 9)) for (int j = 0; j < corpus.size(); ++j) AddSample(&corpus[j]);
  }
  for (unsigned i = 0; i < corpus.size(); ++i)
    WriteAlignments(corpus[i]);
  //ModelAndData posterior(x, &corpus, vocabe, vocabf);
  x.tmodel.Summary();
  x.up0.Summary();

  //posterior.Sample();

  return 0;
}
<commit_msg>remove broken prior, add logging<commit_after>#include <iostream>
#include <tr1/memory>
#include <queue>

#include <boost/multi_array.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "array2d.h"
#include "base_measures.h"
#include "monotonic_pseg.h"
#include "conditional_pseg.h"
#include "trule.h"
#include "tdict.h"
#include "stringlib.h"
#include "filelib.h"
#include "dict.h"
#include "sampler.h"
#include "ccrp_nt.h"
#include "corpus.h"
#include "ngram_base.h"

using namespace std;
using namespace tr1;
namespace po = boost::program_options;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("samples,s",po::value<unsigned>()->default_value(1000),"Number of samples")
        ("input,i",po::value<string>(),"Read parallel data from")
        ("random_seed,S",po::value<uint32_t>(), "Random seed");
  po::options_description clo("Command line options");
  clo.add_options()
        ("config", po::value<string>(), "Configuration file")
        ("help,h", "Print this help message and exit");
  po::options_description dconfig_options, dcmdline_options;
  dconfig_options.add(opts);
  dcmdline_options.add(opts).add(clo);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  if (conf->count("config")) {
    ifstream config((*conf)["config"].as<string>().c_str());
    po::store(po::parse_config_file(config, dconfig_options), *conf);
  }
  po::notify(*conf);

  if (conf->count("help") || (conf->count("input") == 0)) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
}

shared_ptr<MT19937> prng;

struct LexicalAlignment {
  unsigned char src_index;
  bool is_transliteration;
  vector<pair<short, short> > derivation;
};

struct AlignedSentencePair {
  vector<WordID> src;
  vector<WordID> trg;
  vector<LexicalAlignment> a;
  Array2D<short> posterior;
};

struct HierarchicalWordBase {
  explicit HierarchicalWordBase(const unsigned vocab_e_size) :
      base(prob_t::One()), r(25,25,10), u0(-log(vocab_e_size)) {}

  void ResampleHyperparameters(MT19937* rng) {
    r.resample_hyperparameters(rng);
  }

  inline double logp0(const vector<WordID>& s) const {
    return s.size() * u0;
  }

  // return p0 of rule.e_
  prob_t operator()(const TRule& rule) const {
    prob_t p; p.logeq(r.logprob(rule.e_, logp0(rule.e_)));
    return p;
  }

  void Increment(const TRule& rule) {
    if (r.increment(rule.e_)) {
      prob_t p; p.logeq(logp0(rule.e_));
      base *= p;
    }
  }

  void Decrement(const TRule& rule) {
    if (r.decrement(rule.e_)) {
      prob_t p; p.logeq(logp0(rule.e_));
      base /= p;
    }
  }

  prob_t Likelihood() const {
    prob_t p; p.logeq(r.log_crp_prob());
    p *= base;
    return p;
  }

  void Summary() const {
    cerr << "NUMBER OF CUSTOMERS: " << r.num_customers() << "  (\\alpha=" << r.concentration() << ')' << endl;
    for (CCRP_NoTable<vector<WordID> >::const_iterator it = r.begin(); it != r.end(); ++it)
      cerr << "   " << it->second << '\t' << TD::GetString(it->first) << endl;
  }

  prob_t base;
  CCRP_NoTable<vector<WordID> > r;
  const double u0;
};

struct BasicLexicalAlignment {
  explicit BasicLexicalAlignment(const vector<vector<WordID> >& lets,
                                 const unsigned letters_e,
                                 vector<AlignedSentencePair>* corp) :
      letters(lets),
      corpus(*corp),
      //up0("en.chars.1gram", letters_e),
      //up0("en.words.1gram"),
      up0(letters_e),
      //up0("en.chars.2gram"),
      tmodel(up0) {
  }

  void InstantiateRule(const WordID src,
                       const WordID trg,
                       TRule* rule) const {
    static const WordID kX = TD::Convert("X") * -1;
    rule->lhs_ = kX;
    rule->e_ = letters[trg];
    rule->f_ = letters[src];
  }

  void InitializeRandom() {
    const WordID kNULL = TD::Convert("NULL");
    cerr << "Initializing with random alignments ...\n";
    for (unsigned i = 0; i < corpus.size(); ++i) {
      AlignedSentencePair& asp = corpus[i];
      asp.a.resize(asp.trg.size());
      for (unsigned j = 0; j < asp.trg.size(); ++j) {
        const unsigned char a_j = prng->next() * (1 + asp.src.size());
        const WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
        TRule r;
        InstantiateRule(f_a_j, asp.trg[j], &r);
        asp.a[j].is_transliteration = false;
        asp.a[j].src_index = a_j;
        if (tmodel.IncrementRule(r))
          up0.Increment(r);
      }
    }
    cerr << "  LLH = " << Likelihood() << endl;
  }

  prob_t Likelihood() const {
    prob_t p = tmodel.Likelihood();
    p *= up0.Likelihood();
    return p;
  }

  void ResampleHyperparemeters() {
    cerr << "  LLH_prev = " << Likelihood() << flush;
    tmodel.ResampleHyperparameters(&*prng);
    up0.ResampleHyperparameters(&*prng);
    cerr << "\tLLH_post = " << Likelihood() << endl;
  }

  void ResampleCorpus();

  const vector<vector<WordID> >& letters; // spelling dictionary
  vector<AlignedSentencePair>& corpus;
  //PhraseConditionalUninformativeBase up0;
  //PhraseConditionalUninformativeUnigramBase up0;
  //UnigramWordBase up0;
  //HierarchicalUnigramBase up0;
  HierarchicalWordBase up0;
  //CompletelyUniformBase up0;
  //FixedNgramBase up0;
  //ConditionalTranslationModel<PhraseConditionalUninformativeBase> tmodel;
  //ConditionalTranslationModel<PhraseConditionalUninformativeUnigramBase> tmodel;
  //ConditionalTranslationModel<UnigramWordBase> tmodel;
  //ConditionalTranslationModel<HierarchicalUnigramBase> tmodel;
  ConditionalTranslationModel<HierarchicalWordBase> tmodel;
  //ConditionalTranslationModel<FixedNgramBase> tmodel;
  //ConditionalTranslationModel<CompletelyUniformBase> tmodel;
};

void BasicLexicalAlignment::ResampleCorpus() {
  static const WordID kNULL = TD::Convert("NULL");
  for (unsigned i = 0; i < corpus.size(); ++i) {
    AlignedSentencePair& asp = corpus[i];
    SampleSet<prob_t> ss; ss.resize(asp.src.size() + 1);
    for (unsigned j = 0; j < asp.trg.size(); ++j) {
      TRule r;
      unsigned char& a_j = asp.a[j].src_index;
      WordID f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
      InstantiateRule(f_a_j, asp.trg[j], &r);
      if (tmodel.DecrementRule(r))
        up0.Decrement(r);

      for (unsigned prop_a_j = 0; prop_a_j <= asp.src.size(); ++prop_a_j) {
        const WordID prop_f = (prop_a_j ? asp.src[prop_a_j - 1] : kNULL);
        InstantiateRule(prop_f, asp.trg[j], &r);
        ss[prop_a_j] = tmodel.RuleProbability(r);
      }
      a_j = prng->SelectSample(ss);
      f_a_j = (a_j ? asp.src[a_j - 1] : kNULL);
      InstantiateRule(f_a_j, asp.trg[j], &r);
      if (tmodel.IncrementRule(r))
        up0.Increment(r);
    }
  }
  cerr << "  LLH = " << tmodel.Likelihood() << endl;
}

void ExtractLetters(const set<WordID>& v, vector<vector<WordID> >* l, set<WordID>* letset = NULL) {
  for (set<WordID>::const_iterator it = v.begin(); it != v.end(); ++it) {
    vector<WordID>& letters = (*l)[*it];
    if (letters.size()) continue;   // if e and f have the same word

    const string& w = TD::Convert(*it);

    size_t cur = 0;
    while (cur < w.size()) {
      const size_t len = UTF8Len(w[cur]);
      letters.push_back(TD::Convert(w.substr(cur, len)));
      if (letset) letset->insert(letters.back());
      cur += len;
    }
  }
}

void Debug(const AlignedSentencePair& asp) {
  cerr << TD::GetString(asp.src) << endl << TD::GetString(asp.trg) << endl;
  Array2D<bool> a(asp.src.size(), asp.trg.size());
  for (unsigned j = 0; j < asp.trg.size(); ++j)
    if (asp.a[j].src_index) a(asp.a[j].src_index - 1, j) = true;
  cerr << a << endl;
}

void AddSample(AlignedSentencePair* asp) {
  for (unsigned j = 0; j < asp->trg.size(); ++j)
    asp->posterior(asp->a[j].src_index, j)++;
}

void WriteAlignments(const AlignedSentencePair& asp) {
  bool first = true;
  for (unsigned j = 0; j < asp.trg.size(); ++j) {
    int src_index = -1;
    int mc = -1;
    for (unsigned i = 0; i <= asp.src.size(); ++i) {
      if (asp.posterior(i, j) > mc) {
        mc = asp.posterior(i, j);
        src_index = i;
      }
    }

    if (src_index) {
      if (first) first = false; else cout << ' ';
      cout << (src_index - 1) << '-' << j;
    }
  }
  cout << endl;
}

int main(int argc, char** argv) {
  po::variables_map conf;
  InitCommandLine(argc, argv, &conf);

  if (conf.count("random_seed"))
    prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
  else
    prng.reset(new MT19937);
//  MT19937& rng = *prng;

  vector<vector<int> > corpuse, corpusf;
  set<int> vocabe, vocabf;
  corpus::ReadParallelCorpus(conf["input"].as<string>(), &corpusf, &corpuse, &vocabf, &vocabe);
  cerr << "f-Corpus size: " << corpusf.size() << " sentences\n";
  cerr << "f-Vocabulary size: " << vocabf.size() << " types\n";
  cerr << "f-Corpus size: " << corpuse.size() << " sentences\n";
  cerr << "f-Vocabulary size: " << vocabe.size() << " types\n";
  assert(corpusf.size() == corpuse.size());

  vector<AlignedSentencePair> corpus(corpuse.size());
  for (unsigned i = 0; i < corpuse.size(); ++i) {
    corpus[i].src.swap(corpusf[i]);
    corpus[i].trg.swap(corpuse[i]);
    corpus[i].posterior.resize(corpus[i].src.size() + 1, corpus[i].trg.size());
  }
  corpusf.clear(); corpuse.clear();

  vocabf.insert(TD::Convert("NULL"));
  vector<vector<WordID> > letters(TD::NumWords());
  set<WordID> letset;
  ExtractLetters(vocabe, &letters, &letset);
  ExtractLetters(vocabf, &letters, NULL);
  letters[TD::Convert("NULL")].clear();

  BasicLexicalAlignment x(letters, letset.size(), &corpus);
  x.InitializeRandom();
  const unsigned samples = conf["samples"].as<unsigned>();
  for (int i = 0; i < samples; ++i) {
    for (int j = 431; j < 433; ++j) Debug(corpus[j]);
    cerr << i << "\t" << x.tmodel.r.size() << "\t";
    if (i % 10 == 0) x.ResampleHyperparemeters();
    x.ResampleCorpus();
    if (i > (samples / 5) && (i % 10 == 9)) for (int j = 0; j < corpus.size(); ++j) AddSample(&corpus[j]);
  }
  for (unsigned i = 0; i < corpus.size(); ++i)
    WriteAlignments(corpus[i]);
  //ModelAndData posterior(x, &corpus, vocabe, vocabf);
  x.tmodel.Summary();
  x.up0.Summary();

  //posterior.Sample();

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/tools/fetch/http_session.h"
#include "net/tools/fetch/http_server_response_info.h"

HttpSession::HttpSession(const std::string& ip, int port)
    : ALLOW_THIS_IN_INITIALIZER_LIST(
          socket_(HttpListenSocket::Listen(ip, port, this))) {
}

HttpSession::~HttpSession() {
}

void HttpSession::OnRequest(HttpListenSocket* connection,
                            HttpServerRequestInfo* info) {
  // TODO(mbelshe):  Make this function more interesting.

  // Generate a 10KB sequence of data.
  static std::string data;
  if (data.length() == 0) {
    while (data.length() < (10 * 1024))
      data += 'a' + (rand() % 26);
  }

  HttpServerResponseInfo response_info;
  response_info.protocol = "HTTP/1.1";
  response_info.status = 200;
  response_info.content_type = "text/plain";
  response_info.content_length = data.length();

  connection->Respond(&response_info, data);
}
<commit_msg>Fix build.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/tools/fetch/http_session.h"
#include "net/tools/fetch/http_server_response_info.h"

HttpSession::HttpSession(const std::string& ip, int port)
    : ALLOW_THIS_IN_INITIALIZER_LIST(
          socket_(HttpListenSocket::Listen(ip, port, this))) {
}

HttpSession::~HttpSession() {
}

void HttpSession::OnRequest(HttpListenSocket* connection,
                            HttpServerRequestInfo* info) {
  // TODO(mbelshe):  Make this function more interesting.

  // Generate a 10KB sequence of data.
  CR_DEFINE_STATIC_LOCAL(std::string, data, ());
  if (data.length() == 0) {
    while (data.length() < (10 * 1024))
      data += 'a' + (rand() % 26);
  }

  HttpServerResponseInfo response_info;
  response_info.protocol = "HTTP/1.1";
  response_info.status = 200;
  response_info.content_type = "text/plain";
  response_info.content_length = data.length();

  connection->Respond(&response_info, data);
}
<|endoftext|>


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

#include "gmxtrajectoryreader.h"
#include <cstdlib>
#include <gromacs/utility/programcontext.h>
#include <iostream>
#include <votca/csg/topology.h>

namespace votca {
namespace csg {

bool GMXTrajectoryReader::Open(const std::string &file) {
  _filename = file;
  return true;
}

void GMXTrajectoryReader::Close() { close_trx(_gmx_status); }

bool GMXTrajectoryReader::FirstFrame(Topology &conf) {
  gmx_output_env_t *oenv;
  output_env_init(&oenv, gmx::getProgramContext(), time_ps, FALSE, exvgNONE, 0);
  if (!read_first_frame(oenv, &_gmx_status, (char *)_filename.c_str(),
                        &_gmx_frame, TRX_READ_X | TRX_READ_V | TRX_READ_F)) {
    throw std::runtime_error(std::string("cannot open ") + _filename);
  }
  output_env_done(oenv);

  Eigen::Matrix3d m;
  for (Index i = 0; i < 3; i++) {
    for (Index j = 0; j < 3; j++) {
      m(i, j) = _gmx_frame.box[j][i];
    }
  }
  conf.setBox(m);
  conf.setTime(_gmx_frame.time);
  conf.setStep(_gmx_frame.step);
  std::cout << std::endl;

  if (_gmx_frame.natoms != (Index)conf.Beads().size()) {
    throw std::runtime_error(
        "number of beads in trajectory do not match topology");
  }

  // conf.HasPos(true);
  // conf.HasF(_gmx_frame.bF);

  for (Index i = 0; i < _gmx_frame.natoms; i++) {
    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],
                         _gmx_frame.x[i][ZZ]};
    conf.getBead(i)->setPos(r);
    if (_gmx_frame.bF) {
      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],
                           _gmx_frame.f[i][ZZ]};
      conf.getBead(i)->setF(f);
    }
    if (_gmx_frame.bV) {
      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],
                           _gmx_frame.v[i][ZZ]};
      conf.getBead(i)->setVel(v);
    }
  }
  return true;
}

bool GMXTrajectoryReader::NextFrame(Topology &conf) {
  gmx_output_env_t *oenv;
  output_env_init(&oenv, gmx::getProgramContext(), time_ps, FALSE, exvgNONE, 0);
  if (!read_next_frame(oenv, _gmx_status, &_gmx_frame)) {
    return false;
  }
  output_env_done(oenv);

  Eigen::Matrix3d m;
  for (Index i = 0; i < 3; i++) {
    for (Index j = 0; j < 3; j++) {
      m(i, j) = _gmx_frame.box[j][i];
    }
  }
  conf.setTime(_gmx_frame.time);
  conf.setStep(_gmx_frame.step);
  conf.setBox(m);

  // conf.HasF(_gmx_frame.bF);

  for (Index i = 0; i < _gmx_frame.natoms; i++) {
    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],
                         _gmx_frame.x[i][ZZ]};
    conf.getBead(i)->setPos(r);
    if (_gmx_frame.bF) {
      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],
                           _gmx_frame.f[i][ZZ]};
      conf.getBead(i)->setF(f);
    }
    if (_gmx_frame.bV) {
      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],
                           _gmx_frame.v[i][ZZ]};
      conf.getBead(i)->setVel(v);
    }
  }
  return true;
}

}  // namespace csg
}  // namespace votca
<commit_msg>gmxtrajectoryreader: fix compile with gmx-2021<commit_after>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "gmxtrajectoryreader.h"
#include <cstdlib>
#include <gromacs/utility/programcontext.h>
#include <iostream>
#include <votca/csg/topology.h>

namespace votca {
namespace csg {

bool GMXTrajectoryReader::Open(const std::string &file) {
  _filename = file;
  return true;
}

void GMXTrajectoryReader::Close() { close_trx(_gmx_status); }

bool GMXTrajectoryReader::FirstFrame(Topology &conf) {
  gmx_output_env_t *oenv;
#if GMX_VERSION >= 20210000
  gmx::TimeUnit timeunit = gmx::TimeUnit::Picoseconds;
  XvgFormat xvg = XvgFormat::None;
#else
  time_unit_t timeunit = time_ps;
  xvg_format_t xvg = exvgNONE;
#endif
  output_env_init(&oenv, gmx::getProgramContext(), timeunit, FALSE, xvg, 0);
  if (!read_first_frame(oenv, &_gmx_status, (char *)_filename.c_str(),
                        &_gmx_frame, TRX_READ_X | TRX_READ_V | TRX_READ_F)) {
    throw std::runtime_error(std::string("cannot open ") + _filename);
  }
  output_env_done(oenv);

  Eigen::Matrix3d m;
  for (Index i = 0; i < 3; i++) {
    for (Index j = 0; j < 3; j++) {
      m(i, j) = _gmx_frame.box[j][i];
    }
  }
  conf.setBox(m);
  conf.setTime(_gmx_frame.time);
  conf.setStep(_gmx_frame.step);
  std::cout << std::endl;

  if (_gmx_frame.natoms != (Index)conf.Beads().size()) {
    throw std::runtime_error(
        "number of beads in trajectory do not match topology");
  }

  // conf.HasPos(true);
  // conf.HasF(_gmx_frame.bF);

  for (Index i = 0; i < _gmx_frame.natoms; i++) {
    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],
                         _gmx_frame.x[i][ZZ]};
    conf.getBead(i)->setPos(r);
    if (_gmx_frame.bF) {
      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],
                           _gmx_frame.f[i][ZZ]};
      conf.getBead(i)->setF(f);
    }
    if (_gmx_frame.bV) {
      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],
                           _gmx_frame.v[i][ZZ]};
      conf.getBead(i)->setVel(v);
    }
  }
  return true;
}

bool GMXTrajectoryReader::NextFrame(Topology &conf) {
  gmx_output_env_t *oenv;
#if GMX_VERSION >= 20210000
  gmx::TimeUnit timeunit = gmx::TimeUnit::Picoseconds;
  XvgFormat xvg = XvgFormat::None;
#else
  time_unit_t timeunit = time_ps;
  xvg_format_t xvg = exvgNONE;
#endif
  output_env_init(&oenv, gmx::getProgramContext(), timeunit, FALSE, xvg, 0);
  if (!read_next_frame(oenv, _gmx_status, &_gmx_frame)) {
    return false;
  }
  output_env_done(oenv);

  Eigen::Matrix3d m;
  for (Index i = 0; i < 3; i++) {
    for (Index j = 0; j < 3; j++) {
      m(i, j) = _gmx_frame.box[j][i];
    }
  }
  conf.setTime(_gmx_frame.time);
  conf.setStep(_gmx_frame.step);
  conf.setBox(m);

  // conf.HasF(_gmx_frame.bF);

  for (Index i = 0; i < _gmx_frame.natoms; i++) {
    Eigen::Vector3d r = {_gmx_frame.x[i][XX], _gmx_frame.x[i][YY],
                         _gmx_frame.x[i][ZZ]};
    conf.getBead(i)->setPos(r);
    if (_gmx_frame.bF) {
      Eigen::Vector3d f = {_gmx_frame.f[i][XX], _gmx_frame.f[i][YY],
                           _gmx_frame.f[i][ZZ]};
      conf.getBead(i)->setF(f);
    }
    if (_gmx_frame.bV) {
      Eigen::Vector3d v = {_gmx_frame.v[i][XX], _gmx_frame.v[i][YY],
                           _gmx_frame.v[i][ZZ]};
      conf.getBead(i)->setVel(v);
    }
  }
  return true;
}

}  // namespace csg
}  // namespace votca
<|endoftext|>


<commit_before>#ifndef __BOO_MAP__
#define __BOO_MAP__

#include "BooPHF.hpp"

#include "cereal/types/vector.hpp"
#include "cereal/types/utility.hpp"
#include "cereal/archives/binary.hpp"

#include <fstream>
#include <vector>
#include <iterator>
#include <type_traits>

#include <sys/stat.h>

// adapted from :
// http://stackoverflow.com/questions/34875315/implementation-my-own-list-and-iterator-stl-c
template <typename Iter>
class KeyIterator {
public:
    typedef KeyIterator<Iter> self_type;
    typedef typename std::iterator_traits<Iter>::value_type::first_type value_type;
    typedef value_type& reference;
    typedef value_type* pointer;
    typedef std::forward_iterator_tag iterator_category;
    typedef int64_t difference_type;

    KeyIterator(Iter first) : curr_(first) {}
    KeyIterator operator++() { KeyIterator i = *this; curr_++; return i; }
    KeyIterator operator++(int) { ++curr_; return *this; }
    reference operator*() { return curr_->first; }
    pointer operator->() { return &(curr_->first); }
    bool operator==(const self_type& rhs) { return curr_ == rhs.curr_; }
    bool operator!=(const self_type& rhs) { return curr_ != rhs.curr_; }
    bool operator<(const self_type& rhs) { return curr_ < rhs.curr_; }
    bool operator<=(const self_type& rhs) { return curr_ <= rhs.curr_; }

private:
    Iter begin_;
    Iter curr_;
};

template <typename KeyT, typename ValueT>
class BooMap {
public:
    using HasherT = boomphf::SingleHashFunctor<KeyT>;
    using BooPHFT = boomphf::mphf<KeyT, HasherT>;
    using IteratorT = typename std::vector<std::pair<KeyT, ValueT>>::iterator;

    BooMap() : built_(false) {}
    void add(KeyT&& k, ValueT&& v) {
        data_.emplace_back(k, v);
    }

    bool build(int nthreads=1) {
        size_t numElem = data_.size();
        KeyIterator<decltype(data_.begin())> kb(data_.begin());
        KeyIterator<decltype(data_.begin())> ke(data_.end());
        auto keyIt = boomphf::range(kb, ke);
        BooPHFT* ph = new BooPHFT(numElem, keyIt, nthreads);
        boophf_.reset(ph);
        std::cerr << "reordering keys and values to coincide with phf";
        std::vector<size_t> inds; inds.reserve(data_.size());
        for (size_t i = 0; i < data_.size(); ++i) {
            inds.push_back(ph->lookup(data_[i].first));
        }
        reorder_destructive_(inds.begin(), inds.end(), data_.begin());
        built_ = true;
        return built_;
    }

    inline IteratorT find(const KeyT& k) {
        auto ind = boophf_->lookup(k);
        return (ind < data_.size()) ? (data_[ind].first == k ? data_.begin() + ind : data_.end()) : data_.end();
    }

    /**
     * NOTE: This function *assumes* that the key is in the hash.
     * If it isn't, you'll get back a random element!
     */
    inline ValueT& operator[](const KeyT& k) {
        auto ind = boophf_->lookup(k);
        return (ind < data_.size() ? data_[ind].second : data_[0].second);
    }

    inline IteratorT begin() { return data_.begin(); }
    inline IteratorT end() { return data_.end(); }
    inline IteratorT cend() const { return data_.cend(); }
    inline IteratorT cbegin() const { return data_.cbegin(); }

    void save(const std::string& ofileBase) {
        if (built_) {
            std::string hashFN = ofileBase + ".bph";
            // save the perfect hash function
            {
                std::ofstream os(hashFN, std::ios::binary);
                if (!os.is_open()) {
                    std::cerr << "BooM: unable to open output file [" << hashFN << "]; exiting!\n";
                    std::exit(1);
                }
                boophf_->save(os);
                os.close();
            }
            // and the values
            std::string dataFN = ofileBase + ".val";
            {
                std::ofstream valStream(dataFN, std::ios::binary);
                if (!valStream.is_open()) {
                    std::cerr << "BooM: unable to open output file [" << dataFN << "]; exiting!\n";
                    std::exit(1);
                }
                {
                    cereal::BinaryOutputArchive outArchive(valStream);
                    outArchive(data_);
                }
                valStream.close();
            }
        }
    }

    void load(const std::string& ofileBase) {
        std::string hashFN = ofileBase + ".bph";
        std::string dataFN = ofileBase + ".val";

        if ( !FileExists_(hashFN.c_str()) ) {
            std::cerr << "BooM: Looking for perfect hash function file [" << hashFN << "], which doesn't exist! exiting.\n";
            std::exit(1);
        }
        if ( !FileExists_(dataFN.c_str()) ) {
            std::cerr << "BooM: Looking for key-value file [" << dataFN << "], which doesn't exist! exiting.\n";
            std::exit(1);
        }

        // load the perfect hash function
        {
            boophf_.reset(new BooPHFT);
            std::ifstream is(hashFN, std::ios::binary);
            boophf_->load(is);
            is.close();
        }
        // and the values
        {
            std::ifstream dataStream(dataFN, std::ios::binary);
            {
                cereal::BinaryInputArchive inArchive(dataStream);
                inArchive(data_);
            }
            dataStream.close();
        }
        built_ = true;
    }

private:
    // Taken from http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
    bool FileExists_(const char *path) {
        struct stat fileStat;
        if ( stat(path, &fileStat) ) {
            return false;
        }
        if ( !S_ISREG(fileStat.st_mode) ) {
            return false;
        }
        return true;
    }

    // From : http://stackoverflow.com/questions/838384/reorder-vector-using-a-vector-of-indices
    template< typename order_iterator, typename value_iterator >
    void reorder_destructive_( order_iterator order_begin, order_iterator order_end, value_iterator v )  {
        using value_t = typename std::iterator_traits< value_iterator >::value_type;
        using index_t = typename std::iterator_traits< order_iterator >::value_type;
        using diff_t = typename std::iterator_traits< order_iterator >::difference_type;

        diff_t remaining = order_end - 1 - order_begin;
        for ( index_t s = index_t(); remaining > 0; ++ s ) {
            index_t d = order_begin[s];
            if ( d == (diff_t) -1 ) continue;
            -- remaining;
            value_t temp = v[s];
            for ( index_t d2; d != s; d = d2 ) {
                std::swap( temp, v[d] );
                std::swap( order_begin[d], d2 = (diff_t) -1 );
                -- remaining;
            }
            v[s] = temp;
        }
    }

    bool built_;
    std::vector<std::pair<KeyT, ValueT>> data_;
    std::unique_ptr<BooPHFT> boophf_{nullptr};
};
#endif // __BOO_MAP__
<commit_msg>iterator facade doesn't need begin_<commit_after>#ifndef __BOO_MAP__
#define __BOO_MAP__

#include "BooPHF.hpp"

#include "cereal/types/vector.hpp"
#include "cereal/types/utility.hpp"
#include "cereal/archives/binary.hpp"

#include <fstream>
#include <vector>
#include <iterator>
#include <type_traits>

#include <sys/stat.h>

// adapted from :
// http://stackoverflow.com/questions/34875315/implementation-my-own-list-and-iterator-stl-c
template <typename Iter>
class KeyIterator {
public:
    typedef KeyIterator<Iter> self_type;
    typedef typename std::iterator_traits<Iter>::value_type::first_type value_type;
    typedef value_type& reference;
    typedef value_type* pointer;
    typedef std::forward_iterator_tag iterator_category;
    typedef int64_t difference_type;

    KeyIterator(Iter first) : curr_(first) {}
    KeyIterator operator++() { KeyIterator i = *this; curr_++; return i; }
    KeyIterator operator++(int) { ++curr_; return *this; }
    reference operator*() { return curr_->first; }
    pointer operator->() { return &(curr_->first); }
    bool operator==(const self_type& rhs) { return curr_ == rhs.curr_; }
    bool operator!=(const self_type& rhs) { return curr_ != rhs.curr_; }
    bool operator<(const self_type& rhs) { return curr_ < rhs.curr_; }
    bool operator<=(const self_type& rhs) { return curr_ <= rhs.curr_; }

private:
    Iter curr_;
};

template <typename KeyT, typename ValueT>
class BooMap {
public:
    using HasherT = boomphf::SingleHashFunctor<KeyT>;
    using BooPHFT = boomphf::mphf<KeyT, HasherT>;
    using IteratorT = typename std::vector<std::pair<KeyT, ValueT>>::iterator;

    BooMap() : built_(false) {}
    void add(KeyT&& k, ValueT&& v) {
        data_.emplace_back(k, v);
    }

    bool build(int nthreads=1) {
        size_t numElem = data_.size();
        KeyIterator<decltype(data_.begin())> kb(data_.begin());
        KeyIterator<decltype(data_.begin())> ke(data_.end());
        auto keyIt = boomphf::range(kb, ke);
        BooPHFT* ph = new BooPHFT(numElem, keyIt, nthreads);
        boophf_.reset(ph);
        std::cerr << "reordering keys and values to coincide with phf ... ";
        std::vector<size_t> inds; inds.reserve(data_.size());
        for (size_t i = 0; i < data_.size(); ++i) {
            inds.push_back(ph->lookup(data_[i].first));
        }
        reorder_destructive_(inds.begin(), inds.end(), data_.begin());
        std::cerr << "done\n";
        built_ = true;
        return built_;
    }

    inline IteratorT find(const KeyT& k) {
        auto ind = boophf_->lookup(k);
        return (ind < data_.size()) ? (data_[ind].first == k ? data_.begin() + ind : data_.end()) : data_.end();
    }

    /**
     * NOTE: This function *assumes* that the key is in the hash.
     * If it isn't, you'll get back a random element!
     */
    inline ValueT& operator[](const KeyT& k) {
        auto ind = boophf_->lookup(k);
        return (ind < data_.size() ? data_[ind].second : data_[0].second);
    }

    inline IteratorT begin() { return data_.begin(); }
    inline IteratorT end() { return data_.end(); }
    inline IteratorT cend() const { return data_.cend(); }
    inline IteratorT cbegin() const { return data_.cbegin(); }

    void save(const std::string& ofileBase) {
        if (built_) {
            std::string hashFN = ofileBase + ".bph";
            // save the perfect hash function
            {
                std::ofstream os(hashFN, std::ios::binary);
                if (!os.is_open()) {
                    std::cerr << "BooM: unable to open output file [" << hashFN << "]; exiting!\n";
                    std::exit(1);
                }
                boophf_->save(os);
                os.close();
            }
            // and the values
            std::string dataFN = ofileBase + ".val";
            {
                std::ofstream valStream(dataFN, std::ios::binary);
                if (!valStream.is_open()) {
                    std::cerr << "BooM: unable to open output file [" << dataFN << "]; exiting!\n";
                    std::exit(1);
                }
                {
                    cereal::BinaryOutputArchive outArchive(valStream);
                    outArchive(data_);
                }
                valStream.close();
            }
        }
    }

    void load(const std::string& ofileBase) {
        std::string hashFN = ofileBase + ".bph";
        std::string dataFN = ofileBase + ".val";

        if ( !FileExists_(hashFN.c_str()) ) {
            std::cerr << "BooM: Looking for perfect hash function file [" << hashFN << "], which doesn't exist! exiting.\n";
            std::exit(1);
        }
        if ( !FileExists_(dataFN.c_str()) ) {
            std::cerr << "BooM: Looking for key-value file [" << dataFN << "], which doesn't exist! exiting.\n";
            std::exit(1);
        }

        // load the perfect hash function
        {
            boophf_.reset(new BooPHFT);
            std::ifstream is(hashFN, std::ios::binary);
            boophf_->load(is);
            is.close();
        }
        // and the values
        {
            std::ifstream dataStream(dataFN, std::ios::binary);
            {
                cereal::BinaryInputArchive inArchive(dataStream);
                inArchive(data_);
            }
            dataStream.close();
        }
        built_ = true;
    }

private:
    // Taken from http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
    bool FileExists_(const char *path) {
        struct stat fileStat;
        if ( stat(path, &fileStat) ) {
            return false;
        }
        if ( !S_ISREG(fileStat.st_mode) ) {
            return false;
        }
        return true;
    }

    // From : http://stackoverflow.com/questions/838384/reorder-vector-using-a-vector-of-indices
    template< typename order_iterator, typename value_iterator >
    void reorder_destructive_( order_iterator order_begin, order_iterator order_end, value_iterator v )  {
        using value_t = typename std::iterator_traits< value_iterator >::value_type;
        using index_t = typename std::iterator_traits< order_iterator >::value_type;
        using diff_t = typename std::iterator_traits< order_iterator >::difference_type;

        diff_t remaining = order_end - 1 - order_begin;
        for ( index_t s = index_t(); remaining > 0; ++ s ) {
            index_t d = order_begin[s];
            if ( d == (diff_t) -1 ) continue;
            -- remaining;
            value_t temp = v[s];
            for ( index_t d2; d != s; d = d2 ) {
                std::swap( temp, v[d] );
                std::swap( order_begin[d], d2 = (diff_t) -1 );
                -- remaining;
            }
            v[s] = temp;
        }
    }

    bool built_;
    std::vector<std::pair<KeyT, ValueT>> data_;
    std::unique_ptr<BooPHFT> boophf_{nullptr};
};
#endif // __BOO_MAP__
<|endoftext|>


<commit_before>// Author: Akira Okumura 2011/3/6

/******************************************************************************
 * Copyright (C) 2006-, Akira Okumura                                         *
 * All rights reserved.                                                       *
 *****************************************************************************/

// An example of hexagonal Winston cone

// define useful units
static const Double_t cm = AOpticsManager::cm();
static const Double_t mm = AOpticsManager::mm();
static const Double_t um = AOpticsManager::um();
static const Double_t nm = AOpticsManager::nm();
static const Double_t m = AOpticsManager::m();

void HexWinstonCone(Int_t mode = 0) {
  // mode == 0: hex-hex Winston cone built with AGeoWinstonConePoly
  // mode == 1: hex-hex Winston cone built with three AGeoWinstonCone2D
  // mode == 2: circle-circle Winston cone with AGeoWinstonConePoly

  AOpticsManager* manager = new AOpticsManager("manager", "SC");

  // Make the world
  TGeoBBox* worldbox = new TGeoBBox("worldbox", 30 * m, 30 * m, 30 * m);
  AOpticalComponent* world = new AOpticalComponent("world", worldbox);
  manager->SetTopVolume(world);

  // Make the primary mirror
  const Double_t kRin = 20 * mm;
  const Double_t kRout = 10 * mm;
  TGeoRotation* rot30 = new TGeoRotation("rot30", 30, 0, 0);
  rot30->RegisterYourself();
  TGeoRotation* rot60 = new TGeoRotation("rot60", 60, 0, 0);
  rot60->RegisterYourself();
  TGeoRotation* rot120 = new TGeoRotation("rot120", 120, 0, 0);
  rot120->RegisterYourself();

  AGeoWinstonCone2D* coneV =
      new AGeoWinstonCone2D("coneV", kRin, kRout, kRin * 1.733);
  TGeoPgon* pgon = new TGeoPgon("pgon", 0, 360, 6, 4);
  pgon->DefineSection(0, -coneV->GetDZ() * 0.999, 0, kRout * 1.001);
  pgon->DefineSection(1, -coneV->GetDZ() * 0.5, 0, kRin * 0.9);
  pgon->DefineSection(2, -coneV->GetDZ() * 0., 0, kRin * 0.99);
  pgon->DefineSection(3, coneV->GetDZ() * 0.999, 0, kRin * 1.001);

  if (mode == 0) {
    AGeoWinstonConePoly* hexV = new AGeoWinstonConePoly("hexV", kRin, kRout, 6);
    TGeoCompositeShape* coneComp1 =
        new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexV");
    AMirror* coneMirror = new AMirror("coneMirror", coneComp1);
    world->AddNode(coneMirror, 1);
  } else if (mode == 1) {
    TGeoCompositeShape* coneComp1 = new TGeoCompositeShape(
        "coneComp1", "coneV*(coneV:rot60)*(coneV:rot120)");
    TGeoCompositeShape* coneComp2 =
        new TGeoCompositeShape("coneComp2", "pgon:rot30 - coneComp1");
    AMirror* coneMirror = new AMirror("coneMirror", coneComp2);
    world->AddNode(coneMirror, 1);
  } else {
    AGeoWinstonConePoly* hexV =
        new AGeoWinstonConePoly("hexV", kRin, kRout, 100);
    TGeoCompositeShape* coneComp1 =
        new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexV");
    AMirror* coneMirror = new AMirror("coneMirror", coneComp1);
    world->AddNode(coneMirror, 1);
  }  // if

  TGeoPgon* pgonPMT = new TGeoPgon("pgonPMT", 0, 360, 6, 2);
  pgonPMT->DefineSection(0, -coneV->GetDZ() - 0.01 * mm, 0, kRout * 1.01);
  pgonPMT->DefineSection(1, -coneV->GetDZ(), 0, kRout * 1.01);
  AFocalSurface* pmt = new AFocalSurface("pmt", pgonPMT);
  world->AddNode(pmt, 1, rot30);

  manager->CloseGeometry();

  TCanvas* can1 = new TCanvas("can1", "can1");
  world->Draw();

  TGraph* graAeff = new TGraph;

  for (Double_t deg = 0.; deg < 40.; deg += 0.1) {
    TGeoTranslation* raytr = new TGeoTranslation(
        "raytr", 100 * mm * TMath::Sin(deg * TMath::DegToRad()), 0,
        100 * mm * TMath::Cos(deg * TMath::DegToRad()));
    TGeoRotation* rayrot = new TGeoRotation("rayrot", 90, 180 + deg, 0);

    TVector3 dir(0, 0, 1);
    Double_t lambda =
        400 * nm;  // does not affect the results because we have no lens
    // 1 photon per 1 mm^2
    ARayArray* array =
        ARayShooter::Square(lambda, 100 * mm, 101, rayrot, raytr, &dir);
    Double_t dA = 1 * mm * mm;
    manager->TraceNonSequential(*array);
    TObjArray* focused = array->GetFocused();

    Double_t Aeff = 0.;
    for (Int_t j = 0; j <= focused->GetLast(); j++) {
      ARay* ray = (ARay*)(*focused)[j];
      if (!ray) continue;

      // Calculate the effective area from the number of focused photons
      Aeff += dA;

      if (graAeff->GetN() == 0) {
        ray->Draw();  // high CPU load!
      }               // if
    }                 // j

    if (mode == 0 || mode == 1) {
      graAeff->SetPoint(graAeff->GetN(), deg,
                        Aeff / (2 * TMath::Sqrt(3) * kRin * kRin) /
                            TMath::Cos(deg * TMath::DegToRad()));
    } else {
      graAeff->SetPoint(graAeff->GetN(), deg,
                        Aeff / (TMath::Pi() * kRin * kRin) /
                            TMath::Cos(deg * TMath::DegToRad()));
    }  // if

    delete array;
  }  // deg

  TCanvas* can2 = new TCanvas("can2", "can2");
  graAeff->GetXaxis()->SetTitle("Incident Angle (deg)");
  graAeff->GetYaxis()->SetTitle("Collection Efficiency (%)");
  graAeff->Draw("ap");
}
<commit_msg>Increase the cone body size to fix issue #31. This closes #31.<commit_after>// Author: Akira Okumura 2011/3/6

/******************************************************************************
 * Copyright (C) 2006-, Akira Okumura                                         *
 * All rights reserved.                                                       *
 *****************************************************************************/

// An example of hexagonal Winston cone

// define useful units
static const Double_t cm = AOpticsManager::cm();
static const Double_t mm = AOpticsManager::mm();
static const Double_t um = AOpticsManager::um();
static const Double_t nm = AOpticsManager::nm();
static const Double_t m = AOpticsManager::m();

void HexWinstonCone(Int_t mode = 0) {
  // mode == 0: hex-hex Winston cone built with AGeoWinstonConePoly
  // mode == 1: hex-hex Winston cone built with three AGeoWinstonCone2D
  // mode == 2: circle-circle Winston cone with AGeoWinstonConePoly

  AOpticsManager* manager = new AOpticsManager("manager", "SC");

  // Make the world
  TGeoBBox* worldbox = new TGeoBBox("worldbox", 30 * m, 30 * m, 30 * m);
  AOpticalComponent* world = new AOpticalComponent("world", worldbox);
  manager->SetTopVolume(world);

  // Make the primary mirror
  const Double_t kRin = 20 * mm;
  const Double_t kRout = 10 * mm;
  TGeoRotation* rot30 = new TGeoRotation("rot30", 30, 0, 0);
  rot30->RegisterYourself();
  TGeoRotation* rot60 = new TGeoRotation("rot60", 60, 0, 0);
  rot60->RegisterYourself();
  TGeoRotation* rot120 = new TGeoRotation("rot120", 120, 0, 0);
  rot120->RegisterYourself();

  AGeoWinstonCone2D* coneV =
      new AGeoWinstonCone2D("coneV", kRin, kRout, kRin * 1.733);
  TGeoPgon* pgon = new TGeoPgon("pgon", 0, 360, 6, 4);
  pgon->DefineSection(0, -coneV->GetDZ() * 0.999, 0, kRout * 1.1);
  pgon->DefineSection(1, -coneV->GetDZ() * 0.5, 0, kRin * 0.9);
  pgon->DefineSection(2, -coneV->GetDZ() * 0., 0, kRin * 0.99);
  pgon->DefineSection(3, coneV->GetDZ() * 0.999, 0, kRin * 1.001);

  if (mode == 0) {
    AGeoWinstonConePoly* hexV = new AGeoWinstonConePoly("hexV", kRin, kRout, 6);
    TGeoCompositeShape* coneComp1 =
        new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexV");
    AMirror* coneMirror = new AMirror("coneMirror", coneComp1);
    world->AddNode(coneMirror, 1);
  } else if (mode == 1) {
    TGeoCompositeShape* coneComp1 = new TGeoCompositeShape(
        "coneComp1", "coneV*(coneV:rot60)*(coneV:rot120)");
    TGeoCompositeShape* coneComp2 =
        new TGeoCompositeShape("coneComp2", "pgon:rot30 - coneComp1");
    AMirror* coneMirror = new AMirror("coneMirror", coneComp2);
    world->AddNode(coneMirror, 1);
  } else {
    AGeoWinstonConePoly* hexV =
        new AGeoWinstonConePoly("hexV", kRin, kRout, 100);
    TGeoCompositeShape* coneComp1 =
        new TGeoCompositeShape("coneComp1", "pgon:rot30 - hexV");
    AMirror* coneMirror = new AMirror("coneMirror", coneComp1);
    world->AddNode(coneMirror, 1);
  }  // if

  TGeoPgon* pgonPMT = new TGeoPgon("pgonPMT", 0, 360, 6, 2);
  pgonPMT->DefineSection(0, -coneV->GetDZ() - 0.01 * mm, 0, kRout * 1.01);
  pgonPMT->DefineSection(1, -coneV->GetDZ(), 0, kRout * 1.01);
  AFocalSurface* pmt = new AFocalSurface("pmt", pgonPMT);
  world->AddNode(pmt, 1, rot30);

  manager->CloseGeometry();

  TCanvas* can1 = new TCanvas("can1", "can1");
  world->Draw();

  TGraph* graAeff = new TGraph;

  for (Double_t deg = 0.; deg < 40.; deg += 0.1) {
    TGeoTranslation* raytr = new TGeoTranslation(
        "raytr", 100 * mm * TMath::Sin(deg * TMath::DegToRad()), 0,
        100 * mm * TMath::Cos(deg * TMath::DegToRad()));
    TGeoRotation* rayrot = new TGeoRotation("rayrot", 90, 180 + deg, 0);

    TVector3 dir(0, 0, 1);
    Double_t lambda =
        400 * nm;  // does not affect the results because we have no lens
    // 1 photon per 1 mm^2
    ARayArray* array =
        ARayShooter::Square(lambda, 100 * mm, 101, rayrot, raytr, &dir);
    Double_t dA = 1 * mm * mm;
    manager->TraceNonSequential(*array);
    TObjArray* focused = array->GetFocused();

    Double_t Aeff = 0.;
    for (Int_t j = 0; j <= focused->GetLast(); j++) {
      ARay* ray = (ARay*)(*focused)[j];
      if (!ray) continue;

      // Calculate the effective area from the number of focused photons
      Aeff += dA;

      if (graAeff->GetN() == 0) {
        ray->Draw();  // high CPU load!
      }               // if
    }                 // j

    if (mode == 0 || mode == 1) {
      graAeff->SetPoint(graAeff->GetN(), deg,
                        Aeff / (2 * TMath::Sqrt(3) * kRin * kRin) /
                            TMath::Cos(deg * TMath::DegToRad()));
    } else {
      graAeff->SetPoint(graAeff->GetN(), deg,
                        Aeff / (TMath::Pi() * kRin * kRin) /
                            TMath::Cos(deg * TMath::DegToRad()));
    }  // if

    delete array;
  }  // deg

  TCanvas* can2 = new TCanvas("can2", "can2");
  graAeff->GetXaxis()->SetTitle("Incident Angle (deg)");
  graAeff->GetYaxis()->SetTitle("Collection Efficiency (%)");
  graAeff->Draw("ap");
}
<|endoftext|>