<commit_before>// GeometryTiler.cpp : Defines the entry point for the console application.
//

#include <chrono>
#include <fstream>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

#include <FileGDBAPI.h>

#ifndef _DEBUG
    #pragma comment(lib, "lib/FileGDBAPI.lib")
#else
    #pragma comment(lib, "lib/FileGDBAPID.lib")
#endif

// Nicely logs the provided error message and error code.
void LogError(std::wstring errorMessage, fgdbError errorCode)
{
    std::wcout << errorMessage << std::endl;

    std::wstring errorText;
    FileGDBAPI::ErrorInfo::GetErrorDescription(errorCode, errorText);
    std::wcout << "Error: " << errorText << "[" << errorCode << "]" << std::endl;
}

// Processes an individual row.
void ProcessRow(FileGDBAPI::Row& row)
{
    // TODO this is a good point to move into a class.
    fgdbError result;
    FileGDBAPI::ShapeBuffer shapeBuffer;
    if ((result = row.GetGeometry(shapeBuffer)) != S_OK)
    {
        LogError(L"Error loading the shape buffer!", result);
        return;
    }
}

// Processes the provided Table.
void ProcessTable(FileGDBAPI::Table& table)
{
    std::string tableDefinition;

    fgdbError result;
    if ((result = table.GetDefinition(tableDefinition)) != S_OK)
    {
        LogError(L"Error loading the table definition!", result);
        return;
    }

    std::ofstream defFile("table.xml");
    if (!defFile)
    {
        std::cout << "Could not open the file to write the table definition to!" << std::endl;
        return;
    }

    defFile << tableDefinition.c_str();
    defFile.close();
    std::cout << "Table definition has been written to a readable file." << std::endl;

    std::string documentation;
    if ((result = table.GetDocumentation(documentation)) != S_OK)
    {
        LogError(L"Error loading the table documentation!", result);
        return;
    }

    std::ofstream docFile("documentation.xml");
    if (!docFile)
    {
        std::cout << "Could not open the file to write documentation to!" << std::endl;
        return;
    }

    docFile << documentation.c_str();
    docFile.close();
    std::cout << "Documentation has been written to a readable-file." << std::endl;

    FileGDBAPI::Envelope extent;
    if ((result = table.GetExtent(extent)) != S_OK)
    {
        LogError(L"Error loading the table extent!", result);
        return;
    }

    std::cout << "Extent: [" << extent.xMin << ", " << extent.yMin << ", " << extent.zMin << "] to ["
        << extent.xMax << ", " << extent.yMax << ", " << extent.zMax << "]" << std::endl;

    int rowCount;
    if ((result = table.GetRowCount(rowCount)) != S_OK)
    {
        LogError(L"Error loading the table row count!", result);
        return;
    }

    std::cout << "Rows: " << rowCount << std::endl;

    FileGDBAPI::EnumRows allRows;
    std::cout << "Searching ALL rows in the database..." << std::endl;
    if ((result = table.Search(L"*", L"", extent, true, allRows)) != S_OK)
    {
        LogError(L"Error searching for all rows!", result);
        return;
    }

    std::cout << "Counting returned rows..." << std::endl;
    FileGDBAPI::Row row;
    int foundRowCount = 0;
    while (allRows.Next(row) == S_OK)
    {
        ++foundRowCount;
        if (foundRowCount % 1000 == 0)
        {
            std::cout << "  " << foundRowCount << std::endl;
        }

        ProcessRow(row);
    }

    allRows.Close();
    std::cout << "Counted " << foundRowCount << " returned rows (versus " << rowCount << " total rows)" << std::endl;
    if (foundRowCount != rowCount)
    {
        std::cout << "Warning: Didn't read all the data from the database!" << std::endl;
        return;
    }
}

// Processes the provided Geodatabase.
void ProcessGeodatabase(FileGDBAPI::Geodatabase& geodatabase)
{
    // Types
    std::vector<std::wstring> datasetTypes;

    std::wcout << L"Reading dataset types..." << std::endl;
    fgdbError result;
    if ((result = geodatabase.GetDatasetTypes(datasetTypes)) != S_OK)
    {
        LogError(L"Error loading the dataset types!", result);
        return;
    }

    std::wcout << L"Read " << datasetTypes.size() << " dataset types." << std::endl;
    for (unsigned int i = 0; i < datasetTypes.size(); i++)
    {
        std::wcout << L"  " << datasetTypes[i] << std::endl;
    }

    // Relationship types
    std::vector<std::wstring> datasetRelationshipTypes;

    std::wcout << L"Reading dataset relationship types..." << std::endl;
    if ((result = geodatabase.GetDatasetRelationshipTypes(datasetTypes)) != S_OK)
    {
        LogError(L"Error loading the dataset relationship types!", result);
        return;
    }

    std::wcout << L"Read " << datasetRelationshipTypes.size() << " dataset relationship types." << std::endl;
    for (unsigned int i = 0; i < datasetRelationshipTypes.size(); i++)
    {
        std::wcout << L"  " << datasetRelationshipTypes[i] << std::endl;
    }

    // Domains
    std::vector<std::wstring> datasetDomains;

    std::wcout << L"Reading dataset domains..." << std::endl;
    if ((result = geodatabase.GetDomains(datasetTypes)) != S_OK)
    {
        LogError(L"Error loading the dataset domains!", result);
        return;
    }

    std::wcout << L"Read " << datasetDomains.size() << " dataset domains." << std::endl;
    for (unsigned int i = 0; i < datasetDomains.size(); i++)
    {
        std::wcout << L"  " << datasetDomains[i] << std::endl;
    }

    std::vector<std::wstring> childDatasets;

    std::wcout << L"Reading child datasets..." << std::endl;
    if ((result = geodatabase.GetChildDatasets(L"\\", L"", childDatasets)) != S_OK)
    {
        LogError(L"Error loading the child datasets!", result);
        return;
    }

    std::wcout << L"Read " << childDatasets.size() << " child datasets." << std::endl;
    for (unsigned int i = 0; i < childDatasets.size(); i++)
    {
        std::wcout << L"  " << childDatasets[i] << std::endl;
    }

    std::wstring datasetType;
    std::vector<std::string> childDatasetDefinitions;

    std::wcout << L"Reading primary dataset type..." << std::endl;
    if ((result = geodatabase.GetChildDatasetDefinitions(L"\\CONTOUR005_LINE", datasetType, childDatasetDefinitions)) != S_OK)
    {
        LogError(L"Error loading the primary dataset definition info!", result);
        return;
    }

    std::wcout << L"The primary dataset is of type '" << datasetType << "'." << std::endl;
    for (unsigned int i = 0; i < childDatasetDefinitions.size(); i++)
    {
        std::cout << "  " << childDatasetDefinitions[i] << std::endl;
    }

    // Open the primary table
    FileGDBAPI::Table table;
    std::wcout << "Reading in the primary table..." << std::endl;
    if ((result = geodatabase.OpenTable(L"\\CONTOUR005_LINE", table)) != S_OK)
    {
        LogError(L"Error loading the table!", result);
        return;
    }

    std::wcout << "Primary table opened." << std::endl;

    ProcessTable(table);

    std::wcout << "Closing the primary table..." << std::endl;
    if ((result = geodatabase.CloseTable(table)) != S_OK)
    {
        LogError(L"Error closing the table!", result);
        return;
    }

    std::wcout << "Primary table closed." << std::endl;
}

int main(int argc, const char* argv[])
{
    // Honestly this should be a command-line argument but this is just a basic converter tool.
    std::wstring databasePath =
        L"C:\\Users\\Gustave\\Desktop\\KingCounty_GDB_topo_contour005_complete - Copy\\KingCounty_GDB_topo_contour005_complete.gdb";

    FileGDBAPI::Geodatabase geodatabase;

    fgdbError result;
    std::wcout << "Opening the db..." << std::endl;
    if ((result = FileGDBAPI::OpenGeodatabase(databasePath, geodatabase)) != S_OK)
    {
        LogError(L"Could not open the Geodatabase!", result);

        std::this_thread::sleep_for(std::chrono::milliseconds(3000));
        return -1;
    }

    std::wcout << "DB opened." << std::endl;

    ProcessGeodatabase(geodatabase);

    std::wcout << "Closing DB..." << std::endl;
    if ((result = FileGDBAPI::CloseGeodatabase(geodatabase)) != S_OK)
    {
        LogError(L"Could not close the Geodatabase!", result);

        std::this_thread::sleep_for(std::chrono::milliseconds(3000));
        return -1;
    }

    std::wcout << "DB closed." << std::endl;
    std::system("pause");
    return 0;
}

<commit_msg>Extracting basic information. There are many, many points to process...<commit_after>// GeometryTiler.cpp : Defines the entry point for the console application.
//

#include <chrono>
#include <fstream>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

#include <FileGDBAPI.h>

#ifndef _DEBUG
    #pragma comment(lib, "lib/FileGDBAPI.lib")
#else
    #pragma comment(lib, "lib/FileGDBAPID.lib")
#endif

// Nicely logs the provided error message and error code.
void LogError(std::wstring errorMessage, fgdbError errorCode)
{
    std::wcout << errorMessage << std::endl;

    std::wstring errorText;
    FileGDBAPI::ErrorInfo::GetErrorDescription(errorCode, errorText);
    std::wcout << "Error: " << errorText << "[" << errorCode << "]" << std::endl;
}

// Processes an individual row.
long totalPoints = 0;
void ProcessRow(FileGDBAPI::Row& row)
{
    // TODO this is a good point to move into a class.
    fgdbError result;
    FileGDBAPI::ShapeBuffer shapeBuffer;
    if ((result = row.GetGeometry(shapeBuffer)) != S_OK)
    {
        LogError(L"Error loading the shape buffer!", result);
        return;
    }

    double elevation; // Can be negative!
    if ((result = row.GetDouble(L"ELEVATION", elevation)) != S_OK)
    {
        LogError(L"Error loading the shape buffer!", result);
        return;
    }

    // At this point we know (from our saved table.xml file) that this is a polyline, and (from the above), we know the elevation.
    long type = shapeBuffer.shapeBuffer[0];

    // See the extended_shape_buffer_format.PDF file detailing the polyline shape
    long numParts = shapeBuffer.shapeBuffer[sizeof(long) + 4*sizeof(double)];
    long numPoints = shapeBuffer.shapeBuffer[sizeof(long) + 4*sizeof(double) + sizeof(long)];

    // std::cout << type << " " << numParts << " " << numPoints << std::endl;
    /*if ((result = shapeBuffer.GetNumPoints(numPoints)) != S_OK)
    {
        LogError(L"Error loading the number of points in the shape!", result);
        return;
    }*/

    totalPoints += numPoints;
}

