<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Context.hpp"

using std::map;
using std::string;
using std::endl;
using std::vector;
using std::unordered_set;
using std::unordered_map;

using namespace eddic;

vector<Context*> Context::contexts;
unsigned int Context::currentVariable = 0;

Context::~Context() {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

Variable* Context::find(const std::string& variable) {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->find(variable);
        }

        return NULL;
    }

    return it->second;
}

bool Context::exists(const std::string& variable) const {
    if (variables.find(variable) != variables.end()) {
        return true;
    }

    if (m_parent != NULL) {
        return m_parent->exists(variable);
    }

    return false;
}

unsigned int Context::index(const std::string& variable) const {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->index(variable);
        }

        return -1;
    }

    return it->second->index();
}

Variable* Context::create(const std::string& variable, Type type) {
    Variable* v = new Variable(variable, type, currentVariable++);

    variables[variable] = v;

    return v;
}

void Context::write(AssemblyFileWriter& writer) {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
        }
    }
}

void Context::writeAll(AssemblyFileWriter& writer) {
    for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        (*it)->write(writer);
    }
}

void Context::cleanup(){
    for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        delete *it;
    }
}

TempContext::~TempContext() {
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

void TempContext::addVariable(const std::string& variable, Type type){
    Variable* v = new Variable(variable, type);

    m_visibles.insert(variable);

    storeVariable(variable, v);
}

void TempContext::storeVariable(const std::string& name, Variable* variable){
    m_stored[name] = variable;
}

bool TempContext::exists(const std::string& variable) const {
    return m_visibles.find(variable) != m_visibles.end();
}

Variable* TempContext::getVariable(const std::string& variable) const {
    return (*m_stored.find(variable)).second;
}

void BlockContext::write(AssemblyFileWriter& writer){
    //Nothing to be done
}

void FunctionContext::write(AssemblyFileWriter& writer){
    //TODO
}

void GlobalContext::write(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
        }
    }
}

void BlockContext::addVariable(const std::string variable, Type type){
    Variable* v = new Variable(variable, type);

    m_visibles.insert(variable);

    m_functionContext->storeVariable(variable, v);
}
<commit_msg>Make the research for variables recursive<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Context.hpp"

using std::map;
using std::string;
using std::endl;
using std::vector;
using std::unordered_set;
using std::unordered_map;

using namespace eddic;

vector<Context*> Context::contexts;
unsigned int Context::currentVariable = 0;

Context::~Context() {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

Variable* Context::find(const std::string& variable) {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->find(variable);
        }

        return NULL;
    }

    return it->second;
}

bool Context::exists(const std::string& variable) const {
    if (variables.find(variable) != variables.end()) {
        return true;
    }

    if (m_parent != NULL) {
        return m_parent->exists(variable);
    }

    return false;
}

unsigned int Context::index(const std::string& variable) const {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->index(variable);
        }

        return -1;
    }

    return it->second->index();
}

Variable* Context::create(const std::string& variable, Type type) {
    Variable* v = new Variable(variable, type, currentVariable++);

    variables[variable] = v;

    return v;
}

void Context::write(AssemblyFileWriter& writer) {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
        }
    }
}

void Context::writeAll(AssemblyFileWriter& writer) {
    for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        (*it)->write(writer);
    }
}

void Context::cleanup(){
    for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        delete *it;
    }
}

TempContext::~TempContext() {
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

void TempContext::addVariable(const std::string& variable, Type type){
    Variable* v = new Variable(variable, type);

    m_visibles.insert(variable);

    storeVariable(variable, v);
}

void TempContext::storeVariable(const std::string& name, Variable* variable){
    m_stored[name] = variable;
}

bool TempContext::exists(const std::string& variable) const {
    bool found = m_visibles.find(variable) != m_visibles.end();

    if(!found){
        if(m_parent){
            return m_parent->exists(variable);
        }
    }

    return true;
}

Variable* TempContext::getVariable(const std::string& variable) const {
    bool found = m_visibles.find(variable) != m_visibles.end();

    if(!found){
        if(m_parent){
            return getVariable(variable);
        }
    }

    return (*m_stored.find(variable)).second;
}

void BlockContext::write(AssemblyFileWriter& writer){
    //Nothing to be done
}

void FunctionContext::write(AssemblyFileWriter& writer){
    //TODO
}

void GlobalContext::write(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
        }
    }
}

void BlockContext::addVariable(const std::string variable, Type type){
    Variable* v = new Variable(variable, type);

    m_visibles.insert(variable);

    m_functionContext->storeVariable(variable, v);
}
<|endoftext|>


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

#include "Core.h"
#include "Platform.h"
#include "GetSources.h"

using namespace v8;
using namespace WebRTC;

void GetSources::Init(Handle<Object> exports) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  exports->Set(Nan::New("getSources").ToLocalChecked(), Nan::New<FunctionTemplate>(GetSources::GetDevices)->GetFunction());
}

rtc::scoped_refptr<webrtc::AudioTrackInterface> GetSources::GetAudioSource(const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  rtc::scoped_refptr<webrtc::AudioTrackInterface> track;
  rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Platform::GetFactory();

  if (factory.get()) {
    rtc::scoped_refptr<webrtc::AudioSourceInterface> src = factory->CreateAudioSource(constraints->ToConstraints());
    track = factory->CreateAudioTrack("audio", src);
  }

  return track;
}

rtc::scoped_refptr<webrtc::AudioTrackInterface> GetSources::GetAudioSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  // TODO(): CreateAudioSource(cricket::AudioCapturer*, MediaConstraintsInterface) Missing?
  return GetSources::GetAudioSource(constraints);
}

rtc::scoped_refptr<webrtc::VideoTrackInterface> GetSources::GetVideoSource(const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  //cricket::VideoCapturer* capturer = NULL;
  rtc::scoped_refptr<webrtc::VideoTrackInterface> track;
  /*
  cricket::DeviceManagerInterface *manager = Core::GetManager();

  if (manager) {
    std::vector<cricket::Device> video_devs;

    if (manager->GetVideoCaptureDevices(&video_devs)) {
      std::vector<cricket::Device>::iterator video_it;

      for (video_it = video_devs.begin(); video_it != video_devs.end(); ++video_it) {
        capturer = manager->CreateVideoCapturer(*video_it);

        if (capturer != NULL) {
          break;
        }
      }
    } else {
      LOG(LS_ERROR) << "Can't enumerate video devices";
    }
  } else {
    LOG(LS_ERROR) << "Can't create device manager";
  }

  if (capturer) {
    rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Core::CreateFactory();

    if (factory.get()) {
      track = factory->CreateVideoTrack("video", factory->CreateVideoSource(capturer, constraints->ToConstraints()));

      if (!track.get()) {
        LOG(LS_ERROR) << "Can't create video track";
      }
    } else {
      LOG(LS_ERROR) << "Can't get Factory";
    }
  }
  */

  return track;
}

rtc::scoped_refptr<webrtc::VideoTrackInterface> GetSources::GetVideoSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  //cricket::DeviceManagerInterface *manager = Core::GetManager();
  rtc::scoped_refptr<webrtc::VideoTrackInterface> track;
  /*
  cricket::VideoCapturer *cap = 0;

  if (manager) {
    cricket::Device video_dev;

    if (!manager->GetVideoCaptureDevice(id, &video_dev)) {
      cap = manager->CreateVideoCapturer(video_dev);
    }
  }

  if (cap) {
    //webrtc::PeerConnectionFactoryInterface *factory = Core::GetFactory();
    rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Core::CreateFactory();

    if (factory.get()) {
      track = factory->CreateVideoTrack("video", factory->CreateVideoSource(cap, constraints->ToConstraints()));
    }
  }
  */

  return track;
}

Local<Value> GetSources::GetDevices() {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  Nan::EscapableHandleScope scope;
  Local<Array> list = Nan::New<Array>();
  uint32_t index = 0;

  std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> video_info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0));

  if (video_info) {
    int num_devices = video_info->NumberOfDevices();

    for (int i = 0; i < num_devices; ++i) {
      const uint32_t kSize = 256;
      char name[kSize] = {0};
      char id[kSize] = {0};

      if (video_info->GetDeviceName(i, name, kSize, id, kSize) != -1) {
        Local<Object> device = Nan::New<Object>();

        device->Set(Nan::New("kind").ToLocalChecked(), Nan::New("video").ToLocalChecked());
        device->Set(Nan::New("label").ToLocalChecked(), Nan::New(name).ToLocalChecked());
        device->Set(Nan::New("id").ToLocalChecked(), Nan::New(id).ToLocalChecked());

        list->Set(index, device);
        index++;
      }
    }
  }

