<commit_before>// $Id: File_test.C,v 1.5 2000/06/30 15:44:35 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/file.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <fstream>
///////////////////////////

START_TEST(class_name, "$Id: File_test.C,v 1.5 2000/06/30 15:44:35 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

File* f1;

CHECK(File())
	f1 = new File();
	TEST_NOT_EQUAL(f1, 0)
RESULT

CHECK(~File())
	delete f1;
RESULT

CHECK(File(const String& name, OpenMode open_mode = std::ios::in))
	File f("data/File_test.txt");
	TEST_EQUAL(f.getSize(), 100)
RESULT

File f("data/File_test.txt");

CHECK(File(const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
RESULT

CHECK(close())
	TEST_EQUAL(f.getSize(), 100)
	f.close();
	TEST_EQUAL(f.isClosed(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(open(const String& name, OpenMode open_mode = std::ios::in))
	f.open("data/File_test.txt");
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(reopen())
	f.close();
	f.reopen();
	f.reopen();
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getName())
	TEST_EQUAL(f.getName(), "data/File_test.txt")
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getSize())
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static getSize(String filename))
	TEST_EQUAL(f.getSize("data/File_test.txt"), 100)
	f.remove("XXX");
	TEST_EQUAL(f.getSize("XXX"), 0)
RESULT

CHECK(int getOpenMode() const)
	TEST_EQUAL(f.getOpenMode(), 1)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static Type getType(String name, bool trace_link))
	TEST_EQUAL(f.getType("data/File_test.txt", false), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(Type getType(bool trace_link) const;)
	TEST_EQUAL(f.getType(false), 4)
	TEST_EQUAL(f.getType(true), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(std::fstream& getFileStream();)
//	fstream fs;
//	FILE file;
//	file = f.getFileStream(); //!!!
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(copy(String source_name, String destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copy("data/File_test.txt", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", ""), false)
	TEST_EQUAL(f.copy("", ""), false)
	TEST_EQUAL(f.copy("ZZZZZZZZZZ", "XXX"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(copyTo(const String& destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copyTo("data/File_test.txt"), false)
	TEST_EQUAL(f.copyTo(""), false)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(move(const String& source_name, const String& destination_name))
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("YYY"), true)
	TEST_EQUAL(f.move("XXX", "XXX"), false)
	TEST_EQUAL(f.move("", "XXX"), false)
	TEST_EQUAL(f.move("XXX", ""), false)

	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.isAccessible("XXX"), false)
	TEST_EQUAL(f.getSize("YYY"), 100)

	f.copyTo("XXX");
	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.getSize(), 100)
	f.remove("XXX");
	f.remove("YYY");
RESULT

CHECK(moveTo(const String& destination_name))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.moveTo("XXX"), false)
	TEST_EQUAL(f1.moveTo(""), false)
	TEST_EQUAL(f1.moveTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f1.moveTo("YYY"), false)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f.getSize("YYY"), 100)
RESULT

CHECK(remove(String name))
	f.copyTo("XXX");
	TEST_EQUAL(f.remove("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(remove())
	File f1 = File("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(rename(String old_path, String new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.rename("XXX", "XXX"), true)
	TEST_EQUAL(f1.rename("XXX", "YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
	TEST_EQUAL(f.getSize(), 100)
	f.remove("YYY");
RESULT

CHECK(renameTo(const String& new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.renameTo("XXX"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), true)
	TEST_EQUAL(f1.renameTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
RESULT

CHECK(truncate(String path, Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate("XXX", 50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate("XXX", 0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(truncate(Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate(50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate(0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(createTemporaryFilename(String& temporary))
	String s;
	TEST_EQUAL(f.createTemporaryFilename(s), true)
	TEST_NOT_EQUAL(s, "")
RESULT

CHECK(operator == (const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 == f, false)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(operator != (const File& file))
	File f1(f);
	TEST_EQUAL(f1 != f, false)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 != f, true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(isOpen())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isOpen(), true)
	f1.close();
	TEST_EQUAL(f1.isOpen(), false)
RESULT

CHECK(isClosed())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isClosed(), false)
	f1.close();
	TEST_EQUAL(f1.isClosed(), true)
RESULT

CHECK(isAccessible(String name))
	TEST_EQUAL(f.isAccessible("data/File_test.txt"), true)
	f.remove("XXX");
	TEST_EQUAL(f.isAccessible("XXX"), false)
RESULT

CHECK(isAccessible())
	TEST_EQUAL(f.isAccessible(), true)
	f.copyTo("XXX");
	File f1("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(isCanonized())
	File f1("../TEST/data/File_test.txt");
	TEST_EQUAL(f1.isValid(), true)
	TEST_EQUAL(f1.isCanonized(), true)

	File f2("data//File_test.txt");
	TEST_EQUAL(f2.isValid(), true)
	TEST_EQUAL(f2.isCanonized(), true)

	File f4("data/../data/File_test.txt");
	TEST_EQUAL(f4.isValid(), true)
	TEST_EQUAL(f4.isCanonized(), true)

	File f5("./data/File_test.txt");
	TEST_EQUAL(f5.isValid(), true)
	TEST_EQUAL(f5.isCanonized(), true)

	File f6("data/File_test.txt");
	TEST_EQUAL(f6.isValid(), true)
	TEST_EQUAL(f6.isCanonized(), true)

	File f7("~/File_test.txt");
	TEST_EQUAL(f7.isCanonized(), true)
RESULT

CHECK(isReadable(String name))
	TEST_EQUAL(f.isReadable("File_test.C"), true)
RESULT

CHECK(isReadable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isReadable(), true)
RESULT

CHECK(isWritable(String name))
	TEST_EQUAL(f.isWritable("File_test.C"), true)
RESULT

CHECK(isWritable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isWritable(), true)
RESULT

CHECK(isExecutable(String name))
	TEST_EQUAL(f.isExecutable("../configure"), true)
	TEST_EQUAL(f.isExecutable("File_test.C"), false)
RESULT

CHECK(isExecutable())
	File f1("../configure");
	TEST_EQUAL(f1.isExecutable(), true)
	File f2("File_test.C");
	TEST_EQUAL(f2.isExecutable(), false)
RESULT

CHECK(isValid())
	TEST_EQUAL(f.isValid(), true)
	File f1("XXX");
	TEST_EQUAL(f1.isValid(), false)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: using relative paths in MULTI_BUILD mode leads to failing tests, since   "../configure" is "../../configure" in M_B mode!<commit_after>// $Id: File_test.C,v 1.6 2000/07/04 09:30:10 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/file.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <fstream>
///////////////////////////

START_TEST(class_name, "$Id: File_test.C,v 1.6 2000/07/04 09:30:10 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

File* f1;

CHECK(File())
	f1 = new File();
	TEST_NOT_EQUAL(f1, 0)
RESULT

CHECK(~File())
	delete f1;
RESULT

CHECK(File(const String& name, OpenMode open_mode = std::ios::in))
	File f("data/File_test.txt");
	TEST_EQUAL(f.getSize(), 100)
RESULT

File f("data/File_test.txt");

CHECK(File(const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
RESULT

CHECK(close())
	TEST_EQUAL(f.getSize(), 100)
	f.close();
	TEST_EQUAL(f.isClosed(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(open(const String& name, OpenMode open_mode = std::ios::in))
	f.open("data/File_test.txt");
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(reopen())
	f.close();
	f.reopen();
	f.reopen();
	TEST_EQUAL(f.isOpen(), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getName())
	TEST_EQUAL(f.getName(), "data/File_test.txt")
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(getSize())
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static getSize(String filename))
	TEST_EQUAL(f.getSize("data/File_test.txt"), 100)
	f.remove("XXX");
	TEST_EQUAL(f.getSize("XXX"), 0)
RESULT

CHECK(int getOpenMode() const)
	TEST_EQUAL(f.getOpenMode(), 1)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(static Type getType(String name, bool trace_link))
	TEST_EQUAL(f.getType("data/File_test.txt", false), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(Type getType(bool trace_link) const;)
	TEST_EQUAL(f.getType(false), 4)
	TEST_EQUAL(f.getType(true), 4)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(std::fstream& getFileStream();)
//	fstream fs;
//	FILE file;
//	file = f.getFileStream(); //!!!
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(copy(String source_name, String destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copy("data/File_test.txt", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("", "data/File_test.txt"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", ""), false)
	TEST_EQUAL(f.copy("", ""), false)
	TEST_EQUAL(f.copy("ZZZZZZZZZZ", "XXX"), false)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.copy("data/File_test.txt", "XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(copyTo(const String& destination_name, Size buffer_size = 4096))
	TEST_EQUAL(f.copyTo("data/File_test.txt"), false)
	TEST_EQUAL(f.copyTo(""), false)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
	TEST_EQUAL(f.getSize("XXX"), 100)
	f.remove("XXX");
RESULT

CHECK(move(const String& source_name, const String& destination_name))
	TEST_EQUAL(f.copyTo("XXX"), true)
	TEST_EQUAL(f.copyTo("YYY"), true)
	TEST_EQUAL(f.move("XXX", "XXX"), false)
	TEST_EQUAL(f.move("", "XXX"), false)
	TEST_EQUAL(f.move("XXX", ""), false)

	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.isAccessible("XXX"), false)
	TEST_EQUAL(f.getSize("YYY"), 100)

	f.copyTo("XXX");
	TEST_EQUAL(f.move("XXX", "YYY"), true)
	TEST_EQUAL(f.getSize(), 100)
	f.remove("XXX");
	f.remove("YYY");
RESULT

CHECK(moveTo(const String& destination_name))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.moveTo("XXX"), false)
	TEST_EQUAL(f1.moveTo(""), false)
	TEST_EQUAL(f1.moveTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f1.moveTo("YYY"), false)
	TEST_EQUAL(f1.isAccessible(), true)
	TEST_EQUAL(f.getSize("YYY"), 100)
RESULT

CHECK(remove(String name))
	f.copyTo("XXX");
	TEST_EQUAL(f.remove("XXX"), true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(remove())
	File f1 = File("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(rename(String old_path, String new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.rename("XXX", "XXX"), true)
	TEST_EQUAL(f1.rename("XXX", "YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
	TEST_EQUAL(f.getSize(), 100)
	f.remove("YYY");
RESULT

CHECK(renameTo(const String& new_path))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.renameTo("XXX"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), true)
	TEST_EQUAL(f1.renameTo("YYY"), true)
	TEST_EQUAL(f1.isAccessible("XXX"), false)
	TEST_EQUAL(f1.isAccessible("YYY"), true)
	f1.remove();
RESULT

CHECK(truncate(String path, Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate("XXX", 50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate("XXX", 0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(truncate(Size size = 0))
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.truncate(50), true)
	TEST_EQUAL(f1.getSize(), 50)
	TEST_EQUAL(f1.truncate(0), true)
	TEST_EQUAL(f1.getSize(), 0)
	f1.remove();
RESULT

CHECK(createTemporaryFilename(String& temporary))
	String s;
	TEST_EQUAL(f.createTemporaryFilename(s), true)
	TEST_NOT_EQUAL(s, "")
RESULT

CHECK(operator == (const File& file))
	File f1(f);
	TEST_EQUAL(f1 == f, true)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 == f, false)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(operator != (const File& file))
	File f1(f);
	TEST_EQUAL(f1 != f, false)
	f.copyTo("XXX");
	File f2("XXX");
	TEST_EQUAL(f2 != f, true)
	TEST_EQUAL(f.getSize(), 100)
RESULT

CHECK(isOpen())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isOpen(), true)
	f1.close();
	TEST_EQUAL(f1.isOpen(), false)
RESULT

CHECK(isClosed())
	f.copyTo("XXX");
	File f1("XXX");
	TEST_EQUAL(f1.isClosed(), false)
	f1.close();
	TEST_EQUAL(f1.isClosed(), true)
RESULT

CHECK(isAccessible(String name))
	TEST_EQUAL(f.isAccessible("data/File_test.txt"), true)
	f.remove("XXX");
	TEST_EQUAL(f.isAccessible("XXX"), false)
RESULT

CHECK(isAccessible())
	TEST_EQUAL(f.isAccessible(), true)
	f.copyTo("XXX");
	File f1("XXX");
	f1.remove();
	TEST_EQUAL(f1.isAccessible(), false)
RESULT

CHECK(isCanonized())
	File f1("../TEST/data/File_test.txt");
	TEST_EQUAL(f1.isValid(), true)
	TEST_EQUAL(f1.isCanonized(), true)

	File f2("data//File_test.txt");
	TEST_EQUAL(f2.isValid(), true)
	TEST_EQUAL(f2.isCanonized(), true)

	File f4("data/../data/File_test.txt");
	TEST_EQUAL(f4.isValid(), true)
	TEST_EQUAL(f4.isCanonized(), true)

	File f5("./data/File_test.txt");
	TEST_EQUAL(f5.isValid(), true)
	TEST_EQUAL(f5.isCanonized(), true)

	File f6("data/File_test.txt");
	TEST_EQUAL(f6.isValid(), true)
	TEST_EQUAL(f6.isCanonized(), true)

	File f7("~/File_test.txt");
	TEST_EQUAL(f7.isCanonized(), true)
RESULT

CHECK(isReadable(String name))
	TEST_EQUAL(f.isReadable("File_test.C"), true)
RESULT

CHECK(isReadable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isReadable(), true)
RESULT

CHECK(isWritable(String name))
	TEST_EQUAL(f.isWritable("File_test.C"), true)
RESULT

CHECK(isWritable())
	File f2("File_test.C");
	TEST_EQUAL(f2.isWritable(), true)
RESULT

CHECK(isExecutable(String name))
	TEST_EQUAL(f.isExecutable(BALL_PATH "/source/configure"), true)
	TEST_EQUAL(f.isExecutable("File_test.C"), false)
RESULT

CHECK(isExecutable())
	File f1(BALL_PATH "/source/configure");
	TEST_EQUAL(f1.isExecutable(), true)
	File f2("File_test.C");
	TEST_EQUAL(f2.isExecutable(), false)
RESULT

CHECK(isValid())
	TEST_EQUAL(f.isValid(), true)
	File f1("XXX");
	TEST_EQUAL(f1.isValid(), false)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      managedframe.cpp
// Purpose:   Implementation of wxExManagedFrame class.
// Author:    Anton van Wezenbeek
// Created:   2010-04-11
// RCS-ID:    $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/managedframe.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/vi.h>

#if wxUSE_GUI

// Support class.
// Offers a combobox related to a vi object.
class wxExComboBox: public wxComboBox
{
public:
  /// Constructor. Fills the combobox box with values
  /// from FindReplace from config.
  wxExComboBox(
    wxWindow* parent,
    wxExManagedFrame* frame,
    wxStaticText* text,
    wxWindowID id = wxID_ANY,
    const wxPoint& pos = wxDefaultPosition,
    const wxSize& size = wxDefaultSize);

  /// Sets callback.
  void SetVi(wxExVi* vi) {m_vi = vi;};
private:
  void OnEnter(wxCommandEvent& event);
  void OnKeyDown(wxKeyEvent& event);

  wxExManagedFrame* m_Frame;
  wxExVi* m_vi;
  wxStaticText* m_StaticText;

  DECLARE_EVENT_TABLE()
};

#if wxUSE_AUI
BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
  EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
  EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
  EVT_UPDATE_UI_RANGE(
    ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()

wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  long style)
  : wxExFrame(parent, id, title, style)
{
  m_Manager.SetManagedWindow(this);

  wxExToolBar* toolBar = new wxExToolBar(this);

  toolBar->AddControls();

  DoAddControl(toolBar);

  m_Manager.AddPane(toolBar,
    wxAuiPaneInfo().Top().ToolbarPane().Name("TOOLBAR").Caption(_("Toolbar")));

  m_Manager.AddPane(new wxExFindToolBar(this),
    wxAuiPaneInfo().Bottom().ToolbarPane().Name("FINDBAR").Caption(_("Findbar")));

  wxPanel* vipanel = new wxPanel(this);

  wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
  m_viStaticText = new wxStaticText(vipanel, wxID_ANY, wxEmptyString);
  m_viComboBox = new wxExComboBox(vipanel, this, m_viStaticText);

  sizer->AddGrowableCol(1);
  sizer->Add(m_viStaticText, wxSizerFlags().Expand());
  sizer->Add(m_viComboBox, wxSizerFlags().Expand());

  vipanel->SetSizerAndFit(sizer);
  wxExComboBoxFromList(m_viComboBox, wxExListFromConfig("VIBAR"));

  m_Manager.AddPane(vipanel,
    wxAuiPaneInfo().Bottom().Floatable(false).Name("VIBAR").CaptionVisible(false));

  m_Manager.GetPane("VIBAR").Hide();
}

wxExManagedFrame::~wxExManagedFrame()
{
  const auto l = wxExComboBoxToList(m_viComboBox, 25);
  wxExListToConfig(l, "VIBAR");
  m_Manager.UnInit();
}

void wxExManagedFrame::GetViCommand(wxExVi* vi, const wxString& command)
{
  m_viStaticText->SetLabel(command);

  m_viComboBox->SelectAll();
  m_viComboBox->SetFocus();
  m_viComboBox->SetVi(vi);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::HideViBar()
{
  if (m_Manager.GetPane("VIBAR").IsShown())
  {
    m_Manager.GetPane("VIBAR").Hide();
    m_Manager.Update();
  }
}

void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
    case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
    case ID_VIEW_FINDBAR:
      event.Check(m_Manager.GetPane("FINDBAR").IsShown());
    break;

    case ID_VIEW_TOOLBAR:
      event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
    break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::ShowViMessage(const wxString& text)
{
  m_viStaticText->SetLabel(text);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::TogglePane(const wxString& pane)
{
  wxAuiPaneInfo& info = m_Manager.GetPane(pane);

  wxASSERT(info.IsOk());

  info.IsShown() ? info.Hide(): info.Show();

  m_Manager.Update();
}
#endif // wxUSE_AUI

// Implementation of support class.

BEGIN_EVENT_TABLE(wxExComboBox, wxComboBox)
  EVT_CHAR(wxExComboBox::OnKeyDown)
  EVT_TEXT_ENTER(wxID_ANY, wxExComboBox::OnEnter)
END_EVENT_TABLE()

wxExComboBox::wxExComboBox(
  wxWindow* parent,
  wxExManagedFrame* frame,
  wxStaticText* text,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size)
  : wxComboBox(parent, id, wxEmptyString, pos, size, 0, NULL, wxTE_PROCESS_ENTER)
  , m_Frame(frame)
  , m_vi(NULL)
  , m_StaticText(text)
{
}

void wxExComboBox::OnEnter(wxCommandEvent& event)
{
  if (m_StaticText->GetLabel() == ":")
  {
    if (m_vi->ExecCommand(GetValue()))
    {
      m_Frame->HideViBar();
      m_vi->GetSTC()->SetFocus();
    }
  }
  else
  {
    if (m_vi->FindCommand(m_StaticText->GetLabel(), GetValue()))
    {
      m_Frame->HideViBar();
      m_vi->GetSTC()->SetFocus();
    }
  }
}

void wxExComboBox::OnKeyDown(wxKeyEvent& event)
{
  const auto key = event.GetKeyCode();

  if (key == WXK_ESCAPE)
  {
    if (m_vi != NULL)
    {
      m_Frame->HideViBar();
      m_vi->GetSTC()->SetFocus();
    }
  }
  else
  {
    event.Skip();
  }
}

#endif // wxUSE_GUI
<commit_msg>better names<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      managedframe.cpp
// Purpose:   Implementation of wxExManagedFrame class.
// Author:    Anton van Wezenbeek
// Created:   2010-04-11
// RCS-ID:    $Id$
// Copyright: (c) 2010 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/extension/managedframe.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/vi.h>

#if wxUSE_GUI

// Support class.
// Offers a combobox related to a vi object.
class wxExComboBox: public wxComboBox
{
public:
  /// Constructor. Fills the combobox box with values
  /// from FindReplace from config.
  wxExComboBox(
    wxWindow* parent,
    wxExManagedFrame* frame,
    wxStaticText* text,
    wxWindowID id = wxID_ANY,
    const wxPoint& pos = wxDefaultPosition,
    const wxSize& size = wxDefaultSize);

  /// Sets callback.
  void SetVi(wxExVi* vi) {m_vi = vi;};
private:
  void OnCommand(wxCommandEvent& event);
  void OnKey(wxKeyEvent& event);

  wxExManagedFrame* m_Frame;
  wxExVi* m_vi;
  wxStaticText* m_StaticText;

  DECLARE_EVENT_TABLE()
};

#if wxUSE_AUI
BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
  EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
  EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
  EVT_UPDATE_UI_RANGE(
    ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()

wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  long style)
  : wxExFrame(parent, id, title, style)
{
  m_Manager.SetManagedWindow(this);

  wxExToolBar* toolBar = new wxExToolBar(this);

  toolBar->AddControls();

  DoAddControl(toolBar);

  m_Manager.AddPane(toolBar,
    wxAuiPaneInfo().Top().ToolbarPane().Name("TOOLBAR").Caption(_("Toolbar")));

  m_Manager.AddPane(new wxExFindToolBar(this),
    wxAuiPaneInfo().Bottom().ToolbarPane().Name("FINDBAR").Caption(_("Findbar")));

  wxPanel* vipanel = new wxPanel(this);

  wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
  m_viStaticText = new wxStaticText(vipanel, wxID_ANY, wxEmptyString);
  m_viComboBox = new wxExComboBox(vipanel, this, m_viStaticText);

  sizer->AddGrowableCol(1);
  sizer->Add(m_viStaticText, wxSizerFlags().Expand());
  sizer->Add(m_viComboBox, wxSizerFlags().Expand());

  vipanel->SetSizerAndFit(sizer);
  wxExComboBoxFromList(m_viComboBox, wxExListFromConfig("VIBAR"));

  m_Manager.AddPane(vipanel,
    wxAuiPaneInfo().Bottom().Floatable(false).Name("VIBAR").CaptionVisible(false));

  m_Manager.GetPane("VIBAR").Hide();
}

wxExManagedFrame::~wxExManagedFrame()
{
  const auto l = wxExComboBoxToList(m_viComboBox, 25);
  wxExListToConfig(l, "VIBAR");
  m_Manager.UnInit();
}

void wxExManagedFrame::GetViCommand(wxExVi* vi, const wxString& command)
{
  m_viStaticText->SetLabel(command);

  m_viComboBox->SelectAll();
  m_viComboBox->SetFocus();
  m_viComboBox->SetVi(vi);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::HideViBar()
{
  if (m_Manager.GetPane("VIBAR").IsShown())
  {
    m_Manager.GetPane("VIBAR").Hide();
    m_Manager.Update();
  }
}

void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
    case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
    case ID_VIEW_FINDBAR:
      event.Check(m_Manager.GetPane("FINDBAR").IsShown());
    break;

    case ID_VIEW_TOOLBAR:
      event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
    break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::ShowViMessage(const wxString& text)
{
  m_viStaticText->SetLabel(text);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::TogglePane(const wxString& pane)
{
  wxAuiPaneInfo& info = m_Manager.GetPane(pane);

  wxASSERT(info.IsOk());

  info.IsShown() ? info.Hide(): info.Show();

  m_Manager.Update();
}
#endif // wxUSE_AUI

// Implementation of support class.

BEGIN_EVENT_TABLE(wxExComboBox, wxComboBox)
  EVT_CHAR(wxExComboBox::OnKey)
  EVT_TEXT_ENTER(wxID_ANY, wxExComboBox::OnCommand)
END_EVENT_TABLE()

wxExComboBox::wxExComboBox(
  wxWindow* parent,
  wxExManagedFrame* frame,
  wxStaticText* text,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size)
  : wxComboBox(parent, id, wxEmptyString, pos, size, 0, NULL, wxTE_PROCESS_ENTER)
  , m_Frame(frame)
  , m_vi(NULL)
  , m_StaticText(text)
{
}

void wxExComboBox::OnCommand(wxCommandEvent& event)
{
  if (m_StaticText->GetLabel() == ":")
  {
    if (m_vi->ExecCommand(GetValue()))
    {
      m_Frame->HideViBar();
      m_vi->GetSTC()->SetFocus();
    }
  }
  else
  {
    if (m_vi->FindCommand(m_StaticText->GetLabel(), GetValue()))
    {
      m_Frame->HideViBar();
      m_vi->GetSTC()->SetFocus();
    }
  }
}

void wxExComboBox::OnKey(wxKeyEvent& event)
{
  const auto key = event.GetKeyCode();

  if (key == WXK_ESCAPE)
  {
    if (m_vi != NULL)
    {
      m_Frame->HideViBar();
      m_vi->GetSTC()->SetFocus();
    }
  }
  else
  {
    event.Skip();
  }
}

#endif // wxUSE_GUI
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          test.cpp
* Purpose:       Implementation for wxextension report cpp unit testing
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id: test.cpp 589 2009-04-09 13:43:53Z antonvw $
* Created:       za 17 jan 2009 11:51:20 CET
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <TestCaller.h>
#include "test.h"

void wxExReportAppTestFixture::setUp()
{
  wxExFrameWithHistory* frame = (wxExFrameWithHistory *)wxTheApp->GetTopWindow();
  m_ListView = new wxExListViewFile(frame, wxExListViewFile::LIST_PROCESS);
  m_Dir = new wxExDirWithReport(m_ListView, "./");
  m_Process = new wxExProcessWithListView(m_ListView, "wc test.h");
  m_STC = new wxExSTCWithFrame(frame, wxExFileName("test.h"));
}

void wxExReportAppTestFixture::testConstructors()
{
}

void wxExReportAppTestFixture::testMethods()
{
  // test wxExDirWithReport
  CPPUNIT_ASSERT(m_Dir->FindFiles());

  // test wxExFrameWithHistory
  wxExFrameWithHistory* frame = (wxExFrameWithHistory *)wxTheApp->GetTopWindow();
  CPPUNIT_ASSERT(frame->OpenFile(wxExFileName("test.h")));
  CPPUNIT_ASSERT(frame->GetRecentFile().Contains("test.h"));
  CPPUNIT_ASSERT(frame->OpenFile(
    wxExFileName("test.h"),
    0,
    wxEmptyString,
    wxExSTCWithFrame::STC_OPEN_IS_PROJECT));
  CPPUNIT_ASSERT(frame->GetRecentProject().Contains("test.h"));

  // test wxExListViewFile
  CPPUNIT_ASSERT(m_ListView->FileOpen(wxExFileName("test.prj")));
  CPPUNIT_ASSERT(m_ListView->ItemFromText("test1\ntest2\n"));

  // test wxExProcessWithListView
  CPPUNIT_ASSERT(m_Process->Run());
  CPPUNIT_ASSERT(m_Process->Kill() == wxKILL_OK);
  CPPUNIT_ASSERT(m_Process->Run()); // repeat test
  CPPUNIT_ASSERT(m_Process->Kill() == wxKILL_OK);

  // test wxExSTCWithFrame
  CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h");
}

void wxExReportAppTestFixture::tearDown()
{
}

wxExReportTestSuite::wxExReportTestSuite()
  : CppUnit::TestSuite("wxexreport test suite")
{
  addTest(new CppUnit::TestCaller<wxExReportAppTestFixture>(
    "testConstructors",
    &wxExReportAppTestFixture::testConstructors));

  addTest(new CppUnit::TestCaller<wxExReportAppTestFixture>(
    "testMethods",
    &wxExReportAppTestFixture::testMethods));
}

<commit_msg>improved tests<commit_after>/******************************************************************************\
* File:          test.cpp
* Purpose:       Implementation for wxextension report cpp unit testing
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id: test.cpp 589 2009-04-09 13:43:53Z antonvw $
* Created:       za 17 jan 2009 11:51:20 CET
*
* Copyright (c) 2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <TestCaller.h>
#include "test.h"

void wxExReportAppTestFixture::setUp()
{
  wxExFrameWithHistory* frame = (wxExFrameWithHistory *)wxTheApp->GetTopWindow();
  m_ListView = new wxExListViewFile(frame, wxExListViewFile::LIST_PROCESS);
  m_Dir = new wxExDirWithReport(m_ListView, "./");
  m_Process = new wxExProcessWithListView(m_ListView, "wc test.h");
  m_STC = new wxExSTCWithFrame(frame, wxExFileName("test.h"));
}

void wxExReportAppTestFixture::testConstructors()
{
}

void wxExReportAppTestFixture::testMethods()
{
  // test wxExDirWithReport
  CPPUNIT_ASSERT(m_Dir->FindFiles());

  // test wxExFrameWithHistory
  wxExFrameWithHistory* frame = (wxExFrameWithHistory *)wxTheApp->GetTopWindow();
  CPPUNIT_ASSERT(!frame->OpenFile(wxExFileName("test.h"))); // as we have no focused stc
  CPPUNIT_ASSERT(frame->GetRecentFile().Contains("test.h"));
  CPPUNIT_ASSERT(!frame->OpenFile(
    wxExFileName("test.prj"),
    0,
    wxEmptyString,
    wxExSTCWithFrame::STC_OPEN_IS_PROJECT));
  CPPUNIT_ASSERT(!frame->GetRecentProject().Contains("test.prj"));

  // test wxExListViewFile
  CPPUNIT_ASSERT(m_ListView->FileOpen(wxExFileName("test.prj")));
  CPPUNIT_ASSERT(m_ListView->ItemFromText("test1\ntest2\n"));

  // test wxExProcessWithListView
  CPPUNIT_ASSERT(m_Process->Run());
  CPPUNIT_ASSERT(m_Process->Kill() == wxKILL_OK);
  CPPUNIT_ASSERT(m_Process->Run()); // repeat test
  CPPUNIT_ASSERT(m_Process->Kill() == wxKILL_OK);

  // test wxExSTCWithFrame
  CPPUNIT_ASSERT(m_STC->GetFileName().GetFullName() == "test.h");
}

void wxExReportAppTestFixture::tearDown()
{
}

wxExReportTestSuite::wxExReportTestSuite()
  : CppUnit::TestSuite("wxexreport test suite")
{
  addTest(new CppUnit::TestCaller<wxExReportAppTestFixture>(
    "testConstructors",
    &wxExReportAppTestFixture::testConstructors));

  addTest(new CppUnit::TestCaller<wxExReportAppTestFixture>(
    "testMethods",
    &wxExReportAppTestFixture::testMethods));
}

<|endoftext|>


<commit_before>// Standard lib
#include <iostream>
#include <Windows.h>

// Nui Api
#include "NuiApi.h"

// My Header
#include "Kinect.h"

OzansKinect::Kinect::Kinect()
	:mNuiSensor(NULL)
{
}

OzansKinect::Kinect::~Kinect()
{
	if (mNuiSensor)
	{
		mNuiSensor->NuiShutdown();
	}
}

HRESULT OzansKinect::Kinect::Connection()
{
	INuiSensor* pNuiSensor;

	int iSensorCount = 0;
	HRESULT hr = NuiGetSensorCount(&iSensorCount);
	if (FAILED(hr))
	{
		return hr;
	}

	// Look at the kinect
	for (int i = 0; i < iSensorCount; ++i)
	{
		// Create a sensor for check
		hr = NuiCreateSensorByIndex(i, &pNuiSensor);
		if (FAILED(hr))
		{
			continue;
		}

		// Get the status sensor
		hr = pNuiSensor->NuiStatus();
		if (S_OK == hr)
		{
			mNuiSensor = pNuiSensor;
			break;
		}

		// We can release temproray variable
		pNuiSensor->Release();
	}

	if (mNuiSensor != NULL)
	{
		// Initialize the Kinect for skeleton mod
		mNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_SKELETON);
	}

	if (mNuiSensor == NULL || FAILED(hr))
	{
		std::cout << "Kinect not found!" << std::endl;
		return E_FAIL;

	}

	return hr;
}

HRESULT OzansKinect::Kinect::Process()
{
	NUI_SKELETON_FRAME skeletonFrame;

	HRESULT hr = mNuiSensor->NuiSkeletonGetNextFrame(0, &skeletonFrame);
	if (FAILED(hr))
	{
		return hr;
	}

	// Smooth skeleton data
	mNuiSensor->NuiTransformSmooth(&skeletonFrame, NULL);

	for (int i = 0; i < NUI_SKELETON_COUNT; i++)
	{
		NUI_SKELETON_TRACKING_STATE trackingState = skeletonFrame.SkeletonData[i].eTrackingState;
		if (trackingState == NUI_SKELETON_TRACKED)
		{
			Vector4 rightHand = skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_RIGHT];
			Vector4 leftHand = skeletonFrame.SkeletonData[i].SkeletonPositions[NUI_SKELETON_POSITION_HAND_LEFT];

			std::cout << "x" << rightHand.x << " y" << rightHand.y << " z" << rightHand.z << std::endl;
			std::cout << "x" << leftHand.x << " y" << leftHand.y << " z" << leftHand.z << std::endl;
		}
	}
	system("cls");

	return S_OK;
}<commit_msg>All skeleton points<commit_after>// Standard lib
#include <iostream>
#include <Windows.h>

// Nui Api
#include "NuiApi.h"

// My Header
#include "Kinect.h"

OzansKinect::Kinect::Kinect()
	:mNuiSensor(NULL)
{
}

OzansKinect::Kinect::~Kinect()
{
	if (mNuiSensor)
	{
		mNuiSensor->NuiShutdown();
	}
}

HRESULT OzansKinect::Kinect::Connection()
{
	INuiSensor* pNuiSensor;

	int iSensorCount = 0;
	HRESULT hr = NuiGetSensorCount(&iSensorCount);
	if (FAILED(hr))
	{
		return hr;
	}

	// Look at the kinect
	for (int i = 0; i < iSensorCount; ++i)
	{
		// Create a sensor for check
		hr = NuiCreateSensorByIndex(i, &pNuiSensor);
		if (FAILED(hr))
		{
			continue;
		}

		// Get the status sensor
		hr = pNuiSensor->NuiStatus();
		if (S_OK == hr)
		{
			mNuiSensor = pNuiSensor;
			break;
		}

		// We can release temproray variable
		pNuiSensor->Release();
	}

	if (mNuiSensor != NULL)
	{
		// Initialize the Kinect for skeleton mod
		mNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_SKELETON);
	}

	if (mNuiSensor == NULL || FAILED(hr))
	{
		std::cout << "Kinect not found!" << std::endl;
		return E_FAIL;

	}

	return hr;
}

HRESULT OzansKinect::Kinect::Process()
{
	NUI_SKELETON_FRAME skeletonFrame;

	HRESULT hr = mNuiSensor->NuiSkeletonGetNextFrame(0, &skeletonFrame);
	if (FAILED(hr))
	{
		return hr;
	}

	// Smooth skeleton data
	mNuiSensor->NuiTransformSmooth(&skeletonFrame, NULL);

	for (int i = 0; i < NUI_SKELETON_COUNT; i++)
	{
		NUI_SKELETON_TRACKING_STATE trackingState = skeletonFrame.SkeletonData[i].eTrackingState;
		if (trackingState == NUI_SKELETON_TRACKED)
		{
			for (int j = 0; j < 21; j++)
			{
				// Skeleton 21 points
				Vector4 organ = skeletonFrame.SkeletonData[i].SkeletonPositions[j];
				std::cout << "x" << organ.x << " y" << organ.y << " z" << organ.z << std::endl;
			}
		}
	}
	system("cls");

	return S_OK;
}<|endoftext|>


<commit_before><commit_msg>Maximum Product Subarray<commit_after><|endoftext|>


<commit_before>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "overlapgraph.h"

#define VERTEX_INACTIVE 0
#define VERTEX_ACTIVE 1
#define VERTEX_ELIMINATED -1
#define FUZZ 10

using namespace std;

OverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)
{
	reads = readvector;
	overlaps = overlapvector;
	initialize();
}

void OverlapGraph::initialize()
{
	graph.resize(reads.size());
	nonContainedReads.resize(reads.size());
	for(int i=0;i<overlaps.size();i++)
	{
		overlap o = overlaps[i];

		if(o.ahg > 0 & o.bhg > 0)
			graph[o.read1].push_back(o);
		else if(o.ahg < 0 & o.bhg < 0)
			graph[o.read2].push_back(o);
	}
}

void OverlapGraph::runUnitigging()
{
	int N = reads.size();

	//removing contained reads
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			overlap o = graph[i][j];
			nonContainedReads[o.read1] = 1;
			nonContainedReads[o.read2] = 1;
		}
	}

	int *vertexstatus = (int *)malloc(N*sizeof(int));
	memset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));
	vector< vector<bool> > reduceflags(N);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < graph[i].size(); j++)
			reduceflags[i].push_back(false);

	for (int I = 0; I < N; I++)
	{
		if (graph[I].size() == 0)
			continue;

		for (int j = 0; j < graph[I].size(); j++)
			vertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;

		int longest = 0;
		for (int j = 0; j < graph[I].size(); j++)
		{
			if (graph[I][j].bhg > longest)
				longest = graph[I][j].bhg;
		}

		longest += FUZZ;
		cout << longest << endl;

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)
			{
				int x = graph[I][j].read2;
				for (int k = 0; k < graph[x].size(); k++)
				{
					if (graph[I][j].bhg + graph[x][k].bhg <= longest)
					{
						if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
							vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
					}
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)
			{
				reduceflags[I][j] = true;
				//cout << "removed: " << graph[I][j].read1 + 1 << "->" << graph[I][j].read2 + 1 << endl;
			}
			vertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;
		}
	}

	for(int i=0;i<graph.size();i++)
    {
        for(int j=0;j<graph[i].size();j++)
        {
			if (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1])
                cout << graph[i][j].read1 << " -> " << graph[i][j].read2 << endl;
        }
    }

	free(vertexstatus);
	return;
}
<commit_msg>Added modification to reduction algorithm to handle fuzzy overlaps.<commit_after>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "overlapgraph.h"

#define VERTEX_INACTIVE 0
#define VERTEX_ACTIVE 1
#define VERTEX_ELIMINATED -1
#define FUZZ 10

using namespace std;

OverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)
{
	reads = readvector;
	overlaps = overlapvector;
	initialize();
}

void OverlapGraph::initialize()
{
	graph.resize(reads.size());
	nonContainedReads.resize(reads.size());
	for(int i=0;i<overlaps.size();i++)
	{
		overlap o = overlaps[i];

		if(o.ahg > 0 & o.bhg > 0)
			graph[o.read1].push_back(o);
		else if(o.ahg < 0 & o.bhg < 0)
			graph[o.read2].push_back(o);
	}
}

void OverlapGraph::runUnitigging()
{
	int N = reads.size();

	//removing contained reads
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			overlap o = graph[i][j];
			nonContainedReads[o.read1] = 1;
			nonContainedReads[o.read2] = 1;
		}
	}

	int *vertexstatus = (int *)malloc(N*sizeof(int));
	memset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));
	vector< vector<bool> > reduceflags(N);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < graph[i].size(); j++)
			reduceflags[i].push_back(false);

	for (int I = 0; I < N; I++)
	{
		if (graph[I].size() == 0)
			continue;

		for (int j = 0; j < graph[I].size(); j++)
			vertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;

		int longest = 0;
		for (int j = 0; j < graph[I].size(); j++)
		{
			if (graph[I][j].bhg > longest)
				longest = graph[I][j].bhg;
		}

		longest += FUZZ;
		cout << longest << endl;

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)
			{
				int x = graph[I][j].read2;
				for (int k = 0; k < graph[x].size(); k++)
				{
					if (graph[I][j].bhg + graph[x][k].bhg <= longest)
					{
						if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
							vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
					}
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			int x = graph[I][j].read2;
			for (int k = 0; k < graph[x].size(); k++)
			{
				if (graph[x][k].bhg < FUZZ)
				{
					if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
						vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)
			{
				reduceflags[I][j] = true;
				//cout << "removed: " << graph[I][j].read1 + 1 << "->" << graph[I][j].read2 + 1 << endl;
			}
			vertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;
		}
	}

	for(int i=0;i<graph.size();i++)
    {
        for(int j=0;j<graph[i].size();j++)
        {
			if (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1])
                cout << graph[i][j].read1 << " -> " << graph[i][j].read2 << endl;
        }
    }

	free(vertexstatus);
	return;
}
<|endoftext|>


<commit_before>#include <random>
#include <array>
#include "mpiCommon/MPICommon.h"
#include "ospray/ospray_cpp/Data.h"
#include "ospray/ospray_cpp/TransferFunction.h"
#include "ospray/ospray_cpp/Volume.h"
#include "raw_reader.h"
#include "generateSciVis.h"

namespace gensv {
  //TODO: factor this into a reusable piece inside of ospcommon!!!!!!
  // helper function to write the rendered image as PPM file
  void writePPM(const std::string &fileName,
                const int sizeX, const int sizeY,
                const uint32_t *pixel)
  {
    FILE *file = fopen(fileName.c_str(), "wb");
    fprintf(file, "P6\n%i %i\n255\n", sizeX, sizeY);
    unsigned char *out = (unsigned char *)alloca(3*sizeX);
    for (int y = 0; y < sizeY; y++) {
      auto *in = (const unsigned char *)&pixel[(sizeY-1-y)*sizeX];
      for (int x = 0; x < sizeX; x++) {
        out[3*x + 0] = in[4*x + 0];
        out[3*x + 1] = in[4*x + 1];
        out[3*x + 2] = in[4*x + 2];
      }
      fwrite(out, 3*sizeX, sizeof(char), file);
    }
    fprintf(file, "\n");
    fclose(file);
  }

  bool computeDivisor(int x, int &divisor) {
    int upperBound = std::sqrt(x);
    for (int i = 2; i <= upperBound; ++i) {
      if (x % i == 0) {
        divisor = i;
        return true;
      }
    }
    return false;
  }

  // Compute an X x Y x Z grid to have num bricks,
  // only gives a nice grid for numbers with even factors since
  // we don't search for factors of the number, we just try dividing by two
  vec3i computeGrid(int num)
  {
    vec3i grid(1);
    int axis = 0;
    int divisor = 0;
    while (computeDivisor(num, divisor)) {
      grid[axis] *= divisor;
      num /= divisor;
      axis = (axis + 1) % 3;
    }
    if (num != 1) {
      grid[axis] *= num;
    }
    return grid;
  }

  /* This function generates the rank's local geometry within its
   * volume's bounding box. The bbox represents say its simulation
   * or owned data region.
   */
  ospray::cpp::Geometry makeSpheres(const box3f &bbox, const size_t numSpheres,
                                    const float sphereRadius)
  {
    struct Sphere
    {
      vec3f org;
      int colorID {0};
    };

    auto numRanks = static_cast<float>(mpicommon::numGlobalRanks());
    auto myRank   = mpicommon::globalRank();

    std::vector<Sphere> spheres(numSpheres);

    std::mt19937 rng;
    rng.seed(std::random_device()());

    // Generate spheres within this nodes volume, to keep the data disjoint.
    // We also leave some buffer space on the boundaries to avoid clipping
    // artifacts or needing duplication across nodes in the case a sphere
    // crosses a boundary. Note: Since we don't communicated ghost regions
    // among the nodes, we make sure not to generate any spheres which would
    // be clipped.
    std::uniform_real_distribution<float> dist_x(bbox.lower.x + sphereRadius,
                                                 bbox.upper.x - sphereRadius);
    std::uniform_real_distribution<float> dist_y(bbox.lower.y + sphereRadius,
                                                 bbox.upper.y - sphereRadius);
    std::uniform_real_distribution<float> dist_z(bbox.lower.z + sphereRadius,
                                                 bbox.upper.z - sphereRadius);

    for (auto &s : spheres) {
      s.org.x = dist_x(rng);
      s.org.y = dist_y(rng);
      s.org.z = dist_z(rng);
    }

    ospray::cpp::Data sphere_data(numSpheres * sizeof(Sphere), OSP_UCHAR,
                                  spheres.data());

    const float r = (numRanks - myRank) / numRanks;
    const float b = myRank / numRanks;
    const float g = myRank > numRanks / 2 ? 2 * r : 2 * b;
    vec4f color(r, g, b, 1.f);
    ospray::cpp::Data color_data(1, OSP_FLOAT4, &color);

    ospray::cpp::Geometry geom("spheres");
    geom.set("spheres", sphere_data);
    geom.set("color", color_data);
    geom.set("offset_colorID", int(sizeof(vec3f)));
    geom.set("radius", sphereRadius);
    geom.commit();

    return geom;
  }

  enum GhostFace {
    NEITHER_FACE = 0,
    POS_FACE = 1,
    NEG_FACE = 1 << 1,
  };

  /* Compute which faces of this brick we need to specify ghost voxels for,
   * to have correct interpolation at brick boundaries. Returns mask of
   * GhostFaces for x, y, z.
   */
  std::array<int, 3> computeGhostFaces(const vec3i &brickId, const vec3i &grid) {
    std::array<int, 3> faces = {NEITHER_FACE, NEITHER_FACE, NEITHER_FACE};
    for (size_t i = 0; i < 3; ++i) {
      if (brickId[i] < grid[i] - 1) {
        faces[i] |= POS_FACE;
      }
      if (brickId[i] > 0) {
        faces[i] |= NEG_FACE;
      }
    }
    return faces;
  }

  /* Generate this rank's volume data. The volumes are placed in
   * cells of the grid computed in 'computeGrid' based on the number
   * of ranks with each rank owning a specific cell in the gridding.
   * The coloring is based on color-mapping the ranks id.
   * The region occupied by the volume is then used to be the rank's
   * overall region bounds and will be the bounding box for the
   * generated geometry as well.
   */
  std::pair<ospray::cpp::Volume, box3f> makeVolume(vec3f &ghostGridOrigin)
  {
    auto numRanks = static_cast<float>(mpicommon::numGlobalRanks());
    auto myRank   = mpicommon::globalRank();

    ospray::cpp::TransferFunction transferFcn("piecewise_linear");
    const std::vector<vec3f> colors = {
      vec3f(0, 0, 0.56),
      vec3f(0, 0, 1),
      vec3f(0, 1, 1),
      vec3f(0.5, 1, 0.5),
      vec3f(1, 1, 0),
      vec3f(1, 0, 0),
      vec3f(0.5, 0, 0)
    };
    const std::vector<float> opacities = {0.015, 0.015};
    ospray::cpp::Data colorsData(colors.size(), OSP_FLOAT3, colors.data());
    ospray::cpp::Data opacityData(opacities.size(), OSP_FLOAT, opacities.data());
    colorsData.commit();
    opacityData.commit();

    const vec2f valueRange(static_cast<float>(0), static_cast<float>(numRanks));
    transferFcn.set("colors", colorsData);
    transferFcn.set("opacities", opacityData);
    transferFcn.set("valueRange", valueRange);
    transferFcn.commit();

    const vec3i volumeDims(128);
    const vec3i grid = computeGrid(numRanks);
    const vec3f gridSpacing = vec3f(1.f) / (vec3f(grid) * vec3f(volumeDims));
    const vec3i brickId(myRank % grid.x, (myRank / grid.x) % grid.y, myRank / (grid.x * grid.y));
    const vec3f gridOrigin = vec3f(brickId) * gridSpacing * vec3f(volumeDims);
    const std::array<int, 3> ghosts = computeGhostFaces(brickId, grid);
    vec3i ghostDims(0);
    for (size_t i = 0; i < 3; ++i) {
      if (ghosts[i] & POS_FACE) {
        ghostDims[i] += 1;
      }
      if (ghosts[i] & NEG_FACE) {
        ghostDims[i] += 1;
      }
    }
    const vec3i fullDims = volumeDims + ghostDims;
    const vec3i ghostOffset(ghosts[0] & NEG_FACE ? 1 : 0,
                               ghosts[1] & NEG_FACE ? 1 : 0,
                               ghosts[2] & NEG_FACE ? 1 : 0);
    ghostGridOrigin = gridOrigin - vec3f(ghostOffset) * gridSpacing;

    ospray::cpp::Volume volume("block_bricked_volume");
    volume.set("voxelType", "uchar");
    volume.set("dimensions", fullDims);
    volume.set("transferFunction", transferFcn);
    volume.set("gridSpacing", gridSpacing);
    volume.set("gridOrigin", ghostGridOrigin);

    std::vector<unsigned char> volumeData(fullDims.x * fullDims.y * fullDims.z, 0);
    for (size_t i = 0; i < volumeData.size(); ++i) {
      volumeData[i] = myRank;
    }
    volume.setRegion(volumeData.data(), vec3i(0), fullDims);
    volume.commit();

    auto bbox = box3f(gridOrigin, gridOrigin + vec3f(1.f) / vec3f(grid));
    return std::make_pair(volume, bbox);
  }

  size_t sizeForDtype(const std::string &dtype) {
    if (dtype == "uchar" || dtype == "char") {
      return 1;
    }
    if (dtype == "float") {
      return 4;
    }
    if (dtype == "double") {
      return 8;
    }
  }

  std::pair<ospray::cpp::Volume, box3f> loadVolume(const FileName &file,
      const vec3i &dimensions, const std::string &dtype,
      const vec2f &valueRange, vec3f &ghostGridOrigin)
  {
    auto numRanks = static_cast<float>(mpicommon::numGlobalRanks());
    auto myRank   = mpicommon::globalRank();

    ospray::cpp::TransferFunction transferFcn("piecewise_linear");
    const std::vector<vec3f> colors = {
      vec3f(0, 0, 0.56),
      vec3f(0, 0, 1),
      vec3f(0, 1, 1),
      vec3f(0.5, 1, 0.5),
      vec3f(1, 1, 0),
      vec3f(1, 0, 0),
      vec3f(0.5, 0, 0)
    };
    const std::vector<float> opacities = {0.0, 1.0};
    ospray::cpp::Data colorsData(colors.size(), OSP_FLOAT3, colors.data());
    ospray::cpp::Data opacityData(opacities.size(), OSP_FLOAT, opacities.data());
    colorsData.commit();
    opacityData.commit();

    transferFcn.set("colors", colorsData);
    transferFcn.set("opacities", opacityData);
    transferFcn.set("valueRange", valueRange);
    transferFcn.commit();

    const vec3i grid = computeGrid(numRanks);
    const vec3i brickDims = dimensions / grid;
    const vec3i brickId(myRank % grid.x, (myRank / grid.x) % grid.y, myRank / (grid.x * grid.y));
    const vec3f gridOrigin = vec3f(brickId) * vec3f(brickDims);

    const std::array<int, 3> ghosts = computeGhostFaces(brickId, grid);
    vec3i ghostDims(0);
    for (size_t i = 0; i < 3; ++i) {
      if (ghosts[i] & POS_FACE) {
        ghostDims[i] += 1;
      }
      if (ghosts[i] & NEG_FACE) {
        ghostDims[i] += 1;
      }
    }
    const vec3i fullDims = brickDims + ghostDims;
    const vec3i ghostOffset(ghosts[0] & NEG_FACE ? 1 : 0,
                               ghosts[1] & NEG_FACE ? 1 : 0,
                               ghosts[2] & NEG_FACE ? 1 : 0);
    ghostGridOrigin = gridOrigin - vec3f(ghostOffset);

    ospray::cpp::Volume volume("block_bricked_volume");
    volume.set("voxelType", dtype.c_str());
    volume.set("dimensions", fullDims);
    volume.set("transferFunction", transferFcn);
    volume.set("gridOrigin", ghostGridOrigin);

    const size_t dtypeSize = sizeForDtype(dtype);
    std::vector<unsigned char> volumeData(fullDims.x * fullDims.y * fullDims.z * dtypeSize, 0);

    RawReader reader(file, dimensions, dtypeSize);
    reader.readRegion(brickId * brickDims - ghostOffset, fullDims, volumeData.data());
    volume.setRegion(volumeData.data(), vec3i(0), fullDims);
    volume.commit();

    auto bbox = box3f(gridOrigin, gridOrigin + vec3f(brickDims));
    return std::make_pair(volume, bbox);
  }

}

<commit_msg>don't make tfcn in gensv::loadVolume go to actual 0<commit_after>#include <random>
#include <array>
#include "mpiCommon/MPICommon.h"
#include "ospray/ospray_cpp/Data.h"
#include "ospray/ospray_cpp/TransferFunction.h"
#include "ospray/ospray_cpp/Volume.h"
#include "raw_reader.h"
#include "generateSciVis.h"

namespace gensv {
  //TODO: factor this into a reusable piece inside of ospcommon!!!!!!
  // helper function to write the rendered image as PPM file
  void writePPM(const std::string &fileName,
                const int sizeX, const int sizeY,
                const uint32_t *pixel)
  {
    FILE *file = fopen(fileName.c_str(), "wb");
    fprintf(file, "P6\n%i %i\n255\n", sizeX, sizeY);
    unsigned char *out = (unsigned char *)alloca(3*sizeX);
    for (int y = 0; y < sizeY; y++) {
      auto *in = (const unsigned char *)&pixel[(sizeY-1-y)*sizeX];
      for (int x = 0; x < sizeX; x++) {
        out[3*x + 0] = in[4*x + 0];
        out[3*x + 1] = in[4*x + 1];
        out[3*x + 2] = in[4*x + 2];
      }
      fwrite(out, 3*sizeX, sizeof(char), file);
    }
    fprintf(file, "\n");
    fclose(file);
  }

  bool computeDivisor(int x, int &divisor) {
    int upperBound = std::sqrt(x);
    for (int i = 2; i <= upperBound; ++i) {
      if (x % i == 0) {
        divisor = i;
        return true;
      }
    }
    return false;
  }

  // Compute an X x Y x Z grid to have num bricks,
  // only gives a nice grid for numbers with even factors since
  // we don't search for factors of the number, we just try dividing by two
  vec3i computeGrid(int num)
  {
    vec3i grid(1);
    int axis = 0;
    int divisor = 0;
    while (computeDivisor(num, divisor)) {
      grid[axis] *= divisor;
      num /= divisor;
      axis = (axis + 1) % 3;
    }
    if (num != 1) {
      grid[axis] *= num;
    }
    return grid;
  }

  /* This function generates the rank's local geometry within its
   * volume's bounding box. The bbox represents say its simulation
   * or owned data region.
   */
  ospray::cpp::Geometry makeSpheres(const box3f &bbox, const size_t numSpheres,
                                    const float sphereRadius)
  {
    struct Sphere
    {
      vec3f org;
      int colorID {0};
    };

    auto numRanks = static_cast<float>(mpicommon::numGlobalRanks());
    auto myRank   = mpicommon::globalRank();

    std::vector<Sphere> spheres(numSpheres);

    std::mt19937 rng;
    rng.seed(std::random_device()());

    // Generate spheres within this nodes volume, to keep the data disjoint.
    // We also leave some buffer space on the boundaries to avoid clipping
    // artifacts or needing duplication across nodes in the case a sphere
    // crosses a boundary. Note: Since we don't communicated ghost regions
    // among the nodes, we make sure not to generate any spheres which would
    // be clipped.
    std::uniform_real_distribution<float> dist_x(bbox.lower.x + sphereRadius,
                                                 bbox.upper.x - sphereRadius);
    std::uniform_real_distribution<float> dist_y(bbox.lower.y + sphereRadius,
                                                 bbox.upper.y - sphereRadius);
    std::uniform_real_distribution<float> dist_z(bbox.lower.z + sphereRadius,
                                                 bbox.upper.z - sphereRadius);

    for (auto &s : spheres) {
      s.org.x = dist_x(rng);
      s.org.y = dist_y(rng);
      s.org.z = dist_z(rng);
    }

    ospray::cpp::Data sphere_data(numSpheres * sizeof(Sphere), OSP_UCHAR,
                                  spheres.data());

    const float r = (numRanks - myRank) / numRanks;
    const float b = myRank / numRanks;
    const float g = myRank > numRanks / 2 ? 2 * r : 2 * b;
    vec4f color(r, g, b, 1.f);
    ospray::cpp::Data color_data(1, OSP_FLOAT4, &color);

    ospray::cpp::Geometry geom("spheres");
    geom.set("spheres", sphere_data);
    geom.set("color", color_data);
    geom.set("offset_colorID", int(sizeof(vec3f)));
    geom.set("radius", sphereRadius);
    geom.commit();

    return geom;
  }

  enum GhostFace {
    NEITHER_FACE = 0,
    POS_FACE = 1,
    NEG_FACE = 1 << 1,
  };

  /* Compute which faces of this brick we need to specify ghost voxels for,
   * to have correct interpolation at brick boundaries. Returns mask of
   * GhostFaces for x, y, z.
   */
  std::array<int, 3> computeGhostFaces(const vec3i &brickId, const vec3i &grid) {
    std::array<int, 3> faces = {NEITHER_FACE, NEITHER_FACE, NEITHER_FACE};
    for (size_t i = 0; i < 3; ++i) {
      if (brickId[i] < grid[i] - 1) {
        faces[i] |= POS_FACE;
      }
      if (brickId[i] > 0) {
        faces[i] |= NEG_FACE;
      }
    }
    return faces;
  }

  /* Generate this rank's volume data. The volumes are placed in
   * cells of the grid computed in 'computeGrid' based on the number
   * of ranks with each rank owning a specific cell in the gridding.
   * The coloring is based on color-mapping the ranks id.
   * The region occupied by the volume is then used to be the rank's
   * overall region bounds and will be the bounding box for the
   * generated geometry as well.
   */
  std::pair<ospray::cpp::Volume, box3f> makeVolume(vec3f &ghostGridOrigin)
  {
    auto numRanks = static_cast<float>(mpicommon::numGlobalRanks());
    auto myRank   = mpicommon::globalRank();

    ospray::cpp::TransferFunction transferFcn("piecewise_linear");
    const std::vector<vec3f> colors = {
      vec3f(0, 0, 0.56),
      vec3f(0, 0, 1),
      vec3f(0, 1, 1),
      vec3f(0.5, 1, 0.5),
      vec3f(1, 1, 0),
      vec3f(1, 0, 0),
      vec3f(0.5, 0, 0)
    };
    const std::vector<float> opacities = {0.015, 0.015};
    ospray::cpp::Data colorsData(colors.size(), OSP_FLOAT3, colors.data());
    ospray::cpp::Data opacityData(opacities.size(), OSP_FLOAT, opacities.data());
    colorsData.commit();
    opacityData.commit();

    const vec2f valueRange(static_cast<float>(0), static_cast<float>(numRanks));
    transferFcn.set("colors", colorsData);
    transferFcn.set("opacities", opacityData);
    transferFcn.set("valueRange", valueRange);
    transferFcn.commit();

    const vec3i volumeDims(128);
    const vec3i grid = computeGrid(numRanks);
    const vec3f gridSpacing = vec3f(1.f) / (vec3f(grid) * vec3f(volumeDims));
    const vec3i brickId(myRank % grid.x, (myRank / grid.x) % grid.y, myRank / (grid.x * grid.y));
    const vec3f gridOrigin = vec3f(brickId) * gridSpacing * vec3f(volumeDims);
    const std::array<int, 3> ghosts = computeGhostFaces(brickId, grid);
    vec3i ghostDims(0);
    for (size_t i = 0; i < 3; ++i) {
      if (ghosts[i] & POS_FACE) {
        ghostDims[i] += 1;
      }
      if (ghosts[i] & NEG_FACE) {
        ghostDims[i] += 1;
      }
    }
    const vec3i fullDims = volumeDims + ghostDims;
    const vec3i ghostOffset(ghosts[0] & NEG_FACE ? 1 : 0,
                               ghosts[1] & NEG_FACE ? 1 : 0,
                               ghosts[2] & NEG_FACE ? 1 : 0);
    ghostGridOrigin = gridOrigin - vec3f(ghostOffset) * gridSpacing;

    ospray::cpp::Volume volume("block_bricked_volume");
    volume.set("voxelType", "uchar");
    volume.set("dimensions", fullDims);
    volume.set("transferFunction", transferFcn);
    volume.set("gridSpacing", gridSpacing);
    volume.set("gridOrigin", ghostGridOrigin);

    std::vector<unsigned char> volumeData(fullDims.x * fullDims.y * fullDims.z, 0);
    for (size_t i = 0; i < volumeData.size(); ++i) {
      volumeData[i] = myRank;
    }
    volume.setRegion(volumeData.data(), vec3i(0), fullDims);
    volume.commit();

    auto bbox = box3f(gridOrigin, gridOrigin + vec3f(1.f) / vec3f(grid));
    return std::make_pair(volume, bbox);
  }

  size_t sizeForDtype(const std::string &dtype) {
    if (dtype == "uchar" || dtype == "char") {
      return 1;
    }
    if (dtype == "float") {
      return 4;
    }
    if (dtype == "double") {
      return 8;
    }
  }

  std::pair<ospray::cpp::Volume, box3f> loadVolume(const FileName &file,
      const vec3i &dimensions, const std::string &dtype,
      const vec2f &valueRange, vec3f &ghostGridOrigin)
  {
    auto numRanks = static_cast<float>(mpicommon::numGlobalRanks());
    auto myRank   = mpicommon::globalRank();

    ospray::cpp::TransferFunction transferFcn("piecewise_linear");
    const std::vector<vec3f> colors = {
      vec3f(0, 0, 0.56),
      vec3f(0, 0, 1),
      vec3f(0, 1, 1),
      vec3f(0.5, 1, 0.5),
      vec3f(1, 1, 0),
      vec3f(1, 0, 0),
      vec3f(0.5, 0, 0)
    };
    const std::vector<float> opacities = {0.0001, 1.0};
    ospray::cpp::Data colorsData(colors.size(), OSP_FLOAT3, colors.data());
    ospray::cpp::Data opacityData(opacities.size(), OSP_FLOAT, opacities.data());
    colorsData.commit();
    opacityData.commit();

    transferFcn.set("colors", colorsData);
    transferFcn.set("opacities", opacityData);
    transferFcn.set("valueRange", valueRange);
    transferFcn.commit();

    const vec3i grid = computeGrid(numRanks);
    const vec3i brickDims = dimensions / grid;
    const vec3i brickId(myRank % grid.x, (myRank / grid.x) % grid.y, myRank / (grid.x * grid.y));
    const vec3f gridOrigin = vec3f(brickId) * vec3f(brickDims);

    const std::array<int, 3> ghosts = computeGhostFaces(brickId, grid);
    vec3i ghostDims(0);
    for (size_t i = 0; i < 3; ++i) {
      if (ghosts[i] & POS_FACE) {
        ghostDims[i] += 1;
      }
      if (ghosts[i] & NEG_FACE) {
        ghostDims[i] += 1;
      }
    }
    const vec3i fullDims = brickDims + ghostDims;
    const vec3i ghostOffset(ghosts[0] & NEG_FACE ? 1 : 0,
                               ghosts[1] & NEG_FACE ? 1 : 0,
                               ghosts[2] & NEG_FACE ? 1 : 0);
    ghostGridOrigin = gridOrigin - vec3f(ghostOffset);

    ospray::cpp::Volume volume("block_bricked_volume");
    volume.set("voxelType", dtype.c_str());
    volume.set("dimensions", fullDims);
    volume.set("transferFunction", transferFcn);
    volume.set("gridOrigin", ghostGridOrigin);

    const size_t dtypeSize = sizeForDtype(dtype);
    std::vector<unsigned char> volumeData(fullDims.x * fullDims.y * fullDims.z * dtypeSize, 0);

    RawReader reader(file, dimensions, dtypeSize);
    reader.readRegion(brickId * brickDims - ghostOffset, fullDims, volumeData.data());
    volume.setRegion(volumeData.data(), vec3i(0), fullDims);
    volume.commit();

    auto bbox = box3f(gridOrigin, gridOrigin + vec3f(brickDims));
    return std::make_pair(volume, bbox);
  }

}

<|endoftext|>


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

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_data.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
#include "modules/planning/planner/em/decider.h"
#include "modules/planning/tasks/dp_poly_path/dp_poly_path_optimizer.h"
#include "modules/planning/tasks/dp_st_speed/dp_st_speed_optimizer.h"
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h"
#include "modules/planning/tasks/qp_spline_st_speed/qp_spline_st_speed_optimizer.h"
#include "modules/planning/tasks/traffic_decider/traffic_decider.h"

namespace apollo {
namespace planning {

using common::Status;
using common::adapter::AdapterManager;
using common::time::Clock;
using common::ErrorCode;
using common::SpeedPoint;
using common::SLPoint;
using common::TrajectoryPoint;
using common::VehicleState;
using common::math::Vec2d;

void EMPlanner::RegisterTasks() {
  task_factory_.Register(TRAFFIC_DECIDER, []() -> Task* {
    return new TrafficDecider(TaskType_Name(TRAFFIC_DECIDER));
  });
  task_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Task* {
    return new DpPolyPathOptimizer(TaskType_Name(DP_POLY_PATH_OPTIMIZER));
  });
  task_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Task* {
    return new DpStSpeedOptimizer(TaskType_Name(DP_ST_SPEED_OPTIMIZER));
  });
  task_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Task* {
    return new QpSplinePathOptimizer(TaskType_Name(QP_SPLINE_PATH_OPTIMIZER));
  });
  task_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Task* {
    return new QpSplineStSpeedOptimizer(
        TaskType_Name(QP_SPLINE_ST_SPEED_OPTIMIZER));
  });
}

Status EMPlanner::Init(const PlanningConfig& config) {
  AINFO << "In EMPlanner::Init()";
  RegisterTasks();
  for (const auto task : config.em_planner_config().task()) {
    tasks_.emplace_back(
        task_factory_.CreateObject(static_cast<TaskType>(task)));
    AINFO << "Created task:" << tasks_.back()->name();
  }
  for (auto& task : tasks_) {
    if (!task->Init(config)) {
      std::string msg(
          common::util::StrCat("Init task[", task->name(), "] failed."));
      AERROR << msg;
      return Status(ErrorCode::PLANNING_ERROR, msg);
    }
  }
  return Status::OK();
}

void EMPlanner::RecordDebugInfo(const std::string& name,
                                const double time_diff_ms,
                                planning::LatencyStats* ptr_latency_stats) {
  if (!FLAGS_enable_record_debug) {
    ADEBUG << "Skip record debug info";
    return;
  }
  TaskType type;
  DCHECK(TaskType_Parse(name, &type));

  auto ptr_stats = ptr_latency_stats->add_task_stats();
  ptr_stats->set_name(name);
  ptr_stats->set_time_ms(time_diff_ms);
}

void EMPlanner::PopulateDecision(const ReferenceLineInfo& reference_line_info,
                                 Frame* frame) {
  auto* planning_pb = frame->MutableADCTrajectory();
  Decider decider;
  planning_pb->mutable_decision()->CopyFrom(
      decider.MakeDecision(reference_line_info));
}

Status EMPlanner::Plan(const TrajectoryPoint& planning_start_point,
                       Frame* frame, ReferenceLineInfo* reference_line_info) {
  if (!frame) {
    AERROR << "Frame is empty in EMPlanner";
    return Status(ErrorCode::PLANNING_ERROR, "Frame is null");
  }

  ADEBUG << "planning start point:" << planning_start_point.DebugString();
  auto* planning_data = reference_line_info->mutable_planning_data();
  auto* heuristic_speed_data = planning_data->mutable_speed_data();
  auto speed_profile =
      GenerateInitSpeedProfile(planning_start_point, reference_line_info);
  if (speed_profile.empty()) {
    speed_profile = GenerateSpeedHotStart(planning_start_point);
    AINFO << "Using dummy hot start for speed vector";
  }
  heuristic_speed_data->set_speed_vector(speed_profile);

  auto ptr_debug = frame->MutableADCTrajectory()->mutable_debug();
  auto ptr_latency_stats =
      frame->MutableADCTrajectory()->mutable_latency_stats();
  for (auto& optimizer : tasks_) {
    const double start_timestamp = Clock::NowInSecond();
    auto ret = optimizer->Execute(frame, reference_line_info);
    if (!ret.ok()) {
      AERROR << "Failed to run tasks[" << optimizer->name()
             << "], Error message: " << ret.error_message();
      return ret;
    }
    const double end_timestamp = Clock::NowInSecond();
    const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;

    ADEBUG << "after optimizer " << optimizer->name() << ":"
           << planning_data->DebugString() << std::endl;
    ADEBUG << optimizer->name() << " time spend: " << time_diff_ms << " ms.";

    if (FLAGS_enable_record_debug && ptr_debug != nullptr &&
        ptr_latency_stats != nullptr) {
      RecordDebugInfo(optimizer->name(), time_diff_ms, ptr_latency_stats);
    }
  }
  DiscretizedTrajectory trajectory;
  if (!planning_data->CombinePathAndSpeedProfile(
          FLAGS_output_trajectory_time_resolution,
          planning_start_point.relative_time(), &trajectory)) {
    std::string msg("Fail to aggregate planning trajectory.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  reference_line_info->SetTrajectory(trajectory);

  PopulateDecision(*reference_line_info, frame);

  // Add debug information.
  if (FLAGS_enable_record_debug && ptr_debug != nullptr) {
    auto* reference_line = ptr_debug->mutable_planning_data()->add_path();
    reference_line->set_name("planning_reference_line");
    const auto& reference_points =
        reference_line_info->reference_line().reference_points();
    for (const auto& reference_point : reference_points) {
      auto* path_point = reference_line->add_path_point();
      path_point->set_x(reference_point.x());
      path_point->set_y(reference_point.y());
      path_point->set_theta(reference_point.heading());
      path_point->set_kappa(reference_point.kappa());
      path_point->set_dkappa(reference_point.dkappa());
    }
  }
  return Status::OK();
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const common::TrajectoryPoint& planning_init_point,
    const ReferenceLineInfo* reference_line_info) {
  std::vector<SpeedPoint> speed_profile;
  const auto* last_frame = FrameHistory::instance()->Latest();
  if (!last_frame) {
    AWARN << "last frame is empty";
    return speed_profile;
  }
  const ReferenceLineInfo* last_reference_line_info = nullptr;
  auto reference_line_id = reference_line_info->Id();
  for (const auto& ref_info : last_frame->reference_line_info()) {
    // WARNING: weak association between reference lines of two frames.
    if (ref_info.Id() == reference_line_id) {
      last_reference_line_info = &ref_info;
      break;
    }
  }
  if (!last_reference_line_info) {
    AERROR << "last reference line info is empty";
    return speed_profile;
  }
  const auto& last_speed_vector =
      last_reference_line_info->planning_data().speed_data().speed_vector();

  if (!last_speed_vector.empty()) {
    const auto& last_init_point = last_frame->PlanningStartPoint().path_point();
    Vec2d last_xy_point = {last_init_point.x(), last_init_point.y()};
    SLPoint last_sl_point;
    if (!last_reference_line_info->reference_line().get_point_in_frenet_frame(
            last_xy_point, &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }
    Vec2d xy_point = {planning_init_point.path_point().x(),
                      planning_init_point.path_point().y()};
    SLPoint sl_point;
    if (!last_reference_line_info->reference_line().get_point_in_frenet_frame(
            xy_point, &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }
    double s_diff = sl_point.s() - last_sl_point.s();
    double start_time = 0.0;
    double start_s = 0.0;
    bool is_updated_start = false;
    for (const auto& speed_point : last_speed_vector) {
      if (speed_point.s() < s_diff) {
        continue;
      }
      if (!is_updated_start) {
        start_time = speed_point.t();
        start_s = speed_point.s();
        is_updated_start = true;
      }
      SpeedPoint refined_speed_point;
      refined_speed_point.set_s(speed_point.s() - start_s);
      refined_speed_point.set_t(speed_point.t() - start_time);
      refined_speed_point.set_v(speed_point.v());
      refined_speed_point.set_a(speed_point.a());
      refined_speed_point.set_da(speed_point.da());
      speed_profile.push_back(refined_speed_point);
    }
  }
  return speed_profile;
}

// This is a dummy simple hot start, need refine later
std::vector<common::SpeedPoint> EMPlanner::GenerateSpeedHotStart(
    const common::TrajectoryPoint& planning_init_point) {
  std::vector<common::SpeedPoint> speed_profile;
  std::array<double, 3> start_state;

  // distance 0.0
  start_state[0] = 0.0;

  // start velocity
  start_state[1] = planning_init_point.v();

  // start acceleration
  start_state[2] = planning_init_point.a();

  std::array<double, 2> end_state;
  // end state velocity
  end_state[0] = 10.0;

  // end state acceleration
  end_state[1] = 0.0;

  // pre assume the curve time is 8 second, can be change later
  QuarticPolynomialCurve1d speed_curve(start_state, end_state,
                                       FLAGS_trajectory_time_length);
  // assume the time resolution is 0.1
  std::uint32_t num_time_steps =
      static_cast<std::uint32_t>(FLAGS_trajectory_time_length /
                                 FLAGS_trajectory_time_resolution) + 1;
  speed_profile.reserve(num_time_steps);

  for (std::uint32_t i = 0; i < num_time_steps; ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double s = speed_curve.Evaluate(0, t);
    double v = speed_curve.Evaluate(1, t);
    double a = speed_curve.Evaluate(2, t);
    double da = speed_curve.Evaluate(3, t);
    SpeedPoint speed_point;
    speed_point.set_s(s);
    speed_point.set_t(t);
    speed_point.set_v(v);
    speed_point.set_a(a);
    speed_point.set_da(da);
    speed_profile.push_back(std::move(speed_point));
  }
  return speed_profile;
}

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

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_data.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
#include "modules/planning/planner/em/decider.h"
#include "modules/planning/tasks/dp_poly_path/dp_poly_path_optimizer.h"
#include "modules/planning/tasks/dp_st_speed/dp_st_speed_optimizer.h"
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h"
#include "modules/planning/tasks/qp_spline_st_speed/qp_spline_st_speed_optimizer.h"
#include "modules/planning/tasks/traffic_decider/traffic_decider.h"

namespace apollo {
namespace planning {

using common::Status;
using common::adapter::AdapterManager;
using common::time::Clock;
using common::ErrorCode;
using common::SpeedPoint;
using common::SLPoint;
using common::TrajectoryPoint;
using common::VehicleState;
using common::math::Vec2d;

void EMPlanner::RegisterTasks() {
  task_factory_.Register(TRAFFIC_DECIDER, []() -> Task* {
    return new TrafficDecider(TaskType_Name(TRAFFIC_DECIDER));
  });
  task_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Task* {
    return new DpPolyPathOptimizer(TaskType_Name(DP_POLY_PATH_OPTIMIZER));
  });
  task_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Task* {
    return new DpStSpeedOptimizer(TaskType_Name(DP_ST_SPEED_OPTIMIZER));
  });
  task_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Task* {
    return new QpSplinePathOptimizer(TaskType_Name(QP_SPLINE_PATH_OPTIMIZER));
  });
  task_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Task* {
    return new QpSplineStSpeedOptimizer(
        TaskType_Name(QP_SPLINE_ST_SPEED_OPTIMIZER));
  });
}

Status EMPlanner::Init(const PlanningConfig& config) {
  AINFO << "In EMPlanner::Init()";
  RegisterTasks();
  for (const auto task : config.em_planner_config().task()) {
    tasks_.emplace_back(
        task_factory_.CreateObject(static_cast<TaskType>(task)));
    AINFO << "Created task:" << tasks_.back()->name();
  }
  for (auto& task : tasks_) {
    if (!task->Init(config)) {
      std::string msg(
          common::util::StrCat("Init task[", task->name(), "] failed."));
      AERROR << msg;
      return Status(ErrorCode::PLANNING_ERROR, msg);
    }
  }
  return Status::OK();
}

void EMPlanner::RecordDebugInfo(const std::string& name,
                                const double time_diff_ms,
                                planning::LatencyStats* ptr_latency_stats) {
  if (!FLAGS_enable_record_debug) {
    ADEBUG << "Skip record debug info";
    return;
  }
  TaskType type;
  DCHECK(TaskType_Parse(name, &type));

  auto ptr_stats = ptr_latency_stats->add_task_stats();
  ptr_stats->set_name(name);
  ptr_stats->set_time_ms(time_diff_ms);
}

void EMPlanner::PopulateDecision(const ReferenceLineInfo& reference_line_info,
                                 Frame* frame) {
  auto* planning_pb = frame->MutableADCTrajectory();
  Decider decider;
  planning_pb->mutable_decision()->CopyFrom(
      decider.MakeDecision(reference_line_info));
}

Status EMPlanner::Plan(const TrajectoryPoint& planning_start_point,
                       Frame* frame, ReferenceLineInfo* reference_line_info) {
  if (!frame) {
    AERROR << "Frame is empty in EMPlanner";
    return Status(ErrorCode::PLANNING_ERROR, "Frame is null");
  }

  ADEBUG << "planning start point:" << planning_start_point.DebugString();
  auto* planning_data = reference_line_info->mutable_planning_data();
  auto* heuristic_speed_data = planning_data->mutable_speed_data();
  auto speed_profile =
      GenerateInitSpeedProfile(planning_start_point, reference_line_info);
  if (speed_profile.empty()) {
    speed_profile = GenerateSpeedHotStart(planning_start_point);
    AINFO << "Using dummy hot start for speed vector";
  }
  heuristic_speed_data->set_speed_vector(speed_profile);

  auto ptr_debug = frame->MutableADCTrajectory()->mutable_debug();
  auto ptr_latency_stats =
      frame->MutableADCTrajectory()->mutable_latency_stats();
  for (auto& optimizer : tasks_) {
    const double start_timestamp = Clock::NowInSecond();
    auto ret = optimizer->Execute(frame, reference_line_info);
    if (!ret.ok()) {
      AERROR << "Failed to run tasks[" << optimizer->name()
             << "], Error message: " << ret.error_message();
      return ret;
    }
    const double end_timestamp = Clock::NowInSecond();
    const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;

    ADEBUG << "after optimizer " << optimizer->name() << ":"
           << planning_data->DebugString() << std::endl;
    ADEBUG << optimizer->name() << " time spend: " << time_diff_ms << " ms.";

    if (FLAGS_enable_record_debug && ptr_debug != nullptr &&
        ptr_latency_stats != nullptr) {
      RecordDebugInfo(optimizer->name(), time_diff_ms, ptr_latency_stats);
    }
  }
  DiscretizedTrajectory trajectory;
  if (!planning_data->CombinePathAndSpeedProfile(
          FLAGS_output_trajectory_time_resolution,
          planning_start_point.relative_time(), &trajectory)) {
    std::string msg("Fail to aggregate planning trajectory.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }
  reference_line_info->SetTrajectory(trajectory);

  PopulateDecision(*reference_line_info, frame);

  // Add debug information.
  if (FLAGS_enable_record_debug && ptr_debug != nullptr) {
    auto* reference_line = ptr_debug->mutable_planning_data()->add_path();
    reference_line->set_name("planning_reference_line");
    const auto& reference_points =
        reference_line_info->reference_line().reference_points();
    for (const auto& reference_point : reference_points) {
      auto* path_point = reference_line->add_path_point();
      path_point->set_x(reference_point.x());
      path_point->set_y(reference_point.y());
      path_point->set_theta(reference_point.heading());
      path_point->set_kappa(reference_point.kappa());
      path_point->set_dkappa(reference_point.dkappa());
    }
  }
  return Status::OK();
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const common::TrajectoryPoint& planning_init_point,
    const ReferenceLineInfo* reference_line_info) {
  std::vector<SpeedPoint> speed_profile;
  const auto* last_frame = FrameHistory::instance()->Latest();
  if (!last_frame) {
    AWARN << "last frame is empty";
    return speed_profile;
  }
  const ReferenceLineInfo* last_reference_line_info = nullptr;
  auto reference_line_id = reference_line_info->Id();
  for (const auto& ref_info : last_frame->reference_line_info()) {
    // WARNING: weak association between reference lines of two frames.
    if (ref_info.Id() == reference_line_id) {
      last_reference_line_info = &ref_info;
      break;
    }
  }
  if (!last_reference_line_info) {
    AERROR << "last reference line info is empty";
    return speed_profile;
  }
  const auto& last_speed_vector =
      last_reference_line_info->planning_data().speed_data().speed_vector();

  if (!last_speed_vector.empty()) {
    const auto& last_init_point = last_frame->PlanningStartPoint().path_point();
    Vec2d last_xy_point(last_init_point.x(), last_init_point.y());
    SLPoint last_sl_point;
    if (!last_reference_line_info->reference_line().get_point_in_frenet_frame(
            last_xy_point, &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }

    Vec2d xy_point(planning_init_point.path_point().x(),
                   planning_init_point.path_point().y());
    SLPoint sl_point;
    if (!last_reference_line_info->reference_line().get_point_in_frenet_frame(
            xy_point, &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }
    double s_diff = sl_point.s() - last_sl_point.s();
    double start_time = 0.0;
    double start_s = 0.0;
    bool is_updated_start = false;
    for (const auto& speed_point : last_speed_vector) {
      if (speed_point.s() < s_diff) {
        continue;
      }
      if (!is_updated_start) {
        start_time = speed_point.t();
        start_s = speed_point.s();
        is_updated_start = true;
      }
      SpeedPoint refined_speed_point;
      refined_speed_point.set_s(speed_point.s() - start_s);
      refined_speed_point.set_t(speed_point.t() - start_time);
      refined_speed_point.set_v(speed_point.v());
      refined_speed_point.set_a(speed_point.a());
      refined_speed_point.set_da(speed_point.da());
      speed_profile.push_back(std::move(refined_speed_point));
    }
  }
  return speed_profile;
}

// This is a dummy simple hot start, need refine later
std::vector<common::SpeedPoint> EMPlanner::GenerateSpeedHotStart(
    const common::TrajectoryPoint& planning_init_point) {
  std::array<double, 3> start_state;

  // distance 0.0
  start_state[0] = 0.0;

  // start velocity
  start_state[1] = planning_init_point.v();

  // start acceleration
  start_state[2] = planning_init_point.a();

  std::array<double, 2> end_state;
  // end state velocity
  end_state[0] = std::max(10.0, planning_init_point.v());

  // end state acceleration
  end_state[1] = 0.0;

  QuarticPolynomialCurve1d speed_profile(start_state, end_state,
                                       FLAGS_trajectory_time_length);
  // assume the time resolution is 0.1
  std::uint32_t num_time_steps =
      static_cast<std::uint32_t>(FLAGS_trajectory_time_length /
                                 FLAGS_trajectory_time_resolution) + 1;

  std::vector<common::SpeedPoint> discretized_speed_profile;
  discretized_speed_profile.reserve(num_time_steps);
  for (std::uint32_t i = 0; i < num_time_steps; ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double s = speed_profile.Evaluate(0, t);
    double v = speed_profile.Evaluate(1, t);
    double a = speed_profile.Evaluate(2, t);
    double da = speed_profile.Evaluate(3, t);
    SpeedPoint speed_point;
    speed_point.set_s(s);
    speed_point.set_t(t);
    speed_point.set_v(v);
    speed_point.set_a(a);
    speed_point.set_da(da);
    discretized_speed_profile.push_back(std::move(speed_point));
  }
  return discretized_speed_profile;
}

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