// Processes the provided Table.
void ProcessTable(FileGDBAPI::Table& table)
{
    std::string tableDefinition;

    fgdbError result;
    if ((result = table.GetDefinition(tableDefinition)) != S_OK)
    {
        LogError(L"Error loading the table definition!", result);
        return;
    }

    std::ofstream defFile("table.xml");
    if (!defFile)
    {
        std::cout << "Could not open the file to write the table definition to!" << std::endl;
        return;
    }

    defFile << tableDefinition.c_str();
    defFile.close();
    std::cout << "Table definition has been written to a readable file." << std::endl;

    std::string documentation;
    if ((result = table.GetDocumentation(documentation)) != S_OK)
    {
        LogError(L"Error loading the table documentation!", result);
        return;
    }

    std::ofstream docFile("documentation.xml");
    if (!docFile)
    {
        std::cout << "Could not open the file to write documentation to!" << std::endl;
        return;
    }

    docFile << documentation.c_str();
    docFile.close();
    std::cout << "Documentation has been written to a readable-file." << std::endl;

    FileGDBAPI::Envelope extent;
    if ((result = table.GetExtent(extent)) != S_OK)
    {
        LogError(L"Error loading the table extent!", result);
        return;
    }

    std::cout << "Extent: [" << extent.xMin << ", " << extent.yMin << ", " << extent.zMin << "] to ["
        << extent.xMax << ", " << extent.yMax << ", " << extent.zMax << "]" << std::endl;

    int rowCount;
    if ((result = table.GetRowCount(rowCount)) != S_OK)
    {
        LogError(L"Error loading the table row count!", result);
        return;
    }

    std::cout << "Rows: " << rowCount << std::endl;

    FileGDBAPI::EnumRows allRows;
    std::cout << "Searching ALL rows in the database..." << std::endl;
    if ((result = table.Search(L"*", L"", extent, true, allRows)) != S_OK)
    {
        LogError(L"Error searching for all rows!", result);
        return;
    }

    std::cout << "Counting returned rows..." << std::endl;
    FileGDBAPI::Row row;
    int foundRowCount = 0;
    while (allRows.Next(row) == S_OK)
    {
        ++foundRowCount;
        if (foundRowCount % 1000 == 0)
        {
            std::cout << "  " << foundRowCount << std::endl;
        }

        ProcessRow(row);
    }

    allRows.Close();
    std::cout << "Counted " << foundRowCount << " returned rows (versus " << rowCount << " total rows)" << std::endl;
    if (foundRowCount != rowCount)
    {
        std::cout << "Warning: Didn't read all the data from the database!" << std::endl;
        return;
    }

    std::cout << "Total of " << totalPoints << " total geometry points." << std::endl;
}

// Processes the provided Geodatabase.
void ProcessGeodatabase(FileGDBAPI::Geodatabase& geodatabase)
{
    // Types
    std::vector<std::wstring> datasetTypes;

    std::wcout << L"Reading dataset types..." << std::endl;
    fgdbError result;
    if ((result = geodatabase.GetDatasetTypes(datasetTypes)) != S_OK)
    {
        LogError(L"Error loading the dataset types!", result);
        return;
    }

    std::wcout << L"Read " << datasetTypes.size() << " dataset types." << std::endl;
    for (unsigned int i = 0; i < datasetTypes.size(); i++)
    {
        std::wcout << L"  " << datasetTypes[i] << std::endl;
    }

    // Relationship types
    std::vector<std::wstring> datasetRelationshipTypes;

    std::wcout << L"Reading dataset relationship types..." << std::endl;
    if ((result = geodatabase.GetDatasetRelationshipTypes(datasetTypes)) != S_OK)
    {
        LogError(L"Error loading the dataset relationship types!", result);
        return;
    }

    std::wcout << L"Read " << datasetRelationshipTypes.size() << " dataset relationship types." << std::endl;
    for (unsigned int i = 0; i < datasetRelationshipTypes.size(); i++)
    {
        std::wcout << L"  " << datasetRelationshipTypes[i] << std::endl;
    }

    // Domains
    std::vector<std::wstring> datasetDomains;

    std::wcout << L"Reading dataset domains..." << std::endl;
    if ((result = geodatabase.GetDomains(datasetTypes)) != S_OK)
    {
        LogError(L"Error loading the dataset domains!", result);
        return;
    }

    std::wcout << L"Read " << datasetDomains.size() << " dataset domains." << std::endl;
    for (unsigned int i = 0; i < datasetDomains.size(); i++)
    {
        std::wcout << L"  " << datasetDomains[i] << std::endl;
    }

    std::vector<std::wstring> childDatasets;

    std::wcout << L"Reading child datasets..." << std::endl;
    if ((result = geodatabase.GetChildDatasets(L"\\", L"", childDatasets)) != S_OK)
    {
        LogError(L"Error loading the child datasets!", result);
        return;
    }

    std::wcout << L"Read " << childDatasets.size() << " child datasets." << std::endl;
    for (unsigned int i = 0; i < childDatasets.size(); i++)
    {
        std::wcout << L"  " << childDatasets[i] << std::endl;
    }

    std::wstring datasetType;
    std::vector<std::string> childDatasetDefinitions;

    std::wcout << L"Reading primary dataset type..." << std::endl;
    if ((result = geodatabase.GetChildDatasetDefinitions(L"\\CONTOUR005_LINE", datasetType, childDatasetDefinitions)) != S_OK)
    {
        LogError(L"Error loading the primary dataset definition info!", result);
        return;
    }

    std::wcout << L"The primary dataset is of type '" << datasetType << "'." << std::endl;
    for (unsigned int i = 0; i < childDatasetDefinitions.size(); i++)
    {
        std::cout << "  " << childDatasetDefinitions[i] << std::endl;
    }

    // Open the primary table
    FileGDBAPI::Table table;
    std::wcout << "Reading in the primary table..." << std::endl;
    if ((result = geodatabase.OpenTable(L"\\CONTOUR005_LINE", table)) != S_OK)
    {
        LogError(L"Error loading the table!", result);
        return;
    }

    std::wcout << "Primary table opened." << std::endl;

    ProcessTable(table);

    std::wcout << "Closing the primary table..." << std::endl;
    if ((result = geodatabase.CloseTable(table)) != S_OK)
    {
        LogError(L"Error closing the table!", result);
        return;
    }

    std::wcout << "Primary table closed." << std::endl;
}

int main(int argc, const char* argv[])
{
    // Honestly this should be a command-line argument but this is just a basic converter tool.
    std::wstring databasePath =
        L"C:\\Users\\Gustave\\Desktop\\KingCounty_GDB_topo_contour005_complete - Copy\\KingCounty_GDB_topo_contour005_complete.gdb";

    FileGDBAPI::Geodatabase geodatabase;

    fgdbError result;
    std::wcout << "Opening the db..." << std::endl;
    if ((result = FileGDBAPI::OpenGeodatabase(databasePath, geodatabase)) != S_OK)
    {
        LogError(L"Could not open the Geodatabase!", result);

        std::this_thread::sleep_for(std::chrono::milliseconds(3000));
        return -1;
    }

    std::wcout << "DB opened." << std::endl;

    ProcessGeodatabase(geodatabase);

    std::wcout << "Closing DB..." << std::endl;
    if ((result = FileGDBAPI::CloseGeodatabase(geodatabase)) != S_OK)
    {
        LogError(L"Could not close the Geodatabase!", result);

        std::this_thread::sleep_for(std::chrono::milliseconds(3000));
        return -1;
    }

    std::wcout << "DB closed." << std::endl;
    std::system("pause");
    return 0;
}

<|endoftext|>


<commit_before>// $Id$
/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: David Rohr <drohr@cern.ch>                            *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file    AliHLTVZEROOnlineCalibComponent.cxx
    @author  David Rohr <drohr@cern.ch>
    @brief   VZERO online calib component
*/

#include "TTree.h"
#include "TMap.h"
#include "TObjString.h"
#include "TDatime.h"
#include "TH1F.h"

#include "AliLog.h"
#include "AliRunInfo.h"
#include "AliGRPObject.h"
#include "AliGeomManager.h"

#include "AliVZERORecoParam.h"

#include "AliHLTErrorGuard.h"
#include "AliHLTDataTypes.h"
#include "AliHLTVZEROOnlineCalibComponent.h"
#include "AliESDVZERO.h"

#include "AliESDVZEROfriend.h"

using namespace std;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTVZEROOnlineCalibComponent)

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

// #################################################################################
AliHLTVZEROOnlineCalibComponent::AliHLTVZEROOnlineCalibComponent() :
  AliHLTProcessor(),
  fRunInfo(NULL),
  fVZERORecoParam(NULL),
  fHistMult("vzero", "vzero", 100, 0, 1000),
  fEventModulo(0)
  {
  // an example component which implements the ALICE HLT processor
  // interface and does some analysis on the input raw data
  //
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
  //
  // NOTE: all helper classes should be instantiated in DoInit()
}

// #################################################################################
AliHLTVZEROOnlineCalibComponent::~AliHLTVZEROOnlineCalibComponent() {
  // see header file for class documentation
}

/*
 * ---------------------------------------------------------------------------------
 * Public functions to implement AliHLTComponent's interface.
 * These functions are required for the registration process
 * ---------------------------------------------------------------------------------
 */

// #################################################################################
const Char_t* AliHLTVZEROOnlineCalibComponent::GetComponentID() {
  // see header file for class documentation
  return "VZEROOnlineCalib";
}

// #################################################################################
void AliHLTVZEROOnlineCalibComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list) {
  // see header file for class documentation
  list.push_back(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO);
}

// #################################################################################
AliHLTComponentDataType AliHLTVZEROOnlineCalibComponent::GetOutputDataType()
{
  // see header file for class documentation
  return kAliHLTDataTypeHistogram|kAliHLTDataOriginOut;
}

// #################################################################################
void AliHLTVZEROOnlineCalibComponent::GetOutputDataSize( ULong_t& constBase, Double_t& inputMultiplier ) {
  // see header file for class documentation
  constBase = 3000;
  inputMultiplier = 1;
}

// #################################################################################
void AliHLTVZEROOnlineCalibComponent::GetOCDBObjectDescription( TMap* const targetMap) {
  // see header file for class documentation

  if (!targetMap) return;
  targetMap->Add(new TObjString("GRP/GRP/Data"),
		 new TObjString("GRP object - run information"));
  targetMap->Add(new TObjString("GRP/CTP/CTPtiming"),
		 new TObjString("GRP object - CTP information"));
  targetMap->Add(new TObjString("GRP/CTP/TimeAlign"),
		 new TObjString("GRP object - CTP information"));
  targetMap->Add(new TObjString("GRP/Calib/LHCClockPhase"),
		 new TObjString("GRP object - time calibration"));

  targetMap->Add(new TObjString("VZERO/Calib/Data"),
		 new TObjString("VZERO calibration object"));
  targetMap->Add(new TObjString("VZERO/Calib/TimeDelays"),
		 new TObjString("VZERO calibration object"));
  targetMap->Add(new TObjString("VZERO/Calib/TimeSlewing"),
		 new TObjString("VZERO calibration object"));
  targetMap->Add(new TObjString("VZERO/Trigger/Data"),
		 new TObjString("VZERO calibration object"));
  return;
}

