From 422a3aabf2c1ba585d83f721e83908165fb44a5a Mon Sep 17 00:00:00 2001 From: Scott Snyder <scott.snyder@cern.ch> Date: Tue, 16 Sep 2014 08:25:17 +0200 Subject: [PATCH] Fix cool dependencies and adjust for cool API change. (MuonCalibDbOperations-00-07-39) --- .../MuonCalibDbOperations/CalibDbConnection.h | 92 +++ .../CalibHeadOperations.h | 48 ++ .../CalibRtDbOperations.h | 74 ++ .../CalibT0DbOperations.h | 62 ++ .../CalibrationDbIOTool.h | 77 ++ .../MuonCalibDbOperations/CoolInserter.h | 116 +++ .../IConditionsStorage.h | 61 ++ .../IMuonCalibConditionsSource.h | 41 + .../MuonCalibDbCalibrationSource.h | 93 +++ .../MuonCalibDefaultCalibrationSource.h | 80 ++ .../MuonCalibDbOperations/cmt/requirements | 49 ++ .../MuonCalibDbOperations/doc/README | 6 + .../python/CalibrationDefaultSourceConfig.py | 48 ++ .../python/CalibrationSourceConfig.py | 61 ++ .../python/CalibrationTargetFolderConfig.py | 59 ++ .../python/MuonCalibConvertTimeSlewing.py | 32 + .../python/MuonCalibResolveTag.py | 21 + .../python/ReadCalibDb.py | 98 +++ .../MuonCalibDbOperations/python/ReadCool.py | 169 +++++ .../python/genGasmonSource.py | 32 + .../share/CalibCoolCompareRT.py | 131 ++++ .../share/CalibCoolCompareT0.py | 139 ++++ .../share/CalibDbCompareRT.py | 109 +++ .../share/CalibDbCompareT0.py | 115 +++ .../share/CalibDbCool2Calib.py | 86 +++ .../share/CalibDbDump.py | 58 ++ .../share/copy_to_cool.py | 196 +++++ .../share/copy_to_cool_configurator.py | 101 +++ .../share/copy_to_cool_old.py | 135 ++++ .../src/CalibDbConnection.cxx | 243 ++++++ .../src/CalibHeadOperations.cxx | 175 +++++ .../src/CalibRtDbOperations.cxx | 648 ++++++++++++++++ .../src/CalibT0DbOperations.cxx | 717 ++++++++++++++++++ .../src/CalibrationDbIOTool.cxx | 363 +++++++++ .../src/CoolInserter.cxx | 514 +++++++++++++ .../src/IConditionsStorage.cxx | 43 ++ .../src/MuonCalibDbCalibrationSource.cxx | 242 ++++++ .../src/MuonCalibDefaultCalibrationSource.cxx | 203 +++++ .../MuonCalibDbOperations_entries.cxx | 24 + .../components/MuonCalibDbOperations_load.cxx | 3 + 40 files changed, 5564 insertions(+) create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibDbConnection.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibHeadOperations.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibRtDbOperations.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibT0DbOperations.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibrationDbIOTool.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CoolInserter.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IConditionsStorage.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IMuonCalibConditionsSource.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDbCalibrationSource.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDefaultCalibrationSource.h create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/cmt/requirements create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/doc/README create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationDefaultSourceConfig.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationSourceConfig.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationTargetFolderConfig.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibConvertTimeSlewing.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibResolveTag.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCalibDb.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCool.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/genGasmonSource.py create mode 100755 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareRT.py create mode 100755 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareT0.py create mode 100755 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareRT.py create mode 100755 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareT0.py create mode 100755 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCool2Calib.py create mode 100755 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbDump.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_configurator.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_old.py create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibDbConnection.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibHeadOperations.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibRtDbOperations.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibT0DbOperations.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibrationDbIOTool.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CoolInserter.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/IConditionsStorage.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDbCalibrationSource.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDefaultCalibrationSource.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_entries.cxx create mode 100644 MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_load.cxx diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibDbConnection.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibDbConnection.h new file mode 100644 index 0000000000000..d58218f5a3b45 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibDbConnection.h @@ -0,0 +1,92 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef CALIBDBCONNECTION_H +#define CALIBDBCONNECTION_H + + +//c - c++ +#include "string" +#include "set" + +namespace coral { + class IRelationalDomain; + class AttributeList; + class IConnection; + class ISession; + class Context; + class IQuery; + class ITableDataEditor; +}//namespace coral + +namespace MuonCalib{ + +class CalibDbConnection + { + public: +//==================constructor - destructor==================================== + CalibDbConnection(const std::string& ConnectionString, const std::string& WorkingSchema ); + virtual ~CalibDbConnection(); +//==================public member functions===================================== + //connection control + bool OpenConnection(); + void CloseConnection(bool commit=false); + inline void SetLogin(const std::string & username, const std::string &password) + { + m_username = username; + m_password = password; + } + inline void GetLogin(std::string & username, std::string &password) const + { + username = m_username; + password = m_password; + } + inline const std::string GetConnectionString() const + { + return m_connection_string; + } + //set target user - the given login will be used as proxy + inline void SetTargetUser(const std::string & target_user) + { + m_target_user = target_user; + } + //transaction control + void OpenTransaction(); + void Commit(); + void Rollback(); + //get table editor - for insert and update ueries + coral::ITableDataEditor& GetTableEditor(const std::string & table_name); + //get query + coral::IQuery* GetQuery(); + void DestroyQuery(coral::IQuery* query); + //get latest header id + private: +//==================private data members======================================== + //connection strings + std::string m_connection_string, m_working_schema; + bool m_comp_loaded; + //pointer to the open query; + std::set<coral::IQuery*> m_queries; + // The application context + coral::Context* m_context; + //current connectino + coral::IConnection *m_connection; + //current session + coral::ISession *m_session; + // username + std::string m_username; + // password + std::string m_password; + //target user + std::string m_target_user; + //is true if transaction is open + bool m_transaction; +//================private member functions===================================== + // Returns a reference to the domain object for a given connection + coral::IRelationalDomain& domain( const std::string& connectionString ); + }; + +} //namespace MuonCalib + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibHeadOperations.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibHeadOperations.h new file mode 100644 index 0000000000000..c7cbc64804d3f --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibHeadOperations.h @@ -0,0 +1,48 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef CalibHeadOperations_h +#define CalibHeadOperations_h + +//c - c++ +#include <string> +#include <vector> + + +namespace coral { +class IQuery; +class AttributeList; +} + +namespace MuonCalib { + +class CalibDbConnection; + + +class CalibHeadOperations + { + public: +//=====================constructor - destructor================================= + CalibHeadOperations(CalibDbConnection & db_conn); + inline virtual ~CalibHeadOperations() + { + } +//=====================publlic member functions================================= + //Get latest HeadId + int GetLatestHeadId() const; + //Get header information + bool GetHeadInfo(int &head_id, int & lowrun, int &uprun, int &lowtime, int &uptime); + //Open data connection for given head_id. head_id=-1 => Get latest header + CalibDbConnection * GetDataConnection(int head_id=-1, bool write=false, const std::string & writer_connection="", const std::string & writer_user="", const std::string & writer_password=""); +//=====================private data members===================================== + private: + //connections + CalibDbConnection *m_meta_connection; + };//class + + +} //namespace MuonCalib + + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibRtDbOperations.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibRtDbOperations.h new file mode 100644 index 0000000000000..e55013fd02416 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibRtDbOperations.h @@ -0,0 +1,74 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef CalibRtDbOperations_h +#define CalibRtDbOperations_h + +//c - c++ +#include "vector" +#include "string" + +namespace coral { +class IQuery; +class AttributeList; +} + +namespace MuonCalib { + +class CalibDbConnection; +class NtupleStationId; +class RtFullInfo; +class SamplePoint; +class IConditionsStorage; + + +class CalibRtDbOperations + { + public: +//=====================constructor - destructor================================= + CalibRtDbOperations(CalibDbConnection & db_conn); + virtual ~CalibRtDbOperations(); +//=====================publlic member functions================================= + //load rt do not read full info, if full_info=NULL + bool LoadRt(const NtupleStationId & id, int head_id, bool validated, const std::string & /*site_name*/, std::vector<SamplePoint> & points, RtFullInfo * full_info); + //write/update rt + bool WriteUpdateRt(const NtupleStationId & id, int head_id, const std::string & /*site_name*/, const std::vector<SamplePoint> & points, int validflag, const RtFullInfo * full_info); + //set validation flag - last requested rt-id is used as key + bool SetValidflag(int validflag, bool commit=true); + //read for cconditions db insert + bool ReadForConditions(std::string /*site_name*/, int head_id, IConditionsStorage & storage); + private: +//=====================private data members==================================== + //db connection + CalibDbConnection & m_db_conn; + coral::IQuery * m_query; + //current mdt-rt-id + int m_rt_id, m_rt_map_t_id, m_head_id, m_region_id; + std::string m_prev_algs; + int m_n_points; + //red mdt-rt table + bool getRtId(bool validated, RtFullInfo * full_info); + //read r/t/s-table + inline bool readRTS(std::vector<SamplePoint> &points); + //update MDT_RT-Table + inline bool updateFullInfo(const RtFullInfo * full_info, const int & validflag, const int & n_points); + //update r-t-s-table + inline bool updateRTSable(const std::vector<SamplePoint> & points); + //insert into MDT_RT table + inline bool insertFullInfo(const RtFullInfo * full_info, const int & validflag, const int & n_points); + //insert line into r/t/s table + inline bool insertRTSable(const std::vector<SamplePoint> & points); + //initialize data buffer for MDT_RT table + inline void fullInfoInitData( const RtFullInfo * full_info, const int & validflag, coral::AttributeList &updateData, const int & n_bins, const bool & for_insert); + //initialize data buffer for MDT_RT_MAP_. Table + inline void rtTableInitData(coral::AttributeList & rowBuffer); + //get rt map t id + inline bool getRTMapTId(); + //prevent double inserts + inline bool checkRtPresent(const int & head_id, const std::string & /*site_name*/, const NtupleStationId & id, const int & validflag); + }; + +} //namespace MuonCalib + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibT0DbOperations.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibT0DbOperations.h new file mode 100644 index 0000000000000..e3e8a647011e9 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibT0DbOperations.h @@ -0,0 +1,62 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef CalibT0DbOperations_h +#define CalibT0DbOperations_h + +//c - c++ +#include <string> +#include <vector> + + +namespace coral { +class IQuery; +class AttributeList; +class ITableDataEditor; +} + +namespace MuonCalib { + +class CalibDbConnection; +class MdtStationT0Container; +class NtupleStationId; +class MdtTubeFitContainer; +class MuonFixedId; +class IConditionsStorage; + +class CalibT0DbOperations + { + public: +//=====================constructor - destructor================================= + CalibT0DbOperations(CalibDbConnection & db_conn); + virtual ~CalibT0DbOperations(); +//=====================publlic member functions================================= + //load t0 for chamber + MdtStationT0Container * LoadT0Calibration(const NtupleStationId & id, int head_id, std::string &site_name); + //load data for validation + MdtTubeFitContainer * LoadT0Validation(const NtupleStationId & id, int head_id, std::string &site_name); + //write t0 for chamber/set validation flag + // validation_flag[tb_nr]!=3 write complete tube entry + // if validation_flag.size()==0: all tubes are new + bool WriteT0Chamber(const NtupleStationId & id, const MdtTubeFitContainer * t0, std::vector<int> & validation_flag, int head_id, const std::string & site_name); + //read for storage in a conditinos database + bool ReadForConditions(std::string site_name, int head_id, IConditionsStorage & storage); + private: +//=====================private data members==================================== + //db connection + CalibDbConnection & m_db_conn; + coral::IQuery * m_query; +//=====================private functions======================================= + inline void initRowBuffer(std::vector<coral::AttributeList> & rowBuffer, const NtupleStationId &id, const int & head_id, const std::string & site_name, const MdtTubeFitContainer * t0); + inline void fillRowBuffer(std::vector<coral::AttributeList> & rowBuffer, const MdtTubeFitContainer * t0, const int & ml1, const int &ly, const int &ml2, const MuonFixedId &fixId); + bool setValidFlag(const std::string &site_name, const int & head_id, const int & tube_id, const int & new_validflag, coral::ITableDataEditor &editor); + //insert all tubes of chamber + bool insertTubes(const std::string & site_name, int head_id, const NtupleStationId & id, const MdtTubeFitContainer * t0, const std::vector<int> & validation_flag, coral::ITableDataEditor * editor[]); + bool setValidationFlag(const std::string & site_name, int head_id, const NtupleStationId & id, int from, int to, coral::ITableDataEditor & editor); + //check if data already existsd in db + inline bool checkTubesPresent(const int & head_id, const std::string &site_name, const NtupleStationId & id, const std::vector<int> & validflag); + };//class +} //namespace MuonCalib + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibrationDbIOTool.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibrationDbIOTool.h new file mode 100644 index 0000000000000..c5d92e2645b30 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CalibrationDbIOTool.h @@ -0,0 +1,77 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef CalibrationDbIOTool_H +#define CalibrationDbIOTool_H + +class MdtIdHelper; +namespace MuonGM { + class MuonDetectorManager; +} + +// MuonCalibStandAloneBase +#include "MuonCalibStandAloneBase/CalibrationIOTool.h" + +#include "MdtCalibUtils/RtDataFromFile.h" + +class RegionSelectionSvc; + +namespace MuonCalib { + +class CalibDbConnection; +class IRtRelation; +class SamplePoint; +class CalibHeadOperations; + +class CalibrationDbIOTool : public AlgTool, virtual public CalibrationIOTool + { + public: + /** constructor*/ + CalibrationDbIOTool(const std::string& t, const std::string& n, const IInterface* p); + /** initialisation */ + StatusCode initialize(); + /** finalisation */ + StatusCode finalize(); + /** write out t0 */ + StatusCode WriteT0(MdtTubeFitContainer* t0_output, const NtupleStationId & station_id, int iov_start, int iov_end); + /** load t0s*/ + StatusCode LoadT0(std::map<NtupleStationId, MdtStationT0Container *> &t0s, int /*iov_id*/); + /** write rt*/ + StatusCode WriteRt(const RtCalibrationOutput *rt_relation, const IRtResolution * resolution, const NtupleStationId & station_id, int iov_start, int iov_end, bool /*real_rt*/, bool /*real resolution*/); + /** load rts */ + StatusCode LoadRt(std::map<NtupleStationId, IRtRelation *> & rts, std::map<NtupleStationId, IRtResolution *> &res, int /*iov_id*/); + + private: + //! path to calibration directory - job option + std::string m_calib_dir; + //! create rt relation as lookup table if set tot true - job option + bool m_rt_lookup; + //! if true use validated - jo + bool m_use_validated_t0, m_use_validated_rt; + // url of oracle data-base + std::string m_db_ConnectionString; + std::string m_writer_connection_string; + std::string m_db_WorkingSchema; + //! account data + std::string m_reader_account, m_reader_password; + std::string m_writer_account, m_writer_password; + //username and password - job options + int m_max_rt_points; + int m_headid; + std::string m_sitename; + /** pointer to region selection service */ + RegionSelectionSvc *p_reg_sel_svc; + std::vector<MuonCalib::NtupleStationId> region_ids; + /** pointer to db connection */ + CalibDbConnection * m_connection; + CalibDbConnection * m_data_connections[2]; + CalibHeadOperations * m_head_ops; + /** convert rt and resolution to points */ + void fillRtPoints(const IRtRelation* rt_relation, std::vector<SamplePoint> & points); + void fillResPoints(const IRtResolution *rt_resolution, std::vector<SamplePoint> & points); + CalibDbConnection * get_connection(int write); + }; + +} +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CoolInserter.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CoolInserter.h new file mode 100644 index 0000000000000..245fd14da8453 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/CoolInserter.h @@ -0,0 +1,116 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef MuonCalib__CoolInserter_h +#define MuonCalib__CoolInserter_h + + +//this +#include "MuonCalibDbOperations/IConditionsStorage.h" +#include "MuonCalibDbOperations/IMuonCalibConditionsSource.h" + +//athena +#include "GaudiKernel/Algorithm.h" +#include "GaudiKernel/ToolHandle.h" + +// COOL API: database service bootstrap +#include "CoolApplication/Application.h" +#include "CoolApplication/DatabaseSvcFactory.h" + +// COOL API include files (CoolKernel) +#include "CoolKernel/Exception.h" +#include "CoolKernel/IDatabaseSvc.h" +#include "CoolKernel/IDatabase.h" +#include "CoolKernel/IFolder.h" +#include "CoolKernel/IObject.h" +#include "CoolKernel/IObjectIterator.h" +#include "CoolKernel/StorageType.h" +#include "CoolKernel/types.h" +#include "CoolKernel/Record.h" + + +//MuonCalibStandAloneBase +#include "MuonCalibStandAloneBase/NtupleStationId.h" + +class RegionSelectionSvc; + +namespace MuonGM + { + class MuonDetectorManager; + } + +class MdtIdHelper; + +namespace MuonCalib { + +class CalibDbConnection; +class CalibHeadOperations; + +class CoolInserter : public Algorithm + + { + public: +//====================destructor - constructor================================= + CoolInserter(const std::string& name, ISvcLocator* pSvcLocator); + inline ~CoolInserter() {} + /** Is called at the beginning of the analysis */ + StatusCode initialize(); + /** execute function NOTE: This will read all events at once*/ + StatusCode execute(); + /** finalize functions */ + StatusCode finalize(); + bool CoolConnect(const std::string &connection_string, const std::string & tag_t0); + + bool StartT0Chamber(const NtupleStationId & sid); + bool AppendT0(float t0, int validflag, float adc0); + bool StoreT0Chamber(const NtupleStationId & id, const std::string & file, unsigned int creation_flags=0); + bool StoreRtChamber(const NtupleStationId & id, const std::map<int, SamplePoint> & points, const std::string & file, unsigned int creation_flags=0); +//====================interface functions====================================== + private: +//====================private data============================================= + //version string - job option + std::string m_version; + //tags - job options + std::vector<std::string> m_tagt0 ; // tag of the folder + std::vector<std::string> m_tagrt; // tag of the folder + //overwirte iov - job-option + int m_iov_start, m_iov_end; + long long m_iovt_start, m_iovt_end; + //cool connection string - job option job option + std::string m_cool_connection_string; + //cool folders - job options + std::vector<std::string> m_t0_folder; + std::vector<std::string> m_rt_folder; + //indicate if cool folders should be compressed if they are created + std::vector<bool> m_compressed_t0; + std::vector<bool> m_compressed_rt; + //calibratino source tools - jo + ToolHandleArray<IMuonCalibConditionsSource> m_calibraiton_sources; + //region selection service - copy part of the calibration + const RegionSelectionSvc *p_reg_sel_svc; + //cool + cool::IDatabasePtr m_db; + std::vector<cool::IFolderPtr> m_mdtt0_fld; + std::vector<cool::IFolderPtr> m_mdtrt_fld; + cool::Application app; + std::map<bool, coral::AttributeList> m_mdtt0_cool_row; + std::map<bool, coral::AttributeList> m_mdtrt_cool_row; + //flags for cool status + bool m_cool_connect, m_t0_created, m_rt_created; + //already filled chambers - do not double fill + std::set<NtupleStationId> m_t0_filled, m_rt_filled; + const MdtIdHelper* m_mdtIdHelper; + const MuonGM::MuonDetectorManager* m_detMgr; + std::ostringstream m_data_string; + int m_n_tubes_added; + int m_n_tubes_chamber; + float m_aver_t0, m_aver_adc; + NtupleStationId m_sid; + //create a new cool folder + inline bool create_folder(const unsigned int & fldr_nr, const bool &is_rt); + }; + +} //namespace Muoncalib + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IConditionsStorage.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IConditionsStorage.h new file mode 100644 index 0000000000000..bd47042ca84ba --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IConditionsStorage.h @@ -0,0 +1,61 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef MuonCalib__IConditionStorage_h +#define MuonCalib__IConditionStorage_h + +//c - c++ +#include "vector" +#include "string" +#include "map" + +namespace coral { +class AttributeList; +} + +namespace MuonCalib { + +class SamplePoint; + +class IConditionsStorage + { + public: + class TubeId { + public: + int ml, ly, tb; + TubeId(int id_num); + inline TubeId() : ml(0), ly(0), tb(0) {} + bool operator <(const TubeId &other) const; + bool operator >(const TubeId &other) const; + }; + inline IConditionsStorage() {} + inline virtual ~IConditionsStorage() {} + //request rows from MDT_TUBE table + inline virtual const std::vector<std::string> & RowsFromMdtTubeTable() const + { + return m_empty; + } + //request rows from MDT_TUBE_V table + inline virtual const std::vector<std::string> & RowsFromMdtTubeVTable() const + { + return m_empty; + } + //request rows from MDT_TUBE_C table + inline virtual const std::vector<std::string> & RowsFromMdtTubeCTable() const + { + return m_empty; + } + + //call back function for every t0 chamber + virtual bool StoreT0Chamber(const int & chamber, const std::map<TubeId, coral::AttributeList> & rows)=0; + //call back for rt + virtual bool StoreRtChamber(const int & chamber, const std::map<int, SamplePoint> & points)=0; + private: + std::vector<std::string> m_empty; + }; + + +} //namespace MuonCalib + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IMuonCalibConditionsSource.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IMuonCalibConditionsSource.h new file mode 100644 index 0000000000000..7a44f573a1a73 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/IMuonCalibConditionsSource.h @@ -0,0 +1,41 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef MuonCalib_IMuonCalibConditionsSource +#define MuonCalib_IMuonCalibConditionsSource + +// Gaudi +#include "GaudiKernel/AlgTool.h" + +namespace MuonCalib { + +class CoolInserter; + +static const InterfaceID IID_IMuonCalibConditionsSource("MuonCalib::IMuonCalibConditionsSource", 1, 0); + +class IMuonCalibConditionsSource: virtual public IAlgTool + { + public: + /** destructor */ + inline virtual ~IMuonCalibConditionsSource() + { + } + /** interface method */ + static const InterfaceID& interfaceID() { return IID_IMuonCalibConditionsSource;} + /** insert calibration */ + inline bool InstertCalibration(CoolInserter * inserter, bool store_t0, bool store_rt) + { + m_inserter = inserter; + return insert_calibration(store_t0, store_rt); + } + inline virtual void SetIOV(int &/*start*/, int & /*end*/) const {} + protected: + CoolInserter * m_inserter; + virtual bool insert_calibration(bool store_t0, bool store_rt)=0; + + }; + +}//namespace MuonCalib + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDbCalibrationSource.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDbCalibrationSource.h new file mode 100644 index 0000000000000..b64ffbeddbb48 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDbCalibrationSource.h @@ -0,0 +1,93 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef MuonCalib_MuonCalibDbCalibrationSource +#define MuonCalib_MuonCalibDbCalibrationSource + +//this +#include "MuonCalibDbOperations/IConditionsStorage.h" +#include "MuonCalibDbOperations/IMuonCalibConditionsSource.h" +//athena +#include "GaudiKernel/Algorithm.h" +#include "GaudiKernel/ToolHandle.h" + +namespace MuonCalib { + +class CalibDbConnection; +class RegionSelectorBase; +class CalibHeadOperations; + +class MuonCalibDbCalibrationSource: public AlgTool, virtual public IMuonCalibConditionsSource, virtual public IConditionsStorage + { + public: +//===============================destructor -- constructor====================== + /** constructor*/ + MuonCalibDbCalibrationSource(const std::string& t, const std::string& n, const IInterface* p); +//===============================AlgTool interface ============================= + /** initialize */ + StatusCode initialize(); + /** finalize */ + StatusCode finalize(); +//===============================IConditionsStorage interface=================== + /** call back for t0 */ + bool StoreT0Chamber(const int & chamber, const std::map<TubeId, coral::AttributeList> & rows); + //call back for rt + bool StoreRtChamber(const int & chamber, const std::map<int, SamplePoint> & points); + private: + inline const std::vector<std::string> & RowsFromMdtTubeTable() const + { + return m_mdt_tube_cols; + } + inline const std::vector<std::string> & RowsFromMdtTubeVTable() const + { + return m_mdt_tube_v_cols; + } +//===============================IMuonCalibConditionsSource interface ========== + inline void SetIOV(int & start, int & end) const + { + if(start<0) + { + start=m_iov_start; + } + if(end<0) + { + end=m_iov_end; + } + } +//===============================job options==================================== + //head id and site name - job options + std::string m_site_name; + int m_head_id; + //overwirte iov - job-option + int m_iov_start, m_iov_end; + //connection string for calibration db - job option + std::string m_calib_connection_string, m_calib_working_schema; + //username and password for calib-db connection + std::string m_username, m_password; + //calibratino region, for which the calibration is copied + std::string m_region_str; + //drift time offsets per radius - job options + std::vector<float> m_drift_time_offsets; + //store t0 or rt + bool m_store_t0, m_store_rt; + //global t0 offset - added to the t0 values + float m_t0_offset; + //creation flags - job options + bool m_time_slewing_applied, m_b_field_correction_applied; + unsigned int m_creation_flags; +//===============================private data================================== + //selected columns + std::vector<std::string> m_mdt_tube_cols, m_mdt_tube_v_cols; + CalibDbConnection *m_connection, *m_data_connection; + CalibHeadOperations *m_head_ops; + RegionSelectorBase *m_region; + protected: +//===============================IMuonCalibConditionsSource interface ========== + /** insert calibration */ + bool insert_calibration(bool store_t0, bool store_rt); + }; + +}//namespace MuonCalib + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDefaultCalibrationSource.h b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDefaultCalibrationSource.h new file mode 100644 index 0000000000000..a31afdd6c8478 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/MuonCalibDbOperations/MuonCalibDefaultCalibrationSource.h @@ -0,0 +1,80 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef MuonCalib_MuonCalibDefaultCalibrationSource +#define MuonCalib_MuonCalibDefaultCalibrationSource + +//this +#include "MuonCalibDbOperations/IMuonCalibConditionsSource.h" + +//athena +#include "GaudiKernel/Algorithm.h" +#include "GaudiKernel/ToolHandle.h" + +//c - c++ +#include <vector> +#include <string> +#include <map> + +class RegionSelectionSvc; + +namespace MuonCalib { + +//MuonCalibStandAloneBase +class RegionSelectorBase; + +class SamplePoint; +class MuonCalibDefaultCalibrationSource: public AlgTool, virtual public IMuonCalibConditionsSource + { + public: +//===============================destructor -- constructor====================== + /** constructor*/ + MuonCalibDefaultCalibrationSource(const std::string& t, const std::string& n, const IInterface* p); +//===============================AlgTool interface ============================= + /** initialize */ + StatusCode initialize(); + /** finalize */ + inline StatusCode finalize() + { + return StatusCode::SUCCESS; + } + private: +//===============================job options==================================== + //regions and t0 values + std::vector<std::string> m_t0_region_str; + std::vector<float> m_t0; + std::vector<bool> m_time_slewing_applied_t0; + std::vector<bool> m_bfield_applied_t0; + //regions and rt + std::vector<std::string> m_rt_region_str; + std::vector<std::string> m_rt_files; + std::vector<bool> m_time_slewing_applied_rt; + std::vector<bool> m_bfield_applied_rt; +//==============================private data members============================ + //creation flags + std::vector<unsigned int> m_creation_flags_t0; + std::vector<unsigned int> m_creation_flags_rt; + //region classes + std::vector<RegionSelectorBase *> m_t0_regions, m_rt_regions; + //rtt point vector + std::vector<std::map<int, SamplePoint> > m_rt_points; + //region selection service - copy part of the calibration + const RegionSelectionSvc *p_reg_sel_svc; +//===============================private functions============================== + //initialize regions + StatusCode initialize_regions(const std::vector<std::string> ®_str, std::vector<RegionSelectorBase *> & reg); + void initialize_creation_flags(const std::vector<bool> & ts_applied, const std::vector<bool> & bf_applied, unsigned int n_regions, std::vector<unsigned int> & flags); + inline StatusCode load_rt_files(); + inline bool store_t0_fun(); + inline bool store_rt_fun(); + protected: +//===============================IMuonCalibConditionsSource interface ========== + /** insert calibration */ + bool insert_calibration(bool store_t0, bool store_rt); + }; + +}//namespace MuonCalib + + +#endif diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/cmt/requirements b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/cmt/requirements new file mode 100644 index 0000000000000..534aebe43c229 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/cmt/requirements @@ -0,0 +1,49 @@ +package MuonCalibDbOperations + +manager Domizia Orestano <domizia.orestano@cern.ch> +author Domizia Orestano <domizia.orestano@cern.ch> + +use AtlasPolicy AtlasPolicy-* + + +use GaudiInterface GaudiInterface-* External + +use MuonCalibStandAloneBase MuonCalibStandAloneBase-* MuonSpectrometer/MuonCalib/MuonCalibStandAlone +use MdtCalibUtils MdtCalibUtils-* MuonSpectrometer/MuonCalib/MdtCalib + + + +branches MuonCalibDbOperations src share exe run + +apply_pattern declare_joboptions files="*.py" +apply_pattern dual_use_library files= *.cxx +apply_pattern declare_python_modules files="*.py" + +#macro_append MuonCalib_CoolInsert_dependencies "MuonCalibDbOperations" +#application MuonCalib_CoolInsert ../exe/MuonCalib_CoolInsert.cxx + +use AtlasCOOL AtlasCOOL-* External +macro_append MuonCalibDbOperations_linkopts " -lz" +macro_append MuonCalibDbOperationsLib_shlibflags " -lz" + + +private + +apply_pattern declare_scripts files="CalibDbCompareRT.py CalibDbCompareT0.py CalibDbDump.py CalibCoolCompareT0.py CalibCoolCompareRT.py CalibDbCool2Calib.py" + +apply_tag NEEDS_CORAL_BASE +apply_tag NEEDS_COOL_FACTORY +use AtlasCOOL AtlasCOOL-* External +use MdtCalibData MdtCalibData-* MuonSpectrometer/MuonCalib/MdtCalib +use MdtCalibRt MdtCalibRt-* MuonSpectrometer/MuonCalib/MdtCalib +use MuonCalibMath MuonCalibMath-* MuonSpectrometer/MuonCalib/MuonCalibUtils +use StoreGate StoreGate-* Control +use MuonCalibIdentifier MuonCalibIdentifier-* MuonSpectrometer/MuonCalib +use AtlasCORAL AtlasCORAL-* External +use MuonIdHelpers MuonIdHelpers-* MuonSpectrometer +use MuonReadoutGeometry MuonReadoutGeometry-* MuonSpectrometer/MuonDetDescr +use AthenaKernel AthenaKernel-* Control + +private +#macro cppdebugflags '$(cppdebugflags_s)' +#macro_remove componentshr_linkopts "-Wl,-s" diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/doc/README b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/doc/README new file mode 100644 index 0000000000000..8f014e6eb5410 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/doc/README @@ -0,0 +1,6 @@ +access to ORACLE Calibration DBs +author D.Orestano + +customization: to run Test.exe +you should specify your DB, the schema name and the password in +authentication.xml and in test.cxx diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationDefaultSourceConfig.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationDefaultSourceConfig.py new file mode 100644 index 0000000000000..89a6b6b3384e9 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationDefaultSourceConfig.py @@ -0,0 +1,48 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +from MuonCalibDbOperations.MuonCalibDbOperationsConf import MuonCalib__CoolInserter,MuonCalib__MuonCalibDefaultCalibrationSource + +class MuonCalib__CalibrationDefaultSourceConfig: + + __t0_regions=[] + __t0=[] + __rt_regions=[] + __rt_files=[] + __time_slewing_applid_t0=[] + __bfield_correction_applid_t0=[] + __time_slewing_applid_rt=[] + __bfield_correction_applid_rt=[] + + + def AddDefaultT0(self, region, t0, time_slewing_applied=True, bfield_applied=True): + self.__t0_regions.append(region) + self.__t0.append(t0) + self.__time_slewing_applid_t0.append(time_slewing_applied) + self.__bfield_correction_applid_t0.append(bfield_applied) + + def AddDefaultRt(self, region, filename, time_slewing_applied=True, bfield_applied=True): + self.__rt_regions.append(region) + self.__rt_files.append(filename) + self.__time_slewing_applid_rt.append(time_slewing_applied) + self.__bfield_correction_applid_rt.append(bfield_applied) + + def ConfigureTool(self, tool_svc, cool_inserter): + if len(self.__t0_regions) == 0 and len(self.__rt_regions) ==0: + return + MuonCalibDefaultCalibrationSource = MuonCalib__MuonCalibDefaultCalibrationSource() + tool_svc += MuonCalibDefaultCalibrationSource + cool_inserter.CalibrationSources.append( MuonCalibDefaultCalibrationSource ) + + MuonCalibDefaultCalibrationSource.T0Regions = self.__t0_regions[:] + MuonCalibDefaultCalibrationSource.T0 = self.__t0[:] + MuonCalibDefaultCalibrationSource.TimeSlewingAppliedT0 = self.__time_slewing_applid_t0[:] + MuonCalibDefaultCalibrationSource.BFieldCorrectionAppliedT0 = self.__bfield_correction_applid_t0[:] + + + MuonCalibDefaultCalibrationSource.RtRegions = self.__rt_regions[:] + MuonCalibDefaultCalibrationSource.RtFiles = self.__rt_files[:] + MuonCalibDefaultCalibrationSource.TimeSlewingAppliedRt = self.__time_slewing_applid_rt[:] + MuonCalibDefaultCalibrationSource.BFieldCorrectionAppliedRt = self.__bfield_correction_applid_rt[:] + + +MuonCalib_gCalibrationDefaultSourceConfig = MuonCalib__CalibrationDefaultSourceConfig() diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationSourceConfig.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationSourceConfig.py new file mode 100644 index 0000000000000..fc3198b7d683c --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationSourceConfig.py @@ -0,0 +1,61 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +import sys +from MuonCalibDbOperations.MuonCalibDbOperationsConf import MuonCalib__MuonCalibDbCalibrationSource +import cx_Oracle + + +MuonCalib__gCalibrationSourceConfigs = [] + +class MuonCalib__CalibrationSourceConfig: + + __working_schemata={'MP': "ATLAS_MUONCALIB_MPI_META", 'RM': "ATLAS_MUONCALIB_RM_META", 'UM': "ATLAS_MUONCALIB_UM_META"} + + def __init__(self, site_name, head_id, region="", store_rt=True, store_t0=True): + + if not site_name in self.__working_schemata: + print "FATAL: unknown site name ", site_name + print "FATAL: must be one of", self.__working_schemata.keys() + sys.exit(1) + + self.SiteName=site_name + self.HeadID=head_id + self.Region=region + self.StoreRt=store_rt + self.StoreT0=store_t0 + self.T0Offset=0.0 + self.DriftTimeOffsetsVsR=[] + self.__name = "MuonCalibDbCalibrationSource_" + str(len(MuonCalib__gCalibrationSourceConfigs)) + MuonCalib__gCalibrationSourceConfigs.append(self) + self.TimeSlewingApplied=True + self.BFieldCorrectionApplied=True + + def GenCalibrationSource(self, reader_passwd): + source=MuonCalib__MuonCalibDbCalibrationSource(self.__name) + source.WorkingSchema = self.__working_schemata[self.SiteName] + source.UserName = "ATLAS_MUONCALIB_READER" + if hasattr(self, "ReaderPassword"): + source.Password = self.ReaderPassword + else: + source.Password = reader_passwd + source.SiteName = self.SiteName + source.HeadId = self.HeadID + source.Region = self.Region + source.StoreRT = self.StoreRt + source.StoreT0 = self.StoreT0 + source.T0Offset = self.T0Offset + source.DriftTimeOffsetsVsR = self.DriftTimeOffsetsVsR + source.TimeSlewingApplied = self.TimeSlewingApplied + source.BFieldCorrectionApplied = self.BFieldCorrectionApplied + if hasattr(self, "ConnectionString"): + source.ConnectionString = self.ConnectionString + else: + source.ConnectionString = "oracle://ATLAS_MUON/ATLAS_MUONCALIB_READER" + return source + + def GetTime(self, reader_cursor): + reader_cursor.execute("select LOWTIME from " + self.__working_schemata[self.SiteName] + ".MDT_HEAD where head_id=:hid", {'hid': self.HeadID}) + lowtime, =reader_cursor.fetchone() + return lowtime + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationTargetFolderConfig.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationTargetFolderConfig.py new file mode 100644 index 0000000000000..15f6d00c0cb3e --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/CalibrationTargetFolderConfig.py @@ -0,0 +1,59 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +import sys +from PyCool import cool,coral +import CoolConvUtilities.AtlCoolLib as AtlCoolLib +from MuonCalibDbOperations.MuonCalibResolveTag import ResolveTag + + +MuonCalib__gCalibrationTargetConfigs = [] + +class MuonCalib__CalibrationTargetConfig: + + def __init__(self, FolderType="T0"): + if not FolderType in ["T0", "RT"]: + print "FATAL Folder type must be 'T0' or 'RT'" + sys.exit(1) + +#set defaults + if FolderType=="T0": + self.__is_t0=True + self.Folder = "/MDT/T0" + self.Tag=None + self.Compress=False + else: + self.__is_t0=False + self.Folder = "/MDT/RT" + self.Tag=None + self.Compress=False + + MuonCalib__gCalibrationTargetConfigs.append(self) + + + def ResolveGlobalTag(self, tag, dbstring="COOLOFL_MDT/COMP200"): + if self.Tag: + print "INFO Tag for", self.Folder, "already set to", self.Tag + print "INFO Not resolving global tag" + return + try: + db=AtlCoolLib.indirectOpen(dbstring, oracle=True, readOnly=True, debug=True) + except Exception,e: + print 'Problem opening database',e + sys.exit(-1) + cool_folder=db.getFolder(self.Folder) + self.Tag=ResolveTag(cool_folder, tag) + print "INFO tag '" + tag + "' resolves to '" + self.Tag + "' for folder '" + self.Folder + "'" + + + + def AddToCoolInserter(self, coolInserter): + + if self.__is_t0: + coolInserter.T0Folder.append(self.Folder) + coolInserter.T0Tag.append(self.Tag) + coolInserter.T0FolderCompress.append(self.Compress) + else: + coolInserter.RtFolder.append(self.Folder) + coolInserter.RtTag.append(self.Tag) + coolInserter.RtFolderCompress.append(self.Compress) + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibConvertTimeSlewing.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibConvertTimeSlewing.py new file mode 100644 index 0000000000000..5b395c9edc6f5 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibConvertTimeSlewing.py @@ -0,0 +1,32 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +import math + +GasmonDriftTimeOffsetsVsR_total = [ -5.45973, -4.57559, -3.71995, -3.45051, -3.4505, -3.4834, -3.59509, -3.74869, -3.92066, -4.10799, -4.35237, -4.61329, -4.84111, -5.14524 ] + +GasmonDriftTimeOffsetT0=GasmonDriftTimeOffsetsVsR_total[0] + +GasmonDriftTimeOffsetsVsR=[] +for x in GasmonDriftTimeOffsetsVsR_total: + GasmonDriftTimeOffsetsVsR.append(x - GasmonDriftTimeOffsetT0) + +def GetRBin(r): + if r<=0: + return 0 + if r>=14.6: + return len(GasmonDriftTimeOffsetsVsR) -1 + return int(math.floor(r/14.6 * len(GasmonDriftTimeOffsetsVsR))) + + +def Ts2NoTs(r, t): + return t - GasmonDriftTimeOffsetsVsR[GetRBin(r)] + +def NoTs2Ts(r, t): + return t + GasmonDriftTimeOffsetsVsR[GetRBin(r)] + +def TimeSlewingApplied(obj): + return bool(obj.payload()['tech'] & 0x10) + + + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibResolveTag.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibResolveTag.py new file mode 100644 index 0000000000000..7d2940bcfe63d --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/MuonCalibResolveTag.py @@ -0,0 +1,21 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +def ResolveTag(folder, tag): + theTag=tag + if tag.upper() in ['NEXT', 'CURRENT']: + from PyCool import cool + import sys + if not '/afs/cern.ch/user/a/atlcond/utils/python/' in sys.path: + sys.path.append('/afs/cern.ch/user/a/atlcond/utils/python/') + from AtlCoolBKLib import resolveAlias + if tag.upper()=="NEXT": + theTag=resolveAlias.getNext() + else: + theTag=resolveAlias.getCurrent() + theTag=theTag.replace('*', 'ST') + print tag, "resolves to", theTag + folder_tag=folder.resolveTag(theTag) + if folder_tag!=theTag: + print theTag, "resolves to", folder_tag + return folder_tag + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCalibDb.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCalibDb.py new file mode 100644 index 0000000000000..868a7807a7918 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCalibDb.py @@ -0,0 +1,98 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +import cx_Oracle +from MuonCalibIdentifier.MuonFixedIdUnpack import * +import sys + +sys.argv=[sys.argv[0], '-b'] + +from ROOT import * + + +def get_data_schema(cursor, db, head_id): + + meta_schema={'MP': 'ATLAS_MUONCALIB_MPI_META', 'UM' : 'ATLAS_MUONCALIB_UM_META', 'RM' : 'ATLAS_MUONCALIB_RM_META'} + cursor.execute("select data_schema from " + meta_schema[db] + ".MDT_HEAD where head_id=:hid", {'hid': head_id}) + return cursor.fetchone()[0] + +def build_rt_relation(r,t, rt_id): + gr=TGraph(len(r)) + gr.SetName("gr_" + str(rt_id)) + for i in range(0, len(r)): + gr.SetPoint(i, r[i], t[i]) + sp=TSpline3("sp_" + str(rt_id), gr) + up = MuonFixedIdUnpack(rt_id) + id_str=up.stationNameString() + "_" + str(up.stationPhi()) + "_" + str(up.stationEta()) + gr.Write("gr_" + id_str) + sp.Write("sp_" + id_str) + return gr, sp + + + +def ReadRtCalibDb(db, reader_passwd, head_id): + connection=cx_Oracle.connect('ATLAS_MUONCALIB_READER', reader_passwd, 'ATLAS_MUON') + cursor=connection.cursor() + data_schema=get_data_schema(cursor, db, head_id) + + query="select rt.validflag, rt.region_id, mp.r, mp.t from " + data_schema + ".mdt_rt rt, " + data_schema + ".mdt_rt_map mp where mp.head_id=:hid and rt.head_id=:hid and rt.region_id= mp.region_id and mp.calibflag= rt.calibflag and mp.point_nr<rt.bins and rt.validflag>2 order by rt.region_id, mp.point_nr" + cursor.arraysize = 1000*100 + + cursor.execute(query, {'hid': head_id}) + rt_gr={} + rt_sp={} + r=[] + t=[] + prev_id=None + for validflag_in, region_id, r_p, t_p in cursor.fetchall(): + this_id=region_id + if this_id!=prev_id: + if len(r): + rt_gr[prev_id], rt_sp[prev_id] = build_rt_relation(r,t, prev_id) + r=[] + t=[] + prev_id = this_id + r.append(r_p) + t.append(t_p) + if len(r)>0: + rt_gr[prev_id], rt_sp[prev_id] = build_rt_relation(r,t, prev_id) + return rt_gr, rt_sp + + +def build_t0_vec(values): + ret=[] + keys=values.keys() + keys.sort() + for key in keys: + ret.append(values[key]) + return ret + +def ReadT0CalibDb(db, reader_passwd, head_id): + connection=cx_Oracle.connect('ATLAS_MUONCALIB_READER', reader_passwd, 'ATLAS_MUON') + cursor=connection.cursor() + data_schema=get_data_schema(cursor, db, head_id) + + query="select CHAMBER, TUBE_ID, TO_NUMBER(P4), VALIDFLAG, TO_NUMBER(ADC_0) from " + data_schema + ".MDT_TUBE where head_id=:hid and validflag>2 order by chamber" + cursor.arraysize = 1000*400 + cursor.execute(query, {'hid': head_id}) + t0s={} + current_values={} + prev_chamber=None + filled_chambers=set([]) + for chamber, tube, t0, validflag, adc in cursor.fetchall(): + if prev_chamber != chamber: + if prev_chamber: + up=MuonFixedIdUnpack(prev_chamber) + t0s[(up.stationNameString(), up.stationPhi(), up.stationEta())] = build_t0_vec(current_values) + filled_chambers.add(prev_chamber) + prev_chamber = chamber + current_values={} + up=MuonFixedIdUnpack(tube) + tid=288 * (up.mdtMultilayer() - 1) + 72 * (up.mdtTubeLayer() - 1) + (up.mdtTube() - 1 ) + current_values[tid] = (t0, validflag, adc) + up=MuonFixedIdUnpack(prev_chamber) + t0s[(up.stationNameString(), up.stationPhi(), up.stationEta())] = build_t0_vec(current_values) + return t0s + + + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCool.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCool.py new file mode 100644 index 0000000000000..2416bf46dfc0f --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/ReadCool.py @@ -0,0 +1,169 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +import CoolConvUtilities.AtlCoolLib as AtlCoolLib +from PyCool import cool,coral +import zlib,StringIO +import sys +import re +from MuonCalibDbOperations.MuonCalibResolveTag import ResolveTag +from MuonCalibDbOperations.MuonCalibConvertTimeSlewing import * + +sys.argv=[sys.argv[0], '-b'] + +from ROOT import * +from MuonCalibIdentifier.MuonFixedIdUnpack import * + +def UnpackData(data): + if type(data)==str: + return data + if type(data)==coral.Blob: + blob=StringIO.StringIO() + for i in range(data.size()): + blob.write(chr(data[i])) + unpacked=zlib.decompress(blob.getvalue()) + return unpacked + +def iov_keygen(iov): + return long(iov[0])*10000000 + iov[1] + +def DumpFolderSummary(db_string, folder, tag, run=None): + + try: + db=AtlCoolLib.indirectOpen(db_string, oracle=True, readOnly=True, debug=True) + except Exception,e: + print 'Problem opening database',e + sys.exit(-1) + +#get folder and tag + cool_folder=db.getFolder(folder) + cool_tag=ResolveTag(cool_folder, tag) + + counters={} + if run: + objs=cool_folder.browseObjects((run<<32), ((run+1)<<32), cool.ChannelSelection.all(), cool_tag) + else: + objs=cool_folder.browseObjects(0, (999999<<32), cool.ChannelSelection.all(), cool_tag) + for obj in objs: + file_col=obj.payload()['file'] + file_items=re.split('[A-Z,a-z]*', file_col) + site="default" + head_id=-1 + if len(file_items)==2: + try: + head_id = int(file_items[1]) + site = re.sub("[0-9]", "", file_col) + except ValueError: + site=file_col + ts="NOTS" + if TimeSlewingApplied(obj): + ts="TS" + ident=(obj.since()>>32, obj.until()>>32, site, head_id, ts) + if not ident in counters: + counters[ident] = 0 + counters[ident] +=1 + for ident in sorted(counters.keys(), key=iov_keygen): + print "[", ident[0], ",", ident[1], "[", ident[2], ident[3], ident[4], ":" , counters[ident] + + +def ReadRtCool(db_string, folder, tag, run_number): + + try: + db=AtlCoolLib.indirectOpen(db_string, oracle=True, readOnly=True, debug=True) + except Exception,e: + print 'Problem opening database',e + sys.exit(-1) + +#get folder and tag + cool_folder=db.getFolder(folder) + cool_tag=ResolveTag(cool_folder, tag) + +#data to be filled + graphs={} + splines={} + iovs=set([]) + + myiov=(run_number<<32) + + objs=cool_folder.browseObjects(myiov,myiov, cool.ChannelSelection.all(), cool_tag) + for obj in objs: + iov=(obj.since(), obj.until()) + iovs.add(iov) + sp=UnpackData(obj.payload()['data']).split('\n') + sp1=sp[0].split(',') + chamber=int(sp1[0]) + n_points=int(sp1[1]) + sp2=sp[1].split(',') + graphs[chamber]=TGraphErrors(n_points) + up=MuonFixedIdUnpack(chamber) + if up.stationNameString()=='XXX': + print "Invalid station name in ", obj.payload()['file'] + sys.exit(1) + nm=up.stationNameString() + "_" + str(up.stationPhi()) + "_" + str(up.stationEta()) +# print nm + ts_applied=TimeSlewingApplied(obj) + for i in range(0, n_points): + r=float(sp2[3*i]) + t=float(sp2[3*i+1]) + s=float(sp2[3*i+2]) + if not ts_applied: + t_new=NoTs2Ts(r, t) + t=t_new + graphs[chamber].SetPoint(i, r, t) + graphs[chamber].SetPointError(i, 0, s) + splines[chamber]=TSpline3("sp_" + nm, graphs[chamber]) + if gDirectory.IsWritable(): + splines[chamber].Write("sp_" + nm) + graphs[chamber].Write("gr_" + nm) + + return graphs, splines, iovs + + +def ReadT0Cool(db_string, folder, tag, run_number): + + try: + db=AtlCoolLib.indirectOpen(db_string, oracle=True, readOnly=True, debug=True) + except Exception,e: + print 'Problem opening database',e + sys.exit(-1) + +#get folder and tag + cool_folder=db.getFolder(folder) + cool_tag=ResolveTag(cool_folder, tag) + myiov=(run_number<<32) +#data + t0_values={} + + objs=cool_folder.browseObjects(myiov,myiov, cool.ChannelSelection.all(), cool_tag) + + for obj in objs: + sp=UnpackData(obj.payload()['data']).split('\n') + sp1=sp[0].split(',') + ch_sp=sp1[0][2:].split("_") + ch_id=(ch_sp[0], int(ch_sp[1]), int(ch_sp[2])) + ntubes=int(sp1[-1]) + + t0_items=sp[1].split(",") + t0_values[ch_id] = [] + ts_applied=TimeSlewingApplied(obj) + for i in range(0, ntubes): + t0=float(t0_items[3*i+0]) + if not ts_applied: + t0+= GasmonDriftTimeOffsetT0 + t0_values[ch_id].append((t0, int(t0_items[3*i+1]), float(t0_items[3*i+2]))) + + return t0_values + + +def GetFolderTag(db_string, folder): + dbSvc=cool.DatabaseSvcFactory.databaseService() + try: + db=dbSvc.openDatabase(db_string) + except Exception,e: + print 'Problem opening database',e + sys.exit(-1) + +#get folder and tag + cool_folder=db.getFolder(folder) + for x in cool_folder.listTags(): + return x + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/genGasmonSource.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/genGasmonSource.py new file mode 100644 index 0000000000000..cc0bcf2bbb397 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/python/genGasmonSource.py @@ -0,0 +1,32 @@ +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +import sys +from MuonCalibDbOperations.CalibrationSourceConfig import * +import cx_Oracle +import time + + +def MuonCalib__genGasmonSource(toroidOn, cal_time, reader_cursor): + if len(MuonCalib__gCalibrationSourceConfigs)==0 and not time: + print "FATAL Cannot generate gasmon source if no time and no other calibration sources are given" + sys.exit(1) + + if not cal_time: + cal_time = MuonCalib__gCalibrationSourceConfigs[0].GetTime(reader_cursor) + + if not type(cal_time)==type(""): + tm=time.gmtime(cal_time) + cal_time=str(tm.tm_year) + str(tm.tm_mon).zfill(2) + str(tm.tm_mday).zfill(2) + imp_str="GASMON_RT_" + cal_time + "_TP" + if toroidOn: + imp_str += "M" + + print "INFO Getting", imp_str + + reader_cursor.execute("select head_id, data_schema from ATLAS_MUONCALIB_UM_META.MDT_HEAD where IMPLEMENTATION=:imp", {'imp':imp_str}) + gm_head_id, gm_schema= reader_cursor.fetchone() + + return MuonCalib__CalibrationSourceConfig("UM", gm_head_id, "", True, False) + + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareRT.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareRT.py new file mode 100755 index 0000000000000..04aa1c1ed04af --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareRT.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python + +import sys +import getopt + +cool_database_strings=['COOLOFL_MDT/COMP200', 'COOLOFL_MDT/COMP200'] +cool_folders=['/MDT/RT', '/MDT/RT'] +cool_tags=['COMCOND-BLKPST-004-07', 'COMCOND-BLKPST-004-07'] +run_numbers=[None, None] + +def printhelp(argv0): + sys.stderr.write("Usage: " + argv0 + " [-h] [-s <cool database string>] [-f <cool folder>] [-t <cool tag>] <run number 1> [-s <cool database string>] [-f <cool folder>] [-t <cool tag>] <run number 2> <root file>\n") + sys.exit(1) + +theArgs=sys.argv[1:] + +for i in xrange(2): + optlist, args = getopt.getopt(theArgs, 'hs:f:t:') + + for opt, oa in optlist: + if opt=='-s': + if oa[-2:]=='db': + cool_database_strings[i] = 'sqlite://;schema=' + oa + ';dbname=COMP200' + cool_tags[i]='' + else: + cool_database_strings[i] = oa + continue + if opt=='-f': + cool_folders[i]=oa + continue + if opt=='-t': + cool_tags[i]=oa + continue + if opt=='-h': + printhelp(sys.argv[0]) + continue + if len(args)<2: + sys.stderr.write("Error in commandline!\n") + printhelp(sys.argv[0]) + try: + run_numbers[i]=int(args[0]) + except ValueError: + sys.stderr.write("Error in commandline!\n") + printhelp(sys.argv[0]) + theArgs=args[1:] + +if len(theArgs)!=1: + sys.stderr.write("Error in commandline!\n") + printhelp(sys.argv[0]) + +outfile_nm=theArgs[0] + +print cool_database_strings +print cool_folders +print cool_tags +print run_numbers +print outfile_nm + +sys.argv=[sys.argv[0], '-b'] + +from ROOT import * +from array import * + +from MuonCalibDbOperations.ReadCool import * +from MuonCalibIdentifier.MuonFixedIdUnpack import * + +cool_rts=[] + +outfile=TFile(outfile_nm, "RECREATE") + +for i in xrange(2): + outfile.mkdir("graphs_"+str(i)).cd() + if not cool_tags[i]: + cool_tags[i] = GetFolderTag(cool_database_strings[i], cool_folders[i]) + print "Cool database: " + cool_database_strings[i] + " " + cool_folders[i] + " " + cool_tags[i] + " " + str(run_numbers[i]) + cool_rts.append(ReadRtCool(cool_database_strings[i], cool_folders[i], cool_tags[i], run_numbers[i])[1]) + + +all_stations=set(cool_rts[0].keys()).union(set(cool_rts[1].keys())) + +outfile.cd() +tree=TTree("tree", "t0 differences") + +station_nm=array('c', "BIL\0") +station_phi=array('i', [0]) +station_eta=array('i', [0]) +tree.Branch("station_nm", station_nm, "station_nm/C") +tree.Branch("station_phi", station_phi, "station_phi/I") +tree.Branch("station_eta", station_eta, "station_eta/I") + +n_tubes=[] +t=[] +v=[] +r=array('f', 13*[0.0]) +for i in xrange(13): + r[i]=float(i+1) +tree.Branch("r", r, "r[13]/F") +#validflag=[] +#adc=[] +for i in xrange(2): + t.append(array('f', 13*[0.0])) + v.append(array('f', 13*[0.0])) + tree.Branch("t_" + str(i), t[-1], "t_" + str(i) + "[13]/F") + tree.Branch("v_" + str(i), v[-1], "v_" + str(i) + "[13]/F") + +for ident in all_stations: + up=MuonFixedIdUnpack(ident) + nm=up.stationNameString() + for i in range(0,3): + station_nm[i]=nm[i] + station_phi[0]=up.stationPhi() + station_eta[0]=up.stationEta() + for i in xrange(2): + if not ident in cool_rts[i]: + for j in xrange(13): + t[i][j]=-9e9 + v[i][j]=-9e9 + continue + theRt=cool_rts[i][ident] + for j in xrange(13): + t[i][j]=theRt.Eval(float(j+1)) + v[i][j]=1/theRt.Derivative(float(j+1)) + + + tree.Fill() +outfile.Write() + + + + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareT0.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareT0.py new file mode 100755 index 0000000000000..46dc2ff76f26e --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibCoolCompareT0.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python + +import sys +import getopt + +cool_database_strings=['COOLOFL_MDT/COMP200', 'COOLOFL_MDT/COMP200'] +cool_folders=['/MDT/T0', '/MDT/T0'] +cool_tags=['COMCOND-BLKPST-004-07', 'COMCOND-BLKPST-004-07'] +run_numbers=[None, None] + +def printhelp(argv0): + sys.stderr.write("Usage: " + argv0 + " [-h] [-s <cool database string>] [-f <cool folder>] [-t <cool tag>] <run number 1> [-s <cool database string>] [-f <cool folder>] [-t <cool tag>] <run number 2> <root file>\n") + sys.exit(1) + +theArgs=sys.argv[1:] + +for i in xrange(2): + optlist, args = getopt.getopt(theArgs, 'hs:f:t:') + + for opt, oa in optlist: + if opt=='-s': + if oa[-2:]=='db': + cool_database_strings[i] = 'sqlite://;schema=' + oa + ';dbname=COMP200' + cool_tags[i]='' + else: + cool_database_strings[i] = oa + continue + if opt=='-f': + cool_folders[i]=oa + continue + if opt=='-t': + cool_tags[i]=oa + continue + if opt=='-h': + printhelp(sys.argv[0]) + continue + if len(args)<2: + sys.stderr.write("Error in commandline!\n") + printhelp(sys.argv[0]) + try: + run_numbers[i]=int(args[0]) + except ValueError: + sys.stderr.write("Error in commandline!\n") + printhelp(sys.argv[0]) + theArgs=args[1:] + +if len(theArgs)!=1: + sys.stderr.write("Error in commandline!\n") + printhelp(sys.argv[0]) + +outfile_nm=theArgs[0] + +print cool_database_strings +print cool_folders +print cool_tags +print run_numbers +print outfile_nm + +sys.argv=[sys.argv[0], '-b'] + +from ROOT import * +from array import * + +from MuonCalibDbOperations.ReadCool import * + +cool_t0s=[] + +for i in xrange(2): + if not cool_tags[i]: + cool_tags[i] = GetFolderTag(cool_database_strings[i], cool_folders[i]) + print "Cool database: " + cool_database_strings[i] + " " + cool_folders[i] + " " + cool_tags[i] + " " + str(run_numbers[i]) + cool_t0s.append(ReadT0Cool(cool_database_strings[i], cool_folders[i], cool_tags[i], run_numbers[i])) + + +all_stations=set(cool_t0s[0].keys()).union(set(cool_t0s[1].keys())) + + +outfile=TFile(outfile_nm, "RECREATE") +tree=TTree("tree", "t0 differences") + +station_nm=array('c', "BIL\0") +station_phi=array('i', [0]) +station_eta=array('i', [0]) +tree.Branch("station_nm", station_nm, "station_nm/C") +tree.Branch("station_phi", station_phi, "station_phi/I") +tree.Branch("station_eta", station_eta, "station_eta/I") + +n_tubes=[] +t0=[] +t0_mean=[] +t0_min=[] +t0_max=[] +#validflag=[] +#adc=[] +for i in xrange(2): + n_tubes.append(array('i', [0])) + tree.Branch("n_tubes_" + str(i), n_tubes[-1], "n_tubes_" + str(i) + "/I") + t0.append(array('f', 432*[0.0])) + tree.Branch("t0_" + str(i), t0[-1], "t0_" + str(i) + "[n_tubes_" + str(i) + "]/F") + t0_mean.append(array('f', [0.0])) + tree.Branch("t0_mean_" + str(i), t0_mean[-1], "t0_mean_" + str(i) + "/F") + t0_min.append(array('f', [0.0])) + tree.Branch("t0_min_" + str(i), t0_min[-1], "t0_min_" + str(i) + "/F") + t0_max.append(array('f', [0.0])) + tree.Branch("t0_max_" + str(i), t0_max[-1], "t0_max_" + str(i) + "/F") + + +for ident in all_stations: + for i in range(0,3): + station_nm[i]=ident[0][i] + station_phi[0]=ident[1] + station_eta[0]=ident[2] + for i in xrange(2): + if not ident in cool_t0s[i]: + n_tubes[i][0]=0 + t0_mean[i][0]=9e9 + t0_min[i][0]=9e9 + t0_max[i][0]=9e9 + continue + t0_mean[i][0]=0.0 + t0_min[i][0]=9e9 + t0_max[i][0]=-9e9 + theT0s=cool_t0s[i][ident] + n_tubes[i][0]=len(theT0s) + for j in xrange(n_tubes[i][0]): + t0_mean[i][0]+=theT0s[j][0] + if t0_min[i][0]>theT0s[j][0]: + t0_min[i][0]=theT0s[j][0] + if t0_max[i][0]<theT0s[j][0]: + t0_max[i][0]=theT0s[j][0] + t0[i][j]=theT0s[j][0] + t0_mean[i][0]/=float(n_tubes[i][0]) + tree.Fill() +outfile.Write() + + + + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareRT.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareRT.py new file mode 100755 index 0000000000000..bc48f7a057a5f --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareRT.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python + +import getopt +import sys + +cool_database_string='COOLOFL_MDT/COMP200' +cool_folder='/MDT/RT' +cool_tag='MDTRT-BON-UPD1-02' + +def printhelp(argv0): + sys.stderr.write("Usage: " + argv0 + " [-h] [-s <cool database string>] [-f <cool folder>] [-t <cool tag>] <run number> <calib db>/<head id> <reader password> <root file>\n") + sys.exit(1) + +optlist, args = getopt.gnu_getopt(sys.argv, 'hs:f:t:') +if not len(args)==5: + printhelp(args[0]) + +for opt, oa in optlist: + if opt=='-s': + if oa[-2:]=='db': + cool_database_string = 'sqlite://;schema=' + oa + ';dbname=COMP200' + cool_tag='' + else: + cool_database_string = oa + continue + if opt=='-f': + cool_folder=oa + continue + if opt=='-t': + cool_tag=oa + continue + +run_number=int(args[1]) +asp=args[2].split("/") +db=asp[0] +head_id=int(asp[1]) +reader_password=args[3] +root_filename=args[4] + +sys.argv=[ sys.argv[0], '-b' ] +from ROOT import * +from array import * +from MuonCalibDbOperations.ReadCalibDb import * +from MuonCalibDbOperations.ReadCool import * +from MuonCalibIdentifier.MuonFixedIdUnpack import * + + +outfile=TFile(root_filename, "RECREATE") + +if not cool_tag: + cool_tag = GetFolderTag(cool_database_string, cool_folder) + +outfile.mkdir("cool").cd() +print "Cool database: " + cool_database_string + " " + cool_folder + " " + cool_tag + " " + str(run_number) +cool_gr, cool_sp, dummy=ReadRtCool(cool_database_string, cool_folder, cool_tag, run_number) + +outfile.mkdir("calibdb").cd() +print "Calibration database: " + db + "/" + str(head_id) +calib_gr, calib_sp=ReadRtCalibDb(db, reader_password, head_id) + +outfile.cd() +tree=TTree("tree", "rt differences") +region_id=array('i', [0]) +station_nm=array('c', "BIL\0") +station_phi=array('i', [0]) +station_eta=array('i', [0]) +tree.Branch("region_id", region_id, "region_id/I") +tree.Branch("station_nm", station_nm, "station_nm/C") +tree.Branch("station_phi", station_phi, "station_phi/I") +tree.Branch("station_eta", station_eta, "station_eta/I") +n_points=array('i', [0]) +n_points_calib=array('i', [0]) +n_points_cool=array('i', [0]) +dt13=array('f', [0.0]) +dr13=array('f', [0.0]) +dr=array('f', 100*[0.0]) +dt=array('f', 100*[0.0]) +tree.Branch("n_points", n_points, "n_points/I") +tree.Branch("n_points_calib", n_points_calib, "n_points_calib/I") +tree.Branch("n_points_cool", n_points_cool, "n_points_cool/I") +tree.Branch("dt13", dt13, "dt13/F") +tree.Branch("dr13", dr13, "dr13/F") + +for chamber_id in cool_gr: + if not calib_gr.has_key(chamber_id): + continue + region_id[0]=chamber_id + up=MuonFixedIdUnpack(chamber_id) + st_str=up.stationNameString() + for i in range(0,3): + station_nm[i]=st_str[i] + station_phi[0]=up.stationPhi() + station_eta[0]=up.stationEta() + co_gr=cool_gr[chamber_id] + co_sp=cool_sp[chamber_id] + ca_gr=calib_gr[chamber_id] + ca_sp=calib_sp[chamber_id] + n_points[0] = min(co_gr.GetN(), ca_gr.GetN(), 100) + n_points_calib[0] = ca_gr.GetN() + n_points_cool[0] = co_gr.GetN() + for i in range(i, n_points[0]): + dr[i]=ca_gr.GetX()[i] + dt[i]=ca_gr.GetY()[i] + dt13[0] = ca_sp.Eval(13.0) - co_sp.Eval(13.0) + dr13[0] = dt13[0] / ca_sp.Derivative(13.0) + tree.Fill() + +outfile.Write() + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareT0.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareT0.py new file mode 100755 index 0000000000000..6e0c17ad5a99a --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCompareT0.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python + +import getopt +import sys + +cool_database_string='COOLOFL_MDT/COMP200' +cool_folder='/MDT/T0' +cool_tag='MDTT0-BON-UPD1-02' + +def printhelp(argv0): + sys.stderr.write("Usage: " + argv0 + " [-h] [-s <cool database string>] [-f <cool folder>] [-t <cool tag>] <run number> <calib db>/<head id> <reader password> <root file>\n") + sys.exit(1) + +optlist, args = getopt.gnu_getopt(sys.argv, 'hs:f:t:') +if not len(args)==5: + printhelp(args[0]) + +for opt, oa in optlist: + if opt=='-s': + if oa[-2:]=='db': + cool_database_string = 'sqlite://;schema=' + oa + ';dbname=COMP200' + cool_tag='' + else: + cool_database_string = oa + continue + if opt=='-f': + cool_folder=oa + continue + if opt=='-t': + cool_tag=oa + continue + +run_number=int(args[1]) +asp=args[2].split("/") +db=asp[0] +head_id=int(asp[1]) +reader_password=args[3] +root_filename=args[4] + +sys.argv=[ sys.argv[0], '-b' ] +from ROOT import * +from array import * +from MuonCalibDbOperations.ReadCalibDb import * +from MuonCalibDbOperations.ReadCool import * + +if not cool_tag: + cool_tag = GetFolderTag(cool_database_string, cool_folder) + + +print "Cool database: " + cool_database_string + " " + cool_folder + " " + cool_tag + " " + str(run_number) +cool_t0s=ReadT0Cool(cool_database_string, cool_folder, cool_tag, run_number) + +print "Calibration database: " + db + "/" + str(head_id) +calib_t0s=ReadT0CalibDb(db, reader_password, head_id) +print len(calib_t0s), "chambers in calibration databse" + +outfile=TFile(root_filename, "RECREATE") +tree=TTree("tree", "t0 differences") + +station_nm=array('c', "BIL\0") +station_phi=array('i', [0]) +station_eta=array('i', [0]) +tree.Branch("station_nm", station_nm, "station_nm/C") +tree.Branch("station_phi", station_phi, "station_phi/I") +tree.Branch("station_eta", station_eta, "station_eta/I") +n_tubes=array('i', [0]) +n_tubes_calib=array('i', [0]) +n_tubes_cool=array('i', [0]) +dt0=array('f', 432*[0.0]) +t0_cool=array('f', 432*[0.0]) +t0_calib=array('f', 432*[0.0]) +d_validflag=array('i', 432*[0]) +validflag_cool=array('i', 432*[0]) +validflag_calib=array('i', 432*[0]) +d_adc=array('f', 432*[0]) +tree.Branch("n_tubes", n_tubes, "n_tubes/I") +tree.Branch("n_tubes_calib", n_tubes_calib, "n_tubes_calib/I") +tree.Branch("n_tubes_cool", n_tubes_cool, "n_tubes_cool/I") +tree.Branch("dt0", dt0, "dt0[n_tubes]/F") + +tree.Branch("t0_cool", t0_cool, "t0_cool[n_tubes]/F") +tree.Branch("t0_calib", t0_calib, "t0_calib[n_tubes]/F") + + +tree.Branch("d_validflag", d_validflag, "d_validflag[n_tubes]/I") +tree.Branch("validflag_cool", validflag_cool, "validflag_cool[n_tubes]/I") +tree.Branch("validflag_calib", validflag_calib, "validflag_calib[n_tubes]/I") +tree.Branch("d_adc", d_adc, "d_adc[n_tubes]/F") + +for chamber_id in cool_t0s: + if not calib_t0s.has_key(chamber_id): + n_tubes[0]=0 + continue + for i in range(0,3): + station_nm[i]=chamber_id[0][i] + print station_nm + station_phi[0]=chamber_id[1] + station_eta[0]=chamber_id[2] + cot0s=cool_t0s[chamber_id] + cat0s=calib_t0s[chamber_id] + n_tubes[0]=min(len(cot0s), len(cat0s)) + n_tubes_calib[0]=len(cat0s) + n_tubes_cool[0]=len(cot0s) + for i in range(0, n_tubes[0]): + dt0[i]=cot0s[i][0] - cat0s[i][0] + d_validflag[i]=cot0s[i][1] - cat0s[i][1] + validflag_cool[i]=cot0s[i][1] + validflag_calib[i]=cat0s[i][1] + d_adc[i]=cot0s[i][2] - cat0s[i][2] + t0_cool[i]=cot0s[i][0] + t0_calib[i]=cat0s[i][0] + tree.Fill() + +outfile.Write() + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCool2Calib.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCool2Calib.py new file mode 100755 index 0000000000000..3e14767872479 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbCool2Calib.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python + +import getopt +import sys +import os + +cool_database_string='COOLOFL_MDT/COMP200' +t0_cool_folder=None +rt_cool_folder=None +cool_tag='CURRENT' + + +def printhelp(argv0): + sys.stderr.write("Usage: " + argv0 + " [-h] [-s <cool database string>] [-o <t0 cool folder>] [-r <rt cool folder>] [-t <cool tag>] <run nr>\n") + sys.exit(1) + +optlist, args = getopt.gnu_getopt(sys.argv, 'hs:o:r:t:') + +for opt, oa in optlist: + if opt=='-s': + if oa[-2:]=='db': + cool_database_string = 'sqlite://;schema=' + oa + ';dbname=COMP200' + cool_tag='' + else: + cool_database_string = oa + continue + if opt=='-o': + t0_cool_folder=oa + continue + if opt=='-r': + rt_cool_folder=oa + continue + if opt=='-t': + cool_tag=oa + continue + if opt=='-h': + printhelp(sys.argv[0]) + +if not len(args)==2: + sys.stderr.write("Need Run Number\n") + print len(args), args + printhelp(sys.argv[0]) + +try: + run_number=int(args[1]) +except ValueError: + sys.stderr.write("Cannot parse run number " + run_number + "\n") + printhelp(sys.argv[0]) + +sys.argv=[ sys.argv[0], '-b' ] +from MuonCalibDbOperations.ReadCool import * +from MuonCalibIdentifier.MuonFixedIdUnpack import * +from ROOT import * + + +def dump_rt(ident, rt): + up=MuonFixedIdUnpack(ident) + if up.stationNameString()=="XXX": + sys.stderr.write("WARNING: Unknown station found!\n") + return + f=file("calibration/rts/Rt_" + str(up.stationNameString()) + "_" + str(up.stationPhi()) + "_" + str(up.stationEta()) + ".dat", "w") + f.write("v1.0 1 Resolution 1 20000 0 0 0 0 dummy 800 ") + f.write(str(rt.GetN())) + f.write("\n") + for i in xrange(rt.GetN()): + f.write(str(rt.GetX()[i]) + " " + str(rt.GetY()[i]) + " " + str(rt.GetEY()[i])) + f.write("\n") + + + + + +if rt_cool_folder: + graphs=ReadRtCool(cool_database_string, rt_cool_folder, cool_tag, run_number)[0] + try: + os.makedirs("calibration/rts") + except OSError: + try: + os.stat("calibration/rts") + except OSError: + sys.stderr.write("ERROR: Cannot create calibration directory!\n") + sys.exit(1) + for ident, rt in graphs.items(): + dump_rt(ident, rt) + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbDump.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbDump.py new file mode 100755 index 0000000000000..b1eefad327acd --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/CalibDbDump.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +import getopt +import sys + +cool_database_string='COOLOFL_MDT/COMP200' +cool_folder='/MDT/T0' +cool_tag='' + +def printhelp(argv0): + sys.stderr.write("Usage: " + argv0 + " [-h] [-s <cool database string>] [-f <cool folder>] [-t <cool tag>] [<run nr> [<run nr> [..]]]\n") + sys.exit(1) + +optlist, args = getopt.gnu_getopt(sys.argv, 'hs:f:t:') +#if not len(args)==0: +# printhelp(args[0]) + +for opt, oa in optlist: + if opt=='-s': + if oa[-2:]=='db': + cool_database_string = 'sqlite://;schema=' + oa + ';dbname=COMP200' + cool_tag='' + else: + cool_database_string = oa + continue + if opt=='-f': + cool_folder=oa + continue + if opt=='-t': + cool_tag=oa + continue + if opt=='-h': + printhelp(sys.argv[0]) + + + +sys.argv=[ sys.argv[0], '-b' ] +from MuonCalibDbOperations.ReadCool import * + +if not cool_tag: + cool_tag = GetFolderTag(cool_database_string, cool_folder) + + +print "Cool database: " + cool_database_string + " " + cool_folder + " " + cool_tag + +if len(args)==1: + DumpFolderSummary(cool_database_string, cool_folder, cool_tag) + sys.exit(0) + +for run_nr in args[1:]: + print "IOVs for run ", run_nr + print (len("IOVs for run ") + len(run_nr) + 1) * "=" + DumpFolderSummary(cool_database_string, cool_folder, cool_tag, int(run_nr)) + print + + + + diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool.py new file mode 100644 index 0000000000000..ffdbbd41f3bb1 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool.py @@ -0,0 +1,196 @@ +from MuonCalibDbOperations.CalibrationSourceConfig import * +from MuonCalibDbOperations.CalibrationTargetFolderConfig import * +from MuonCalibDbOperations.CalibrationDefaultSourceConfig import * +import inspect +coolFileName = inspect.getfile( inspect.currentframe() )[:-3] + ".db" +################################################################################ +################################################################################ +################################################################################ +################################################################################ + + +################################### +#set detector description version # +# release default if commented # +################################### + +atlasVersion = "ATLAS-GEO-20-00-01" + +########################################################### +# if set to true, gasmon rts will be filled for chambers, # +# where rt is not set by other calibration sources # +########################################################### + +autoFillGasmon = False + +#################################################### +# set to true if you are filling conditions for MC # +#################################################### + +isMC=False + +##################################################### +# password for ATLAS_MUONCALIB_READER@INTR.CERN.CH # +# required for automatic addition of gasmon rts # +##################################################### + +readerPassword = "REPLACE ME" + +##################################################### +# slelect toroid status # +# required for automatic addition of gasmon rts # +##################################################### + +toroidOn = False + +######################################### +# time for retrieving gas monitor rt # +# eicther None, utime or "YYYYMMDD" # +######################################### + +calibrationTime = None + +########################################## +# drift time offsets for gas monitor rts # +########################################## + +#GasmonDriftTimeOffsetsVsR = [ -5.45973, -4.57559, -3.71995, -3.45051, -3.4505, -3.4834, -3.59509, -3.74869, -3.92066, -4.10799, -4.35237, -4.61329, -4.84111, -5.14524 ] + + +############################################ +# path to the target sqlite-file # +# defaults to sciptname # +############################################ + +#coolFileName = "test.db" + +########################################################## +# set to true, if you want to insert in an existing file # +########################################################## + +appendToExistingFile = False + +######################################################## +# target IOV # +# -1 in beginning or end: get from calibration source # +# [0, -2]: Infinite IOV, use for UPD1 updates # +# [-1, -1]: Get IOV form calibration source # +######################################################## + +targetIov = [0, -2] + +################################################# +# region selector string. # +# Only chambers in this region will be inserted # +################################################# + +regionToInsert = "" + +#################################################### +# this tag will be resolved for the target folders # +#################################################### + +if toroidOn: + globalConditionsTag = "CURRENT" +else: + globalConditionsTag = "CURRENT" + +#globalConditionsTag = "SOMETHING-ELSE" + +############################################################################### +############################################################################### +## ## +## CALIBRATION SOURCES - several sources can be defined ## +## ## +############################################################################### +############################################################################### + +#add calibration source +#calibrationSource=MuonCalib__CalibrationSourceConfig(<site mame>, <head id>) +#<site name> is "MP", "RM" or "UM" for Munich, Rome or Michigan + +calibrationSource=MuonCalib__CalibrationSourceConfig("MP", 22) + +#calibrationSource.Region = "" +#calibrationSource.StoreRt = True +#calibrationSource.StoreT0 = True +#calibrationSource.T0Offset = 0.0 +calibrationSource.TimeSlewingApplied = True +calibrationSource.BFieldCorrectionApplied = True + + +#calibrationSource2=MuonCalib__CalibrationSourceConfig("RM", 22) + +#calibrationSource2.Region = "" +#calibrationSource2.StoreRt = True +#calibrationSource2.StoreT0 = True +#calibrationSource2.T0Offset = 0.0 +#calibrationSource2.TimeSlewingApplied = True +#calibrationSource2.BFieldCorrectionApplied = True + +############################################################################### +############################################################################### +## ## +## DEFAULT CALIBRATION SOURCES ## +## ## +############################################################################### +############################################################################### + +#MuonCalib_gCalibrationDefaultSourceConfig.AddDefaultT0("[E??]", 500) + +#MuonCalib_gCalibrationDefaultSourceConfig.AddDefaultT0("[B??]", 600) + +#MuonCalib_gCalibrationDefaultSourceConfig.AddDefaultRt("", "Rt_BML_2_2.dat") + +############################################################################### +############################################################################### +## ## +## CALIBRATION TARGET FOLDERS - several targets can be defined ## +## ## +############################################################################### +############################################################################### + +#target folder=MuonCalib__CalibrationTargetConfig(<folder type>) +#folder type is "T0" or "RT" +target_folder_t0=MuonCalib__CalibrationTargetConfig("T0") + +#target_folder_t0.Folder = "/MDT/T0" +#target_folder_t0.Tag = None +#target_folder_t0.Compress = False + +target_folder_rt=MuonCalib__CalibrationTargetConfig("RT") + +#target_folder_rt.Folder = "/MDT/RT" +#target_folder_rt.Tag = None +#target_folder_rt.Compress = False + + +target_folder_t0_blob=MuonCalib__CalibrationTargetConfig("T0") +target_folder_t0_blob.Folder = "/MDT/T0BLOB" +#target_folder_t0_blob.Tag = None +target_folder_t0_blob.Compress = True + +target_folder_rt_blob=MuonCalib__CalibrationTargetConfig("RT") +target_folder_rt_blob.Folder = "/MDT/RTBLOB" +#target_folder_rt_blob.Tag = None +target_folder_rt_blob.Compress = True + + +#target_folder_t0_onl=MuonCalib__CalibrationTargetConfig("T0") +#target_folder_t0.Folder = "/MDT/Onl/T0" +#target_folder_t0.Tag = None +#target_folder_t0.Compress = False + +#target_folder_rt_onl=MuonCalib__CalibrationTargetConfig("RT") +#target_folder_rt.Folder = "/MDT/Onl/RT" +#target_folder_rt.Tag = None +#target_folder_rt.Compress = False + + +################################################################################ +################################################################################ +################################################################################ +################################################################################ + + +include("MuonCalibDbOperations/copy_to_cool_configurator.py") diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_configurator.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_configurator.py new file mode 100644 index 0000000000000..08b9c63b24e72 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_configurator.py @@ -0,0 +1,101 @@ +import os + +appendToExistingFile_flag=False +if "appendToExistingFile" in dir(): + appendToExistingFile_flag = appendToExistingFile + +if os.path.exists(coolFileName) and not appendToExistingFile_flag: + print "FATAL File", coolFileName, "already exists" + print "FATAL remove file or set 'appendToExistingFile = True'" + sys.exit(1) + + + +### Setup Athena common flags +#include ("AthenaCommon/AthenaCommonFlags.py") +#include.block("AthenaCommon/AthenaCommonFlags.py") + +#include( "IOVDbSvc/IOVRecExCommon.py" ) + +doMuonCalibAtlas=True + + +from AthenaCommon.AppMgr import ServiceMgr, ToolSvc +from AthenaCommon.GlobalFlags import globalflags +globalflags.DetGeo.set_Value_and_Lock('atlas') +ToolSvc = Service( "ToolSvc" ) +globalflags.DataSource.set_Value_and_Lock('data') +#globalflags.Print() +from AthenaCommon.DetFlags import DetFlags +DetFlags.detdescr.Muon_setOn() +DetFlags.detdescr.ID_setOff() +DetFlags.detdescr.LAr_setOff() +DetFlags.detdescr.Tile_setOff() +DetFlags.Print() + +from AtlasGeoModel import SetGeometryVersion, GeoModelInit +GeoModelSvc = ServiceMgr.GeoModelSvc +if "atlasVersion" in dir(): + GeoModelSvc.AtlasVersion = atlasVersion + + +from MuonCalibDbOperations.MuonCalibDbOperationsConf import MuonCalib__CoolInserter, MuonCalib__MuonCalibDbCalibrationSource, MuonCalib__MuonCalibDefaultCalibrationSource +CoolInserter=MuonCalib__CoolInserter() +from AthenaCommon.AlgSequence import AlgSequence +topSequence = AlgSequence() +topSequence += CoolInserter + + +#cheat athena event loop +theApp.EvtMax = 1 + +from MuonCalibStandAloneBase.MuonCalibStandAloneBaseConf import RegionSelectionSvc +RegionSelectionSvc = RegionSelectionSvc() +RegionSelectionSvc.PrintList = True +ServiceMgr += RegionSelectionSvc + +from MuonCalibDbOperations.CalibrationSourceConfig import * +from MuonCalibDbOperations.CalibrationTargetFolderConfig import * +from MuonCalibDbOperations.genGasmonSource import * +from MuonCalibDbOperations.CalibrationDefaultSourceConfig import * +import cx_Oracle + + +if autoFillGasmon: + reader_connection=cx_Oracle.connect("ATLAS_MUONCALIB_READER", readerPassword, "ATLAS_MUON") + reader_cursor=reader_connection.cursor() + gasmon_source=MuonCalib__genGasmonSource(toroidOn, calibrationTime, reader_cursor) + if "GasmonDriftTimeOffsetsVsR" in dir(): + gasmon_source.DriftTimeOffsetsVsR=GasmonDriftTimeOffsetsVsR + gasmon_source.BFieldCorrectionApplied = not toroidOn + gasmon_source.TimeSlewingApplied = False + + +for source_config in MuonCalib__gCalibrationSourceConfigs: + MuonCalibDbCalibrationSource = source_config.GenCalibrationSource(readerPassword) + ToolSvc += MuonCalibDbCalibrationSource + CoolInserter.CalibrationSources.append(MuonCalibDbCalibrationSource) + print MuonCalibDbCalibrationSource + +MuonCalib_gCalibrationDefaultSourceConfig.ConfigureTool(ToolSvc, CoolInserter) + +dbname="COMP200" +if "isMC" in dir(): + if isMC: + dbname="OFLP200" + +CoolInserter.CoolConnectionString = "sqlite://;schema=" + coolFileName + ";dbname="+dbname + +for target_config in MuonCalib__gCalibrationTargetConfigs: + if globalConditionsTag: + target_config.ResolveGlobalTag(globalConditionsTag) + target_config.AddToCoolInserter(CoolInserter) +if not regionToInsert: + regionToInsert="" + +RegionSelectionSvc.Region = regionToInsert + +CoolInserter.IOVStart=targetIov[0] +CoolInserter.IOVEnd=targetIov[1] + +print CoolInserter diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_old.py b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_old.py new file mode 100644 index 0000000000000..35cec2171c776 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/share/copy_to_cool_old.py @@ -0,0 +1,135 @@ +### Setup Athena common flags +include ("AthenaCommon/AthenaCommonFlags.py") +include.block("AthenaCommon/AthenaCommonFlags.py") + +include( "IOVDbSvc/IOVRecExCommon.py" ) + +doMuonCalibAtlas=True + + +from AthenaCommon.AppMgr import ServiceMgr, ToolSvc +from AthenaCommon.GlobalFlags import GlobalFlags +GlobalFlags.DetGeo.set_atlas() +ToolSvc = Service( "ToolSvc" ) +GlobalFlags.DataSource.set_data() +GlobalFlags.Print() +from AthenaCommon.DetFlags import DetFlags +DetFlags.detdescr.Muon_setOn() +DetFlags.detdescr.ID_setOff() +DetFlags.detdescr.LAr_setOff() +DetFlags.detdescr.Tile_setOff() +DetFlags.Print() + +from AtlasGeoModel import SetGeometryVersion, GeoModelInit +GeoModelSvc = ServiceMgr.GeoModelSvc +GeoModelSvc.AtlasVersion = "ATLAS-GEO-08-00-00" + + +from MuonCalibDbOperations.MuonCalibDbOperationsConf import MuonCalib__CoolInserter, MuonCalib__MuonCalibDbCalibrationSource, MuonCalib__MuonCalibDefaultCalibrationSource +CoolInserter=MuonCalib__CoolInserter() +from AthenaCommon.AlgSequence import AlgSequence +topSequence = AlgSequence() +topSequence += CoolInserter + + +#cheat athena event loop +theApp.EvtMax = 1 + +from MuonCalibStandAloneBase.MuonCalibStandAloneBaseConf import RegionSelectionSvc +RegionSelectionSvc = RegionSelectionSvc() +RegionSelectionSvc.PrintList = True +ServiceMgr += RegionSelectionSvc + + + + + +################################################################################ +################################################################################ +## START OF USER SETTINGS ## +################################################################################ +################################################################################ + + +################################################################################ +#select calibration sources +################################################################################ + +CalibrationDatabase=True +DefaultValues=False + +################################################################################ +#parameters of calibration database connection +################################################################################ + +if CalibrationDatabase: + MuonCalibDbCalibrationSource = MuonCalib__MuonCalibDbCalibrationSource() + ToolSvc += MuonCalibDbCalibrationSource + CoolInserter.CalibrationSources.append( MuonCalibDbCalibrationSource ) + + MuonCalibDbCalibrationSource.ConnectionString = "oracle://INTR/ATLAS_MUONCALIB_READER" +#select ROME/MUNICH/MICHIGAN + MuonCalibDbCalibrationSource.WorkingSchema = "ATLAS_MUONCALIB_MPI_META" +# MuonCalibDbCalibrationSource.WorkingSchema = "ATLAS_MUONCALIB_RM_META" +# MuonCalibDbCalibrationSource.WorkingSchema = "ATLAS_MUONCALIB_UM_META" + MuonCalibDbCalibrationSource.UserName = "ATLAS_MUONCALIB_READER" + MuonCalibDbCalibrationSource.Password = "XXXXXXX" + MuonCalibDbCalibrationSource.SiteName = "MP" + MuonCalibDbCalibrationSource.HeadId = 109 + MuonCalibDbCalibrationSource.Region = "[B??]" + + MuonCalibDbCalibrationSource.StoreRT=True + MuonCalibDbCalibrationSource.StoreT0=True + + + print MuonCalibDbCalibrationSource + +################################################################################ +# parameters for default values +################################################################################ + +if DefaultValues: + MuonCalibDefaultCalibrationSource = MuonCalib__MuonCalibDefaultCalibrationSource() + ToolSvc += MuonCalibDefaultCalibrationSource + CoolInserter.CalibrationSources.append( MuonCalibDefaultCalibrationSource ) + +#endcap chambes + MuonCalibDefaultCalibrationSource.T0Regions += [ "[E??]" ] + MuonCalibDefaultCalibrationSource.T0 += [ 500 ] +#barrel chambers + MuonCalibDefaultCalibrationSource.T0Regions += [ "[B??]" ] + MuonCalibDefaultCalibrationSource.T0 += [ 600 ] +#rt regon + MuonCalibDefaultCalibrationSource.RtRegions += [ "" ] + MuonCalibDefaultCalibrationSource.RtFiles += [ "Rt_BML_2_2.dat" ] + print MuonCalibDefaultCalibrationSource + + +################################################################################ +#parameters for cool database +################################################################################ + +CoolInserter.CoolConnectionString = "sqlite://;schema=test.db;dbname=COMP200" +#online folders + +CoolInserter.T0Folder += [ "/MDT/T0" ] +CoolInserter.T0Tag += [ "MDTT0_RPCwBeam-02" ] +CoolInserter.T0FolderCompress += [True] +CoolInserter.RtFolder += [ "/MDT/RT" ] +CoolInserter.RtTag += [ "MDTRT_RPCwBeam-02" ] +CoolInserter.RtFolderCompress += [True] + + +#if set to -1 the IOV from the header is used - IOV is inclusive +CoolInserter.IOVStart=-1 +CoolInserter.IOVEnd=-1 + + +################################################################################ +#replication options +################################################################################ + +#select region to replicate +RegionSelectionSvc.Region = "" + +print CoolInserter diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibDbConnection.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibDbConnection.cxx new file mode 100644 index 0000000000000..bcc546ce4f55f --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibDbConnection.cxx @@ -0,0 +1,243 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/CalibDbConnection.h" + +//coral +#include "RelationalAccess/IRelationalService.h" +#include "RelationalAccess/IConnection.h" +#include "RelationalAccess/IConnectionService.h" +#include "RelationalAccess/ISession.h" +#include "RelationalAccess/IRelationalDomain.h" +#include "RelationalAccess/ITransaction.h" +#include "RelationalAccess/IQuery.h" +#include "RelationalAccess/ISchema.h" +#include "RelationalAccess/ICursor.h" +#include "RelationalAccess/ITable.h" +#include "RelationalAccess/ITableDataEditor.h" +#include "RelationalAccess/IAuthenticationService.h" +#include "RelationalAccess/IAuthenticationCredentials.h" +#include "RelationalAccess/SchemaException.h" +#include "CoralBase/AttributeList.h" +#include "CoralBase/Attribute.h" +#include "CoralBase/AttributeSpecification.h" +#include "CoralKernel/Context.h" + + +// c- c++ +#include <stdexcept> +#include "iostream" + +namespace MuonCalib{ + +///////////////// +// Constructor // +///////////////// + +CalibDbConnection::CalibDbConnection(const std::string& ConnectionString, const std::string& WorkingSchema): m_connection_string(ConnectionString), m_working_schema(WorkingSchema), m_comp_loaded(false), m_context( &coral::Context::instance() ), m_connection(NULL), m_session(NULL), m_transaction(false) + { + std::cout<<"X"<<std::endl; + coral::IHandle<coral::IConnectionService> lookSvcH = m_context->query<coral::IConnectionService>(); + std::cout<<"XX"<<std::endl; + if (!lookSvcH.isValid()) + { + std::cout<<"XX"<<std::endl; + m_context->loadComponent( "CORAL/Services/ConnectionService" ); + lookSvcH = m_context->query<coral::IConnectionService>(); + std::cout<<"XX"<<std::endl; + } + if (!lookSvcH.isValid()) + { + return; + } + std::cout<<"Y"<<std::endl; + m_context->loadComponent( "CORAL/Services/XMLAuthenticationService" ); + std::cout<<"YY"<<std::endl; + m_context->loadComponent( "CORAL/Services/RelationalService" ); + std::cout<<"YYY"<<std::endl; + m_comp_loaded=true; + m_connection=NULL; + } + + +CalibDbConnection::~CalibDbConnection() + { + CloseConnection(); + } + + +//////////////////// +// OpenConnection // +//////////////////// + +bool CalibDbConnection::OpenConnection() + { + if(!m_comp_loaded) + { + return false; + } + if (m_connection!=NULL) + { + return true; + } + try { + coral::IRelationalDomain &domain = this->domain( m_connection_string); + std::pair<std::string,std::string> cstr(domain.decodeUserConnectionString(m_connection_string)); + m_connection=domain.newConnection(cstr.first); + m_connection->connect(); + m_session=m_connection->newSession(cstr.second); + m_session->startUserSession(m_username,m_password); + return true; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + m_connection=NULL; + return false; + } + } + + +///////////////////// +// CloseConnection // +///////////////////// + +void CalibDbConnection::CloseConnection(bool commit) + { + for(std::set<coral::IQuery*>::iterator it=m_queries.begin(); it!=m_queries.end(); it++) + { + if(*it) + delete (*it); + } + m_queries.clear(); + if(m_session != NULL) + { + if(commit) + Commit(); + else + Rollback(); + m_session->endUserSession(); + } + if (m_connection !=NULL) + m_connection->disconnect(); + m_session=NULL; + m_connection=NULL; + } + + +///////////////////// +// OpenTransaction // +///////////////////// + +void CalibDbConnection :: OpenTransaction() + { + if(!m_transaction) + { + m_session->transaction().start(); + m_transaction=true; + } + } + + +//////////// +// Commit // +//////////// + +void CalibDbConnection :: Commit() + { + if(m_transaction) + { + m_session->transaction().commit(); + m_transaction=false; + } + } + + +////////////// +// Rollback // +////////////// + +void CalibDbConnection :: Rollback() + { + if(m_transaction) + { + m_session->transaction().rollback(); + m_transaction=false; + } + } + + +//////////////////// +// GetTableEditor // +//////////////////// + +coral::ITableDataEditor& CalibDbConnection :: GetTableEditor(const std::string & table_name) + { + return m_session->schema( m_working_schema ).tableHandle(table_name).dataEditor(); + } + + +////////////// +// GetQuery // +////////////// + +coral::IQuery* CalibDbConnection :: GetQuery() + { + if(m_session==NULL) + { + std::cerr<<"No Session open!"<<std::endl; + return NULL; + } + std::cout<<m_connection_string<<" "<<m_working_schema<<std::endl; + coral::ISchema& workingSchema = m_session->schema( m_working_schema ); + coral::IQuery* query = workingSchema.newQuery(); + m_queries.insert(query); + return query; + } + +////////////// +// GetQuery // +////////////// + +void CalibDbConnection :: DestroyQuery(coral::IQuery *query) + { + std::set<coral::IQuery*> :: iterator it=m_queries.find(query); + if(it==m_queries.end()) + { + return; + } + m_queries.erase(it); + delete query; + } + +coral::IRelationalDomain& +CalibDbConnection::domain( const std::string& connectionString ) + { + coral::IHandle<coral::IRelationalService> relationalService= m_context->query<coral::IRelationalService>(); + if ( !relationalService.isValid() ) + { + throw std::runtime_error( "Could not locate the relational service" ); + } + + coral::IHandle<coral::IAuthenticationService> authenticationService= m_context->query<coral::IAuthenticationService>(); + if ( !authenticationService.isValid() ) + { + throw std::runtime_error( "Could not locate the authentication service" ); + } + if(m_username=="") + { + const coral::IAuthenticationCredentials& credentials = authenticationService->credentials( connectionString ); + m_username = credentials.valueForItem( "user" ); + m_password = credentials.valueForItem( "password" ); + } + if(m_target_user!="" && m_target_user!=m_username) + { + m_username = m_username + "[" + m_target_user + "]"; + } + return relationalService->domainForConnection( connectionString ); + } + + +}//namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibHeadOperations.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibHeadOperations.cxx new file mode 100644 index 0000000000000..26ffc7ca9eabf --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibHeadOperations.cxx @@ -0,0 +1,175 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/CalibHeadOperations.h" +#include "MuonCalibDbOperations/CalibDbConnection.h" + +//coral +#include "RelationalAccess/IRelationalService.h" +#include "RelationalAccess/IConnection.h" +#include "RelationalAccess/IConnectionService.h" +#include "RelationalAccess/ISession.h" +#include "RelationalAccess/IRelationalDomain.h" +#include "RelationalAccess/ITransaction.h" +#include "RelationalAccess/IQuery.h" +#include "RelationalAccess/ISchema.h" +#include "RelationalAccess/ICursor.h" +#include "RelationalAccess/ITable.h" +#include "RelationalAccess/IAuthenticationService.h" +#include "RelationalAccess/IAuthenticationCredentials.h" +#include "RelationalAccess/SchemaException.h" +#include "CoralBase/AttributeList.h" +#include "CoralBase/Attribute.h" +#include "CoralBase/AttributeSpecification.h" +#include "CoralKernel/Context.h" + +//c - c+++ +#include "iostream" + + +namespace MuonCalib { + + +CalibHeadOperations :: CalibHeadOperations(CalibDbConnection & db_conn) : m_meta_connection(&db_conn) + { + } + + +int CalibHeadOperations :: GetLatestHeadId() const + { + try + { + m_meta_connection->OpenTransaction(); + coral::IQuery * query=m_meta_connection->GetQuery(); + query->setRowCacheSize(1); + query->addToTableList("MDT_HEAD"); + query->addToOutputList("max(HEAD_ID)", "max_head_id"); + coral::ICursor& cursor = query->execute(); + if(!cursor.next()) + { + std::cerr<<"Query for head_id failed!"<<std::endl; + return -1; + } + const coral::AttributeList & al= cursor.currentRow(); + return static_cast<int>(al["max_head_id"].data<double>()); + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + return -1; + } + } + + +bool CalibHeadOperations :: GetHeadInfo(int &head_id, int & lowrun, int &uprun, int &lowtime, int &uptime) + { + if(head_id<0) + { + head_id=GetLatestHeadId(); + } + if(head_id<0) + { + std::cerr<<"CalibHeadOperations :: GetHeadInfo: Cannot get latest head id"<<std::endl; + return -1; + } + try + { + m_meta_connection->OpenTransaction(); + coral::IQuery * query=m_meta_connection->GetQuery(); + query->addToTableList("MDT_HEAD"); + query->addToOutputList("LOWRUN"); + query->addToOutputList("UPRUN"); + query->addToOutputList("LOWTIME"); + query->addToOutputList("UPTIME"); + std::string condition = "HEAD_ID=:hid"; + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData["hid"].data<int>()=head_id; + query->setCondition( condition, conditionData ); + coral::ICursor& cursor = query->execute(); + if(!cursor.next()) + { + std::cerr<<"No information about head_id="<<head_id<<" found!"<<std::endl; + return false; + } + const coral::AttributeList & al= cursor.currentRow(); + lowrun=al["LOWRUN"].data<int>(); + uprun=al["UPRUN"].data<int>(); + lowtime=al["LOWTIME"].data<int>(); + uptime=al["UPTIME"].data<int>(); + return true; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + return false; + } + + } + + + +CalibDbConnection * CalibHeadOperations :: GetDataConnection(int head_id, bool write, const std::string & writer_connection, const std::string & writer_user, const std::string & writer_password) + { + if (head_id<0) + { + head_id = GetLatestHeadId(); + } + if (head_id<0) + return NULL; + try + { + m_meta_connection->OpenTransaction(); + coral::IQuery * query=m_meta_connection->GetQuery(); + query->setRowCacheSize(1); + query->addToTableList("MDT_HEAD"); + query->addToTableList("MDT_DATA_SCHEMA"); + query->addToOutputList("MDT_DATA_SCHEMA.SCHEMA_NAME", "SCHEMA"); + query->addToOutputList("MDT_DATA_SCHEMA.WRITER_ACCOUNT", "WRITER_ACCOUNT"); + query->addToOutputList("MDT_DATA_SCHEMA.ACTIVE", "ACTIVE"); + query->addToOutputList("MDT_DATA_SCHEMA.ARCHIVED", "ARCHIVED"); + query->addToOutputList( "MDT_DATA_SCHEMA.ARCHIVE_CONNECTION_STRING", "ARCHIVE_CONNECTION_STRING"); + std::string condition = "MDT_HEAD.DATA_SCHEMA=MDT_DATA_SCHEMA.SCHEMA_NAME and MDT_HEAD.HEAD_ID=:hid"; + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData["hid"].data<int>()=head_id; + query->setCondition( condition, conditionData ); + coral::ICursor& cursor = query->execute(); + if(!cursor.next()) + { + std::cerr<<"No information about head_id="<<head_id<<" found!"<<std::endl; + return NULL; + } + const coral::AttributeList & al= cursor.currentRow(); + if(write && !al["ACTIVE"].data<bool>()) + { + std::cerr<<"Can only write to the active schema"<<std::endl; + return NULL; + } + if(al["ARCHIVED"].data<bool>()) + { + return new CalibDbConnection(al["ARCHIVE_CONNECTION_STRING"].data<std::string>(), al["SCHEMA"].data<std::string>()); + } + if(!write) + { + CalibDbConnection *conn=new CalibDbConnection(m_meta_connection->GetConnectionString(), al["SCHEMA"].data<std::string>()); + std::string user, passwd; + m_meta_connection->GetLogin(user, passwd); + conn->SetLogin(user, passwd); + return conn; + } + CalibDbConnection *ret= new CalibDbConnection(writer_connection, al["SCHEMA"].data<std::string>()); + ret->SetTargetUser(al["WRITER_ACCOUNT"].data<std::string>()); + ret->SetLogin(writer_user, writer_password); + return ret; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + return NULL; + } + } + +}// namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibRtDbOperations.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibRtDbOperations.cxx new file mode 100644 index 0000000000000..5bb53ed4147de --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibRtDbOperations.cxx @@ -0,0 +1,648 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/CalibRtDbOperations.h" +#include "MuonCalibDbOperations/CalibDbConnection.h" +#include "MuonCalibDbOperations/IConditionsStorage.h" + + +//MuonCalibStandAloneBase +#include "MuonCalibStandAloneBase/NtupleStationId.h" +#include "MuonCalibStandAloneBase/MdtStationT0Container.h" + +//MdtCalibData +#include "MdtCalibData/RtFullInfo.h" + +//MuonCalibMath +#include "MuonCalibMath/SamplePoint.h" + +//coral +#include "RelationalAccess/IRelationalService.h" +#include "RelationalAccess/IConnection.h" +#include "RelationalAccess/IConnectionService.h" +#include "RelationalAccess/ISession.h" +#include "RelationalAccess/IRelationalDomain.h" +#include "RelationalAccess/ITransaction.h" +#include "RelationalAccess/IQuery.h" +#include "RelationalAccess/ISchema.h" +#include "RelationalAccess/ICursor.h" +#include "RelationalAccess/ITable.h" +#include "RelationalAccess/ITableDataEditor.h" +#include "RelationalAccess/IAuthenticationService.h" +#include "RelationalAccess/IAuthenticationCredentials.h" +#include "RelationalAccess/SchemaException.h" +#include "RelationalAccess/IBulkOperation.h" +#include "CoralBase/AttributeList.h" +#include "CoralBase/Attribute.h" +#include "CoralBase/AttributeSpecification.h" +#include "CoralKernel/Context.h" + +//c - c++ +#include "sstream" +#include "string" +#include "cmath" + + +namespace MuonCalib { + + +CalibRtDbOperations :: CalibRtDbOperations(CalibDbConnection & db_conn) : m_db_conn(db_conn), m_rt_id(-1), m_rt_map_t_id(-1), m_head_id(-1), m_region_id(-1), m_n_points(0) + { + m_query=NULL; + } + +CalibRtDbOperations :: ~CalibRtDbOperations() + { + } + + +bool CalibRtDbOperations ::LoadRt(const NtupleStationId & id, int head_id, bool validated, const std::string & /*site_name*/, std::vector<SamplePoint> & points, RtFullInfo * full_info) + { + m_head_id=head_id; + m_region_id=id.FixedId(); + std::cout<<"CalibRtDbOperations ::LoadRt: "<<head_id<<" "<<id.FixedId()<<std::endl; + try + { + points.clear(); + m_db_conn.OpenTransaction(); + m_rt_id=-1; + if(!getRtId(validated, full_info)) + { + std::cerr<<"Header query failed!"<<std::endl; + m_db_conn.Rollback(); + return false; + } + if (m_rt_id<0) + { + m_db_conn.Rollback(); + return false; + } + if(!readRTS(points)) + { + m_db_conn.Rollback(); + return false; + } + return true; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + return false; + } + } + + + +bool CalibRtDbOperations :: WriteUpdateRt(const NtupleStationId & id, int head_id, const std::string & /*site_name*/, const std::vector<SamplePoint> & points, int validflag, const RtFullInfo * full_info) + { + m_prev_algs=""; + m_head_id=head_id; + m_region_id=id.FixedId(); + try + { + m_db_conn.OpenTransaction(); + if(!getRtId((validflag>1), NULL)) + { + m_db_conn.Rollback(); + std::cerr<<"Questing RT header failed!"<<std::endl; + return false; + } + if(m_rt_id>=0) + { + if(!updateFullInfo(full_info, validflag, static_cast<int>(points.size()))) + { + std::cout<<"Failed update header"<<std::endl; + m_db_conn.Rollback(); + return false; + } + if(!updateRTSable(points)) + { + m_db_conn.Rollback(); + return false; + } + + } + else + { + std::cout<<"fill"<<std::endl; + if(!insertFullInfo(full_info, validflag, static_cast<int>(points.size()))) + { + std::cout<<"Failed update header"<<std::endl; + m_db_conn.Rollback(); + return false; + } + if(!insertRTSable(points)) + { + m_db_conn.Rollback(); + return false; + } + + } + std::cout<<"filled"<<std::endl; + m_db_conn.Commit(); + return true; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + m_db_conn.Rollback(); + return false; + } + + } + + +bool CalibRtDbOperations :: SetValidflag(int validflag, bool commit) + { + if(m_rt_id<0) + { + std::cerr<<"No current rt!"<<std::endl; + return false; + } + try + { + m_db_conn.OpenTransaction(); + coral::ITableDataEditor & editor=m_db_conn.GetTableEditor("MDT_RT"); + std::string updateAction = "VALIDFLAG=:val"; + std::string updateCondition = "HEAD_ID=:hid and REGION_ID=:rid and CALIBFLAG=:rtid"; + coral::AttributeList updateData; + updateData.extend<int>("val"); + updateData[0].data<int>()=validflag; + updateData.extend<int>("rtid"); + updateData["rtid"].data<int>()=m_rt_id; + updateData.extend<int>("hid"); + updateData["hid"].data<int>()=m_head_id; + updateData.extend<int>("rid"); + updateData["rid"].data<int>()=m_region_id; + + std::cout<<m_head_id<<" "<<m_region_id<<" "<<m_rt_id<<std::endl; + int n_rows=editor.updateRows( updateAction, updateCondition, updateData ); + if(n_rows!=1) + { + std::cerr<<"Invalid number of rows updated in MDT_RT! "<<n_rows<<" instead of 1"<<std::endl; + m_db_conn.Rollback(); + return false; + } + if(commit) + m_db_conn.Commit(); + return true; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + m_db_conn.Rollback(); + return false; + } + } + + +bool CalibRtDbOperations :: ReadForConditions(std::string /*site_name*/, int head_id, IConditionsStorage & storage) + { + try + { + m_db_conn.OpenTransaction(); + m_query=m_db_conn.GetQuery(); + m_query->addToTableList("MDT_RT"); + m_query->addToTableList("MDT_RT_MAP"); + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData[0].data<int>()=head_id; + std::string condition = "MDT_RT.HEAD_ID=:hid and MDT_RT_MAP.HEAD_ID=:hid and MDT_RT.REGION_ID = MDT_RT_MAP.REGION_ID and MDT_RT.CALIBFLAG = MDT_RT_MAP.CALIBFLAG and MDT_RT.VALIDFLAG>1"; + m_query->setCondition( condition, conditionData ); + m_query->addToOrderList( "MDT_RT.REGION_ID" ); + m_query->addToOutputList("MDT_RT.REGION_ID", "REGION_ID"); + m_query->addToOutputList("MDT_RT_MAP.POINT_NR", "POINT_NR"); + m_query->addToOutputList("MDT_RT_MAP.T", "T"); + m_query->addToOutputList("MDT_RT_MAP.R", "R"); + m_query->addToOutputList("MDT_RT_MAP.S", "S"); + m_query->setRowCacheSize(100000); + //execute query + int last_region_id(-1); + std::map<int, SamplePoint> points; + coral::ICursor& cursor = m_query->execute(); + while (cursor.next()) + { + const coral::AttributeList & al= cursor.currentRow(); + int rt_id=static_cast<int>(al["REGION_ID"].data<float>()); + if(last_region_id>0 && rt_id!=last_region_id) + { + if(!storage.StoreRtChamber(last_region_id, points)) + { + std::cerr<<"Storage_failed"<<std::endl; + return false; + } + points.clear(); + } + last_region_id=rt_id; + SamplePoint pt(al["T"].data<float>(), al["R"].data<float>(), al["S"].data<float>()); + points[static_cast<int>(al["POINT_NR"].data<short>())] = pt; + } + if(last_region_id>0) + if(!storage.StoreRtChamber(last_region_id, points)) + { + std::cerr<<"Storage_failed"<<std::endl; + return false; + } + return true; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + m_db_conn.Rollback(); + return false; + } + } + + +bool CalibRtDbOperations :: getRtId(bool validated, RtFullInfo * full_info) + { + std::cout<<"CalibRtDbOperations :: getRtId"<<std::endl; +//select MDT_RT, ... from MDT_RT where head_id=:hid and site_name=:sn and region_id=:rid and [and validflag>0| and validflag=0] + m_query=m_db_conn.GetQuery(); + m_query->addToTableList("MDT_RT"); + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData[0].data<int>()=m_head_id; + conditionData.extend<int>("rid"); + conditionData[1].data<int>()=m_region_id; + m_prev_algs = ""; + std::string condition = "HEAD_ID=:hid and REGION_ID=:rid"; + if (validated) + { + condition += " and VALIDFLAG>1"; + } + else + { + condition += " and VALIDFLAG=0"; + } + m_query->setCondition( condition, conditionData ); + m_query->addToOutputList("CALIBFLAG"); + m_query->addToOutputList("BINS"); + m_query->addToOutputList("ALGO_FLAG"); + if(full_info!=NULL) + { + m_query->addToOutputList("N_SEGS"); + m_query->addToOutputList("AVER_ANGLE"); + m_query->addToOutputList("DELTA_AVER_ANGLE"); + m_query->addToOutputList("AVER_SPREAD"); + m_query->addToOutputList("DELTA_AVER_SPREAD"); + m_query->addToOutputList("CONVERGENCE"); + m_query->addToOutputList("B_AVER"); + m_query->addToOutputList("T_AVER"); + } + coral::ICursor& cursor = m_query->execute(); + int n_rows=0; + m_rt_id=-9999; + while (cursor.next()) + { + n_rows++; + const coral::AttributeList & al= cursor.currentRow(); + m_rt_id = al["CALIBFLAG"].data<short>(); + m_n_points = static_cast<int>(al["BINS"].data<short>()); + m_prev_algs = al["ALGO_FLAG"].data<std::string>(); + if(full_info!=NULL) + { + full_info->setNumSeg(static_cast<int>(al["N_SEGS"].data<int>())); + full_info->setMeanAng(al["AVER_ANGLE"] .data<float>()); + full_info->setRmsAng(al["DELTA_AVER_ANGLE"]. data<float>()); + full_info->setMeanPos(al["AVER_SPREAD"]. data<float>()); + full_info->setRmsPos(al["DELTA_AVER_SPREAD"]. data<float>()); + full_info->setConvEst(al["CONVERGENCE"].data<float>()); + full_info->setImplementation(m_prev_algs); + } + } + if(n_rows>1) + { + std::cerr<<"Fount "<<n_rows<<" in MDT_RT instead of 0 or 1"<<std::endl; + return false; + } + m_db_conn.DestroyQuery(m_query); + return true; + } + +inline bool CalibRtDbOperations ::readRTS(std::vector<SamplePoint> &points) + { + std::cout<<"CalibRtDbOperations ::readRTS"<<std::endl; + std::cout<<"m_n_points="<<m_n_points<<std::endl; + m_query=m_db_conn.GetQuery(); + m_query->addToTableList("MDT_RT_MAP"); + coral::AttributeList conditionData; + conditionData.extend<int>("rtid"); + conditionData[0].data<int>()=m_rt_id; + conditionData.extend<int>("hid"); + conditionData[1].data<int>()=m_head_id; + conditionData.extend<int>("rid"); + conditionData[2].data<int>()=m_region_id; + std::string condition = "HEAD_ID=:hid and REGION_ID=:rid and CALIBFLAG=:rtid"; + m_query->setCondition( condition, conditionData ); + m_query->addToOutputList("MDT_RT_MAP.POINT_NR", "POINT_NR"); + m_query->addToOutputList("MDT_RT_MAP.R", "R"); + m_query->addToOutputList("MDT_RT_MAP.T", "T"); + m_query->addToOutputList("MDT_RT_MAP.S", "S"); + m_query->addToOrderList("MDT_RT_MAP.POINT_NR"); + m_query->setRowCacheSize(100); + std::cout<<"m_n_points="<<m_n_points<<std::endl; + coral::ICursor& cursor = m_query->execute(); + points.clear(); + points.resize(m_n_points); + std::cout<<"m_n_points="<<m_n_points<<std::endl; + int count(0); + while (cursor.next()) + { + const coral::AttributeList & al= cursor.currentRow(); + int pt_nr(static_cast<int>(al["POINT_NR"].data<short>())); + if(pt_nr>=m_n_points) + { + std::cerr<<"Illegal point number "<<pt_nr<<std::endl; + return false; + } + SamplePoint point(al["T"].data<float>(), al["R"].data<float>(), al["S"].data<float>()); + points[pt_nr]=point; + count++; + } + if (count!=m_n_points) + { + std::cerr<<m_n_points<<" points expected, "<<count<<" found!"<<std::endl; + return false; + } + m_db_conn.DestroyQuery(m_query); + return true; + } + + +inline bool CalibRtDbOperations ::updateFullInfo(const RtFullInfo * full_info, const int & validflag, const int & n_points) + { + std::cout<<"CalibRtDbOperations :: updateFullInfo"<<std::endl; + coral::ITableDataEditor & editor=m_db_conn.GetTableEditor("MDT_RT"); + std::string updateAction = "N_SEGS = :N_SEGS, AVER_ANGLE = :AVER_ANGLE, DELTA_AVER_ANGLE = :DELTA_AVER_ANGLE, AVER_SPREAD = :AVER_SPREAD, DELTA_AVER_SPREAD = :DELTA_AVER_SPREAD, CONVERGENCE = :CONVERGENCE, VALIDFLAG=:VALIDFLAG, BINS=:BINS, ALGO_FLAG=:ALGO_FLAG"; + std::string updateCondition = "HEAD_ID=:hid and REGION_ID=:rid and CALIBFLAG=:rtid"; + coral::AttributeList updateData; + fullInfoInitData(full_info, validflag, updateData, n_points, false); + updateData.extend<int>("rtid"); + updateData["rtid"].data<int>()=m_rt_id; + updateData.extend<int>("hid"); + updateData["hid"].data<int>()=m_head_id; + updateData.extend<int>("rid"); + updateData["rid"].data<int>()=m_region_id; + if(editor.updateRows( updateAction, updateCondition, updateData )!=1) + { + std::cerr<<"Invalid number of rows updated in MDT_RT!"<<std::endl; + return false; + } + return true; + } + + +inline bool CalibRtDbOperations ::updateRTSable(const std::vector<SamplePoint> & points) + { + coral::ITableDataEditor & editor=m_db_conn.GetTableEditor("MDT_RT_MAP"); +//check if there are now less points than before + if(static_cast<int>(points.size())<m_n_points) + { + std::string deleteCondition = "HEAD_ID = :hid and REGION_ID=:rid and CALIBFLAG=:rtid and POINT_NR>=:max_point"; + coral::AttributeList deleteData; + deleteData.extend<int>( "hid" ); + deleteData[0].data<int>() = m_head_id; + deleteData.extend<int>( "rid" ); + deleteData[1].data<int>() = m_region_id; + deleteData.extend<int>( "rtid" ); + deleteData[2].data<int>() = m_rt_id; + deleteData.extend<int>( "max_point" ); + deleteData[3].data<int>() = static_cast<int>(points.size()); + long rowsDeleted = editor.deleteRows( deleteCondition, deleteData ); + if(rowsDeleted != m_n_points - static_cast<int>(points.size())) + { + std::cerr<<rowsDeleted<<" Points removed instead of "<< m_n_points - static_cast<int>(points.size())<<"! Rolling back!"<<std::endl; + return false; + } + } + coral::AttributeList table_data; + rtTableInitData(table_data); + table_data["CALIBFLAG"].data<int>()=m_rt_id; + table_data["HEAD_ID"].data<int>()=m_head_id; + table_data["REGION_ID"].data<int>()=m_region_id; + for(int i=0; i<static_cast<int>(points.size()); i++) + { + table_data["POINT_NR"].data<int>() = i; + table_data["T"].data<float>() = points[i].x1(); + table_data["R"].data<float>() = points[i].x2(); + table_data["S"].data<float>() = points[i].error(); + if(i<m_n_points) + { + std::string updateAction = "R=:R, T=:T, S=:S"; + std::string updateCondition = "CALIBFLAG=:CALIBFLAG and POINT_NR=:POINT_NR and HEAD_ID=:HEAD_ID and REGION_ID=:REGION_ID"; + if(editor.updateRows( updateAction, updateCondition, table_data)!=1) + { + std::cerr<<"Wrong number of points updated!"<<std::endl; + return false; + } + } + else + { + editor.insertRow(table_data); + } + } + return true; + } + + +inline bool CalibRtDbOperations ::insertFullInfo(const RtFullInfo * full_info, const int & validflag, const int & n_points) + { + std::cout<<"CalibRtDbOperations :: insertFullInfo"<<std::endl; + coral::ITableDataEditor & editor=m_db_conn.GetTableEditor("MDT_RT"); + coral::AttributeList rowBuffer; + fullInfoInitData(full_info, validflag, rowBuffer, n_points,true); + editor.insertRow( rowBuffer ); + return getRtId((validflag>1), NULL); + } + + +inline bool CalibRtDbOperations ::insertRTSable(const std::vector<SamplePoint> & points) + { + coral::ITableDataEditor & editor=m_db_conn.GetTableEditor("MDT_RT_MAP"); + coral::AttributeList table_data; + rtTableInitData(table_data); + table_data["CALIBFLAG"].data<int>()=m_rt_id; + table_data["HEAD_ID"].data<int>()=m_head_id; + table_data["REGION_ID"].data<int>()=m_region_id; + coral::IBulkOperation *bulk_inserter=editor.bulkInsert( table_data, 100); +//use trigger to fill in MDT_RT_ID + for(int i=0; i<static_cast<int>(points.size()); i++) + { + table_data["POINT_NR"].data<int>()=i; + table_data["T"].data<float>()=points[i].x1(); + table_data["R"].data<float>()=points[i].x2(); + table_data["S"].data<float>()=points[i].error(); + bulk_inserter->processNextIteration(); + } + bulk_inserter->flush(); + delete bulk_inserter; + return true; + } + +inline void CalibRtDbOperations :: fullInfoInitData( const RtFullInfo * full_info, const int & validflag, coral::AttributeList &updateData, const int & n_bins, const bool & for_insert) + { + std::cout<<"CalibRtDbOperations :: fullInfoInitData"<<std::endl; + if(for_insert) + { + updateData.extend<int>("REGION_ID"); + updateData["REGION_ID"].data<int>()=m_region_id; + updateData.extend<int>("HEAD_ID"); + updateData["HEAD_ID"].data<int>()=m_head_id; + updateData.extend<int>("LOWRUN"); + updateData["LOWRUN"].data<int>()=0; + updateData.extend<int>("UPRUN"); + updateData["UPRUN"].data<int>()=1; + updateData.extend<std::string>("HISTOGRAM"); + updateData["HISTOGRAM"].data<std::string>()="DUMMY"; + } + if(m_prev_algs!="") + { + m_prev_algs+=":"; + } + if(full_info->implementation()=="RtCalibrationIntegration") + { + m_prev_algs+="Int"; + } + else if (full_info->implementation()=="RtCalibrationCruved") + { + m_prev_algs+="Cur"; + } + else if (full_info->implementation()=="RtCalibrationAnalytic") + { + m_prev_algs+="Ana"; + } + else if (full_info->implementation()=="RtCalibrationAnalyticExt") + { + m_prev_algs+="AnaExt"; + } + else if (full_info->implementation()=="Validation") + { + m_prev_algs+="Val"; + } + else + { + std::cout<<"Unknown implementation '"<<full_info->implementation()<<"'!"<<std::endl; + m_prev_algs+="UU"; + } + if(m_prev_algs.size()>25) + { + std::cout<<"m_prev_algs exceeds size: "<<m_prev_algs<<std::endl; + m_prev_algs=".."; + } + updateData.extend<std::string>("ALGO_FLAG"); + updateData["ALGO_FLAG"].data<std::string>()=m_prev_algs; + updateData.extend<int>("N_SEGS"); + updateData["N_SEGS"].data<int>()=full_info->numSeg(); + updateData.extend<float>("AVER_ANGLE"); + updateData["AVER_ANGLE"].data<float>()=full_info->meanAng(); + if(std::fabs(full_info->meanAng()) > 9.9999) + { + updateData["AVER_ANGLE"].data<float>() = ((full_info->meanAng() < 0)? -1 : 1) * 9.9999; + } + updateData.extend<float>("DELTA_AVER_ANGLE"); + updateData["DELTA_AVER_ANGLE"].data<float>()=full_info->rmsAng(); + if(std::fabs(full_info->rmsAng()) > 9.9999) + { + updateData["DELTA_AVER_ANGLE"].data<float>() = ((full_info->rmsAng() < 0)? -1 : 1) * 9.9999; + } + updateData.extend<float>("AVER_SPREAD"); + updateData["AVER_SPREAD"].data<float>()=full_info->meanPos(); + if(std::fabs(full_info->meanPos()) > 9.9999) + { + updateData["AVER_SPREAD"].data<float>() = ((full_info->meanPos() < 0)? -1 : 1) * 9.9999; + } + updateData.extend<float>("DELTA_AVER_SPREAD"); + updateData["DELTA_AVER_SPREAD"].data<float>()=full_info->rmsPos(); + if(std::fabs(full_info->rmsPos()) > 9.9999) + { + updateData["DELTA_AVER_SPREAD"].data<float>() = ((full_info->rmsPos() < 0)? -1 : 1) * 9.9999; + } + updateData.extend<float>("CONVERGENCE"); + updateData["CONVERGENCE"].data<float>()=full_info->convEst(); + if(std::fabs(full_info->convEst()) > 999.999) + { + updateData["CONVERGENCE"].data<float>() = ((full_info->rmsPos() < 0)? -1 : 1) * 999.999; + } + if(for_insert) + { + updateData.extend<float>("B_AVER"); + updateData["B_AVER"].data<float>()=0.; + updateData.extend<float>("T_AVER"); + updateData["T_AVER"].data<float>()=0.; + updateData.extend<float>("HV"); + updateData["HV"].data<float>()=0.; + updateData.extend<float>("CURR"); + updateData["CURR"].data<float>()=0.; + updateData.extend<float>("GAS"); + updateData["GAS"].data<float>()=0.; + updateData.extend<int>("CALIBFLAG"); + updateData["CALIBFLAG"].data<int>() = static_cast<int>(validflag>3); + } + updateData.extend<int>("VALIDFLAG"); + updateData["VALIDFLAG"].data<int>()=validflag; + updateData.extend<short>("BINS"); + updateData["BINS"].data<short>()=n_bins; + } + + +inline void CalibRtDbOperations :: rtTableInitData(coral::AttributeList & rowBuffer) + { + rowBuffer.extend<int>("HEAD_ID"); + rowBuffer.extend<int>("REGION_ID"); + rowBuffer.extend<int>("CALIBFLAG"); + rowBuffer.extend<int>("POINT_NR"); + rowBuffer.extend<float>("T"); + rowBuffer.extend<float>("R"); + rowBuffer.extend<float>("S"); + } + + +inline bool CalibRtDbOperations :: checkRtPresent(const int & head_id, const std::string & /*site_name*/, const NtupleStationId & id, const int & validflag) + { + m_query=m_db_conn.GetQuery(); +//select count(MDT_RT.MDT_RT_ID) as N_TUBES, MDT_RT.VALIDFLAG as VALIDFLAG from MDT_RT where MDT_RT.HEAD_ID = :hid and MDT_RT.REGION_ID = :chamb and SITE_NAME=:sn group by MDT_RT.VALIDFLAG; + m_query->addToTableList("MDT_RT"); + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData[0].data<int>()=head_id; +//as long as the chamber id is stored as a string, it is more efficient to pass the chamber id as a string in the query + std::ostringstream ostr; + ostr<<id.FixedId(); + conditionData.extend<std::string>("chamb"); + conditionData[1].data<std::string>()=ostr.str(); + std::string condition = "MDT_RT.HEAD_ID = :hid and MDT_RT.REGION_ID = :chamb"; + m_query->setCondition( condition, conditionData ); + m_query->addToOutputList( "count(MDT_RT.CALIBFLAG)", "N_RTS"); + m_query->addToOutputList( "MDT_RT.VALIDFLAG", "VALIDFLAG" ); + m_query->groupBy("MDT_RT.VALIDFLAG"); + coral::ICursor& cursor = m_query->execute(); + bool has_unvalidated(false), has_validated(false); + while (cursor.next()) + { + const coral::AttributeList & al= cursor.currentRow(); + if(al["VALIDFLAG"].data<short>()>0) + { + if(al["N_RTS"].data<double>()>0) + { + has_validated=true; + } + } + else + { + if(al["N_RTS"].data<double>()>0) + { + has_unvalidated=true; + } + } + } + if (validflag==0 && has_unvalidated) return false; + if (validflag>0 && has_validated) return false; + return true; + } + + + +}//namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibT0DbOperations.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibT0DbOperations.cxx new file mode 100644 index 0000000000000..ecc43a6540d8b --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibT0DbOperations.cxx @@ -0,0 +1,717 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/CalibT0DbOperations.h" +#include "MuonCalibDbOperations/CalibDbConnection.h" +#include "MuonCalibDbOperations/IConditionsStorage.h" + +//MuonCalibStandAloneBase +#include "MuonCalibStandAloneBase/NtupleStationId.h" +#include "MuonCalibStandAloneBase/MdtStationT0Container.h" + +//MuonCalibIdentifier +#include "MuonCalibIdentifier/MuonFixedId.h" + +//MdtCalibData +#include "MdtCalibData/MdtTubeFitContainer.h" + +//coral +#include "RelationalAccess/IRelationalService.h" +#include "RelationalAccess/IConnection.h" +#include "RelationalAccess/IConnectionService.h" +#include "RelationalAccess/ISession.h" +#include "RelationalAccess/IRelationalDomain.h" +#include "RelationalAccess/ITransaction.h" +#include "RelationalAccess/IQuery.h" +#include "RelationalAccess/ISchema.h" +#include "RelationalAccess/ICursor.h" +#include "RelationalAccess/ITable.h" +#include "RelationalAccess/ITableDataEditor.h" +#include "RelationalAccess/IAuthenticationService.h" +#include "RelationalAccess/IAuthenticationCredentials.h" +#include "RelationalAccess/SchemaException.h" +#include "RelationalAccess/IBulkOperation.h" +#include "CoralBase/AttributeList.h" +#include "CoralBase/Attribute.h" +#include "CoralBase/AttributeSpecification.h" +#include "CoralKernel/Context.h" + +//c - c++ +#include "sstream" +#include "string" +#include "cmath" + +namespace MuonCalib { + +CalibT0DbOperations :: CalibT0DbOperations(CalibDbConnection & db_conn) : m_db_conn(db_conn), m_query(NULL) + { +// m_query=m_db_conn.GetQuery(); + } + + +CalibT0DbOperations :: ~CalibT0DbOperations() + { +// m_db_conn.DestroyQuery(m_query); + } + + +MdtStationT0Container * CalibT0DbOperations :: LoadT0Calibration(const NtupleStationId & id, int head_id, std::string & site_name) + { + std::cout<<"CalibT0DbOperations :: LoadT0Calibration"<<std::endl; + try + { +//slect MDT_TUBE.TUBE_ID, MDT_TUBE.P4 from MDT_TUBE where MDT_TUBE.HEAD_ID = :hid and MDT_TUBE.CHAMBER = :chamb and MDT_TUBE.VALIDFLAG>1 + m_db_conn.OpenTransaction(); + m_query=m_db_conn.GetQuery(); + m_query->setRowCacheSize(432); + m_query->addToTableList("MDT_TUBE"); + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData[0].data<int>()=head_id; +//as long as the chamber id is stored as a string, it is more efficient to pass the chamber id as a string in the query + conditionData.extend<int>("chamb"); + conditionData[1].data<int>()=id.FixedId(); + std::string condition = "MDT_TUBE.HEAD_ID = :hid and MDT_TUBE.CHAMBER = :chamb and MDT_TUBE.VALIDFLAG>1"; + m_query->setCondition( condition, conditionData ); + m_query->addToOutputList( "MDT_TUBE.TUBE_ID", "TUBE_ID" ); + m_query->addToOutputList( "MDT_TUBE.P4", "T0" ); + m_query->addToOutputList( "MDT_TUBE.ADC_1", "ADC_1" ); + coral::ICursor& cursor = m_query->execute(); + MdtStationT0Container *ret=new MdtStationT0Container(); + int count(0); + while (cursor.next()) + { + const coral::AttributeList & al= cursor.currentRow(); + MuonFixedId fid(al[0].data<int>()); + ret->Sett0(fid.mdtMultilayer(), fid.mdtTubeLayer(), fid.mdtTube(), al[1].data<float>(), al[2].data<float>()); + count++; + } + if(count==0) + { + std::cerr<<"No tubes found for "<<id.regionId()<<" Header "<<site_name<<head_id<<std::endl; + delete ret; + return NULL; + } + return ret; + }//try + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + return NULL; + } + } + + +MdtTubeFitContainer * CalibT0DbOperations :: LoadT0Validation(const NtupleStationId & id, int head_id, std::string &/*site_name*/) + { + std::cout<<"CalibT0DbOperations :: LoadT0Validation"<<std::endl; + try + { + m_db_conn.OpenTransaction(); + m_query=m_db_conn.GetQuery(); + m_query->setRowCacheSize(432); + m_query->addToTableList("MDT_TUBE"); + m_query->addToTableList("MDT_TUBE_V"); + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData[0].data<int>()=head_id; +//as long as the chamber id is stored as a string, it is more efficient to pass the chamber id as a string in the query + std::ostringstream ostr; + ostr<<id.FixedId(); + conditionData.extend<std::string>("chamb"); + conditionData[1].data<std::string>()=ostr.str(); + std::string condition = "MDT_TUBE.HEAD_ID = :hid and MDT_TUBE.CHAMBER = :chamb and MDT_TUBE.VALIDFLAG=0 and MDT_TUBE_V.HEAD_ID=:hid and MDT_TUBE_V.TUBE_ID = MDT_TUBE.TUBE_ID and MDT_TUBE_V.CALIBFLAG=MDT_TUBE.CALIBFLAG"; + m_query->setCondition( condition, conditionData ); + m_query->addToOutputList( "MDT_TUBE.TUBE_ID", "TUBE_ID" ); + m_query->addToOutputList( "MDT_TUBE.P4", "T0" ); + m_query->addToOutputList( "MDT_TUBE_V.ENTRIES", "ENTRIES"); + m_query->addToOutputList( "MDT_TUBE_V.CHISQUARE_1", "CHISQUARE_1"); + m_query->addToOutputList( "MDT_TUBE_V.CHISQUARE_2", "CHISQUARE_2"); + for(int i=0; i<7; i++) + { + std::ostringstream ostr; + if(i==4) + { + ostr<<"MDT_TUBE.P4"; + } + else + { + ostr<<"MDT_TUBE_V.P"<<i; + } + std::ostringstream ostr2; + ostr2<<"P"<<i; + m_query->addToOutputList( ostr.str(), ostr2.str() ); + if(i>3 && i<7) + { + if(i==4) + { + m_query->addToOutputList("MDT_TUBE_V.P4_ERR", "P4_ERR"); + } + else + { + ostr<<"_ERR"; + ostr2<<"_ERR"; + m_query->addToOutputList( ostr.str(), ostr2.str() ); + } + } + } + m_query->addToOutputList( "MDT_TUBE.NHITS", "NHITS"); + m_query->addToOutputList( "MDT_TUBE.NHITS_ABOVE_ADC_CUT", "NHITS_ABOVE_ADC_CUT"); + m_query->addToOutputList( "MDT_TUBE_V.ALGO_FLAG", "ALGO_FLAG"); + m_query->addToOutputList( "MDT_TUBE_V.TUBE_GROUPING", "TUBE_GROUPING"); + std::cout<<"Execute"<<std::endl; + coral::ICursor& cursor = m_query->execute(); + int n_tubes(0), n_layers(0), n_ml(0); + std::map<MuonFixedId, MdtTubeFitContainer::SingleTubeFit> fits; + std::map<MuonFixedId, MdtTubeFitContainer::SingleTubeCalib> calibs; + std::string alg_flg, tb_grp; + bool str_set(false); + while (cursor.next()) + { +// std::cout<<"."<<std::endl; + const coral::AttributeList & al= cursor.currentRow(); + MuonFixedId fid(al["TUBE_ID"].data<int>()); + MdtTubeFitContainer::SingleTubeCalib &calib(calibs[fid]); + calib.t0=al["P4"].data<float>(); + calib.adcCal=0; + MdtTubeFitContainer::SingleTubeFit &fit(fits[fid]); + fit.statistics = al["ENTRIES"].data<int>(); + fit.n_hits=al["NHITS"].data<int>(); + fit.n_hits_above_adc_cut = al["NHITS_ABOVE_ADC_CUT"].data<int>(); + fit.chi2Tdc=0.0; + fit.chi2TdcEnd=0.0; + for(int i=0; i<7; i++) + { + std::ostringstream ostr2; + ostr2<<"P"<<i; + fit.par[i]=al[ostr2.str()].data<float>(); + if(i>3 && i<7) + { + ostr2<<"_ERR"; + fit.cov[i]=al[ostr2.str()].data<float>(); + } + else + { + fit.cov[i]=0.0; + } + } + if(n_tubes<fid.mdtTube()) + n_tubes=fid.mdtTube(); + if(n_layers<fid.mdtTubeLayer()) + n_layers=fid.mdtTubeLayer(); + if(n_ml<fid.mdtMultilayer()) + n_ml=fid.mdtMultilayer(); + if(!str_set) + { + alg_flg=al["ALGO_FLAG"].data<std::string>(); + tb_grp=al["TUBE_GROUPING"].data<std::string>(); + str_set=true; + } + } + //create output class + MdtTubeFitContainer *ret=new MdtTubeFitContainer(id.regionId(), n_ml, n_layers, n_tubes); + for(std::map<MuonFixedId, MdtTubeFitContainer::SingleTubeFit> :: const_iterator it=fits.begin(); it!=fits.end(); it++) + { + int ml=it->first.mdtMultilayer()-1; + int ly=it->first.mdtTubeLayer()-1; + int tb=it->first.mdtTube()-1; + ret->setFit(ml, ly, tb, it->second); + ret->setCalib(ml, ly, tb, calibs[it->first]); + } + ret->setGroupBy(tb_grp); + ret->setImplementation(alg_flg); + return ret; + } //try + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + return NULL; + } + } + + + +bool CalibT0DbOperations :: WriteT0Chamber(const NtupleStationId & id, const MdtTubeFitContainer * t0, std::vector<int> & validation_flag, int head_id, const std::string & site_name) + { + std::cout<<"CalibT0DbOperations :: WriteT0Chamber"<<std::endl; + try + { + m_db_conn.OpenTransaction(); + if(!checkTubesPresent(head_id, site_name, id, validation_flag)) + { + std::cerr<<"Trying to insert data for chamber " << id.regionId()<<" header "<<head_id<<site_name<<" which already exists!"<<std::endl; + m_db_conn.Rollback(); + return false; + } + coral::ITableDataEditor *editor[] = {&m_db_conn.GetTableEditor(std::string("MDT_TUBE")), &m_db_conn.GetTableEditor(std::string("MDT_TUBE_V")), &m_db_conn.GetTableEditor(std::string("MDT_TUBE_C"))}; + //insert new tubes + if (validation_flag.size()==0) + { + if(!insertTubes(site_name, head_id, id, t0, validation_flag, editor)) + { + m_db_conn.Rollback(); + return false; + } + m_db_conn.Commit(); + return true; + } + //check if all tubes ar enew or if all tubes a validated good + bool all_new(true), all_good(true); + for(std::vector<int> :: const_iterator it = validation_flag.begin(); it!=validation_flag.end(); it++) + { + if ((*it)!=0) all_new=false; + if ((*it)!=3) all_good=false; + if (!all_new && !all_good) break; + } + //insert new tubes + if(all_new) + { + if(!insertTubes(site_name, head_id, id, t0, validation_flag, editor)) + { + m_db_conn.Rollback(); + return false; + } + m_db_conn.Commit(); + return true; + } + //all tubes are good. Update the whole chamber in one go + if(all_good) + { + if(!setValidationFlag(site_name, head_id, id, 0, 3, *editor[0])) + { + m_db_conn.Rollback(); + return false; + } + m_db_conn.Commit(); + return true; + } + //update flag for failed and dummy tubes - insert for failed + std::vector<coral::AttributeList> rowBuffer(3); + bool row_buffer_initialized(false); + unsigned int nml=t0->numMultilayers(); + unsigned int nly=t0->numLayers(); + unsigned int ntb=t0->numTubes(); + MuonFixedId fixId(0); + fixId.setTechnology(0); + fixId.setStationName(id.GetStation()); + fixId.setStationEta(id.GetEta()); + fixId.setStationPhi(id.GetPhi()); + for(unsigned int ml=0; ml<nml; ml++) + for(unsigned int ly=0; ly<nly; ly++) + for(unsigned int tb=0; tb<ntb; tb++) + { + int tb_index=tb + ntb*ly + ntb*nly*ml; + if(validation_flag[tb_index]==3) continue; + fixId.setMdtTube(tb+1); + fixId.setMdtTubeLayer(ly+1); + fixId.setMdtMultilayer(ml+1); + //new tubes or tubes that are validated bad are inserted + int rowsUpdated; + if (validation_flag[tb_index]==5) + rowsUpdated=setValidFlag(site_name, head_id, fixId.getIdInt(), 5, *editor[0]); + else + rowsUpdated=setValidFlag(site_name, head_id, fixId.getIdInt(), 1, *editor[0]); + + if(rowsUpdated!=1) + { + std::cerr<<id.regionId()<<" tb="<<tb<<" ly="<<ly<<" ml="<<ml<<" head_id="<<head_id<<": "<<rowsUpdated<<" Rows to be updated! This is wrong! Check database!"<<std::endl; + m_db_conn.Rollback(); + return false; + } + if(validation_flag[tb_index]!=5) + { + std::cout<<"Insert new "<<fixId.getIdInt()<<std::endl; + //initialize row buffers + if(!row_buffer_initialized) + { + initRowBuffer(rowBuffer, id, head_id, site_name, t0); + row_buffer_initialized=true; + } + //fill row buffers + fillRowBuffer(rowBuffer, t0, ml, ly, tb, fixId); + rowBuffer[0]["VALIDFLAG"].data<int>() =validation_flag[tb_index]; + //loop over 3 t0 tables - get seqid from 1st and insert it into 2nd and 3rd. + for(unsigned int i=0; i<3; i++) + { + rowBuffer[i]["CALIBFLAG"].data<int>() = static_cast<int>(validation_flag[tb_index] > 3); + editor[i]->insertRow( rowBuffer[i] ); + } + } + } + //now all tubes whit validflag == 0 are good update in one go + if(!setValidationFlag(site_name, head_id, id, 0, 3, *editor[0])) + { + m_db_conn.Rollback(); + return false; + } + m_db_conn.Commit(); + return true; + }//try + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + m_db_conn.Rollback(); + return false; + } + } + + +bool CalibT0DbOperations :: ReadForConditions(std::string /*site_name*/, int head_id, IConditionsStorage & storage) + { + std::cout<<"CalibT0DbOperations :: ReadForConditions"<<std::endl; + try + { + //prepare query + std::cout<<"OpenTransaction();"<<std::endl; + m_db_conn.OpenTransaction(); + std::cout<<"GetQuery();"<<std::endl; + m_query=m_db_conn.GetQuery(); + m_query->addToTableList("MDT_TUBE"); + m_query->addToOutputList("MDT_TUBE.CHAMBER", "CHAMBER"); + m_query->addToOutputList("MDT_TUBE.TUBE_ID", "TUBE_ID"); + m_query->setRowCacheSize(10000); + const std::vector<std::string> &rows_tube_table(storage.RowsFromMdtTubeTable()); + for(std::vector<std::string>::const_iterator it=rows_tube_table.begin(); it!=rows_tube_table.end(); it++) + { + if(*it=="CHAMBER" || *it=="TUBE_ID") continue; + m_query->addToOutputList(std::string("MDT_TUBE.") + *it, *it); + } + const std::vector<std::string> &rows_tube_v_table(storage.RowsFromMdtTubeVTable()); + if(rows_tube_v_table.size() != 0) + { + m_query->addToTableList("MDT_TUBE_V"); + for(std::vector<std::string>::const_iterator it=rows_tube_v_table.begin(); it!=rows_tube_v_table.end(); it++) + { + m_query->addToOutputList( std::string("MDT_TUBE_V.") + *it, *it); + } + } + const std::vector<std::string> &rows_tube_c_table(storage.RowsFromMdtTubeCTable()); + if(rows_tube_c_table.size() != 0) + { + m_query->addToTableList("MDT_TUBE_C"); + for(std::vector<std::string>::const_iterator it=rows_tube_c_table.begin(); it!=rows_tube_c_table.end(); it++) + { + m_query->addToOutputList( std::string("MDT_TUBE_C.") + *it, *it); + std::cout<<std::string("MDT_TUBE_C.") + *it<<std::endl; + } + } + coral::AttributeList conditionData; + conditionData.extend<int>("HEAD_ID"); + conditionData["HEAD_ID"].data<int>()=head_id; + std::string condition = "MDT_TUBE.HEAD_ID = :HEAD_ID and MDT_TUBE.VALIDFLAG>1 "; + if (rows_tube_v_table.size() != 0) + condition = condition + " and MDT_TUBE.HEAD_ID = MDT_TUBE_V.HEAD_ID and MDT_TUBE.TUBE_ID=MDT_TUBE_V.TUBE_ID and MDT_TUBE.CALIBFLAG=MDT_TUBE_V.CALIBFLAG"; + if (rows_tube_c_table.size() != 0) + condition = condition + " and MDT_TUBE.HEAD_ID = MDT_TUBE_C.HEAD_ID and MDT_TUBE.TUBE_ID=MDT_TUBE_C.TUBE_ID and MDT_TUBE.CALIBFLAG=MDT_TUBE_C.CALIBFLAG"; + m_query->setCondition( condition, conditionData ); + m_query->addToOrderList( "MDT_TUBE.CHAMBER" ); + //execute query + int old_chamber_id(-1); + std::map<IConditionsStorage::TubeId, coral::AttributeList> rows_of_a_chamber; + coral::ICursor& cursor = m_query->execute(); + while (cursor.next()) + { + const coral::AttributeList & al= cursor.currentRow(); + //if we have a new chamber - call callback + if(old_chamber_id != al["CHAMBER"].data<int>() && rows_of_a_chamber.size() != 0) + { + if(!storage.StoreT0Chamber(old_chamber_id, rows_of_a_chamber)) + { + return false; + } + rows_of_a_chamber.clear(); + } + //store row + IConditionsStorage::TubeId id(al["TUBE_ID"].data<int>()); + rows_of_a_chamber[id]=al; + old_chamber_id=al["CHAMBER"].data<int>(); + } + if(!storage.StoreT0Chamber(old_chamber_id, rows_of_a_chamber)) + { + return false; + } + return true; + } + catch( coral::SchemaException& e ) + { + std::cerr << "Schema exception : " << e.what() << std::endl; + return false; + } + } + + +inline void CalibT0DbOperations :: initRowBuffer(std::vector<coral::AttributeList> & rowBuffer, const NtupleStationId &id, const int & head_id, const std::string & /*site_name*/, const MdtTubeFitContainer * t0) + { + std::cout<<"CalibT0DbOperations :: initRowBuffer"<<std::endl; + for(unsigned int i=0; i<3; i++) + { + rowBuffer[i].extend<int>("TUBE_ID"); + rowBuffer[i].extend<int>("HEAD_ID"); + rowBuffer[i]["HEAD_ID"].data<int>()=head_id; + rowBuffer[i].extend<int>("CALIBFLAG"); + } + rowBuffer[0].extend<int>("CHAMBER"); + rowBuffer[0]["CHAMBER"].data<int>()=id.FixedId(); +// rowBuffer[0].extend<std::string>("SITE_NAME"); +// rowBuffer[0]["SITE_NAME"].data<std::string>()=site_name; + rowBuffer[0].extend<int>("VALIDFLAG"); + rowBuffer[1].extend<int>("ENTRIES"); +// rowBuffer[1].extend<int>("SEQID"); +// rowBuffer[2].extend<int>("SEQID"); + rowBuffer[1].extend<float>("CHISQUARE_1"); + rowBuffer[1].extend<float>("CHISQUARE_2"); + for(int i=0; i<8; i++) + { + std::ostringstream ostr2; + ostr2<<"P"<<i; + if(i==4) + rowBuffer[0].extend<float>(ostr2.str()); + else + rowBuffer[1].extend<float>(ostr2.str()); + ostr2<<"_ERR"; + if(i>3 && i<7) + rowBuffer[1].extend<float>(ostr2.str()); + else + rowBuffer[2].extend<float>(ostr2.str()); + } + for(int i=0; i<4; i++) + { + std::ostringstream ostr2; + ostr2<<"ADC_"<<i; + //!!!!!!ADC_0 should be moved to MDT_TUBE + rowBuffer[0].extend<float>(ostr2.str()); + ostr2<<"_ERR"; + rowBuffer[2].extend<float>(ostr2.str()); + } + rowBuffer[2].extend<float>("ADC_CHISQUARE"); + rowBuffer[0].extend<int>("NHITS"); + rowBuffer[0].extend<int>("NHITS_ABOVE_ADC_CUT"); + rowBuffer[1].extend<std::string>("ALGO_FLAG"); + if(t0->implementation()=="T0CalibrationClassic") + { + rowBuffer[1]["ALGO_FLAG"].data<std::string>()="T0Classic"; + } + else if(t0->implementation()=="T0CalibrationMT") + { + rowBuffer[1]["ALGO_FLAG"].data<std::string>()="T0MT"; + } + else + { + rowBuffer[1]["ALGO_FLAG"].data<std::string>()="Unknown"; + } + rowBuffer[1].extend<std::string>("TUBE_GROUPING"); + rowBuffer[1]["TUBE_GROUPING"].data<std::string>() = "UNKNOWN"; + } + + +inline void CalibT0DbOperations :: fillRowBuffer(std::vector<coral::AttributeList> & rowBuffer, const MdtTubeFitContainer * t0, const int & ml, const int &ly, const int &tb, const MuonFixedId &fixId) + { + std::cout<<"CalibT0DbOperations :: fillRowBuffer"<<std::endl; + for(unsigned int i=0; i<3; i++) + { + rowBuffer[i]["TUBE_ID"].data<int>()=fixId.getIdInt(); + } + rowBuffer[1]["ENTRIES"].data<int>()=t0->getFit(ml,ly,tb)->statistics; + rowBuffer[1]["CHISQUARE_1"].data<float>()=t0->getFit(ml,ly,tb)->chi2Tdc; + rowBuffer[1]["CHISQUARE_2"].data<float>() = t0->getFit(ml,ly,tb)->chi2TdcEnd; + rowBuffer[1]["TUBE_GROUPING"].data<std::string>() = t0->getFit(ml,ly,tb)->group_by; + for(int i=0; i<8; i++) + { + double val=t0->getFit(ml,ly,tb)->par[i]; + if(std::isnan(val)) val=-99999.; + std::ostringstream ostr2; + ostr2<<"P"<<i; + if(i==4) + rowBuffer[0][ostr2.str()].data<float>()=val; + else + rowBuffer[1][ostr2.str()].data<float>()=val; + ostr2<<"_ERR"; + val=t0->getFit(ml,ly,tb)->cov[i]; + if(std::isnan(val)) val=-99999.; + if(i>3 && i<7) + rowBuffer[1][ostr2.str()].data<float>()=val; + else + rowBuffer[2][ostr2.str()].data<float>()=val; + } + for(int i=0; i<4; i++) + { + std::ostringstream ostr2; + ostr2<<"ADC_"<<i; + rowBuffer[0][ostr2.str()].data<float>() = t0->getFit(ml,ly,tb)->adc_par[i]; + ostr2<<"_ERR"; + rowBuffer[2][ostr2.str()].data<float>() = t0->getFit(ml,ly,tb)->adc_err[i]; + } + rowBuffer[2]["ADC_CHISQUARE"].data<float>()=t0->getFit(ml,ly,tb)->adc_chi2; + rowBuffer[0]["NHITS"].data<int>()=t0->getFit(ml,ly,tb)->n_hits; + if(t0->getFit(ml,ly,tb)->n_hits > 999999) + rowBuffer[0]["NHITS"].data<int>()=999999; + rowBuffer[0]["NHITS_ABOVE_ADC_CUT"].data<int>() = t0->getFit(ml,ly,tb)-> n_hits_above_adc_cut; + if(t0->getFit(ml,ly,tb)-> n_hits_above_adc_cut > 999999) + rowBuffer[0]["NHITS_ABOVE_ADC_CUT"].data<int>() = 999999; + } + + +bool CalibT0DbOperations :: setValidFlag(const std::string &/*site_name*/, const int & head_id, const int & tube_id, const int & new_validflag, coral::ITableDataEditor &editor) + { + std::string updateAction = "validflag = :newval"; + std::string updateCondition = "head_id=:hid and tube_id=:tid and validflag=0"; + coral::AttributeList updateData; + updateData.extend<int>("hid"); + updateData[0].data<int>()=head_id; + updateData.extend<int>("tid"); + updateData[1].data<int>()=tube_id; +// updateData.extend<std::string>("sn"); +// updateData[2].data<std::string>()=site_name; + updateData.extend<int>("newval"); + updateData[2].data<int>()=new_validflag; + long rowsUpdated = editor.updateRows( updateAction, updateCondition, updateData ); + return rowsUpdated; + } + + +bool CalibT0DbOperations :: insertTubes(const std::string & site_name, int head_id, const NtupleStationId & id, const MdtTubeFitContainer * t0, const std::vector<int> & validation_flag, coral::ITableDataEditor * editor[]) + { + std::vector<coral::AttributeList> rowBuffer(3); + std::vector<coral::IBulkOperation *> bulk_inserter(3); + bool row_buffer_initialized(false); + unsigned int nml=t0->numMultilayers(); + unsigned int nly=t0->numLayers(); + unsigned int ntb=t0->numTubes(); +//do not insert completely dead chambers + bool all_dead(true); + for(unsigned int ml=0; ml<nml; ml++) + for(unsigned int ly=0; ly<nly; ly++) + for(unsigned int tb=0; tb<ntb; tb++) + { + if(t0->getFit(ml,ly,tb)->statistics > 0) + { + all_dead=false; + break; + } + } + if(all_dead) + { + std::cerr<<"Refusing to insert completely dead chamber"<<std::endl; + return false; + } + MuonFixedId fixId(0); + fixId.setTechnology(0); + fixId.setStationName(id.GetStation()); + fixId.setStationEta(id.GetEta()); + fixId.setStationPhi(id.GetPhi()); + for(unsigned int ml=0; ml<nml; ml++) + for(unsigned int ly=0; ly<nly; ly++) + for(unsigned int tb=0; tb<ntb; tb++) + { + int tb_index=tb + ntb*ly + ntb*nly*ml; + fixId.setMdtTube(tb+1); + fixId.setMdtTubeLayer(ly+1); + fixId.setMdtMultilayer(ml+1); + int v_flag=0; + if (static_cast<int>(validation_flag.size())>tb_index) + { + v_flag=validation_flag[tb_index]; + } + if(!row_buffer_initialized) + { + initRowBuffer(rowBuffer, id, head_id, site_name, t0); + for (int i=0; i<3; i++) + { + bulk_inserter[i]=editor[i]->bulkInsert( rowBuffer[i], 432); + } + row_buffer_initialized=true; + } + fillRowBuffer(rowBuffer, t0, ml, ly, tb, fixId); + rowBuffer[0]["VALIDFLAG"].data<int>() =v_flag; + std::cout<<"XXXXXXXX='"<<rowBuffer[1]["TUBE_GROUPING"].data<std::string>()<<"'"<<std::endl; + for(unsigned int i=0; i<3; i++) + { + rowBuffer[i]["CALIBFLAG"].data<int>() = static_cast<int>(v_flag>3); + bulk_inserter[i]->processNextIteration(); + + } + } + for(unsigned int i=0; i<3; i++) + { + bulk_inserter[i]->flush(); + delete bulk_inserter[i]; + } + return true; + } + +bool CalibT0DbOperations :: setValidationFlag(const std::string & /*site_name*/, int head_id, const NtupleStationId & id, int from, int to, coral::ITableDataEditor & editor) + { + std::string updateAction = "validflag = :newval"; + std::string updateCondition = "head_id=:hid and chamber=:cham and validflag=:old_val"; + coral::AttributeList updateData; + updateData.extend<int>("hid"); + updateData[0].data<int>()=head_id; + updateData.extend<std::string>("cham"); + std::ostringstream ostr; + ostr<<id.FixedId(); + updateData[1].data<std::string>()=ostr.str(); + updateData.extend<int>("newval"); + updateData[2].data<int>()=to; + updateData.extend<int>("old_val"); + updateData[3].data<int>()=from; + long rowsUpdated = editor.updateRows( updateAction, updateCondition, updateData ); + return (rowsUpdated<=432); + } + + +inline bool CalibT0DbOperations :: checkTubesPresent(const int & head_id, const std::string &/*site_name*/, const NtupleStationId & id, const std::vector<int> & validflag) + { + m_query=m_db_conn.GetQuery(); +//select count(MDT_TUBE.TUBE_ID) as N_TUBES, MDT_TUBE.VALIDFLAG as VALIDFLAG from MDT_TUBE where MDT_TUBE.HEAD_ID = :hid and MDT_TUBE.CHAMBER = :chamb and SITE_NAME=:sn group by MDT_TUBE.VALIDFLAG; + m_query->addToTableList("MDT_TUBE"); + coral::AttributeList conditionData; + conditionData.extend<int>("hid"); + conditionData[0].data<int>()=head_id; +//as long as the chamber id is stored as a string, it is more efficient to pass the chamber id as a string in the query + std::ostringstream ostr; + ostr<<id.FixedId(); + conditionData.extend<std::string>("chamb"); + conditionData[1].data<std::string>()=ostr.str(); + std::string condition = "MDT_TUBE.HEAD_ID = :hid and MDT_TUBE.CHAMBER = :chamb"; + m_query->setCondition( condition, conditionData ); + m_query->addToOutputList( "count(MDT_TUBE.TUBE_ID)", "N_TUBES"); + m_query->addToOutputList( "MDT_TUBE.VALIDFLAG", "VALIDFLAG" ); + m_query->groupBy("MDT_TUBE.VALIDFLAG"); + coral::ICursor& cursor = m_query->execute(); + bool has_unvalidated(false), has_validated(false); + while (cursor.next()) + { + const coral::AttributeList & al= cursor.currentRow(); + if(al["VALIDFLAG"].data<short>()>0) + { + if(al["N_TUBES"].data<double>()>0) + { + has_validated=true; + } + } + else + { + if(al["N_TUBES"].data<double>()>0) + { + has_unvalidated=true; + } + } + } +//check what has to be done + if(validflag.size()==0) + return !has_unvalidated; + for(std::vector<int>::const_iterator it=validflag.begin(); it!=validflag.end(); it++) + { + if((*it) > 0 && has_validated) + return false; + if((*it) == 0 && has_unvalidated) + return false; + } + return true; + } + + + +} //namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibrationDbIOTool.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibrationDbIOTool.cxx new file mode 100644 index 0000000000000..a3f4b9655c4a0 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CalibrationDbIOTool.cxx @@ -0,0 +1,363 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/CalibrationDbIOTool.h" +#include "MuonCalibDbOperations/CalibDbConnection.h" +#include "MuonCalibDbOperations/CalibT0DbOperations.h" +#include "MuonCalibDbOperations/CalibRtDbOperations.h" +#include "MuonCalibDbOperations/CalibHeadOperations.h" +//gaudi +#include "GaudiKernel/MsgStream.h" +#include "StoreGate/StoreGateSvc.h" + +//MdtCalibUtils +#include "MdtCalibUtils/TubeDataFromFile.h" +#include "MdtCalibUtils/RtDataFromFile.h" + +//MdtCalibData +#include "MdtCalibData/MdtTubeFitContainer.h" +#include "MdtCalibData/IRtResolution.h" +#include "MdtCalibData/RtChebyshev.h" +#include "MdtCalibData/RtRelationLookUp.h" +#include "MdtCalibData/RtResolutionLookUp.h" +#include "MdtCalibData/RtSpline.h" +#include "MdtCalibData/RtResolutionFromPoints.h" +#include "MdtCalibData/RtFromPoints.h" + +//MdtCalibRt +#include "MdtCalibRt/RtCalibrationOutput.h" + +//MuonCalibStandAloneBase +#include "MuonCalibStandAloneBase/NtupleStationId.h" +#include "MuonCalibStandAloneBase/MdtStationT0Container.h" + +//MuonCalibMath +#include "MuonCalibMath/SamplePoint.h" + +//c - c++ +#include "string" +#include "iostream" +#include "fstream" +#include <sys/types.h> +#include <dirent.h> + +#include "MuonCalibStandAloneBase/RegionSelectionSvc.h" + + +namespace MuonCalib { + + CalibrationDbIOTool :: CalibrationDbIOTool(const std::string& t, const std::string& n, const IInterface* p) : AlgTool(t, n, p), m_db_ConnectionString(""), m_db_WorkingSchema(""), m_sitename("") + { + declareInterface< CalibrationIOTool >(this) ; + declareProperty("ConnectionString", m_db_ConnectionString); + declareProperty("WriterConnectionString", m_writer_connection_string); + declareProperty("WorkingSchema", m_db_WorkingSchema); + m_headid=-1; + declareProperty("HeadId", m_headid); + declareProperty("SiteName", m_sitename); + m_max_rt_points=100; + declareProperty("MaxRtPoints", m_max_rt_points); + m_use_validated_t0=true; + declareProperty("UseValidaedT0", m_use_validated_t0); + m_use_validated_t0=false; + declareProperty("UseValidaedRt", m_use_validated_rt); + for (int i=0; i<2;i++) + { + m_data_connections[i]=NULL; + } + declareProperty("ReaderAccount", m_reader_account); + declareProperty("ReaderPassword", m_reader_password); + declareProperty("WriterAccount", m_writer_account); + declareProperty("WriterPassword", m_writer_password); + } + + +StatusCode CalibrationDbIOTool :: initialize() + { + MsgStream log(msgSvc(), name()); + + StatusCode sc= serviceLocator()->service("RegionSelectionSvc", p_reg_sel_svc); + if(!sc.isSuccess()) + { + log << MSG::ERROR <<"Cannot retrieve RegionSelectionSvc!" <<endreq; + return sc; + } + region_ids=p_reg_sel_svc->GetStationsInRegions(); + log<< MSG::INFO << " CalibrationDbIOTool :: initialize() - number of selected regions: "<<region_ids.size()<<endreq; + +log<< MSG::INFO << "open connection" <<endreq; + m_connection = new CalibDbConnection(m_db_ConnectionString, m_db_WorkingSchema); +log<< MSG::INFO << "." <<endreq; + if(m_reader_account!="") + { + m_connection->SetLogin(m_reader_account, m_reader_password); + } + if (!m_connection->OpenConnection()) + { + log<< MSG::FATAL << "Cannot open connection to database!" <<endreq; + return StatusCode::FAILURE; + } +log<< MSG::INFO << ".." <<endreq; + m_head_ops = new CalibHeadOperations(*m_connection); + if (m_headid<0) + { + m_headid=m_head_ops->GetLatestHeadId(); + if (m_headid<0) + { + log<< MSG::FATAL << "Cannot get latest head_id for site "<< m_sitename<<endreq; + return StatusCode::FAILURE; + } + } + return StatusCode::SUCCESS; + } + +StatusCode CalibrationDbIOTool :: finalize() + { + MsgStream log(msgSvc(), name()); + log << MSG::INFO <<"CalibrationDbIOTool finalize"<<endreq; + for(int i=0; i<2; i++) + { + if (m_data_connections[i]!=NULL) + m_data_connections[i]->CloseConnection(); + } + m_connection->CloseConnection(); + return StatusCode::SUCCESS; + } + + +StatusCode CalibrationDbIOTool :: WriteT0(MdtTubeFitContainer* t0, const NtupleStationId & it, int /*iov_start*/, int /*iov_end*/) + { + MsgStream log(msgSvc(), name()); + log<<MSG::INFO<<"Writing to database"<<endreq; + if(!m_connection->OpenConnection()) + { + log << MSG::FATAL <<"Open Connection failed!"<<endreq; + return StatusCode::FAILURE; + } + else + { + if(get_connection(1)==NULL) + { + return StatusCode::FAILURE; + } + m_data_connections[1]->OpenConnection(); + std::cout<<"."<<std::endl; + CalibT0DbOperations t0_op(*m_data_connections[1]); + std::cout<<"."<<std::endl; + std::vector<int> val(0); + std::cout<<"."<<std::endl; + if(!t0_op.WriteT0Chamber(it, t0, val, m_headid, m_sitename)) + { + std::cout<<"."<<std::endl; + log << MSG::FATAL <<"Writing t0 failed!"<<endreq; + std::cout<<"."<<std::endl; + m_connection->CloseConnection(); + m_data_connections[1]->CloseConnection(); + return StatusCode::FAILURE; + } + } + return StatusCode::SUCCESS; + } + + +StatusCode CalibrationDbIOTool :: LoadT0(std::map<NtupleStationId, MdtStationT0Container *> &t0s, int /*iov_id*/) + { + MsgStream log(msgSvc(), name()); + if(!m_connection->OpenConnection()) + { + log << MSG::FATAL <<"Open Connection failed!"<<endreq; + return StatusCode::FAILURE; + } + else + { + if(!get_connection(0)) + { + return StatusCode::FAILURE; + } + m_data_connections[0]->OpenConnection(); + CalibT0DbOperations t0_op(*m_data_connections[0]); + t0s.clear(); + + //loop on all the ids in the selected calibration region + for (std::vector<MuonCalib::NtupleStationId>::iterator it=region_ids.begin(); it!=region_ids.end(); it++) + { + log << MSG::INFO << "Reading t0s for region " << it->regionId() << endreq; + MdtStationT0Container * t0; + t0=t0_op.LoadT0Calibration(*it, m_headid, m_sitename); + if(t0!=NULL) + t0s[*it]=t0; + } + } + m_data_connections[0]->CloseConnection(); + m_connection->CloseConnection(); + return StatusCode::SUCCESS; + } + + +StatusCode CalibrationDbIOTool :: WriteRt(const RtCalibrationOutput *rt_relation, const IRtResolution * resolution, const NtupleStationId & station_id, int /*iov_start*/, int /*iov_end*/, bool /*real_rt*/, bool /*real resolution*/) + { + MsgStream log(msgSvc(), name()); + std::vector<SamplePoint> points; +//fill rt poits + fillRtPoints(rt_relation->rt(), points); +//fill resolution points + fillResPoints(resolution, points); +//fill multilayer rt difference as pseudo-point + if(rt_relation->rt()->HasTmaxDiff()) + { + SamplePoint point(rt_relation->rt()->GetTmaxDiff(), -99.9, 0.0); + points.push_back(point); + } + if(!m_connection->OpenConnection()) + { + log << MSG::FATAL <<"Open Connection failed!"<<endreq; + return StatusCode::FAILURE; + } + else + { + if(get_connection(1)==NULL) + { + return StatusCode::FAILURE; + } + m_data_connections[1]->OpenConnection(); + CalibRtDbOperations rt_op(*m_data_connections[1]); + if(!rt_op.WriteUpdateRt(station_id, m_headid, m_sitename, points, 0, rt_relation->fullInfo())) + { + log << MSG::FATAL <<"Writing rt failed!"<<endreq; + m_connection->CloseConnection(); + m_data_connections[1]->CloseConnection(); + return StatusCode::FAILURE; + } + } + return StatusCode::SUCCESS; + } + + + +StatusCode CalibrationDbIOTool :: LoadRt(std::map<NtupleStationId, IRtRelation *> & rts, std::map<NtupleStationId, IRtResolution *> &res, int /*iov_id*/) + { + MsgStream log(msgSvc(), name()); + if(!m_connection->OpenConnection()) + { + log << MSG::FATAL <<"Open Connection failed!"<<endreq; + return StatusCode::FAILURE; + } + else + { + if(!get_connection(0)) + { + return StatusCode::FAILURE; + } + m_data_connections[0]->OpenConnection(); + CalibRtDbOperations rt_op(*m_data_connections[0]); + //loop on all the ids in the selected calibration region + RtFromPoints rt_from_points; + RtResolutionFromPoints res_from_points; + for (std::vector<MuonCalib::NtupleStationId>::iterator it=region_ids.begin(); it!=region_ids.end(); it++) + { + std::vector<SamplePoint> in_points; + RtFullInfo full_info; + if(!rt_op.LoadRt(*it, m_headid, m_use_validated_rt, m_sitename, in_points, &full_info)) + continue; + log << MSG::INFO << "Reading rts for region " << it->regionId() << endreq; + std::vector<SamplePoint> outpoints; + float tmax_diff(-9e9); + for (unsigned int k=0; k<in_points.size(); k++) + { + if (in_points[k].x2()<-99) + { + tmax_diff=in_points[k].x1(); + continue; + } + SamplePoint outpoint(in_points[k].x1(), in_points[k].x2(), 1.0); + outpoints.push_back(outpoint); + } + rts[*it]= new RtRelationLookUp(rt_from_points.getRtRelationLookUp(outpoints)); + if(tmax_diff>-8e8) + { + rts[*it]->SetTmaxDiff(tmax_diff); + } + outpoints.clear(); + for (unsigned int k=0; k<in_points.size(); k++) + { + if (in_points[k].x2()<-99) + { + continue; + } + SamplePoint outpoint(in_points[k].x1(), in_points[k].error(), 1.0); + outpoints.push_back(outpoint); + } + res[*it] = new RtResolutionLookUp(res_from_points.getRtResolutionLookUp(outpoints)); + } + } + m_data_connections[0]->CloseConnection(); + m_connection->CloseConnection(); + return StatusCode::SUCCESS; + } + + +inline void CalibrationDbIOTool :: fillRtPoints( const IRtRelation* rt, std::vector<SamplePoint> & points) + { + MsgStream log(msgSvc(), name()); + points.clear(); +//for rt relations based on support points, write points + const RtRelationLookUp *rt_lookup=dynamic_cast<const RtRelationLookUp *>(rt); + const CalibFunc::ParVec & rt_param = rt->parameters(); + if(rt_lookup && static_cast<int>(rt_lookup->nPar()-2)<=m_max_rt_points) + { + double t_min(rt_param[0]); + double bin_size = rt_param[1]; + unsigned int nb_points(rt_lookup->nPar()-2); + for (unsigned int k=0; k<nb_points; k++) + { + double radius(rt_param[k+2]); + if(std::isnan(radius)) + { + log<<MSG::WARNING<<"Skipping NAN"<<endreq; + continue; + } + SamplePoint point(t_min+bin_size*k, rt_param[k+2], -1); + points.push_back(point); + } + return; + } + const RtSpline *rt_spline=dynamic_cast<const RtSpline *>(rt); + if(rt_spline && static_cast<int>(rt_param.size()/2)<=m_max_rt_points) + { + for(unsigned int i=0; i<rt_param.size(); i+=2) + { + SamplePoint point(rt_param[i], rt_param[i+1], -1); + points.push_back(point); + } + return; + } +//for all others, or if the number of support points is too high, calculate new support points + for(int i=0; i< m_max_rt_points; i++) + { + double t=rt->tLower() + i*((rt->tUpper() - rt->tLower())/(m_max_rt_points - 1)); + SamplePoint point(t, rt->radius(t), -1.0); + } + } + +inline void CalibrationDbIOTool :: fillResPoints(const IRtResolution *rt_resolution, std::vector<SamplePoint> & points) + { + for(unsigned int i=0; i<points.size(); i++) + { + points[i].set_error(rt_resolution->resolution(points[i].x1())); + } + } + +CalibDbConnection * CalibrationDbIOTool :: get_connection(int write) + { + if(m_data_connections[write]!=0) + { + return m_data_connections[write]; + } + m_data_connections[write] = m_head_ops->GetDataConnection(m_headid, static_cast<bool>(write), m_writer_connection_string, m_writer_account, m_writer_password); + return m_data_connections[write]; + } + + +} ///namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CoolInserter.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CoolInserter.cxx new file mode 100644 index 0000000000000..e3350efadc13d --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/CoolInserter.cxx @@ -0,0 +1,514 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/CoolInserter.h" +#include "MuonCalibDbOperations/CalibDbConnection.h" +#include "MuonCalibDbOperations/CalibT0DbOperations.h" +#include "MuonCalibDbOperations/CalibRtDbOperations.h" +#include "MuonCalibDbOperations/CalibHeadOperations.h" +//coral +#include "CoralBase/AttributeList.h" +#include "CoralBase/Attribute.h" +#include "CoolKernel/ConstRecordAdapter.h" +#include "CoolKernel/FolderSpecification.h" + +#include "AthenaKernel/IOVTime.h" + +//MuonCalibIdentifier +#include "MuonCalibIdentifier/MuonFixedId.h" + +//MuonCalibMath +#include "MuonCalibMath/SamplePoint.h" + +//MuonCalibStandAloneBase +#include "MuonCalibStandAloneBase/RegionSelectionSvc.h" + + +#include "GaudiKernel/MsgStream.h" +#include "GaudiKernel/IMessageSvc.h" +#include "StoreGate/StoreGateSvc.h" +#include "MuonIdHelpers/MdtIdHelper.h" + +#include "MuonReadoutGeometry/MuonDetectorManager.h" +#include "MuonReadoutGeometry/MdtReadoutElement.h" +//c - c++ +#include "iostream" +#include "sstream" +#include "exception" +#include <typeinfo> +#include "zlib.h" +//using namespace cool; +namespace MuonCalib { + +CoolInserter :: CoolInserter(const std::string& name, ISvcLocator* pSvcLocator) : Algorithm(name, pSvcLocator), m_version("v0.0"), p_reg_sel_svc(NULL), m_cool_connect(false), m_t0_created(false), m_rt_created(false), m_mdtIdHelper(NULL), m_detMgr(NULL) + { + declareProperty("CoolConnectionString", m_cool_connection_string); + declareProperty("RtVersion", m_version); + declareProperty("T0Tag", m_tagt0); + declareProperty("RtTag", m_tagrt); + declareProperty("IOVStart", m_iov_start); + declareProperty("IOVEnd", m_iov_end); + declareProperty("T0Folder", m_t0_folder); + declareProperty("RtFolder", m_rt_folder); + declareProperty("T0FolderCompress", m_compressed_t0); + declareProperty("RtFolderCompress", m_compressed_rt); + + declareProperty("CalibrationSources", m_calibraiton_sources); + m_n_tubes_chamber=0; + m_n_tubes_added=0; + m_iovt_start=0; + m_iovt_end=0; + m_aver_t0=0; + m_aver_adc=0; + } + +StatusCode CoolInserter :: initialize() + { + MsgStream log(msgSvc(), name()); +//check jo + if(m_tagt0.size() != m_t0_folder.size() || m_tagrt.size() != m_rt_folder.size()) + { + log << MSG::FATAL << "Configuration error: Number of folders and tags do not match!"<< endreq; + return StatusCode::FAILURE; + } + StoreGateSvc * detStore; + StatusCode sc=service("DetectorStore", detStore); + if(!sc.isSuccess()) + { + log << MSG::FATAL << "Cannot retrieve Store Gate!" << endreq; + return sc; + } + + sc = detStore->retrieve(m_mdtIdHelper, "MDTIDHELPER" ); + if (!sc.isSuccess()) + { + log << MSG::FATAL << "Can't retrieve MdtIdHelper" << endreq; + return sc; + } + + sc = detStore->retrieve( m_detMgr ); + if (!sc.isSuccess()) + { + log << MSG::FATAL << "Can't retrieve MuonDetectorManager" << endreq; + return sc; + } + +//get region selection service + sc=service("RegionSelectionSvc", p_reg_sel_svc); + if(!sc.isSuccess()) + { + log << MSG::ERROR <<"Cannot retrieve RegionSelectionSvc!" <<endreq; + return sc; + } +//connect to cool database + try + { + m_db = app.databaseService().openDatabase(m_cool_connection_string ,false ); + } + catch ( cool::DatabaseDoesNotExist & e ) + { + log<<MSG::INFO<<"Creating new database."<<endreq; + try + { + m_db = app.databaseService().createDatabase(m_cool_connection_string); + } + catch(cool::Exception & e) + { + log << MSG::FATAL << "Cannot create database and datbasae does not exist!" << endreq; + return StatusCode::FAILURE; + } + } + m_cool_connect=true; + if(m_t0_folder.size()) + { + log << MSG::INFO <<"Replication into t0 folders: "; + for(unsigned int i=0; i<m_t0_folder.size(); i++) + { + log<<m_t0_folder[i] << "(" << m_tagt0[i] << ") "; + } + log<<endreq; + } + if(m_rt_folder.size()) + { + log << MSG::INFO <<"Replication into rt folders: "; + for(unsigned int i=0; i<m_rt_folder.size(); i++) + { + log<<m_rt_folder[i] << "(" << m_tagrt[i] << ") "; + } + log<<endreq; + } +//retrieve calibraiotn sources + sc=m_calibraiton_sources.retrieve(); + if(!sc.isSuccess()) + { + log << MSG::FATAL <<"Cannot retrieve calibraition sources!"<<endreq; + return sc; + } +//get iov + for(unsigned int i=0; i<m_calibraiton_sources.size(); i++) + { + int iov_start(-1), iov_end(-1); + m_calibraiton_sources[i]->SetIOV(iov_start, iov_end); + if(m_iov_start<0 && iov_start>=0) + m_iov_start = iov_start; + if(m_iov_end==-1 && iov_end!=-1) + m_iov_end = iov_end; + } + if(m_iov_start<0 || m_iov_end==-1) + { + log << MSG::FATAL << "IOV has to be set, if no calibration source provides it!"<<endreq; + return StatusCode :: FAILURE; + } + IOVTime start(m_iov_start, 0); + m_iovt_start = start.re_time(); + if (m_iov_end<-1) + { + IOVTime end(IOVTime::MAXTIMESTAMP); + m_iovt_end = end.timestamp(); + } + else + { + IOVTime end(m_iov_end, 0); + m_iovt_end = end.re_time(); + } + log << MSG::INFO << "IOV is "<<m_iov_start<<" to "<<m_iov_end<<endreq; +//fill compressed flags + if(m_compressed_t0.size() < m_t0_folder.size()) + for(unsigned int i=m_compressed_t0.size(); i<m_t0_folder.size(); i++) + m_compressed_t0.push_back(false); + if(m_compressed_rt.size() < m_rt_folder.size()) + for(unsigned int i=m_compressed_rt.size(); i<m_rt_folder.size(); i++) + m_compressed_rt.push_back(false); + return StatusCode::SUCCESS; + } + + + + +StatusCode CoolInserter :: finalize() + { + MsgStream log(msgSvc(), name()); + log << MSG::INFO << "finalizing "<<endreq; + try + { + for(unsigned int i=0; i<m_mdtt0_fld.size(); i++) + m_mdtt0_fld[i]->flushStorageBuffer(); + for(unsigned int i=0; i<m_mdtrt_fld.size(); i++) + m_mdtrt_fld[i]->flushStorageBuffer(); + } + catch(std::exception & e) + { + log << MSG::FATAL << "Exception in finalize: " << e.what() <<endreq; + return StatusCode :: FAILURE; + } + return StatusCode::SUCCESS; + } + + +StatusCode CoolInserter :: execute() + { + MsgStream log(msgSvc(), name()); + for(unsigned int i=0; i<m_calibraiton_sources.size(); i++) + { + log << MSG::INFO << "Now running " <<m_calibraiton_sources[i] <<endreq; + if (!m_calibraiton_sources[i]->InstertCalibration(this, static_cast<bool>(m_t0_folder.size()), static_cast<bool>(m_rt_folder.size()))) + { + log << MSG::FATAL << "Calibration Source " << m_calibraiton_sources[i].name() << " failed!" << endreq; + return StatusCode :: FAILURE; + } + } + return StatusCode::SUCCESS; + } + + +bool CoolInserter :: StartT0Chamber(const NtupleStationId & sid) + { + m_n_tubes_added=0; + m_sid=sid; + m_sid.SetMultilayer(0); + if (!m_sid.InitializeGeometry(m_mdtIdHelper, m_detMgr)) + return false; +//get number of tubes + int max_nly(-1); + int max_ntb(-1); + for(int ml=0; ml<m_sid.NMultilayers(); ml++) + { + if(max_nly < m_sid.NLayers(ml)) + { + max_nly=m_sid.NLayers(ml); + } + if(max_ntb<m_sid.NTubes(ml)) + max_ntb=m_sid.NTubes(ml); + } + m_n_tubes_chamber=max_nly * max_ntb * m_sid.NMultilayers(); + m_data_string.str(""); + m_data_string.clear(); + m_data_string << "T0" << m_sid.regionId() << "," << m_version<< ",1," <<m_n_tubes_chamber<<std::endl; + m_aver_t0=0; + m_aver_adc=0; + return true; + } + +bool CoolInserter :: AppendT0(float t0, int validflag, float adc0) + { + if(m_n_tubes_added >= m_n_tubes_chamber) + { + return false; + } + m_data_string<<t0<<","<<validflag<<","<<adc0<<","; + m_n_tubes_added++; + m_aver_t0+=t0; + m_aver_adc+=adc0; + return true; + } + +bool CoolInserter :: StoreT0Chamber(const NtupleStationId & id, const std::string & file, unsigned int creation_flags) + { + MsgStream log(msgSvc(), name()); + MuonFixedId fid(id.FixedId()); +//generate fixed if for chamber + if(!p_reg_sel_svc->isInRegion(fid)) + { + return true; + } +//do not fill double + if(m_t0_filled.find(id) != m_t0_filled.end()) + { + return true; + } + m_t0_filled.insert(id); +//check number of added tubes + if (m_n_tubes_added < m_n_tubes_chamber) + { + log << MSG::WARNING << "Filling missing tubes with average for chamber" << m_sid.regionId()<<endreq; + m_aver_t0/=m_n_tubes_added; + m_aver_adc/=m_n_tubes_added; + for(int i=m_n_tubes_added; i<m_n_tubes_chamber; i++) + { + AppendT0(m_aver_t0, 5, m_aver_adc); + } + } +//cool + if(m_cool_connect && !m_t0_created) + { + for(unsigned int i=0; i<m_t0_folder.size(); i++) + { + if(!m_db->existsFolder(m_t0_folder[i])) + { + if(!create_folder(i, false)) + { + log << MSG::FATAL << "Cannot create folder '" << m_t0_folder[i] <<"'!"<<endreq; + return false; + } + } + m_mdtt0_fld.push_back(m_db->getFolder(m_t0_folder[i])); + m_mdtt0_fld[i]->setupStorageBuffer(); + + cool::RecordSpecification mdtt0_rec =(m_mdtt0_fld[i]->payloadSpecification()); + bool compressed(false); + if(m_compressed_t0.size()>i) + compressed=m_compressed_t0[i]; + m_mdtt0_cool_row[compressed] = cool::Record(mdtt0_rec).attributeList(); + } + m_t0_created = true; + } + if(m_t0_created) + { + std::cout<<"."<<std::flush; +// std::cout<<data_column.str()<<std::endl; + for(std::map<bool, coral::AttributeList> :: iterator it=m_mdtt0_cool_row.begin(); it!=m_mdtt0_cool_row.end(); it++) { + it->second["file"].data<cool::String4k>() = file; + it->second["tech"].data<int>() = creation_flags; + if(it->first) + { + uLongf dest_len = compressBound(m_data_string.str().size()); + coral::Blob &blob( it->second["data"].data<coral::Blob>()); + blob.resize(dest_len); + Bytef * p=static_cast<Bytef *>(blob.startingAddress()); + + + compress(p, &dest_len, reinterpret_cast<const Bytef *>(m_data_string.str().c_str()), m_data_string.str().size()); + blob.resize(dest_len); + } + else + { + it->second["data"].data<cool::String16M>() = m_data_string.str(); + } + for(unsigned int i=0; i<m_mdtt0_fld.size(); i++) + { + cool::ConstRecordAdapter record (m_mdtt0_fld[i]->payloadSpecification(), + m_mdtt0_cool_row[m_compressed_t0[i]]); + m_mdtt0_fld[i]->storeObject( m_iovt_start, + m_iovt_end, + record, + id.FixedId(), + m_tagt0[i]); + } + } + } + return true; + } + + +bool CoolInserter :: StoreRtChamber(const NtupleStationId & id, const std::map<int, SamplePoint> & points, const std::string & file, unsigned int creation_flags) + { + MsgStream log(msgSvc(), name()); +//generate fixed if for chamber + MuonFixedId fid(id.FixedId()); + if(!p_reg_sel_svc->isInRegion(fid)) + { + return true; + } +//check for duplicates + NtupleStationId id_cp(id); + bool found[3]; + for(int i=0; i<3; i++) + { + id_cp.SetMultilayer(i); + found[i]=(m_rt_filled.find(id_cp) != m_rt_filled.end()); + } + if (id.GetMl()==0) + { + if(found[0] || (found[1] && found[2])) + return true; + if(found[1]) + { + id_cp.SetMultilayer(2); + } + if(found[2]) + { + id_cp.SetMultilayer(1); + } + if(!found[1] && !found[2]) + { + id_cp.SetMultilayer(0); + } + } + if (id.GetMl()!=0) + { + if(found[0] || found[id.GetMl()]) + return true; + } + m_rt_filled.insert(id_cp); + if(m_cool_connect && !m_rt_created) + { + for(unsigned int i=0; i<m_rt_folder.size(); i++) + { + + if(!m_db->existsFolder(m_rt_folder[i])) + { + if(!create_folder(i, true)) + { + log << MSG::FATAL << "Cannot create folder '" << m_rt_folder[i] <<"'!"<<endreq; + return false; + } + } + m_mdtrt_fld.push_back(m_db->getFolder (m_rt_folder[i])); + m_mdtrt_fld[i]->setupStorageBuffer(); + + cool::RecordSpecification mdtrt_rec =(m_mdtrt_fld[i]->payloadSpecification()); + bool compressed(false); + if(m_compressed_rt.size()>i) + compressed=m_compressed_rt[i]; + m_mdtrt_cool_row[compressed] = cool::Record(mdtrt_rec).attributeList(); + } + m_rt_created = true; + } + std::ostringstream data_column; + data_column<<id_cp.FixedId()<<","<<points.size()<<std::endl; + for(std::map<int, SamplePoint> :: const_iterator it=points.begin(); it!=points.end(); it++) + { + data_column<<it->second.x2() << "," << it->second.x1() << "," << it->second.error() << ","; + } + if(m_rt_created) + { + std::cout<<"."<<std::flush; +// std::cout<<data_column.str()<<std::endl; + for(std::map<bool, coral::AttributeList> :: iterator it=m_mdtrt_cool_row.begin(); it!=m_mdtrt_cool_row.end(); it++) { + it->second["tech"].data<int>() = creation_flags; + it->second["file"].data<cool::String4k>() = file; + if(it->first) + { + uLongf dest_len = compressBound(data_column.str().size()); + coral::Blob &blob(it->second["data"].data<coral::Blob>()); + blob.resize(dest_len); + Bytef * p=static_cast<Bytef *>(blob.startingAddress()); + + compress(p, &dest_len, reinterpret_cast<const Bytef *>(data_column.str().c_str()), data_column.str().size()); + blob.resize(dest_len); + } + else + { + it->second["data"].data<cool::String16M>() = data_column.str(); + } + }//for(std::map<bool, coral::AttributeList> ... + for(unsigned int i=0; i<m_mdtrt_fld.size(); i++) + { + cool::ConstRecordAdapter record (m_mdtrt_fld[i]->payloadSpecification(), + m_mdtrt_cool_row[m_compressed_rt[i]]); + m_mdtrt_fld[i]->storeObject( m_iovt_start, + m_iovt_end, + record, + id_cp.FixedId(), + m_tagrt[i]); + } + } + return true; + } + +inline bool CoolInserter :: create_folder(const unsigned int & fldr_nr, const bool &is_rt) + { + std::string folder; + std::string description; + if (is_rt) + { + folder = m_rt_folder[fldr_nr]; + description = std::string("<timeStamp>run-lumi</timeStamp><addrHeader><address_header service_type=\"71\" clid=\"1238547719\" /></addrHeader><typeName>CondAttrListCollection</typeName><key>")+folder+"</key>"; + } + else + { + folder = m_t0_folder[fldr_nr]; + description = std::string("<timeStamp>run-lumi</timeStamp><addrHeader><address_header service_type=\"71\" clid=\"1238547719\" /></addrHeader><typeName>CondAttrListCollection</typeName><key>")+folder+"</key>"; + } + + bool compressed(false); + if (is_rt) + { + if(m_compressed_rt.size()>fldr_nr) + if (m_compressed_rt[fldr_nr]) + compressed=true; + } + else + { + std::cout<<"XXxxXX "<<m_compressed_t0.size() <<" "<<fldr_nr<<std::endl; + if(m_compressed_t0.size()>fldr_nr) + if (m_compressed_t0[fldr_nr]) + compressed=true; + } + cool::RecordSpecification spec; + spec.extend("tech",cool::StorageType::Int32); + if(compressed) + { + spec.extend("file",cool::StorageType::String255); + spec.extend("data",cool::StorageType::Blob64k); + } + else + { + spec.extend("file",cool::StorageType::String4k); + if(is_rt) + { + spec.extend("data", cool::StorageType::String4k); + } + else + { + spec.extend("data", cool::StorageType::String16M); + } + } + cool::FolderSpecification fspec (cool::FolderVersioning::MULTI_VERSION, + spec); + m_db->createFolder(folder, fspec, description, true); + return true; + } +} //namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/IConditionsStorage.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/IConditionsStorage.cxx new file mode 100644 index 0000000000000..35d174e637eb3 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/IConditionsStorage.cxx @@ -0,0 +1,43 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#include "MuonCalibDbOperations/IConditionsStorage.h" + +//MuonCalibIdentifier +#include "MuonCalibIdentifier/MuonFixedId.h" + + + +namespace MuonCalib { + +IConditionsStorage :: TubeId :: TubeId(int id_num) + { + MuonFixedId id(id_num); + ml=id.mdtMultilayer(); + ly=id.mdtTubeLayer(); + tb=id.mdtTube(); + } + +bool IConditionsStorage :: TubeId :: operator <(const IConditionsStorage :: TubeId &other) const + { + if(ml<other.ml) return true; + if(ml>other.ml) return false; + if(ly<other.ly) return true; + if(ly>other.ly) return false; + if(tb<other.tb) return true; + return false; + } + +bool IConditionsStorage :: TubeId :: operator >(const IConditionsStorage :: TubeId &other) const + { + if(ml>other.ml) return true; + if(ml<other.ml) return false; + if(ly>other.ly) return true; + if(ly<other.ly) return false; + if(tb>other.tb) return true; + return false; + } + + +} diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDbCalibrationSource.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDbCalibrationSource.cxx new file mode 100644 index 0000000000000..53275b8628674 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDbCalibrationSource.cxx @@ -0,0 +1,242 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/MuonCalibDbCalibrationSource.h" +#include "MuonCalibDbOperations/CalibDbConnection.h" +#include "MuonCalibDbOperations/CalibT0DbOperations.h" +#include "MuonCalibDbOperations/CalibRtDbOperations.h" +#include "MuonCalibDbOperations/CalibHeadOperations.h" +#include "MuonCalibDbOperations/CoolInserter.h" + +//coral +#include "CoralBase/AttributeList.h" +#include "CoralBase/Attribute.h" + +//MuonCalibIdentifier//MuonCalibIdentifier +#include "MuonCalibIdentifier/MuonFixedId.h" +#include "MuonCalibIdentifier/MdtCalibCreationFlags.h" + +//MuonCalibMath +#include "MuonCalibMath/SamplePoint.h" + +#include "GaudiKernel/MsgStream.h" +#include "GaudiKernel/IMessageSvc.h" +//MuonCalibStandALoneBase +#include "MuonCalibStandAloneBase/NtupleStationId.h" +#include "MuonCalibStandAloneBase/RegionSelectorBase.h" +//c - c++ +#include "iostream" +#include "sstream" +#include "exception" + +namespace MuonCalib { + +MuonCalibDbCalibrationSource :: MuonCalibDbCalibrationSource(const std::string& t, const std::string& n, const IInterface* p): IMuonCalibConditionsSource(), IConditionsStorage(), AlgTool(t, n, p) + { + declareInterface< IMuonCalibConditionsSource >(this); + declareProperty("SiteName", m_site_name); + declareProperty("HeadId", m_head_id); + declareProperty("ConnectionString", m_calib_connection_string); + declareProperty("WorkingSchema", m_calib_working_schema); + declareProperty("UserName", m_username); + declareProperty("Password", m_password); + declareProperty("Region", m_region_str); + m_mdt_tube_cols.push_back(std::string("TUBE_ID")); + m_mdt_tube_cols.push_back(std::string("P4")); + m_mdt_tube_cols.push_back(std::string("VALIDFLAG")); + m_mdt_tube_cols.push_back(std::string("ADC_1")); + m_store_t0=true; + m_store_rt=true; + declareProperty("StoreT0", m_store_t0); + declareProperty("StoreRT", m_store_rt); + m_t0_offset=0.0; + declareProperty("DriftTimeOffsetsVsR", m_drift_time_offsets); + declareProperty("T0Offset", m_t0_offset); + m_time_slewing_applied=false; + declareProperty("TimeSlewingApplied", m_time_slewing_applied); + m_b_field_correction_applied=false; + declareProperty("BFieldCorrectionApplied", m_b_field_correction_applied); + m_creation_flags=0; + } + + +StatusCode MuonCalibDbCalibrationSource :: initialize() + { + MsgStream log(msgSvc(), name()); +//process region + m_region = RegionSelectorBase::GetRegion(m_region_str); + if(m_region==NULL) + { + log<<MSG::FATAL<<"Error in regino string!"<<endreq; + return StatusCode::FAILURE; + } +//open conneciton to calibration db + m_connection = new CalibDbConnection(m_calib_connection_string, m_calib_working_schema); + m_connection->SetLogin(m_username, m_password); + if (!m_connection->OpenConnection()) + { + log << MSG::FATAL << "Cannot open connection to calibration database!" <<endreq; + return StatusCode::FAILURE; + } + m_head_ops=new CalibHeadOperations(*m_connection); + int lowrun, uprun, lowtime, uptime; + if(!m_head_ops->GetHeadInfo(m_head_id, lowrun, uprun, lowtime, uptime)) + { + log<<MSG::FATAL<<"Cannot get header "<<m_head_id << "from calib datbase"<<endreq; + return StatusCode::FAILURE; + } + m_iov_start = lowrun; + m_iov_end = uprun; + m_iov_end ++; + m_data_connection = m_head_ops->GetDataConnection(m_head_id, false); + if(m_data_connection==NULL) + { + log<<MSG::FATAL<<"Cannot open data connection!"<<endreq; + return StatusCode::FAILURE; + } + if(!m_data_connection->OpenConnection()) + { + log<<MSG::FATAL<<"Cannot open data connection!"<<endreq; + return StatusCode::FAILURE; + } + m_creation_flags=0; + if(m_time_slewing_applied) + m_creation_flags|=MuonCalib::TIME_SLEWING_CORRECTION_APPLIED; + if(m_b_field_correction_applied) + m_creation_flags|=MuonCalib::B_FIELD_CORRECTIONS_APPLIED; + return StatusCode::SUCCESS; + } + +StatusCode MuonCalibDbCalibrationSource :: finalize() + { + MsgStream log(msgSvc(), name()); + log << MSG::INFO << "finalizing "<<endreq; + try + { + m_connection->CloseConnection(); + m_data_connection->CloseConnection(); + if(m_head_ops!=NULL) + { + delete m_head_ops; + } + if(m_connection != NULL) + { + delete m_connection; + } + if(m_data_connection !=NULL) + { + delete m_data_connection; + } + } + catch(std::exception & e) + { + log << MSG::FATAL << "Exception in finalize: " << e.what() <<endreq; + return StatusCode :: FAILURE; + } + return StatusCode::SUCCESS; + } + + +bool MuonCalibDbCalibrationSource :: StoreT0Chamber(const int & chamber, const std::map<TubeId, coral::AttributeList> & rows) + { + MsgStream log(msgSvc(), name()); + MuonFixedId id(chamber); + if(!m_region->Result(id)) + { + return true; + } + NtupleStationId sid(id); + sid.SetMultilayer(0); + std::string data_string; + std::ostringstream f; + f<<chamber<<m_site_name<<m_head_id; + if (!m_inserter->StartT0Chamber(sid)) + { + log<< MSG::WARNING <<"Cannot insert chamber "<<chamber<<endreq; + return StatusCode::SUCCESS; + } + for(std::map<TubeId, coral::AttributeList> :: const_iterator it=rows.begin(); it!=rows.end(); it++) + { + if(!m_inserter->AppendT0(it->second["P4"].data<float>() + m_t0_offset, it->second["VALIDFLAG"].data<short>(), it->second["ADC_1"].data<float>())) + { + log << MSG::WARNING << "Wrong number of tubes in database for " << sid.regionId() << "!" <<endreq; + break; + } + } + m_inserter->StoreT0Chamber(sid, f.str(), m_creation_flags); + return StatusCode::SUCCESS; + } + + +bool MuonCalibDbCalibrationSource :: StoreRtChamber(const int & chamber, const std::map<int, SamplePoint> & points) + { + MuonFixedId id(chamber); + if(!m_region->Result(id)) + { + return true; + } + NtupleStationId sid(id); + sid.SetMultilayer(0); + std::ostringstream f; + f<<chamber<<m_site_name<<m_head_id; + if (m_drift_time_offsets.size()) + { + float slice_width=14.6/static_cast<float>(m_drift_time_offsets.size()); + std::map<int, SamplePoint> points_cp(points); + for(std::map<int, SamplePoint>::iterator it=points_cp.begin(); it!=points_cp.end(); it++) + { + int slice_number=static_cast<int>(std::floor(it->second.x2()/slice_width)); + if (slice_number<0) + slice_number=0; + if (slice_number >= static_cast<int>(m_drift_time_offsets.size())) + slice_number = static_cast<int>(m_drift_time_offsets.size()) - 1; + it->second.set_x1(it->second.x1() + m_drift_time_offsets[slice_number]); + } + m_inserter->StoreRtChamber(sid, points_cp, f.str(), m_creation_flags); + } + else + { + m_inserter->StoreRtChamber(sid, points, f.str(), m_creation_flags); + } + return StatusCode::SUCCESS; + } + + +bool MuonCalibDbCalibrationSource :: insert_calibration( bool store_t0, bool store_rt) + { + MsgStream log(msgSvc(), name()); + try{ + if(store_t0 && m_store_t0) + { + CalibT0DbOperations t0_op(*m_data_connection); + if(!t0_op.ReadForConditions(m_site_name, m_head_id, *this)) + { + log << MSG::FATAL <<"T0 insert failed!" << endreq; + return false; + } + } + if(store_rt&& m_store_rt) + { + CalibRtDbOperations rt_op(*m_data_connection); + if(!rt_op.ReadForConditions(m_site_name, m_head_id, *this)) + { + log << MSG::FATAL <<"RT insert failed!" << endreq; + return false; + } + } + } //try + catch(std::exception & e) + { + log << MSG::FATAL << "Exception: " << e.what() <<endreq; + return false; + } + return true; + + } + + + + +}//namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDefaultCalibrationSource.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDefaultCalibrationSource.cxx new file mode 100644 index 0000000000000..fd84b88c10874 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/MuonCalibDefaultCalibrationSource.cxx @@ -0,0 +1,203 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//this +#include "MuonCalibDbOperations/MuonCalibDefaultCalibrationSource.h" +#include "MuonCalibDbOperations/CoolInserter.h" + +//MuonCalibStandAloneBase +#include "MuonCalibStandAloneBase/RegionSelectorBase.h" +#include "MuonCalibStandAloneBase/RegionSelectionSvc.h" + +//MuonCalibMath +#include "MuonCalibMath/SamplePoint.h" + +//MuonCalibIdentifier//MuonCalibIdentifier +#include "MuonCalibIdentifier/MdtCalibCreationFlags.h" + +//c-c++ +#include <fstream> +#include <sstream> + +namespace MuonCalib { + +MuonCalibDefaultCalibrationSource :: MuonCalibDefaultCalibrationSource(const std::string& t, const std::string& n, const IInterface* p): AlgTool(t, n, p) + { + declareInterface< IMuonCalibConditionsSource >(this); + declareProperty("T0Regions", m_t0_region_str); + declareProperty("T0", m_t0); + declareProperty("TimeSlewingAppliedT0", m_time_slewing_applied_t0); + declareProperty("BFieldCorrectionAppliedT0", m_bfield_applied_t0); + declareProperty("RtRegions", m_rt_region_str); + declareProperty("RtFiles", m_rt_files); + declareProperty("TimeSlewingAppliedRt", m_time_slewing_applied_rt); + declareProperty("BFieldCorrectionAppliedRt", m_bfield_applied_rt); + } + + +StatusCode MuonCalibDefaultCalibrationSource :: initialize() + { + MsgStream log(msgSvc(), name()); +//get region selection service + StatusCode sc=service("RegionSelectionSvc", p_reg_sel_svc); + if(!sc.isSuccess()) + { + log << MSG::ERROR <<"Cannot retrieve RegionSelectionSvc!" <<endreq; + return sc; + } +//check matching lengths + if(m_t0_region_str.size() != m_t0.size()) + { + log << MSG::FATAL << "Configuration error: T0Regions and T0 have different size!" << endreq; + return StatusCode::FAILURE; + } + if(m_rt_region_str.size() != m_rt_files.size()) + { + log << MSG::FATAL << "Configuration error: RtRegions and RtFiles have different size!" << endreq; + return StatusCode::FAILURE; + } +//initialize regions + sc=initialize_regions(m_t0_region_str, m_t0_regions); + if(!sc.isSuccess()) + { + return sc; + } + initialize_creation_flags(m_time_slewing_applied_t0, m_bfield_applied_t0, m_t0_regions.size(), m_creation_flags_t0); + sc=initialize_regions(m_rt_region_str, m_rt_regions); + if(!sc.isSuccess()) + { + return sc; + } + initialize_creation_flags(m_time_slewing_applied_rt, m_bfield_applied_rt, m_rt_regions.size(), m_creation_flags_rt); +//load rt files + sc=load_rt_files(); + return sc; + } + + +bool MuonCalibDefaultCalibrationSource :: insert_calibration(bool store_t0, bool store_rt) + { + if (store_t0) + { + if(!store_t0_fun()) + return false; + } + if (store_rt) + { + if(!store_rt_fun()) + return false; + } + return true; + } + + +StatusCode MuonCalibDefaultCalibrationSource :: initialize_regions(const std::vector<std::string> ®_str, std::vector<RegionSelectorBase *> & reg) + { + MsgStream log(msgSvc(), name()); + for(std::vector<std::string> :: const_iterator it=reg_str.begin(); it!=reg_str.end(); it++) + { + RegionSelectorBase * r(RegionSelectorBase::GetRegion(*it)); + if(r==NULL) + { + log<<MSG::FATAL<<"Error in region "<<*it<<endreq; + return StatusCode::FAILURE; + } + reg.push_back(r); + } + return StatusCode::SUCCESS; + } + +void MuonCalibDefaultCalibrationSource :: initialize_creation_flags(const std::vector<bool> & ts_applied, const std::vector<bool> & bf_applied, unsigned int n_regions, std::vector<unsigned int> & flags) + { + for(unsigned int i=0; i<n_regions; i++) + { + unsigned int flag(0); + if(i<ts_applied.size() && ts_applied[i]) + { + flag|=MuonCalib::TIME_SLEWING_CORRECTION_APPLIED; + } + if(i<bf_applied.size() && bf_applied[i]) + { + flag|=MuonCalib::B_FIELD_CORRECTIONS_APPLIED; + } + flags.push_back(flag); + } + } + +inline StatusCode MuonCalibDefaultCalibrationSource :: load_rt_files() + { + MsgStream log(msgSvc(), name()); + for(std::vector<std::string> :: const_iterator it=m_rt_files.begin(); it!= m_rt_files.end(); it++) + { + const std::string &fname(*it); + std::string line; + std::ifstream rtf(fname.c_str()); + if(!rtf.good()) + { + log<<MSG::FATAL<<"Cannot open rt file '" <<fname<< "'!" <<endreq; + return StatusCode::FAILURE; + } + std::map<int, SamplePoint> pts; +//read dummy line + std::getline(rtf, line); + int i(0); + while (!rtf.eof()) + { + std::getline(rtf, line); + std::istringstream ln_str(line); + double r,t,s; + ln_str>>r; + ln_str>>t; + ln_str>>s; + if(rtf.eof()) + break; + SamplePoint pt(t,r,s); + pts[i]=pt; + i++; + } + m_rt_points.push_back(pts); + } + return StatusCode::SUCCESS; + } + +inline bool MuonCalibDefaultCalibrationSource :: store_t0_fun() + { + const std::vector<NtupleStationId> ®ions( p_reg_sel_svc->GetStationsInRegions()); + for(std::vector<NtupleStationId> :: const_iterator it=regions.begin(); it!= regions.end(); it++) + { + MuonFixedId fid(it->FixedId()); + for(unsigned int i=0; i<m_t0_regions.size(); i++) + { + if(m_t0_regions[i]->Result(fid)) + { + m_inserter->StartT0Chamber(*it); + while(m_inserter->AppendT0(m_t0[i], 5, 0.0)) {} + m_inserter->StoreT0Chamber(*it, std::string("default"), m_creation_flags_t0[i]); +// break; + } + } + } + return true; + } + +inline bool MuonCalibDefaultCalibrationSource :: store_rt_fun() + { + const std::vector<NtupleStationId> ®ions( p_reg_sel_svc->GetStationsInRegions()); + for(std::vector<NtupleStationId> :: const_iterator it=regions.begin(); it!= regions.end(); it++) + { + MuonFixedId fid(it->FixedId()); + for(unsigned int i=0; i<m_rt_regions.size(); i++) + { + if(m_rt_regions[i]->Result(fid)) + { + m_inserter->StoreRtChamber(*it, m_rt_points[i], std::string("default"), m_creation_flags_rt[i]); + break; + } + } + } + return true; + } + + +} //namespace MuonCalib diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_entries.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_entries.cxx new file mode 100644 index 0000000000000..5ffbc7a0d83e3 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_entries.cxx @@ -0,0 +1,24 @@ +#include "GaudiKernel/DeclareFactoryEntries.h" +#include "MuonCalibDbOperations/CalibrationDbIOTool.h" +#include "MuonCalibDbOperations/CoolInserter.h" +#include "MuonCalibDbOperations/MuonCalibDbCalibrationSource.h" +#include "MuonCalibDbOperations/MuonCalibDefaultCalibrationSource.h" + + +using namespace MuonCalib; + +DECLARE_TOOL_FACTORY ( CalibrationDbIOTool ) +DECLARE_TOOL_FACTORY ( MuonCalibDbCalibrationSource ) +DECLARE_TOOL_FACTORY ( MuonCalibDefaultCalibrationSource ) + +DECLARE_FACTORY_ENTRIES(MuonCalibDbOperations) { + DECLARE_TOOL(CalibrationDbIOTool) + DECLARE_TOOL(MuonCalibDbCalibrationSource) + DECLARE_TOOL(MuonCalibDefaultCalibrationSource) +} + +DECLARE_ALGORITHM_FACTORY ( CoolInserter ) + +DECLARE_FACTORY_ENTRIES( CoolInserter ) { + DECLARE_TOOL(CoolInserter) +} diff --git a/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_load.cxx b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_load.cxx new file mode 100644 index 0000000000000..add89ad104c30 --- /dev/null +++ b/MuonSpectrometer/MuonCalib/MuonCalibDbOperations/src/components/MuonCalibDbOperations_load.cxx @@ -0,0 +1,3 @@ +#include "GaudiKernel/LoadFactoryEntries.h" + +LOAD_FACTORY_ENTRIES(MuonCalibDbOperations) -- GitLab