/*
  cricket::DeviceManagerInterface *manager = Core::GetManager();

  if (manager) {
    std::vector<cricket::Device> audio_devs;
    std::vector<cricket::Device> video_devs;

    if (manager->GetAudioInputDevices(&audio_devs)) {
      std::vector<cricket::Device>::iterator audio_it;

      for (audio_it = audio_devs.begin(); audio_it != audio_devs.end(); audio_it++) {
        const cricket::Device &dev = *audio_it;
        Local<Object> dev_obj = Nan::New<Object>();

        dev_obj->Set(Nan::New("kind").ToLocalChecked(), Nan::New("audio").ToLocalChecked());
        dev_obj->Set(Nan::New("label").ToLocalChecked(), Nan::New(dev.name.c_str()).ToLocalChecked());
        dev_obj->Set(Nan::New("id").ToLocalChecked(), Nan::New(dev.id.c_str()).ToLocalChecked());

        list->Set(index, dev_obj);
        index++;
      }
    }

    if (manager->GetVideoCaptureDevices(&video_devs)) {
      std::vector<cricket::Device>::iterator video_it = video_devs.begin();

      for (video_it = video_devs.begin(); video_it != video_devs.end(); video_it++) {
        const cricket::Device &dev = *video_it;
        Local<Object> dev_obj = Nan::New<Object>();

        dev_obj->Set(Nan::New("kind").ToLocalChecked(), Nan::New("video").ToLocalChecked());
        dev_obj->Set(Nan::New("label").ToLocalChecked(), Nan::New(dev.name.c_str()).ToLocalChecked());
        dev_obj->Set(Nan::New("id").ToLocalChecked(), Nan::New(dev.id.c_str()).ToLocalChecked());

        list->Set(index, dev_obj);
        index++;
      }
    }
  }
*/

  return scope.Escape(list);
}

void GetSources::GetDevices(const Nan::FunctionCallbackInfo<Value> &info) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  if (info.Length() == 1 && info[0]->IsFunction()) {
    Local<Function> callback = Local<Function>::Cast(info[0]);

    Local<Value> argv[1] = {
      GetSources::GetDevices()
    };

    if (!callback.IsEmpty()) {
      callback->Call(info.This(), 1, argv);
    }
  }

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

#include "Core.h"
#include "Platform.h"
#include "GetSources.h"

using namespace v8;
using namespace WebRTC;

void GetSources::Init(Handle<Object> exports) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  exports->Set(Nan::New("getSources").ToLocalChecked(), Nan::New<FunctionTemplate>(GetSources::GetDevices)->GetFunction());
}

rtc::scoped_refptr<webrtc::AudioTrackInterface> GetSources::GetAudioSource(const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  rtc::scoped_refptr<webrtc::AudioTrackInterface> track;
  rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Platform::GetFactory();

  if (factory.get()) {
    rtc::scoped_refptr<webrtc::AudioSourceInterface> src = factory->CreateAudioSource(constraints->ToConstraints());
    track = factory->CreateAudioTrack("audio", src);
  }

  return track;
}

rtc::scoped_refptr<webrtc::AudioTrackInterface> GetSources::GetAudioSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;
  return GetSources::GetAudioSource(constraints);
}

rtc::scoped_refptr<webrtc::VideoTrackInterface> GetSources::GetVideoSource(const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  cricket::VideoCapturer* capturer = nullptr;
  rtc::scoped_refptr<webrtc::VideoTrackInterface> track;
  rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Platform::GetFactory();
  std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> video_info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0));

  if (factory.get()) {
    if (video_info) {
      int num_devices = video_info->NumberOfDevices();

      for (int i = 0; i < num_devices; ++i) {
        const uint32_t kSize = 256;
        char name[kSize] = {0};
        char id[kSize] = {0};

        if (video_info->GetDeviceName(i, name, kSize, id, kSize) != -1) {
          capturer = factory.Create(cricket::Device(name, 0));

          if (capturer) {
            track = factory->CreateAudioTrack("video", factory->CreateVideoSource(capturer, constraints->ToConstraints()));
            return track;
          }
        }
      }
    }
  }

  return track;
}

rtc::scoped_refptr<webrtc::VideoTrackInterface> GetSources::GetVideoSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  cricket::VideoCapturer* capturer = nullptr;
  rtc::scoped_refptr<webrtc::VideoTrackInterface> track;
  rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> factory = Platform::GetFactory();
  std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> video_info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0));

  if (factory.get()) {
    if (video_info) {
      int num_devices = video_info->NumberOfDevices();

      for (int i = 0; i < num_devices; ++i) {
        const uint32_t kSize = 256;
        char name[kSize] = {0};
        char id[kSize] = {0};

        if (video_info->GetDeviceName(i, name, kSize, id, kSize) != -1) {
          if (id.empty() || id.compare(name) == 0) {
            capturer = factory.Create(cricket::Device(name, 0));

            if (capturer) {
              track = factory->CreateAudioTrack("video", factory->CreateVideoSource(capturer, constraints->ToConstraints()));
              return track;
            }
          }
        }
      }
    }
  }

  return track;
}

Local<Value> GetSources::GetDevices() {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  Nan::EscapableHandleScope scope;
  Local<Array> list = Nan::New<Array>();
  uint32_t index = 0;

  std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> video_info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0));

  if (video_info) {
    int num_devices = video_info->NumberOfDevices();

    for (int i = 0; i < num_devices; ++i) {
      const uint32_t kSize = 256;
      char name[kSize] = {0};
      char id[kSize] = {0};

      if (video_info->GetDeviceName(i, name, kSize, id, kSize) != -1) {
        Local<Object> device = Nan::New<Object>();

        device->Set(Nan::New("kind").ToLocalChecked(), Nan::New("video").ToLocalChecked());
        device->Set(Nan::New("label").ToLocalChecked(), Nan::New(name).ToLocalChecked());
        device->Set(Nan::New("id").ToLocalChecked(), Nan::New(id).ToLocalChecked());

        list->Set(index, device);
        index++;
      }
    }
  }

  return scope.Escape(list);
}

void GetSources::GetDevices(const Nan::FunctionCallbackInfo<Value> &info) {
  LOG(LS_INFO) << __PRETTY_FUNCTION__;

  if (info.Length() == 1 && info[0]->IsFunction()) {
    Local<Function> callback = Local<Function>::Cast(info[0]);

    Local<Value> argv[1] = {
      GetSources::GetDevices()
    };

    if (!callback.IsEmpty()) {
      callback->Call(info.This(), 1, argv);
    }
  }

  info.GetReturnValue().SetUndefined();
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Context.hpp"

using std::map;
using std::string;
using std::endl;
using std::vector;
using std::unordered_set;
using std::unordered_map;

using namespace eddic;

vector<Context*> Context::contexts;

/*vector<OldContext*> OldContext::contexts;
unsigned int OldContext::currentVariable = 0;

OldContext::~OldContext() {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

Variable* OldContext::find(const std::string& variable) {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->find(variable);
        }

        return NULL;
    }

    return it->second;
}

bool OldContext::exists(const std::string& variable) const {
    if (variables.find(variable) != variables.end()) {
        return true;
    }

    if (m_parent != NULL) {
        return m_parent->exists(variable);
    }

    return false;
}

unsigned int OldContext::index(const std::string& variable) const {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->index(variable);
        }

        return -1;
    }

    return it->second->index();
}

Variable* OldContext::create(const std::string& variable, Type type) {
    Variable* v = new Variable(variable, type, currentVariable++);

    variables[variable] = v;

    return v;
}

void OldContext::write(AssemblyFileWriter& writer) {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
        }
    }
}

void OldContext::writeAll(AssemblyFileWriter& writer) {
    for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        (*it)->write(writer);
    }
}

void OldContext::cleanup(){
    for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        delete *it;
    }
}*/

Context::~Context() {
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

void Context::storeVariable(const std::string& name, Variable* variable){
    m_stored[name] = variable;
}

bool Context::exists(const std::string& variable) const {
    bool found = m_visibles.find(variable) != m_visibles.end();

    if(!found){
        if(m_parent){
            return m_parent->exists(variable);
        }
    }

    return true;
}

Variable* Context::getVariable(const std::string& variable) const {
    bool found = m_visibles.find(variable) != m_visibles.end();

    if(!found){
        if(m_parent){
            return getVariable(variable);
        }
    }

    return (*m_stored.find(variable)).second;
}

void Context::cleanup(){
    for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        delete *it;
    }
}

void FunctionContext::write(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    int size = 0;

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            size += 4;
        } else if (it->second->type() == STRING) {
            size += 8;
        }
    }

    if(size > 0){
        writer.stream() << "subl $" << size << " , %edx" << std::endl;
    }
}

void FunctionContext::release(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    int size = 0;

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            size += 4;
        } else if (it->second->type() == STRING) {
            size += 8;
        }
    }

    if(size > 0){
        writer.stream() << "addl $" << size << " , %edx" << std::endl;
    }
}

void GlobalContext::write(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->position().name() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->position().name() << ",8,4" << endl;
        }
    }
}

Variable* GlobalContext::addVariable(const std::string& variable, Type type){
    Position position(GLOBAL, variable);

    Variable* v = new Variable(variable, type, position);

    m_visibles.insert(variable);

    storeVariable(variable, v);

    return v;
}

Variable* FunctionContext::newVariable(const std::string& variable, Type type){
    Position position(STACK, currentPosition);

    currentPosition += type == INT ? 4 : 8;

    return new Variable(variable, type, position);
}

Variable* FunctionContext::addVariable(const std::string& variable, Type type){
    Variable* v = newVariable(variable, type);

    m_visibles.insert(variable);

    storeVariable(variable, v);

    return v;
}

Variable* BlockContext::addVariable(const std::string& variable, Type type){
    Variable* v = m_functionContext->newVariable(variable, type);

    m_visibles.insert(variable);

    m_functionContext->storeVariable(variable, v);

    return v;
}