// #################################################################################
AliHLTComponent* AliHLTVZEROOnlineCalibComponent::Spawn() {
  // see header file for class documentation
  return new AliHLTVZEROOnlineCalibComponent;
}

/*
 * ---------------------------------------------------------------------------------
 * Protected functions to implement AliHLTComponent's interface.
 * These functions provide initialization as well as the actual processing
 * capabilities of the component.
 * ---------------------------------------------------------------------------------
 */

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::DoInit( Int_t argc, const Char_t** argv ) {
  // see header file for class documentation

  Int_t iResult=0;

  // -- Load GeomManager
  if(AliGeomManager::GetGeometry()==NULL){
    AliGeomManager::LoadGeometry();
  }

  // -- Read the component arguments
  if (iResult>=0) {
    iResult=ConfigureFromArgumentString(argc, argv);
  }

  // -- Get AliRunInfo variables
  // -----------------------------
  TObject* pOCDBEntry=LoadAndExtractOCDBObject("GRP/GRP/Data");
  AliGRPObject* pGRP=pOCDBEntry?dynamic_cast<AliGRPObject*>(pOCDBEntry):NULL;

  TString beamType = "";
  TString lhcState = "";
  TString runType = "";
  Float_t beamEnergy = 0.;
  UInt_t activeDetectors = 0;

  if (pGRP) {
    lhcState        = pGRP->GetLHCState();
    beamType        = pGRP->GetBeamType();
    runType         = pGRP->GetRunType();
    beamEnergy      = pGRP->GetBeamEnergy();
    activeDetectors = pGRP->GetDetectorMask();
  }

  // -- Initialize members
  // -----------------------
  do {
    if (iResult<0) break;

    // AliGRPManager grpMan;
    // Bool_t status       = grpMan.ReadGRPEntry(); // Read the corresponding OCDB entry
    // status              = grpMan.SetMagField();  // Set global field instanton
    // AliRunInfo *runInfo = grpMan.GetRunInfo();   // Get instance of run info

    fRunInfo = new AliRunInfo(lhcState.Data(), beamType.Data(),
			      beamEnergy, runType.Data(), activeDetectors);
    if (!fRunInfo) {
      iResult=-ENOMEM;
      break;
    }

    fVZERORecoParam = new AliVZERORecoParam;
    if (!fVZERORecoParam) {
      iResult=-ENOMEM;
      break;
    }

    // implement further initialization
  } while (0);

  if (iResult<0) {
    // implement cleanup

    if (fVZERORecoParam)
      delete fVZERORecoParam;
    fVZERORecoParam = NULL;

    if (fRunInfo)
      delete fRunInfo;
    fRunInfo = NULL;
  }

  return iResult;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::ScanConfigurationArgument(Int_t /*argc*/, const Char_t** argv) {
  Int_t ii =0;
  TString argument=argv[ii];

  if (argument.IsNull()) return 0;

  return 0;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::DoDeinit() {
  // see header file for class documentation

  if (fVZERORecoParam)
    delete fVZERORecoParam;
  fVZERORecoParam = NULL;

  if (fRunInfo)
    delete fRunInfo;
  fRunInfo = NULL;

  return 0;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::DoEvent(const AliHLTComponentEventData& /*evtData*/,
					AliHLTComponentTriggerData& /*trigData*/) {
  // see header file for class documentation
  Int_t iResult=0;

  // -- Only use data event
  if (!IsDataEvent())
    return 0;

  //Get input data, and proceed if we got a VZERO ESD object
  const AliESDVZERO* esdVZERO = dynamic_cast<const AliESDVZERO*>(GetFirstInputObject(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO, "AliESDVZERO"));
  if (esdVZERO)
  {
    //Just some example, create histogram with VZero multiplicity.
    float vZEROMultiplicity = 0.f;
    for (int i = 0;i < 64;i++) vZEROMultiplicity += esdVZERO->GetMultiplicity(i);
    fHistMult.Fill(vZEROMultiplicity);
    //vZEROTriggerChargeA = esdVZERO->GetTriggerChargeA();
    //vZEROTriggerChargeC = esdVZERO->GetTriggerChargeC();
  }

  //If the histogram is not empty, we send it out every 16th event (to collect some statistics).
  //Depending on the pushback period set for the component, it might not be send out every time, but only after a certain amount of time. (order of 3 minutes)
  //We check whether it was really sent out, and only if so, we reset the histogram.
  //The ZMQ merging component that sits at the end of the chain will receive all histograms from all concurrent VZEROOnlineCalib components, and merge them to the final histogram.
  if ((++fEventModulo % 16 == 0) && fHistMult.GetEntries() && PushBack(&fHistMult, kAliHLTDataTypeHistogram|kAliHLTDataOriginHLT) > 0) fHistMult.Reset();

  return iResult;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::Reconfigure(const Char_t* cdbEntry, const Char_t* chainId) {
  // see header file for class documentation

  Int_t iResult=0;
  return iResult;
}

<commit_msg>Place member TH1 to top root directory<commit_after>// $Id$
/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: David Rohr <drohr@cern.ch>                            *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file    AliHLTVZEROOnlineCalibComponent.cxx
    @author  David Rohr <drohr@cern.ch>
    @brief   VZERO online calib component
*/

#include "TTree.h"
#include "TMap.h"
#include "TObjString.h"
#include "TDatime.h"
#include "TH1F.h"

#include "AliLog.h"
#include "AliRunInfo.h"
#include "AliGRPObject.h"
#include "AliGeomManager.h"

#include "AliVZERORecoParam.h"

#include "AliHLTErrorGuard.h"
#include "AliHLTDataTypes.h"
#include "AliHLTVZEROOnlineCalibComponent.h"
#include "AliESDVZERO.h"

#include "AliESDVZEROfriend.h"

using namespace std;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTVZEROOnlineCalibComponent)

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

// #################################################################################
AliHLTVZEROOnlineCalibComponent::AliHLTVZEROOnlineCalibComponent() :
  AliHLTProcessor(),
  fRunInfo(NULL),
  fVZERORecoParam(NULL),
  fHistMult("vzero", "vzero", 100, 0, 1000),
  fEventModulo(0)
  {
  // an example component which implements the ALICE HLT processor
  // interface and does some analysis on the input raw data
  //
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
  //
  // NOTE: all helper classes should be instantiated in DoInit()
  fHistMult.SetDirectory(0);
}

// #################################################################################
AliHLTVZEROOnlineCalibComponent::~AliHLTVZEROOnlineCalibComponent() {
  // see header file for class documentation
}

/*
 * ---------------------------------------------------------------------------------
 * Public functions to implement AliHLTComponent's interface.
 * These functions are required for the registration process
 * ---------------------------------------------------------------------------------
 */

// #################################################################################
const Char_t* AliHLTVZEROOnlineCalibComponent::GetComponentID() {
  // see header file for class documentation
  return "VZEROOnlineCalib";
}

// #################################################################################
void AliHLTVZEROOnlineCalibComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list) {
  // see header file for class documentation
  list.push_back(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO);
}

// #################################################################################
AliHLTComponentDataType AliHLTVZEROOnlineCalibComponent::GetOutputDataType()
{
  // see header file for class documentation
  return kAliHLTDataTypeHistogram|kAliHLTDataOriginOut;
}

// #################################################################################
void AliHLTVZEROOnlineCalibComponent::GetOutputDataSize( ULong_t& constBase, Double_t& inputMultiplier ) {
  // see header file for class documentation
  constBase = 3000;
  inputMultiplier = 1;
}

// #################################################################################
void AliHLTVZEROOnlineCalibComponent::GetOCDBObjectDescription( TMap* const targetMap) {
  // see header file for class documentation

  if (!targetMap) return;
  targetMap->Add(new TObjString("GRP/GRP/Data"),
		 new TObjString("GRP object - run information"));
  targetMap->Add(new TObjString("GRP/CTP/CTPtiming"),
		 new TObjString("GRP object - CTP information"));
  targetMap->Add(new TObjString("GRP/CTP/TimeAlign"),
		 new TObjString("GRP object - CTP information"));
  targetMap->Add(new TObjString("GRP/Calib/LHCClockPhase"),
		 new TObjString("GRP object - time calibration"));

  targetMap->Add(new TObjString("VZERO/Calib/Data"),
		 new TObjString("VZERO calibration object"));
  targetMap->Add(new TObjString("VZERO/Calib/TimeDelays"),
		 new TObjString("VZERO calibration object"));
  targetMap->Add(new TObjString("VZERO/Calib/TimeSlewing"),
		 new TObjString("VZERO calibration object"));
  targetMap->Add(new TObjString("VZERO/Trigger/Data"),
		 new TObjString("VZERO calibration object"));
  return;
}

// #################################################################################
AliHLTComponent* AliHLTVZEROOnlineCalibComponent::Spawn() {
  // see header file for class documentation
  return new AliHLTVZEROOnlineCalibComponent;
}

/*
 * ---------------------------------------------------------------------------------
 * Protected functions to implement AliHLTComponent's interface.
 * These functions provide initialization as well as the actual processing
 * capabilities of the component.
 * ---------------------------------------------------------------------------------
 */

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::DoInit( Int_t argc, const Char_t** argv ) {
  // see header file for class documentation

  Int_t iResult=0;

  // -- Load GeomManager
  if(AliGeomManager::GetGeometry()==NULL){
    AliGeomManager::LoadGeometry();
  }

  // -- Read the component arguments
  if (iResult>=0) {
    iResult=ConfigureFromArgumentString(argc, argv);
  }

  // -- Get AliRunInfo variables
  // -----------------------------
  TObject* pOCDBEntry=LoadAndExtractOCDBObject("GRP/GRP/Data");
  AliGRPObject* pGRP=pOCDBEntry?dynamic_cast<AliGRPObject*>(pOCDBEntry):NULL;

  TString beamType = "";
  TString lhcState = "";
  TString runType = "";
  Float_t beamEnergy = 0.;
  UInt_t activeDetectors = 0;

  if (pGRP) {
    lhcState        = pGRP->GetLHCState();
    beamType        = pGRP->GetBeamType();
    runType         = pGRP->GetRunType();
    beamEnergy      = pGRP->GetBeamEnergy();
    activeDetectors = pGRP->GetDetectorMask();
  }

  // -- Initialize members
  // -----------------------
  do {
    if (iResult<0) break;

    // AliGRPManager grpMan;
    // Bool_t status       = grpMan.ReadGRPEntry(); // Read the corresponding OCDB entry
    // status              = grpMan.SetMagField();  // Set global field instanton
    // AliRunInfo *runInfo = grpMan.GetRunInfo();   // Get instance of run info

    fRunInfo = new AliRunInfo(lhcState.Data(), beamType.Data(),
			      beamEnergy, runType.Data(), activeDetectors);
    if (!fRunInfo) {
      iResult=-ENOMEM;
      break;
    }

    fVZERORecoParam = new AliVZERORecoParam;
    if (!fVZERORecoParam) {
      iResult=-ENOMEM;
      break;
    }

    // implement further initialization
  } while (0);

  if (iResult<0) {
    // implement cleanup

    if (fVZERORecoParam)
      delete fVZERORecoParam;
    fVZERORecoParam = NULL;

    if (fRunInfo)
      delete fRunInfo;
    fRunInfo = NULL;
  }

  return iResult;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::ScanConfigurationArgument(Int_t /*argc*/, const Char_t** argv) {
  Int_t ii =0;
  TString argument=argv[ii];

  if (argument.IsNull()) return 0;

  return 0;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::DoDeinit() {
  // see header file for class documentation

  if (fVZERORecoParam)
    delete fVZERORecoParam;
  fVZERORecoParam = NULL;

  if (fRunInfo)
    delete fRunInfo;
  fRunInfo = NULL;

  return 0;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::DoEvent(const AliHLTComponentEventData& /*evtData*/,
					AliHLTComponentTriggerData& /*trigData*/) {
  // see header file for class documentation
  Int_t iResult=0;

  // -- Only use data event
  if (!IsDataEvent())
    return 0;

  //Get input data, and proceed if we got a VZERO ESD object
  const AliESDVZERO* esdVZERO = dynamic_cast<const AliESDVZERO*>(GetFirstInputObject(kAliHLTDataTypeESDContent | kAliHLTDataOriginVZERO, "AliESDVZERO"));
  if (esdVZERO)
  {
    //Just some example, create histogram with VZero multiplicity.
    float vZEROMultiplicity = 0.f;
    for (int i = 0;i < 64;i++) vZEROMultiplicity += esdVZERO->GetMultiplicity(i);
    fHistMult.Fill(vZEROMultiplicity);
    //vZEROTriggerChargeA = esdVZERO->GetTriggerChargeA();
    //vZEROTriggerChargeC = esdVZERO->GetTriggerChargeC();
  }

  //If the histogram is not empty, we send it out every 16th event (to collect some statistics).
  //Depending on the pushback period set for the component, it might not be send out every time, but only after a certain amount of time. (order of 3 minutes)
  //We check whether it was really sent out, and only if so, we reset the histogram.
  //The ZMQ merging component that sits at the end of the chain will receive all histograms from all concurrent VZEROOnlineCalib components, and merge them to the final histogram.
  if ((++fEventModulo % 16 == 0) && fHistMult.GetEntries() && PushBack(&fHistMult, kAliHLTDataTypeHistogram|kAliHLTDataOriginHLT) > 0) fHistMult.Reset();

  return iResult;
}

// #################################################################################
Int_t AliHLTVZEROOnlineCalibComponent::Reconfigure(const Char_t* cdbEntry, const Char_t* chainId) {
  // see header file for class documentation

  Int_t iResult=0;
  return iResult;
}

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2022.  All rights reserved
 */
#include "../StroikaPreComp.h"

#if qPlatform_POSIX
#include <fcntl.h>
#include <string.h>
#include <string>
#include <unistd.h>
#if defined(__APPLE__) && defined(__MACH__)
#include <sys/types.h>
#endif
#include <cstdio>
#include <signal.h>
#include <sys/ptrace.h>
#elif qPlatform_Windows
#include <Windows.h>
#endif
#include "../Math/Common.h"

#include "Debugger.h"

using namespace Stroika::Foundation;

#ifndef __has_builtin
#define __has_builtin(x) 0 // Compatibility with non-clang compilers.
#endif

#if qPlatform_Linux
namespace {
    // From https://stackoverflow.com/questions/3596781/how-to-detect-if-the-current-process-is-being-run-by-gdb
    bool debuggerIsAttached_ ()
    {
        char      buf[4096];
        const int status_fd = ::open ("/proc/self/status", O_RDONLY);
        if (status_fd == -1)
            return false;
        const ssize_t num_read = ::read (status_fd, buf, sizeof (buf) - 1);
        ::close (status_fd);
        if (num_read <= 0)
            return false;
        buf[num_read]                    = '\0';
        constexpr char tracerPidString[] = "TracerPid:";
        const auto     tracer_pid_ptr    = ::strstr (buf, tracerPidString);
        if (!tracer_pid_ptr)
            return false;
        for (const char* characterPtr = tracer_pid_ptr + sizeof (tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr) {
            if (::isspace (*characterPtr))
                continue;
            else
                return ::isdigit (*characterPtr) != 0 && *characterPtr != '0';
        }
        return false;
    }
}
#endif

#if qPlatform_MacOS
namespace {
    // https://stackoverflow.com/questions/2200277/detecting-debugger-on-mac-os-x

    // Returns true if the current process is being debugged (either
    // running under the debugger or has a debugger attached post facto).
    bool AmIBeingDebugged_ ()
    {
        // Initialize the flags so that, if sysctl fails for some bizarre
        // reason, we get a predictable result.
        kinfo_proc info{};
        // Initialize mib, which tells sysctl the info we want, in this case
        // we're looking for information about a specific process ID.
        int mib[4] = {
            CTL_KERN,
            KERN_PROC,
            KERN_PROC_PID,
            getpid ()};
        size_t size = sizeof (info);
        int    junk = sysctl (mib, sizeof (mib) / sizeof (*mib), &info, &size, NULL, 0);
        Assert (junk == 0);
        return (info.kp_proc.p_flag & P_TRACED) != 0;
    }
}
#endif

/*
 ********************************************************************************
 ************************ Debug::IsThisProcessBeingDebugged **********************
 ********************************************************************************
 */
optional<bool> Debug::IsThisProcessBeingDebugged ()
{
#if qPlatform_Linux
    return debuggerIsAttached_ ();
#endif
#if qPlatform_MacOS
    return AmIBeingDebugged_ ();
#endif
#if qPlatform_POSIX
#if 0
    // Not a good approach - see https://stackoverflow.com/questions/3596781/how-to-detect-if-the-current-process-is-being-run-by-gdb
   return ptrace (PTRACE_TRACEME, 0, NULL, 0) == -1;
#endif
#endif
#if qPlatform_Windows
    return ::IsDebuggerPresent ();
#endif
    return nullopt;
}

/*
 ********************************************************************************
 ************************ Debug::DropIntoDebuggerIfPresent **********************
 ********************************************************************************
 */
void Debug::DropIntoDebuggerIfPresent ()
{
    if (IsThisProcessBeingDebugged () == true) {
#if __has_builtin(__builtin_trap) || defined(__GNUC__)
        __builtin_trap ();
#elif qPlatform_POSIX
        raise (SIGTRAP);
#elif qPlatform_Windows
        ::DebugBreak ();
#else
        abort ();
#endif
    }
}
<commit_msg>minor code cleanups<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2022.  All rights reserved
 */
#include "../StroikaPreComp.h"

#if qPlatform_POSIX
#include <fcntl.h>
#include <string.h>
#include <string>
#include <unistd.h>
#if defined(__APPLE__) && defined(__MACH__)
#include <sys/types.h>
#endif
#include <cstdio>
#include <signal.h>
#include <sys/ptrace.h>
#elif qPlatform_Windows
#include <Windows.h>
#endif
#include "../Math/Common.h"

#include "Debugger.h"

using namespace Stroika::Foundation;

#ifndef __has_builtin
#define __has_builtin(x) 0 // Compatibility with non-clang compilers.
#endif

#if qPlatform_Linux
namespace {
    // From https://stackoverflow.com/questions/3596781/how-to-detect-if-the-current-process-is-being-run-by-gdb
    bool DebuggerIsAttached_ ()
    {
        char      buf[4096];
        const int status_fd = ::open ("/proc/self/status", O_RDONLY);
        if (status_fd == -1)
            return false;
        const ssize_t num_read = ::read (status_fd, buf, sizeof (buf) - 1);
        ::close (status_fd);
        if (num_read <= 0)
            return false;
        buf[num_read]                    = '\0';
        constexpr char tracerPidString[] = "TracerPid:";
        const auto     tracer_pid_ptr    = ::strstr (buf, tracerPidString);
        if (!tracer_pid_ptr)
            return false;
        for (const char* characterPtr = tracer_pid_ptr + sizeof (tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr) {
            if (::isspace (*characterPtr))
                continue;
            else
                return ::isdigit (*characterPtr) != 0 && *characterPtr != '0';
        }
        return false;
    }
}
#endif

#if qPlatform_MacOS
namespace {
    // https://stackoverflow.com/questions/2200277/detecting-debugger-on-mac-os-x

    // Returns true if the current process is being debugged (either
    // running under the debugger or has a debugger attached post facto).
    bool DebuggerIsAttached_ ()
    {
        // Initialize the flags so that, if sysctl fails for some bizarre
        // reason, we get a predictable result.
        kinfo_proc info{};
        // Initialize mib, which tells sysctl the info we want, in this case
        // we're looking for information about a specific process ID.
        int mib[4] = {
            CTL_KERN,
            KERN_PROC,
            KERN_PROC_PID,
            getpid ()};
        size_t size = sizeof (info);
        int    junk = sysctl (mib, sizeof (mib) / sizeof (*mib), &info, &size, NULL, 0);
        Assert (junk == 0);
        return (info.kp_proc.p_flag & P_TRACED) != 0;
    }
}
#endif

/*
 ********************************************************************************
 ************************ Debug::IsThisProcessBeingDebugged **********************
 ********************************************************************************
 */
optional<bool> Debug::IsThisProcessBeingDebugged ()
{
#if qPlatform_Linux
    return DebuggerIsAttached_ ();
#endif
#if qPlatform_MacOS
    return DebuggerIsAttached_ ();
#endif
#if qPlatform_POSIX
#if 0
    // Not a good approach - see https://stackoverflow.com/questions/3596781/how-to-detect-if-the-current-process-is-being-run-by-gdb
   return ptrace (PTRACE_TRACEME, 0, NULL, 0) == -1;
#endif
#endif
#if qPlatform_Windows
    return ::IsDebuggerPresent ();
#endif
    return nullopt;
}

/*
 ********************************************************************************
 ************************ Debug::DropIntoDebuggerIfPresent **********************
 ********************************************************************************
 */
void Debug::DropIntoDebuggerIfPresent ()
{
    if (IsThisProcessBeingDebugged () == true) {
#if __has_builtin(__builtin_trap) || defined(__GNUC__)
        __builtin_trap ();
#elif qPlatform_POSIX
        raise (SIGTRAP);
#elif qPlatform_Windows
        ::DebugBreak ();
#else
        abort ();
#endif
    }
}
<|endoftext|>


<commit_before>
#include "tablemodelanovamodel.h"

#include <QMimeData>
#include <QDebug>

#include "utils.h"
#include <boost/foreach.hpp>

#include "options/optionboolean.h"

using namespace std;

TableModelAnovaModel::TableModelAnovaModel(QObject *parent)
	: TableModel(parent)
{
	_boundTo = NULL;
	_customModel = false;

	_terms.setSortParent(_variables);
}

QVariant TableModelAnovaModel::data(const QModelIndex &index, int role) const
{
	if (_boundTo == NULL || index.isValid() == false)
		return QVariant();

	if (role == Qt::DisplayRole)
	{
		int colNo = index.column();
		int rowNo = index.row();
		Options *row = _rows.at(rowNo);

		if (colNo == 0) {

			OptionTerms *termOption = static_cast<OptionTerms *>(row->get(0));
			Term t(termOption->value().front());
			return t.asQString();
		}
	}
	else if (role == Qt::CheckStateRole)
	{
		int colNo = index.column();
		int rowNo = index.row();
		Options *row = _rows.at(rowNo);

		if (colNo == 1)
		{
			OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1));
			return booleanOption->value() ? Qt::Checked : Qt::Unchecked;
		}
	}

	return QVariant();
}

int TableModelAnovaModel::rowCount(const QModelIndex &) const
{
	if (_boundTo == NULL)
		return 0;

	return _rows.size();
}

int TableModelAnovaModel::columnCount(const QModelIndex &) const
{
	if (_boundTo == NULL)
		return 0;

	return _boundTo->rowTemplate()->size();
}

bool TableModelAnovaModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
	if (index.isValid() == false)
		return false;

	if (index.column() == 1 && role == Qt::CheckStateRole)
	{
		Options *row = _rows.at(index.row());
		OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1));
		booleanOption->setValue(value.toInt() == Qt::Checked);

		_boundTo->setValue(_rows);

		return true;
	}

	return false;
}

QStringList TableModelAnovaModel::mimeTypes() const
{
	QStringList types;

	types << "application/vnd.list.term";

	return types;
}

void TableModelAnovaModel::setVariables(const Terms &variables)
{
	beginResetModel();

	_variables.set(variables);

	if (_customModel)
	{
		Terms terms = _terms;
		terms.discardWhatDoesntContainTheseComponents(_variables);
		if (terms.size() != _terms.size())
			setTerms(terms);
	}
	else
	{
		Terms terms = _variables.crossCombinations();
		if (terms != _terms)
			setTerms(terms);
	}

	emit variablesAvailableChanged();

	endResetModel();
}

const Terms &TableModelAnovaModel::variables() const
{
	return _variables;
}

void TableModelAnovaModel::setCustomModelMode(bool on)
{
	_customModel = on;

	if (_customModel)
		clear();
	else
		setTerms(_variables.crossCombinations());
}

void TableModelAnovaModel::bindTo(Option *option)
{
	_boundTo = dynamic_cast<OptionsTable *>(option);
}

void TableModelAnovaModel::mimeDataMoved(const QModelIndexList &indexes)
{
	// sort indices, and delete from end to beginning

	QModelIndexList sorted = indexes;
	qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>());

	int lastRowDeleted = -1;

	Terms terms = _terms;

	foreach (const QModelIndex &index, sorted)
	{
		int rowNo = index.row();
		if (rowNo != lastRowDeleted)
			terms.remove(index.row());
		lastRowDeleted = rowNo;
	}

	setTerms(terms);
}

const Terms &TableModelAnovaModel::terms() const
{
	return _terms;
}

bool TableModelAnovaModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
{
	Q_UNUSED(action);
	Q_UNUSED(row);
	Q_UNUSED(column);
	Q_UNUSED(parent);

	if (mimeTypes().contains("application/vnd.list.term"))
	{
		QByteArray encodedData = data->data("application/vnd.list.term");
		QDataStream stream(&encodedData, QIODevice::ReadOnly);

		if (stream.atEnd())
			return false;

		return true;
	}

	return false;
}

bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent, int assignType)
{
	if (action == Qt::IgnoreAction)
		return true;

	if ( ! canDropMimeData(data, action, row, column, parent))
		return false;

	if ( ! data->hasFormat("application/vnd.list.term"))
		return false;

	QByteArray encodedData = data->data("application/vnd.list.term");

	Terms dropped;
	dropped.setSortParent(_variables);
	dropped.set(encodedData);

	Terms newTerms;

	switch (assignType)
	{
	case Cross:
		newTerms = dropped.crossCombinations();
		break;
	case Interaction:
		newTerms = dropped.wayCombinations(dropped.size());
		break;
	case MainEffects:
		newTerms = dropped.wayCombinations(1);
		break;
	case All2Way:
		newTerms = dropped.wayCombinations(2);
		break;
	case All3Way:
		newTerms = dropped.wayCombinations(3);
		break;
	case All4Way:
		newTerms = dropped.wayCombinations(4);
		break;
	case All5Way:
		newTerms = dropped.wayCombinations(5);
		break;
	default:
		(void)newTerms;
	}

	assign(newTerms);

	return true;
}

bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
	return dropMimeData(data, action, row, column, parent, Cross);
}

QMimeData *TableModelAnovaModel::mimeData(const QModelIndexList &indexes) const
{
	/* returns dummy data. when the user drags entries away from this listbox
	 * it means that they're deleting entries, so there's no point populating
	 * this data object properly
	 */

	Q_UNUSED(indexes);

	QMimeData *mimeData = new QMimeData();
	QByteArray encodedData;

	QDataStream dataStream(&encodedData, QIODevice::WriteOnly);

	dataStream << 0;

	mimeData->setData("application/vnd.list.term", encodedData);

	return mimeData;
}

Qt::ItemFlags TableModelAnovaModel::flags(const QModelIndex &index) const
{
	if (index.isValid())
	{
		if (index.column() == 0)
			return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
		else
			return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
	}
	else
	{
		return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;
	}
}

QVariant TableModelAnovaModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
	{
		if (section == 0)
			return "Model Terms";
		if (section == 1)
			return "Is Nuisance";
	}

	return QVariant();
}

Qt::DropActions TableModelAnovaModel::supportedDropActions() const
{
	return Qt::CopyAction;
}

Qt::DropActions TableModelAnovaModel::supportedDragActions() const
{
	return Qt::MoveAction;
}

OptionVariables *TableModelAnovaModel::termOptionFromRow(Options *row)
{
	return static_cast<OptionVariables *>(row->get(0));
}

