<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 "views/controls/textfield/textfield.h"

#if defined(OS_LINUX)
#include <gdk/gdkkeysyms.h>
#endif

#include "app/gfx/insets.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#include "base/win_util.h"
#endif

#include "base/string_util.h"
#include "views/controls/textfield/native_textfield_wrapper.h"
#include "views/widget/widget.h"

#if defined(OS_WIN)
// TODO(beng): this should be removed when the OS_WIN hack from
// ViewHierarchyChanged is removed.
#include "views/controls/textfield/native_textfield_win.h"
#endif

namespace views {

// static
const char Textfield::kViewClassName[] = "views/Textfield";

/////////////////////////////////////////////////////////////////////////////
// Textfield

Textfield::Textfield()
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(STYLE_DEFAULT),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      text_color_(SK_ColorBLACK),
      background_color_(SK_ColorWHITE),
      use_default_text_color_(true),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::Textfield(StyleFlags style)
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(style),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      text_color_(SK_ColorBLACK),
      background_color_(SK_ColorWHITE),
      use_default_text_color_(true),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::~Textfield() {
}

void Textfield::SetController(Controller* controller) {
  controller_ = controller;
}

Textfield::Controller* Textfield::GetController() const {
  return controller_;
}

void Textfield::SetReadOnly(bool read_only) {
  read_only_ = read_only;
  if (native_wrapper_) {
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateTextColor();
    native_wrapper_->UpdateBackgroundColor();
  }
}

bool Textfield::IsPassword() const {
  return style_ & STYLE_PASSWORD;
}

bool Textfield::IsMultiLine() const {
  return !!(style_ & STYLE_MULTILINE);
}

void Textfield::SetText(const string16& text) {
  text_ = text;
  if (native_wrapper_)
    native_wrapper_->UpdateText();
}

void Textfield::AppendText(const string16& text) {
  text_ += text;
  if (native_wrapper_)
    native_wrapper_->AppendText(text);
}

void Textfield::SelectAll() {
  if (native_wrapper_)
    native_wrapper_->SelectAll();
}

string16 Textfield::GetSelectedText() const {
  if (native_wrapper_)
    return native_wrapper_->GetSelectedText();
  return string16();
}

void Textfield::ClearSelection() const {
  if (native_wrapper_)
    native_wrapper_->ClearSelection();
}

void Textfield::SetTextColor(SkColor color) {
  text_color_ = color;
  use_default_text_color_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateTextColor();
}

void Textfield::UseDefaultTextColor() {
  use_default_text_color_ = true;
  if (native_wrapper_)
    native_wrapper_->UpdateTextColor();
}

void Textfield::SetBackgroundColor(SkColor color) {
  background_color_ = color;
  use_default_background_color_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::UseDefaultBackgroundColor() {
  use_default_background_color_ = true;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::SetFont(const gfx::Font& font) {
  font_ = font;
  if (native_wrapper_)
    native_wrapper_->UpdateFont();
}

void Textfield::SetHorizontalMargins(int left, int right) {
  if (native_wrapper_)
    native_wrapper_->SetHorizontalMargins(left, right);
}

void Textfield::SetHeightInLines(int num_lines) {
  DCHECK(IsMultiLine());
  num_lines_ = num_lines;
}

void Textfield::RemoveBorder() {
  if (!draw_border_)
    return;

  draw_border_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBorder();
}

void Textfield::CalculateInsets(gfx::Insets* insets) {
  DCHECK(insets);

  if (!draw_border_)
    return;

  // NOTE: One would think GetThemeMargins would return the insets we should
  // use, but it doesn't. The margins returned by GetThemeMargins are always
  // 0.

  // This appears to be the insets used by Windows.
  insets->Set(3, 3, 3, 3);
}

void Textfield::SyncText() {
  if (native_wrapper_)
    text_ = native_wrapper_->GetText();
}

////////////////////////////////////////////////////////////////////////////////
// Textfield, View overrides:

void Textfield::Layout() {
  if (native_wrapper_) {
    native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));
    native_wrapper_->GetView()->Layout();
  }
}

gfx::Size Textfield::GetPreferredSize() {
  gfx::Insets insets;
  CalculateInsets(&insets);
  return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +
                       insets.width(),
                   num_lines_ * font_.height() + insets.height());
}

bool Textfield::IsFocusable() const {
  return IsEnabled() && !read_only_;
}

void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {
  SelectAll();
}

bool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {
#if defined(OS_WIN)
  // TODO(hamaji): Figure out which keyboard combinations we need to add here,
  //               similar to LocationBarView::SkipDefaultKeyEventProcessing.
  const int c = e.GetCharacter();
  if (c == VK_BACK)
    return true;  // We'll handle BackSpace ourselves.

  // We don't translate accelerators for ALT + NumPad digit, they are used for
  // entering special characters.  We do translate alt-home.
  if (e.IsAltDown() && (c != VK_HOME) &&
      win_util::IsNumPadDigit(c, e.IsExtendedKey()))
    return true;
#endif
  return false;
}

void Textfield::SetEnabled(bool enabled) {
  View::SetEnabled(enabled);
  if (native_wrapper_)
    native_wrapper_->UpdateEnabled();
}

void Textfield::Focus() {
  if (native_wrapper_) {
    // Forward the focus to the wrapper if it exists.
    native_wrapper_->SetFocus();
  } else {
    // If there is no wrapper, cause the RootView to be focused so that we still
    // get keyboard messages.
    View::Focus();
  }
}

void Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {
    initialized_ = true;

    // The native wrapper's lifetime will be managed by the view hierarchy after
    // we call AddChildView.
    native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);
    AddChildView(native_wrapper_->GetView());
    // TODO(beng): Move this initialization to NativeTextfieldWin once it
    //             subclasses NativeControlWin.
    native_wrapper_->UpdateText();
    native_wrapper_->UpdateTextColor();
    native_wrapper_->UpdateBackgroundColor();
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateFont();
    native_wrapper_->UpdateEnabled();
    native_wrapper_->UpdateBorder();

#if defined(OS_WIN)
    // TODO(beng): remove this once NativeTextfieldWin subclasses
    // NativeControlWin. This is currently called to perform post-AddChildView
    // initialization for the wrapper. The GTK version subclasses things
    // correctly and doesn't need this.
    //
    // Remove the include for native_textfield_win.h above when you fix this.
    static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();
#endif
  }
}

std::string Textfield::GetClassName() const {
  return kViewClassName;
}

NativeTextfieldWrapper* Textfield::CreateWrapper() {
  NativeTextfieldWrapper* native_wrapper =
      NativeTextfieldWrapper::CreateWrapper(this);

  native_wrapper->UpdateText();
  native_wrapper->UpdateBackgroundColor();
  native_wrapper->UpdateReadOnly();
  native_wrapper->UpdateFont();
  native_wrapper->UpdateEnabled();
  native_wrapper->UpdateBorder();

  return native_wrapper;
}

base::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {
#if defined(OS_WIN)
  return static_cast<base::KeyboardCode>(key_);
#else
  return static_cast<base::KeyboardCode>(event_.keyval);
#endif
}

#if defined(OS_WIN)
bool Textfield::Keystroke::IsControlHeld() const {
  return win_util::IsCtrlPressed();
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return win_util::IsShiftPressed();
}
#else
bool Textfield::Keystroke::IsControlHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_CONTROL_MASK;
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_SHIFT_MASK;
}
#endif

}  // namespace views
<commit_msg>fix Linux views 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 "views/controls/textfield/textfield.h"

#if defined(OS_LINUX)
#include <gdk/gdkkeysyms.h>
#endif

#include "app/gfx/insets.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#include "base/win_util.h"
#endif

#include "base/string_util.h"
#include "views/controls/textfield/native_textfield_wrapper.h"
#include "views/widget/widget.h"

#if defined(OS_WIN)
// TODO(beng): this should be removed when the OS_WIN hack from
// ViewHierarchyChanged is removed.
#include "views/controls/textfield/native_textfield_win.h"
#endif