void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg){
    if(m_type == INT){
        if(m_position.isStack()){
            writer.stream() << "movl -" << m_position.offset() << "(ebp), " << reg << endl;
        } else if(m_position.isGlobal()){
            writer.stream() << "movl VI" << m_position.name() << ", " << reg << endl;
        }
   } else if (m_type == STRING){
       //TODO Should never be called
   }
}

void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
    if(m_type == INT){
       //TODO Should never be called
   } else if (m_type == STRING){
       if(m_position.isStack()){
           writer.stream() << "movl -" << m_position.name() << "(ebp), " << reg1 << endl;
           writer.stream() << "movl -" << (m_position.offset() + 4) << "(ebp), " << reg2 << endl;
       } else {
           writer.stream() << "movl VS" << m_position.name() << ", " << reg1 << endl;
           writer.stream() << "movl VS" << m_position.name() << "+4, " << reg2 << endl;
       }
   }
}

void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg){
    if(m_type == INT){
        if(m_position.isStack()){
            writer.stream() << "movl " << reg << ", -" << m_position.offset() << "(ebp)" << endl;
        } else if(m_position.isGlobal()){
            writer.stream() << "movl " << reg << ", VI" << m_position.name()  << endl;
        }
   } else if (m_type == STRING){
       //TODO Should never be called
   }
}

void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
    if(m_type == INT){
       //TODO Should never be called
   } else if (m_type == STRING){
       if(m_position.isStack()){
           writer.stream() << "movl " << reg1 << ", -" << m_position.name() << "(ebp)" << endl;
           writer.stream() << "movl " << reg2 << ", -" << (m_position.offset() + 4) << "(ebp)" << endl;
       } else {
           writer.stream() << "movl " << reg1 << ", VS" << m_position.name() << endl;
           writer.stream() << "movl " << reg2 << ", VS" << m_position.name() << "+4" << endl;
       }
   }
}

void Variable::pushToStack(AssemblyFileWriter& writer){
    switch (m_type) {
        case INT:
            if(m_position.isStack()){
                writer.stream() << "pushl -" << m_position.offset() << "(ebp)" << std::endl;
            } else if(m_position.isGlobal()){
                writer.stream() << "pushl VI" << m_position.name() << std::endl;
            }

            break;
        case STRING:
            if(m_position.isStack()){
                writer.stream() << "pushl -" << m_position.offset() << "(ebp)" << std::endl;
                writer.stream() << "pushl -" << (m_position.offset() + 4) << "(ebp)" << std::endl;
            } else if(m_position.isGlobal()){
                writer.stream() << "pushl VS" << m_index << endl;
                writer.stream() << "pushl VS" << m_index << "+4" << std::endl;
            }

            break;
    }
}

void Variable::popFromStack(AssemblyFileWriter& writer){
    switch (m_type) {
        case INT:
            writer.stream() << "movl (%esp), %eax" << endl;
            writer.stream() << "addl $4, %esp" << endl;

            moveFromRegister(writer, "%eax");

            break;
        case STRING:
            writer.stream() << "movl (%esp), %eax" << endl;
            writer.stream() << "movl 4(%esp), %ebx" << endl;
            writer.stream() << "addl $8, %esp" << endl;

            moveFromRegister(writer, "%eax", "%ebx");

            break;
    }
}
<commit_msg>Bug in the exists function of the context<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Context.hpp"

using std::map;
using std::string;
using std::endl;
using std::vector;
using std::unordered_set;
using std::unordered_map;

using namespace eddic;

vector<Context*> Context::contexts;

/*vector<OldContext*> OldContext::contexts;
unsigned int OldContext::currentVariable = 0;

OldContext::~OldContext() {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

Variable* OldContext::find(const std::string& variable) {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->find(variable);
        }

        return NULL;
    }

    return it->second;
}

bool OldContext::exists(const std::string& variable) const {
    if (variables.find(variable) != variables.end()) {
        return true;
    }

    if (m_parent != NULL) {
        return m_parent->exists(variable);
    }

    return false;
}

unsigned int OldContext::index(const std::string& variable) const {
    map<string, Variable*>::const_iterator it = variables.find(variable);

    if (it == variables.end()) {
        if (m_parent != NULL) {
            return m_parent->index(variable);
        }

        return -1;
    }

    return it->second->index();
}

Variable* OldContext::create(const std::string& variable, Type type) {
    Variable* v = new Variable(variable, type, currentVariable++);

    variables[variable] = v;

    return v;
}

void OldContext::write(AssemblyFileWriter& writer) {
    map<string, Variable*>::const_iterator it = variables.begin();
    map<string, Variable*>::const_iterator end = variables.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
        }
    }
}

void OldContext::writeAll(AssemblyFileWriter& writer) {
    for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        (*it)->write(writer);
    }
}

void OldContext::cleanup(){
    for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        delete *it;
    }
}*/

Context::~Context() {
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        delete it->second;
    }
}

void Context::storeVariable(const std::string& name, Variable* variable){
    m_stored[name] = variable;
}

bool Context::exists(const std::string& variable) const {
    bool found = m_visibles.find(variable) != m_visibles.end();

    if(!found){
        if(m_parent){
            return m_parent->exists(variable);
        }
    }

    return found;
}

Variable* Context::getVariable(const std::string& variable) const {
    bool found = m_visibles.find(variable) != m_visibles.end();

    if(!found){
        if(m_parent){
            return getVariable(variable);
        }
    }

    return (*m_stored.find(variable)).second;
}

void Context::cleanup(){
    for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
        delete *it;
    }
}

void FunctionContext::write(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    int size = 0;

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            size += 4;
        } else if (it->second->type() == STRING) {
            size += 8;
        }
    }

    if(size > 0){
        writer.stream() << "subl $" << size << " , %edx" << std::endl;
    }
}

void FunctionContext::release(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    int size = 0;

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            size += 4;
        } else if (it->second->type() == STRING) {
            size += 8;
        }
    }

    if(size > 0){
        writer.stream() << "addl $" << size << " , %edx" << std::endl;
    }
}

void GlobalContext::write(AssemblyFileWriter& writer){
    StoredVariables::const_iterator it = m_stored.begin();
    StoredVariables::const_iterator end = m_stored.end();

    for ( ; it != end; ++it) {
        if (it->second->type() == INT) {
            writer.stream() << ".comm VI" << it->second->position().name() << ",4,4" << endl;
        } else if (it->second->type() == STRING) {
            writer.stream() << ".comm VS" << it->second->position().name() << ",8,4" << endl;
        }
    }
}

Variable* GlobalContext::addVariable(const std::string& variable, Type type){
    Position position(GLOBAL, variable);

    Variable* v = new Variable(variable, type, position);

    m_visibles.insert(variable);

    storeVariable(variable, v);

    return v;
}

Variable* FunctionContext::newVariable(const std::string& variable, Type type){
    Position position(STACK, currentPosition);

    currentPosition += type == INT ? 4 : 8;

    return new Variable(variable, type, position);
}

Variable* FunctionContext::addVariable(const std::string& variable, Type type){
    Variable* v = newVariable(variable, type);

    m_visibles.insert(variable);

    storeVariable(variable, v);

    return v;
}

Variable* BlockContext::addVariable(const std::string& variable, Type type){
    Variable* v = m_functionContext->newVariable(variable, type);

    m_visibles.insert(variable);

    m_functionContext->storeVariable(variable, v);

    return v;
}

void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg){
    if(m_type == INT){
        if(m_position.isStack()){
            writer.stream() << "movl -" << m_position.offset() << "(ebp), " << reg << endl;
        } else if(m_position.isGlobal()){
            writer.stream() << "movl VI" << m_position.name() << ", " << reg << endl;
        }
   } else if (m_type == STRING){
       //TODO Should never be called
   }
}

void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
    if(m_type == INT){
       //TODO Should never be called
   } else if (m_type == STRING){
       if(m_position.isStack()){
           writer.stream() << "movl -" << m_position.name() << "(ebp), " << reg1 << endl;
           writer.stream() << "movl -" << (m_position.offset() + 4) << "(ebp), " << reg2 << endl;
       } else {
           writer.stream() << "movl VS" << m_position.name() << ", " << reg1 << endl;
           writer.stream() << "movl VS" << m_position.name() << "+4, " << reg2 << endl;
       }
   }
}

void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg){
    if(m_type == INT){
        if(m_position.isStack()){
            writer.stream() << "movl " << reg << ", -" << m_position.offset() << "(ebp)" << endl;
        } else if(m_position.isGlobal()){
            writer.stream() << "movl " << reg << ", VI" << m_position.name()  << endl;
        }
   } else if (m_type == STRING){
       //TODO Should never be called
   }
}

void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
    if(m_type == INT){
       //TODO Should never be called
   } else if (m_type == STRING){
       if(m_position.isStack()){
           writer.stream() << "movl " << reg1 << ", -" << m_position.name() << "(ebp)" << endl;
           writer.stream() << "movl " << reg2 << ", -" << (m_position.offset() + 4) << "(ebp)" << endl;
       } else {
           writer.stream() << "movl " << reg1 << ", VS" << m_position.name() << endl;
           writer.stream() << "movl " << reg2 << ", VS" << m_position.name() << "+4" << endl;
       }
   }
}