void TableModelAnovaModel::setTerms(const Terms &terms)
{
	_terms.set(terms);

	if (_boundTo == NULL)
		return;

	beginResetModel();

	BOOST_FOREACH(Options *row, _rows)
		delete row;

	_rows.clear();

	BOOST_FOREACH(const Term &term, _terms.terms())
	{
		(void)_terms;
		Options *row = static_cast<Options *>(_boundTo->rowTemplate()->clone());
		OptionTerms *termCell = static_cast<OptionTerms *>(row->get(0));
		termCell->setValue(term.scomponents());

		_rows.push_back(row);
	}

	_boundTo->setValue(_rows);

	endResetModel();

	emit termsChanged();
}

void TableModelAnovaModel::clear()
{
	setTerms(Terms());
}

void TableModelAnovaModel::assign(const Terms &terms)
{
	Terms t = _terms;
	t.add(terms);
	setTerms(t);
}
<commit_msg>B ANOVA: Tweaks to the "Is Nuisance" column width<commit_after>
#include "tablemodelanovamodel.h"

#include <QMimeData>
#include <QDebug>

#include "utils.h"
#include <boost/foreach.hpp>

#include "options/optionboolean.h"

using namespace std;

TableModelAnovaModel::TableModelAnovaModel(QObject *parent)
	: TableModel(parent)
{
	_boundTo = NULL;
	_customModel = false;

	_terms.setSortParent(_variables);
}

QVariant TableModelAnovaModel::data(const QModelIndex &index, int role) const
{
	if (_boundTo == NULL || index.isValid() == false)
		return QVariant();

	if (role == Qt::DisplayRole)
	{
		int colNo = index.column();
		int rowNo = index.row();
		Options *row = _rows.at(rowNo);

		if (colNo == 0) {

			OptionTerms *termOption = static_cast<OptionTerms *>(row->get(0));
			Term t(termOption->value().front());
			return t.asQString();
		}
	}
	else if (role == Qt::CheckStateRole)
	{
		int colNo = index.column();
		int rowNo = index.row();
		Options *row = _rows.at(rowNo);

		if (colNo == 1)
		{
			OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1));
			return booleanOption->value() ? Qt::Checked : Qt::Unchecked;
		}
	}

	return QVariant();
}

int TableModelAnovaModel::rowCount(const QModelIndex &) const
{
	if (_boundTo == NULL)
		return 0;

	return _rows.size();
}

int TableModelAnovaModel::columnCount(const QModelIndex &) const
{
	if (_boundTo == NULL)
		return 0;

	return _boundTo->rowTemplate()->size();
}

bool TableModelAnovaModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
	if (index.isValid() == false)
		return false;

	if (index.column() == 1 && role == Qt::CheckStateRole)
	{
		Options *row = _rows.at(index.row());
		OptionBoolean *booleanOption = static_cast<OptionBoolean *>(row->get(1));
		booleanOption->setValue(value.toInt() == Qt::Checked);

		_boundTo->setValue(_rows);

		return true;
	}

	return false;
}

QStringList TableModelAnovaModel::mimeTypes() const
{
	QStringList types;

	types << "application/vnd.list.term";

	return types;
}

void TableModelAnovaModel::setVariables(const Terms &variables)
{
	beginResetModel();

	_variables.set(variables);

	if (_customModel)
	{
		Terms terms = _terms;
		terms.discardWhatDoesntContainTheseComponents(_variables);
		if (terms.size() != _terms.size())
			setTerms(terms);
	}
	else
	{
		Terms terms = _variables.crossCombinations();
		if (terms != _terms)
			setTerms(terms);
	}

	emit variablesAvailableChanged();

	endResetModel();
}

const Terms &TableModelAnovaModel::variables() const
{
	return _variables;
}

void TableModelAnovaModel::setCustomModelMode(bool on)
{
	_customModel = on;

	if (_customModel)
		clear();
	else
		setTerms(_variables.crossCombinations());
}

void TableModelAnovaModel::bindTo(Option *option)
{
	_boundTo = dynamic_cast<OptionsTable *>(option);
}

void TableModelAnovaModel::mimeDataMoved(const QModelIndexList &indexes)
{
	// sort indices, and delete from end to beginning

	QModelIndexList sorted = indexes;
	qSort(sorted.begin(), sorted.end(), qGreater<QModelIndex>());

	int lastRowDeleted = -1;

	Terms terms = _terms;

	foreach (const QModelIndex &index, sorted)
	{
		int rowNo = index.row();
		if (rowNo != lastRowDeleted)
			terms.remove(index.row());
		lastRowDeleted = rowNo;
	}

	setTerms(terms);
}

const Terms &TableModelAnovaModel::terms() const
{
	return _terms;
}

bool TableModelAnovaModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
{
	Q_UNUSED(action);
	Q_UNUSED(row);
	Q_UNUSED(column);
	Q_UNUSED(parent);

	if (mimeTypes().contains("application/vnd.list.term"))
	{
		QByteArray encodedData = data->data("application/vnd.list.term");
		QDataStream stream(&encodedData, QIODevice::ReadOnly);

		if (stream.atEnd())
			return false;

		return true;
	}

	return false;
}

bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent, int assignType)
{
	if (action == Qt::IgnoreAction)
		return true;

	if ( ! canDropMimeData(data, action, row, column, parent))
		return false;

	if ( ! data->hasFormat("application/vnd.list.term"))
		return false;

	QByteArray encodedData = data->data("application/vnd.list.term");

	Terms dropped;
	dropped.setSortParent(_variables);
	dropped.set(encodedData);

	Terms newTerms;

	switch (assignType)
	{
	case Cross:
		newTerms = dropped.crossCombinations();
		break;
	case Interaction:
		newTerms = dropped.wayCombinations(dropped.size());
		break;
	case MainEffects:
		newTerms = dropped.wayCombinations(1);
		break;
	case All2Way:
		newTerms = dropped.wayCombinations(2);
		break;
	case All3Way:
		newTerms = dropped.wayCombinations(3);
		break;
	case All4Way:
		newTerms = dropped.wayCombinations(4);
		break;
	case All5Way:
		newTerms = dropped.wayCombinations(5);
		break;
	default:
		(void)newTerms;
	}

	assign(newTerms);

	return true;
}

bool TableModelAnovaModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
	return dropMimeData(data, action, row, column, parent, Cross);
}

QMimeData *TableModelAnovaModel::mimeData(const QModelIndexList &indexes) const
{
	/* returns dummy data. when the user drags entries away from this listbox
	 * it means that they're deleting entries, so there's no point populating
	 * this data object properly
	 */

	Q_UNUSED(indexes);

	QMimeData *mimeData = new QMimeData();
	QByteArray encodedData;

	QDataStream dataStream(&encodedData, QIODevice::WriteOnly);

	dataStream << 0;

	mimeData->setData("application/vnd.list.term", encodedData);

	return mimeData;
}

Qt::ItemFlags TableModelAnovaModel::flags(const QModelIndex &index) const
{
	if (index.isValid())
	{
		if (index.column() == 0)
			return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
		else
			return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;
	}
	else
	{
		return Qt::ItemIsEnabled | Qt::ItemIsDropEnabled;
	}
}

QVariant TableModelAnovaModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	if (orientation == Qt::Horizontal)
	{
		if (role == Qt::DisplayRole)
		{
			if (section == 0)
				return "Model Terms";
			else if (section == 1)
				return "Is Nuisance";
		}
		else
		{
			if (section == 1 && role == Qt::SizeHintRole)
				return QSize(50, -1);
		}
	}

	return QVariant();
}

Qt::DropActions TableModelAnovaModel::supportedDropActions() const
{
	return Qt::CopyAction;
}

Qt::DropActions TableModelAnovaModel::supportedDragActions() const
{
	return Qt::MoveAction;
}

OptionVariables *TableModelAnovaModel::termOptionFromRow(Options *row)
{
	return static_cast<OptionVariables *>(row->get(0));
}

void TableModelAnovaModel::setTerms(const Terms &terms)
{
	_terms.set(terms);

	if (_boundTo == NULL)
		return;

	beginResetModel();

	BOOST_FOREACH(Options *row, _rows)
		delete row;

	_rows.clear();

	BOOST_FOREACH(const Term &term, _terms.terms())
	{
		(void)_terms;
		Options *row = static_cast<Options *>(_boundTo->rowTemplate()->clone());
		OptionTerms *termCell = static_cast<OptionTerms *>(row->get(0));
		termCell->setValue(term.scomponents());

		_rows.push_back(row);
	}

	_boundTo->setValue(_rows);

	endResetModel();

	emit termsChanged();
}

void TableModelAnovaModel::clear()
{
	setTerms(Terms());
}

void TableModelAnovaModel::assign(const Terms &terms)
{
	Terms t = _terms;
	t.add(terms);
	setTerms(t);
}
<|endoftext|>


<commit_before>  ///////////////////////////////////////////////////////////////////////////
  ///\file AddTaskEMCALPhotonIsolation.C
  ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
  ///
  /// Version to be used in lego train for testing on pp@7TeV
  ///
  /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
  /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
  /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
  ///////////////////////////////////////////////////////////////////////////

AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
                                                                 const char*            periodstr                 = "LHC11c",
                                                                 const char*            ntracks                   = "EmcalTracks",
                                                                 const char*            nclusters                 = "EmcCaloClusters",
                                                                 const UInt_t           pSel                      = AliVEvent::kEMC7,
                                                                 const TString          dType                     = "ESD",
                                                                 const Bool_t	        bHisto                    = kTRUE,
                                                                 const Int_t	        iOutput	  	          = 0,
                                                                 const Bool_t	        bIsMC  	                  = kFALSE,
                                                                 const Bool_t           bMCNormalization          = kFALSE,
                                                                 const Bool_t           bNLMCut                   = kFALSE,
                                                                 const Int_t            NLMCut                    = 0,
                                                                 const Double_t         minPtCutCluster           = 0.3,
                                                                 const Double_t         EtIso                     = 2.,
                                                                 const Int_t            iIsoMethod                = 1,
                                                                 const Int_t            iEtIsoMethod              = 0,
                                                                 const Int_t            iUEMethod                 = 1,
                                                                 const Bool_t           bUseofTPC                 = kFALSE,
                                                                 const Double_t         TMdeta                    = 0.02,
                                                                 const Double_t         TMdphi                    = 0.03,
                                                                 const Bool_t           bTMClusterRejection       = kTRUE,
                                                                 const Bool_t           bTMClusterRejectionInCone = kTRUE,
                                                                 const Float_t          iIsoConeRadius            = 0.4,
                                                                 const Bool_t           iSmearingSS               = kFALSE,
                                                                 const Float_t          iWidthSSsmear             = 0.,
                                                                 const Float_t          iMean_SSsmear             = 0.,
                                                                 const Bool_t           iExtraIsoCuts             = kFALSE,
                                                                 const Bool_t           i_pPb                     = kFALSE
                                                                 )
{

  Printf("Preparing neutral cluster analysis\n");

    // #### Define manager and data container names
  AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
  if (!manager) {
    ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
    return NULL;
  }

  printf("Creating container names for cluster analysis\n");
  TString myContName("");
  if(bIsMC)
    myContName = Form("Analysis_Neutrals_MC");
  else
    myContName = Form("Analysis_Neutrals");

  myContName.Append(Form("_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_nNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off"));

    // #### Define analysis task
  AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);

    // #### Task preferences
  task->SetOutputFormat(iOutput);
  task->SetLCAnalysis(kFALSE);
  task->SetIsoConeRadius(iIsoConeRadius);
  task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso
  task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta
  task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi
  task->SetQA(kTRUE);
  task->SetIsoMethod(iIsoMethod);
  task->SetEtIsoMethod(iEtIsoMethod);
  task->SetUEMethod(iUEMethod);
  task->SetUSEofTPC(bUseofTPC);
  task->SetMC(bIsMC);
  task->SetM02Smearing(iSmearingSS);
  task->SetWidth4Smear(iWidthSSsmear);
  task->SetMean4Smear(iMean_SSsmear);
  task->SetExtraIsoCuts(iExtraIsoCuts);
  task->SetAnalysispPb(i_pPb);
  if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);

  task->SetNLMCut(bNLMCut,NLMCut);

  TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters));
  cout<<"name of the containers  "<<name.Data()<<endl;

    // tracks to be used for the track matching (already used in TM task, TPC only tracks)
  AliTrackContainer *trackCont  = task->AddTrackContainer("tracks");
  if(!trackCont)
    Printf("Error with TPCOnly!!");
  trackCont->SetName("tpconlyMatch");
  trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);
    // clusters to be used in the analysis already filtered
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

    // tracks to be used in the analysis (Hybrid tracks)
  AliTrackContainer * tracksForAnalysis = task->AddTrackContainer("tracks");
  if(!tracksForAnalysis)
    Printf("Error with Hybrids!!");
  tracksForAnalysis->SetName("filterTracksAna");
  tracksForAnalysis->SetFilterHybridTracks(kTRUE);
  if(dType=="ESD"){
    tracksForAnalysis->SetTrackCutsPeriod(periodstr);
    tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);
  }

  Printf("Name of Tracks for matching: %s \n Name for Tracks for Isolation: %s",trackCont->GetName(),tracksForAnalysis->GetName());

  printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
    // #### Add analysis task
  manager->AddTask(task);

  AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName()));
  AliAnalysisDataContainer *cinput  = manager->GetCommonInputContainer();
  manager->ConnectInput(task, 0, cinput);
  manager->ConnectOutput(task, 1, contHistos);

  return task;
}
<commit_msg>fixing flag in AddTask for TrackCuts<commit_after>  ///////////////////////////////////////////////////////////////////////////
  ///\file AddTaskEMCALPhotonIsolation.C
  ///\brief Configuration of AliAnalysisTaskEMCALPhotonIsolation
  ///
  /// Version to be used in lego train for testing on pp@7TeV
  ///
  /// \author Lucile Ronflette <lucile.ronflette@cern.ch>, SUBATECH, Nantes
  /// \author Davide Francesco Lodato <davide.francesco.lodato@cern.ch>, Utrecht University
  /// \author Marco Marquard <marco.marquard@cern.ch>, University Frankfurt am Main
  ///////////////////////////////////////////////////////////////////////////