namespace views {

// static
const char Textfield::kViewClassName[] = "views/Textfield";

/////////////////////////////////////////////////////////////////////////////
// Textfield

Textfield::Textfield()
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(STYLE_DEFAULT),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      text_color_(SK_ColorBLACK),
      use_default_text_color_(true),
      background_color_(SK_ColorWHITE),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::Textfield(StyleFlags style)
    : native_wrapper_(NULL),
      controller_(NULL),
      style_(style),
      read_only_(false),
      default_width_in_chars_(0),
      draw_border_(true),
      text_color_(SK_ColorBLACK),
      use_default_text_color_(true),
      background_color_(SK_ColorWHITE),
      use_default_background_color_(true),
      num_lines_(1),
      initialized_(false) {
  SetFocusable(true);
}

Textfield::~Textfield() {
}

void Textfield::SetController(Controller* controller) {
  controller_ = controller;
}

Textfield::Controller* Textfield::GetController() const {
  return controller_;
}

void Textfield::SetReadOnly(bool read_only) {
  read_only_ = read_only;
  if (native_wrapper_) {
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateTextColor();
    native_wrapper_->UpdateBackgroundColor();
  }
}

bool Textfield::IsPassword() const {
  return style_ & STYLE_PASSWORD;
}

bool Textfield::IsMultiLine() const {
  return !!(style_ & STYLE_MULTILINE);
}

void Textfield::SetText(const string16& text) {
  text_ = text;
  if (native_wrapper_)
    native_wrapper_->UpdateText();
}

void Textfield::AppendText(const string16& text) {
  text_ += text;
  if (native_wrapper_)
    native_wrapper_->AppendText(text);
}

void Textfield::SelectAll() {
  if (native_wrapper_)
    native_wrapper_->SelectAll();
}

string16 Textfield::GetSelectedText() const {
  if (native_wrapper_)
    return native_wrapper_->GetSelectedText();
  return string16();
}

void Textfield::ClearSelection() const {
  if (native_wrapper_)
    native_wrapper_->ClearSelection();
}

void Textfield::SetTextColor(SkColor color) {
  text_color_ = color;
  use_default_text_color_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateTextColor();
}

void Textfield::UseDefaultTextColor() {
  use_default_text_color_ = true;
  if (native_wrapper_)
    native_wrapper_->UpdateTextColor();
}

void Textfield::SetBackgroundColor(SkColor color) {
  background_color_ = color;
  use_default_background_color_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::UseDefaultBackgroundColor() {
  use_default_background_color_ = true;
  if (native_wrapper_)
    native_wrapper_->UpdateBackgroundColor();
}

void Textfield::SetFont(const gfx::Font& font) {
  font_ = font;
  if (native_wrapper_)
    native_wrapper_->UpdateFont();
}

void Textfield::SetHorizontalMargins(int left, int right) {
  if (native_wrapper_)
    native_wrapper_->SetHorizontalMargins(left, right);
}

void Textfield::SetHeightInLines(int num_lines) {
  DCHECK(IsMultiLine());
  num_lines_ = num_lines;
}

void Textfield::RemoveBorder() {
  if (!draw_border_)
    return;

  draw_border_ = false;
  if (native_wrapper_)
    native_wrapper_->UpdateBorder();
}

void Textfield::CalculateInsets(gfx::Insets* insets) {
  DCHECK(insets);

  if (!draw_border_)
    return;

  // NOTE: One would think GetThemeMargins would return the insets we should
  // use, but it doesn't. The margins returned by GetThemeMargins are always
  // 0.

  // This appears to be the insets used by Windows.
  insets->Set(3, 3, 3, 3);
}

void Textfield::SyncText() {
  if (native_wrapper_)
    text_ = native_wrapper_->GetText();
}

////////////////////////////////////////////////////////////////////////////////
// Textfield, View overrides:

void Textfield::Layout() {
  if (native_wrapper_) {
    native_wrapper_->GetView()->SetBounds(GetLocalBounds(true));
    native_wrapper_->GetView()->Layout();
  }
}

gfx::Size Textfield::GetPreferredSize() {
  gfx::Insets insets;
  CalculateInsets(&insets);
  return gfx::Size(font_.GetExpectedTextWidth(default_width_in_chars_) +
                       insets.width(),
                   num_lines_ * font_.height() + insets.height());
}

bool Textfield::IsFocusable() const {
  return IsEnabled() && !read_only_;
}

void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) {
  SelectAll();
}

bool Textfield::SkipDefaultKeyEventProcessing(const KeyEvent& e) {
#if defined(OS_WIN)
  // TODO(hamaji): Figure out which keyboard combinations we need to add here,
  //               similar to LocationBarView::SkipDefaultKeyEventProcessing.
  const int c = e.GetCharacter();
  if (c == VK_BACK)
    return true;  // We'll handle BackSpace ourselves.

  // We don't translate accelerators for ALT + NumPad digit, they are used for
  // entering special characters.  We do translate alt-home.
  if (e.IsAltDown() && (c != VK_HOME) &&
      win_util::IsNumPadDigit(c, e.IsExtendedKey()))
    return true;
#endif
  return false;
}

void Textfield::SetEnabled(bool enabled) {
  View::SetEnabled(enabled);
  if (native_wrapper_)
    native_wrapper_->UpdateEnabled();
}

void Textfield::Focus() {
  if (native_wrapper_) {
    // Forward the focus to the wrapper if it exists.
    native_wrapper_->SetFocus();
  } else {
    // If there is no wrapper, cause the RootView to be focused so that we still
    // get keyboard messages.
    View::Focus();
  }
}

void Textfield::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && !native_wrapper_ && GetWidget() && !initialized_) {
    initialized_ = true;

    // The native wrapper's lifetime will be managed by the view hierarchy after
    // we call AddChildView.
    native_wrapper_ = NativeTextfieldWrapper::CreateWrapper(this);
    AddChildView(native_wrapper_->GetView());
    // TODO(beng): Move this initialization to NativeTextfieldWin once it
    //             subclasses NativeControlWin.
    native_wrapper_->UpdateText();
    native_wrapper_->UpdateTextColor();
    native_wrapper_->UpdateBackgroundColor();
    native_wrapper_->UpdateReadOnly();
    native_wrapper_->UpdateFont();
    native_wrapper_->UpdateEnabled();
    native_wrapper_->UpdateBorder();

#if defined(OS_WIN)
    // TODO(beng): remove this once NativeTextfieldWin subclasses
    // NativeControlWin. This is currently called to perform post-AddChildView
    // initialization for the wrapper. The GTK version subclasses things
    // correctly and doesn't need this.
    //
    // Remove the include for native_textfield_win.h above when you fix this.
    static_cast<NativeTextfieldWin*>(native_wrapper_)->AttachHack();
#endif
  }
}

std::string Textfield::GetClassName() const {
  return kViewClassName;
}

NativeTextfieldWrapper* Textfield::CreateWrapper() {
  NativeTextfieldWrapper* native_wrapper =
      NativeTextfieldWrapper::CreateWrapper(this);

  native_wrapper->UpdateText();
  native_wrapper->UpdateBackgroundColor();
  native_wrapper->UpdateReadOnly();
  native_wrapper->UpdateFont();
  native_wrapper->UpdateEnabled();
  native_wrapper->UpdateBorder();

  return native_wrapper;
}

base::KeyboardCode Textfield::Keystroke::GetKeyboardCode() const {
#if defined(OS_WIN)
  return static_cast<base::KeyboardCode>(key_);
#else
  return static_cast<base::KeyboardCode>(event_.keyval);
#endif
}

#if defined(OS_WIN)
bool Textfield::Keystroke::IsControlHeld() const {
  return win_util::IsCtrlPressed();
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return win_util::IsShiftPressed();
}
#else
bool Textfield::Keystroke::IsControlHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_CONTROL_MASK;
}

bool Textfield::Keystroke::IsShiftHeld() const {
  return (event_.state & gtk_accelerator_get_default_mod_mask()) ==
      GDK_SHIFT_MASK;
}
#endif

}  // namespace views
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *
 *  \author Nico Blodow (blodow@cs.tum.edu), Julius Kammerl (julius@kammerl.de)
 * */

#include "pcl/octree/octree.h"
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <iostream>

#include <vtkCubeSource.h>

/////////////////////////////////////////////////////////////////////////////
// Create a vtkSmartPointer object containing a cube
vtkSmartPointer<vtkPolyData>
GetCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ)
{
  vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New ();
  cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ);
  return cube->GetOutput ();
}

/////////////////////////////////////////////////////////////////////////////
// Create vtkActorCollection of vtkSmartPointers describing octree cubes
void
GetOctreeActors (std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> >& voxelCenters, double voxelSideLen, vtkSmartPointer<vtkActorCollection> coll)
{

  vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New ();

  size_t i;
  double s = voxelSideLen/2.0;

  for (i = 0; i < voxelCenters.size (); i++)
  {

    double x = voxelCenters[i].x;
    double y = voxelCenters[i].y;
    double z = voxelCenters[i].z;

    treeWireframe->AddInput (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s));
  }

  vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New ();

  vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
  mapper->SetInput (treeWireframe->GetOutput ());
  treeActor->SetMapper (mapper);

  treeActor->GetProperty ()->SetRepresentationToWireframe ();
  treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0);
  treeActor->GetProperty ()->SetLineWidth (2);
  coll->AddItem (treeActor);
}

////////////////////////////////////////////////////////////////////////////////
// Create a vtkPolyData object from a set of vtkPoints
vtkDataSet*
  createDataSetFromVTKPoints (vtkPoints *points)
{
  vtkCellArray *verts = vtkCellArray::New ();
  vtkPolyData *data   = vtkPolyData::New  ();
  // Iterate through the points
  for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++)
    verts->InsertNextCell ((vtkIdType)1, &i);
  data->SetPoints (points);
  data->SetVerts (verts);
  return data;
}

/////////////////////////////////////////////////////////////////////////////
// Create vtkActorCollection of vtkSmartPointers describing input points
void
  GetPointActors (pcl::PointCloud<pcl::PointXYZ>& cloud, vtkSmartPointer<vtkActorCollection> coll)
{
  vtkPolyData* points_poly;

  size_t i;

  vtkPoints *octreeLeafPoints = vtkPoints::New ();

  // add all points from octree to vtkPoint object
  for (i=0; i< cloud.points.size(); i++) {
    octreeLeafPoints->InsertNextPoint (cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);
  }
  points_poly = (vtkPolyData*)createDataSetFromVTKPoints(octreeLeafPoints);

  vtkSmartPointer<vtkActor> pointsActor = vtkSmartPointer<vtkActor>::New ();

  vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
  mapper->SetInput (points_poly);
  pointsActor->SetMapper (mapper);

  pointsActor->GetProperty ()->SetColor (1.0, 0.0, 0.0);
  pointsActor->GetProperty ()->SetPointSize (4);
  coll->AddItem (pointsActor);

}

void
printHelp (int argc, char **argv)
{
  std::cout << "Syntax is " << argv[0] << " <file_name.pcd> <octree resolution> \n";
  std::cout << "Example: ./octree_viewer ../../test/bunny.pcd 0.02 \n";

  exit(1);
}

/////////////////////////////////////////////////////////////////////////////
// MAIN
/* ---[ */
int
  main (int argc, char** argv)
{

  if (argc!=3) {
    printHelp(argc, argv);
  }

  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
  pcl::io::loadPCDFile (argv[1], *cloud);

  vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New ();

  vtkRenderer* ren = vtkRenderer::New ();

  // create octree from pointcloud
  pcl::octree::OctreePointCloud<pcl::PointXYZ> octree (atof (argv[2]));
  octree.setInputCloud (cloud);
  octree.addPointsFromInputCloud ();

  // get vector of voxel centers from octree
  double voxelSideLen;
  std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> > voxelCenters;
  octree.getOccupiedVoxelCenters (voxelCenters);
  voxelSideLen = sqrt (octree.getVoxelSquaredSideLen ());

  // delete octree
  octree.deleteTree();

  // generate voxel boxes
  GetOctreeActors ( voxelCenters, voxelSideLen, coll);

  // visualize point input
  GetPointActors ( *cloud, coll);

  vtkActor* a;
  coll->InitTraversal ();
  a = coll->GetNextActor ();
  while(a!=0)
  {
    ren->AddActor (a);
    a = coll->GetNextActor ();
  }

  // Create Renderer and Interractor
  ren->SetBackground (1.0, 1.0, 1.0);

  vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New ();
  vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New ();
  win->AddRenderer (ren);

  iren->SetRenderWindow (win);
  iren->Start ();
}
<commit_msg>no window is opened in octree_viewer on Windows<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *
 *  \author Nico Blodow (blodow@cs.tum.edu), Julius Kammerl (julius@kammerl.de)
 * */