void Variable::pushToStack(AssemblyFileWriter& writer){
    switch (m_type) {
        case INT:
            if(m_position.isStack()){
                writer.stream() << "pushl -" << m_position.offset() << "(ebp)" << std::endl;
            } else if(m_position.isGlobal()){
                writer.stream() << "pushl VI" << m_position.name() << std::endl;
            }

            break;
        case STRING:
            if(m_position.isStack()){
                writer.stream() << "pushl -" << m_position.offset() << "(ebp)" << std::endl;
                writer.stream() << "pushl -" << (m_position.offset() + 4) << "(ebp)" << std::endl;
            } else if(m_position.isGlobal()){
                writer.stream() << "pushl VS" << m_index << endl;
                writer.stream() << "pushl VS" << m_index << "+4" << std::endl;
            }

            break;
    }
}

void Variable::popFromStack(AssemblyFileWriter& writer){
    switch (m_type) {
        case INT:
            writer.stream() << "movl (%esp), %eax" << endl;
            writer.stream() << "addl $4, %esp" << endl;

            moveFromRegister(writer, "%eax");

            break;
        case STRING:
            writer.stream() << "movl (%esp), %eax" << endl;
            writer.stream() << "movl 4(%esp), %ebx" << endl;
            writer.stream() << "addl $8, %esp" << endl;

            moveFromRegister(writer, "%eax", "%ebx");

            break;
    }
}
<|endoftext|>


<commit_before>#include "IRVisitor.h"
#include "IR.h"

namespace Halide {
namespace Internal {

IRVisitor::~IRVisitor() {
}

void IRVisitor::visit(const IntImm *) {
}

void IRVisitor::visit(const FloatImm *) {
}

void IRVisitor::visit(const StringImm *) {
}

void IRVisitor::visit(const Cast *op) {
    op->value.accept(this);
}

void IRVisitor::visit(const Variable *) {
}

void IRVisitor::visit(const Add *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Sub *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Mul *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Div *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Mod *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Min *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Max *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const EQ *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const NE *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const LT *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const LE *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const GT *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const GE *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const And *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Or *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Not *op) {
    op->a.accept(this);
}

void IRVisitor::visit(const Select *op) {
    op->condition.accept(this);
    op->true_value.accept(this);
    op->false_value.accept(this);
}

void IRVisitor::visit(const Load *op) {
    op->index.accept(this);
}

void IRVisitor::visit(const Ramp *op) {
    op->base.accept(this);
    op->stride.accept(this);
}

void IRVisitor::visit(const Broadcast *op) {
    op->value.accept(this);
}

void IRVisitor::visit(const Call *op) {
    for (size_t i = 0; i < op->args.size(); i++) {
        op->args[i].accept(this);
    }

    // Consider extern call args
    Function f = op->func;
    if (op->call_type == Call::Halide && f.has_extern_definition()) {
        for (size_t i = 0; i < f.extern_arguments().size(); i++) {
            ExternFuncArgument arg = f.extern_arguments()[i];
            if (arg.is_expr()) {
                arg.expr.accept(this);
            }
        }
    }
}

void IRVisitor::visit(const Let *op) {
    op->value.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const LetStmt *op) {
    op->value.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const AssertStmt *op) {
    op->condition.accept(this);
    op->message.accept(this)
}

void IRVisitor::visit(const Pipeline *op) {
    op->produce.accept(this);
    if (op->update.defined()) op->update.accept(this);
    op->consume.accept(this);
}

void IRVisitor::visit(const For *op) {
    op->min.accept(this);
    op->extent.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const Store *op) {
    op->value.accept(this);
    op->index.accept(this);
}

void IRVisitor::visit(const Provide *op) {
    for (size_t i = 0; i < op->values.size(); i++) {
        op->values[i].accept(this);
    }
    for (size_t i = 0; i < op->args.size(); i++) {
        op->args[i].accept(this);
    }
}

void IRVisitor::visit(const Allocate *op) {
    for (size_t i = 0; i < op->extents.size(); i++) {
      op->extents[i].accept(this);
    }
    op->condition.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const Free *op) {
}

void IRVisitor::visit(const Realize *op) {
    for (size_t i = 0; i < op->bounds.size(); i++) {
        op->bounds[i].min.accept(this);
        op->bounds[i].extent.accept(this);
    }
    op->condition.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const Block *op) {
    op->first.accept(this);
    if (op->rest.defined()) {
        op->rest.accept(this);
    }
}

void IRVisitor::visit(const IfThenElse *op) {
    op->condition.accept(this);
    op->then_case.accept(this);
    if (op->else_case.defined()) {
        op->else_case.accept(this);
    }
}

void IRVisitor::visit(const Evaluate *op) {
    op->value.accept(this);
}

void IRGraphVisitor::include(const Expr &e) {
    if (visited.count(e.ptr)) {
        return;
    } else {
        visited.insert(e.ptr);
        e.accept(this);
        return;
    }
}

void IRGraphVisitor::include(const Stmt &s) {
    if (visited.count(s.ptr)) {
        return;
    } else {
        visited.insert(s.ptr);
        s.accept(this);
        return;
    }
}

void IRGraphVisitor::visit(const IntImm *) {
}

void IRGraphVisitor::visit(const FloatImm *) {
}

void IRGraphVisitor::visit(const StringImm *) {
}

void IRGraphVisitor::visit(const Cast *op) {
    include(op->value);
}

void IRGraphVisitor::visit(const Variable *op) {
}

void IRGraphVisitor::visit(const Add *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Sub *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Mul *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Div *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Mod *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Min *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Max *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const EQ *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const NE *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const LT *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const LE *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const GT *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const GE *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const And *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Or *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Not *op) {
    include(op->a);
}

void IRGraphVisitor::visit(const Select *op) {
    include(op->condition);
    include(op->true_value);
    include(op->false_value);
}

void IRGraphVisitor::visit(const Load *op) {
    include(op->index);
}

void IRGraphVisitor::visit(const Ramp *op) {
    include(op->base);
    include(op->stride);
}

void IRGraphVisitor::visit(const Broadcast *op) {
    include(op->value);
}

void IRGraphVisitor::visit(const Call *op) {
    for (size_t i = 0; i < op->args.size(); i++) {
        include(op->args[i]);
    }
}

void IRGraphVisitor::visit(const Let *op) {
    include(op->value);
    include(op->body);
}

void IRGraphVisitor::visit(const LetStmt *op) {
    include(op->value);
    include(op->body);
}

void IRGraphVisitor::visit(const AssertStmt *op) {
    include(op->condition);
    include(op->message);
}

void IRGraphVisitor::visit(const Pipeline *op) {
    include(op->produce);
    if (op->update.defined()) include(op->update);
    include(op->consume);
}

void IRGraphVisitor::visit(const For *op) {
    include(op->min);
    include(op->extent);
    include(op->body);
}

void IRGraphVisitor::visit(const Store *op) {
    include(op->value);
    include(op->index);
}

void IRGraphVisitor::visit(const Provide *op) {
    for (size_t i = 0; i < op->values.size(); i++) {
        include(op->values[i]);
    }
    for (size_t i = 0; i < op->args.size(); i++) {
        include(op->args[i]);
    }
}

void IRGraphVisitor::visit(const Allocate *op) {
    for (size_t i = 0; i < op->extents.size(); i++) {
        include(op->extents[i]);
    }
    include(op->condition);
    include(op->body);
}

void IRGraphVisitor::visit(const Free *op) {
}

void IRGraphVisitor::visit(const Realize *op) {
    for (size_t i = 0; i < op->bounds.size(); i++) {
        include(op->bounds[i].min);
        include(op->bounds[i].extent);
    }
    include(op->condition);
    include(op->body);
}

void IRGraphVisitor::visit(const Block *op) {
    include(op->first);
    if (op->rest.defined()) include(op->rest);
}

void IRGraphVisitor::visit(const IfThenElse *op) {
    include(op->condition);
    include(op->then_case);
    if (op->else_case.defined()) {
        include(op->else_case);
    }
}

void IRGraphVisitor::visit(const Evaluate *op) {
    include(op->value);
}

}
}
<commit_msg>Fix missing ;<commit_after>#include "IRVisitor.h"
#include "IR.h"