AliAnalysisTaskEMCALPhotonIsolation* AddTaskEMCALPhotonIsolation(
                                                                 const char*            periodstr                 = "LHC11c",
                                                                 const char*            ntracks                   = "EmcalTracks",
                                                                 const char*            nclusters                 = "EmcCaloClusters",
                                                                 const UInt_t           pSel                      = AliVEvent::kEMC7,
                                                                 const TString          dType                     = "ESD",
                                                                 const Bool_t	        bHisto                    = kTRUE,
                                                                 const Int_t	        iOutput	  	          = 0,
                                                                 const Bool_t	        bIsMC  	                  = kFALSE,
                                                                 const Bool_t           bMCNormalization          = kFALSE,
                                                                 const Bool_t           bNLMCut                   = kFALSE,
                                                                 const Int_t            NLMCut                    = 0,
                                                                 const Double_t         minPtCutCluster           = 0.3,
                                                                 const Double_t         EtIso                     = 2.,
                                                                 const Int_t            iIsoMethod                = 1,
                                                                 const Int_t            iEtIsoMethod              = 0,
                                                                 const Int_t            iUEMethod                 = 1,
                                                                 const Bool_t           bUseofTPC                 = kFALSE,
                                                                 const Double_t         TMdeta                    = 0.02,
                                                                 const Double_t         TMdphi                    = 0.03,
                                                                 const Bool_t           bTMClusterRejection       = kTRUE,
                                                                 const Bool_t           bTMClusterRejectionInCone = kTRUE,
                                                                 const Float_t          iIsoConeRadius            = 0.4,
                                                                 const Bool_t           iSmearingSS               = kFALSE,
                                                                 const Float_t          iWidthSSsmear             = 0.,
                                                                 const Float_t          iMean_SSsmear             = 0.,
                                                                 const Bool_t           iExtraIsoCuts             = kFALSE,
                                                                 const Bool_t           i_pPb                     = kFALSE
                                                                 )
{

  Printf("Preparing neutral cluster analysis\n");

    // #### Define manager and data container names
  AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
  if (!manager) {
    ::Error("AddTaskEMCALPhotonIsolation", "No analysis manager to connect to.");
    return NULL;
  }

  printf("Creating container names for cluster analysis\n");
  TString myContName("");
  if(bIsMC)
    myContName = Form("Analysis_Neutrals_MC");
  else
    myContName = Form("Analysis_Neutrals");

  myContName.Append(Form("_TM_%s_CPVe%.2lf_CPVp%.2lf_IsoMet%d_EtIsoMet%d_UEMet%d_TPCbound_%s_IsoConeR%.1f_NLMCut_%s_nNLM%d_SSsmear_%s_Width%.3f_Mean_%.3f_PureIso_%s",bTMClusterRejection? "On" :"Off", TMdeta , TMdphi ,iIsoMethod,iEtIsoMethod,iUEMethod,bUseofTPC ? "Yes" : "No",iIsoConeRadius,bNLMCut ? "On": "Off",NLMCut, iSmearingSS ? "On":"Off",iWidthSSsmear,iMean_SSsmear,iExtraIsoCuts?"On":"Off"));

    // #### Define analysis task
  AliAnalysisTaskEMCALPhotonIsolation* task = new AliAnalysisTaskEMCALPhotonIsolation("Analysis",bHisto);

    // #### Task preferences
  task->SetOutputFormat(iOutput);
  task->SetLCAnalysis(kFALSE);
  task->SetIsoConeRadius(iIsoConeRadius);
  task->SetEtIsoThreshold(EtIso); // after should be replace by EtIso
  task->SetCTMdeltaEta(TMdeta); // after should be replaced by TMdeta
  task->SetCTMdeltaPhi(TMdphi); // after should be replaced by TMdphi
  task->SetQA(kTRUE);
  task->SetIsoMethod(iIsoMethod);
  task->SetEtIsoMethod(iEtIsoMethod);
  task->SetUEMethod(iUEMethod);
  task->SetUSEofTPC(bUseofTPC);
  task->SetMC(bIsMC);
  task->SetM02Smearing(iSmearingSS);
  task->SetWidth4Smear(iWidthSSsmear);
  task->SetMean4Smear(iMean_SSsmear);
  task->SetExtraIsoCuts(iExtraIsoCuts);
  task->SetAnalysispPb(i_pPb);
  if(bIsMC && bMCNormalization) task->SetIsPythia(kTRUE);

  task->SetNLMCut(bNLMCut,NLMCut);

  TString name(Form("PhotonIsolation_%s_%s", ntracks, nclusters));
  cout<<"name of the containers  "<<name.Data()<<endl;

    // tracks to be used for the track matching (already used in TM task, TPC only tracks)
  AliTrackContainer *trackCont  = task->AddTrackContainer("tracks");
  if(!trackCont)
    Printf("Error with TPCOnly!!");
  trackCont->SetName("tpconlyMatch");
  trackCont->SetTrackFilterType(AliEmcalTrackSelection::kTPCOnlyTracks);
    // clusters to be used in the analysis already filtered
  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

    // tracks to be used in the analysis (Hybrid tracks)
  AliTrackContainer * tracksForAnalysis = task->AddTrackContainer("tracks");
  if(!tracksForAnalysis)
    Printf("Error with Hybrids!!");
  tracksForAnalysis->SetName("filterTracksAna");
  tracksForAnalysis->SetFilterHybridTracks(kTRUE);
  if(!bIsMC){
    tracksForAnalysis->SetTrackCutsPeriod(periodstr);
    tracksForAnalysis->SetDefTrackCutsPeriod(periodstr);
  }

  Printf("Name of Tracks for matching: %s \n Name for Tracks for Isolation: %s",trackCont->GetName(),tracksForAnalysis->GetName());

  printf("Task for neutral cluster analysis created and configured, pass it to AnalysisManager\n");
    // #### Add analysis task
  manager->AddTask(task);

  AliAnalysisDataContainer *contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer,Form("%s:NeutralClusters",AliAnalysisManager::GetCommonFileName()));
  AliAnalysisDataContainer *cinput  = manager->GetCommonInputContainer();
  manager->ConnectInput(task, 0, cinput);
  manager->ConnectOutput(task, 1, contHistos);

  return task;
}
<|endoftext|>


<commit_before>/*!
	@file
	@author		Albert Semenov
	@date		01/2008
	@module
*/
#include "MyGUI_Prerequest.h"
#include "MyGUI_ControllerFadeAlpha.h"
#include "MyGUI_Gui.h"
#include "MyGUI_InputManager.h"
#include "MyGUI_WidgetManager.h"
#include "MyGUI_Widget.h"

namespace MyGUI
{

	ControllerFadeAlpha::ControllerFadeAlpha()
	{
	}

	ControllerFadeAlpha::ControllerFadeAlpha(float _alpha, float _coef, bool _enabled) :
		mAlpha(_alpha), mCoef(_coef), mEnabled(_enabled)
	{
		MYGUI_DEBUG_ASSERT(mCoef > 0, "coef must be > 0");
	}

	const std::string & ControllerFadeAlpha::getType()
	{
		static std::string type("FadeAlphaController");
		return type;
	}

	void ControllerFadeAlpha::prepareItem(WidgetPtr _widget)
	{
		// подготовка виджета
		_widget->setEnabledSilent(mEnabled);

		if ((ALPHA_MIN != mAlpha) && (false == _widget->isShow())) {
			_widget->setAlpha(ALPHA_MIN);
			_widget->show();
		}

		// отписываем его от ввода
		if (false == mEnabled) InputManager::getInstance()._unlinkWidget(_widget);

		// вызываем пользовательский делегат для подготовки
		eventPreAction(_widget);
	}

	/*void ControllerFadeAlpha::replaseItem(WidgetPtr _widget, ControllerItem * _item)
	{
		ControllerFadeAlpha * item = static_cast<ControllerFadeAlpha*>(_item);
		mEnabled = item->getEnabled();
		mCoef = item->getCoef();
		mAlpha = item->getAlpha();
	}*/

	bool ControllerFadeAlpha::addTime(WidgetPtr _widget, float _time)
	{
		float alpha = _widget->getAlpha();

		// проверяем нужно ли к чему еще стремиться
		if (mAlpha > alpha) {
			alpha += _time * mCoef;
			if (mAlpha > alpha) {
				_widget->setAlpha(alpha);
				return true;
			}
			else {
				_widget->setAlpha(mAlpha);
			}
		}
		else if (mAlpha < alpha) {
			alpha -= _time * mCoef;
			if (mAlpha < alpha) {
				_widget->setAlpha(alpha);
				return true;
			}
			else {
				_widget->setAlpha(mAlpha);
			}
		}

		// вызываем пользовательский делегат пост обработки
		eventPostAction(_widget);

		return false;
	}

} // namespace MyGUI
<commit_msg>fix controller<commit_after>/*!
	@file
	@author		Albert Semenov
	@date		01/2008
	@module
*/
#include "MyGUI_Prerequest.h"
#include "MyGUI_ControllerFadeAlpha.h"
#include "MyGUI_Gui.h"
#include "MyGUI_InputManager.h"
#include "MyGUI_WidgetManager.h"
#include "MyGUI_Widget.h"

namespace MyGUI
{

	ControllerFadeAlpha::ControllerFadeAlpha()
	{
	}

	ControllerFadeAlpha::ControllerFadeAlpha(float _alpha, float _coef, bool _enabled) :
		mAlpha(_alpha), mCoef(_coef), mEnabled(_enabled)
	{
		MYGUI_DEBUG_ASSERT(mCoef > 0, "coef must be > 0");
	}

	const std::string & ControllerFadeAlpha::getType()
	{
		static std::string type("FadeAlphaController");
		return type;
	}

	void ControllerFadeAlpha::prepareItem(WidgetPtr _widget)
	{
		// подготовка виджета, блокируем если только нужно
		if (!mEnabled) _widget->setEnabledSilent(mEnabled);

		if ((ALPHA_MIN != mAlpha) && (false == _widget->isShow())) {
			_widget->setAlpha(ALPHA_MIN);
			_widget->show();
		}

		// отписываем его от ввода
		if (false == mEnabled) InputManager::getInstance()._unlinkWidget(_widget);

		// вызываем пользовательский делегат для подготовки
		eventPreAction(_widget);
	}

	/*void ControllerFadeAlpha::replaseItem(WidgetPtr _widget, ControllerItem * _item)
	{
		ControllerFadeAlpha * item = static_cast<ControllerFadeAlpha*>(_item);
		mEnabled = item->getEnabled();
		mCoef = item->getCoef();
		mAlpha = item->getAlpha();
	}*/

	bool ControllerFadeAlpha::addTime(WidgetPtr _widget, float _time)
	{
		float alpha = _widget->getAlpha();

		// проверяем нужно ли к чему еще стремиться
		if (mAlpha > alpha) {
			alpha += _time * mCoef;
			if (mAlpha > alpha) {
				_widget->setAlpha(alpha);
				return true;
			}
			else {
				_widget->setAlpha(mAlpha);
			}
		}
		else if (mAlpha < alpha) {
			alpha -= _time * mCoef;
			if (mAlpha < alpha) {
				_widget->setAlpha(alpha);
				return true;
			}
			else {
				_widget->setAlpha(mAlpha);
			}
		}

		// вызываем пользовательский делегат пост обработки
		eventPostAction(_widget);

		return false;
	}

} // namespace MyGUI
<|endoftext|>


<commit_before>#include "gillet_johnson.h"
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

// --------- TODO: no est contando com a capacidade de cada ponto de atendimento --------
namespace rotas
{
	namespace algoritmos
	{

		bool compara_diferencas(Cidade *a, Cidade *b) {
			return a->diferenca > b->diferenca;
		}

		vector<Cidade*> encontra_lista_designacao(vector<Cidade> &pontos_demanda, vector<Cidade> &pontos_atendimento) {
			vector<Cidade*> lista_designacao = vector<Cidade*>();

			if (pontos_atendimento.size() == 1) {
				lista_designacao.push_back(&(pontos_atendimento.front()));
				return lista_designacao;
			}

			for (unsigned int i = 0; i < pontos_demanda.size(); i++) {
				Cidade *ponto_demanda = &pontos_demanda[i];
				//Passo 1: Encontrar L1 e L2, as duas medianas mais prximas
				//vector<Cidade*>* Cidade::ordena_por_distancia(vector<Cidade> *destinos)
				vector<Cidade*> *pontos_atendimento_ordenados = ponto_demanda->ordena_por_distancia(&pontos_atendimento);
				//L1 -> cidades_ordenadas[0]
				//L2 -> cidades_ordenadas[1]

				//Passo 2: calcular a razo r = |L2| - |L1|
				double d1 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(0));
				double d2 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(1));
				ponto_demanda->diferenca = d2 - d1;