#include "pcl/octree/octree.h"
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <iostream>

#include <vtkCubeSource.h>

/////////////////////////////////////////////////////////////////////////////
// Create a vtkSmartPointer object containing a cube
vtkSmartPointer<vtkPolyData>
GetCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ)
{
  vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New ();
  cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ);
  return cube->GetOutput ();
}

/////////////////////////////////////////////////////////////////////////////
// Create vtkActorCollection of vtkSmartPointers describing octree cubes
void
GetOctreeActors (std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> >& voxelCenters, double voxelSideLen, vtkSmartPointer<vtkActorCollection> coll)
{

  vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New ();

  size_t i;
  double s = voxelSideLen/2.0;

  for (i = 0; i < voxelCenters.size (); i++)
  {

    double x = voxelCenters[i].x;
    double y = voxelCenters[i].y;
    double z = voxelCenters[i].z;

    treeWireframe->AddInput (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s));
  }

  vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New ();

  vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
  mapper->SetInput (treeWireframe->GetOutput ());
  treeActor->SetMapper (mapper);

  treeActor->GetProperty ()->SetRepresentationToWireframe ();
  treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0);
  treeActor->GetProperty ()->SetLineWidth (2);
  coll->AddItem (treeActor);
}

////////////////////////////////////////////////////////////////////////////////
// Create a vtkPolyData object from a set of vtkPoints
vtkDataSet*
  createDataSetFromVTKPoints (vtkPoints *points)
{
  vtkCellArray *verts = vtkCellArray::New ();
  vtkPolyData *data   = vtkPolyData::New  ();
  // Iterate through the points
  for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++)
    verts->InsertNextCell ((vtkIdType)1, &i);
  data->SetPoints (points);
  data->SetVerts (verts);
  return data;
}

/////////////////////////////////////////////////////////////////////////////
// Create vtkActorCollection of vtkSmartPointers describing input points
void
  GetPointActors (pcl::PointCloud<pcl::PointXYZ>& cloud, vtkSmartPointer<vtkActorCollection> coll)
{
  vtkPolyData* points_poly;

  size_t i;

  vtkPoints *octreeLeafPoints = vtkPoints::New ();

  // add all points from octree to vtkPoint object
  for (i=0; i< cloud.points.size(); i++) {
    octreeLeafPoints->InsertNextPoint (cloud.points[i].x, cloud.points[i].y, cloud.points[i].z);
  }
  points_poly = (vtkPolyData*)createDataSetFromVTKPoints(octreeLeafPoints);

  vtkSmartPointer<vtkActor> pointsActor = vtkSmartPointer<vtkActor>::New ();

  vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New ();
  mapper->SetInput (points_poly);
  pointsActor->SetMapper (mapper);

  pointsActor->GetProperty ()->SetColor (1.0, 0.0, 0.0);
  pointsActor->GetProperty ()->SetPointSize (4);
  coll->AddItem (pointsActor);

}

void
printHelp (int argc, char **argv)
{
  std::cout << "Syntax is " << argv[0] << " <file_name.pcd> <octree resolution> \n";
  std::cout << "Example: ./octree_viewer ../../test/bunny.pcd 0.02 \n";

  exit(1);
}

/////////////////////////////////////////////////////////////////////////////
// MAIN
/* ---[ */
int
  main (int argc, char** argv)
{

  if (argc!=3) {
    printHelp(argc, argv);
  }

  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
  pcl::io::loadPCDFile (argv[1], *cloud);

  vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New ();

  vtkRenderer* ren = vtkRenderer::New ();

  // create octree from pointcloud
  pcl::octree::OctreePointCloud<pcl::PointXYZ> octree (atof (argv[2]));
  octree.setInputCloud (cloud);
  octree.addPointsFromInputCloud ();

  // get vector of voxel centers from octree
  double voxelSideLen;
  std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> > voxelCenters;
  octree.getOccupiedVoxelCenters (voxelCenters);
  voxelSideLen = sqrt (octree.getVoxelSquaredSideLen ());

  // delete octree
  octree.deleteTree();

  // generate voxel boxes
  GetOctreeActors ( voxelCenters, voxelSideLen, coll);

  // visualize point input
  GetPointActors ( *cloud, coll);

  vtkActor* a;
  coll->InitTraversal ();
  a = coll->GetNextActor ();
  while(a!=0)
  {
    ren->AddActor (a);
    a = coll->GetNextActor ();
  }

  // Create Renderer and Interractor
  ren->SetBackground (1.0, 1.0, 1.0);

  vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New ();
  vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New ();
  win->AddRenderer (ren);

  iren->SetRenderWindow (win);
  win->Render ();
  iren->Start ();
}
<|endoftext|>


<commit_before>/*
 *  variable.cpp - implementation of the dynamically derived value container compare.
 *  Copyright (C) 2001, Ron Steinke
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Contact:  Joseph Zupko
 *            jaz147@psu.edu
 *
 *            189 Reese St.
 *            Old Forge, PA 18518
 */

#include <string>
#include <varconf/dyncmp.h>

namespace varconf {
namespace dynvar {

Compare& Compare::operator=( const Compare& c)
{
  VarBase::operator=(c);
  m_v1 = c.m_v1;
  m_v2 = c.m_v2;
}

void Compare::set_val()
{
  if(m_v1.is_bool() && m_v2.is_bool())
    VarBase::operator=(bool_cmp(bool(m_v1), bool(m_v2)));
  else if(m_v1.is_int() && m_v2.is_int())
    VarBase::operator=(int_cmp(int(m_v1), int(m_v2)));
  else if(m_v1.is_double() && m_v2.is_double())
    VarBase::operator=(double_cmp(double(m_v1), double(m_v2)));
  else if(m_v1.is_string() && m_v2.is_string()) {
    std::string s1 = std::string(m_v1), s2 = std::string(m_v2);
    VarBase::operator=(string_cmp(s1, s2));
  }
  else
    VarBase::operator=(VarBase()); // Set it invalid
}

}} // namespace varconf::dynvar
<commit_msg>BUGFIX Tsk tsk.  Added a missing return statement to this piece of ancient code.  Probably unused anyway but hey.<commit_after>/*
 *  variable.cpp - implementation of the dynamically derived value container compare.
 *  Copyright (C) 2001, Ron Steinke
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Contact:  Joseph Zupko
 *            jaz147@psu.edu
 *
 *            189 Reese St.
 *            Old Forge, PA 18518
 */

#include <string>
#include <varconf/dyncmp.h>

namespace varconf {
namespace dynvar {

Compare& Compare::operator=( const Compare& c)
{
  VarBase::operator=(c);
  m_v1 = c.m_v1;
  m_v2 = c.m_v2;
  return *this;
}

void Compare::set_val()
{
  if(m_v1.is_bool() && m_v2.is_bool())
    VarBase::operator=(bool_cmp(bool(m_v1), bool(m_v2)));
  else if(m_v1.is_int() && m_v2.is_int())
    VarBase::operator=(int_cmp(int(m_v1), int(m_v2)));
  else if(m_v1.is_double() && m_v2.is_double())
    VarBase::operator=(double_cmp(double(m_v1), double(m_v2)));
  else if(m_v1.is_string() && m_v2.is_string()) {
    std::string s1 = std::string(m_v1), s2 = std::string(m_v2);
    VarBase::operator=(string_cmp(s1, s2));
  }
  else
    VarBase::operator=(VarBase()); // Set it invalid
}

}} // namespace varconf::dynvar
<|endoftext|>


<commit_before><commit_msg>SessionManagerClient::open need not be exported<commit_after><|endoftext|>


<commit_before>#ifndef UPPER_LOWER_CASE_CONVERTER
#define UPPER_LOWER_CASE_CONVERTER

#include "ConversionInterface.hpp"

namespace protobuf_decoder
{

class UpperLowerCaseConverter : public ConversionInterface
{
public:

    virtual std::string encode(const std::string& iDecodedString);

    virtual std::string decode(const std::string& iEncodedString);

    virtual void setEncodeAlgorithm(const std::string& iAlgoName);

    virtual void setMessagePath(const std::string& iMessagePath);

};

}

#endif // UPPER_LOWER_CASE_CONVERTER
<commit_msg>Delete UpperLowerCaseConverter.hpp<commit_after><|endoftext|>


<commit_before>#include "control.h"

void switch_allele(char* str)
{
	switch(*str)
	{
		case 'A':
			*str = 'T';
			break;
		case 'T':
			*str = 'A';
			break;
		case 'C':
			*str = 'G';
			break;
		case 'G':
			*str = 'C';
			break;
		/*case '1':
			*str = '2';
			break;
		case '2':
			*str = '1';
			break;*/
	}
}