namespace Halide {
namespace Internal {

IRVisitor::~IRVisitor() {
}

void IRVisitor::visit(const IntImm *) {
}

void IRVisitor::visit(const FloatImm *) {
}

void IRVisitor::visit(const StringImm *) {
}

void IRVisitor::visit(const Cast *op) {
    op->value.accept(this);
}

void IRVisitor::visit(const Variable *) {
}

void IRVisitor::visit(const Add *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Sub *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Mul *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Div *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Mod *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Min *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Max *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const EQ *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const NE *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const LT *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const LE *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const GT *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const GE *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const And *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Or *op) {
    op->a.accept(this);
    op->b.accept(this);
}

void IRVisitor::visit(const Not *op) {
    op->a.accept(this);
}

void IRVisitor::visit(const Select *op) {
    op->condition.accept(this);
    op->true_value.accept(this);
    op->false_value.accept(this);
}

void IRVisitor::visit(const Load *op) {
    op->index.accept(this);
}

void IRVisitor::visit(const Ramp *op) {
    op->base.accept(this);
    op->stride.accept(this);
}

void IRVisitor::visit(const Broadcast *op) {
    op->value.accept(this);
}

void IRVisitor::visit(const Call *op) {
    for (size_t i = 0; i < op->args.size(); i++) {
        op->args[i].accept(this);
    }

    // Consider extern call args
    Function f = op->func;
    if (op->call_type == Call::Halide && f.has_extern_definition()) {
        for (size_t i = 0; i < f.extern_arguments().size(); i++) {
            ExternFuncArgument arg = f.extern_arguments()[i];
            if (arg.is_expr()) {
                arg.expr.accept(this);
            }
        }
    }
}

void IRVisitor::visit(const Let *op) {
    op->value.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const LetStmt *op) {
    op->value.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const AssertStmt *op) {
    op->condition.accept(this);
    op->message.accept(this);
}

void IRVisitor::visit(const Pipeline *op) {
    op->produce.accept(this);
    if (op->update.defined()) op->update.accept(this);
    op->consume.accept(this);
}

void IRVisitor::visit(const For *op) {
    op->min.accept(this);
    op->extent.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const Store *op) {
    op->value.accept(this);
    op->index.accept(this);
}

void IRVisitor::visit(const Provide *op) {
    for (size_t i = 0; i < op->values.size(); i++) {
        op->values[i].accept(this);
    }
    for (size_t i = 0; i < op->args.size(); i++) {
        op->args[i].accept(this);
    }
}

void IRVisitor::visit(const Allocate *op) {
    for (size_t i = 0; i < op->extents.size(); i++) {
      op->extents[i].accept(this);
    }
    op->condition.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const Free *op) {
}

void IRVisitor::visit(const Realize *op) {
    for (size_t i = 0; i < op->bounds.size(); i++) {
        op->bounds[i].min.accept(this);
        op->bounds[i].extent.accept(this);
    }
    op->condition.accept(this);
    op->body.accept(this);
}

void IRVisitor::visit(const Block *op) {
    op->first.accept(this);
    if (op->rest.defined()) {
        op->rest.accept(this);
    }
}

void IRVisitor::visit(const IfThenElse *op) {
    op->condition.accept(this);
    op->then_case.accept(this);
    if (op->else_case.defined()) {
        op->else_case.accept(this);
    }
}

void IRVisitor::visit(const Evaluate *op) {
    op->value.accept(this);
}

void IRGraphVisitor::include(const Expr &e) {
    if (visited.count(e.ptr)) {
        return;
    } else {
        visited.insert(e.ptr);
        e.accept(this);
        return;
    }
}

void IRGraphVisitor::include(const Stmt &s) {
    if (visited.count(s.ptr)) {
        return;
    } else {
        visited.insert(s.ptr);
        s.accept(this);
        return;
    }
}

void IRGraphVisitor::visit(const IntImm *) {
}

void IRGraphVisitor::visit(const FloatImm *) {
}

void IRGraphVisitor::visit(const StringImm *) {
}

void IRGraphVisitor::visit(const Cast *op) {
    include(op->value);
}

void IRGraphVisitor::visit(const Variable *op) {
}

void IRGraphVisitor::visit(const Add *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Sub *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Mul *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Div *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Mod *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Min *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Max *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const EQ *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const NE *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const LT *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const LE *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const GT *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const GE *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const And *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Or *op) {
    include(op->a);
    include(op->b);
}

void IRGraphVisitor::visit(const Not *op) {
    include(op->a);
}

void IRGraphVisitor::visit(const Select *op) {
    include(op->condition);
    include(op->true_value);
    include(op->false_value);
}

void IRGraphVisitor::visit(const Load *op) {
    include(op->index);
}

void IRGraphVisitor::visit(const Ramp *op) {
    include(op->base);
    include(op->stride);
}

void IRGraphVisitor::visit(const Broadcast *op) {
    include(op->value);
}

void IRGraphVisitor::visit(const Call *op) {
    for (size_t i = 0; i < op->args.size(); i++) {
        include(op->args[i]);
    }
}

void IRGraphVisitor::visit(const Let *op) {
    include(op->value);
    include(op->body);
}

void IRGraphVisitor::visit(const LetStmt *op) {
    include(op->value);
    include(op->body);
}

void IRGraphVisitor::visit(const AssertStmt *op) {
    include(op->condition);
    include(op->message);
}

void IRGraphVisitor::visit(const Pipeline *op) {
    include(op->produce);
    if (op->update.defined()) include(op->update);
    include(op->consume);
}

void IRGraphVisitor::visit(const For *op) {
    include(op->min);
    include(op->extent);
    include(op->body);
}

void IRGraphVisitor::visit(const Store *op) {
    include(op->value);
    include(op->index);
}

void IRGraphVisitor::visit(const Provide *op) {
    for (size_t i = 0; i < op->values.size(); i++) {
        include(op->values[i]);
    }
    for (size_t i = 0; i < op->args.size(); i++) {
        include(op->args[i]);
    }
}

void IRGraphVisitor::visit(const Allocate *op) {
    for (size_t i = 0; i < op->extents.size(); i++) {
        include(op->extents[i]);
    }
    include(op->condition);
    include(op->body);
}

void IRGraphVisitor::visit(const Free *op) {
}

void IRGraphVisitor::visit(const Realize *op) {
    for (size_t i = 0; i < op->bounds.size(); i++) {
        include(op->bounds[i].min);
        include(op->bounds[i].extent);
    }
    include(op->condition);
    include(op->body);
}

void IRGraphVisitor::visit(const Block *op) {
    include(op->first);
    if (op->rest.defined()) include(op->rest);
}

void IRGraphVisitor::visit(const IfThenElse *op) {
    include(op->condition);
    include(op->then_case);
    if (op->else_case.defined()) {
        include(op->else_case);
    }
}

void IRGraphVisitor::visit(const Evaluate *op) {
    include(op->value);
}

}
}
<|endoftext|>


<commit_before>//
// Basic analysis task.
//
// Basic analysis task template for analysis jets storing information in both tree
// branches and histograms

#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TTree.h>
#include <TList.h>
#include <AliAnalysisDataSlot.h>
#include <AliAnalysisDataContainer.h>
#include <TProfile.h>
#include <TChain.h>

// aliroot Headers
#include "AliAODEvent.h"
#include "AliParticleContainer.h"
#include "AliJetContainer.h"
#include "AliMCEvent.h"
#include "AliEmcalJet.h"

//My Header
#include "AliAnalysisTaskJetChargeFlavourTemplates.h"

//Globals
using std::cout;
using std::endl;

ClassImp(AliAnalysisTaskJetChargeFlavourTemplates)

//________________________________________________________________________
AliAnalysisTaskJetChargeFlavourTemplates::AliAnalysisTaskJetChargeFlavourTemplates() :
  AliAnalysisTaskEmcalJet("AliAnalysisTaskJetChargeFlavourTemplates", kTRUE),
  fContainer(0),
  pChain(0),
  fPtThreshold(-9999.),
  fCentSelectOn(kTRUE),
  fCentMin(0),
  fCentMax(10),
  fJetRadius(0),
  JetChargeK(0.5),
  Pt(-999),
  Phi(-999),
  Eta(-999),
  JetCharge(-999),
  ParticlePt(-999),
  ParticlePhi(-999),
  ParticleEta(-999),
  ParticleJetCharge(-999),
  LeadingTrackPt(-999),
  PdgCode(0),
  ProgenetorFraction(-1),

  fTreeJets(0)
{

}

//________________________________________________________________________
AliAnalysisTaskJetChargeFlavourTemplates::AliAnalysisTaskJetChargeFlavourTemplates(const char *name) :
  AliAnalysisTaskEmcalJet(name, kTRUE),
  fContainer(0),
  pChain(0),
  fPtThreshold(-9999.),
  fCentSelectOn(kTRUE),
  fCentMin(0),
  fCentMax(10),
  fJetRadius(0),
  JetChargeK(0.5),
  Pt(-999),
  Phi(-999),
  Eta(-999),
  JetCharge(-999),
  ParticlePt(-999),
  ParticlePhi(-999),
  ParticleEta(-999),
  ParticleJetCharge(-999),
  LeadingTrackPt(-999),
  PdgCode(0),
  ProgenetorFraction(-1),

  fTreeJets(0)
{

  SetMakeGeneralHistograms(kTRUE);
  DefineOutput(1, TList::Class());
  DefineOutput(2, TTree::Class());
}

//________________________________________________________________________
AliAnalysisTaskJetChargeFlavourTemplates::~AliAnalysisTaskJetChargeFlavourTemplates()
{
  // Destructor.
}