				//Passo 3: preencher a lista de designao
				lista_designacao.push_back(ponto_demanda);
			}
			return lista_designacao;
		}

		void remove_cidade(vector<Cidade> &cidades, Cidade *to_remove) {
			for (unsigned int i = 0; i < cidades.size(); i++) {
				if (cidades[i].get_id() == to_remove->get_id()) {
					cidades.erase(cidades.begin() + i);
					return;
				}
			}
		}

		void diminui_capacidade_pela_propria_demanda(vector<Cidade> &pontos_atendimento)
		{
			size_t size_pontos_atendimento = pontos_atendimento.size();
			for (unsigned int i = 0; i < size_pontos_atendimento; i++)
			{
				double capacidade_atual = pontos_atendimento[i].get_capacidade();
				double demanda_atual = pontos_atendimento[i].get_demanda();
				if (capacidade_atual > demanda_atual)
				{
					pontos_atendimento[i].set_capacidade(capacidade_atual - demanda_atual);
				}
			}
		}

		void GilletJohnson::encontra_medianas(vector<Cidade> & cidades) {

			vector<Cidade> pontos_atendimento = vector<Cidade>();
			vector<Cidade> pontos_demanda = vector<Cidade>();
			for (unsigned int i = 0; i < cidades.size(); i++) {
				if (cidades[i].is_mediana()) {
					pontos_atendimento.push_back(cidades[i]);
				}
				pontos_demanda.push_back(cidades[i]);
			}

			diminui_capacidade_pela_propria_demanda(pontos_atendimento);

			switch (pontos_atendimento.size()) {
			case 0:
				//Se no encontrou nenhum ponto de atendimento, o algoritmo no faz sentido
				//TODO disparar exceo
				return;
			case 1:
				//Se encontrou um ponto de atendimento, ele atende a todos os pontos de demanda
				for (unsigned int i = 0; i < cidades.size(); i++) {
					cidades[i].set_id_mediana(pontos_atendimento.front().get_id());
				}
				return;
			default:
				bool flag_demanda_estourada;
				vector<Cidade*> lista_designacao;

				do {
					flag_demanda_estourada = false;
					// Passos 1-3: Encontrar a lista de designao
					lista_designacao = encontra_lista_designacao(pontos_demanda, pontos_atendimento);

					//Passo 4: organizar a lista por ordem decrescente de d
					sort(lista_designacao.begin(), lista_designacao.end(), compara_diferencas);

					//Passo 5: Designar os pontos de demanda ao ponto de atendimento mais prximo
					for (unsigned i = 0; i < lista_designacao.size(); i++) {
						Cidade* ponto_atendimento_mais_prox = lista_designacao[i]->encontra_mais_proxima(&pontos_atendimento);
						double capacidade = ponto_atendimento_mais_prox->get_capacidade();
						if (capacidade >= lista_designacao[i]->get_demanda()) {
							ponto_atendimento_mais_prox->set_capacidade(capacidade - lista_designacao[i]->get_demanda());
							lista_designacao[i]->set_id_mediana(ponto_atendimento_mais_prox->get_id());
							cidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento_mais_prox->get_id());

							//Tira a cidade atendida dos pontos de demanda
							remove_cidade(pontos_demanda, lista_designacao[i]);
						}
						else {
							//Ponto de atendimento no tem mais capacidade, atribuir ao prximo disponvel
							vector<Cidade*> *pontos_atendimento_ordenados = lista_designacao[i]->ordena_por_distancia(&pontos_atendimento);
							for (size_t j = 0; j < pontos_atendimento_ordenados->size(); j++) {
								Cidade *ponto_atendimento = pontos_atendimento_ordenados->at(j);

								if (lista_designacao[i]->get_demanda() >= ponto_atendimento->get_capacidade()) {
									continue;
								}

								ponto_atendimento->set_capacidade(ponto_atendimento->get_capacidade() - lista_designacao[i]->get_demanda());
								lista_designacao[i]->set_id_mediana(ponto_atendimento->get_id());
								cidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento->get_id());
								break;
							}

							flag_demanda_estourada = true;
							//Tira a cidade atendida dos pontos de demanda
							remove_cidade(pontos_demanda, lista_designacao[i]);

							break;
						}
					}
				} while (flag_demanda_estourada);

				/*for (unsigned i = 0; i < lista_designacao.size(); i++) {
					Cidade cidade = lista_designacao[i];
					cidades[cidade.get_id()].set_id_mediana(cidade.get_id_mediana());
				}*/

				break;
			}

		}
	} // algoritmos
} // rotas
<commit_msg>Corrigido bug do gillet que tava adicionando sede duas vezes na rota<commit_after>#include "gillet_johnson.h"
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

// --------- TODO: no est contando com a capacidade de cada ponto de atendimento --------
namespace rotas
{
	namespace algoritmos
	{

		bool compara_diferencas(Cidade *a, Cidade *b) {
			return a->diferenca > b->diferenca;
		}

		vector<Cidade*> encontra_lista_designacao(vector<Cidade> &pontos_demanda, vector<Cidade> &pontos_atendimento) {
			vector<Cidade*> lista_designacao = vector<Cidade*>();

			if (pontos_atendimento.size() == 1) {
				lista_designacao.push_back(&(pontos_atendimento.front()));
				return lista_designacao;
			}

			for (unsigned int i = 0; i < pontos_demanda.size(); i++) {
				Cidade *ponto_demanda = &pontos_demanda[i];
				//Passo 1: Encontrar L1 e L2, as duas medianas mais prximas
				//vector<Cidade*>* Cidade::ordena_por_distancia(vector<Cidade> *destinos)
				vector<Cidade*> *pontos_atendimento_ordenados = ponto_demanda->ordena_por_distancia(&pontos_atendimento);
				//L1 -> cidades_ordenadas[0]
				//L2 -> cidades_ordenadas[1]

				//Passo 2: calcular a razo r = |L2| - |L1|
				double d1 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(0));
				double d2 = ponto_demanda->get_distancia(pontos_atendimento_ordenados->at(1));
				ponto_demanda->diferenca = d2 - d1;

				//Passo 3: preencher a lista de designao
				lista_designacao.push_back(ponto_demanda);
			}
			return lista_designacao;
		}

		void remove_cidade(vector<Cidade> &cidades, Cidade *to_remove) {
			for (unsigned int i = 0; i < cidades.size(); i++) {
				if (cidades[i].get_id() == to_remove->get_id()) {
					cidades.erase(cidades.begin() + i);
					return;
				}
			}
		}

		void diminui_capacidade_pela_propria_demanda(vector<Cidade> &pontos_atendimento)
		{
			size_t size_pontos_atendimento = pontos_atendimento.size();
			for (unsigned int i = 0; i < size_pontos_atendimento; i++)
			{
				double capacidade_atual = pontos_atendimento[i].get_capacidade();
				double demanda_atual = pontos_atendimento[i].get_demanda();
				if (capacidade_atual > demanda_atual)
				{
					pontos_atendimento[i].set_capacidade(capacidade_atual - demanda_atual);
				}
			}
		}

		void GilletJohnson::encontra_medianas(vector<Cidade> & cidades) {

			vector<Cidade> pontos_atendimento = vector<Cidade>();
			vector<Cidade> pontos_demanda = vector<Cidade>();
			for (unsigned int i = 0; i < cidades.size(); i++) {
				if (cidades[i].is_mediana()) {
					pontos_atendimento.push_back(cidades[i]);
				}
				else {
					pontos_demanda.push_back(cidades[i]);
				}
			}

			diminui_capacidade_pela_propria_demanda(pontos_atendimento);

			switch (pontos_atendimento.size()) {
			case 0:
				//Se no encontrou nenhum ponto de atendimento, o algoritmo no faz sentido
				//TODO disparar exceo
				return;
			case 1:
				//Se encontrou um ponto de atendimento, ele atende a todos os pontos de demanda
				for (unsigned int i = 0; i < cidades.size(); i++) {
					cidades[i].set_id_mediana(pontos_atendimento.front().get_id());
				}
				return;
			default:
				bool flag_demanda_estourada;
				vector<Cidade*> lista_designacao;

				do {
					flag_demanda_estourada = false;
					// Passos 1-3: Encontrar a lista de designao
					lista_designacao = encontra_lista_designacao(pontos_demanda, pontos_atendimento);

					//Passo 4: organizar a lista por ordem decrescente de d
					sort(lista_designacao.begin(), lista_designacao.end(), compara_diferencas);

					//Passo 5: Designar os pontos de demanda ao ponto de atendimento mais prximo
					for (unsigned i = 0; i < lista_designacao.size(); i++) {
						Cidade* ponto_atendimento_mais_prox = lista_designacao[i]->encontra_mais_proxima(&pontos_atendimento);
						double capacidade = ponto_atendimento_mais_prox->get_capacidade();
						if (capacidade >= lista_designacao[i]->get_demanda()) {
							ponto_atendimento_mais_prox->set_capacidade(capacidade - lista_designacao[i]->get_demanda());
							lista_designacao[i]->set_id_mediana(ponto_atendimento_mais_prox->get_id());
							cidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento_mais_prox->get_id());

							//Tira a cidade atendida dos pontos de demanda
							remove_cidade(pontos_demanda, lista_designacao[i]);
						}
						else {
							//Ponto de atendimento no tem mais capacidade, atribuir ao prximo disponvel
							vector<Cidade*> *pontos_atendimento_ordenados = lista_designacao[i]->ordena_por_distancia(&pontos_atendimento);
							for (size_t j = 0; j < pontos_atendimento_ordenados->size(); j++) {
								Cidade *ponto_atendimento = pontos_atendimento_ordenados->at(j);

								if (lista_designacao[i]->get_demanda() >= ponto_atendimento->get_capacidade()) {
									continue;
								}

								ponto_atendimento->set_capacidade(ponto_atendimento->get_capacidade() - lista_designacao[i]->get_demanda());
								lista_designacao[i]->set_id_mediana(ponto_atendimento->get_id());
								cidades[lista_designacao[i]->get_id()].set_id_mediana(ponto_atendimento->get_id());
								break;
							}

							flag_demanda_estourada = true;
							//Tira a cidade atendida dos pontos de demanda
							remove_cidade(pontos_demanda, lista_designacao[i]);

							break;
						}
					}
				} while (flag_demanda_estourada);

				/*for (unsigned i = 0; i < lista_designacao.size(); i++) {
					Cidade cidade = lista_designacao[i];
					cidades[cidade.get_id()].set_id_mediana(cidade.get_id_mediana());
				}*/

				break;
			}

		}
	} // algoritmos
} // rotas
<|endoftext|>