void frequency(int total_people, int** chr, int num_of_chrs)
{//http://pngu.mgh.harvard.edu/~purcell/plink/binary.shtml BED file format
	char pattern[CHAR_MAX_LENGTH+1]="";char pattern1[CHAR_MAX_LENGTH+1]="";

	ifstream input_bim, input_fre;
	ofstream output_fre;
	input_bim.open(BIM,ios::in);
	output_fre.open("fre_result.freq",ios::out);

	bool external_freq_or_not;
	streamoff position;

	extern char Freq_ext_result[150];
	if(strcmp(Freq_ext_result,"0") == 0)
	{
		//cout<<"--"<<Freq_ext_result<<"--"<<endl;getchar();
		external_freq_or_not = false;
	}
	else
	{
		//cout<<"=="<<Freq_ext_result<<"=="<<endl;getchar();
		external_freq_or_not = true;
		input_fre.open(Freq_ext_result,ios::in);
		input_fre.getline(pattern, CHAR_MAX_LENGTH);//first line is useless
		position = input_fre.tellg();
	}
	//===============================================set propriate pre-fetch array size
	int remain_people = total_people%4;
	int boundary;//for last byte
	int const_need_per_marker;//byte
		if(remain_people != 0)
		{
			const_need_per_marker = total_people/4 + 1;
			boundary = remain_people*2;
		}
		else
		{
			const_need_per_marker = total_people/4;
			boundary = 8;
		}
	//===============================================calculate total markers
	int total_marker = 0;
	FILE* input_bed = fopen(BED,"r");
	bitset<8> a_byte;//represent 4 people
	fgets(pattern, 3+1, input_bed);//first 3 bytes is for special use

	for(int i=0;i<num_of_chrs;i++)
	{
		char buffer[50];
		sprintf (buffer, "metadata%d.ped", chr[i][0]);
		ofstream output_ped;
		output_ped.open(buffer,ios::out);

		int total_marker_for_chr = chr[i][1];
		total_marker += chr[i][1];
		//cout<<num_of_chrs;getchar();
		//cout<<total_marker_for_chr;getchar();
		//===============================================
		int num_pre_fetch_marker = 1;//decide_prefetch_chrs_once(chr,num_of_chrs,const_need_per_marker);//一次處理幾個marker
		int pre_fetch_size = num_pre_fetch_marker*const_need_per_marker;
		while(total_marker_for_chr)//共幾個marker
		{
			memset(pattern,0,sizeof(pattern));
			fread((void*)pattern, 1, pre_fetch_size, input_bed);
			for(int h=0;h<num_pre_fetch_marker;h++)//依序處理marker
			{
				char* _tmp;
				string string1;
				char* _tmp_A[2];
				{
					input_bim.getline(pattern1, CHAR_MAX_LENGTH);
					//if(!strtok(pattern," 	,")) break;
					_tmp = strtok(pattern1, " 	");
					//cout<<_tmp<<"=="<<strlen(_tmp)<<endl;
					_tmp = strtok(NULL, " 	");
					//cout<<_tmp<<"=="<<strlen(_tmp)<<endl;
					//allele_count[3] = atoi(_tmp);//NAME
					string1 = _tmp;
					//cout<<string1;getchar();
					//cout<<atoi(_tmp)<<" "<<endl;
					_tmp = strtok(NULL, " 	");
					_tmp = strtok(NULL, " 	");
					//cout<<_tmp;getchar();
					_tmp_A[0] = strtok(NULL, " 	");
					_tmp_A[1] = strtok(NULL, " 	");
					//cout<<_tmp_A[0]<<" "<<endl;cout<<_tmp_A[1]<<" "<<endl;getchar();
				}
				//===================
				int start = const_need_per_marker*h;
				int end = start + const_need_per_marker -1;
				double allele_count[4]={0};//two alleles: (A,T,C,G,1,2), missing, NAME
				{
					//leave last byte to another handle
					for(int k=start;k<end;k++)
					{
						a_byte = pattern[k];
						for(int ii=0;ii<8;ii+=2)
						{
							if(a_byte[ii]==1 && a_byte[ii+1]==0)
							{
								allele_count[2]+=2;
								output_ped<<"0 0 ";
							}
							else for(int jj=ii;jj<ii+2;jj++)
							{
								allele_count[a_byte[jj]]++;
								output_ped<<_tmp_A[a_byte[jj]]<<" ";
							}
						}
					}
					//for last byte
					a_byte = pattern[end];
					for(int ii=0;ii<boundary;ii+=2)
					{
						if(a_byte[ii]==1 && a_byte[ii+1]==0)
						{
							allele_count[2]+=2;
							output_ped<<"0 0 ";
						}
						else for(int jj=ii;jj<ii+2;jj++)
						{
							allele_count[a_byte[jj]]++;
							output_ped<<_tmp_A[a_byte[jj]]<<" ";
						}
					}
					output_ped<<endl;//end of a marker
				}
				//cout<<allele_count[0]<<" "<<allele_count[1]<<" "<<allele_count[2]<<endl;
				if(allele_count[0]+allele_count[1]+allele_count[2] != total_people*2) cout<<"some errors occur!!"<<endl;

				int allele_sample_space = total_people*2-allele_count[2];
				if(allele_sample_space == 0)
				{
					allele_count[0] = allele_count[1] = 0;
				}
				else
				{
					allele_count[0] = allele_count[0]/allele_sample_space;
					allele_count[1] = 1-allele_count[0];
				}
				//===================
				if(external_freq_or_not)//use external freq file or not
				{
					char* tmp;
					string string2;
					char* tmp_A[2];
					input_fre.clear();
					input_fre.seekg(position);
					do{
						input_fre.getline(pattern, CHAR_MAX_LENGTH);
						tmp = strtok(pattern, " 	");
						if(!tmp) break;
						tmp = strtok(NULL, " 	");
						string2 = tmp;
						//cout<<string2;getchar();
					}
					while(string1.compare(string2)!=0);
					if(string1.compare(string2)==0)
					{
						position = input_fre.tellg();
						//cout<<"hit!!!!!!!!!!!!!!!!!!!!!"<<endl;getchar();
						tmp_A[0] = strtok(NULL, " 	");
						tmp_A[1] = strtok(NULL, " 	");

						int match_valid;
						if(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;//ok
						else if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;//ok
						else
						{
							switch_allele(tmp_A[0]);
							switch_allele(tmp_A[1]);
							match_valid = 0;
							if(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;//ok
							else if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;//ok
						}
						if(match_valid)//marker is matched in ASN.freq
						{
							tmp = strtok(NULL, " 	");//MAF
							double MAF = atof(tmp);

							double n1 = allele_sample_space/2;//n1
							tmp = strtok(NULL, " 	");
							double n2 = atoi(tmp);//n2

							if(match_valid == 1)
							{
								allele_count[0] = allele_count[0]*(n1/(n1+n2)) + MAF*(n2/(n1+n2));
								allele_count[1] = allele_count[1]*(n1/(n1+n2)) + (1-MAF)*(n2/(n1+n2));
							}
							else if(match_valid == 2)
							{
								allele_count[0] = allele_count[0]*(n1/(n1+n2)) + (1-MAF)*(n2/(n1+n2));
								allele_count[1] = allele_count[1]*(n1/(n1+n2)) + (MAF)*(n2/(n1+n2));
							}
						}
						else
						{
							//frequency.snp
						}
					}
					else {}//no matched marker in ASN.freq
				}
				//===================
				//output_fre<<"M "<<allele_count[3]<<endl;
				output_fre<<"M "<<string1<<endl;
				//cout      <<"M "<<string1<<endl;
				for(int i=0;i<2;i++)
				{
					if(allele_count[i]>0)
					{
						output_fre<<"A "<<(_tmp_A[i])<<" "<<allele_count[i]<<endl;
						//cout      <<"A "<<(_tmp_A[i])<<" "<<allele_count[i]<<endl;
					}
				}
			}
			//cout<<total_marker_for_chr<<endl;getchar();
			total_marker_for_chr -= num_pre_fetch_marker;
		}
		output_ped.close();
	}
	//cout<<total_marker<<endl;getchar();//1000,4737983
	if(external_freq_or_not) input_fre.close();
	//===============================================
	fclose(input_bed);
	input_bim.close();
	output_fre.close();
}<commit_msg>modify frequency calculation formula<commit_after>#include "control.h"

void switch_allele(char* str)
{
	switch(*str)
	{
		case 'A':
			*str = 'T';
			break;
		case 'T':
			*str = 'A';
			break;
		case 'C':
			*str = 'G';
			break;
		case 'G':
			*str = 'C';
			break;
		/*case '1':
			*str = '2';
			break;
		case '2':
			*str = '1';
			break;*/
	}
}

void frequency(int total_people, int** chr, int num_of_chrs)
{//http://pngu.mgh.harvard.edu/~purcell/plink/binary.shtml BED file format
	char pattern[CHAR_MAX_LENGTH+1]="";char pattern1[CHAR_MAX_LENGTH+1]="";

	ifstream input_bim, input_fre;
	ofstream output_fre;
	input_bim.open(BIM,ios::in);
	output_fre.open("fre_result.freq",ios::out);

	bool external_freq_or_not;
	streamoff position;

	extern char Freq_ext_result[150];
	if(strcmp(Freq_ext_result,"0") == 0)
	{
		//cout<<"--"<<Freq_ext_result<<"--"<<endl;getchar();
		external_freq_or_not = false;
	}
	else
	{
		//cout<<"=="<<Freq_ext_result<<"=="<<endl;getchar();
		external_freq_or_not = true;
		input_fre.open(Freq_ext_result,ios::in);
		input_fre.getline(pattern, CHAR_MAX_LENGTH);//first line is useless
		position = input_fre.tellg();
	}
	//===============================================set propriate pre-fetch array size
	int remain_people = total_people%4;
	int boundary;//for last byte
	int const_need_per_marker;//byte
		if(remain_people != 0)
		{
			const_need_per_marker = total_people/4 + 1;
			boundary = remain_people*2;
		}
		else
		{
			const_need_per_marker = total_people/4;
			boundary = 8;
		}
	//===============================================calculate total markers
	int total_marker = 0;
	FILE* input_bed = fopen(BED,"r");
	bitset<8> a_byte;//represent 4 people
	fgets(pattern, 3+1, input_bed);//first 3 bytes is for special use

	for(int i=0;i<num_of_chrs;i++)
	{
		char buffer[50];
		sprintf (buffer, "metadata%d.ped", chr[i][0]);
		ofstream output_ped;
		output_ped.open(buffer,ios::out);

		int total_marker_for_chr = chr[i][1];
		total_marker += chr[i][1];
		//cout<<num_of_chrs;getchar();
		//cout<<total_marker_for_chr;getchar();
		//===============================================
		int num_pre_fetch_marker = 1;//decide_prefetch_chrs_once(chr,num_of_chrs,const_need_per_marker);//一次處理幾個marker
		int pre_fetch_size = num_pre_fetch_marker*const_need_per_marker;
		while(total_marker_for_chr)//共幾個marker
		{
			memset(pattern,0,sizeof(pattern));
			fread((void*)pattern, 1, pre_fetch_size, input_bed);
			for(int h=0;h<num_pre_fetch_marker;h++)//依序處理marker
			{
				char* _tmp;
				string string1;
				char* _tmp_A[2];
				{
					input_bim.getline(pattern1, CHAR_MAX_LENGTH);
					//if(!strtok(pattern," 	,")) break;
					_tmp = strtok(pattern1, " 	");
					//cout<<_tmp<<"=="<<strlen(_tmp)<<endl;
					_tmp = strtok(NULL, " 	");
					//cout<<_tmp<<"=="<<strlen(_tmp)<<endl;
					//allele_count[3] = atoi(_tmp);//NAME
					string1 = _tmp;
					//cout<<string1;getchar();
					//cout<<atoi(_tmp)<<" "<<endl;
					_tmp = strtok(NULL, " 	");
					_tmp = strtok(NULL, " 	");
					//cout<<_tmp;getchar();
					_tmp_A[0] = strtok(NULL, " 	");
					_tmp_A[1] = strtok(NULL, " 	");
					//cout<<_tmp_A[0]<<" "<<endl;cout<<_tmp_A[1]<<" "<<endl;getchar();
				}
				//===================
				int start = const_need_per_marker*h;
				int end = start + const_need_per_marker -1;
				double allele_count[4]={0};//two alleles: (A,T,C,G,1,2), missing, NAME
				{
					//leave last byte to another handle
					for(int k=start;k<end;k++)
					{
						a_byte = pattern[k];
						for(int ii=0;ii<8;ii+=2)
						{
							if(a_byte[ii]==1 && a_byte[ii+1]==0)
							{
								allele_count[2]+=2;
								output_ped<<"0 0 ";
							}
							else for(int jj=ii;jj<ii+2;jj++)
							{
								allele_count[a_byte[jj]]++;
								output_ped<<_tmp_A[a_byte[jj]]<<" ";
							}
						}
					}
					//for last byte
					a_byte = pattern[end];
					for(int ii=0;ii<boundary;ii+=2)
					{
						if(a_byte[ii]==1 && a_byte[ii+1]==0)
						{
							allele_count[2]+=2;
							output_ped<<"0 0 ";
						}
						else for(int jj=ii;jj<ii+2;jj++)
						{
							allele_count[a_byte[jj]]++;
							output_ped<<_tmp_A[a_byte[jj]]<<" ";
						}
					}
					output_ped<<endl;//end of a marker
				}
				//cout<<allele_count[0]<<" "<<allele_count[1]<<" "<<allele_count[2]<<endl;
				if(allele_count[0]+allele_count[1]+allele_count[2] != total_people*2) cout<<"some errors occur!!"<<endl;

				int allele_sample_space = total_people*2-allele_count[2];
				if(allele_sample_space == 0)
				{
					allele_count[0] = allele_count[1] = 0;
				}
				else
				{
					allele_count[0] = allele_count[0]/allele_sample_space;
					allele_count[1] = 1-allele_count[0];
				}
				//===================
				if(external_freq_or_not)//use external freq file or not
				{
					char* tmp;
					string string2;
					char* tmp_A[2];
					input_fre.clear();
					input_fre.seekg(position);
					do{
						input_fre.getline(pattern, CHAR_MAX_LENGTH);
						tmp = strtok(pattern, " 	");
						if(!tmp) break;
						tmp = strtok(NULL, " 	");
						string2 = tmp;
						//cout<<string2;getchar();
					}
					while(string1.compare(string2)!=0);
					if(string1.compare(string2)==0)
					{
						position = input_fre.tellg();
						//cout<<"hit!!!!!!!!!!!!!!!!!!!!!"<<endl;getchar();
						tmp_A[0] = strtok(NULL, " 	");
						tmp_A[1] = strtok(NULL, " 	");

						int match_valid;
						if(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;//ok
						else if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;//ok
						else
						{
							switch_allele(tmp_A[0]);
							switch_allele(tmp_A[1]);
							match_valid = 0;
							if(strcmp(_tmp_A[0],tmp_A[0]) == 0 && strcmp(_tmp_A[1],tmp_A[1]) == 0) match_valid = 1;//ok
							else if(strcmp(_tmp_A[0],tmp_A[1]) == 0 && strcmp(_tmp_A[1],tmp_A[0]) == 0) match_valid = 2;//ok
						}
						if(match_valid)//marker is matched in ASN.freq
						{
							tmp = strtok(NULL, " 	");//MAF
							double MAF = atof(tmp);

							double n1 = allele_sample_space/2;//n1
							tmp = strtok(NULL, " 	");
							double n2 = atoi(tmp);//n2

							if(match_valid == 1)
							{
								allele_count[0] = allele_count[0]*(n1/(n1+n2)) + MAF*(n2/(n1+n2));
								allele_count[1] = 1=allele_count[0];//allele_count[1]*(n1/(n1+n2)) + (1-MAF)*(n2/(n1+n2));
							}
							else if(match_valid == 2)
							{
								allele_count[0] = allele_count[0]*(n1/(n1+n2)) + (1-MAF)*(n2/(n1+n2));
								allele_count[1] = 1=allele_count[0];//allele_count[1]*(n1/(n1+n2)) + (MAF)*(n2/(n1+n2));
							}
						}
						else
						{
							//frequency.snp
						}
					}
					else {}//no matched marker in ASN.freq
				}
				//===================
				//output_fre<<"M "<<allele_count[3]<<endl;
				output_fre<<"M "<<string1<<endl;
				//cout      <<"M "<<string1<<endl;
				for(int i=0;i<2;i++)
				{
					if(allele_count[i]>0)
					{
						output_fre<<"A "<<(_tmp_A[i])<<" "<<allele_count[i]<<endl;
						//cout      <<"A "<<(_tmp_A[i])<<" "<<allele_count[i]<<endl;
					}
				}
			}
			//cout<<total_marker_for_chr<<endl;getchar();
			total_marker_for_chr -= num_pre_fetch_marker;
		}
		output_ped.close();
	}
	//cout<<total_marker<<endl;getchar();//1000,4737983
	if(external_freq_or_not) input_fre.close();
	//===============================================
	fclose(input_bed);
	input_bim.close();
	output_fre.close();
}<|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow 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 "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"

namespace tensorflow {

template <typename InputShape>
static Graph* BroadcastTo(int size, InputShape input_shape) {
  Graph* g = new Graph(OpRegistry::Global());

  Tensor input(DT_FLOAT, input_shape(size));
  input.flat<float>() = input.flat<float>().setRandom();

  Tensor shape(DT_INT32, TensorShape({2}));
  shape.flat<int32>()(0) = size;
  shape.flat<int32>()(1) = size;

  Node* node;
  TF_CHECK_OK(NodeBuilder(g->NewName("n"), "BroadcastTo")
                  .Input(test::graph::Constant(g, input))
                  .Input(test::graph::Constant(g, shape))
                  .Attr("T", DT_FLOAT)
                  .Attr("Tidx", DT_INT32)
                  .Finalize(g, &node));
  return g;
}

#define BM_BroadcastTo_InnerDim(SIZE, type)                             \
  static void BM_BroadcastTo_Inner##_##type##_##SIZE(int iters) {       \
    testing::UseRealTime();                                             \
    testing::ItemsProcessed(static_cast<int64>(iters) * SIZE * SIZE);   \
    test::Benchmark(#type, BroadcastTo(SIZE,                            \
                                       [](int size) {                   \
                                         return TensorShape({size, 1}); \
                                       }))                              \
        .Run(iters);                                                    \
  }                                                                     \
  BENCHMARK(BM_BroadcastTo_Inner##_##type##_##SIZE);

#define BM_BroadcastTo_OuterDim(SIZE, type)                             \
  static void BM_BroadcastTo_Outer##_##type##_##SIZE(int iters) {       \
    testing::UseRealTime();                                             \
    testing::ItemsProcessed(static_cast<int64>(iters) * SIZE * SIZE);   \
    test::Benchmark(#type, BroadcastTo(SIZE,                            \
                                       [](int size) {                   \
                                         return TensorShape({1, size}); \
                                       }))                              \
        .Run(iters);                                                    \
  }                                                                     \
  BENCHMARK(BM_BroadcastTo_Outer##_##type##_##SIZE);

BM_BroadcastTo_InnerDim(64, cpu);
BM_BroadcastTo_InnerDim(128, cpu);
BM_BroadcastTo_InnerDim(256, cpu);
BM_BroadcastTo_InnerDim(512, cpu);
BM_BroadcastTo_InnerDim(1024, cpu);

BM_BroadcastTo_OuterDim(64, cpu);
BM_BroadcastTo_OuterDim(128, cpu);
BM_BroadcastTo_OuterDim(256, cpu);
BM_BroadcastTo_OuterDim(512, cpu);
BM_BroadcastTo_OuterDim(1024, cpu);

}  // end namespace tensorflow
<commit_msg>Add more benchmarks to BroadcastTo test<commit_after>/* Copyright 2019 The TensorFlow 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 "tensorflow/core/common_runtime/kernel_benchmark_testlib.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/node_builder.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"

namespace tensorflow {

template <typename InputShape>
static Graph* BroadcastTo(int dim0, int dim1, InputShape input_shape) {
  Graph* g = new Graph(OpRegistry::Global());

  Tensor input(DT_FLOAT, input_shape(dim0, dim1));
  input.flat<float>() = input.flat<float>().setRandom();

  Tensor shape(DT_INT32, TensorShape({2}));
  shape.flat<int32>()(0) = dim0;
  shape.flat<int32>()(1) = dim1;

  Node* node;
  TF_CHECK_OK(NodeBuilder(g->NewName("n"), "BroadcastTo")
                  .Input(test::graph::Constant(g, input))
                  .Input(test::graph::Constant(g, shape))
                  .Attr("T", DT_FLOAT)
                  .Attr("Tidx", DT_INT32)
                  .Finalize(g, &node));
  return g;
}

#define BM_BroadcastTo_InnerDim(DIM0, DIM1, type)                          \
  static void BM_BroadcastTo_Inner##_##type##_##DIM0##_##DIM1(int iters) { \
    testing::UseRealTime();                                                \
    testing::ItemsProcessed(static_cast<int64>(iters) * DIM0 * DIM1);      \
    test::Benchmark(#type, BroadcastTo(DIM0, DIM1,                         \
                                       [](int dim0, int dim1) {            \
                                         return TensorShape({dim0, 1});    \
                                       }))                                 \
        .Run(iters);                                                       \
  }                                                                        \
  BENCHMARK(BM_BroadcastTo_Inner##_##type##_##DIM0##_##DIM1);

#define BM_BroadcastTo_OuterDim(DIM0, DIM1, type)                          \
  static void BM_BroadcastTo_Outer##_##type##_##DIM0##_##DIM1(int iters) { \
    testing::UseRealTime();                                                \
    testing::ItemsProcessed(static_cast<int64>(iters) * DIM0 * DIM1);      \
    test::Benchmark(#type, BroadcastTo(DIM0, DIM1,                         \
                                       [](int dim0, int dim1) {            \
                                         return TensorShape({1, dim1});    \
                                       }))                                 \
        .Run(iters);                                                       \
  }                                                                        \
  BENCHMARK(BM_BroadcastTo_Outer##_##type##_##DIM0##_##DIM1);

BM_BroadcastTo_InnerDim(64, 64, cpu);
BM_BroadcastTo_InnerDim(128, 128, cpu);
BM_BroadcastTo_InnerDim(256, 256, cpu);
BM_BroadcastTo_InnerDim(512, 512, cpu);
BM_BroadcastTo_InnerDim(1024, 1024, cpu);
BM_BroadcastTo_InnerDim(500, 20000, cpu);

BM_BroadcastTo_OuterDim(64, 64, cpu);
BM_BroadcastTo_OuterDim(128, 128, cpu);
BM_BroadcastTo_OuterDim(256, 256, cpu);
BM_BroadcastTo_OuterDim(512, 512, cpu);
BM_BroadcastTo_OuterDim(1024, 1024, cpu);
BM_BroadcastTo_OuterDim(500, 20000, cpu);

}  // end namespace tensorflow
<|endoftext|>


<commit_before>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "elang/lir/value.h"

#include "base/logging.h"

namespace elang {
namespace lir {

bool Value::is_memory_slot() const {
  return is_parameter() || is_argument() || is_stack_slot() || is_spill_slot();
}

Value Value::Argument(Value type, int data) {
  return Value(type.type, type.size, Kind::Argument, data);
}

bool Value::CanBeImmediate(int64_t value) {
  return value >= kMinimumImmediate && value <= kMaximumImmediate;
}

Value Value::False() {
  return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 0);
}

Value Value::Float32Literal() {
  return Value(Float32Type(), Kind::Literal);
}

Value Value::Float64Literal() {
  return Value(Float64Type(), Kind::Literal);
}

Value Value::Float32Type() {
  return Value(Type::Float, ValueSize::Size32, Kind::Void, 0);
}

Value Value::Float64Type() {
  return Value(Type::Float, ValueSize::Size64, Kind::Void, 0);
}

Value Value::FrameSlot(Value type, int data) {
  return Value(type.type, type.size, Kind::FrameSlot, data);
}

Value Value::Immediate(ValueSize size, int data) {
  DCHECK(CanBeImmediate(data));
  return Value(Type::Integer, size, Kind::Immediate, data);
}

Value Value::Int16Type() {
  return Value(Type::Integer, ValueSize::Size16, Kind::Void, 0);
}

Value Value::Int32Type() {
  return Value(Type::Integer, ValueSize::Size32, Kind::Void, 0);
}

Value Value::Int64Type() {
  return Value(Type::Integer, ValueSize::Size64, Kind::Void, 0);
}

Value Value::Int8Type() {
  return Value(Type::Integer, ValueSize::Size8, Kind::Void, 0);
}

Value Value::Literal(Value type) {
  return Value(type, Kind::Literal);
}

Value Value::Parameter(Value type, int data) {
  return Value(type.type, type.size, Kind::Parameter, data);
}

Value Value::Register(Value type, int data) {
  return Value(type.type, type.size, Kind::VirtualRegister, data);
}

Value Value::SmallInt16(int data) {
  DCHECK_LT(static_cast<uint32_t>(data), 1u << 16);
  return Immediate(ValueSize::Size16, data);
}

Value Value::SmallInt32(int data) {
  return Immediate(ValueSize::Size32, data);
}

Value Value::SmallInt64(int data) {
  return Immediate(ValueSize::Size64, data);
}

Value Value::SmallInt8(int data) {
  DCHECK_LT(static_cast<uint32_t>(data), 1u << 8);
  return Immediate(ValueSize::Size8, data);
}

Value Value::SpillSlot(Value type, int data) {
  return Value(type.type, type.size, Kind::SpillSlot, data);
}

Value Value::StackSlot(Value type, int data) {
  return Value(type.type, type.size, Kind::StackSlot, data);
}

Value Value::True() {
  return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 1);
}

bool Value::is_output() const {
  switch (kind) {
    case Kind::Argument:
    case Kind::Condition:
    case Kind::FrameSlot:
    case Kind::Parameter:
    case Kind::PhysicalRegister:
    case Kind::SpillSlot:
    case Kind::StackSlot:
    case Kind::VirtualRegister:
      return true;
  }
  return false;
}

}  // namespace lir
}  // namespace elang

namespace std {
size_t hash<elang::lir::Value>::operator()(
    const elang::lir::Value& value) const {
  auto const p = reinterpret_cast<const uint32_t*>(&value);
  return std::hash<uint32_t>()(*p);
}
}  // namespace std
<commit_msg>elang/lir: Make |Value::is_memory_slot()| to recognize |FrameSlot|.<commit_after>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "elang/lir/value.h"

#include "base/logging.h"

namespace elang {
namespace lir {

bool Value::is_memory_slot() const {
  return is_parameter() || is_argument() || is_stack_slot() ||
         is_frame_slot() || is_spill_slot();
}

Value Value::Argument(Value type, int data) {
  return Value(type.type, type.size, Kind::Argument, data);
}

bool Value::CanBeImmediate(int64_t value) {
  return value >= kMinimumImmediate && value <= kMaximumImmediate;
}

Value Value::False() {
  return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 0);
}

Value Value::Float32Literal() {
  return Value(Float32Type(), Kind::Literal);
}

Value Value::Float64Literal() {
  return Value(Float64Type(), Kind::Literal);
}

Value Value::Float32Type() {
  return Value(Type::Float, ValueSize::Size32, Kind::Void, 0);
}

Value Value::Float64Type() {
  return Value(Type::Float, ValueSize::Size64, Kind::Void, 0);
}

Value Value::FrameSlot(Value type, int data) {
  return Value(type.type, type.size, Kind::FrameSlot, data);
}

Value Value::Immediate(ValueSize size, int data) {
  DCHECK(CanBeImmediate(data));
  return Value(Type::Integer, size, Kind::Immediate, data);
}

Value Value::Int16Type() {
  return Value(Type::Integer, ValueSize::Size16, Kind::Void, 0);
}

Value Value::Int32Type() {
  return Value(Type::Integer, ValueSize::Size32, Kind::Void, 0);
}

Value Value::Int64Type() {
  return Value(Type::Integer, ValueSize::Size64, Kind::Void, 0);
}

Value Value::Int8Type() {
  return Value(Type::Integer, ValueSize::Size8, Kind::Void, 0);
}

Value Value::Literal(Value type) {
  return Value(type, Kind::Literal);
}

Value Value::Parameter(Value type, int data) {
  return Value(type.type, type.size, Kind::Parameter, data);
}

Value Value::Register(Value type, int data) {
  return Value(type.type, type.size, Kind::VirtualRegister, data);
}

Value Value::SmallInt16(int data) {
  DCHECK_LT(static_cast<uint32_t>(data), 1u << 16);
  return Immediate(ValueSize::Size16, data);
}

Value Value::SmallInt32(int data) {
  return Immediate(ValueSize::Size32, data);
}

Value Value::SmallInt64(int data) {
  return Immediate(ValueSize::Size64, data);
}

Value Value::SmallInt8(int data) {
  DCHECK_LT(static_cast<uint32_t>(data), 1u << 8);
  return Immediate(ValueSize::Size8, data);
}

Value Value::SpillSlot(Value type, int data) {
  return Value(type.type, type.size, Kind::SpillSlot, data);
}

Value Value::StackSlot(Value type, int data) {
  return Value(type.type, type.size, Kind::StackSlot, data);
}

Value Value::True() {
  return Value(Type::Integer, ValueSize::Size8, Kind::Condition, 1);
}

bool Value::is_output() const {
  switch (kind) {
    case Kind::Argument:
    case Kind::Condition:
    case Kind::FrameSlot:
    case Kind::Parameter:
    case Kind::PhysicalRegister:
    case Kind::SpillSlot:
    case Kind::StackSlot:
    case Kind::VirtualRegister:
      return true;
  }
  return false;
}

}  // namespace lir
}  // namespace elang

namespace std {
size_t hash<elang::lir::Value>::operator()(
    const elang::lir::Value& value) const {
  auto const p = reinterpret_cast<const uint32_t*>(&value);
  return std::hash<uint32_t>()(*p);
}
}  // namespace std
<|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow 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 "tensorflow/lite/delegates/gpu/cl/environment.h"

#include <string>
#include <vector>

#include "tensorflow/lite/delegates/gpu/cl/util.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"

namespace tflite {
namespace gpu {
namespace cl {
namespace {
absl::Status CreateEnvironment(Environment* result, bool shared,
                               cl_context_properties egl_context,
                               cl_context_properties egl_display) {
  CLDevice gpu;
  RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));

  CLContext context;
  if (shared) {
    RETURN_IF_ERROR(CreateCLGLContext(gpu, egl_context, egl_display, &context));
  } else {
    RETURN_IF_ERROR(CreateCLContext(gpu, &context));
  }
  CLCommandQueue queue;
  RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
  ProfilingCommandQueue profiling_queue;
  RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));

  *result = Environment(std::move(gpu), std::move(context), std::move(queue),
                        std::move(profiling_queue));

  return result->Init();
}

bool IsGpuSupportsStorageType(const GpuInfo& gpu_info,
                              TensorStorageType storage_type) {
  switch (storage_type) {
    case TensorStorageType::TEXTURE_2D:
      return !gpu_info.IsAMD();
    case TensorStorageType::BUFFER:
      return true;
    case TensorStorageType::TEXTURE_ARRAY:
      return !gpu_info.IsAMD() && gpu_info.SupportsTextureArray();
    case TensorStorageType::IMAGE_BUFFER:
      return (gpu_info.IsAdreno() || gpu_info.IsAMD() || gpu_info.IsNvidia()) &&
             gpu_info.SupportsImageBuffer();
    case TensorStorageType::TEXTURE_3D:
      return !gpu_info.IsAMD() && gpu_info.SupportsImage3D();
    case TensorStorageType::SINGLE_TEXTURE_2D:
      return false;
    case TensorStorageType::UNKNOWN:
      return false;
  }
  return false;
}

bool IsGpuSupportsPrecision(const GpuInfo& gpu_info,
                            CalculationsPrecision precision) {
  switch (precision) {
    case CalculationsPrecision::F32_F16:
    case CalculationsPrecision::F16:
      return gpu_info.SupportsFP16();
    case CalculationsPrecision::F32:
      return true;
  }
}

}  // namespace

Environment::Environment(CLDevice&& device, CLContext&& context,
                         CLCommandQueue&& queue,
                         ProfilingCommandQueue&& profiling_queue)
    : device_(std::move(device)),
      context_(std::move(context)),
      queue_(std::move(queue)),
      profiling_queue_(std::move(profiling_queue)) {}

Environment::Environment(Environment&& environment)
    : device_(std::move(environment.device_)),
      context_(std::move(environment.context_)),
      queue_(std::move(environment.queue_)),
      profiling_queue_(std::move(environment.profiling_queue_)),
      program_cache_(std::move(environment.program_cache_)) {}

Environment& Environment::operator=(Environment&& environment) {
  if (this != &environment) {
    device_ = std::move(environment.device_);
    context_ = std::move(environment.context_);
    queue_ = std::move(environment.queue_);
    profiling_queue_ = std::move(environment.profiling_queue_);
    program_cache_ = std::move(environment.program_cache_);
  }
  return *this;
}

absl::Status Environment::Init() {
  if (device().GetInfo().IsAdreno() &&
      device().GetInfo().SupportsTextureArray()) {
    const auto& adreno_info = device().info_.adreno_info;
    // Some Adreno < 600 have bug with one layer texture array. b/131099086
    // If we have one layer texture array and will write smt from kernel to this
    // texture, we will get zeroes instead of actual values.
    // The same kernel will work, if we use texture array with more than one
    // layer.
    if (adreno_info.IsAdreno3xx() || adreno_info.IsAdreno4xx() ||
        adreno_info.IsAdreno5xx()) {
      GetDevicePtr()->DisableOneLayerTextureArray();
    }
  }
  return absl::OkStatus();
}

void Environment::SetHighPerformance() const {
  // TODO(sorokin) use cl_perf_hint if available
}

void Environment::SetDefaultPerformance() const {
  // TODO(sorokin) use cl_perf_hint if available
}

void Environment::SetLowPerformance() const {
  // TODO(sorokin) use cl_perf_hint if available
}

std::vector<CalculationsPrecision> Environment::GetSupportedPrecisions() const {
  std::vector<CalculationsPrecision> precisions;
  for (CalculationsPrecision precision :
       {CalculationsPrecision::F32, CalculationsPrecision::F32_F16,
        CalculationsPrecision::F16}) {
    if (IsSupported(precision)) {
      precisions.push_back(precision);
    }
  }
  return precisions;
}

bool Environment::IsSupported(CalculationsPrecision precision) const {
  return IsGpuSupportsPrecision(device_.GetInfo(), precision);
}

std::vector<TensorStorageType> Environment::GetSupportedStorages() const {
  std::vector<TensorStorageType> storage_types;
  for (auto storage_type :
       {TensorStorageType::TEXTURE_2D, TensorStorageType::BUFFER,
        TensorStorageType::TEXTURE_ARRAY, TensorStorageType::IMAGE_BUFFER,
        TensorStorageType::TEXTURE_3D}) {
    if (IsSupported(storage_type)) {
      storage_types.push_back(storage_type);
    }
  }
  return storage_types;
}

std::vector<TensorStorageType>
Environment::GetSupportedStoragesWithHWZeroClampSupport() const {
  std::vector<TensorStorageType> storage_types;
  for (auto storage_type :
       {TensorStorageType::TEXTURE_2D, TensorStorageType::TEXTURE_ARRAY,
        TensorStorageType::TEXTURE_3D}) {
    if (IsSupported(storage_type)) {
      storage_types.push_back(storage_type);
    }
  }
  return storage_types;
}

bool Environment::IsSupported(TensorStorageType storage_type) const {
  return IsGpuSupportsStorageType(device_.GetInfo(), storage_type);
}

TensorStorageType GetFastestStorageType(const GpuInfo& gpu_info) {
  if (gpu_info.IsAdreno()) {
    if (gpu_info.adreno_info.IsAdreno6xxOrHigher() &&
        !gpu_info.opencl_info.IsImage2dFromBufferSupported()) {
      return TensorStorageType::TEXTURE_ARRAY;
    } else {
      return TensorStorageType::TEXTURE_2D;
    }
  } else if (gpu_info.IsPowerVR()) {
    return TensorStorageType::TEXTURE_2D;
  } else if (gpu_info.IsMali()) {
    const MaliInfo mali_info = gpu_info.mali_info;
    if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||
        mali_info.IsValhall()) {
      return TensorStorageType::TEXTURE_2D;
    } else {
      return TensorStorageType::BUFFER;
    }
  } else if (gpu_info.IsNvidia()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsAMD()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsIntel()) {
    return TensorStorageType::BUFFER;
  }
  return TensorStorageType::BUFFER;
}

TensorStorageType GetStorageTypeWithMinimalMemoryConsumption(
    const GpuInfo& gpu_info) {
  if (gpu_info.IsAdreno()) {
    if (gpu_info.adreno_info.IsAdreno3xx() ||
        gpu_info.adreno_info.IsAdreno4xx()) {
      return TensorStorageType::BUFFER;
    } else {
      if (gpu_info.opencl_info.IsImage2dFromBufferSupported()) {
        return TensorStorageType::TEXTURE_2D;
      } else {
        return TensorStorageType::IMAGE_BUFFER;
      }
    }
  } else if (gpu_info.IsPowerVR()) {
    if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&
        CanUseSubBufferForImage2d(gpu_info)) {
      return TensorStorageType::TEXTURE_2D;
    } else {
      return TensorStorageType::BUFFER;
    }
  } else if (gpu_info.IsMali()) {
    const MaliInfo mali_info = gpu_info.mali_info;
    if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||
        mali_info.IsValhall()) {
      if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&
          CanUseSubBufferForImage2d(gpu_info)) {
        return TensorStorageType::TEXTURE_2D;
      } else {
        return TensorStorageType::BUFFER;
      }
    } else {
      return TensorStorageType::BUFFER;
    }
  } else if (gpu_info.IsNvidia()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsAMD()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsIntel()) {
    return TensorStorageType::BUFFER;
  }
  return TensorStorageType::BUFFER;
}

bool CanUseSubBufferForImage2d(const GpuInfo& gpu_info) {
  if (!gpu_info.IsCL11OrHigher()) {
    return false;
  }
  if (gpu_info.IsPowerVR()) {
    // driver issue
    return false;
  }
  if (gpu_info.IsMali() &&
      (gpu_info.mali_info.IsBifrost() || gpu_info.mali_info.IsMidgard())) {
    // Known driver issue on some G72 (Bifrost), G76 (Bifrost), T830 (Midgard),
    // and T880 (Midgard) devices.
    return false;
  }
  return true;
}

absl::Status CreateEnvironment(Environment* result) {
  CLDevice gpu;
  RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));

  CLContext context;
  RETURN_IF_ERROR(CreateCLContext(gpu, &context));
  CLCommandQueue queue;
  RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
  ProfilingCommandQueue profiling_queue;
  RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));

  *result = Environment(std::move(gpu), std::move(context), std::move(queue),
                        std::move(profiling_queue));
  return result->Init();
}

}  // namespace cl
}  // namespace gpu
}  // namespace tflite
<commit_msg>Nvidia excluded from CanUseSubBufferForImage2d.<commit_after>/* Copyright 2019 The TensorFlow 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 "tensorflow/lite/delegates/gpu/cl/environment.h"

#include <string>
#include <vector>

#include "tensorflow/lite/delegates/gpu/cl/util.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"

namespace tflite {
namespace gpu {
namespace cl {
namespace {
absl::Status CreateEnvironment(Environment* result, bool shared,
                               cl_context_properties egl_context,
                               cl_context_properties egl_display) {
  CLDevice gpu;
  RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));

  CLContext context;
  if (shared) {
    RETURN_IF_ERROR(CreateCLGLContext(gpu, egl_context, egl_display, &context));
  } else {
    RETURN_IF_ERROR(CreateCLContext(gpu, &context));
  }
  CLCommandQueue queue;
  RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
  ProfilingCommandQueue profiling_queue;
  RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));

  *result = Environment(std::move(gpu), std::move(context), std::move(queue),
                        std::move(profiling_queue));

  return result->Init();
}

bool IsGpuSupportsStorageType(const GpuInfo& gpu_info,
                              TensorStorageType storage_type) {
  switch (storage_type) {
    case TensorStorageType::TEXTURE_2D:
      return !gpu_info.IsAMD();
    case TensorStorageType::BUFFER:
      return true;
    case TensorStorageType::TEXTURE_ARRAY:
      return !gpu_info.IsAMD() && gpu_info.SupportsTextureArray();
    case TensorStorageType::IMAGE_BUFFER:
      return (gpu_info.IsAdreno() || gpu_info.IsAMD() || gpu_info.IsNvidia()) &&
             gpu_info.SupportsImageBuffer();
    case TensorStorageType::TEXTURE_3D:
      return !gpu_info.IsAMD() && gpu_info.SupportsImage3D();
    case TensorStorageType::SINGLE_TEXTURE_2D:
      return false;
    case TensorStorageType::UNKNOWN:
      return false;
  }
  return false;
}

bool IsGpuSupportsPrecision(const GpuInfo& gpu_info,
                            CalculationsPrecision precision) {
  switch (precision) {
    case CalculationsPrecision::F32_F16:
    case CalculationsPrecision::F16:
      return gpu_info.SupportsFP16();
    case CalculationsPrecision::F32:
      return true;
  }
}

}  // namespace

Environment::Environment(CLDevice&& device, CLContext&& context,
                         CLCommandQueue&& queue,
                         ProfilingCommandQueue&& profiling_queue)
    : device_(std::move(device)),
      context_(std::move(context)),
      queue_(std::move(queue)),
      profiling_queue_(std::move(profiling_queue)) {}

Environment::Environment(Environment&& environment)
    : device_(std::move(environment.device_)),
      context_(std::move(environment.context_)),
      queue_(std::move(environment.queue_)),
      profiling_queue_(std::move(environment.profiling_queue_)),
      program_cache_(std::move(environment.program_cache_)) {}

Environment& Environment::operator=(Environment&& environment) {
  if (this != &environment) {
    device_ = std::move(environment.device_);
    context_ = std::move(environment.context_);
    queue_ = std::move(environment.queue_);
    profiling_queue_ = std::move(environment.profiling_queue_);
    program_cache_ = std::move(environment.program_cache_);
  }
  return *this;
}

absl::Status Environment::Init() {
  if (device().GetInfo().IsAdreno() &&
      device().GetInfo().SupportsTextureArray()) {
    const auto& adreno_info = device().info_.adreno_info;
    // Some Adreno < 600 have bug with one layer texture array. b/131099086
    // If we have one layer texture array and will write smt from kernel to this
    // texture, we will get zeroes instead of actual values.
    // The same kernel will work, if we use texture array with more than one
    // layer.
    if (adreno_info.IsAdreno3xx() || adreno_info.IsAdreno4xx() ||
        adreno_info.IsAdreno5xx()) {
      GetDevicePtr()->DisableOneLayerTextureArray();
    }
  }
  return absl::OkStatus();
}

void Environment::SetHighPerformance() const {
  // TODO(sorokin) use cl_perf_hint if available
}

void Environment::SetDefaultPerformance() const {
  // TODO(sorokin) use cl_perf_hint if available
}

void Environment::SetLowPerformance() const {
  // TODO(sorokin) use cl_perf_hint if available
}

std::vector<CalculationsPrecision> Environment::GetSupportedPrecisions() const {
  std::vector<CalculationsPrecision> precisions;
  for (CalculationsPrecision precision :
       {CalculationsPrecision::F32, CalculationsPrecision::F32_F16,
        CalculationsPrecision::F16}) {
    if (IsSupported(precision)) {
      precisions.push_back(precision);
    }
  }
  return precisions;
}

bool Environment::IsSupported(CalculationsPrecision precision) const {
  return IsGpuSupportsPrecision(device_.GetInfo(), precision);
}

std::vector<TensorStorageType> Environment::GetSupportedStorages() const {
  std::vector<TensorStorageType> storage_types;
  for (auto storage_type :
       {TensorStorageType::TEXTURE_2D, TensorStorageType::BUFFER,
        TensorStorageType::TEXTURE_ARRAY, TensorStorageType::IMAGE_BUFFER,
        TensorStorageType::TEXTURE_3D}) {
    if (IsSupported(storage_type)) {
      storage_types.push_back(storage_type);
    }
  }
  return storage_types;
}

std::vector<TensorStorageType>
Environment::GetSupportedStoragesWithHWZeroClampSupport() const {
  std::vector<TensorStorageType> storage_types;
  for (auto storage_type :
       {TensorStorageType::TEXTURE_2D, TensorStorageType::TEXTURE_ARRAY,
        TensorStorageType::TEXTURE_3D}) {
    if (IsSupported(storage_type)) {
      storage_types.push_back(storage_type);
    }
  }
  return storage_types;
}

bool Environment::IsSupported(TensorStorageType storage_type) const {
  return IsGpuSupportsStorageType(device_.GetInfo(), storage_type);
}

TensorStorageType GetFastestStorageType(const GpuInfo& gpu_info) {
  if (gpu_info.IsAdreno()) {
    if (gpu_info.adreno_info.IsAdreno6xxOrHigher() &&
        !gpu_info.opencl_info.IsImage2dFromBufferSupported()) {
      return TensorStorageType::TEXTURE_ARRAY;
    } else {
      return TensorStorageType::TEXTURE_2D;
    }
  } else if (gpu_info.IsPowerVR()) {
    return TensorStorageType::TEXTURE_2D;
  } else if (gpu_info.IsMali()) {
    const MaliInfo mali_info = gpu_info.mali_info;
    if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||
        mali_info.IsValhall()) {
      return TensorStorageType::TEXTURE_2D;
    } else {
      return TensorStorageType::BUFFER;
    }
  } else if (gpu_info.IsNvidia()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsAMD()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsIntel()) {
    return TensorStorageType::BUFFER;
  }
  return TensorStorageType::BUFFER;
}

TensorStorageType GetStorageTypeWithMinimalMemoryConsumption(
    const GpuInfo& gpu_info) {
  if (gpu_info.IsAdreno()) {
    if (gpu_info.adreno_info.IsAdreno3xx() ||
        gpu_info.adreno_info.IsAdreno4xx()) {
      return TensorStorageType::BUFFER;
    } else {
      if (gpu_info.opencl_info.IsImage2dFromBufferSupported()) {
        return TensorStorageType::TEXTURE_2D;
      } else {
        return TensorStorageType::IMAGE_BUFFER;
      }
    }
  } else if (gpu_info.IsPowerVR()) {
    if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&
        CanUseSubBufferForImage2d(gpu_info)) {
      return TensorStorageType::TEXTURE_2D;
    } else {
      return TensorStorageType::BUFFER;
    }
  } else if (gpu_info.IsMali()) {
    const MaliInfo mali_info = gpu_info.mali_info;
    if (mali_info.IsMaliT8xx() || mali_info.IsBifrostGen3() ||
        mali_info.IsValhall()) {
      if (gpu_info.opencl_info.IsImage2dFromBufferSupported() &&
          CanUseSubBufferForImage2d(gpu_info)) {
        return TensorStorageType::TEXTURE_2D;
      } else {
        return TensorStorageType::BUFFER;
      }
    } else {
      return TensorStorageType::BUFFER;
    }
  } else if (gpu_info.IsNvidia()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsAMD()) {
    return gpu_info.SupportsImageBuffer() ? TensorStorageType::IMAGE_BUFFER
                                          : TensorStorageType::BUFFER;
  } else if (gpu_info.IsIntel()) {
    return TensorStorageType::BUFFER;
  }
  return TensorStorageType::BUFFER;
}

bool CanUseSubBufferForImage2d(const GpuInfo& gpu_info) {
  if (!gpu_info.IsCL11OrHigher()) {
    return false;
  }
  if (gpu_info.IsPowerVR()) {
    // driver issue
    return false;
  }
  if (gpu_info.IsNvidia()) {
    return false;
  }
  if (gpu_info.IsMali() &&
      (gpu_info.mali_info.IsBifrost() || gpu_info.mali_info.IsMidgard())) {
    // Known driver issue on some G72 (Bifrost), G76 (Bifrost), T830 (Midgard),
    // and T880 (Midgard) devices.
    return false;
  }
  return true;
}

absl::Status CreateEnvironment(Environment* result) {
  CLDevice gpu;
  RETURN_IF_ERROR(CreateDefaultGPUDevice(&gpu));

  CLContext context;
  RETURN_IF_ERROR(CreateCLContext(gpu, &context));
  CLCommandQueue queue;
  RETURN_IF_ERROR(CreateCLCommandQueue(gpu, context, &queue));
  ProfilingCommandQueue profiling_queue;
  RETURN_IF_ERROR(CreateProfilingCommandQueue(gpu, context, &profiling_queue));

  *result = Environment(std::move(gpu), std::move(context), std::move(queue),
                        std::move(profiling_queue));
  return result->Init();
}

}  // namespace cl
}  // namespace gpu
}  // namespace tflite
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify %s

namespace PR6915 {
  template <typename T>
  class D {
    enum T::X v; // expected-error{{use of 'X' with tag type that does not match previous declaration}} \
    // expected-error{{no enum named 'X' in 'PR6915::D3'}}
  };

  struct D1 {
    enum X { value };
  };
  struct D2 {
    class X { }; // expected-note{{previous use is here}}
  };
  struct D3 { };

  template class D<D1>;
  template class D<D2>; // expected-note{{in instantiation of}}
  template class D<D3>; // expected-note{{in instantiation of}}
}

template<typename T>
struct DeclOrDef {
  enum T::foo; // expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}
  enum T::bar { // expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}
    value
  };
};

namespace PR6649 {
  template <typename T> struct foo {
    class T::bar;  // expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}
  };
}
<commit_msg>Tweak test case slightly<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify %s

namespace PR6915 {
  template <typename T>
  class D {
    enum T::X v; // expected-error{{use of 'X' with tag type that does not match previous declaration}} \
    // expected-error{{no enum named 'X' in 'PR6915::D3'}}
  };

  struct D1 {
    enum X { value };
  };
  struct D2 {
    class X { }; // expected-note{{previous use is here}}
  };
  struct D3 { };

  template class D<D1>;
  template class D<D2>; // expected-note{{in instantiation of}}
  template class D<D3>; // expected-note{{in instantiation of}}
}

template<typename T>
struct DeclOrDef {
  enum T::foo; // expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}
  enum T::bar { // expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}
    value
  };
};

namespace PR6649 {
  template <typename T> struct foo {
    class T::bar;  // expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}
    class T::bar { int x; }; // expected-error{{nested name specifier for a declaration cannot depend on a template parameter}}
  };
}
<|endoftext|>