//________________________________________________________________________
 void AliAnalysisTaskJetChargeFlavourTemplates::UserCreateOutputObjects()
{
  // Echo jet radius
  //Info("TaskJets","Using jet radius R=%f",fJetRadius);

  // Create user output.
  AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
  Bool_t oldStatus = TH1::AddDirectoryStatus();
  TH1::AddDirectory(kFALSE);
  TH1::AddDirectory(oldStatus);
  //create output TTree
  const char* nameoutput = GetOutputSlot(2)->GetContainer()->GetName();
  fTreeJets = new TTree(nameoutput, nameoutput);
  // Names for the branches

  // Name the branches of your TTree here

  fTreeJets->Branch("Pt",&Pt,"Pt/F");
  fTreeJets->Branch("Phi",&Phi,"Phi/F");
  fTreeJets->Branch("Eta",&Eta,"Eta/F");
  fTreeJets->Branch("JetCharge",&JetCharge,"JetCharge/F");
  fTreeJets->Branch("ParticlePt",&ParticlePt,"ParticlePt/F");
  fTreeJets->Branch("ParticlePhi",&ParticlePhi,"ParticlePhi/F");
  fTreeJets->Branch("ParticleEta",&ParticleEta,"ParticleEta/F");
  fTreeJets->Branch("ParticleJetCharge",&ParticleJetCharge,"ParticleJetCharge/F");
  fTreeJets->Branch("LeadingTrackPt",&LeadingTrackPt,"LeadingTrackPt/F");
  fTreeJets->Branch("PdgCode",&PdgCode,"pdgcode/I");
  fTreeJets->Branch("ProgenetorFraction",&ProgenetorFraction,"ProgenetorFraction/F");

  // Make sure that the outputs get written out
  PostData(1,fOutput);
  PostData(2,fTreeJets);
  // delete [] fShapesVarNames;
}

//________________________________________________________________________
Bool_t AliAnalysisTaskJetChargeFlavourTemplates::Run()
{
  // Run analysis code here, if needed. It will be executed before FillHistograms().

  return kTRUE;
}

//________________________________________________________________________
Bool_t AliAnalysisTaskJetChargeFlavourTemplates::FillHistograms()
{
  // Centrality selection, if enabled
  if (fCentSelectOn){
    if ((fCent>fCentMax) || (fCent<fCentMin))
      return 0;
  }

  // Reset the Tree Parameters
  Pt = -999;
  Phi = -999;
  Eta = -999;
  JetCharge = -999;
  ParticlePt  = -999;
  ParticlePhi = -999;
  ParticleEta = -999;
  ParticleJetCharge = -999;
  LeadingTrackPt = -999;
  PdgCode = 0;
  ProgenetorFraction = -1;

  // Initialise Jet shapes
  Int_t fPdgCodes[100] = {};
  Int_t fCurrentPdg = 0;
  Int_t nMothers = 0;
  Float_t jetCharge = 0;
  Float_t jetChargeParticle = 0;

  Int_t fParticleUniqueID[100] = {};
  Int_t fCurrentParticleUniqueID = 0;

  // Initialise jet pointer
  //cout << "Running Fill Histograms" << endl;
  AliEmcalJet *Jet1 = NULL; //Original Jet in the event                                                                                // Get jet container (0 = ?)
  AliJetContainer *JetCont= GetJetContainer(0); //Jet Container for event
  AliEmcalJet *TruthJet = NULL; //Original Jet in the event                                                                                // Get jet container (0 = ?)
  AliJetContainer *JetGen= GetJetContainer(1); //Jet Container for event

  AliParticleContainer *MCParticleContainer = JetGen->GetParticleContainer();
  Int_t nAcceptedJets = JetCont->GetNAcceptedJets();
  //TClonesArray *trackArr = dynamic_cast<TClonesArray*>(InputEvent()->FindListObject("HybridTracks"));
  Float_t JetPhi=0;
  Float_t JetParticlePhi=0;
  Float_t JetPt_ForThreshold=0;

  if(JetCont) {

    for (auto Jet1 : JetCont->accepted()) {
      // ...

      if(!Jet1)
      {

        continue;
      }

      // Jet is above threshold?

      //cout << "Running A Jet" << endl;

      // Get the jet constituents

      //AliParticleContainer *fMCContainer = GetParticleContainer(1);
      //UInt_t nMCConstituents = fMCContainer->GetNParticles();

      //AliParticleContainer * MCTracks  = dynamic_cast<AliParticleContainer *> (GetParticleContainer("embeddedTracks"));
      //UInt_t nMCTracks = MCTracks->GetNParticles();

      /*
      TIter nextPartColl(&fParticleCollArray);
      AliParticleContainer* tracks = 0;
      while ((tracks = static_cast<AliParticleContainer*>(nextPartColl())))
      {
      AliParticleContainer* fMCContainer = tracks;
      }
      */

      AliParticleContainer *fTrackCont = JetCont->GetParticleContainer();
      UInt_t nJetConstituents = Jet1->GetNumberOfTracks();

      //cout << nTest << "::::" << nMCConstituents << "::::" << nJetConstituents << endl;

      // Must have at least two constituents
      if( nJetConstituents < 2 )
      {
        continue;
      }

      JetPt_ForThreshold = Jet1->Pt();

      if(JetPt_ForThreshold<fPtThreshold)
      {

        continue;
      }
      else {

        //Check the jet leading track is Greater than 5 GeV to reduce cominatorial jets

        if(Jet1->GetLeadingTrack()->Pt() < 5)
        {
            continue;
        }

        LeadingTrackPt = Jet1->GetLeadingTrack()->Pt();

        // Initialising the Tagged PYTHIA Jet.
        Bool_t kHasTruthJet = kFALSE;
        AliEmcalJet* TruthJet;
        UInt_t nTruthConstituents;

        if(Jet1->ClosestJet() != NULL)
        {
          kHasTruthJet = kTRUE;
          TruthJet = Jet1->ClosestJet();
          nTruthConstituents = TruthJet->GetNumberOfTracks();

        }

        //Finding Pdg Code using TRUTH Jet.

        if(kHasTruthJet)
        {

          if(TruthJet->Pt()<fPtThreshold)
          {

            continue;
          }

          //std::cout <<"Leading Track Pt" <<  Jet1->GetLeadingTrack()->Pt()<< std::endl;

          // Filling the Tree here

          JetPhi=Jet1->Phi();
          if(JetPhi < -1*TMath::Pi())
            JetPhi += (2*TMath::Pi());
          else if (JetPhi > TMath::Pi())
            JetPhi -= (2*TMath::Pi());

          JetParticlePhi=TruthJet->Phi();
          if(JetParticlePhi < -1*TMath::Pi())
            JetParticlePhi += (2*TMath::Pi());
          else if (JetParticlePhi > TMath::Pi())
            JetParticlePhi -= (2*TMath::Pi());

          // Filling the TTree branches here
          Pt          = Jet1->Pt();
          Phi         = JetPhi;
          Eta         = Jet1->Eta();

          ParticlePt  = TruthJet->Pt();
          ParticlePhi = JetParticlePhi;
          ParticleEta = TruthJet->Eta();

          // Identifing PDG Codes of Mothers
          for (UInt_t iTruthConst = 0; iTruthConst < nTruthConstituents; iTruthConst++ )
          {
            AliMCParticle* TruthParticle = (AliMCParticle*) TruthJet->Track(iTruthConst);
            AliMCParticle *MotherParticle = (AliMCParticle*)  MCParticleContainer->GetParticle(TruthParticle->GetMother());
            while(MotherParticle->GetMother() > 0)
            {
              MotherParticle = (AliMCParticle*) MCParticleContainer->GetParticle(MotherParticle->GetMother());
            }
            // Insure this isnt a beam proton
            if(MotherParticle->PdgCode() != 2212)
            {

            fCurrentParticleUniqueID = MotherParticle->GetLabel();
            fCurrentPdg = MotherParticle->PdgCode();
            fPdgCodes[nMothers] = fCurrentPdg;
            fParticleUniqueID[nMothers] = fCurrentParticleUniqueID;

            //cout << fPdgCodes[nMothers] << endl;
            nMothers++;

            }
          }

          Int_t UniquePdgCodes[20] = {};            //To be filled, maximium is that there are  20 uniques
          Float_t UniquePdgFrequency[20] = {};
          Int_t nUniques = 0;

          //Loop of PDG code found
          for(int i = 0; i < nMothers; i++)
          {

            // Consider one pdgCode at the time.
            fCurrentPdg = fPdgCodes[i];
            // Loop over unique arry to be filled

            for(int j = 0; j < nMothers; j++)
            {

              // If it hasnt matched and the current unique value is empty list the new value and increment frequncy by 1 and then break
              if(UniquePdgCodes[j] != fCurrentPdg && UniquePdgCodes[j] == 0)
              {
                UniquePdgCodes[j] = fCurrentPdg;
                UniquePdgFrequency[j] = UniquePdgFrequency[j] + 1.;
                nUniques ++;
                break;
              }

              //Check if the PDG is already lsited if it matched increase the frequency counter by 1
              else if(UniquePdgCodes[j] == fCurrentPdg)
              {
                UniquePdgFrequency[j] = UniquePdgFrequency[j] + 1.;
                break;
              }
              // Otherwise the PDG hasnt matched and the value isnt zero check the next value

            }
          }

          // Setting Final Pdg Code
          // normalising frequency array

          for(unsigned int i = 0; i < nUniques; i++)
          {
            UniquePdgFrequency[i] = UniquePdgFrequency[i]/nMothers;
          }

         // Loop to store largest number And corresponding pdg code
          Float_t CurrentFraction;

          int IndexOfMaximum = -1;
          CurrentFraction = UniquePdgFrequency[0];
          for(unsigned int i = 0;i < nUniques; ++i)
          {
            if(UniquePdgFrequency[i] >= CurrentFraction)
            {
              IndexOfMaximum = i;
              CurrentFraction = UniquePdgFrequency[i];
            }
          }

          ProgenetorFraction = CurrentFraction;
          fCurrentPdg = fPdgCodes[IndexOfMaximum];

          // Now Caluclate the jet Charge

          // Loop over the consituents
          for (UInt_t iJetConst = 0; iJetConst < nJetConstituents; iJetConst++ )
          {
            AliVParticle *JetParticle = Jet1->Track(iJetConst);
            jetCharge += JetParticle->Charge()*pow(JetParticle->Pt(),JetChargeK);
          }

          for (UInt_t iTruthConst = 0; iTruthConst < nTruthConstituents; iTruthConst++ )
          {
            AliMCParticle* TruthParticle = (AliMCParticle*) TruthJet->Track(iTruthConst);
            //Divided by 3 since its parton level and in units of e/3
            jetChargeParticle += TruthParticle->Charge()/3*pow(TruthParticle->Pt(),JetChargeK);
          }

          // Normalise the Non Flavoured Jet CHarge
          jetCharge/=pow(Jet1->Pt(),0.5);

          // Normalise Particle level jet charge
          jetChargeParticle/=pow(TruthJet->Pt(),0.5);

          //Put The Jet Charge in the right place
          JetCharge = jetCharge;
          ParticleJetCharge = jetChargeParticle;

          PdgCode = fCurrentPdg;

          //Outputs for Checking
          if(fCurrentPdg > 30000)
          {
          cout << "Final PDG CODE: " << fCurrentPdg << endl;
          cout << "Progenetor Fraction: " << ProgenetorFraction << endl;

          //Output Frequency of Uniques
          cout << "Frequency of Uniques: [" ;
          for(int i = 0; i < nUniques; i++)
          {
            cout << UniquePdgFrequency[i] << "," ;
          }
          cout << "] " << endl;

          //Output for checking the list of raw pdgCodes
          cout << "Pdg Codes: [" ;
          for(int i = 0; i < nMothers; i++)
          {
            cout << fPdgCodes[i] << "," ;
          }
          cout << "] " << endl;

          //Outputs for checking Raw ParticleUniqueIDs
          cout << "Particle Label: [" ;
          for(int i = 0; i < nMothers; i++)
          {
            cout << fParticleUniqueID[i] << "," ;
          }
          cout << "] " << endl;

          }

          fTreeJets->Fill();

      }

      //cout << "End of Jet" << endl;
      }
    }
  }
  return kTRUE;
}

//________________________________________________________________________
Bool_t AliAnalysisTaskJetChargeFlavourTemplates::RetrieveEventObjects() {
  //
  // retrieve event objects
  //
  if (!AliAnalysisTaskEmcalJet::RetrieveEventObjects())
    return kFALSE;

  return kTRUE;
}

//_______________________________________________________________________
void AliAnalysisTaskJetChargeFlavourTemplates::Terminate(Option_t *)
{
  // Called once at the end of the analysis.

  // Normalise historgrams over number of Jets considered

}
<commit_msg>Removed the output  to terminal used for debugging accidently left in.<commit_after>//
// Basic analysis task.
//
// Basic analysis task template for analysis jets storing information in both tree
// branches and histograms

#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TTree.h>
#include <TList.h>
#include <AliAnalysisDataSlot.h>
#include <AliAnalysisDataContainer.h>
#include <TProfile.h>
#include <TChain.h>

// aliroot Headers
#include "AliAODEvent.h"
#include "AliParticleContainer.h"
#include "AliJetContainer.h"
#include "AliMCEvent.h"
#include "AliEmcalJet.h"

//My Header
#include "AliAnalysisTaskJetChargeFlavourTemplates.h"

//Globals
using std::cout;
using std::endl;

ClassImp(AliAnalysisTaskJetChargeFlavourTemplates)

//________________________________________________________________________
AliAnalysisTaskJetChargeFlavourTemplates::AliAnalysisTaskJetChargeFlavourTemplates() :
  AliAnalysisTaskEmcalJet("AliAnalysisTaskJetChargeFlavourTemplates", kTRUE),
  fContainer(0),
  pChain(0),
  fPtThreshold(-9999.),
  fCentSelectOn(kTRUE),
  fCentMin(0),
  fCentMax(10),
  fJetRadius(0),
  JetChargeK(0.5),
  Pt(-999),
  Phi(-999),
  Eta(-999),
  JetCharge(-999),
  ParticlePt(-999),
  ParticlePhi(-999),
  ParticleEta(-999),
  ParticleJetCharge(-999),
  LeadingTrackPt(-999),
  PdgCode(0),
  ProgenetorFraction(-1),

  fTreeJets(0)
{

}

//________________________________________________________________________
AliAnalysisTaskJetChargeFlavourTemplates::AliAnalysisTaskJetChargeFlavourTemplates(const char *name) :
  AliAnalysisTaskEmcalJet(name, kTRUE),
  fContainer(0),
  pChain(0),
  fPtThreshold(-9999.),
  fCentSelectOn(kTRUE),
  fCentMin(0),
  fCentMax(10),
  fJetRadius(0),
  JetChargeK(0.5),
  Pt(-999),
  Phi(-999),
  Eta(-999),
  JetCharge(-999),
  ParticlePt(-999),
  ParticlePhi(-999),
  ParticleEta(-999),
  ParticleJetCharge(-999),
  LeadingTrackPt(-999),
  PdgCode(0),
  ProgenetorFraction(-1),

  fTreeJets(0)
{

  SetMakeGeneralHistograms(kTRUE);
  DefineOutput(1, TList::Class());
  DefineOutput(2, TTree::Class());
}

//________________________________________________________________________
AliAnalysisTaskJetChargeFlavourTemplates::~AliAnalysisTaskJetChargeFlavourTemplates()
{
  // Destructor.
}

//________________________________________________________________________
 void AliAnalysisTaskJetChargeFlavourTemplates::UserCreateOutputObjects()
{
  // Echo jet radius
  //Info("TaskJets","Using jet radius R=%f",fJetRadius);

  // Create user output.
  AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
  Bool_t oldStatus = TH1::AddDirectoryStatus();
  TH1::AddDirectory(kFALSE);
  TH1::AddDirectory(oldStatus);
  //create output TTree
  const char* nameoutput = GetOutputSlot(2)->GetContainer()->GetName();
  fTreeJets = new TTree(nameoutput, nameoutput);
  // Names for the branches

  // Name the branches of your TTree here

  fTreeJets->Branch("Pt",&Pt,"Pt/F");
  fTreeJets->Branch("Phi",&Phi,"Phi/F");
  fTreeJets->Branch("Eta",&Eta,"Eta/F");
  fTreeJets->Branch("JetCharge",&JetCharge,"JetCharge/F");
  fTreeJets->Branch("ParticlePt",&ParticlePt,"ParticlePt/F");
  fTreeJets->Branch("ParticlePhi",&ParticlePhi,"ParticlePhi/F");
  fTreeJets->Branch("ParticleEta",&ParticleEta,"ParticleEta/F");
  fTreeJets->Branch("ParticleJetCharge",&ParticleJetCharge,"ParticleJetCharge/F");
  fTreeJets->Branch("LeadingTrackPt",&LeadingTrackPt,"LeadingTrackPt/F");
  fTreeJets->Branch("PdgCode",&PdgCode,"pdgcode/I");
  fTreeJets->Branch("ProgenetorFraction",&ProgenetorFraction,"ProgenetorFraction/F");

  // Make sure that the outputs get written out
  PostData(1,fOutput);
  PostData(2,fTreeJets);
  // delete [] fShapesVarNames;
}

//________________________________________________________________________
Bool_t AliAnalysisTaskJetChargeFlavourTemplates::Run()
{
  // Run analysis code here, if needed. It will be executed before FillHistograms().

  return kTRUE;
}

//________________________________________________________________________
Bool_t AliAnalysisTaskJetChargeFlavourTemplates::FillHistograms()
{
  // Centrality selection, if enabled
  if (fCentSelectOn){
    if ((fCent>fCentMax) || (fCent<fCentMin))
      return 0;
  }

  // Reset the Tree Parameters
  Pt = -999;
  Phi = -999;
  Eta = -999;
  JetCharge = -999;
  ParticlePt  = -999;
  ParticlePhi = -999;
  ParticleEta = -999;
  ParticleJetCharge = -999;
  LeadingTrackPt = -999;
  PdgCode = 0;
  ProgenetorFraction = -1;

  // Initialise Jet shapes
  Int_t fPdgCodes[100] = {};
  Int_t fCurrentPdg = 0;
  Int_t nMothers = 0;
  Float_t jetCharge = 0;
  Float_t jetChargeParticle = 0;

  Int_t fParticleUniqueID[100] = {};
  Int_t fCurrentParticleUniqueID = 0;

  // Initialise jet pointer
  //cout << "Running Fill Histograms" << endl;
  AliEmcalJet *Jet1 = NULL; //Original Jet in the event                                                                                // Get jet container (0 = ?)
  AliJetContainer *JetCont= GetJetContainer(0); //Jet Container for event
  AliEmcalJet *TruthJet = NULL; //Original Jet in the event                                                                                // Get jet container (0 = ?)
  AliJetContainer *JetGen= GetJetContainer(1); //Jet Container for event

  AliParticleContainer *MCParticleContainer = JetGen->GetParticleContainer();
  Int_t nAcceptedJets = JetCont->GetNAcceptedJets();
  //TClonesArray *trackArr = dynamic_cast<TClonesArray*>(InputEvent()->FindListObject("HybridTracks"));
  Float_t JetPhi=0;
  Float_t JetParticlePhi=0;
  Float_t JetPt_ForThreshold=0;

  if(JetCont) {

    for (auto Jet1 : JetCont->accepted()) {
      // ...

      if(!Jet1)
      {

        continue;
      }

      // Jet is above threshold?

      //cout << "Running A Jet" << endl;

      // Get the jet constituents

      //AliParticleContainer *fMCContainer = GetParticleContainer(1);
      //UInt_t nMCConstituents = fMCContainer->GetNParticles();

      //AliParticleContainer * MCTracks  = dynamic_cast<AliParticleContainer *> (GetParticleContainer("embeddedTracks"));
      //UInt_t nMCTracks = MCTracks->GetNParticles();

      /*
      TIter nextPartColl(&fParticleCollArray);
      AliParticleContainer* tracks = 0;
      while ((tracks = static_cast<AliParticleContainer*>(nextPartColl())))
      {
      AliParticleContainer* fMCContainer = tracks;
      }
      */

      AliParticleContainer *fTrackCont = JetCont->GetParticleContainer();
      UInt_t nJetConstituents = Jet1->GetNumberOfTracks();

      //cout << nTest << "::::" << nMCConstituents << "::::" << nJetConstituents << endl;

      // Must have at least two constituents
      if( nJetConstituents < 2 )
      {
        continue;
      }

      JetPt_ForThreshold = Jet1->Pt();

      if(JetPt_ForThreshold<fPtThreshold)
      {

        continue;
      }
      else {

        //Check the jet leading track is Greater than 5 GeV to reduce cominatorial jets

        if(Jet1->GetLeadingTrack()->Pt() < 5)
        {
            continue;
        }

        LeadingTrackPt = Jet1->GetLeadingTrack()->Pt();

        // Initialising the Tagged PYTHIA Jet.
        Bool_t kHasTruthJet = kFALSE;
        AliEmcalJet* TruthJet;
        UInt_t nTruthConstituents;

        if(Jet1->ClosestJet() != NULL)
        {
          kHasTruthJet = kTRUE;
          TruthJet = Jet1->ClosestJet();
          nTruthConstituents = TruthJet->GetNumberOfTracks();

        }

        //Finding Pdg Code using TRUTH Jet.

        if(kHasTruthJet)
        {

          if(TruthJet->Pt()<fPtThreshold)
          {

            continue;
          }

          //std::cout <<"Leading Track Pt" <<  Jet1->GetLeadingTrack()->Pt()<< std::endl;

          // Filling the Tree here

          JetPhi=Jet1->Phi();
          if(JetPhi < -1*TMath::Pi())
            JetPhi += (2*TMath::Pi());
          else if (JetPhi > TMath::Pi())
            JetPhi -= (2*TMath::Pi());

          JetParticlePhi=TruthJet->Phi();
          if(JetParticlePhi < -1*TMath::Pi())
            JetParticlePhi += (2*TMath::Pi());
          else if (JetParticlePhi > TMath::Pi())
            JetParticlePhi -= (2*TMath::Pi());

          // Filling the TTree branches here
          Pt          = Jet1->Pt();
          Phi         = JetPhi;
          Eta         = Jet1->Eta();

          ParticlePt  = TruthJet->Pt();
          ParticlePhi = JetParticlePhi;
          ParticleEta = TruthJet->Eta();

          // Identifing PDG Codes of Mothers
          for (UInt_t iTruthConst = 0; iTruthConst < nTruthConstituents; iTruthConst++ )
          {
            AliMCParticle* TruthParticle = (AliMCParticle*) TruthJet->Track(iTruthConst);
            AliMCParticle *MotherParticle = (AliMCParticle*)  MCParticleContainer->GetParticle(TruthParticle->GetMother());
            while(MotherParticle->GetMother() > 0)
            {
              MotherParticle = (AliMCParticle*) MCParticleContainer->GetParticle(MotherParticle->GetMother());
            }
            // Insure this isnt a beam proton
            if(MotherParticle->PdgCode() != 2212)
            {

            fCurrentParticleUniqueID = MotherParticle->GetLabel();
            fCurrentPdg = MotherParticle->PdgCode();
            fPdgCodes[nMothers] = fCurrentPdg;
            fParticleUniqueID[nMothers] = fCurrentParticleUniqueID;

            //cout << fPdgCodes[nMothers] << endl;
            nMothers++;

            }
          }

          Int_t UniquePdgCodes[20] = {};            //To be filled, maximium is that there are  20 uniques
          Float_t UniquePdgFrequency[20] = {};
          Int_t nUniques = 0;

          //Loop of PDG code found
          for(int i = 0; i < nMothers; i++)
          {

            // Consider one pdgCode at the time.
            fCurrentPdg = fPdgCodes[i];
            // Loop over unique arry to be filled

            for(int j = 0; j < nMothers; j++)
            {

              // If it hasnt matched and the current unique value is empty list the new value and increment frequncy by 1 and then break
              if(UniquePdgCodes[j] != fCurrentPdg && UniquePdgCodes[j] == 0)
              {
                UniquePdgCodes[j] = fCurrentPdg;
                UniquePdgFrequency[j] = UniquePdgFrequency[j] + 1.;
                nUniques ++;
                break;
              }

              //Check if the PDG is already lsited if it matched increase the frequency counter by 1
              else if(UniquePdgCodes[j] == fCurrentPdg)
              {
                UniquePdgFrequency[j] = UniquePdgFrequency[j] + 1.;
                break;
              }
              // Otherwise the PDG hasnt matched and the value isnt zero check the next value

            }
          }

          // Setting Final Pdg Code
          // normalising frequency array

          for(unsigned int i = 0; i < nUniques; i++)
          {
            UniquePdgFrequency[i] = UniquePdgFrequency[i]/nMothers;
          }

         // Loop to store largest number And corresponding pdg code
          Float_t CurrentFraction;

          int IndexOfMaximum = -1;
          CurrentFraction = UniquePdgFrequency[0];
          for(unsigned int i = 0;i < nUniques; ++i)
          {
            if(UniquePdgFrequency[i] >= CurrentFraction)
            {
              IndexOfMaximum = i;
              CurrentFraction = UniquePdgFrequency[i];
            }
          }

          ProgenetorFraction = CurrentFraction;
          fCurrentPdg = fPdgCodes[IndexOfMaximum];

          // Now Caluclate the jet Charge

          // Loop over the consituents
          for (UInt_t iJetConst = 0; iJetConst < nJetConstituents; iJetConst++ )
          {
            AliVParticle *JetParticle = Jet1->Track(iJetConst);
            jetCharge += JetParticle->Charge()*pow(JetParticle->Pt(),JetChargeK);
          }

          for (UInt_t iTruthConst = 0; iTruthConst < nTruthConstituents; iTruthConst++ )
          {
            AliMCParticle* TruthParticle = (AliMCParticle*) TruthJet->Track(iTruthConst);
            //Divided by 3 since its parton level and in units of e/3
            jetChargeParticle += TruthParticle->Charge()/3*pow(TruthParticle->Pt(),JetChargeK);
          }

          // Normalise the Non Flavoured Jet CHarge
          jetCharge/=pow(Jet1->Pt(),0.5);

          // Normalise Particle level jet charge
          jetChargeParticle/=pow(TruthJet->Pt(),0.5);

          //Put The Jet Charge in the right place
          JetCharge = jetCharge;
          ParticleJetCharge = jetChargeParticle;

          PdgCode = fCurrentPdg;

          //Outputs for Checking
          /*
          cout << "Final PDG CODE: " << fCurrentPdg << endl;
          cout << "Progenetor Fraction: " << ProgenetorFraction << endl;

          //Output Frequency of Uniques
          cout << "Frequency of Uniques: [" ;
          for(int i = 0; i < nUniques; i++)
          {
            cout << UniquePdgFrequency[i] << "," ;
          }
          cout << "] " << endl;

          //Output for checking the list of raw pdgCodes
          cout << "Pdg Codes: [" ;
          for(int i = 0; i < nMothers; i++)
          {
            cout << fPdgCodes[i] << "," ;
          }
          cout << "] " << endl;

          //Outputs for checking Raw ParticleUniqueIDs
          cout << "Particle Label: [" ;
          for(int i = 0; i < nMothers; i++)
          {
            cout << fParticleUniqueID[i] << "," ;
          }
          cout << "] " << endl;

          */

          fTreeJets->Fill();

      }

      //cout << "End of Jet" << endl;
      }
    }
  }
  return kTRUE;
}

//________________________________________________________________________
Bool_t AliAnalysisTaskJetChargeFlavourTemplates::RetrieveEventObjects() {
  //
  // retrieve event objects
  //
  if (!AliAnalysisTaskEmcalJet::RetrieveEventObjects())
    return kFALSE;

  return kTRUE;
}

//_______________________________________________________________________
void AliAnalysisTaskJetChargeFlavourTemplates::Terminate(Option_t *)
{
  // Called once at the end of the analysis.

  // Normalise historgrams over number of Jets considered

}
<|endoftext|>