id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,534,330
|
config.h
|
ppLorins_aurora/src/config/config.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef _AURORA_CONFIG_H_
#define _AURORA_CONFIG_H_
#include "gflags/gflags.h"
namespace RaftCore::Config {
//Service config.
DECLARE_uint32(notify_cq_num);
DECLARE_uint32(notify_cq_threads);
DECLARE_uint32(call_cq_num);
DECLARE_uint32(call_cq_threads);
DECLARE_uint32(client_thread_num);
DECLARE_uint32(request_pool_size);
//Common config
DECLARE_string(ip);
DECLARE_uint32(port);
DECLARE_uint32(lockfree_queue_resync_log_elements);
DECLARE_uint32(lockfree_queue_resync_data_elements);
DECLARE_uint32(lockfree_queue_client_react_elements);
DECLARE_uint32(lockfree_queue_consumer_wait_ms);
DECLARE_uint32(lockfree_queue_consumer_threads_num);
DECLARE_uint32(list_op_tracker_hash_slot_num);
DECLARE_uint32(timer_precision_ms);
DECLARE_uint32(thread_stop_waiting_us);
DECLARE_uint32(gc_interval_ms);
DECLARE_uint32(garbage_deque_retain_num);
DECLARE_uint32(iterating_threads);
DECLARE_uint32(iterating_wait_timeo_us);
//Guid
DECLARE_uint32(guid_step_len);
DECLARE_uint32(guid_disk_random_write_hint_ms);
//Binlog config
DECLARE_uint32(binlog_meta_hash_buf_size);
DECLARE_uint32(binlog_max_size);
DECLARE_uint32(binlog_max_log_num);
DECLARE_uint32(binlog_parse_buf_size);
DECLARE_uint32(binlog_append_file_timeo_us);
DECLARE_uint32(binlog_reserve_log_num);
//leader config --> follower entity
DECLARE_uint32(leader_heartbeat_rpc_timeo_ms);
DECLARE_uint32(leader_append_entries_rpc_timeo_ms);
DECLARE_uint32(leader_commit_entries_rpc_timeo_ms);
DECLARE_uint32(leader_resync_log_rpc_timeo_ms);
DECLARE_uint32(leader_heartbeat_interval_ms);
DECLARE_uint32(leader_last_log_resolve_additional_wait_ms);
//leader config --> connection pool
DECLARE_uint32(conn_per_link);
DECLARE_uint32(channel_pool_size);
DECLARE_uint32(client_pool_size);
//leader config --> resync log
DECLARE_uint32(resync_log_reverse_step_len);
//leader config --> resync data
DECLARE_uint32(resync_data_item_num_each_rpc);
DECLARE_uint32(resync_data_log_num_each_rpc);
DECLARE_uint32(resync_data_task_max_time_ms);
//leader config --> optimization
DECLARE_uint32(group_commit_count);
//leader config --> cutempty
DECLARE_uint32(cut_empty_timeos_ms);
//follower config
DECLARE_uint32(follower_check_heartbeat_interval_ms);
DECLARE_uint32(disorder_msg_timeo_ms);
//For CGG problem
DECLARE_uint32(cgg_wait_for_last_released_guid_finish_us);
//For election.
DECLARE_uint32(election_heartbeat_timeo_ms);
DECLARE_uint32(election_term_interval_min_ms);
DECLARE_uint32(election_term_interval_max_ms);
DECLARE_uint32(election_vote_rpc_timeo_ms);
DECLARE_uint32(election_non_op_timeo_ms);
DECLARE_uint32(election_wait_non_op_finish_ms);
//For membership change.
DECLARE_uint32(memchg_sync_data_wait_seconds);
DECLARE_uint32(memchg_rpc_timeo_ms);
//For Storage.
DECLARE_uint32(memory_table_max_item);
DECLARE_uint32(memory_table_hash_slot_num);
DECLARE_uint32(sstable_table_hash_slot_num);
DECLARE_uint32(sstable_purge_interval_second);
//For unit test.
DECLARE_uint32(child_glog_v);
DECLARE_uint32(election_thread_wait_us);
DECLARE_bool(do_heartbeat);
DECLARE_bool(heartbeat_oneshot);
DECLARE_bool(member_leader_gone);
DECLARE_uint32(concurrent_client_thread_num);
DECLARE_bool(enable_sstable_gc);
DECLARE_bool(checking_heartbeat);
DECLARE_uint32(append_entries_start_idx);
DECLARE_bool(clear_existing_sstable_files);
DECLARE_uint32(hash_slot_num);
DECLARE_uint32(resync_log_start_idx);
DECLARE_uint32(deque_op_count);
DECLARE_uint32(meta_count);
DECLARE_uint32(follower_svc_benchmark_req_round);
DECLARE_uint32(leader_svc_benchmark_req_count);
DECLARE_uint32(benchmark_client_cq_num);
DECLARE_uint32(benchmark_client_polling_thread_num_per_cq);
DECLARE_uint32(benchmark_client_entrusting_thread_num);
DECLARE_uint32(client_write_timo_ms);
DECLARE_string(target_ip);
DECLARE_string(my_ip);
DECLARE_uint32(storage_get_slice_count);
DECLARE_uint32(retain_num_unordered_single_list);
DECLARE_bool(do_commit);
DECLARE_uint32(value_len);
DECLARE_uint32(client_count);
DECLARE_uint32(launch_threads_num);
DECLARE_uint32(queue_initial_size);
DECLARE_uint32(queue_op_count);
DECLARE_uint32(conn_op_count);
}
#endif
| 5,292
|
C++
|
.h
| 126
| 37.436508
| 73
| 0.737006
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,331
|
state_mgr.h
|
ppLorins_aurora/src/state/state_mgr.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_STATE_MGR_H__
#define __AURORA_STATE_MGR_H__
#include <list>
#include "topology/topology_mgr.h"
namespace RaftCore::State {
enum class RaftRole{ UNKNOWN , //Init state
LEADER, //Raft Leader
CANDIDATE , //Raft Candidate
FOLLOWER , //Raft Follower
};
class StateMgr final{
public:
static void Initialize(const ::RaftCore::Topology &global_topo) noexcept;
static void UnInitialize() noexcept;
static bool Ready() noexcept;
static RaftRole GetRole() noexcept;
static const char* GetRoleStr(RaftRole state=RaftRole::UNKNOWN) noexcept;
static void SwitchTo(RaftRole state,const std::string &new_leader="") noexcept;
static const std::string& GetMyAddr() noexcept;
static const std::list<std::string>& GetNICAddrs() noexcept;
static void SetMyAddr(const std::string& addr) noexcept;
static bool AddressUndetermined() noexcept;
private:
StateMgr() = delete;
virtual ~StateMgr() noexcept = delete;
StateMgr(const StateMgr &) = delete;
StateMgr& operator=(const StateMgr &) = delete;
private:
/* For the 'm_cur_state' variable ,multiple thread reading, one thread blind-writing, no need to lock.
Yeah , hopefully things like EMSI protocol can keep CPU caches from being inconsistent.
I believe it anyway. */
static RaftRole m_cur_state;
static bool m_initialized;
static std::string m_my_addr;
static std::list<std::string> m_nic_addrs;
};
std::ostream& operator<<(std::ostream& os, const RaftRole& obj);
}
#endif
| 2,439
|
C++
|
.h
| 54
| 40.166667
| 106
| 0.703704
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,332
|
topology_mgr.h
|
ppLorins_aurora/src/topology/topology_mgr.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_TOPOLOGY_H__
#define __AURORA_TOPOLOGY_H__
#include <iostream>
#include <fstream>
#include <set>
#include <string>
#include <shared_mutex>
#define _AURORA_TOPOLOGY_CONFFIG_FILE_ "topology.config"
namespace RaftCore{
struct Topology {
std::string m_leader = "";
std::set<std::string> m_followers;
std::set<std::string> m_candidates;
std::string m_my_addr = "";
Topology()noexcept;
void Reset()noexcept;
uint32_t GetClusterSize() const noexcept;
bool InCurrentCluster(const std::string &node) noexcept;
};
std::ostream& operator<<(std::ostream& os, const Topology& obj);
class CTopologyMgr final{
public:
static void Initialize() noexcept;
static void UnInitialize() noexcept;
static void Update(const Topology &input) noexcept;
static void Read(Topology *p_output=nullptr) noexcept;
private:
static bool Load() noexcept;
private:
static Topology m_ins;
static std::fstream m_file_stream;
static std::shared_timed_mutex m_mutex;
private:
CTopologyMgr() = delete;
virtual ~CTopologyMgr() noexcept = delete;
CTopologyMgr(const CTopologyMgr&) = delete;
CTopologyMgr& operator=(const CTopologyMgr&) = delete;
};
}
#endif
| 2,089
|
C++
|
.h
| 55
| 34.890909
| 73
| 0.714857
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,333
|
guid_generator.h
|
ppLorins_aurora/src/guid/guid_generator.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _AURORA_GUID_GENERATOR_H_
#define _AURORA_GUID_GENERATOR_H_
#include <atomic>
#define _GUID_ERR_ (0xFFFFFFFFFFFFFFFF)
namespace RaftCore::Guid {
class GuidGenerator final {
public:
struct GUIDPair {
//2^64 is 18446744073709551616,which can satisfy 1M/s requests for 584942 years.
uint64_t m_pre_guid; //Based on which the allocated guid is generated
uint64_t m_cur_guid; //Allocated guid
bool operator<(const GUIDPair &other) const noexcept {
return this->m_cur_guid < other.m_cur_guid;
}
};
public:
static void Initialize(uint64_t last_released=0) noexcept;
static void UnInitialize() noexcept;
static GUIDPair GenerateGuid() noexcept;
//Set m_last_released_guid to the given id , for fail recovery purpose.
static void SetNextBasePoint(uint64_t base_point) noexcept;
static uint64_t GetLastReleasedGuid() noexcept;
private:
static std::atomic<uint64_t> m_last_released_guid;
private:
GuidGenerator() = delete;
virtual ~GuidGenerator() = delete;
GuidGenerator(const GuidGenerator&) = delete;
GuidGenerator& operator=(const GuidGenerator&) = delete;
};
}
#endif
| 1,984
|
C++
|
.h
| 46
| 39.26087
| 88
| 0.728796
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,334
|
member_manager.h
|
ppLorins_aurora/src/member/member_manager.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_MEMBER_MANAGER_H__
#define __AURORA_MEMBER_MANAGER_H__
#include <unordered_map>
#include <shared_mutex>
#include <set>
#include "protocol/raft.pb.h"
#include "common/comm_defs.h"
#include "leader/follower_entity.h"
#include "leader/leader_bg_task.h"
#define _AURORA_MEMBER_CONFIG_FILE_ "membership-change.config"
namespace RaftCore::Member {
using ::raft::MemberChangeInnerRequest;
using ::RaftCore::Leader::TypePtrFollowerEntity;
using ::RaftCore::Leader::BackGroundTask::TwoPhaseCommitContext;
using ::RaftCore::Common::PhaseID;
using ::RaftCore::Common::TwoPhaseCommitBatchTask;
class MemberMgr final {
public:
struct JointTopology {
const JointTopology& operator=(const JointTopology &one);
const JointTopology& operator=(JointTopology &&one);
void Reset()noexcept;
void Update(const std::set<std::string> * p_new_cluster=nullptr)noexcept;
std::set<std::string> m_new_cluster;
//Treat all new nodes all followers first.
std::unordered_map<std::string,TypePtrFollowerEntity> m_added_nodes;
std::set<std::string> m_removed_nodes;
bool m_leader_gone_away;
std::string m_old_leader;
};
struct JointSummary {
void Reset()noexcept;
EJointStatus m_joint_status;
JointTopology m_joint_topology;
//Increased monotonously,never go back.
uint32_t m_version;
};
class MemberChangeContext final : public TwoPhaseCommitContext{};
public:
static void Initialize() noexcept;
static void UnInitialize() noexcept;
static void ResetMemchgEnv() noexcept;
static const char* PullTrigger(const std::set<std::string> &new_cluster)noexcept;
static void SwitchToJointConsensus(JointTopology &updated_topo,uint32_t version=_MAX_UINT32_)noexcept;
static bool SwitchToStable()noexcept;
static std::string FindPossibleAddress(const std::list<std::string> &nic_addrs)noexcept;
static uint32_t GetVersion()noexcept;
static void MemberChangePrepareCallBack(const ::grpc::Status &status,
const ::raft::MemberChangeInnerResponse& rsp, void* ptr_follower, uint32_t idx)noexcept;
static void MemberChangeCommitCallBack(const ::grpc::Status &status,
const ::raft::MemberChangeInnerResponse& rsp, void* ptr_follower, uint32_t idx)noexcept;
static void Statistic(const ::grpc::Status &status,
const ::raft::MemberChangeInnerResponse& rsp, void* ptr_follower, uint32_t joint_flag,
PhaseID phase_id) noexcept;
#ifdef _MEMBER_MANAGEMENT_TEST_
static void PendingExecution()noexcept;
static void ContinueExecution()noexcept;
#endif
typedef std::shared_ptr<MemberChangeInnerRequest> TypePtrMemberChangReq;
public:
/*Not persisted.If leader crashes, the new elected leader takes the responsibilities to continue. */
static JointSummary m_joint_summary;
static std::shared_timed_mutex m_mutex;
//No multi threads accessing, no lock for this.
static MemberChangeContext m_memchg_ctx;
private:
#ifdef _MEMBER_MANAGEMENT_TEST_
static bool m_execution_flag;
#endif
static void PollingCQ(std::shared_ptr<::grpc::CompletionQueue> shp_cq,int entrust_num)noexcept;
static void LoadFile() noexcept;
static void SaveFile() noexcept;
//The callback function used to notify a node are fully synced event.
static void NotifyOnSynced(TypePtrFollowerEntity &shp_follower) noexcept;
//The main logic of membership-change after all nodes synced.
static void Routine() noexcept;
inline static const char* MacroToString(EJointStatus enum_val) noexcept;
inline static EJointStatus StringToMacro(const char* src) noexcept;
static bool PropagateMemberChange(TypePtrMemberChangReq& shp_req, PhaseID phase_id) noexcept;
static void WaitForSyncDataDone() noexcept;
private:
//A temporary variable used for further switching.
static JointTopology m_joint_topo_snapshot;
//CV used for notifying resync-data completion in membership change phase.
static std::condition_variable m_resync_data_cv;
static std::mutex m_resync_data_cv_mutex;
static std::atomic<bool> m_in_processing;
static TwoPhaseCommitBatchTask<TypePtrFollowerEntity> m_phaseI_task;
static TwoPhaseCommitBatchTask<TypePtrFollowerEntity> m_phaseII_task;
static const char* m_macro_names[];
private:
MemberMgr() = delete;
virtual ~MemberMgr() noexcept = delete;
MemberMgr(const MemberMgr&) = delete;
MemberMgr& operator=(const MemberMgr&) = delete;
};
} //end namespace
#endif
| 5,510
|
C++
|
.h
| 113
| 44.017699
| 106
| 0.73525
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,335
|
candidate_request.h
|
ppLorins_aurora/src/candidate/candidate_request.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_CANDIDATE_REQUEST_H__
#define __AURORA_CANDIDATE_REQUEST_H__
#include <memory>
#include "protocol/raft.grpc.pb.h"
#include "protocol/raft.pb.h"
#include "common/request_base.h"
using ::raft::RaftService;
using ::grpc::ServerCompletionQueue;
using ::RaftCore::Common::UnaryRequest;
namespace RaftCore::Candidate {
template<typename T,typename R,typename Q>
class CandidateUnaryRequest : public UnaryRequest<T, R, Q> {
public:
CandidateUnaryRequest()noexcept;
virtual ~CandidateUnaryRequest()noexcept;
private:
CandidateUnaryRequest(const CandidateUnaryRequest&) = delete;
CandidateUnaryRequest& operator=(const CandidateUnaryRequest&) = delete;
};
} //end namespace
#include "candidate_request.cc"
#endif
| 1,540
|
C++
|
.h
| 37
| 39.648649
| 76
| 0.769386
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,336
|
candidate_view.h
|
ppLorins_aurora/src/candidate/candidate_view.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_CANDIDATE_VIEW_H__
#define __AURORA_CANDIDATE_VIEW_H__
#include <memory>
#include <shared_mutex>
#include "common/comm_view.h"
namespace RaftCore::Candidate {
using ::RaftCore::Common::CommonView;
//CandidateView is nothing inside, all logic in candidate is in the `Election` module.
class CandidateView final: public CommonView{
public:
static void Initialize() noexcept;
static void UnInitialize() noexcept;
private:
CandidateView() = delete;
virtual ~CandidateView() = delete;
CandidateView(const CandidateView&) = delete;
CandidateView& operator=(const CandidateView&) = delete;
};
} //end namespace
#endif
| 1,457
|
C++
|
.h
| 35
| 39.342857
| 87
| 0.753747
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,337
|
global_env.h
|
ppLorins_aurora/src/global/global_env.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_GLOBAL_ENV_H__
#define __AURORA_GLOBAL_ENV_H__
#include <thread>
#include "grpc++/server_builder.h"
#include "grpc++/server.h"
#include "grpc++/completion_queue.h"
#include "protocol/raft.grpc.pb.h"
#include "state/state_mgr.h"
#include "common/react_base.h"
#include "common/react_group.h"
namespace RaftCore::Global {
using ::grpc::CompletionQueue;
using ::RaftCore::Common::TypePtrCQ;
using ::RaftCore::Common::TypeReactorFunc;
using ::RaftCore::Common::ReactWorkGroup;
/*Note: This is the class for representing follower's state in follower's own view. */
class GlobalEnv final {
public:
static void InitialEnv(bool switching_role=false) noexcept;
static void RunServer() noexcept;
static void StopServer() noexcept;
static void UnInitialEnv(::RaftCore::State::RaftRole state=::RaftCore::State::RaftRole::UNKNOWN) noexcept;
//Note : Must called in other threads , not in any gRPC threads.
static void ShutDown() noexcept;
static bool IsRunning() noexcept;
static TypePtrCQ<CompletionQueue> GetClientCQInstance(uint32_t idx) noexcept;
static std::vector<ReactWorkGroup<>> m_vec_notify_cq_workgroup;
private:
static void InitGrpcEnv() noexcept;
static void StartGrpcService() noexcept;
static void SpawnFamilyBucket(std::shared_ptr<::raft::RaftService::AsyncService> shp_svc, std::size_t cq_idx) noexcept;
static void StopGrpcService() noexcept;
private:
static std::unique_ptr<::grpc::Server> m_pserver;
static volatile bool m_running;
static volatile bool m_cq_fully_shutdown;
static std::vector<ReactWorkGroup<>> m_vec_call_cq_workgroup;
static std::vector<ReactWorkGroup<CompletionQueue>> m_vec_client_cq_workgroup;
static std::shared_ptr<::raft::RaftService::AsyncService> m_async_service;
static std::string m_server_addr;
static ::grpc::ServerBuilder m_builder;
private:
GlobalEnv() = delete;
virtual ~GlobalEnv() noexcept = delete;
GlobalEnv(const GlobalEnv&) = delete;
GlobalEnv& operator=(const GlobalEnv&) = delete;
};
} //end namespace
#endif
| 2,929
|
C++
|
.h
| 64
| 42.53125
| 123
| 0.742381
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,338
|
memory_log_follower.h
|
ppLorins_aurora/src/follower/memory_log_follower.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef _AURORA_MEMORY_LOG_FOLLOWER_H_
#define _AURORA_MEMORY_LOG_FOLLOWER_H_
#include <ostream>
#include "protocol/raft.pb.h"
#include "tools/trivial_lock_double_list.h"
#include "common/memory_log_base.h"
using ::RaftCore::Common::MemoryLogItemBase;
using ::RaftCore::Common::EntityIDEqual;
using ::RaftCore::Common::EntityIDSmallerEqual;
namespace RaftCore::Follower {
class MemoryLogItemFollower final : public ::RaftCore::DataStructure::OrderedTypeBase<MemoryLogItemFollower> , public MemoryLogItemBase {
public:
virtual ~MemoryLogItemFollower() noexcept;
MemoryLogItemFollower(uint32_t _term, uint64_t _index) noexcept;
MemoryLogItemFollower(const ::raft::Entity &_entity) noexcept;
bool operator<=(const MemoryLogItemFollower& _other)const noexcept;
virtual bool operator<(const MemoryLogItemFollower& _other)const noexcept;
virtual bool operator>(const MemoryLogItemFollower& _other)const noexcept;
virtual bool operator==(const MemoryLogItemFollower& _other)const noexcept;
virtual bool operator!=(const MemoryLogItemFollower& _other)const noexcept;
protected:
virtual void NotImplemented() noexcept{}
};
typedef std::list<std::shared_ptr<MemoryLogItemFollower>> TypeMemlogFollowerList;
bool CmpMemoryLogFollower(const MemoryLogItemFollower& left, const MemoryLogItemFollower& right) noexcept;
}
#endif
| 2,161
|
C++
|
.h
| 42
| 48.952381
| 137
| 0.784417
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,339
|
follower_bg_task.h
|
ppLorins_aurora/src/follower/follower_bg_task.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_FOLLOWER_BG_TASK_H__
#define __AURORA_FOLLOWER_BG_TASK_H__
#include "tools/utilities.h"
#include "tools/trivial_lock_double_list.h"
namespace RaftCore {
namespace Service {
class AppendEntries;
}
}
namespace RaftCore::Follower::BackGroundTask {
using ::RaftCore::DataStructure::OrderedTypeBase;
using ::RaftCore::Tools::TypeSysTimePoint;
using ::RaftCore::Service::AppendEntries;
class DisorderMessageContext final : public OrderedTypeBase<DisorderMessageContext> {
public:
DisorderMessageContext(int value_flag = 0)noexcept;
virtual ~DisorderMessageContext()noexcept;
virtual bool operator<(const DisorderMessageContext& other)const noexcept override;
virtual bool operator>(const DisorderMessageContext& other)const noexcept override;
virtual bool operator==(const DisorderMessageContext& other)const noexcept override;
std::shared_ptr<AppendEntries> m_append_request;
TypeSysTimePoint m_generation_tp;
/*<0: minimal value;
>0:max value;
==0:comparable value. */
int m_value_flag = 0;
std::atomic<bool> m_processed_flag;
};
} //end namespace
#endif
| 2,004
|
C++
|
.h
| 45
| 40.377778
| 92
| 0.734641
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,340
|
follower_request.h
|
ppLorins_aurora/src/follower/follower_request.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_FOLLOWER_REQUEST_H__
#define __AURORA_FOLLOWER_REQUEST_H__
#include <memory>
#include "protocol/raft.grpc.pb.h"
#include "protocol/raft.pb.h"
#include "common/request_base.h"
using ::raft::RaftService;
using ::grpc::ServerCompletionQueue;
using ::RaftCore::Common::UnaryRequest;
using ::RaftCore::Common::BidirectionalRequest;
namespace RaftCore::Follower {
//Just a thin wrapper for differentiate rpcs.
template<typename T,typename R,typename Q>
class FollowerUnaryRequest : public UnaryRequest<T,R,Q>{
public:
FollowerUnaryRequest()noexcept;
virtual ~FollowerUnaryRequest()noexcept;
private:
FollowerUnaryRequest(const FollowerUnaryRequest&) = delete;
FollowerUnaryRequest& operator=(const FollowerUnaryRequest&) = delete;
};
template<typename T,typename R,typename Q>
class FollowerBidirectionalRequest : public BidirectionalRequest<T,R,Q>{
public:
FollowerBidirectionalRequest()noexcept;
virtual ~FollowerBidirectionalRequest()noexcept;
private:
FollowerBidirectionalRequest(const FollowerBidirectionalRequest&) = delete;
FollowerBidirectionalRequest& operator=(const FollowerBidirectionalRequest&) = delete;
};
} //end namespace
#include "follower_request.cc"
#endif
| 2,033
|
C++
|
.h
| 48
| 40.083333
| 90
| 0.785276
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,341
|
follower_view.h
|
ppLorins_aurora/src/follower/follower_view.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_FOLLOWER_VIEW_H__
#define __AURORA_FOLLOWER_VIEW_H__
#include <memory>
#include <shared_mutex>
#include "common/comm_defs.h"
#include "common/comm_view.h"
#include "follower/memory_log_follower.h"
#include "follower/follower_bg_task.h"
#include "tools/trivial_lock_double_list.h"
#include "tools/trivial_lock_single_list.h"
namespace RaftCore::Follower {
using ::RaftCore::Common::CommonView;
using ::RaftCore::Follower::MemoryLogItemFollower;
using ::RaftCore::Follower::BackGroundTask::DisorderMessageContext;
using ::RaftCore::DataStructure::LockFreeUnorderedSingleList;
using ::RaftCore::DataStructure::SingleListNode;
using ::RaftCore::DataStructure::TrivialLockSingleList;
using ::RaftCore::DataStructure::DoubleListNode;
using ::RaftCore::DataStructure::TrivialLockDoubleList;
/*Note: This is the class for representing follower's state in follower's own view. */
class FollowerView final: public CommonView{
public:
//Pending log entries waiting to be written into binlog file.
static TrivialLockDoubleList<MemoryLogItemFollower> m_phaseI_pending_list;
//Pending log entries waiting to be stored.
static TrivialLockDoubleList<MemoryLogItemFollower> m_phaseII_pending_list;
static LockFreeUnorderedSingleList<DoubleListNode<MemoryLogItemFollower>> m_garbage;
//Pending log entries waiting to be returned.
static TrivialLockSingleList<DisorderMessageContext> m_disorder_list;
static LockFreeUnorderedSingleList<SingleListNode<DisorderMessageContext>> m_disorder_garbage;
//Threads whose log entries haven't been written are waiting on this CV
static std::condition_variable m_cv;
//Used together with the above CV
static std::mutex m_cv_mutex;
static std::chrono::time_point<std::chrono::steady_clock> m_last_heartbeat;
static std::shared_timed_mutex m_last_heartbeat_lock;
public:
static void Initialize(bool switching_role=false) noexcept;
static void UnInitialize() noexcept;
static void Clear() noexcept;
private:
FollowerView() = delete;
virtual ~FollowerView() = delete;
FollowerView(const FollowerView&) = delete;
FollowerView& operator=(const FollowerView&) = delete;
};
} //end namespace
#endif
| 3,055
|
C++
|
.h
| 63
| 45.650794
| 102
| 0.771284
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,342
|
test_all.h
|
ppLorins_aurora/src/gtest/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_H__
#define __GTEST_H__
#include "gtest/tools/test_all.h"
#include "gtest/topology/test_all.h"
#include "gtest/storage/test_all.h"
#include "gtest/state/test_all.h"
#include "gtest/guid/test_all.h"
#include "gtest/common/test_all.h"
#include "gtest/binlog/test_all.h"
#include "gtest/follower/test_all.h"
#include "gtest/service/test_all.h"
#include "gtest/global/test_all.h"
#include "gtest/leader/test_all.h"
#include "gtest/candidate/test_all.h"
#include "gtest/election/test_all.h"
#include "gtest/member/test_all.h"
#include "gtest/client/test_all.h"
#endif
| 1,369
|
C++
|
.h
| 33
| 40.272727
| 73
| 0.752445
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,343
|
test_base.h
|
ppLorins_aurora/src/gtest/test_base.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_BASE_H__
#define __GTEST_BASE_H__
#ifndef _RAFT_UNIT_TEST_
#error You must define the '_RAFT_UNIT_TEST_' macro to start unit testing ,otherwise some functions wont running correctly.
#endif
#include "grpc++/channel.h"
#include "grpc++/create_channel.h"
#include "boost/process.hpp"
#include "boost/process/environment.hpp"
#include "boost/filesystem.hpp"
#include "gtest/gtest.h"
#include "config/config.h"
#include "global/global_env.h"
#include "topology/topology_mgr.h"
#include "tools/utilities.h"
#include "guid/guid_generator.h"
#include "election/election.h"
#include "member/member_manager.h"
#define _RAFT_UNIT_TEST_LEADER_PORT_ (10010)
#define _RAFT_UNIT_TEST_FOLLWER_PORT_ (10020)
#define _RAFT_UNIT_TEST_NEW_NODES_PORT_ (10030)
#define _TEST_LEADER_BINLOG_ "raft.binlog.leader"
#define _TEST_FOLLOWER_BINLOG_ "raft.binlog.follower"
#define _TEST_TOPOLOGY_MEMCHG_FILE_ "topology.config.memchg"
#define _TEST_FOLLOWER_NUM_ (3)
namespace fs = boost::filesystem;
namespace bp = boost::process;
class TestBase : public ::testing::Test {
public:
TestBase() {
this->m_leader_addr = this->m_local_ip + ":" + std::to_string(_RAFT_UNIT_TEST_LEADER_PORT_);
}
virtual ~TestBase() {}
protected:
virtual void SetUp() override {}
virtual void TearDown() override {}
auto StartTimeing() {
return ::RaftCore::Tools::StartTimeing();
}
void EndTiming(const std::chrono::time_point<std::chrono::steady_clock> &tp_start,const char* operation_name) {
this->m_time_cost_us = ::RaftCore::Tools::EndTiming(tp_start,operation_name);
}
void LaunchMultipleThread(std::function<void(int thread_idx)> fn,int working_thread=0) {
auto _tp = this->StartTimeing();
std::vector<std::thread*> _vec;
int _thread_num = this->m_cpu_cores;
if (working_thread > 0)
_thread_num = working_thread;
for (int i = 0; i < _thread_num;++i) {
std::thread* _p_thread = new std::thread(fn,i);
_vec.push_back(_p_thread);
}
for (auto &_p_thread : _vec)
_p_thread->join();
this->EndTiming(_tp, "total thread");
}
uint64_t GetTimeCost() {
return this->m_time_cost_us;
}
protected:
const int m_cpu_cores = std::thread::hardware_concurrency();
const std::string m_local_ip = _AURORA_LOCAL_IP_;
std::string m_leader_addr = "";
const int m_follower_port = _RAFT_UNIT_TEST_FOLLWER_PORT_;
uint64_t m_time_cost_us = 0;
};
class TestSingleBackendFollower : public TestBase {
public:
TestSingleBackendFollower() {
this->m_follower_svc_addr = this->m_local_ip + ":" + std::to_string(this->m_follower_port);
//Force the instance to listen on the specific port.
::RaftCore::Config::FLAGS_port = _RAFT_UNIT_TEST_FOLLWER_PORT_;
//Init is a time consuming operation.
::RaftCore::Global::GlobalEnv::InitialEnv();
m_thread = new std::thread([]() {
::RaftCore::Global::GlobalEnv::RunServer();
});
//Waiting for server to get fully start.
std::this_thread::sleep_for(std::chrono::seconds(3));
}
virtual ~TestSingleBackendFollower() {
::RaftCore::Global::GlobalEnv::StopServer();
::RaftCore::Global::GlobalEnv::UnInitialEnv();
m_thread->join();
}
protected:
std::string m_follower_svc_addr ;
std::thread * m_thread = nullptr;
};
class TestMultipleBackendFollower : public TestBase {
public:
TestMultipleBackendFollower() {}
virtual ~TestMultipleBackendFollower() {}
protected:
virtual void StartFollowers(int empty_follower_num=0) final {
auto _generator = [](int idx) ->const char*{ return _TEST_LEADER_BINLOG_; };
this->StartFollowersFunc(_generator,empty_follower_num);
}
virtual void StartFollowersFunc(std::function<const char*(int)> generator,
int empty_follower_num=0,int follower_num = _TEST_FOLLOWER_NUM_) final{
//-----------------------Unifying config of leader and followers.-----------------------//
::RaftCore::CTopologyMgr::Initialize();
::RaftCore::Topology _topo;
::RaftCore::CTopologyMgr::Read(&_topo);
_topo.m_leader = this->m_local_ip + ":" + std::to_string(::RaftCore::Config::FLAGS_port);
int port_base = _RAFT_UNIT_TEST_FOLLWER_PORT_;
_topo.m_followers.clear();
for (int i = 0; i < follower_num; ++i) {
int _port = port_base + i;
_topo.m_followers.emplace(this->m_local_ip + ":" + std::to_string(_port));
}
::RaftCore::CTopologyMgr::Update(_topo);
::RaftCore::CTopologyMgr::UnInitialize();
this->m_main_path = fs::current_path();
//-----------------------Starting server.-----------------------//
std::unordered_map<const char*, const char*> _copies;
_copies.emplace(_AURORA_ELECTION_CONFIG_FILE_,_AURORA_ELECTION_CONFIG_FILE_);
_copies.emplace(_AURORA_MEMBER_CONFIG_FILE_,_AURORA_MEMBER_CONFIG_FILE_);
_copies.emplace(_AURORA_TOPOLOGY_CONFFIG_FILE_, _AURORA_TOPOLOGY_CONFFIG_FILE_);
for (int i = 0; i < follower_num; ++i) {
int _port = port_base + i;
auto src = generator(i);
_copies.emplace(src, _TEST_FOLLOWER_BINLOG_);
this->StartOneFollower(i,_port,_copies);
_copies.erase(src);
}
//Empty followers use different topology config file.
_copies.erase(_AURORA_TOPOLOGY_CONFFIG_FILE_);
_copies.emplace(_TEST_TOPOLOGY_MEMCHG_FILE_,_AURORA_TOPOLOGY_CONFFIG_FILE_);
//Start empty followers for member change testing.
int _empty_follower_base = (follower_num / 10) * 10 + 10;
for (int i = 0; i < empty_follower_num; ++i) {
int _port = _RAFT_UNIT_TEST_NEW_NODES_PORT_ + i;
int _follower_dir_idx = _empty_follower_base + i;
this->StartOneFollower(_follower_dir_idx,_port,_copies);
}
//Working directory already changed,go back to the initial path.
fs::current_path(this->m_main_path);
//Waiting for the followers to get fully started.
std::this_thread::sleep_for(std::chrono::seconds(3));
}
virtual void EndFollowers() final{
for (auto& p_child : this->m_p_children)
p_child->terminate();
}
protected:
virtual void StartOneFollower(int follower_idx,int follower_port,
const std::unordered_map<const char*,const char*> &copies) final{
//Set up followers.
char sz_path[256] = {0};
std::snprintf(sz_path,sizeof(sz_path),"follower_%d",follower_idx);
fs::current_path(this->m_main_path);
//Initial followers' working directory.
fs::path _dst_dir = fs::path(sz_path);
fs::remove_all(_dst_dir);
//This reassignment is trying to solve the 'access denied' problem.
//_dst_dir = fs::path(sz_path);
fs::create_directory(_dst_dir);
//Copy server dependent files.
for (auto &_pair_kv : copies)
fs::copy_file(fs::path(_pair_kv.first),_dst_dir/_pair_kv.second);
//Starting follower instances.
fs::current_path(this->m_main_path / fs::path(sz_path));
#define _PARA_BUF_SIZE_ (64)
char* _p_port = (char*)malloc(_PARA_BUF_SIZE_);
std::snprintf(_p_port,_PARA_BUF_SIZE_,"--port=%d", follower_port);
char* _p_a = (char*)malloc(_PARA_BUF_SIZE_);
std::snprintf(_p_a,_PARA_BUF_SIZE_,"--iterating_wait_timeo_us=%d",::RaftCore::Config::FLAGS_iterating_wait_timeo_us);
char* _p_b = (char*)malloc(_PARA_BUF_SIZE_);
std::snprintf(_p_b,_PARA_BUF_SIZE_,"--election_heartbeat_timeo_ms=%d",::RaftCore::Config::FLAGS_election_heartbeat_timeo_ms);
char* _p_c = (char*)malloc(_PARA_BUF_SIZE_);
std::snprintf(_p_c,_PARA_BUF_SIZE_,"--checking_heartbeat=%d",::RaftCore::Config::FLAGS_checking_heartbeat);
auto _env = boost::this_process::environment();
_env["GLOG_v"] = std::to_string(::RaftCore::Config::FLAGS_child_glog_v).c_str();
#define _CMD_BUF_SIZE_ (2048)
#ifdef _WIN32
const char *_p_path = "C:\\Users\\95\\Documents\\Visual Studio 2015\\Projects\\apollo\\%s\\raft_svr.exe";
char*_p_exe_file = (char*)malloc(_CMD_BUF_SIZE_);
#ifdef _DEBUG
std::snprintf(_p_exe_file,_CMD_BUF_SIZE_,_p_path,"Debug");
#else
std::snprintf(_p_exe_file,_CMD_BUF_SIZE_,_p_path,"Release");
#endif
#elif __APPLE__
const char *_p_exe_file = "/Users/arthur/git/aurora/bin/debug/aurora";
#elif __linux__
const char *_p_exe_file = "/root/git/aurora/bin/debug/aurora";
#else
CHECK(false) << "unknown platform";
#endif
bp::child *_p_child = new bp::child(_p_exe_file, _env,_p_port,_p_a,_p_b,_p_c);
this->m_p_children.emplace_back(_p_child);
std::cout << "started child process:" << _p_child->id() << std::endl;
}
std::vector<bp::child*> m_p_children;
fs::path m_main_path;
};
class TestCluster : public TestMultipleBackendFollower {
public:
TestCluster(int empty_followers=0) {
this->StartFollowers(empty_followers);
::RaftCore::Config::FLAGS_port = _RAFT_UNIT_TEST_LEADER_PORT_;
//Init is a time consuming operation.
::RaftCore::Global::GlobalEnv::InitialEnv();
std::thread *_thread = new std::thread([]() {
::RaftCore::Global::GlobalEnv::RunServer();
});
_thread->detach();
//Waiting for server to get fully start.
std::this_thread::sleep_for(std::chrono::seconds(3));
}
virtual ~TestCluster() {
//Serve could be shutdown if old leader no long exist in the new cluster.
if (::RaftCore::Global::GlobalEnv::IsRunning()) {
::RaftCore::Global::GlobalEnv::StopServer();
::RaftCore::Global::GlobalEnv::UnInitialEnv();
}
this->EndFollowers();
}
virtual void ClientWrite(const std::string &key="client_key_test",const std::string &val="client_val_test") {
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(this->m_leader_addr, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
//std::chrono::system_clock::time_point _deadline = std::chrono::system_clock::now() + std::chrono::seconds(1);
//_context.set_deadline(_deadline);
::raft::ClientWriteRequest _w_req;
::raft::ClientWriteResponse _w_rsp;
auto *_p_wop = _w_req.mutable_req();
_p_wop->set_key(key);
_p_wop->set_value(val);
::grpc::ClientContext _contextX;
::grpc::Status _status = _stub->Write(&_contextX, _w_req, &_w_rsp);
ASSERT_TRUE(_status.ok());
ASSERT_TRUE(_w_rsp.client_comm_rsp().result()==::raft::ErrorCode::SUCCESS) << "ClientWrite fail,detail:" << _w_rsp.DebugString();
}
};
#endif
| 12,478
|
C++
|
.h
| 251
| 40.350598
| 137
| 0.600545
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,344
|
test_all.h
|
ppLorins_aurora/src/gtest/leader/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_LEADER_H__
#define __GTEST_ALL_LEADER_H__
#include "gtest/leader/test_conn_pool.h"
#include "gtest/leader/test_follower_entity.h"
#include "gtest/leader/test_leader_view.h"
#endif
| 990
|
C++
|
.h
| 21
| 45.809524
| 73
| 0.75052
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,345
|
test_follower_entity.h
|
ppLorins_aurora/src/gtest/leader/test_follower_entity.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_FOLLOWER_ENTITY_H__
#define __GTEST_FOLLOWER_ENTITY_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "leader/follower_entity.h"
using ::RaftCore::Leader::FollowerEntity;
using ::RaftCore::Leader::FollowerStatus;
using ::RaftCore::Member::JointConsensusMask;
class TestFollowerEntity : public TestSingleBackendFollower {
public:
TestFollowerEntity() {}
protected:
virtual void SetUp() override {}
virtual void TearDown() override {}
};
TEST_F(TestFollowerEntity, GeneralOperation) {
std::shared_ptr<CompletionQueue> _shp_cq(new CompletionQueue());
FollowerEntity _obj_entity(this->m_follower_svc_addr, FollowerStatus::NORMAL,
uint32_t(JointConsensusMask::IN_OLD_CLUSTER), _shp_cq);
}
#endif
| 1,602
|
C++
|
.h
| 38
| 39.368421
| 81
| 0.746114
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,346
|
test_leader_view.h
|
ppLorins_aurora/src/gtest/leader/test_leader_view.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LEADER_VIEW_H__
#define __GTEST_LEADER_VIEW_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "election/election.h"
#include "storage/storage_singleton.h"
#include "leader/memory_log_leader.h"
using ::RaftCore::Leader::LeaderView;
using ::RaftCore::Leader::BackGroundTask::LogReplicationContext;
using ::RaftCore::Leader::BackGroundTask::ReSyncLogContext;
using ::RaftCore::Leader::BackGroundTask::SyncDataContenxt;
using ::RaftCore::Leader::TypePtrFollowerEntity;
using ::RaftCore::Leader::MemoryLogItemLeader;
using ::RaftCore::Leader::FollowerStatus;
using ::RaftCore::Election::ElectionMgr;
using ::RaftCore::Storage::StorageGlobal;
namespace fs = boost::filesystem;
class TestLeaderView : public TestMultipleBackendFollower {
public:
TestLeaderView() {}
protected:
virtual void SetUp() override {
this->StartFollowers();
//-----------------------Initializing server.-----------------------//
::RaftCore::Global::GlobalEnv::InitialEnv();
}
virtual void TearDown() override {
std::cout << "destructor of TestMultipleBackendFollower called" << std::endl;
::RaftCore::Global::GlobalEnv::UnInitialEnv();
this->EndFollowers();
}
};
TEST_F(TestLeaderView, GeneralOperation) {
auto _lrl = BinLogGlobal::m_instance.GetLastReplicated();
LogIdentifier _lcl;
_lcl.Set(0,_lrl.m_index - 10);
StorageGlobal::m_instance.Set(_lcl, "lcl_key", "lcl_val");
LogIdentifier _start_point;
_start_point.Set(ElectionMgr::m_cur_term.load(), _lcl.m_index + 1);
std::string _follower_addr = this->m_local_ip + ":" + std::to_string(this->m_follower_port);
TypePtrFollowerEntity _shp_follower(new FollowerEntity(_follower_addr,FollowerStatus::RESYNC_LOG));
std::shared_ptr<ReSyncLogContext> _shp_task(new ReSyncLogContext());
_shp_task->m_last_sync_point.Set(_start_point);
_shp_task->m_follower = _shp_follower;
LeaderView::ReSyncLogCB(_shp_task);
std::shared_ptr<SyncDataContenxt> _shp_sync_data_ctx(new SyncDataContenxt(_shp_follower));
LeaderView::SyncDataCB(_shp_sync_data_ctx);
}
#endif
| 3,014
|
C++
|
.h
| 66
| 41.590909
| 103
| 0.710716
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,347
|
test_conn_pool.h
|
ppLorins_aurora/src/gtest/leader/test_conn_pool.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_CONNECTION_POOL_H__
#define __GTEST_CONNECTION_POOL_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "client/client_impl.h"
#include "leader/channel_pool.h"
#include "leader/client_pool.h"
using ::raft::HeartBeatRequest;
using ::RaftCore::Leader::ChannelPool;
using ::RaftCore::Leader::ClientPool;
using ::RaftCore::Client::AppendEntriesAsyncClient;
class TestConnPool : public TestSingleBackendFollower {
public:
TestConnPool() {}
protected:
virtual void SetUp() override {
this->m_shp_cq.reset(new CompletionQueue());
this->m_shp_channel_pool.reset(new ChannelPool(this->m_follower_svc_addr,::RaftCore::Config::FLAGS_channel_pool_size));
auto _channel = this->m_shp_channel_pool->GetOneChannel();
for (int i = 0; i < this->m_cpu_cores; ++i) {
std::shared_ptr<AppendEntriesAsyncClient> _shp_client( new AppendEntriesAsyncClient(_channel, this->m_shp_cq, false));
this->m_obj_pool.Back(_shp_client);
}
}
virtual void TearDown() override { }
std::shared_ptr<ChannelPool> m_shp_channel_pool;
std::shared_ptr<CompletionQueue> m_shp_cq;
ClientPool<AppendEntriesAsyncClient> m_obj_pool;
};
TEST_F(TestConnPool, GeneralOperation) {
std::cout << "start.." << std::endl;
auto _shp_client = m_obj_pool.Fetch();
m_obj_pool.Back(_shp_client);
auto _shp_channel = this->m_shp_channel_pool->GetOneChannel();
//Test 0 term is okay.
this->m_shp_channel_pool->HeartBeat(0,this->m_leader_addr);
ASSERT_EQ(m_obj_pool.GetParentFollower(),nullptr);
std::cout << "end.." << std::endl;
}
TEST_F(TestConnPool, ConcurrentOperation) {
uint32_t _threads = ::RaftCore::Config::FLAGS_launch_threads_num;
uint32_t _op_count = ::RaftCore::Config::FLAGS_conn_op_count;
auto _op = [&](int thread_idx) {
for (std::size_t i = 0; i < _op_count; ++i) {
auto _shp_client = m_obj_pool.Fetch();
ASSERT_TRUE(_shp_client);
_shp_client->PushCallBackArgs(nullptr);
_shp_client->PushCallBackArgs(nullptr);
_shp_client->Reset();
m_obj_pool.Back(_shp_client);
this->m_shp_channel_pool->HeartBeat(0,this->m_leader_addr);
}
};
this->LaunchMultipleThread(_op, _threads);
uint32_t _total = _op_count * 2 * _threads;
uint64_t _time_cost_us = this->GetTimeCost();
std::cout << "(M)operations per second:" << _total / float(_time_cost_us) << std::endl;
}
#endif
| 3,422
|
C++
|
.h
| 76
| 39.302632
| 135
| 0.66586
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,348
|
test_all.h
|
ppLorins_aurora/src/gtest/service/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_SERVICE_H__
#define __GTEST_ALL_SERVICE_H__
#include "gtest/service/test_follower_service.h"
#include "gtest/service/test_leader_service.h"
#endif
| 957
|
C++
|
.h
| 20
| 46.5
| 73
| 0.751613
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,349
|
test_follower_service.h
|
ppLorins_aurora/src/gtest/service/test_follower_service.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_FOLLOWER_SERVICE_H__
#define __GTEST_FOLLOWER_SERVICE_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/service/test_benchmark.h"
#include "follower/follower_view.h"
class TestFollowerServiceBanchmark : public BenchmarkBase {
public:
TestFollowerServiceBanchmark() : BenchmarkBase(false) {}
virtual ~TestFollowerServiceBanchmark() {}
virtual std::string GetLeaderAddr()const noexcept = 0;
virtual void EntrustBatch(std::shared_ptr<Channel> &shp_channel,
std::shared_ptr<CompletionQueue> &shp_cq, uint32_t total,
const FIdxGenertor &generator)noexcept override {
static std::tm m_start_tm = { 0, 0, 0, 26, 9 - 1, 2019 - 1900 };
static auto m_start_tp = std::chrono::system_clock::from_time_t(std::mktime(&m_start_tm));
AppendEntrieBenchmarkClient *_p_client = new AppendEntrieBenchmarkClient(shp_channel, shp_cq, total);
for (std::size_t n = 0; n < total; ++n) {
//Shouldn't start with 0 when doing appendEntries.
uint32_t _req_idx = generator(n) + 1;
std::shared_ptr<AppendEntriesRequest> _shp_req(new AppendEntriesRequest());
std::string _my_addr = this->GetLeaderAddr();
if (::RaftCore::Config::FLAGS_my_ip != std::string("default_none"))
_my_addr = ::RaftCore::Config::FLAGS_my_ip;
_shp_req->mutable_base()->set_addr(_my_addr);
_shp_req->mutable_base()->set_term(0);
auto _p_entry = _shp_req->add_replicate_entity();
auto _p_entity_id = _p_entry->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(_req_idx);
auto _p_pre_entity_id = _p_entry->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(_req_idx - 1);
auto _p_wop = _p_entry->mutable_write_op();
_p_wop->set_key("follower_benchmark_key_" + std::to_string(_req_idx));
_p_wop->set_value("follower_benchmark_val_" + std::to_string(_req_idx));
auto us = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - m_start_tp);
_shp_req->set_debug_info(std::to_string(us.count()));
auto _req_setter = [&_shp_req](std::shared_ptr<::raft::AppendEntriesRequest>& _target)->void {
_target = _shp_req;
};
auto _f_prepare = std::bind(&::raft::RaftService::Stub::PrepareAsyncAppendEntries,
_p_client->GetStub().get(), std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3);
_p_client->EntrustRequest(_req_setter, _f_prepare,
::RaftCore::Config::FLAGS_leader_append_entries_rpc_timeo_ms);
}
}
};
class TestFollowerService : public TestSingleBackendFollower, public TestFollowerServiceBanchmark {
public:
TestFollowerService() {}
virtual void SetUp() override {
//::RaftCore::Config::FLAGS_memory_table_max_item = 10;
::RaftCore::Config::FLAGS_checking_heartbeat = false;
}
virtual void TearDown() override {}
protected:
std::string GetLeaderAddr()const noexcept override {
return this->m_leader_addr;
}
void DoHeartBeat() {
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(this->m_follower_svc_addr, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
::grpc::ClientContext _context;
std::chrono::system_clock::time_point _deadline = std::chrono::system_clock::now() + std::chrono::seconds(1);
//_context.set_deadline(_deadline);
::raft::HeartBeatRequest _req;
::raft::CommonResponse _rsp;
_req.mutable_base()->set_addr(this->m_leader_addr);
_req.mutable_base()->set_term(0);
::grpc::Status _status = _stub->HeartBeat(&_context, _req, &_rsp);
ASSERT_TRUE(_status.ok());
ASSERT_TRUE(_rsp.result()==ErrorCode::SUCCESS) << "DoHeartBeat fail,detail:" << _rsp.DebugString();
}
void DoAppendEntriesCommit() {
std::string _target_ip = ::RaftCore::Config::FLAGS_target_ip ;
std::string _real_ip = this->m_follower_svc_addr;
if (_target_ip != "default_none")
_real_ip = _target_ip;
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(_real_ip, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
AppendEntriesRequest _req;
AppendEntriesResponse _rsp;
_req.mutable_base()->set_addr(this->m_leader_addr);
_req.mutable_base()->set_term(0);
//8057:overlap, 8062:exact match,8063:disorder.
int _start = ::RaftCore::Config::FLAGS_append_entries_start_idx;
int _sum = 10;
for (int i = _start; i < _start + _sum; ++i) {
auto _p_entity = _req.add_replicate_entity();
auto _p_entity_id = _p_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
auto _p_pre_entity_id = _p_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(i==0?0:i-1);
auto _p_wop = _p_entity->mutable_write_op();
std::string _idx = std::to_string(i);
_p_wop->set_key("key_" + _idx);
_p_wop->set_value("val_" + _idx);
}
::grpc::ClientContext _contextX;
std::chrono::system_clock::time_point _deadline = std::chrono::system_clock::now() +
std::chrono::milliseconds(::RaftCore::Config::FLAGS_leader_append_entries_rpc_timeo_ms);
_contextX.set_deadline(_deadline);
::grpc::Status _status = _stub->AppendEntries(&_contextX, _req, &_rsp);
ASSERT_TRUE(_status.ok()) << ", error_code:" << _status.error_code() << ",err msg:" << _status.error_message();
ASSERT_TRUE(_rsp.comm_rsp().result()==ErrorCode::SUCCESS ||
_rsp.comm_rsp().result()==ErrorCode::SUCCESS_MERGED) << "DoAppendEntriesCommit fail,detail:" << _rsp.DebugString();
//Committing
CommitEntryRequest _commit_req;
CommitEntryResponse _commit_rsp;
_commit_req.mutable_base()->set_addr(this->m_leader_addr);
_commit_req.mutable_base()->set_term(0);
auto _p_entity_id = _commit_req.mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(_start + _sum - 1);
::grpc::ClientContext _context;
_deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(::RaftCore::Config::FLAGS_leader_commit_entries_rpc_timeo_ms);
_context.set_deadline(_deadline);
_status = _stub->CommitEntries(&_context, _commit_req, &_commit_rsp);
ASSERT_TRUE(_status.ok());
ASSERT_TRUE(_commit_rsp.comm_rsp().result()==ErrorCode::SUCCESS ||
_commit_rsp.comm_rsp().result()==ErrorCode::ALREADY_COMMITTED) << "DoAppendEntriesCommit fail,detail:" << _commit_rsp.DebugString();
}
void DoSyncData() {
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(this->m_follower_svc_addr, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
::grpc::ClientContext _context;
std::shared_ptr<::grpc::ClientReaderWriter<::raft::SyncDataRequest,::raft::SyncDataResponse>> _stream = _stub->SyncData(&_context);
::raft::SyncDataRequest _req;
_req.mutable_base()->set_term(0);
_req.mutable_base()->set_addr(this->m_leader_addr);
_req.set_msg_type(::raft::SyncDataMsgType::PREPARE);
_stream->Write(_req);
::raft::SyncDataResponse _rsp;
_rsp.Clear();
CHECK(_stream->Read(&_rsp));
CHECK_EQ(_rsp.comm_rsp().result(), ErrorCode::PREPARE_CONFRIMED) << "sync data fail,msg:" << _rsp.DebugString();
//Sync data.
int _write_times = 5;
int _counter = 10;
for (int j = 0; j < _write_times; ++j) {
_req.clear_entity();
_req.set_msg_type(::raft::SyncDataMsgType::SYNC_DATA);
int _start = j * _counter;
int _end = _start + _counter;
for (int i = _start; i < _end; ++i) {
auto _p_entity = _req.add_entity();
auto _p_pre_log_id = _p_entity->mutable_pre_log_id();
_p_pre_log_id->set_term(0);
_p_pre_log_id->set_idx(i-1);
auto _p_entity_id = _p_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
std::string _idx = std::to_string(i);
auto _p_wop = _p_entity->mutable_write_op();
_p_wop->set_key("resync_data_key_" + _idx);
_p_wop->set_value("resync_data_val_" + _idx);
}
_stream->Write(_req);
_rsp.Clear();
_stream->Read(&_rsp);
CHECK_EQ(_rsp.comm_rsp().result(), ErrorCode::SYNC_DATA_CONFRIMED) << "sync data fail,msg:" << _rsp.DebugString();
}
//Sync log.
int _log_write_times = 5;
int _log_counter = 10;
int _log_start = _log_write_times * _log_counter;
for (int j = 0; j < _log_write_times; ++j) {
_req.clear_entity();
_req.set_msg_type(::raft::SyncDataMsgType::SYNC_LOG);
int _start = _log_start + j * _log_counter;
int _end = _start + _log_counter;
for (int i = _start; i < _end; ++i) {
auto _p_entity = _req.add_entity();
auto _p_pre_log_id = _p_entity->mutable_pre_log_id();
_p_pre_log_id->set_term(0);
_p_pre_log_id->set_idx(i-1);
auto _p_entity_id = _p_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
std::string _idx = std::to_string(i);
auto _p_wop = _p_entity->mutable_write_op();
_p_wop->set_key("resync_log_key_" + _idx);
_p_wop->set_value("resync_log_val_" + _idx);
}
_stream->Write(_req);
_rsp.Clear();
_stream->Read(&_rsp);
CHECK_EQ(_rsp.comm_rsp().result(), ErrorCode::SYNC_LOG_CONFRIMED) << "sync data fail,msg:" << _rsp.DebugString();
}
CHECK(_stream->WritesDone()) << "client writes done fail.";
::grpc::Status _status = _stream->Finish();
CHECK(_status.ok()) << "error_code:" << _status.error_code() << ",err msg:"
<< _status.error_message();
}
};
class TestFollowerServiceClient : public TestBase, public TestFollowerServiceBanchmark {
public:
TestFollowerServiceClient() {}
virtual ~TestFollowerServiceClient() {}
protected:
std::string GetLeaderAddr()const noexcept override {
return this->m_leader_addr;
}
};
TEST_F(TestFollowerService, GeneralOperation) {
this->DoAppendEntriesCommit();
this->DoSyncData();
this->DoHeartBeat();
}
TEST_F(TestFollowerService, ContinuousWorking) {
this->DoAppendEntriesCommit();
}
TEST_F(TestFollowerService, ConcurrentOperation) {
auto _tp = this->StartTimeing();
//Be sure to remove binlog file before this test.
int _test_thread_num = ::RaftCore::Config::FLAGS_concurrent_client_thread_num;
if (_test_thread_num <= 0)
_test_thread_num = this->m_cpu_cores;
std::mutex _mutex;
std::atomic<int> _counter;
_counter.store(0);
int _sum = 1000;
auto _op = [&](int thread_idx) {
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(this->m_follower_svc_addr, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
std::chrono::system_clock::time_point _deadline = std::chrono::system_clock::now() + std::chrono::seconds(1);
//_context.set_deadline(_deadline);
AppendEntriesRequest _req;
AppendEntriesResponse _rsp;
CommitEntryRequest _commit_req;
CommitEntryResponse _commit_rsp;
int _run_times = 1000;
for (int k = 0; k < _run_times; ++k) {
_req.Clear();
_req.mutable_base()->set_term(0);
_req.mutable_base()->set_addr(this->m_leader_addr);
int _write_num = 10;
for (int i = 0; i < _write_num; ++i) {
int _cur_idx = k * _write_num * _test_thread_num + thread_idx * _write_num + i;
auto _p_entity = _req.add_replicate_entity();
auto _p_entity_id = _p_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(_cur_idx);
auto _p_pre_entity_id = _p_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(_cur_idx==0?0:_cur_idx-1);
auto _p_wop = _p_entity->mutable_write_op();
std::string _idx = std::to_string(_cur_idx);
_p_wop->set_key("key_" + _idx);
_p_wop->set_value("val_" + _idx);
}
int _start = k * _write_num * _test_thread_num + thread_idx * _write_num;
int _end = k * _write_num * _test_thread_num + thread_idx * _write_num + _write_num - 1;
_mutex.lock();
std::cout << "thread " << thread_idx << " write log from " << _start << " to " << _end << std::endl;
_mutex.unlock();
::grpc::ClientContext _contextX;
::grpc::Status _status = _stub->AppendEntries(&_contextX, _req, &_rsp);
_counter.fetch_add(1);
ASSERT_TRUE(_status.ok());
ASSERT_TRUE(_rsp.comm_rsp().result()==ErrorCode::SUCCESS || _rsp.comm_rsp().result()==ErrorCode::SUCCESS_MERGED) << "DoAppendEntriesCommit fail,detail:" << _rsp.DebugString();
//Committing
_commit_req.Clear();
_commit_req.mutable_base()->set_addr(this->m_leader_addr);
_commit_req.mutable_base()->set_term(0);
auto _p_entity_id = _commit_req.mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(_end);
::grpc::ClientContext _context;
_status = _stub->CommitEntries(&_context, _commit_req, &_commit_rsp);
ASSERT_TRUE(_status.ok());
ASSERT_TRUE(_rsp.comm_rsp().result()==ErrorCode::SUCCESS) << "DoAppendEntriesCommit fail,detail:" << _rsp.DebugString();
}
};
this->LaunchMultipleThread(_op,_test_thread_num);
std::cout << "total req send&recv:" << _counter.load() << std::endl;
this->EndTiming(_tp, "Follower service benchmark cost");
std::cout << "sleeping... CHECK if the memory cost is decreasing...???";
std::this_thread::sleep_for(std::chrono::seconds(5));
}
TEST_F(TestFollowerService, Benchmark) {
this->DoBenchmark(false);
}
TEST_F(TestFollowerServiceClient, Benchmark) {
this->DoBenchmark();
}
#endif
| 16,862
|
C++
|
.h
| 307
| 42.791531
| 187
| 0.562831
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,350
|
test_benchmark.h
|
ppLorins_aurora/src/gtest/service/test_benchmark.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_SERVICE_H__
#define __GTEST_SERVICE_H__
#include <list>
#include <memory>
#include <chrono>
#include <ctime>
#include "gtest/test_base.h"
using grpc::Channel;
using grpc::ClientAsyncResponseReader;
using grpc::ClientContext;
using grpc::CompletionQueue;
using grpc::Status;
using ::raft::ClientWriteRequest;
using ::raft::ClientWriteResponse;
using ::raft::AppendEntriesRequest;
using ::raft::AppendEntriesResponse;
using ::raft::CommitEntryRequest;
using ::raft::CommitEntryResponse;
using ::raft::ErrorCode;
template<typename T,typename R>
using FPrepareAsync = std::function<std::unique_ptr< ::grpc::ClientAsyncResponseReader<R>>(
::grpc::ClientContext*,const T&, CompletionQueue*)>;
typedef std::function<uint32_t(uint32_t)> FIdxGenertor;
class BenchmarkTime {
public:
BenchmarkTime() {
this->m_start_tp = std::chrono::system_clock::from_time_t(std::mktime(&this->m_start_tm));
}
protected:
static uint64_t GetAvgUSLantency() {
return m_total_latency.load();
}
protected:
std::chrono::time_point<std::chrono::system_clock> m_start_tp;
static std::atomic<uint64_t> m_total_latency;
private:
//2019-09-26
std::tm m_start_tm = { 0, 0, 0, 26, 9 - 1, 2019 - 1900 };
};
std::atomic<uint64_t> BenchmarkTime::m_total_latency = 0;
class BenchmarkReact {
public:
virtual uint64_t React(bool cq_result) noexcept = 0;
};
template<typename T,typename R>
class BenchmarkClient : public BenchmarkTime {
public:
template<typename S>
class CallData : public BenchmarkReact {
public:
CallData(BenchmarkClient<T, S>* parent) {
this->m_client_context.reset(new ::grpc::ClientContext());
this->m_parent_client = parent;
}
virtual uint64_t React(bool cq_result) noexcept override {
if (!cq_result) {
LOG(ERROR) << "UnaryBenchmarkClient got false result from CQ.";
return 0;
}
uint64_t _latency = this->m_parent_client->Responder(this->m_final_status, this->m_response);
if (this->m_parent_client->JudgeLast())
delete this->m_parent_client;
return _latency;
}
std::unique_ptr<::grpc::ClientAsyncResponseReader<S>> m_reader;
std::shared_ptr<::grpc::ClientContext> m_client_context;
::grpc::Status m_final_status;
S m_response;
BenchmarkClient<T, S>* m_parent_client;
};
public:
BenchmarkClient(std::shared_ptr<Channel> shp_channel, std::shared_ptr<CompletionQueue> shp_cq, uint32_t total_entrust) {
this->m_channel = shp_channel;
this->m_cq = shp_cq;
this->m_stub = ::raft::RaftService::NewStub(shp_channel);
this->m_resposne_got.store(0);
this->m_total_entrusted = total_entrust;
}
virtual ~BenchmarkClient() {}
void EntrustRequest(std::function<void(std::shared_ptr<T>&)> req_setter,
const FPrepareAsync<T, R> &f_prepare_async, uint32_t timeo_ms) noexcept {
req_setter(this->m_shp_request);
std::chrono::time_point<std::chrono::system_clock> _deadline = std::chrono::system_clock::now() +
std::chrono::milliseconds(timeo_ms);
CallData<R>* _p_call_data = new CallData<R>(this);
_p_call_data->m_client_context->set_deadline(_deadline);
_p_call_data->m_reader = f_prepare_async(_p_call_data->m_client_context.get(), *this->m_shp_request, this->m_cq.get());
_p_call_data->m_reader->StartCall();
_p_call_data->m_reader->Finish(&_p_call_data->m_response, &_p_call_data->m_final_status, _p_call_data);
}
std::shared_ptr<::raft::RaftService::Stub> GetStub() noexcept {
return this->m_stub;
}
uint32_t CalculateLatency(uint32_t start_us) {
auto _now_us = (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - this->m_start_tp)).count();
return (uint32_t)(_now_us - start_us);
}
bool JudgeLast() noexcept {
uint32_t _pre = this->m_resposne_got.fetch_add(1);
return _pre + 1 == this->m_total_entrusted;
}
protected:
virtual uint32_t Responder(const ::grpc::Status& status, const R& rsp) noexcept = 0;
protected:
std::shared_ptr<::grpc::Channel> m_channel;
std::shared_ptr<CompletionQueue> m_cq;
std::shared_ptr<T> m_shp_request;
std::shared_ptr<::raft::RaftService::Stub> m_stub;
protected:
std::atomic<uint32_t> m_resposne_got;
uint32_t m_total_entrusted;
private:
BenchmarkClient(const BenchmarkClient&) = delete;
BenchmarkClient& operator=(const BenchmarkClient&) = delete;
};
class CommitEntrieBenchmarkClient : public BenchmarkClient<CommitEntryRequest, CommitEntryResponse> {
public:
CommitEntrieBenchmarkClient(std::shared_ptr<::grpc::Channel> shp_channel, std::shared_ptr<::grpc::CompletionQueue> shp_cq, uint32_t total) :
BenchmarkClient<CommitEntryRequest, CommitEntryResponse>(shp_channel, shp_cq, total) {}
virtual ~CommitEntrieBenchmarkClient() {}
virtual uint32_t Responder(const ::grpc::Status& status,
const ::raft::CommitEntryResponse& rsp) noexcept override {
const auto &_idx = this->m_shp_request->entity_id().idx();
VLOG(89) << "Commit got index:" << _idx;
CHECK(status.ok()) << "error_code:" << status.error_code() << ",err msg"
<< status.error_message() << ",idx:" << _idx;
const ::raft::CommonResponse& comm_rsp = rsp.comm_rsp();
auto _error_code = comm_rsp.result();
CHECK(_error_code == ErrorCode::SUCCESS || _error_code == ErrorCode::ALREADY_COMMITTED) << int(_error_code);
auto _start_us = (uint32_t)std::atoll(comm_rsp.err_msg().c_str());
auto _lantency_us = this->CalculateLatency(_start_us);
m_total_latency.fetch_add(_lantency_us);
return _lantency_us;
}
};
class AppendEntrieBenchmarkClient : public BenchmarkClient<AppendEntriesRequest, AppendEntriesResponse> {
public:
AppendEntrieBenchmarkClient(std::shared_ptr<::grpc::Channel> shp_channel, std::shared_ptr<::grpc::CompletionQueue> shp_cq, uint32_t total) :
BenchmarkClient<AppendEntriesRequest, AppendEntriesResponse>(shp_channel, shp_cq, total) {}
virtual ~AppendEntrieBenchmarkClient() {}
virtual uint32_t Responder(const ::grpc::Status& status,
const AppendEntriesResponse& rsp) noexcept override {
int _lst_idx = this->m_shp_request->replicate_entity().size() - 1;
uint64_t _lst_log_idx = this->m_shp_request->replicate_entity(_lst_idx).entity_id().idx();
VLOG(89) << "appendEntries got index:" << _lst_log_idx;
CHECK(status.ok()) << "error_code:" << status.error_code() << ",err msg:"
<< status.error_message() << ",idx:" << _lst_log_idx;
const ::raft::CommonResponse& comm_rsp = rsp.comm_rsp();
auto _error_code = comm_rsp.result();
CHECK(_error_code == ErrorCode::SUCCESS || _error_code == ErrorCode::SUCCESS_MERGED)
<< int(_error_code);
auto _start_us = (uint32_t)std::atoll(comm_rsp.err_msg().c_str());
auto _lantency_us = this->CalculateLatency(_start_us);
m_total_latency.fetch_add(_lantency_us);
if (!::RaftCore::Config::FLAGS_do_commit)
return _lantency_us;
//Entrust commit request.
std::shared_ptr<CommitEntryRequest> _shp_commit_req(new CommitEntryRequest());
std::string _local_addr = std::string(_AURORA_LOCAL_IP_) + ":"
+ std::to_string(_RAFT_UNIT_TEST_LEADER_PORT_);
_shp_commit_req->mutable_base()->set_addr(_local_addr);
_shp_commit_req->mutable_base()->set_term(0);
auto _p_entity_id = _shp_commit_req->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(_lst_log_idx);
auto * _p_commit_client = new CommitEntrieBenchmarkClient(this->m_channel, this->m_cq, this->m_total_entrusted);
auto _req_setter = [&](std::shared_ptr<::raft::CommitEntryRequest>& _target)->void {
_target = _shp_commit_req;
};
auto _f_prepare = std::bind(&::raft::RaftService::Stub::PrepareAsyncCommitEntries,
_p_commit_client->GetStub().get(), std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3);
_p_commit_client->EntrustRequest(_req_setter, _f_prepare,
::RaftCore::Config::FLAGS_leader_commit_entries_rpc_timeo_ms);
VLOG(89) << "client entrust commit of idx:" << _lst_log_idx;
return _lantency_us;
}
};
class WriteBenchmarkClient : public BenchmarkClient<ClientWriteRequest, ClientWriteResponse>{
public:
WriteBenchmarkClient(std::shared_ptr<::grpc::Channel> shp_channel,
std::shared_ptr<::grpc::CompletionQueue> shp_cq, uint32_t total) :
BenchmarkClient<ClientWriteRequest, ClientWriteResponse>(shp_channel, shp_cq, total) {}
virtual ~WriteBenchmarkClient() {}
virtual uint32_t Responder(const ::grpc::Status& status,
const ClientWriteResponse& rsp) noexcept override {
if (!status.ok()) {
LOG(ERROR) << "error_code:" << status.error_code() << ",err msg"
<< status.error_message();
return 0;
}
const ::raft::ClientCommonResponse& _client_comm_rsp = rsp.client_comm_rsp();
auto _error_code = _client_comm_rsp.result();
CHECK(_error_code == ErrorCode::SUCCESS) << "err code:" << int(_error_code)
<< ",err msg:" << _client_comm_rsp.err_msg();
auto _start_us = (uint32_t)std::atoll(_client_comm_rsp.err_msg().c_str());
auto _lantency_us = this->CalculateLatency(_start_us);
m_total_latency.fetch_add(_lantency_us);
return _lantency_us;
}
};
class BenchmarkBase : public BenchmarkTime {
public:
BenchmarkBase(bool leader_svc = true) {
std::string _leader_addr = std::string(_AURORA_LOCAL_IP_) + ":" + std::to_string(_RAFT_UNIT_TEST_LEADER_PORT_);
std::string _follower_addr = std::string(_AURORA_LOCAL_IP_) + ":" + std::to_string(_RAFT_UNIT_TEST_FOLLWER_PORT_);
this->m_leader_svc = leader_svc;
this->m_target_addr = this->m_leader_svc ? _leader_addr : _follower_addr;
std::string _target_ip = ::RaftCore::Config::FLAGS_target_ip;
if (_target_ip != "default_none")
this->m_target_addr = _target_ip;
this->m_polling_thread_num_per_cq = ::RaftCore::Config::FLAGS_benchmark_client_polling_thread_num_per_cq;
this->m_cq_num = ::RaftCore::Config::FLAGS_benchmark_client_cq_num;
this->m_req_num_per_entrusing_thread = ::RaftCore::Config::FLAGS_follower_svc_benchmark_req_round;
if (::RaftCore::Config::FLAGS_do_commit)
this->m_req_num_per_entrusing_thread *= 2;;
if (this->m_leader_svc)
this->m_req_num_per_entrusing_thread = ::RaftCore::Config::FLAGS_leader_svc_benchmark_req_count;
this->m_total_req_num = this->m_req_num_per_entrusing_thread * this->m_cq_num;
CHECK(this->m_total_req_num % this->m_polling_thread_num_per_cq == 0);
this->m_req_num_per_polling_thread = this->m_total_req_num / this->m_polling_thread_num_per_cq;
}
virtual ~BenchmarkBase() {
for (auto &_cq : this->m_vec_cq)
_cq->Shutdown();
}
virtual void EntrustBatch(std::shared_ptr<Channel> &shp_channel,
std::shared_ptr<CompletionQueue> &shp_cq, uint32_t total,
const FIdxGenertor &generator)noexcept = 0;
void DoBenchmark(bool pure_client = true)noexcept {
std::vector<std::shared_ptr<::grpc::Channel>> _vec_channel;
for (std::size_t i = 0; i < ::RaftCore::Config::FLAGS_conn_per_link; ++i) {
auto _channel_args = ::grpc::ChannelArguments();
std::string _key = "key_" + std::to_string(i);
std::string _val = "val_" + std::to_string(i);
_channel_args.SetString(_key,_val);
_vec_channel.emplace_back(::grpc::CreateCustomChannel(this->m_target_addr, grpc::InsecureChannelCredentials(), _channel_args));
}
for (std::size_t i = 0; i < this->m_cq_num; ++i)
this->m_vec_cq.emplace_back(new CompletionQueue());
auto _thread_func = [&](int cq_idx) {
void* tag;
bool ok;
auto _start = std::chrono::steady_clock::now();
uint32_t _cur_got_num = 0;
uint64_t _total_latency = 0;
auto _shp_cq = this->m_vec_cq[cq_idx];
while (true) {
if (_cur_got_num >= this->m_req_num_per_polling_thread)
break;
_shp_cq->Next(&tag, &ok);
BenchmarkReact* _p_ins = static_cast<BenchmarkReact*>(tag);
_total_latency += _p_ins->React(ok);
_cur_got_num++;
delete _p_ins;
}
auto _end = std::chrono::steady_clock::now();
auto _ms = std::chrono::duration_cast<std::chrono::milliseconds>(_end - _start);
std::cout << "thread " << std::this_thread::get_id() << " inner time cost:" << _ms.count() << std::endl;
uint32_t _throughput = (uint32_t)(_cur_got_num / float(_ms.count()) * 1000);
std::cout << "thread " << std::this_thread::get_id() << " inner throughput : "
<< _throughput << ",latency(us):" << _total_latency / float(_cur_got_num)
<< ", current thread total num:" << _cur_got_num << std::endl;
};
//start the polling thread on CQ first.
std::vector<std::thread*> _polling_threads;
for (std::size_t i = 0; i < this->m_cq_num; ++i) {
for (std::size_t j = 0; j < this->m_polling_thread_num_per_cq; ++j) {
std::thread *_pthread = new std::thread(_thread_func, i);
_polling_threads.push_back(_pthread);
VLOG(89) << "clientCQ thread : " << _pthread->get_id() << " for CQ:" << i << " started.";
}
}
std::cout << "set timeout value begin" << std::endl << std::flush;
//start entrusting the requests.
auto _entrust_reqs = [&](int cq_idx, int thread_idx) {
int _channel_num = _vec_channel.size();
int _total_thread_num = this->m_polling_thread_num_per_cq * this->m_cq_num;
int _total_thread_idx = this->m_polling_thread_num_per_cq * cq_idx + thread_idx;
auto &_shp_channel = _vec_channel[_total_thread_idx % _channel_num];
auto _gen_idx = [&](uint32_t n) -> uint32_t{
return n * _total_thread_num + _total_thread_idx;
};
this->EntrustBatch(_shp_channel, this->m_vec_cq[cq_idx], this->m_req_num_per_entrusing_thread, _gen_idx);
};
auto _start = std::chrono::steady_clock::now();
std::vector<std::thread*> _entrusting_threads;
for (std::size_t n = 0; n < this->m_cq_num; ++n) {
for (std::size_t j = 0; j < ::RaftCore::Config::FLAGS_benchmark_client_entrusting_thread_num; ++j) {
auto* _p_thread = new std::thread(_entrust_reqs, n, j);
_entrusting_threads.push_back(_p_thread);
}
}
for (auto &_item : _polling_threads)
_item->join();
auto _end = std::chrono::steady_clock::now();
auto _ms = std::chrono::duration_cast<std::chrono::milliseconds>(_end - _start);
std::cout << "req number " << m_total_req_num << " total cost(ms):" << _ms.count() << std::endl;
float _throughput = m_total_req_num / float(_ms.count()) * 1000;
uint64_t _total_latency = GetAvgUSLantency();
uint64_t _avg_latenct_us = (uint64_t)(_total_latency / float(m_total_req_num));
std::cout << " inner throughput : " << _throughput << ",avg latency(us):" << _avg_latenct_us << std::endl;
//Entrusting threads are the least to wait.
for (auto &_item : _entrusting_threads)
_item->join();
if (pure_client)
return;
int _waiting_finish_seconds = 5;
std::cout << "waiting for ongoing remote processing to be finished for " << _waiting_finish_seconds << " seconds.";
std::this_thread::sleep_for(std::chrono::seconds(_waiting_finish_seconds));
}
private:
std::string m_target_addr = "";
uint32_t m_req_num_per_entrusing_thread = 0;
uint32_t m_req_num_per_polling_thread = 0;
uint32_t m_cq_num = 0;
uint32_t m_polling_thread_num_per_cq = 0;
uint32_t m_total_req_num = 0;
std::vector<std::shared_ptr<CompletionQueue>> m_vec_cq;
bool m_leader_svc = false;
private:
BenchmarkBase(const BenchmarkBase&) = delete;
BenchmarkBase& operator=(const BenchmarkBase&) = delete;
};
#endif
| 17,805
|
C++
|
.h
| 340
| 43.873529
| 144
| 0.619788
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,351
|
test_leader_service.h
|
ppLorins_aurora/src/gtest/service/test_leader_service.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LEADER_SERVICE_H__
#define __GTEST_LEADER_SERVICE_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/service/test_benchmark.h"
#include "leader/leader_view.h"
class TestLeaderServiceBanchmark : public BenchmarkBase {
public:
TestLeaderServiceBanchmark() {
uint32_t _buf_len = ::RaftCore::Config::FLAGS_value_len + 1;
this->m_val_buf = (char*)malloc(_buf_len);
std::memset(this->m_val_buf, 'a', _buf_len);
this->m_val_buf[_buf_len - 1] = '\0';
}
virtual ~TestLeaderServiceBanchmark() {
free(this->m_val_buf);
}
virtual void EntrustBatch(std::shared_ptr<Channel> &shp_channel,
std::shared_ptr<CompletionQueue> &shp_cq, uint32_t total,
const FIdxGenertor &generator)noexcept override {
WriteBenchmarkClient *_p_client = new WriteBenchmarkClient(shp_channel, shp_cq, total);
for (std::size_t n = 0; n < total; ++n) {
auto us = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - this->m_start_tp);
std::shared_ptr<ClientWriteRequest> _shp_req(new ClientWriteRequest());
auto * _req = _shp_req->mutable_req();
uint32_t _req_idx = generator(n);
_req->set_key("leader_benchmark_key_" + std::to_string(_req_idx));
_req->set_value(std::string(this->m_val_buf));
_shp_req->set_timestamp(us.count());
auto _req_setter = [&_shp_req](std::shared_ptr<ClientWriteRequest>& _target)->void {
_target = _shp_req;
};
auto _f_prepare = std::bind(&::raft::RaftService::Stub::PrepareAsyncWrite,
_p_client->GetStub().get(), std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3);
_p_client->EntrustRequest(_req_setter, _f_prepare, ::RaftCore::Config::FLAGS_client_write_timo_ms);
}
}
private:
char* m_val_buf = nullptr;
};
class TestLeaderService : public TestCluster , public TestLeaderServiceBanchmark {
public:
TestLeaderService() {
//Give a long enough timeout value to facilitate unit test in debug mode l.
//::RaftCore::Config::FLAGS_leader_append_entries_rpc_timeo_ms = 5 *1000;
//::RaftCore::Config::FLAGS_leader_commit_entries_rpc_timeo_ms = 100 *1000;
//::RaftCore::Config::FLAGS_leader_resync_log_rpc_timeo_ms = 100 *1000;
//::RaftCore::Config::FLAGS_leader_heartbeat_rpc_timeo_ms = 100 *1000;
}
virtual void SetUp() override {}
virtual void TearDown() override {}
protected:
void ClientRead() {
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(this->m_leader_addr, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
//std::chrono::system_clock::time_point _deadline = std::chrono::system_clock::now() + std::chrono::seconds(1);
//_context.set_deadline(_deadline);
::raft::ClientReadRequest _r_req;
::raft::ClientReadResponse _r_rsp;
_r_req.set_key("client_key_test");
::grpc::ClientContext _contextX;
::grpc::Status _status = _stub->Read(&_contextX, _r_req, &_r_rsp);
ASSERT_TRUE(_status.ok());
ASSERT_TRUE(_r_rsp.client_comm_rsp().result()==::raft::ErrorCode::SUCCESS) << "ClientRead fail,detail:" << _r_rsp.DebugString();
//ASSERT_STREQ(_r_rsp.value().c_str(),"client_val_test") << "ClientRead value not correct:" << _r_rsp.DebugString();
}
};
class TestLeaderServiceClient : public TestBase, public TestLeaderServiceBanchmark {
public:
TestLeaderServiceClient() {}
virtual ~TestLeaderServiceClient() {}
protected:
};
TEST_F(TestLeaderService, GeneralOperation) {
std::cout << "start general test.." << std::endl;
this->ClientWrite();
this->ClientRead();
std::cout << "end general test.." << std::endl;
}
TEST_F(TestLeaderService, ConcurrentOperation) {
//Be sure to remove binlog file before this test.
auto _tp = this->StartTimeing();
auto _op = [&](int thread_idx) {
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(this->m_leader_addr, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
int _read_counter = 0;
int _start = 0;
int _run_times = 1000;
for (int k = 0; k < _run_times; ++k) {
int _write_num = 10;
for (int i = 0; i < _write_num; ++i) {
int _cur_idx = _start + k * _write_num * this->m_cpu_cores + thread_idx * _write_num + i;
ClientWriteRequest _w_req;
ClientWriteResponse _w_rsp;
std::string _key = "client_key_no_order_" + std::to_string(_cur_idx);
std::string _val = "client_val_no_order_" + std::to_string(_cur_idx);
auto *_p_wop = _w_req.mutable_req();
_p_wop->set_key(_key);
_p_wop->set_value(_val);
::grpc::ClientContext _contextX;
std::chrono::system_clock::time_point _deadline = std::chrono::system_clock::now() +
std::chrono::milliseconds(::RaftCore::Config::FLAGS_client_write_timo_ms);
//_contextX.set_deadline(_deadline);
::grpc::Status _status = _stub->Write(&_contextX, _w_req, &_w_rsp);
ASSERT_TRUE(_status.ok()) << "status wrong:" << _status.error_message();
ASSERT_TRUE(_w_rsp.client_comm_rsp().result()==::raft::ErrorCode::SUCCESS) << "ClientWrite fail,detail:" << _w_rsp.DebugString();
if (_read_counter++ > 20) {
::raft::ClientReadRequest _r_req;
::raft::ClientReadResponse _r_rsp;
_r_req.set_key(_key);
::grpc::ClientContext _contextY;
std::chrono::system_clock::time_point _deadline = std::chrono::system_clock::now() + std::chrono::seconds(3);
//_contextY.set_deadline(_deadline);
::grpc::Status _status = _stub->Read(&_contextY, _r_req, &_r_rsp);
ASSERT_TRUE(_status.ok()) << "status wrong:" << _status.error_message();
ASSERT_TRUE(_r_rsp.client_comm_rsp().result()==::raft::ErrorCode::SUCCESS) << "ClientRead fail,detail:" << _r_rsp.DebugString();
std::cout << "read key:" << _key << ",val:" << _r_rsp.value() << std::endl;
_read_counter = 0;
}
//std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
};
this->LaunchMultipleThread(_op);
this->EndTiming(_tp, "leader service benchmark cost");
std::cout << "sleeping... CHECK if the memory cost is decreasing?????";
std::this_thread::sleep_for(std::chrono::seconds(20));
}
TEST_F(TestLeaderService, Benchmark) {
this->DoBenchmark(false);
}
TEST_F(TestLeaderServiceClient, Benchmark) {
this->DoBenchmark();
}
#endif
| 8,096
|
C++
|
.h
| 152
| 43.671053
| 148
| 0.601652
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,352
|
test_all.h
|
ppLorins_aurora/src/gtest/storage/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_STORAGE_H__
#define __GTEST_ALL_STORAGE_H__
#include "gtest/storage/test_storage.h"
#include "gtest/storage/test_hashable_string.h"
#include "gtest/storage/test_memory_table.h"
#include "gtest/storage/test_sstable.h"
#endif
| 1,034
|
C++
|
.h
| 22
| 45.681818
| 73
| 0.754229
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,353
|
test_sstable.h
|
ppLorins_aurora/src/gtest/storage/test_sstable.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_SSTABLE_H__
#define __GTEST_SSTABLE_H__
#include <list>
#include <memory>
#include "gtest/test_base.h"
#include "storage/sstable.h"
using ::RaftCore::Storage::MemoryTable;
using ::RaftCore::Storage::SSTAble;
class TestSSTable : public TestBase {
public:
TestSSTable() {}
virtual void SetUp() override {}
virtual void TearDown() override {}
protected:
void GeneralOperation() {
}
};
TEST_F(TestSSTable, GeneralOperation) {
MemoryTable _memtable_1;
_memtable_1.Insert("k1", "v1", 1, 1);
_memtable_1.Insert("k2", "v2", 1, 2);
_memtable_1.Insert("k3", "v3", 1, 3);
SSTAble _sstable_1(_memtable_1);
MemoryTable _memtable_2;
_memtable_2.Insert("k2", "v2", 1, 2);
_memtable_2.Insert("k3", "v3", 1, 3);
_memtable_2.Insert("k4", "v4", 1, 4);
SSTAble _sstable_2(_memtable_2);
SSTAble _sstable_3(_sstable_2.GetFilename().c_str());
//Older file merged into newer file.
SSTAble _sstable_merged(_sstable_1,_sstable_2);
std::string _val = "";
ASSERT_TRUE(_sstable_merged.Read("k4", _val));
ASSERT_TRUE(_val == "v4");
auto _max_id = _sstable_merged.GetMaxLogID();
ASSERT_TRUE(_max_id.m_term == 1 && _max_id.m_index == 4);
ASSERT_TRUE(_sstable_merged.GetFilename() == (_sstable_2.GetFilename() + _AURORA_SSTABLE_MERGE_SUFFIX_));
auto _traverse = [](const SSTAble::Meta &meta,const HashableString &key) ->bool{
std::cout << "traverse term:" << meta.m_term << ",index:" << meta.m_index << std::endl;;
return true;
};
_sstable_merged.IterateByVal(_traverse);
}
TEST_F(TestSSTable, Performance) {
MemoryTable _memtable;
std::string _key = "", _val="";
for (int i = 0; i < 20000; ++i) {
_key = std::to_string(i);
_val = std::to_string(i);
_memtable.Insert(_key, _val, 1, 1);
}
std::cout << "........." << std::endl;
SSTAble _sstable(_memtable);
}
TEST_F(TestSSTable, ConcurrentOperation) {
MemoryTable _memtable_1;
_memtable_1.Insert("k1", "v1", 1, 1);
_memtable_1.Insert("k2", "v2", 1, 2);
_memtable_1.Insert("k3", "v3", 1, 3);
_memtable_1.Insert("k4", "v4", 1, 4);
SSTAble _sstable_1(_memtable_1);
auto _op = [&](int idx) {
for (int i = 1; i <= 4; ++i) {
std::string _key = "k" + std::to_string(i);
std::string _expected_val = "v" + std::to_string(i);
std::string _val = "";
ASSERT_TRUE(_sstable_1.Read(_key, _val)) << "key:" << _key;
ASSERT_EQ(_val, _expected_val);
}
};
this->LaunchMultipleThread(_op);
}
#endif
| 3,451
|
C++
|
.h
| 88
| 34.170455
| 109
| 0.624284
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,354
|
test_storage.h
|
ppLorins_aurora/src/gtest/storage/test_storage.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_STORAGE_H__
#define __GTEST_STORAGE_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "common/log_identifier.h"
#include "binlog/binlog_singleton.h"
#include "storage/storage.h"
using ::RaftCore::Storage::StorageMgr;
using ::RaftCore::BinLog::BinLogGlobal;
using ::RaftCore::Common::LogIdentifier;
class TestStorage : public TestBase {
public:
TestStorage() {
//::RaftCore::Config::FLAGS_memory_table_max_item = 20;
}
virtual ~TestStorage() {}
virtual void SetUp() override {
//Clear all existing files.
if (::RaftCore::Config::FLAGS_clear_existing_sstable_files) {
fs::path _data_path("data");
fs::remove_all(_data_path);
}
//Using the test binlog file.
BinLogGlobal::m_instance.Initialize(_ROLE_STR_TEST_);
this->m_lrl = BinLogGlobal::m_instance.GetLastReplicated();
this->m_const_term = this->m_lrl.m_term;
this->m_base_index = this->m_lrl.m_index;
this->m_obj.Initialize(_ROLE_STR_TEST_);
}
virtual void TearDown() override {
this->m_obj.UnInitialize();
}
protected:
void DoRW(int thread_idx = -1) {
for (int i = 1; i <= this->m_counter;++i) {
uint64_t _idx = this->m_base_index + i;
if (thread_idx >= 0)
_idx = this->m_base_index + thread_idx*this->m_counter + i;
//VLOG(89) << "writing idx:" << _idx;
LogIdentifier _log_id;
_log_id.Set(this->m_const_term,_idx);
std::string _i = std::to_string(_idx);
std::string _key = "key_" + _i;
std::string _val = "val_" + _i;
ASSERT_TRUE(this->m_obj.Set(_log_id,_key,_val));
std::string _val_2 = "val_" + _i;
ASSERT_TRUE(this->m_obj.Get(_key, _val_2));
if (_val != _val_2)
ASSERT_TRUE(false) << "_key:" << _key << ",expect _val:" << _val << ",actual _val:" << _val_2;
}
}
void GeneralOperation() {
this->DoRW();
LogIdentifier _max_log_id;
_max_log_id.Set(this->m_const_term, this->m_counter + this->m_base_index);
ASSERT_EQ(this->m_obj.GetLastCommitted(), _max_log_id);
LogIdentifier _log_id;
int _start_idx = this->m_counter / 2;
_log_id.Set(this->m_const_term,_start_idx);
std::list<StorageMgr::StorageItem> output_list;
int _get_count = ::RaftCore::Config::FLAGS_storage_get_slice_count;
this->m_obj.GetSlice(_log_id,_get_count,output_list);
ASSERT_EQ(output_list.size(), _get_count);
_start_idx++;
for (const auto &_item : output_list) {
LogIdentifier _id;
_id.Set(this->m_const_term,_start_idx);
ASSERT_EQ(_item.m_log_id,_id);
std::string _key = "key_" + std::to_string(_start_idx);
ASSERT_EQ(*_item.m_key,_key);
std::string _val = "val_" + std::to_string(_start_idx);
ASSERT_EQ(*_item.m_value,_val);
_start_idx++;
}
}
StorageMgr m_obj;
LogIdentifier m_lrl;
uint32_t m_const_term;
uint64_t m_base_index;
int m_counter = 100;
};
TEST_F(TestStorage, GeneralOperation) {
this->GeneralOperation();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
this->m_obj.PurgeGarbage();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
TEST_F(TestStorage, Reset) {
for (int i = 0; i < 1000; ++i)
this->m_obj.Reset();
}
TEST_F(TestStorage, ConcurrentOperation) {
auto _op = [&](int idx) {
//Note:More rounds more memory will be consumed.
this->m_counter = 200;
this->DoRW(idx);
};
this->LaunchMultipleThread(_op);
std::cout << "start GC ....." << std::endl;
//Check memory reclaiming status.
this->m_obj.PurgeGarbage();
std::cout << "start GC done, check memory usage now." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
}
#endif
| 5,153
|
C++
|
.h
| 122
| 33.122951
| 114
| 0.573639
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,355
|
test_hashable_string.h
|
ppLorins_aurora/src/gtest/storage/test_hashable_string.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_HASHABLE_STRING_H__
#define __GTEST_HASHABLE_STRING_H__
#include <list>
#include <memory>
#include "gtest/test_base.h"
#include "storage/hashable_string.h"
using ::RaftCore::Storage::HashableString;
class TestHashableString : public TestBase {
public:
TestHashableString() {}
virtual void SetUp() override {}
virtual void TearDown() override {}
protected:
};
TEST_F(TestHashableString, GeneralOperation) {
HashableString _obj1("abc1");
HashableString _obj2("abc2");
HashableString _obj3("abc2");
ASSERT_TRUE(_obj2.Hash() == _obj3.Hash());
ASSERT_TRUE(_obj1 < _obj2);
ASSERT_TRUE(_obj2 == _obj3);
ASSERT_TRUE(_obj2 == "abc2");
_obj3 = _obj1;
ASSERT_TRUE(_obj3 == "abc1");
ASSERT_TRUE(_obj3.GetStr() == "abc1");
std::string _tmp = "on_the_fly";
HashableString _obj4(_tmp, false);
ASSERT_TRUE(_obj4.GetStr()==_tmp);
}
#endif
| 1,738
|
C++
|
.h
| 45
| 35.022222
| 73
| 0.701205
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,356
|
test_memory_table.h
|
ppLorins_aurora/src/gtest/storage/test_memory_table.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_MEMORY_TABLE_H__
#define __GTEST_MEMORY_TABLE_H__
#include <list>
#include <memory>
#include "gtest/test_base.h"
#include "storage/memory_table.h"
using ::RaftCore::Storage::MemoryTable;
using ::RaftCore::Storage::TypePtrHashableString;
using ::RaftCore::Storage::TypePtrHashValue;
class TestMemoryTable : public TestBase {
public:
TestMemoryTable() {}
virtual void SetUp() override {}
virtual void TearDown() override {}
protected:
void GeneralOperation() {
this->m_obj.Insert("k1", "v1", 1, 1);
this->m_obj.Insert("k2", "v2", 1, 2);
this->m_obj.Insert("k3", "v3", 1, 3);
auto _iterator = [](const TypePtrHashableString &k,const TypePtrHashValue &v) {
//std::cout << "k:" << k->GetStr() << ",v:" << v->m_term << "|" << v->m_index << "|" << v->m_val << std::endl;;
return true;
};
this->m_obj.IterateByKey(_iterator);
std::string _val = "";
ASSERT_TRUE(this->m_obj.GetData("k1", _val));
ASSERT_TRUE(_val == "v1");
ASSERT_TRUE(this->m_obj.Size() == 3) << ",actual size:" << this->m_obj.Size();
}
protected:
MemoryTable m_obj;
};
TEST_F(TestMemoryTable, GeneralOperation) {
this->GeneralOperation();
}
TEST_F(TestMemoryTable, ConcurrentOperation) {
auto _op = [&](int idx) {
int _run_times = 1000;
for (int i = 0; i < _run_times; ++i) {
this->GeneralOperation();
std::cout << "thread:" << std::this_thread::get_id() << " finish round:" << i << std::endl;
}
};
this->LaunchMultipleThread(_op);
}
#endif
| 2,504
|
C++
|
.h
| 61
| 35.04918
| 127
| 0.62179
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,357
|
test_all.h
|
ppLorins_aurora/src/gtest/tools/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_TOOLS_H__
#define __GTEST_ALL_TOOLS_H__
#include "gtest/tools/test_lock_free_deque.h"
#include "gtest/tools/test_lock_free_hash.h"
#include "gtest/tools/test_lock_free_queue.h"
#include "gtest/tools/test_lock_free_unordered_single_list.h"
#include "gtest/tools/test_lock_free_priority_queue.h"
#include "gtest/tools/test_trivial_double_list.h"
#include "gtest/tools/test_trivial_single_list.h"
#include "gtest/tools/test_utilities.h"
#include "gtest/tools/test_timer.h"
#endif
| 1,287
|
C++
|
.h
| 27
| 46.407407
| 73
| 0.758978
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,358
|
test_lock_free_single_list.h
|
ppLorins_aurora/src/gtest/tools/test_lock_free_single_list.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LOCK_FREE_SINGLE_LIST_H__
#define __GTEST_LOCK_FREE_SINGLE_LIST_H__
#include "gtest/tools/test_data_structure_base.h"
#include "tools/lock_free_single_list.h"
using ::RaftCore::DataStructure::SingleListNode;
using ::RaftCore::DataStructure::LockFreeSingleList;
class TestLockFreeSingList : public DataStructureBase<LockFreeSingleList,int> {
protected:
virtual void SetUp() override {
//Install GC.
std::thread _t([&]() {
//auto _f = std::bind(&LockFreeSingleList<int>::PurgeSingleList, &(this->m_ds));
while (true)
this->m_ds.PurgeSingleList(2);
});
_t.detach();
}
virtual void TearDown() override {}
virtual void Dump() override {
auto _printer = [](int *p) {
std::cout << *p << " ";
};
this->m_ds.Iterate(_printer);
}
};
TEST_F(TestLockFreeSingList, GeneralOperation) {
auto _deleter = [](int* p_data) {
std::cout << "customized deleter called" << std::endl;
delete p_data;
};
this->m_ds.SetDeleter(_deleter);
uint32_t _push_num = 5;
for (std::size_t i = 0; i < _push_num; ++i) {
int *_p_i = new int(i);
this->m_ds.PushFront(_p_i);
}
ASSERT_TRUE(this->m_ds.Size() <= _push_num);
int _retain_num = 2;
this->m_ds.PurgeSingleList(_retain_num);
ASSERT_EQ(this->m_ds.Size(), _retain_num);
std::cout << "after testing...:" << std::endl;
this->Dump();
}
TEST_F(TestLockFreeSingList, ConcurrentOperation) {
int _count = 10000;
auto _push_it = [&](int idx){
for (int i = 0; i < _count; ++i) {
int *_p_i = new int(i);
this->m_ds.PushFront(_p_i);
}
};
this->LaunchMultipleThread(_push_it);
//Waiting for purging done.
std::this_thread::sleep_for(std::chrono::seconds(1));
ASSERT_EQ(this->m_ds.Size() , 2) << "actual size:" << this->m_ds.Size();
std::cout << "done.";
}
#endif
| 2,846
|
C++
|
.h
| 73
| 32.780822
| 96
| 0.618023
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,359
|
test_trivial_double_list.h
|
ppLorins_aurora/src/gtest/tools/test_trivial_double_list.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_TRIVIAL_DOUBLE_LIST_H__
#define __GTEST_TRIVIAL_DOUBLE_LIST_H__
#include <list>
#include <memory>
#include <chrono>
#include <random>
#include "gtest/tools/test_data_structure_base.h"
#include "tools/trivial_lock_double_list.h"
using ::RaftCore::DataStructure::TrivialLockDoubleList;
using ::RaftCore::DataStructure::OrderedTypeBase;
using ::RaftCore::DataStructure::DoubleListNode;
class TestDoubletList final : public OrderedTypeBase<TestDoubletList>{
public:
TestDoubletList(uint32_t i) : m_i(i) {}
virtual bool operator<(const TestDoubletList& _other)const noexcept override {
return this->m_i < _other.m_i;
}
virtual bool operator>(const TestDoubletList& _other)const noexcept override {
return this->m_i > _other.m_i;
}
virtual bool operator==(const TestDoubletList& _other)const noexcept override {
return this->m_i == _other.m_i;
}
uint32_t m_i;
};
class TestTrivialLockDoubleList : public DataStructureBase<TrivialLockDoubleList,TestDoubletList> {
public:
TestTrivialLockDoubleList(): DataStructureBase(
std::shared_ptr<TestDoubletList>(new TestDoubletList(0x0)),
std::shared_ptr<TestDoubletList>(new TestDoubletList(0xFFFFFFFF)) ) {}
protected:
virtual void Dump() override {
auto _print = [](const TestDoubletList &_other) {
std::cout << _other.m_i << " ";
return true;
};
this->m_ds.Iterate(_print);
}
int CheckCutHeadByValue(int _max,bool check_delete=true) {
DoubleListNode<TestDoubletList>* output_head = this->m_ds.CutHeadByValue(TestDoubletList(_max));
if (output_head == nullptr) {
//VLOG(89) << "--------cut head empty---------";
return 0;
}
int _head_size = 0;
auto _cur = output_head;
//std::cout << "checking cut by value:" << _max << std::endl;
std::string _line = "";
uint32_t _last = 0;
while (_cur) {
if (check_delete)
CHECK(!_cur->IsDeleted()) << "deleted node found in the output list.";
CHECK(_last < _cur->m_val->m_i) << "check order fail:" << _last
<< "|" << _cur->m_val->m_i << ",until now values:" << _line;
_last = _cur->m_val->m_i;
//std::cout << _cur->m_val->m_i << " ";
_line += ("|" + std::to_string(_cur->m_val->m_i));
_head_size++;
_cur = _cur->m_atomic_next.load();
}
//this->m_ds.ReleaseCutHead(output_head);
//VLOG(89) << "cuthead values: " << _line;
return _head_size;
}
int CheckCutHeadAdjacent(bool check_delete=true) {
auto _adjacent_judger = [](const TestDoubletList &a,const TestDoubletList &b)->bool { return b.m_i == a.m_i + 1; };
DoubleListNode<TestDoubletList>* output_head = this->m_ds.CutHead(_adjacent_judger);
if (output_head == nullptr) {
std::cout << "--------cut head empty---------" << std::endl;
return 0;
}
int _head_size = 0;
auto _cur = output_head;
//std::cout << std::this_thread::get_id() << " checking cut by adjacent ";
uint32_t _last = 0;
std::string _line = "";
while (_cur) {
if (check_delete)
CHECK(!_cur->IsDeleted()) << "deleted node found in the output list.";
if (_last > 0)
CHECK(_last+1 == _cur->m_val->m_i) << "check adjacent fail:" << _last
<< "|" << _cur->m_val->m_i << ",total:" << _line;
_last = _cur->m_val->m_i;
//std::cout << _cur->m_val->m_i << " ";
_line += ("|" + std::to_string(_cur->m_val->m_i));
_head_size++;
_cur = _cur->m_atomic_next.load();
}
//std::cout << std::endl;
this->m_ds.ReleaseCutHead(output_head);
return _head_size;
}
};
TEST_F(TestTrivialLockDoubleList, GeneralOperation) {
std::shared_ptr<TestDoubletList> _shp_1(new TestDoubletList(3));
DoubleListNode<TestDoubletList>* _node_1 = new DoubleListNode<TestDoubletList>(_shp_1);
std::shared_ptr<TestDoubletList> _shp_2(new TestDoubletList(5));
DoubleListNode<TestDoubletList>* _node_2 = new DoubleListNode<TestDoubletList>(_shp_2);
_node_1->m_atomic_next.store(_node_2);
_node_2->m_atomic_pre.store(_node_1);
DoubleListNode<TestDoubletList>::Apply(_node_1,[](DoubleListNode<TestDoubletList>* p_input) {
std::cout << "element: " << p_input->m_val->m_i << std::endl;
});
//Insert 100 elements.
int _total = 100;
int _offset = 10;
for (int i = 1; i <= _total;++i) {
bool _over_half_way = false;
if (i >= _total / 2) {
_over_half_way = true;
}
//int _avg = (_total + _total / 2) / 2;
//int val = _over_half_way ? _avg*2-i + _offset : i ;
int val = _over_half_way ? _total + _offset - (i - _total / 2) : i;
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(val));
DoubleListNode<TestDoubletList>* new_node = new DoubleListNode<TestDoubletList>(_shp);
if (_over_half_way) {
this->m_ds.Insert(new_node);
continue;
}
this->m_ds.Insert(_shp);
}
this->Dump();
ASSERT_EQ(this->m_ds.GetSize(), _total);
//Delete 10 elements.
int _delete_num = 10;
for (int i = 1; i <= _delete_num;++i) {
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(i));
this->m_ds.Delete(_shp);
}
ASSERT_EQ(this->m_ds.GetSize(), _total - _delete_num);
//CutHead
auto _adjacent = [](const TestDoubletList &left, const TestDoubletList &right)->bool {
return left.m_i + 1 == right.m_i;
};
int _adjacent_size = 0;
DoubleListNode<TestDoubletList>* output_head = this->m_ds.CutHead(_adjacent);
auto _cur = output_head;
std::cout << "checking adjacent..." << std::endl;
while (_cur) {
CHECK(!_cur->IsDeleted()) << "deleted node found in the output list.";
std::cout << _cur->m_val->m_i << " ";
_adjacent_size++;
_cur = _cur->m_atomic_next.load();
}
this->m_ds.ReleaseCutHead(output_head);
ASSERT_EQ(_adjacent_size, _total / 2 - _delete_num - 1);
//Cut by value.
int _less_than = 80;
output_head = this->m_ds.CutHeadByValue(TestDoubletList(_less_than));
int _head_size = 0;
_cur = output_head;
std::cout << "checking cut by value:" << _less_than << std::endl;
while (_cur) {
CHECK(!_cur->IsDeleted()) << "deleted node found in the output list.";
std::cout << _cur->m_val->m_i << " ";
_head_size++;
_cur = _cur->m_atomic_next.load();
}
this->m_ds.ReleaseCutHead(output_head);
ASSERT_EQ(_head_size,_less_than - _total/2 - _offset + 1);
this->m_ds.DeleteAll();
ASSERT_EQ(this->m_ds.GetSize(),0);
this->m_ds.Clear();
ASSERT_EQ(this->m_ds.GetSize(),0);
}
TEST_F(TestTrivialLockDoubleList, ConcurrentInsert) {
int _max = 1000;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
auto _insert = [&](int idx) {
auto _tp = this->StartTimeing();
for (int i = 1; i <= _max/2; ++i) {
uint32_t insert_val = dis(gen);
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << std::endl;
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(insert_val));
this->m_ds.Insert(_shp);
}
this->EndTiming(_tp, "one thread inserting");
};
this->LaunchMultipleThread(_insert);
ASSERT_LE(this->CheckCutHeadByValue(_max),_max);
}
TEST_F(TestTrivialLockDoubleList, ConcurrentInsertDelete) {
int _max = 1000;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
auto _insert_delete = [&](int idx) {
auto _tp = this->StartTimeing();
bool _delete_flg = false;
for (int i = 1; i <= _max/2; ++i) {
uint32_t insert_val = (dis(gen) % (_max/2));
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << ",i:" << i << std::endl;
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(insert_val));
this->m_ds.Insert(_shp);
if (_delete_flg) {
//std::cout << "thread:" << std::this_thread::get_id() << " deleting " << insert_val << ",i:" << i << std::endl;
this->m_ds.Delete(_shp);
}
//Reverse the flag.
_delete_flg = !_delete_flg;
}
this->EndTiming(_tp, "one thread inserting");
};
this->LaunchMultipleThread(_insert_delete);
ASSERT_LE(this->CheckCutHeadByValue(_max),_max/2);
}
TEST_F(TestTrivialLockDoubleList, ConcurrentInsertCutHead) {
int _max = 10;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
std::atomic<int> _total_cut_size(0);
auto _insert_cut = [&](int idx) {
auto _tp = this->StartTimeing();
int _counter = 0;
int _start = _max*idx + 1;
int _end = _start + _max - 1;
//std::cout << "start:" << _start << ",end:" << _end << std::endl;
for (int i = _end; i >= _start; --i) {
uint32_t insert_val = dis(gen);
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << ",i:" << i << std::endl;
//VLOG(89) << "inserting " << i;
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(i));
this->m_ds.Insert(_shp);
//VLOG(89) << "inserted " << i;
_counter++;
if (_counter >= 10) {
int _size = this->CheckCutHeadByValue(_end,false);
//VLOG(89) << "interval cut head,size:" << _size;
_counter = 0;
_total_cut_size.fetch_add(_size);
}
}
this->EndTiming(_tp, "one thread inserting");
};
int _thread_num = this->m_cpu_cores;
//int _thread_num = 6;
this->LaunchMultipleThread(_insert_cut, _thread_num);
ASSERT_EQ(_total_cut_size.load(), _max * _thread_num);
std::cout << "finial cutHead size:" <<this->CheckCutHeadByValue(_max,false) << std::endl;
}
TEST_F(TestTrivialLockDoubleList, ConcurrentInsertDeleteCutHead) {
int _max = 2000;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
auto _insert_delete_cut = [&](int idx) {
auto _tp = this->StartTimeing();
bool _delete_flg = false;
int _counter = 0;
for (int i = 1; i <= _max/2; ++i) {
uint32_t insert_val = dis(gen);
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << ",i:" << i << std::endl;
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(insert_val));
this->m_ds.Insert(_shp);
if (_delete_flg) {
//std::cout << "thread:" << std::this_thread::get_id() << " deleting " << insert_val << ",i:" << i << std::endl;
this->m_ds.Delete(_shp);
}
//Reverse the flag.
_delete_flg = !_delete_flg;
_counter++;
if (_counter >= 20) {
int _size = this->CheckCutHeadByValue(_max,false);
//std::cout << "interval cut head,size:" << _size << std::endl;
_counter = 0;
}
}
this->EndTiming(_tp, "one thread inserting");
};
this->LaunchMultipleThread(_insert_delete_cut);
std::cout << "finial cutHead size:" <<this->CheckCutHeadByValue(_max,false) << std::endl;
}
TEST_F(TestTrivialLockDoubleList, Adjacent) {
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(1));
this->m_ds.Insert(_shp);
this->m_ds.Delete(_shp);
this->m_ds.Insert(_shp);
ASSERT_EQ(this->CheckCutHeadAdjacent(), 1);
ASSERT_EQ(this->CheckCutHeadAdjacent(), 0);
//Do it again.
this->m_ds.Insert(_shp);
this->m_ds.Delete(_shp);
this->m_ds.Insert(_shp);
std::shared_ptr<TestDoubletList> _shp_2(new TestDoubletList(3));
this->m_ds.Insert(_shp_2);
this->m_ds.Delete(_shp_2);
this->m_ds.Insert(_shp_2);
this->m_ds.Delete(_shp_2);
this->m_ds.Insert(_shp_2);
ASSERT_EQ(this->CheckCutHeadAdjacent(), 1);
ASSERT_EQ(this->CheckCutHeadAdjacent(), 1);
}
TEST_F(TestTrivialLockDoubleList, ConcurrentInsertCutHeadAdjacent) {
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, 10);
auto _insert_cut_adjacent = [&](int idx) {
auto _tp = this->StartTimeing();
int _run_times = 8000;
for (int i = 1; i <= _run_times; ++i) {
std::shared_ptr<TestDoubletList> _shp(new TestDoubletList(i));
this->m_ds.Insert(_shp);
//std::cout << std::this_thread::get_id() << " inserting " << i << std::endl;
uint32_t _ran_val = dis(gen);
if (_ran_val & 1) {
int _size = this->CheckCutHeadAdjacent();
//std::cout << "interval cut head,size:" << _size << std::endl;
}
}
this->EndTiming(_tp, "one thread inserting");
};
this->LaunchMultipleThread(_insert_cut_adjacent);
std::cout << "finial cutHead size:" <<this->CheckCutHeadAdjacent() << std::endl;
}
#endif
| 14,977
|
C++
|
.h
| 334
| 35.934132
| 128
| 0.5664
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,360
|
test_trivial_single_list.h
|
ppLorins_aurora/src/gtest/tools/test_trivial_single_list.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_TRIVIAL_SINGLE_LIST_H__
#define __GTEST_TRIVIAL_SINGLE_LIST_H__
#include <list>
#include <memory>
#include <chrono>
#include <random>
#include "gtest/tools/test_data_structure_base.h"
#include "tools/trivial_lock_single_list.h"
using ::RaftCore::DataStructure::TrivialLockSingleList;
using ::RaftCore::DataStructure::OrderedTypeBase;
using ::RaftCore::DataStructure::SingleListNode;
class TestSingletList final : public OrderedTypeBase<TestSingletList>{
public:
TestSingletList(uint32_t i) : m_i(i) {}
virtual bool operator<(const TestSingletList& _other)const noexcept override {
return m_i < _other.m_i;
}
virtual bool operator>(const TestSingletList& _other)const noexcept override {
return m_i > _other.m_i;
}
virtual bool operator==(const TestSingletList& _other)const noexcept override {
return m_i == _other.m_i;
}
uint32_t m_i;
};
class TestTrivialSingleLockList : public DataStructureBase<TrivialLockSingleList,TestSingletList> {
public:
TestTrivialSingleLockList(): DataStructureBase(
std::shared_ptr<TestSingletList>(new TestSingletList(0x0)),
std::shared_ptr<TestSingletList>(new TestSingletList(0xFFFFFFFF)) ) {}
protected:
virtual void Dump() override {
auto _print = [](std::shared_ptr<TestSingletList> &_other) {
std::cout << _other->m_i << " ";
return true;
};
this->m_ds.Iterate(_print);
}
int CheckCutHeadByValue(int _max, bool check_delete = true) {
SingleListNode<TestSingletList>* output_head = this->m_ds.CutHeadByValue(TestSingletList(_max));
if (output_head == nullptr) {
//VLOG(89) << "--------cut head empty---------";
return 0;
}
int _head_size = 0;
auto _cur = output_head;
//std::cout << "checking cut by value:" << _max << std::endl;
std::string _line = "";
uint32_t _last = 0;
bool _first = true;
while (_cur) {
if (check_delete)
CHECK(!_cur->IsDeleted()) << "deleted node found in the output list.";
//bool _update_last = true;
if (!_first) {
//CHECK(_last < _cur->m_val->m_i) << "check order fail:" << _last << "|" << _cur->m_val->m_i << ",until now values:" << _line;
if (_last >= _cur->m_val->m_i) {
VLOG(89) << "check order fail:" << _last << "|" << _cur->m_val->m_i
<< ",until now values:" << _line;
std::cout << "error occur!" << std::endl;
}
//_update_last = false;
}
//if (_update_last)
_last = _cur->m_val->m_i;
_first = false;
//std::cout << _cur->m_val->m_i << " ";
_line += ("|" + std::to_string(_cur->m_val->m_i));
_head_size++;
_cur = _cur->m_atomic_next.load();
}
this->m_ds.ReleaseCutHead(output_head);
VLOG(89) << "cuthead values: " << _line;
return _head_size;
}
};
TEST_F(TestTrivialSingleLockList, GeneralOperation) {
std::shared_ptr<TestSingletList> _shp_1(new TestSingletList(3));
SingleListNode<TestSingletList>* _node_1 = new SingleListNode<TestSingletList>(_shp_1);
std::shared_ptr<TestSingletList> _shp_2(new TestSingletList(5));
SingleListNode<TestSingletList>* _node_2 = new SingleListNode<TestSingletList>(_shp_2);
_node_1->m_atomic_next.store(_node_2);
SingleListNode<TestSingletList>::Apply(_node_1,[](SingleListNode<TestSingletList>* p_input) {
std::cout << "element: " << p_input->m_val->m_i << std::endl;
});
//Insert 100 elements.
int _total = 100;
int _offset = 10;
for (int i = 1; i <= _total;++i) {
bool _over_half_way = false;
if (i >= _total / 2) {
_over_half_way = true;
}
int val = _over_half_way ? _total + _offset - (i - _total / 2) : i;
std::shared_ptr<TestSingletList> _shp(new TestSingletList(val));
SingleListNode<TestSingletList>* new_node = new SingleListNode<TestSingletList>(_shp);
if (_over_half_way) {
this->m_ds.Insert(new_node);
continue;
}
this->m_ds.Insert(_shp);
}
this->Dump();
ASSERT_EQ(this->m_ds.GetSize(), _total);
//Delete 10 elements.
int _delete_num = 10;
for (int i = 1; i <= _delete_num;++i) {
std::shared_ptr<TestSingletList> _shp(new TestSingletList(i));
this->m_ds.Delete(_shp);
}
ASSERT_EQ(this->m_ds.GetSize(), _total - _delete_num);
//Cut by value.
int _less_than = 80;
auto *output_head = this->m_ds.CutHeadByValue(TestSingletList(_less_than));
int _head_size = 0;
auto *_cur = output_head;
std::cout << "checking cut by value:" << _less_than << std::endl;
while (_cur) {
CHECK(!_cur->IsDeleted()) << "deleted node found in the output list.";
std::cout << _cur->m_val->m_i << " ";
_head_size++;
_cur = _cur->m_atomic_next.load();
}
this->m_ds.ReleaseCutHead(output_head);
ASSERT_EQ(_head_size, _less_than - _delete_num - _offset);
this->m_ds.Clear();
ASSERT_EQ(this->m_ds.GetSize(),0);
}
TEST_F(TestTrivialSingleLockList, ConcurrentInsert) {
int _max = 1000;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
auto _insert = [&](int idx) {
auto _tp = this->StartTimeing();
for (int i = 1; i <= _max/2; ++i) {
uint32_t insert_val = dis(gen);
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << std::endl;
std::shared_ptr<TestSingletList> _shp(new TestSingletList(insert_val));
this->m_ds.Insert(_shp);
}
};
this->LaunchMultipleThread(_insert);
ASSERT_LE(this->CheckCutHeadByValue(_max),_max);
}
TEST_F(TestTrivialSingleLockList, ConcurrentInsertDelete) {
int _max = 1000;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
auto _insert_delete = [&](int idx) {
VLOG(89) << "unit test concurrent thread started";
auto _tp = this->StartTimeing();
bool _delete_flg = false;
for (int i = 1; i <= _max/2; ++i) {
uint32_t insert_val = (dis(gen) % (_max/2));
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << ",i:" << i << std::endl;
std::shared_ptr<TestSingletList> _shp(new TestSingletList(insert_val));
this->m_ds.Insert(_shp);
if (_delete_flg) {
//std::cout << "thread:" << std::this_thread::get_id() << " deleting " << insert_val << ",i:" << i << std::endl;
this->m_ds.Delete(_shp);
}
//Reverse the flag.
_delete_flg = !_delete_flg;
}
this->EndTiming(_tp, "one thread inserting");
};
this->LaunchMultipleThread(_insert_delete);
ASSERT_LE(this->CheckCutHeadByValue(_max),_max/2);
}
TEST_F(TestTrivialSingleLockList, ConcurrentInsertCutHead) {
int _max = 2000;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
std::atomic<int> _total_cut_size(0);
auto _insert_cut = [&](int idx) {
auto _tp = this->StartTimeing();
VLOG(89) << "unite test thread spawned";
int _counter = 0;
int _start = _max*idx + 1;
int _end = _start + _max - 1;
VLOG(89) << "start:" << _start << ",end:" << _end << std::endl;
for (int i = _end; i >= _start; --i) {
uint32_t insert_val = dis(gen);
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << ",i:" << i << std::endl;
//VLOG(89) << "inserting " << i;
std::shared_ptr<TestSingletList> _shp(new TestSingletList(i));
this->m_ds.Insert(_shp);
//VLOG(89) << "inserted " << i;
_counter++;
if (_counter >= 10) {
int _size = this->CheckCutHeadByValue(_end,false);
//VLOG(89) << "interval cut head,size:" << _size;
_counter = 0;
_total_cut_size.fetch_add(_size);
}
}
this->EndTiming(_tp, "one thread inserting");
};
int _thread_num = this->m_cpu_cores;
//int _thread_num = 6;
this->LaunchMultipleThread(_insert_cut, _thread_num);
ASSERT_EQ(_total_cut_size.load(), _max * _thread_num);
std::cout << "finial cutHead size:" <<this->CheckCutHeadByValue(_max,false) << std::endl;
}
TEST_F(TestTrivialSingleLockList, ConcurrentInsertDeleteCutHead) {
int _max = 2000;
std::random_device rd;
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, _max);
std::atomic<int> _total_cut_size(0);
auto _insert_delete_cut = [&](int idx) {
auto _tp = this->StartTimeing();
bool _delete_flg = false;
int _counter = 0;
for (int i = 1; i <= _max/2; ++i) {
uint32_t insert_val = dis(gen);
//std::cout << "thread:" << std::this_thread::get_id() << " inserting " << insert_val << ",i:" << i << std::endl;
std::shared_ptr<TestSingletList> _shp(new TestSingletList(insert_val));
this->m_ds.Insert(_shp);
if (_delete_flg) {
//std::cout << "thread:" << std::this_thread::get_id() << " deleting " << insert_val << ",i:" << i << std::endl;
this->m_ds.Delete(_shp);
}
//Reverse the flag.
_delete_flg = !_delete_flg;
_counter++;
if (_counter >= 20) {
int _size = this->CheckCutHeadByValue(_max, false);
//std::cout << "interval cut head,size:" << _size << std::endl;
_counter = 0;
_total_cut_size.fetch_add(_size);
}
}
this->EndTiming(_tp, "one thread inserting");
};
this->LaunchMultipleThread(_insert_delete_cut);
std::cout << "finial cutHead size:" << this->CheckCutHeadByValue(_max, false)
<< ",total CutHead size:" << _total_cut_size.load() << std::endl;
}
#endif
| 11,632
|
C++
|
.h
| 258
| 35.895349
| 146
| 0.563914
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,361
|
test_lock_free_hash.h
|
ppLorins_aurora/src/gtest/tools/test_lock_free_hash.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LOCK_FREE_HASH_H__
#define __GTEST_LOCK_FREE_HASH_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/tools/test_data_structure_base.h"
#include "tools/lock_free_hash.h"
#include "tools/lock_free_hash_specific.h"
using ::RaftCore::DataStructure::LockFreeHash;
using ::RaftCore::DataStructure::HashNodeAtomic;
using ::RaftCore::DataStructure::HashTypeBase;
using ::RaftCore::DataStructure::LockFreeHashAtomic;
template<typename T>
class DataStructureHash {
public:
template<typename ...Args>
DataStructureHash(Args&&... args) : m_ds(std::forward<Args>(args)...) { }
virtual ~DataStructureHash() {}
protected:
T m_ds;
virtual void Dump() = 0;
};
class TestHash final : public HashTypeBase<TestHash>{
public:
TestHash(int i) :m_i(i) {}
virtual bool operator<(const TestHash& _other)const noexcept override {
return m_i < _other.m_i;
}
virtual bool operator==(const TestHash& _other)const noexcept override {
return m_i == _other.m_i;
}
virtual std::size_t Hash() const noexcept override {
return this->m_i;
}
int m_i;
};
typedef std::shared_ptr<TestHash> TypePtrTestHash;
template<typename T>
class TestLockFreeHashBase : public TestBase, public DataStructureHash<T> {
protected:
TestLockFreeHashBase() :DataStructureHash<T>(500) {}
virtual ~TestLockFreeHashBase() noexcept{}
protected:
virtual void SetUp() override {}
virtual void TearDown() override {}
virtual void Dump() override {
std::list<std::shared_ptr<TestHash>> _output;
this->m_ds.GetOrderedByKey(_output);
for (auto &_item : _output)
std::cout << _item->m_i << " ";
}
protected:
int m_sum = 10000;
};
class TestLockFreeHash : public TestLockFreeHashBase<LockFreeHash<TestHash,int>> {
protected:
TestLockFreeHash() {}
virtual ~TestLockFreeHash() noexcept{}
void GeneralOperation()noexcept {
int val = 7;
auto _tp = this->StartTimeing();
for (int i = 0; i < this->m_sum;++i) {
std::shared_ptr<TestHash> _shp_key(new TestHash(val+i));
std::shared_ptr<int> _shp_val(new int(val+i));
this->m_ds.Insert(_shp_key,_shp_val);
}
//Do insert again ,should overwrite all the previously inserted values.
for (int i = 0; i < this->m_sum;++i) {
std::shared_ptr<TestHash> _shp_key(new TestHash(val+i));
std::shared_ptr<int> _shp_val(new int(val+i));
this->m_ds.Insert(_shp_key,_shp_val);
}
ASSERT_TRUE(this->m_ds.Size() == this->m_sum);
std::shared_ptr<int> _shp_val;
this->m_ds.Read(TestHash(this->m_sum),_shp_val);
ASSERT_TRUE(*_shp_val == this->m_sum);
/*
int _new_val = 17;
std::shared_ptr<int> _shp_val_2(new int(_new_val));
TestHash *_p_obj = new TestHash(this->m_sum);
if (!this->m_ds.Upsert(_p_obj, _shp_val_2))
delete _p_obj;
_shp_val.reset();
this->m_ds.Read(TestHash(this->m_sum),_shp_val);
ASSERT_TRUE(*_shp_val == _new_val);
*/
auto _traverse = [](const std::shared_ptr<TestHash> &k,const std::shared_ptr<int> &v)->bool {
//std::cout << "k:" << k->Hash() << ",v:" << *v << std::endl;
return true;
};
this->m_ds.Iterate(_traverse);
auto _cond = [&](const TestHash &x) ->bool{
return x.m_i >= val;
};
ASSERT_TRUE(this->m_ds.CheckCond(_cond));
this->EndTiming(_tp, "CheckCond");
std::list<std::shared_ptr<TestHash>> _output;
this->m_ds.GetOrderedByKey(_output);
LockFreeHash<TestHash,int>::ValueComparator _func = [](const std::shared_ptr<int> &left, const std::shared_ptr<int> &right) {
return *left < *right;
};
std::map<std::shared_ptr<int>,TypePtrTestHash,decltype(_func)> _output_val(_func);
this->m_ds.GetOrderedByValue(_output_val);
ASSERT_EQ(_output_val.size(), this->m_sum);
ASSERT_EQ(*_output_val.cbegin()->first, val);
this->EndTiming(_tp, "GetOrder");
_tp = this->StartTimeing();
ASSERT_EQ(_output.size(), this->m_sum);
ASSERT_EQ(_output.front()->m_i, val);
ASSERT_TRUE(this->m_ds.Find(*_output.front()));
ASSERT_FALSE(this->m_ds.Find(TestHash(6)));
this->m_ds.Delete(*_output.front());
this->EndTiming(_tp, "find & delete");
_tp = this->StartTimeing();
this->m_ds.GetOrderedByKey(_output);
ASSERT_EQ(_output.size(), this->m_sum-1);
this->EndTiming(_tp, "GetOrderedByKey");
int _adder = 10;
auto _modifier = [&](std::shared_ptr<TestHash> &x) ->void{
x->m_i += _adder;
};
this->m_ds.Map(_modifier);
this->m_ds.GetOrderedByKey(_output);
ASSERT_EQ(_output.front()->m_i, val + _adder + 1);
this->m_ds.Clear();
this->m_ds.GetOrderedByKey(_output);
ASSERT_EQ(_output.size(), 0);
}
void ConcurrentOperation() noexcept {
//The program will consume more memory as _counter increasing due to its inner mechanism.
int _counter = 10000;
auto _insert = [&](int idx) {
auto _tp = this->StartTimeing();
bool _flg = true;
for (int i = 0; i < _counter; ++i) {
int _val = idx * _counter + i;
std::shared_ptr<TestHash> _shp_key(new TestHash(_val));
std::shared_ptr<int> _shp_val(new int(_val));
this->m_ds.Insert(_shp_key,_shp_val);
ASSERT_TRUE(this->m_ds.Find(*_shp_key));
this->m_ds.Read(TestHash(_val),_shp_val);
ASSERT_TRUE(*_shp_val==_val);
if (_flg) {
this->m_ds.Delete(*_shp_key);
ASSERT_FALSE(this->m_ds.Find(*_shp_key));
}
_flg = !_flg;
}
this->EndTiming(_tp, "one thread inserting");
};
this->LaunchMultipleThread(_insert);
auto _tp = this->StartTimeing();
std::list<std::shared_ptr<TestHash>> _output;
this->m_ds.GetOrderedByKey(_output);
this->EndTiming(_tp, "get ordered");
ASSERT_EQ(_output.size(), this->m_cpu_cores * _counter/2 );
}
};
class TestLockFreeHashAtomic : public TestLockFreeHashBase<LockFreeHashAtomic<TestHash,int>> {
protected:
TestLockFreeHashAtomic() {}
virtual ~TestLockFreeHashAtomic() noexcept{}
};
TEST_F(TestLockFreeHash, GeneralOperation) {
this->GeneralOperation();
}
TEST_F(TestLockFreeHash, ConcurrentOperation) {
this->ConcurrentOperation();
}
TEST_F(TestLockFreeHash, Allocation) {
for (int i = 0; i < 1000; ++i)
LockFreeHash<TestHash, int> obj;
}
TEST_F(TestLockFreeHashAtomic, Specifics) {
//this->GeneralOperation();
int _new_val = 17;
int* _p_val = new int(_new_val);
TestHash *_p_obj = new TestHash(this->m_sum);
if (!this->m_ds.Upsert(_p_obj, _p_val))
delete _p_obj;
std::shared_ptr<int> _shp_val;
this->m_ds.Read(TestHash(this->m_sum),_shp_val);
ASSERT_EQ(*_shp_val, _new_val);
}
#endif
| 8,635
|
C++
|
.h
| 200
| 33.12
| 137
| 0.568345
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,362
|
test_timer.h
|
ppLorins_aurora/src/gtest/tools/test_timer.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_TIMER_H__
#define __GTEST_TIMER_H__
#include <list>
#include <memory>
#include <chrono>
#include <random>
#include "gtest/test_base.h"
#include "tools/timer.h"
using ::RaftCore::Timer::GlobalTimer;
class TestTimer : public TestBase {
public:
TestTimer() {}
virtual void SetUp() override {
}
virtual void TearDown() override {
}
protected:
};
TEST_F(TestTimer, GeneralOperation) {
GlobalTimer::Initialize();
int _counter = 0;
auto _print = [&]() ->bool{
if (_counter++ >= 10) {
return false;
}
std::cout << "thread id: " << std::this_thread::get_id() << " job called." << std::endl;
return true;
};
GlobalTimer::AddTask(1000,_print);
std::this_thread::sleep_for(std::chrono::seconds(8));
GlobalTimer::UnInitialize();
//Manually checking if the thread exist
std::this_thread::sleep_for(std::chrono::seconds(10));
std::cout << "done." << std::endl;
}
#endif
| 1,813
|
C++
|
.h
| 51
| 31.431373
| 96
| 0.672622
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,363
|
test_lock_free_queue.h
|
ppLorins_aurora/src/gtest/tools/test_lock_free_queue.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LOCK_FREE_QUEUE_H__
#define __GTEST_LOCK_FREE_QUEUE_H__
#include <list>
#include <memory>
#include <chrono>
#include <random>
#include "gtest/tools/test_data_structure_base.h"
#include "tools/lock_free_queue.h"
#include "common/error_code.h"
using ::RaftCore::DataStructure::QueueNode;
using ::RaftCore::DataStructure::LockFreeQueue;
class TestLockFreeQueue : public DataStructureBase<LockFreeQueue,int> {
public:
TestLockFreeQueue(): DataStructureBase() {}
virtual void SetUp() override {
this->m_fn_cb = [](std::shared_ptr<int> ptr_element) ->bool{
//std::cout << *ptr_element << " ";
return true;
};
this->m_initial_size = ::RaftCore::Config::FLAGS_queue_initial_size;
this->m_ds.Initilize(this->m_fn_cb, this->m_initial_size);
}
virtual void TearDown() override {
}
protected:
virtual void Dump() override {
}
std::function<bool(std::shared_ptr<int> ptr_element)> m_fn_cb;
uint32_t m_initial_size = 0;
};
TEST_F(TestLockFreeQueue, GeneralOperation) {
int _num_processed = 0;
int i = 0;
bool _process_result = true;
int _rst_val = 0;
while (_process_result) {
std::shared_ptr<int> _shp(new int(i++));
_rst_val = this->m_ds.Push(&_shp);
_process_result = _rst_val==QUEUE_SUCC;
if (!_process_result)
std::cout << "Push fail ,result:" << _rst_val << std::endl;
_num_processed++;
}
int _original_size = this->m_ds.GetCapacity();
ASSERT_EQ(_num_processed, _original_size);
_num_processed = 0;
_process_result = true;
while (_process_result) {
_rst_val = this->m_ds.PopConsume();
_process_result = _rst_val==QUEUE_SUCC;
if (!_process_result)
std::cout << "Pop fail ,result:" << _rst_val << std::endl;
_num_processed++;
}
ASSERT_EQ(_num_processed, _original_size);
ASSERT_EQ(this->m_ds.GetSize(), 0);
ASSERT_TRUE(this->m_ds.Empty());
}
TEST_F(TestLockFreeQueue, ConcurrentPush) {
auto _insert = [&](int idx) {
int i = 0;
bool _process_result = true;
while (_process_result) {
std::shared_ptr<int> _shp(new int(i++));
int _rst_val = this->m_ds.Push(&_shp);
_process_result = _rst_val==QUEUE_SUCC;
if (!_process_result)
ASSERT_TRUE(_rst_val == QUEUE_FULL) << "unexpected result:" << _rst_val;
}
};
this->LaunchMultipleThread(_insert, ::RaftCore::Config::FLAGS_launch_threads_num);
uint64_t _time_cost_us = this->GetTimeCost();
std::cout << "(M)operations per second:" << this->m_initial_size / float(_time_cost_us) << std::endl;
ASSERT_EQ(this->m_ds.GetSize(), this->m_ds.GetCapacity()-1);
}
TEST_F(TestLockFreeQueue, ConcurrentPopConsume) {
int i = 0;
bool _process_result = true;
while (_process_result) {
std::shared_ptr<int> _shp(new int(i++));
int _rst_val = this->m_ds.Push(&_shp);
_process_result = _rst_val==QUEUE_SUCC;
if (!_process_result)
ASSERT_TRUE(_rst_val == QUEUE_FULL) << "unexpected result:" << _rst_val;
}
ASSERT_EQ(this->m_ds.GetSize(), this->m_ds.GetCapacity() -1);
auto _pop = [&](int idx) {
bool _pop_rst = true;
while (_pop_rst) {
int _rst_val = this->m_ds.PopConsume();
_pop_rst = _rst_val==QUEUE_SUCC;
if (!_pop_rst)
ASSERT_TRUE(_rst_val == QUEUE_EMPTY) << "unexpected result:" << _rst_val;
}
};
this->LaunchMultipleThread(_pop, ::RaftCore::Config::FLAGS_launch_threads_num);
uint64_t _time_cost_us = this->GetTimeCost();
std::cout << "(M)operations per second:" << this->m_initial_size / float(_time_cost_us) << std::endl;
ASSERT_EQ(this->m_ds.GetSize(), 0);
}
TEST_F(TestLockFreeQueue, ConcurrentPushPopConsume) {
std::shared_ptr<int> _shp(new int(7));
for (int i = 0; i < 1000; ++i)
this->m_ds.Push(&_shp);
uint32_t _threads = ::RaftCore::Config::FLAGS_launch_threads_num;
uint32_t _op_count = ::RaftCore::Config::FLAGS_queue_op_count;
auto _push_pop = [&](int idx) {
for (std::size_t n = 0; n < _op_count; ++n) {
bool _process_result = true;
std::shared_ptr<int> _shp(new int(n));
int _rst_val = this->m_ds.Push(&_shp);
ASSERT_TRUE(_rst_val == QUEUE_SUCC);
_rst_val = this->m_ds.PopConsume();
ASSERT_TRUE(_rst_val == QUEUE_SUCC);
}
};
this->LaunchMultipleThread(_push_pop, _threads);
uint32_t _total = _op_count * 2 * _threads;
uint64_t _time_cost_us = this->GetTimeCost();
std::cout << "(M)operations per second:" << _total / float(_time_cost_us) << std::endl;
}
TEST_F(TestLockFreeQueue, Cmp1) {
std::shared_ptr<int> _shp(new int(7));
for (int i = 0; i < 1000000; ++i) {
this->m_ds.Push(&_shp);
int _rst_val = this->m_ds.PopConsume();
CHECK(_rst_val == QUEUE_SUCC);
}
}
TEST_F(TestLockFreeQueue, Cmp2) {
std::shared_ptr<int> _shp(new int(7));
for (int i = 0; i < 1000000; ++i) {
int* p = new int(7);
delete p;
}
}
#endif
| 6,105
|
C++
|
.h
| 152
| 33.539474
| 105
| 0.602577
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,364
|
test_lock_free_priority_queue.h
|
ppLorins_aurora/src/gtest/tools/test_lock_free_priority_queue.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LOCK_FREE_PRIORITY_QUEUE_H__
#define __GTEST_LOCK_FREE_PRIORITY_QUEUE_H__
#include <list>
#include <memory>
#include <chrono>
#include "tools/lock_free_priority_queue.h"
using ::RaftCore::DataStructure::LockFreeQueue;
using ::RaftCore::DataStructure::LockFreeQueueBase;
using ::RaftCore::DataStructure::LockFreePriotityQueue;
class TestLockFreePriorityQueue : public DataStructureBase<LockFreeQueue,int> {
public:
struct STask1 {
STask1(int i):m_i(i) {}
static bool Func1(std::shared_ptr<STask1> ptr_element) {
//std::cout << "Task1 got:" << ptr_element->m_i << std::endl;
return true;
}
int m_i;
};
struct STask2 {
STask2(int i):m_i(i) {}
static bool Func2(std::shared_ptr<STask2> ptr_element) {
//std::cout << "Task2 got:" << ptr_element->m_i << std::endl;
return true;
}
int m_i;
};
struct STask3 {
STask3(int i):m_i(i) {}
static bool Func3(std::shared_ptr<STask3> ptr_element) {
//std::cout << "Task3 got:" << ptr_element->m_i << std::endl;
return true;
}
int m_i;
};
public:
TestLockFreePriorityQueue() {}
virtual ~TestLockFreePriorityQueue() {}
virtual void SetUp() override {
this->m_pri_queue.Initialize(this->m_cpu_cores * 2);
//this->m_pri_queue.Initialize(1);
auto _p_queue_2 = new LockFreeQueue<STask2>();
_p_queue_2->Initilize(STask2::Func2,::RaftCore::Config::FLAGS_lockfree_queue_resync_data_elements);
this->m_pri_queue.AddTask(LockFreePriotityQueue::TaskType::RESYNC_DATA,(LockFreeQueueBase*)_p_queue_2);
auto _p_queue_3 = new LockFreeQueue<STask3>();
_p_queue_3->Initilize(STask3::Func3,::RaftCore::Config::FLAGS_lockfree_queue_resync_log_elements);
this->m_pri_queue.AddTask(LockFreePriotityQueue::TaskType::RESYNC_LOG,(LockFreeQueueBase*)_p_queue_3);
}
virtual void TearDown() override {}
virtual void Dump() override {}
protected:
LockFreePriotityQueue m_pri_queue;
};
TEST_F(TestLockFreePriorityQueue, GeneralOperation) {
this->m_pri_queue.Launch();
std::this_thread::sleep_for(std::chrono::milliseconds(600));
std::shared_ptr<STask3> _shp_t3_1(new STask3(1));
int _rst_val = this->m_pri_queue.Push(LockFreePriotityQueue::TaskType::RESYNC_LOG,&_shp_t3_1);
if (_rst_val==QUEUE_SUCC)
std::cout << "T3 Push fail ,result:" << _rst_val << std::endl;
std::shared_ptr<STask3> _shp_t3_2(new STask3(2));
_rst_val = this->m_pri_queue.Push(LockFreePriotityQueue::TaskType::RESYNC_LOG,&_shp_t3_2);
if (_rst_val==QUEUE_SUCC)
std::cout << "T3 Push fail ,result:" << _rst_val << std::endl;
std::shared_ptr<STask2> _shp_t2_1(new STask2(10));
_rst_val = this->m_pri_queue.Push(LockFreePriotityQueue::TaskType::RESYNC_LOG,&_shp_t2_1);
if (_rst_val==QUEUE_SUCC)
std::cout << "T2 Push fail ,result:" << _rst_val << std::endl;
std::shared_ptr<STask2> _shp_t2_2(new STask2(11));
_rst_val = this->m_pri_queue.Push(LockFreePriotityQueue::TaskType::RESYNC_LOG,&_shp_t2_2);
if (_rst_val==QUEUE_SUCC)
std::cout << "T2 Push fail ,result:" << _rst_val << std::endl;
std::cout << "wait a little while";
std::this_thread::sleep_for(std::chrono::milliseconds(200));
this->m_pri_queue.UnInitialize();
}
TEST_F(TestLockFreePriorityQueue, ConcurrentOperation) {
this->m_pri_queue.Launch();
//Pushing.
auto _push = [&](int idx) {
auto _tp = this->StartTimeing();
int i = 0;
bool _process_result = true;
int _counter = 0, _run_times = 50000;
int _rst_val = 0;
while (_process_result && _run_times>=0) {
_counter++;
_run_times--;
if (_counter>=30) {
_counter = 0;
continue;
}
std::shared_ptr<STask3> _shp_t3(new STask3(i++));
_rst_val = this->m_pri_queue.Push(LockFreePriotityQueue::TaskType::RESYNC_LOG,&_shp_t3);
_process_result = _rst_val==QUEUE_SUCC;
if (!_process_result) {
std::cout << "T3 Push fail ,result:" << _rst_val << std::endl;
continue;
}
if (_counter>=20)
continue;
std::shared_ptr<STask2> _shp_t2(new STask2(i++));
_rst_val = this->m_pri_queue.Push(LockFreePriotityQueue::TaskType::RESYNC_DATA,&_shp_t2);
_process_result = _rst_val==QUEUE_SUCC;
if (!_process_result) {
std::cout << "T2 Push fail ,result:" << _rst_val << std::endl;
continue;
}
this->m_pri_queue.GetSize();
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
this->EndTiming(_tp,"one thread inserting");
};
this->LaunchMultipleThread(_push);
this->m_pri_queue.UnInitialize();
}
#endif
| 5,977
|
C++
|
.h
| 132
| 36.606061
| 115
| 0.604354
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,365
|
test_lock_free_deque.h
|
ppLorins_aurora/src/gtest/tools/test_lock_free_deque.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LOCK_FREE_DEQUE_H__
#define __GTEST_LOCK_FREE_DEQUE_H__
#include "gtest/tools/test_data_structure_base.h"
#include "tools/lock_free_deque.h"
using ::RaftCore::DataStructure::LockFreeDeque;
using ::RaftCore::DataStructure::EDequeNodeFlag;
class TestLockFreeDeque : public DataStructureBase<LockFreeDeque,int> {
protected:
virtual void SetUp() override {
//Install GC.
std::thread _t([&]() {
while (true) {
if (!this->m_running)
break;
LockFreeDeque<int>::GC();
}
});
_t.detach();
}
virtual void TearDown() override {
this->m_running = false;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
virtual void Dump() override {
while (auto shp = this->m_ds.Pop()) {
std::cout << *shp << " ";
}
}
bool m_running = true;
};
TEST_F(TestLockFreeDeque, GeneralOperation) {
int val = 7;
std::shared_ptr<int> _shp(new int(val));
this->m_ds.Push(_shp);
ASSERT_EQ(this->m_ds.Size(), 1);
decltype(_shp) _out = this->m_ds.Pop();
ASSERT_EQ(*_out, val);
_out = this->m_ds.Pop();
ASSERT_TRUE(!_out);
//simulate a bug scenario.
int _count = 2;
for (int i = 0; i < _count;++i)
this->m_ds.Push(std::make_shared<int>(i));
//simulate a bug scenario.
while (auto shp = this->m_ds.Pop());
ASSERT_EQ(this->m_ds.Size(),0);
for (int i = 0; i < _count;++i)
this->m_ds.Push(std::make_shared<int>(i));
while (auto shp = this->m_ds.Pop());
ASSERT_EQ(this->m_ds.Size(),0);
}
TEST_F(TestLockFreeDeque, ConcurrentPop) {
int _count = ::RaftCore::Config::FLAGS_deque_op_count;
for (int i = 0; i < _count; ++i)
this->m_ds.Push(std::make_shared<int>(i), EDequeNodeFlag::NO_COUNTING);
auto _pop_it = [&](int idx){
while (auto shp = this->m_ds.Pop());
};
this->LaunchMultipleThread(_pop_it, ::RaftCore::Config::FLAGS_launch_threads_num);
uint64_t _time_cost_us = this->GetTimeCost();
std::cout << "(M)operations per second:" << _count / float(_time_cost_us) << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
ASSERT_EQ(this->m_ds.GetSizeByIterating(),0);
}
TEST_F(TestLockFreeDeque, ConcurrentPush) {
int _count = ::RaftCore::Config::FLAGS_deque_op_count;
std::shared_ptr<int> _shp(new int(7));
auto _push_it = [&](int idx){
for (int i = 0; i < _count;++i)
this->m_ds.Push(_shp, EDequeNodeFlag::NO_COUNTING);
};
uint32_t _threads = ::RaftCore::Config::FLAGS_launch_threads_num;
this->LaunchMultipleThread(_push_it, _threads);
uint32_t _real_threads = _threads == 0 ? this->m_cpu_cores : _threads;
uint32_t _total = _count * _real_threads;
uint64_t _time_cost_us = this->GetTimeCost();
std::cout << "(M)operations per second:" << _total / float(_time_cost_us) << std::endl;
ASSERT_EQ(this->m_ds.GetSizeByIterating(), _total);
}
TEST_F(TestLockFreeDeque, ConcurrentPushPop) {
int _initial_count = 100;
for (int i = 0; i < _initial_count;++i)
this->m_ds.Push(std::make_shared<int>(i), EDequeNodeFlag::NO_COUNTING);
uint32_t _count = ::RaftCore::Config::FLAGS_deque_op_count;
auto _do_it = [&](int idx){
for (std::size_t i = 0; i < _count;++i) {
auto shp = this->m_ds.Pop();
if (!shp) {
std::cout << "thread:" << std::this_thread::get_id() << " pop empty"
<< ",size:" << this->m_ds.GetSizeByIterating() << ",i:" << i << std::endl;
continue;
}
int x = *shp;
*shp = _initial_count + x + 1;
this->m_ds.Push(shp, EDequeNodeFlag::NO_COUNTING);
}
};
uint32_t _threads = ::RaftCore::Config::FLAGS_launch_threads_num;
uint32_t _real_threads = _threads == 0 ? this->m_cpu_cores : _threads;
uint32_t _total = _count * 2 * _real_threads;
this->LaunchMultipleThread(_do_it, _threads);
uint64_t _time_cost_us = this->GetTimeCost();
std::cout << "(M)operations per second:" << _total / float(_time_cost_us) << std::endl;
ASSERT_EQ(this->m_ds.GetSizeByIterating(), _initial_count);
}
#endif
| 5,175
|
C++
|
.h
| 121
| 35.834711
| 94
| 0.6014
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,366
|
test_data_structure_base.h
|
ppLorins_aurora/src/gtest/tools/test_data_structure_base.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_DATA_STRUCTURE_BASE_H__
#define __GTEST_DATA_STRUCTURE_BASE_H__
#include <thread>
#include <vector>
#include <functional>
#include "gtest/test_base.h"
template<template<typename> typename T , typename S>
class DataStructureBase : public TestBase {
public:
template<typename ...Args>
DataStructureBase(Args&&... args) : m_ds(std::forward<Args>(args)...) { }
virtual ~DataStructureBase() {}
protected:
T<S> m_ds;
virtual void Dump() = 0;
};
#endif
| 1,314
|
C++
|
.h
| 32
| 38.0625
| 81
| 0.71485
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,367
|
test_lock_free_unordered_single_list.h
|
ppLorins_aurora/src/gtest/tools/test_lock_free_unordered_single_list.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_LOCK_FREE_UNORDERED_jSINGLE_LIST_H__
#define __GTEST_LOCK_FREE_UNORDERED_jSINGLE_LIST_H__
#include "gtest/tools/test_data_structure_base.h"
#include "tools/lock_free_unordered_single_list.h"
using ::RaftCore::DataStructure::UnorderedSingleListNode;
using ::RaftCore::DataStructure::LockFreeUnorderedSingleList;
class TestLockFreeUnorderedSingList : public DataStructureBase<LockFreeUnorderedSingleList,int> {
protected:
virtual void SetUp() override {
this->m_remain = ::RaftCore::Config::FLAGS_retain_num_unordered_single_list;
//Install GC.
std::thread _t([&]() {
//auto _f = std::bind(&LockFreeUnorderedSingleList<int>::PurgeSingleList, &(this->m_ds));
while (true) {
if (!this->m_running)
break;
this->m_ds.PurgeSingleList(this->m_remain);
}
});
_t.detach();
}
virtual void TearDown() override {
this->m_running = false;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
virtual void Dump() override {
auto _printer = [](int *p) {
std::cout << *p << " ";
};
this->m_ds.Iterate(_printer);
}
int m_remain = 10000;
bool m_running = true;
};
TEST_F(TestLockFreeUnorderedSingList, GeneralOperation) {
auto _deleter = [](int* p_data) {
std::cout << "customized deleter called" << std::endl;
delete p_data;
};
this->m_ds.SetDeleter(_deleter);
uint32_t _push_num = 5;
for (std::size_t i = 0; i < _push_num; ++i) {
int *_p_i = new int(i);
this->m_ds.PushFront(_p_i);
}
ASSERT_TRUE(this->m_ds.Size() <= _push_num);
int _retain_num = 2;
this->m_ds.PurgeSingleList(_retain_num);
ASSERT_EQ(this->m_ds.Size(), _retain_num);
std::cout << "after testing...:" << std::endl;
this->Dump();
}
TEST_F(TestLockFreeUnorderedSingList, ConcurrentOperation) {
int _count = 10000;
auto _push_it = [&](int idx){
for (int i = 0; i < _count; ++i) {
int *_p_i = new int(i);
this->m_ds.PushFront(_p_i);
}
};
this->LaunchMultipleThread(_push_it);
//Waiting for purging done.
std::this_thread::sleep_for(std::chrono::seconds(1));
//ASSERT_EQ(this->m_ds.Size() , this->m_remain) << "actual size:" << this->m_ds.Size();
std::cout << "done.";
}
#endif
| 3,334
|
C++
|
.h
| 82
| 33.512195
| 105
| 0.614117
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,368
|
test_utilities.h
|
ppLorins_aurora/src/gtest/tools/test_utilities.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_UTILITIES_H__
#define __GTEST_UTILITIES_H__
#include <list>
#include <memory>
#include <chrono>
#include <random>
#include "gtest/test_base.h"
#include "tools/utilities.h"
using ::RaftCore::Tools::TypeSysTimePoint;
class TestUtilities : public TestBase {
public:
TestUtilities() {}
virtual void SetUp() override {
}
virtual void TearDown() override {
}
protected:
};
TEST_F(TestUtilities, GeneralOperation) {
uint32_t uTest = 0x12345678;
uint32_t uTest2 = 0x78563412;
unsigned char* pTest = (unsigned char*)&uTest;
bool _big_endian = (*pTest) == 0x12;
ASSERT_EQ(::RaftCore::Tools::LocalBigEndian(), _big_endian);
uint32_t uTmp = 0x0;
::RaftCore::Tools::ConvertToBigEndian<uint32_t>(uTest,&uTmp);
if (_big_endian)
ASSERT_EQ(uTmp,uTest);
else
ASSERT_EQ(uTmp,uTest2);
uint32_t uRst1 = 0;
::RaftCore::Tools::ConvertBigEndianToLocal<uint32_t>(uTmp,&uRst1);
ASSERT_EQ(uRst1,uTest);
std::list<std::string> myself_addr;
::RaftCore::Tools::GetLocalIPs(myself_addr);
for (const auto &_item : myself_addr)
std::cout << "ip : " << _item << std::endl;
uint32_t x = 5;
ASSERT_EQ(::RaftCore::Tools::RoundUp(x),8);
ASSERT_EQ(::RaftCore::Tools::GetMask(x),3);
std::string _test_buf = "test_buf";
uint32_t _crc32_result = ::RaftCore::Tools::CalculateCRC32(_test_buf.data(), _test_buf.length());
ASSERT_EQ(_crc32_result, 0x3BF65345);
//Checking the log with VLOG level >= 90.
auto _tp = ::RaftCore::Tools::StartTimeing();
::RaftCore::Tools::EndTiming(_tp,"unit test operations");
std::list<std::string> _output;
::RaftCore::Tools::StringSplit("||def||abc||xyz|||",'|',_output);
ASSERT_EQ(_output.size(),3);
auto _iter = _output.cbegin();
ASSERT_EQ(*_iter++,"def");
ASSERT_EQ(*_iter++,"abc");
ASSERT_EQ(*_iter++,"xyz");
ASSERT_TRUE(_iter == _output.cend());
TypeSysTimePoint _deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(100);
_deadline += std::chrono::microseconds(2000);
std::cout << "now:" << ::RaftCore::Tools::TimePointToString(_deadline) << std::endl;
}
#endif
| 3,023
|
C++
|
.h
| 74
| 36.486486
| 101
| 0.67239
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,369
|
test_all.h
|
ppLorins_aurora/src/gtest/election/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_ELECTION_H__
#define __GTEST_ALL_ELECTION_H__
#include "gtest/election/test_election.h"
#endif
| 905
|
C++
|
.h
| 19
| 46.263158
| 73
| 0.748578
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,370
|
test_election.h
|
ppLorins_aurora/src/gtest/election/test_election.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ELECTION_H__
#define __GTEST_ELECTION_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "global/global_env.h"
#include "election/election.h"
using ::RaftCore::Election::ElectionMgr;
using ::RaftCore::Election::RaftRole;
class TestElection : public TestMultipleBackendFollower {
public:
TestElection() {}
protected:
virtual void SetUp() override {
this->PrepareBinlogFiles();
this->StartFollowersFunc(TestElection::GenerateFileName);
::RaftCore::Global::GlobalEnv::InitialEnv();
}
virtual void TearDown() override {
::RaftCore::Global::GlobalEnv::UnInitialEnv();
this->EndFollowers();
}
private:
void PrepareBinlogFiles()noexcept {
int _log_entry_base_num = 5;
for (int idx = 0; idx < _TEST_FOLLOWER_NUM_;++idx) {
auto _role = this->GenerateFileRole(idx);
auto _binlog_file = this->GenerateFileName(idx);
this->ConstructBinlogFile(_binlog_file,_role , _log_entry_base_num++);
}
//Construct current binlog.
this->ConstructBinlogFile(_TEST_LEADER_BINLOG_,"leader", _log_entry_base_num++);
}
void ConstructBinlogFile(const char* binlog_file,const char* role,
int entry_num) noexcept {
if (fs::exists(fs::path(binlog_file)))
ASSERT_TRUE(std::remove(binlog_file)==0);
//testing file
BinLogGlobal::m_instance.Initialize(role);
//Construct binlog file.
std::list<std::shared_ptr<::raft::Entity> > _input;
for (int i = 0; i < entry_num;++i) {
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
auto _p_pre_entity_id = _shp_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(i==0?0:i-1);
auto _p_wop = _shp_entity->mutable_write_op();
_p_wop->set_key("key_" + std::to_string(i));
_p_wop->set_value("val_" + std::to_string(i));
_input.emplace_back(_shp_entity);
}
ASSERT_TRUE(BinLogGlobal::m_instance.AppendEntry(_input));
std::list<std::shared_ptr<FileMetaData::IdxPair>> _output;
BinLogGlobal::m_instance.GetOrderedMeta(_output);
//A routine test for binlog operator.
ASSERT_TRUE(BinLogGlobal::m_instance.GetLastReplicated() == LogIdentifier(*_output.back()));
ASSERT_STREQ(BinLogGlobal::m_instance.GetBinlogFileName().c_str(),binlog_file);
BinLogGlobal::m_instance.UnInitialize();
}
static const char* GenerateFileName(int idx) noexcept {
auto _role = GenerateFileRole(idx);
static char _binlog_file[100] = {};
std::snprintf(_binlog_file,sizeof(_binlog_file),"%s.%s",_AURORA_BINLOG_NAME_,_role);
return _binlog_file;
}
static const char* GenerateFileRole(int idx) noexcept {
static char _role[100] = {};
std::snprintf(_role,sizeof(_role),"election-%d",idx);
return _role;
}
};
TEST_F(TestElection, GeneralOperation) {
//ElectionMgr::Initialize();
/*First make sure term 3 is not in the 'election.config' config file.Only
after that can we start the unit test. */
ASSERT_TRUE(ElectionMgr::TryVote(3, "12.34.56.78:100")=="");
ASSERT_TRUE(ElectionMgr::TryVote(3, "12.34.56.78:101")=="12.34.56.78:100");
ElectionMgr::AddVotingTerm(7, "12.34.56.78:200");
ElectionMgr::AddVotingTerm(7, "12.34.56.78:201");
ASSERT_TRUE(ElectionMgr::TryVote(4, "12.34.56.78:200")=="");
ElectionMgr::SwitchRole(RaftRole::FOLLOWER,"12.34.56.78:300");
ElectionMgr::SwitchRole(RaftRole::CANDIDATE);
ElectionMgr::SwitchRole(RaftRole::LEADER);
ElectionMgr::SwitchRole(RaftRole::FOLLOWER,"12.34.56.78:300");
ElectionMgr::ElectionThread();
//Waiting above thread to get fully started.
std::this_thread::sleep_for(std::chrono::seconds(3));
ElectionMgr::NotifyNewLeaderEvent(4,"12.34.56.78:300");
ElectionMgr::WaitElectionThread();
//ElectionMgr::UnInitialize();
std::cout << "test election end." << std::endl;
}
TEST_F(TestElection, Election) {
/*Waiting current leader sending heartbeat msg to followers thus triggering theirs heartbeat
checking mechanism. */
std::this_thread::sleep_for(std::chrono::seconds(2));
//Start grpc service.
std::thread* _th = new std::thread([]() {
::RaftCore::Global::GlobalEnv::RunServer();
});
//Wait for server get fully started
std::this_thread::sleep_for(std::chrono::milliseconds(500));
ElectionMgr::SwitchRole(RaftRole::FOLLOWER,"12.34.56.78:300");
//Waiting for detecting the fake leader has gone.
std::cout << "Waiting for detecting the fake leader has gone..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
//Waiting for a new leader being elected out.
std::cout << "Waiting for a new leader being elected out..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
Topology _topo;
CTopologyMgr::Read(&_topo);
std::list<std::string> _valid_new_leaders{"127.0.0.1:10022","127.0.0.1:10010"};
ASSERT_TRUE(std::find(_valid_new_leaders.cbegin(), _valid_new_leaders.cend(), _topo.m_leader) != _valid_new_leaders.cend())
<< "new leader invalid: " << _topo.m_leader;
std::cout << "new leader elected :" << _topo.m_leader << " under term:" << ElectionMgr::m_cur_term.load() << std::endl;
//Waiting for the new leader finish syncing logs with its followers.
std::cout << "Waiting for the new leader finish syncing logs with its followers..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
::RaftCore::Global::GlobalEnv::StopServer();
//Waiting for the above spawned thread exist.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
#endif
| 7,133
|
C++
|
.h
| 142
| 41.93662
| 127
| 0.63484
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,371
|
test_all.h
|
ppLorins_aurora/src/gtest/common/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_COMMON_H__
#define __GTEST_ALL_COMMON_H__
#include "gtest/common/test_comm.h"
#endif
| 895
|
C++
|
.h
| 19
| 45.736842
| 73
| 0.745685
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,372
|
test_comm.h
|
ppLorins_aurora/src/gtest/common/test_comm.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_COMMON_H__
#define __GTEST_COMMON_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "common/comm_view.h"
#include "common/comm_defs.h"
#include "common/log_identifier.h"
#include "leader/memory_log_leader.h"
#include "follower/memory_log_follower.h"
using ::RaftCore::Common::LogIdentifier;
using ::RaftCore::Leader::MemoryLogItemLeader;
using ::RaftCore::Follower::MemoryLogItemFollower;
using ::RaftCore::Common::CommonView;
using ::raft::EntityID;
class TestComm : public TestBase {
public:
TestComm() {}
virtual void SetUp() override {
}
virtual void TearDown() override {
}
};
TEST_F(TestComm, GeneralOperation) {
LogIdentifier _obj1;
_obj1.Set(3, 17);
LogIdentifier _obj2;
_obj2.Set(_obj1);
ASSERT_TRUE(_obj1==_obj2);
_obj2.m_index = 19;
ASSERT_TRUE(_obj1!=_obj2);
_obj2.m_index = 17;
ASSERT_TRUE(_obj1<=_obj2);
_obj2.m_index = 13;
ASSERT_TRUE(_obj1>_obj2);
_obj2.m_index = 17;
ASSERT_TRUE(_obj1>=_obj2);
std::cout << _obj1.ToString() << std::endl;
std::cout << _obj1 << std::endl;
EntityID _entity_id;
_entity_id.set_term(3);
_entity_id.set_idx(17);
ASSERT_TRUE(::RaftCore::Common::ConvertID(_entity_id)== _obj2);
ASSERT_TRUE(::RaftCore::Common::EntityIDEqual(_entity_id, _obj2));
_obj2.m_index = 19;
//ASSERT_TRUE(::RaftCore::Common::EntityIDNotEqual(_entity_id, _obj2));
_obj2.m_index = 13;
ASSERT_TRUE(::RaftCore::Common::EntityIDLarger(_entity_id, _obj2));
_obj2.m_index = 19;
ASSERT_TRUE(::RaftCore::Common::EntityIDSmaller(_entity_id, _obj2));
_obj2.m_index = 17;
//ASSERT_TRUE(::RaftCore::Common::EntityIDSmallerEqual(_entity_id, _obj2));
MemoryLogItemLeader _ldr1(3,17);
MemoryLogItemLeader _ldr2(3,19);
MemoryLogItemLeader _ldr3(*_ldr1.GetEntity());
ASSERT_TRUE(_ldr1<_ldr2);
ASSERT_TRUE(_ldr2>_ldr1);
ASSERT_TRUE(_ldr1==_ldr3);
MemoryLogItemFollower _f1(3,17);
MemoryLogItemFollower _f2(*_f1.GetEntity());
MemoryLogItemFollower _f3(3,19);
ASSERT_TRUE(_f1<=_f2);
ASSERT_TRUE(_f1<_f3);
ASSERT_TRUE(_f3>_f1);
ASSERT_TRUE(_f1==_f2);
ASSERT_TRUE(_f1!=_f3);
CommonView::Initialize();
CommonView::UnInitialize();
}
#endif
| 3,134
|
C++
|
.h
| 86
| 32.44186
| 79
| 0.68449
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,373
|
test_all.h
|
ppLorins_aurora/src/gtest/state/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_STATE_H__
#define __GTEST_ALL_STATE_H__
#include "gtest/state/test_state.h"
#endif
| 893
|
C++
|
.h
| 19
| 45.631579
| 73
| 0.745098
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,374
|
test_state.h
|
ppLorins_aurora/src/gtest/state/test_state.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_STATE_H__
#define __GTEST_STATE_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "state/state_mgr.h"
#include "topology/topology_mgr.h"
using ::RaftCore::State::RaftRole;
using ::RaftCore::State::StateMgr;
using ::RaftCore::Topology;
using ::RaftCore::CTopologyMgr;
class TestState : public TestBase {
public:
TestState() {}
virtual void SetUp() override {
}
virtual void TearDown() override {
}
};
TEST_F(TestState, GeneralOperation) {
CTopologyMgr::Initialize();
Topology _topo;
CTopologyMgr::Read(&_topo);
StateMgr::Initialize(_topo);
auto _state = StateMgr::GetRole();
ASSERT_EQ(_state, RaftRole::LEADER);
ASSERT_STREQ(StateMgr::GetRoleStr(), "leader");
ASSERT_STREQ(StateMgr::GetMyAddr().c_str(),this->m_leader_addr.c_str());
//---------------Leader --> Follower----------------//
#define _NEW_LEADER_ADDRESS_ "192.168.0.100:10077"
int _old_follower_size = _topo.m_followers.size();
StateMgr::SwitchTo(RaftRole::FOLLOWER,_NEW_LEADER_ADDRESS_);
_state = StateMgr::GetRole();
ASSERT_EQ(_state, RaftRole::FOLLOWER);
ASSERT_STREQ(StateMgr::GetRoleStr(), "follower");
CTopologyMgr::Read(&_topo);
ASSERT_STREQ(_topo.m_leader.c_str(),_NEW_LEADER_ADDRESS_);
int _new_follower_size = _topo.m_followers.size();
ASSERT_EQ(_old_follower_size + 1, _new_follower_size );
ASSERT_TRUE(std::find(_topo.m_followers.cbegin(),_topo.m_followers.cend(),this->m_leader_addr) != _topo.m_followers.cend());
StateMgr::UnInitialize();
}
#endif
| 2,417
|
C++
|
.h
| 59
| 37.40678
| 128
| 0.694981
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,375
|
test_all.h
|
ppLorins_aurora/src/gtest/topology/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_TOPOLOGY_H__
#define __GTEST_ALL_TOPOLOGY_H__
#include "gtest/topology/test_topology.h"
#endif
| 905
|
C++
|
.h
| 19
| 46.263158
| 73
| 0.748578
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,376
|
test_topology.h
|
ppLorins_aurora/src/gtest/topology/test_topology.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_TOPOLOGY_H__
#define __GTEST_TOPOLOGY_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "topology/topology_mgr.h"
using ::RaftCore::Topology;
using ::RaftCore::CTopologyMgr;
class TestTopology : public TestBase {
public:
TestTopology() {}
virtual void SetUp() override {
CTopologyMgr::Initialize();
}
virtual void TearDown() override {
CTopologyMgr::UnInitialize();
}
void GeneralOP() noexcept{
Topology _topo;
CTopologyMgr::Read(&_topo);
std::cout << _topo;
_topo.m_leader = "some content";
_topo.Reset();
ASSERT_EQ(_topo.m_leader,"");
_topo.m_leader = "";
_topo.m_followers.emplace("127.0.0.1:3000");
_topo.m_followers.emplace("127.0.0.1:3001");
_topo.m_candidates.emplace("127.0.0.1:3002");
_topo.m_candidates.emplace("127.0.0.1:3003");
ASSERT_EQ(_topo.GetClusterSize(),5);
ASSERT_TRUE(_topo.InCurrentCluster("127.0.0.1:3000"));
ASSERT_FALSE(_topo.InCurrentCluster("127.0.0.1:3005"));
_topo.m_leader = "new value";
CTopologyMgr::Update(_topo);
std::cout << _topo;
}
};
TEST_F(TestTopology, GeneralOperation) {
this->GeneralOP();
}
TEST_F(TestTopology, ConcurrentOperation) {
auto _op = [&](int idx) {
int _run_times = 100;
for (int i = 0; i < _run_times; ++i) {
this->GeneralOP();
}
};
this->LaunchMultipleThread(_op);
}
#endif
| 2,441
|
C++
|
.h
| 66
| 30.424242
| 73
| 0.626917
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,377
|
test_all.h
|
ppLorins_aurora/src/gtest/guid/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_GUID_H__
#define __GTEST_ALL_GUID_H__
#include "gtest/guid/test_guid.h"
#endif
| 889
|
C++
|
.h
| 19
| 45.421053
| 73
| 0.743917
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,378
|
test_guid.h
|
ppLorins_aurora/src/gtest/guid/test_guid.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_GUID_H__
#define __GTEST_GUID_H__
#include <list>
#include <memory>
#include <chrono>
#include "boost/filesystem.hpp"
#include "gtest/test_base.h"
#include "guid/guid_generator.h"
using ::RaftCore::Guid::GuidGenerator;
namespace fs = ::boost::filesystem;
class TestGuid : public TestBase {
public:
TestGuid() {}
virtual void SetUp() override {
m_i.store(0);
}
virtual void TearDown() override {
}
protected:
std::vector<uint64_t> *m_vec_output = new std::vector<uint64_t>[this->m_cpu_cores];
std::atomic<int> m_i;
};
TEST_F(TestGuid, GeneralOperation) {
uint64_t _base = 100;
GuidGenerator::Initialize(_base);
uint64_t _pre = _base;
uint64_t _last_release = _base;
for (int i = 1; i <= 50 ; ++i) {
GuidGenerator::GUIDPair _pair = GuidGenerator::GenerateGuid();
uint64_t _cur = _last_release + 1;
ASSERT_EQ(_pair.m_pre_guid,_pre);
ASSERT_EQ(_pair.m_cur_guid,_cur);
_pre = _cur;
_last_release = _cur;
}
_base = 300;
_last_release = _base;
GuidGenerator::SetNextBasePoint(_base);
GuidGenerator::GUIDPair _pair = GuidGenerator::GenerateGuid();
ASSERT_EQ(_pair.m_pre_guid, _base);
ASSERT_EQ(_pair.m_cur_guid, _last_release + 1);
ASSERT_EQ(GuidGenerator::GetLastReleasedGuid(), _last_release + 1);
GuidGenerator::UnInitialize();
}
TEST_F(TestGuid, ConcurrentOperation) {
GuidGenerator::Initialize();
auto _op = [&](int idx) {
int _counter = 0;
for (int i = 1; i <= 100 ; ++i) {
GuidGenerator::GUIDPair _pair = GuidGenerator::GenerateGuid();
std::cout << std::this_thread::get_id() << " generate: " << _pair.m_pre_guid << "|"
<< _pair.m_cur_guid << std::endl;
_counter++;
if (_counter > 20) {
std::cout << std::this_thread::get_id() << " last guid: " << GuidGenerator::GetLastReleasedGuid() << std::endl;
GuidGenerator::SetNextBasePoint(_pair.m_cur_guid - 5);
_counter = 0;
}
m_vec_output[idx].push_back(_pair.m_cur_guid);
}
};
this->LaunchMultipleThread(_op);
//merge vectors
std::vector<uint64_t> _total_vec;
for (int i = 0; i < this->m_cpu_cores; ++i)
_total_vec.insert(_total_vec.cend(),m_vec_output[i].cbegin(),m_vec_output[i].cend());
std::sort(_total_vec.begin(), _total_vec.end());
//for (const auto & _item : _total_vec)
// std::cout << "final :" << _item << std::endl;
GuidGenerator::UnInitialize();
}
#endif
| 3,456
|
C++
|
.h
| 87
| 33.689655
| 127
| 0.624135
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,379
|
test_all.h
|
ppLorins_aurora/src/gtest/member/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_MEMBER_H__
#define __GTEST_ALL_MEMBER_H__
#include "gtest/member/test_member.h"
#endif
| 897
|
C++
|
.h
| 19
| 45.842105
| 73
| 0.746269
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,380
|
test_member.h
|
ppLorins_aurora/src/gtest/member/test_member.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_MEMBER_H__
#define __GTEST_MEMBER_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "global/global_env.h"
#include "common/comm_defs.h"
#include "binlog/binlog_singleton.h"
#include "storage/storage_singleton.h"
#include "member/member_manager.h"
using ::RaftCore::Common::ReadLock;
using ::RaftCore::Member::MemberMgr;
using ::RaftCore::BinLog::BinLogGlobal;
using ::RaftCore::Storage::StorageGlobal;
using ::RaftCore::Leader::BackGroundTask::TwoPhaseCommitContext;
class TestMember : public TestCluster {
public:
//Start several normal servers and 2 empty servers.
TestMember() : TestCluster(2) {}
protected:
virtual void SetUp() override {}
virtual void TearDown() override {}
virtual void SetStoragePoint(int backoff = 10) {
auto _lrl = BinLogGlobal::m_instance.GetLastReplicated();
LogIdentifier _lcl;
_lcl.Set(0, _lrl.m_index - backoff);
StorageGlobal::m_instance.Set(_lcl,"lcl_key","lcl_val");
}
virtual void IssueMemberChangeRequest() {
std::shared_ptr<::grpc::Channel> _channel = grpc::CreateChannel(this->m_leader_addr, grpc::InsecureChannelCredentials());
std::unique_ptr<::raft::RaftService::Stub> _stub = ::raft::RaftService::NewStub(_channel);
::raft::MemberChangeRequest _memchg_req;
::raft::MemberChangeResponse _memchg_rsp;
std::set<std::string> _new_cluster = this->m_cluster_leader_not_gone;
if (::RaftCore::Config::FLAGS_member_leader_gone)
_new_cluster = this->m_cluster_leader_gone;
for (const auto &_item : _new_cluster) {
auto *_node = _memchg_req.add_node_list();
*_node = _item;
}
::grpc::ClientContext _contextX;
::grpc::Status _status = _stub->MembershipChange(&_contextX, _memchg_req, &_memchg_rsp);
ASSERT_TRUE(_status.ok());
ASSERT_TRUE(_memchg_rsp.client_comm_rsp().result()==::raft::ErrorCode::SUCCESS) << "ClientWrite fail,detail:" << _memchg_rsp.DebugString();
}
protected:
std::set<std::string> m_cluster_leader_not_gone{"127.0.0.1:10010","127.0.0.1:10022", // old nodes.
"127.0.0.1:10030","127.0.0.1:10031"}; // new empty nodes.
std::set<std::string> m_cluster_leader_gone{"127.0.0.1:10022", // old nodes.
"127.0.0.1:10030","127.0.0.1:10031"}; // new empty nodes.
};
TEST_F(TestMember, GeneralOperation) {
std::cout << "member version:" << MemberMgr::GetVersion();
this->SetStoragePoint();
std::set<std::string> _new_cluster = this->m_cluster_leader_not_gone;
if (::RaftCore::Config::FLAGS_member_leader_gone)
_new_cluster = this->m_cluster_leader_gone;
MemberMgr::PullTrigger(_new_cluster);
MemberMgr::ContinueExecution();
auto _old_version = MemberMgr::GetVersion();
//Give enough time to wait for the membership change finish.
while(true) {
ReadLock _r_lock(MemberMgr::m_mutex);
auto _new_version = MemberMgr::m_joint_summary.m_version;
//Note:A two phase membership replication will eventually causing version increased by 2.
if (_new_version == (_old_version + 2))
break;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
//Wait routine to finish.
std::this_thread::sleep_for(std::chrono::seconds(2));
//Wait for the new cluster to elect out a new leader.
if (::RaftCore::Config::FLAGS_member_leader_gone)
std::this_thread::sleep_for(std::chrono::seconds(5));
}
TEST_F(TestMember, WriteData) {
this->SetStoragePoint();
//Step 1. start membership changing but just finish phaseI.
this->IssueMemberChangeRequest();
//Waiting for sync-data process to finish and leader switched to joint consensus state.
std::this_thread::sleep_for(std::chrono::seconds(20));
//Step 2. start writing data through server's public rpc interface.
this->ClientWrite("memberchg_key","memberchg_val");
std::this_thread::sleep_for(std::chrono::seconds(3));
//Step 3. manually check whether the appending log requests are propagated to both C-old and C-new,and judge by it.
//Step 4. resume execution of the pending routine thread.
MemberMgr::ContinueExecution();
//Waiting for continue to complete.
std::this_thread::sleep_for(std::chrono::seconds(2));
//Step 5. write again
this->ClientWrite("memberchg_second_key","memberchg_second_val");
//Step 6. manually check whether the appending log requests are propagated to only C-new,and judge by it.
}
TEST_F(TestMember, Election) {
//Use a short binlog.
this->SetStoragePoint(5);
//Step 1. start membership changing but just finish phaseI.
this->IssueMemberChangeRequest();
//Waiting for sync-data process to finish and leader switched to joint consensus state.
std::this_thread::sleep_for(std::chrono::seconds(5));
//Step 2. start election by start and then stop the heartbeat.
::RaftCore::Config::FLAGS_do_heartbeat = true;
LOG(INFO) << "starting heartbeat..." << std::endl;;
//Waiting for the heartbeat message to be sent out.
std::this_thread::sleep_for(std::chrono::seconds(3));
LOG(INFO) << "stopping heartbeat..." << std::endl;;
//Stop sending heartbeat.
::RaftCore::Config::FLAGS_heartbeat_oneshot = true;
LOG(INFO) << "wait heartbeat timeout..." << std::endl;;
//Waiting for heartbeat timeout
std::this_thread::sleep_for(std::chrono::seconds(3));
//Waiting for election finished.
std::this_thread::sleep_for(std::chrono::seconds(3));
//Step 3. manually check whether the election requests are propagated to both C-old and C-new,and judge by it.
}
#endif
| 6,743
|
C++
|
.h
| 132
| 44.348485
| 151
| 0.669008
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,381
|
test_all.h
|
ppLorins_aurora/src/gtest/candidate/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_CANDIDATE_H__
#define __GTEST_ALL_CANDIDATE_H__
#include "gtest/candidate/test_candidate.h"
#endif
| 909
|
C++
|
.h
| 19
| 46.473684
| 73
| 0.749717
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,382
|
test_candidate.h
|
ppLorins_aurora/src/gtest/candidate/test_candidate.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_CANDIDATE_H__
#define __GTEST_CANDIDATE_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "candidate/candidate_view.h"
using ::RaftCore::Candidate::CandidateView;
class TestCandidate : public TestBase {
public:
TestCandidate() {}
~TestCandidate() {}
protected:
virtual void SetUp() override {}
virtual void TearDown() override {}
};
TEST_F(TestCandidate, GeneralOperation) {
CandidateView::Initialize();
CandidateView::UnInitialize();
std::cout << "test candidate end." << std::endl;
}
#endif
| 1,410
|
C++
|
.h
| 37
| 35.108108
| 73
| 0.725389
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,383
|
test_all.h
|
ppLorins_aurora/src/gtest/global/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_GLOBAL_H__
#define __GTEST_ALL_GLOBAL_H__
#include "gtest/global/test_global.h"
#endif
| 897
|
C++
|
.h
| 19
| 45.842105
| 73
| 0.746269
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,384
|
test_global.h
|
ppLorins_aurora/src/gtest/global/test_global.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_GLOBAL_H__
#define __GTEST_GLOBAL_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "global/global_env.h"
#include "state/state_mgr.h"
using ::RaftCore::Global::GlobalEnv;
using ::RaftCore::State::RaftRole;
class TestGlobalEnv : public TestMultipleBackendFollower {
public:
TestGlobalEnv() {}
virtual void SetUp() override {
this->StartFollowers();
}
virtual void TearDown() override {
this->EndFollowers();
}
};
TEST_F(TestGlobalEnv, GeneralOperation) {
::RaftCore::Global::GlobalEnv::InitialEnv();
std::cout << "server is going to run 1st time..." << std::endl;
std::thread* _th = new std::thread([]() {
::RaftCore::Global::GlobalEnv::RunServer();
});
std::this_thread::sleep_for(std::chrono::seconds(3));
::RaftCore::Global::GlobalEnv::StopServer();
::RaftCore::Global::GlobalEnv::UnInitialEnv(RaftRole::LEADER);
_th->join();
std::cout << "server is stopped now 1st time..." << std::endl;
::RaftCore::Global::GlobalEnv::InitialEnv(true);
std::cout << "server is going to run 2nd time..." << std::endl;
_th = new std::thread([]() {
::RaftCore::Global::GlobalEnv::RunServer();
});
std::this_thread::sleep_for(std::chrono::seconds(3));
::RaftCore::Global::GlobalEnv::StopServer();
::RaftCore::Global::GlobalEnv::UnInitialEnv(RaftRole::LEADER);
_th->join();
std::cout << "server is stopped now 2nd time..." << std::endl;
::RaftCore::Global::GlobalEnv::InitialEnv(true);
std::cout << "server is going to run 3rd time..." << std::endl;
_th = new std::thread([]() {
::RaftCore::Global::GlobalEnv::RunServer();
});
::RaftCore::Global::GlobalEnv::ShutDown();
std::cout << "server is stopped now 3rd time..." << std::endl;
}
#endif
| 2,690
|
C++
|
.h
| 65
| 36.969231
| 73
| 0.668082
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,385
|
test_all.h
|
ppLorins_aurora/src/gtest/follower/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_FOLLOWER_H__
#define __GTEST_ALL_FOLLOWER_H__
#include "gtest/follower/test_follower.h"
#endif
| 905
|
C++
|
.h
| 19
| 46.263158
| 73
| 0.748578
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,386
|
test_follower.h
|
ppLorins_aurora/src/gtest/follower/test_follower.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_FOLLOWER_H__
#define __GTEST_FOLLOWER_H__
#include <list>
#include <memory>
#include <chrono>
#include "gtest/test_base.h"
#include "follower/follower_view.h"
using ::RaftCore::Follower::FollowerView;
class TestFollower : public TestBase {
public:
TestFollower() {}
protected:
virtual void SetUp() override {
}
virtual void TearDown() override {
}
};
TEST_F(TestFollower, GeneralOperation) {
FollowerView::Initialize();
FollowerView::Clear();
FollowerView::UnInitialize();
std::cout << "test follower end." << std::endl;
}
#endif
| 1,414
|
C++
|
.h
| 39
| 33.076923
| 73
| 0.717873
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,387
|
test_all.h
|
ppLorins_aurora/src/gtest/client/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_CLIENT_H__
#define __GTEST_ALL_CLIENT_H__
#include "gtest/client/test_client.h"
#endif
| 897
|
C++
|
.h
| 19
| 45.842105
| 73
| 0.746269
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,388
|
test_client.h
|
ppLorins_aurora/src/gtest/client/test_client.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_CLIENT_H__
#define __GTEST_CLIENT_H__
#include "gtest/test_base.h"
#include "client/client_impl.h"
using ::RaftCore::Client::AppendEntriesAsyncClient;
class TestClient : public TestBase {
public:
TestClient() {}
virtual void SetUp() override {
auto _channel_args = ::grpc::ChannelArguments();
this->m_shp_channel = ::grpc::CreateCustomChannel(this->m_leader_addr, ::grpc::InsecureChannelCredentials(), _channel_args);
}
virtual void TearDown() override {
}
protected:
std::shared_ptr<::grpc::Channel> m_shp_channel;
};
TEST_F(TestClient, GeneralOperation) {
std::shared_ptr<CompletionQueue> _shp_cq;
for (std::size_t i = 0; i < ::RaftCore::Config::FLAGS_client_count; ++i)
auto *_obj_client = new AppendEntriesAsyncClient(this->m_shp_channel, _shp_cq);
std::this_thread::sleep_for(std::chrono::seconds(30));
}
#endif
| 1,741
|
C++
|
.h
| 39
| 40.512821
| 136
| 0.70119
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,389
|
test_all.h
|
ppLorins_aurora/src/gtest/binlog/test_all.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_ALL_BINLOG_H__
#define __GTEST_ALL_BINLOG_H__
#include "gtest/binlog/test_meta.h"
#include "gtest/binlog/test_binlog.h"
#endif
| 933
|
C++
|
.h
| 20
| 45.3
| 73
| 0.747241
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,390
|
test_binlog.h
|
ppLorins_aurora/src/gtest/binlog/test_binlog.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_BINLOG_H__
#define __GTEST_BINLOG_H__
#include <list>
#include <memory>
#include <chrono>
#include "boost/filesystem.hpp"
#include "gtest/test_base.h"
#include "common/comm_defs.h"
#include "binlog/binlog_singleton.h"
#include "storage/storage_singleton.h"
#include "leader/leader_view.h"
using ::RaftCore::BinLog::BinLogGlobal;
using ::RaftCore::BinLog::BinLogOperator;
using ::RaftCore::Storage::StorageGlobal;
using ::RaftCore::Leader::LeaderView;
using ::RaftCore::DataStructure::HashNode;
namespace fs = ::boost::filesystem;
class TestBinlog : public TestBase {
public:
TestBinlog() {}
protected:
virtual void SetUp() override {
m_zero.Set(0, 0);
}
virtual void TearDown() override {
}
auto RevertPreviousLogs(int cur_idx,int thread_idx) {
//test reverting.
std::list<std::shared_ptr<MemoryLogItemFollower>> _log_list;
int _pre_count = 3;
for (int i = cur_idx - _pre_count; i <= cur_idx; ++i) {
::raft::Entity _tmp;
auto _p_id = _tmp.mutable_entity_id();
_p_id->set_term(0);
_p_id->set_idx(i);
auto _p_pre_id = _tmp.mutable_pre_log_id();
_p_pre_id->set_term(0);
_p_pre_id->set_idx(i-1);
auto _p_wop = _tmp.mutable_write_op();
char sz_val[1024] = { 0 };
//std::snprintf(sz_val,sizeof(sz_val),"val_%d tid:%d",i,thread_idx);
std::snprintf(sz_val,sizeof(sz_val),"val_%d",i);
_p_wop->set_key("key_" + std::to_string(i));
_p_wop->set_value(sz_val);
_log_list.emplace_back(new MemoryLogItemFollower(_tmp));
}
return BinLogGlobal::m_instance.RevertLog(_log_list, this->m_zero);
}
LogIdentifier m_zero;
};
TEST_F(TestBinlog, GeneralOperation) {
//Remove existing binlog file first.
const char *_role = "test";
std::string _binlog_file = _AURORA_BINLOG_NAME_ + std::string(".") + _role;
if (fs::exists(fs::path(_binlog_file)))
ASSERT_TRUE(std::remove(_binlog_file.c_str())==0);
//testing file
BinLogGlobal::m_instance.Initialize(_role);
//Construct binlog file.
std::list<std::shared_ptr<::raft::Entity> > _input;
for (int i = 0; i < 10;++i) {
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
auto _p_pre_entity_id = _shp_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(i==0?0:i-1);
auto _p_wop = _shp_entity->mutable_write_op();
_p_wop->set_key("key_" + std::to_string(i));
_p_wop->set_value("val_" + std::to_string(i));
_input.emplace_back(_shp_entity);
}
ASSERT_TRUE(BinLogGlobal::m_instance.AppendEntry(_input));
std::list<std::shared_ptr<FileMetaData::IdxPair>> _output;
BinLogGlobal::m_instance.GetOrderedMeta(_output);
ASSERT_TRUE(BinLogGlobal::m_instance.GetLastReplicated() == LogIdentifier(*_output.back()));
ASSERT_TRUE(BinLogGlobal::m_instance.GetBinlogFileName() == _binlog_file);
//test reverting.
std::list<std::shared_ptr<MemoryLogItemFollower>> _log_list;
/*This is test case is for 1> 3) of the scenarios mentioned in the implementation
of BinLogGlobal::m_instance.RevertLog function.Others too less error prone to test. */
for (int i = 6; i <= 15; ++i) {
::raft::Entity _tmp;
auto _p_id = _tmp.mutable_entity_id();
_p_id->set_term(0);
_p_id->set_idx(i);
auto _p_pre_id = _tmp.mutable_pre_log_id();
_p_pre_id->set_term(0);
_p_pre_id->set_idx(i-1);
auto _p_wop = _tmp.mutable_write_op();
int idx = i <= 7 ? i : i+1;
std::string _cur_idx = std::to_string(idx);
_p_wop->set_key("key_" + _cur_idx);
_p_wop->set_value("val_" + _cur_idx);
_log_list.emplace_back(new MemoryLogItemFollower(_tmp));
}
BinLogGlobal::m_instance.RevertLog(_log_list, this->m_zero);
//Setting Head.
int _head_idx = 13317;
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(_head_idx);
auto _p_wop = _shp_entity->mutable_write_op();
std::string _cur_idx = std::to_string(_head_idx);
_p_wop->set_key("key_head_" + _cur_idx);
_p_wop->set_value("val_head_" + _cur_idx);
BinLogGlobal::m_instance.SetHead(_shp_entity);
BinLogGlobal::m_instance.UnInitialize();
}
//TODO: figure out why binlog consume so much memory: 8w ~25MB.
TEST_F(TestBinlog, ConcurrentOperation) {
//Remove existing binlog file first.
const char *_role = "test";
std::string _binlog_file = _AURORA_BINLOG_NAME_ + std::string(".") + _role;
if (fs::exists(fs::path(_binlog_file)))
ASSERT_TRUE(std::remove(_binlog_file.c_str())==0);
//testing file
BinLogGlobal::m_instance.Initialize(_role);
int _sum = 10000;
auto _op = [&](int thread_idx) {
int _revert_each = 100;
int _revert_counter = 0;
for (int i=thread_idx; i < _sum*this->m_cpu_cores;i+=this->m_cpu_cores) {
std::list<std::shared_ptr<::raft::Entity> > _input;
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
auto _p_pre_entity_id = _shp_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(i==0?0:i-1);
auto _p_wop = _shp_entity->mutable_write_op();
std::string _cur_idx = std::to_string(i);
char sz_val[1024] = { 0 };
//std::snprintf(sz_val,sizeof(sz_val),"val_%d tid:%d",i,thread_idx);
std::snprintf(sz_val,sizeof(sz_val),"val_%d",i);
_p_wop->set_key("key_" + _cur_idx);
_p_wop->set_value(sz_val);
_input.emplace_back(_shp_entity);
ASSERT_TRUE(BinLogGlobal::m_instance.AppendEntry(_input));
if (_revert_counter >= _revert_each) {
auto _revert_code = this->RevertPreviousLogs(i,thread_idx);
//ASSERT_TRUE(_revert_code == BinLogOperator::BinlogErrorCode::SUCCEED_TRUNCATED || _revert_code == BinLogOperator::BinlogErrorCode::OTHER_ERROR) << "error code:" << _revert_code;
if (_revert_code == BinLogOperator::BinlogErrorCode::SUCCEED_TRUNCATED) {
std::cout << "!!!!!!!! revert succeed,cur_idx:" << i << ",thread_idx:" << thread_idx << std::endl;
}
if(_revert_code != BinLogOperator::BinlogErrorCode::SUCCEED_TRUNCATED && _revert_code != BinLogOperator::BinlogErrorCode::OTHER_ERROR)
std::cout << "----------error code:" << int(_revert_code) << ",cur_idx:" << i
<< ",thread_idx:" << thread_idx << std::endl;
_revert_counter = 0;
}
std::cout << BinLogGlobal::m_instance.GetLastReplicated() << ",thread_idx:" << thread_idx << std::endl;
_revert_counter++;
}
ASSERT_TRUE(BinLogGlobal::m_instance.GetBinlogFileName() == _binlog_file);
};
this->LaunchMultipleThread(_op);
LogIdentifier _end_log_id;
_end_log_id.Set(0,_sum * this->m_cpu_cores - 1);
ASSERT_TRUE(BinLogGlobal::m_instance.GetLastReplicated()==_end_log_id);
BinLogGlobal::m_instance.UnInitialize();
}
TEST_F(TestBinlog, SetHead) {
//Remove existing binlog file first.
const char *_role = "setHead";
std::string _binlog_file = _AURORA_BINLOG_NAME_ + std::string(".") + _role;
if (fs::exists(fs::path(_binlog_file)))
ASSERT_TRUE(std::remove(_binlog_file.c_str())==0);
//testing file
BinLogGlobal::m_instance.Initialize(_role);
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
int i = 17;
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
auto _p_wop = _shp_entity->mutable_write_op();
_p_wop->set_key("key_" + std::to_string(i));
_p_wop->set_value("val_" + std::to_string(i));
BinLogGlobal::m_instance.SetHead(_shp_entity);
i = 19;
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
_p_wop = _shp_entity->mutable_write_op();
_p_wop->set_key("key_" + std::to_string(i));
_p_wop->set_value("val_" + std::to_string(i));
BinLogGlobal::m_instance.SetHead(_shp_entity);
BinLogGlobal::m_instance.UnInitialize();
}
TEST_F(TestBinlog, RotateFile) {
::RaftCore::Config::FLAGS_binlog_max_size = 100;
::RaftCore::Config::FLAGS_binlog_reserve_log_num = 2;
//Remove existing binlog file first.
const char *_role = "test";
std::string _binlog_file = _AURORA_BINLOG_NAME_ + std::string(".") + _role;
if (fs::exists(fs::path(_binlog_file)))
ASSERT_TRUE(std::remove(_binlog_file.c_str())==0);
//testing file
BinLogGlobal::m_instance.Initialize(_role);
//Set storage first.
ASSERT_TRUE(StorageGlobal::m_instance.Initialize(_ROLE_STR_TEST_));
LogIdentifier _lcl_id;
_lcl_id.Set(0, 5);
ASSERT_TRUE(StorageGlobal::m_instance.Set(_lcl_id,"k","v"));
//Construct binlog file.
std::list<std::shared_ptr<::raft::Entity> > _input;
for (int i = 0; i < 10;++i) {
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
auto _p_pre_entity_id = _shp_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(i==0?0:i-1);
auto _p_wop = _shp_entity->mutable_write_op();
_p_wop->set_key("key_" + std::to_string(i));
_p_wop->set_value("val_" + std::to_string(i));
_input.emplace_back(_shp_entity);
}
ASSERT_TRUE(BinLogGlobal::m_instance.AppendEntry(_input));
BinLogGlobal::m_instance.UnInitialize();
}
TEST_F(TestBinlog, Perf) {
//Remove existing binlog file first.
const char *_role = "test";
std::string _binlog_file = _AURORA_BINLOG_NAME_ + std::string(".") + _role;
if (fs::exists(fs::path(_binlog_file)))
ASSERT_TRUE(std::remove(_binlog_file.c_str())==0);
//testing file
BinLogGlobal::m_instance.Initialize(_role);
auto _start = std::chrono::steady_clock::now();
int _write_times = 10000;
int _count_each_time = 20;
uint32_t _start_idx = 0;
for (int i = 0; i < _write_times; ++i) {
std::list<std::shared_ptr<::raft::Entity> > _input;
_start_idx = i * _count_each_time;
for (int j = _start_idx; j < _count_each_time;++j) {
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
auto _p_pre_entity_id = _shp_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(j==0?0:j-1);
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(j);
auto _p_wop = _shp_entity->mutable_write_op();
_p_wop->set_key("key_" + std::to_string(j));
_p_wop->set_value("val_" + std::to_string(j));
_input.emplace_back(_shp_entity);
}
ASSERT_TRUE(BinLogGlobal::m_instance.AppendEntry(_input));
}
auto _end = std::chrono::steady_clock::now();
auto _ms = std::chrono::duration_cast<std::chrono::microseconds>(_end - _start).count();
std::cout << "time cost:" << _ms << " us with write " << _write_times << " times,"
<< _count_each_time << " items for each write, avg " << _ms/float(_write_times) << " us for each write.";
BinLogGlobal::m_instance.UnInitialize();
}
#endif
| 13,012
|
C++
|
.h
| 275
| 39.501818
| 195
| 0.597846
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,391
|
test_meta.h
|
ppLorins_aurora/src/gtest/binlog/test_meta.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __GTEST_META_H__
#define __GTEST_META_H__
#include <list>
#include <memory>
#include <cstdio>
#include <chrono>
#include "gtest/test_base.h"
#include "binlog/binlog_meta_data.h"
#include "binlog/binlog_singleton.h"
/*
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>*/
using ::RaftCore::BinLog::FileMetaData;
using ::RaftCore::BinLog::BinLogGlobal;
using ::RaftCore::Common::LogIdentifier;
using ::RaftCore::DataStructure::HashNode;
class TestMeta : public TestBase {
public:
TestMeta() {}
virtual void SetUp() override {
}
virtual void TearDown() override {
}
protected:
void GenerateTestMeta(int _sum,FileMetaData &_meta){
int _counter = 0;
bool _add_batch = true;
std::list<std::shared_ptr<FileMetaData::IdxPair>> _list;
for (int i = 0; i < _sum; ++i) {
_counter++;
if (_counter <= 5) {
std::shared_ptr<FileMetaData::IdxPair> _shp_pair(new FileMetaData::IdxPair(10, i, i, 79, 79));
_list.emplace_back(_shp_pair);
if (i == _sum - 1)
_meta.AddLogOffset(_list);
continue;
}
if (_add_batch) {
std::shared_ptr<FileMetaData::IdxPair> _shp_pair(new FileMetaData::IdxPair(10, i, i, 79, 79));
_list.emplace_back(_shp_pair);
_meta.AddLogOffset(_list);
_add_batch = false;
_list.clear();
continue;
}
//add single
_meta.AddLogOffset(10,i,i,79,79);
_add_batch = true;
_counter = 0;
}
}
void CheckMetaListEqual(const std::list<std::shared_ptr<FileMetaData::IdxPair>> &_output1,
const std::list<std::shared_ptr<FileMetaData::IdxPair>> &_output2) {
ASSERT_EQ(_output1.size(),_output2.size());
auto _iter2 = _output2.cbegin();
for (auto _iter = _output1.cbegin(); _iter != _output1.cend();++_iter,++_iter2) {
ASSERT_TRUE(**_iter == **_iter2);
}
}
void CheckMetaEqual(const FileMetaData &meta1,const FileMetaData &meta2) {
std::list<std::shared_ptr<FileMetaData::IdxPair>> _output1;
meta1.GetOrderedMeta(_output1);
std::list<std::shared_ptr<FileMetaData::IdxPair>> _output2;
meta2.GetOrderedMeta(_output2);
this->CheckMetaListEqual(_output1, _output2);
}
};
TEST_F(TestMeta, GeneralOperation) {
//testing IdxPair.
FileMetaData::IdxPair _pair_1(10,20,30,40,50);
FileMetaData::IdxPair _pair_2(10,21,30,40,50);
ASSERT_TRUE(_pair_1 < _pair_2);
FileMetaData::IdxPair _pair_3(10,20,30,40,50);
ASSERT_TRUE(_pair_1 == _pair_3);
std::cout << _pair_3.Hash() << std::endl;
FileMetaData::IdxPair _pair_4(10,19,30,40,50);
ASSERT_TRUE(_pair_1 > _pair_4);
LogIdentifier _log_id1;
_log_id1.Set(10,19);
ASSERT_TRUE(_pair_1 > _log_id1);
ASSERT_TRUE(_pair_1 >= _log_id1);
LogIdentifier _log_id2;
_log_id2.Set(10,21);
ASSERT_TRUE(_pair_1<_log_id2);
ASSERT_TRUE(_pair_1<=_log_id2);
::raft::EntityID _entity_id;
_entity_id.set_term(10);
_entity_id.set_idx(21);
ASSERT_TRUE(_pair_1<_entity_id);
_entity_id.set_idx(19);
ASSERT_TRUE(_pair_1>_entity_id);
ASSERT_TRUE(_pair_1!=_entity_id);
_entity_id.set_idx(20);
ASSERT_TRUE(_pair_1==_entity_id);
//testing FileMetaData.
int _sum = 10000;
FileMetaData _meta;
this->GenerateTestMeta(_sum,_meta);
std::list<std::shared_ptr<FileMetaData::IdxPair>> _output;
_meta.GetOrderedMeta(_output);
ASSERT_EQ(_sum, _output.size());
int _delete_point1 = _sum / 3;
FileMetaData::IdxPair _pair_d1(10,_delete_point1 , _delete_point1, 79, 79);
_meta.Delete(_pair_d1);
int _delete_point2 = _sum / 3*2;
FileMetaData::IdxPair _pair_d2(10, _delete_point2, _delete_point2, 79, 79);
_meta.Delete(_pair_d2);
_meta.GetOrderedMeta(_output);
ASSERT_EQ(_sum - 2, _output.size());
int _cur_val = 0;
auto _iter = _output.cbegin();
for (int i = 0; i < _sum; ++i) {
if (_cur_val == _delete_point1 || _cur_val == _delete_point2)
continue;
ASSERT_TRUE(*(*_iter) == FileMetaData::IdxPair(10, i, 0, 0, 0));
_iter++;
_cur_val++;
}
//testing buf.
uint32_t _buf_size = 0;;
unsigned char* _pbuf = nullptr;
std::tie(_pbuf,_buf_size) = _meta.GenerateBuffer();
std::cout << "generated buf size:" << _buf_size << std::endl;
FileMetaData _meta_2;
_meta_2.ConstructMeta(_pbuf,_buf_size);
this->CheckMetaEqual(_meta,_meta_2);
//Remove existing binlog file first.
const char *_role = "test";
ASSERT_EQ(std::remove(std::string(_AURORA_BINLOG_NAME_ + std::string(".") + _role).c_str()),0);
//testing file
BinLogGlobal::m_instance.Initialize(_role);
//Construct binlog file.
std::list<std::shared_ptr<::raft::Entity> > _input;
for (int i = 0; i < 10;++i) {
std::shared_ptr<::raft::Entity> _shp_entity(new ::raft::Entity());
auto _p_entity_id = _shp_entity->mutable_entity_id();
_p_entity_id->set_term(0);
_p_entity_id->set_idx(i);
auto _p_pre_entity_id = _shp_entity->mutable_pre_log_id();
_p_pre_entity_id->set_term(0);
_p_pre_entity_id->set_idx(i==0?0:i-1);
auto _p_wop = _shp_entity->mutable_write_op();
_p_wop->set_key("key_" + std::to_string(i));
_p_wop->set_value("val_" + std::to_string(i));
_input.emplace_back(_shp_entity);
}
ASSERT_TRUE(BinLogGlobal::m_instance.AppendEntry(_input));
BinLogGlobal::m_instance.GetOrderedMeta(_output);
BinLogGlobal::m_instance.UnInitialize();
//starting real test.
std::FILE* _hfile = std::fopen(BinLogGlobal::m_instance.GetBinlogFileName().c_str(),_AURORA_BINLOG_OP_MODE_);
ASSERT_EQ(std::fseek(_hfile, 0, SEEK_SET), 0);
FileMetaData _meta_3;
_meta_3.ConstructMeta(_hfile);
std::list<std::shared_ptr<FileMetaData::IdxPair>> _output2;
_meta_3.GetOrderedMeta(_output2);
this->CheckMetaListEqual(_output,_output2);
}
TEST_F(TestMeta, MetaAllocate) {
auto _start = this->StartTimeing();
LogIdentifier _log_id;
this->EndTiming(_start, "new id");
_start = this->StartTimeing();
::RaftCore::DataStructure::LockFreeHash<FileMetaData::IdxPair> m_meta_hash;
this->EndTiming(_start, "new LockFreeHash");
_start = this->StartTimeing();
FileMetaData _meta;
this->EndTiming(_start, "new meta");
std::cout << "sizeof meta:" << sizeof(_meta) << std::endl;
}
template <typename T,typename R=void>
class HashNodeTest final {
public:
HashNodeTest(const std::shared_ptr<T> &key, const std::shared_ptr<R> &val) noexcept {
this->m_shp_key = key;
this->m_shp_val = val;
this->m_next = nullptr;
}
private:
std::shared_ptr<T> m_shp_key;
std::shared_ptr<R> m_shp_val;
HashNodeTest<T,R>* m_next = nullptr;
uint32_t m_iterating_tag = 0;
private:
HashNodeTest(const HashNodeTest&) = delete;
HashNodeTest& operator=(const HashNodeTest&) = delete;
};
TEST_F(TestMeta, MetaLeak) {
std::cout << "sizeof(FileMetaData) :" << sizeof(FileMetaData) << std::endl;;
std::cout << "sizeof(::RaftCore::DataStructure::LockFreeHash<IdxPair>) :"
<< sizeof(::RaftCore::DataStructure::LockFreeHash<FileMetaData::IdxPair>) << std::endl;
std::cout << "sizeof(HashNodeTest<IdxPair>) :" << sizeof(HashNodeTest<FileMetaData::IdxPair>) << std::endl;
std::cout << "sizeof(std::atomic<HashNodeTest<IdxPair>*>) :"
<< sizeof(std::atomic<HashNodeTest<FileMetaData::IdxPair>*>) << std::endl;
std::cout << "sizeof(FileMetaData::IdxPair) :" << sizeof(FileMetaData::IdxPair) << std::endl;
{
uint32_t _count = ::RaftCore::Config::FLAGS_meta_count;
//FileMetaData is not the cause.
/* FileMetaData _meta;
for (std::size_t i = 0; i < _count; ++i)
_meta.AddLogOffset(0, i, 7, 1, 1); */
::RaftCore::DataStructure::LockFreeHash<FileMetaData::IdxPair> m_meta_hash;
for (std::size_t i = 0; i < _count; ++i) {
//std::shared_ptr<FileMetaData::IdxPair> _shp_new_record(new FileMetaData::IdxPair(0, i, 7, 1, 1));
//m_meta_hash.Insert(_shp_new_record);
//HashNodeTest<FileMetaData::IdxPair, void>* p_new_node = new HashNodeTest<FileMetaData::IdxPair, void>(_shp_new_record, nullptr);
//std::shared_ptr<uint64_t> _shp_new_record(new uint64_t(i), [](auto *P) {});
std::shared_ptr<uint64_t> _shp_new_record(new uint64_t(i));
HashNodeTest<uint64_t>* p_new_node = new HashNodeTest<uint64_t>(_shp_new_record, nullptr);
}
std::cout << "check buf size now." << sizeof(HashNodeTest<uint64_t>) << std::endl;
}
std::cout << "clear now." << std::endl;;
//_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
//_CrtDumpMemoryLeaks();
}
#endif
| 10,080
|
C++
|
.h
| 233
| 35.802575
| 142
| 0.609846
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,392
|
client_base.h
|
ppLorins_aurora/src/client/client_base.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_CLIENT_BASE_H__
#define __AURORA_CLIENT_BASE_H__
#include <vector>
namespace RaftCore::Client {
//For the prospective common properties .
class ClientBase {
public:
ClientBase();
virtual ~ClientBase();
void PushCallBackArgs(void* cb_data)noexcept;
protected:
void ClearCallBackArgs()noexcept;
std::vector<void*> m_callback_args;
private:
ClientBase(const ClientBase&) = delete;
ClientBase& operator=(const ClientBase&) = delete;
};
}
#endif
| 1,295
|
C++
|
.h
| 34
| 35.676471
| 73
| 0.742143
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,393
|
client_impl.h
|
ppLorins_aurora/src/client/client_impl.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_CLIENT_IMPL_H__
#define __AURORA_CLIENT_IMPL_H__
#include "protocol/raft.pb.h"
#include "protocol/raft.grpc.pb.h"
#include "client/client_framework.h"
#include "client/client_base.h"
#include "service/ownership_delegator.h"
namespace RaftCore {
namespace Service {
class Write;
}
}
namespace RaftCore::Client {
using ::RaftCore::Client::UnarySyncClient;
using ::RaftCore::Client::ClientBase;
using ::RaftCore::Service::Write;
using ::RaftCore::Service::OwnershipDelegator;
class AppendEntriesAsyncClient : public UnaryAsyncClient<::raft::AppendEntriesRequest,
::raft::AppendEntriesResponse, AppendEntriesAsyncClient>,
public OwnershipDelegator<AppendEntriesAsyncClient>, public OwnershipDelegator<Write>,
public ClientBase {
public:
AppendEntriesAsyncClient(std::shared_ptr<::grpc::Channel> shp_channel,
std::shared_ptr<::grpc::CompletionQueue> shp_cq, bool delegate_me = true);
virtual ~AppendEntriesAsyncClient();
protected:
virtual void Responder(const ::grpc::Status& status, const ::raft::AppendEntriesResponse& rsp) noexcept override;
virtual void Release() noexcept override;
private:
AppendEntriesAsyncClient(const AppendEntriesAsyncClient&) = delete;
AppendEntriesAsyncClient& operator=(const AppendEntriesAsyncClient&) = delete;
};
class CommitEntriesAsyncClient : public UnaryAsyncClient<::raft::CommitEntryRequest,
::raft::CommitEntryResponse, CommitEntriesAsyncClient>,
public OwnershipDelegator<CommitEntriesAsyncClient>, public OwnershipDelegator<Write>,
public ClientBase {
public:
CommitEntriesAsyncClient(std::shared_ptr<::grpc::Channel> shp_channel,
std::shared_ptr<::grpc::CompletionQueue> shp_cq);
virtual ~CommitEntriesAsyncClient();
virtual void Release() noexcept override;
protected:
virtual void Responder(const ::grpc::Status& status, const ::raft::CommitEntryResponse& rsp) noexcept override;
private:
CommitEntriesAsyncClient(const CommitEntriesAsyncClient&) = delete;
CommitEntriesAsyncClient& operator=(const CommitEntriesAsyncClient&) = delete;
};
typedef std::shared_ptr<CommitEntriesAsyncClient> TypePtrCommitAC;
class HeartbeatSyncClient : public UnarySyncClient<::raft::HeartBeatRequest, ::raft::CommonResponse>,
public ClientBase {
public:
HeartbeatSyncClient(std::shared_ptr<::grpc::Channel> shp_channel);
virtual ~HeartbeatSyncClient();
private:
HeartbeatSyncClient(const HeartbeatSyncClient&) = delete;
HeartbeatSyncClient& operator=(const HeartbeatSyncClient&) = delete;
};
class WriteSyncClient : public UnarySyncClient<::raft::ClientWriteRequest, ::raft::ClientWriteResponse>,
public ClientBase {
public:
WriteSyncClient(std::shared_ptr<::grpc::Channel> shp_channel);
virtual ~WriteSyncClient();
private:
WriteSyncClient(const WriteSyncClient&) = delete;
WriteSyncClient& operator=(const WriteSyncClient&) = delete;
};
class SyncDataSyncClient : public BidirectionalSyncClient<::raft::SyncDataRequest, ::raft::SyncDataResponse>,
public ClientBase {
public:
SyncDataSyncClient(std::shared_ptr<::grpc::Channel> shp_channel);
virtual ~SyncDataSyncClient();
auto GetInstantiatedReq() noexcept-> decltype(m_shp_request);
auto GetReaderWriter() noexcept -> decltype(m_sync_rw);
::raft::SyncDataResponse* GetResponse() noexcept;
private:
SyncDataSyncClient(const SyncDataSyncClient&) = delete;
SyncDataSyncClient& operator=(const SyncDataSyncClient&) = delete;
};
class MemberChangePrepareAsyncClient : public UnaryAsyncClient<::raft::MemberChangeInnerRequest,
::raft::MemberChangeInnerResponse, MemberChangePrepareAsyncClient,::grpc::CompletionQueue>, public ClientBase {
public:
MemberChangePrepareAsyncClient(std::shared_ptr<::grpc::Channel> shp_channel,
std::shared_ptr<::grpc::CompletionQueue> shp_cq);
virtual ~MemberChangePrepareAsyncClient();
protected:
virtual void Responder(const ::grpc::Status& status, const ::raft::MemberChangeInnerResponse& rsp) noexcept override;
private:
MemberChangePrepareAsyncClient(const MemberChangePrepareAsyncClient&) = delete;
MemberChangePrepareAsyncClient& operator=(const MemberChangePrepareAsyncClient&) = delete;
};
class MemberChangeCommitAsyncClient : public UnaryAsyncClient<::raft::MemberChangeInnerRequest,
::raft::MemberChangeInnerResponse, MemberChangeCommitAsyncClient,::grpc::CompletionQueue>, public ClientBase {
public:
MemberChangeCommitAsyncClient(std::shared_ptr<::grpc::Channel> shp_channel,
std::shared_ptr<::grpc::CompletionQueue> shp_cq);
virtual ~MemberChangeCommitAsyncClient();
protected:
virtual void Responder(const ::grpc::Status& status, const ::raft::MemberChangeInnerResponse& rsp) noexcept override;
private:
MemberChangeCommitAsyncClient(const MemberChangeCommitAsyncClient&) = delete;
MemberChangeCommitAsyncClient& operator=(const MemberChangeCommitAsyncClient&) = delete;
};
class PrevoteAsyncClient : public UnaryAsyncClient<::raft::VoteRequest,
::raft::VoteResponse, PrevoteAsyncClient,::grpc::CompletionQueue>, public ClientBase {
public:
PrevoteAsyncClient(std::shared_ptr<::grpc::Channel> shp_channel,
std::shared_ptr<::grpc::CompletionQueue> shp_cq);
virtual ~PrevoteAsyncClient();
protected:
virtual void Responder(const ::grpc::Status& status, const ::raft::VoteResponse& rsp) noexcept override;
private:
PrevoteAsyncClient(const PrevoteAsyncClient&) = delete;
PrevoteAsyncClient& operator=(const PrevoteAsyncClient&) = delete;
};
class VoteAsyncClient : public UnaryAsyncClient<::raft::VoteRequest,
::raft::VoteResponse, VoteAsyncClient,::grpc::CompletionQueue>, public ClientBase {
public:
VoteAsyncClient(std::shared_ptr<::grpc::Channel> shp_channel,
std::shared_ptr<::grpc::CompletionQueue> shp_cq);
virtual ~VoteAsyncClient();
protected:
virtual void Responder(const ::grpc::Status& status, const ::raft::VoteResponse& rsp) noexcept override;
private:
VoteAsyncClient(const VoteAsyncClient&) = delete;
VoteAsyncClient& operator=(const VoteAsyncClient&) = delete;
};
}
#endif
| 7,010
|
C++
|
.h
| 143
| 45.223776
| 122
| 0.778024
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,394
|
client_framework.h
|
ppLorins_aurora/src/client/client_framework.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_CLIENT_FRAMEWORK_H__
#define __AURORA_CLIENT_FRAMEWORK_H__
#include <memory>
#include "grpc/grpc.h"
#include "grpc++/grpc++.h"
#include "protocol/raft.grpc.pb.h"
#include "common/react_base.h"
namespace RaftCore::Client {
using ::grpc::CompletionQueue;
//using ::grpc::ServerCompletionQueue;
using ::grpc::Channel;
using ::RaftCore::Common::ReactBase;
template<typename T,typename R>
using FPrepareAsync = std::function<std::unique_ptr< ::grpc::ClientAsyncResponseReader<R>>(
::grpc::ClientContext*,const T&, ::grpc::CompletionQueue*)>;
template<typename T=void>
class ClientFramework {
public:
ClientFramework(std::shared_ptr<Channel> shp_channel)noexcept;
virtual ~ClientFramework()noexcept;
//Reset a client object for reusing purpose.
virtual void Reset() noexcept;
virtual std::shared_ptr<::raft::RaftService::Stub> GetStub() noexcept final;
protected:
std::shared_ptr<::grpc::ClientContext> m_client_context;
std::shared_ptr<::raft::RaftService::Stub> m_stub;
::grpc::Status m_final_status;
private:
ClientFramework(const ClientFramework&) = delete;
ClientFramework& operator=(const ClientFramework&) = delete;
};
template<typename T,typename R>
class ClientTpl : public ClientFramework<void> {
public:
typedef std::function<void(const ::grpc::Status &, const R&)> TypeResponder;
ClientTpl(std::shared_ptr<Channel> shp_channel)noexcept;
virtual ~ClientTpl()noexcept;
protected:
std::shared_ptr<T> m_shp_request;
R m_response;
private:
ClientTpl(const ClientTpl&) = delete;
ClientTpl& operator=(const ClientTpl&) = delete;
};
template<typename T,typename R>
class SyncClient : public ClientTpl<T,R> {
public:
SyncClient(std::shared_ptr<Channel> shp_channel)noexcept;
virtual ~SyncClient()noexcept;
private:
SyncClient(const SyncClient&) = delete;
SyncClient& operator=(const SyncClient&) = delete;
};
template<typename T,typename R>
class UnarySyncClient : public SyncClient<T,R> {
public:
UnarySyncClient(std::shared_ptr<Channel> shp_channel)noexcept;
virtual ~UnarySyncClient()noexcept;
const R& DoRPC(std::function<void(std::shared_ptr<T>&)> req_setter,
std::function<::grpc::Status(::grpc::ClientContext*,const T&,R*)> rpc, uint32_t timeo_ms,
::grpc::Status &ret_status)noexcept;
private:
UnarySyncClient(const UnarySyncClient&) = delete;
UnarySyncClient& operator=(const UnarySyncClient&) = delete;
};
template<typename T,typename R>
class BidirectionalSyncClient : public SyncClient<T,R> {
public:
BidirectionalSyncClient(std::shared_ptr<Channel> shp_channel)noexcept;
virtual ~BidirectionalSyncClient()noexcept;
protected:
std::shared_ptr<::grpc::ClientReaderWriter<T, R>> m_sync_rw;
private:
BidirectionalSyncClient(const BidirectionalSyncClient&) = delete;
BidirectionalSyncClient& operator=(const BidirectionalSyncClient&) = delete;
};
template<typename T,typename R,typename CQ=CompletionQueue>
class AsyncClient : public ClientTpl<T,R>, public ReactBase {
public:
AsyncClient(std::shared_ptr<Channel> shp_channel,std::shared_ptr<CQ> shp_cq)noexcept;
virtual ~AsyncClient()noexcept;
virtual void Responder(const ::grpc::Status& status, const R& rsp) noexcept = 0;
protected:
std::shared_ptr<CQ> m_server_cq;
private:
AsyncClient(const AsyncClient&) = delete;
AsyncClient& operator=(const AsyncClient&) = delete;
};
template<typename T,typename R,typename Q,typename CQ=CompletionQueue>
class UnaryAsyncClient : public AsyncClient<T,R,CQ> {
public:
UnaryAsyncClient(std::shared_ptr<Channel> shp_channel,std::shared_ptr<CQ> shp_cq)noexcept;
virtual ~UnaryAsyncClient()noexcept;
void EntrustRequest(const std::function<void(std::shared_ptr<T>&)> &req_setter,
const FPrepareAsync<T,R> &f_prepare_async, uint32_t timeo_ms) noexcept;
protected:
virtual void React(bool cq_result) noexcept override;
virtual void Release() noexcept;
protected:
std::unique_ptr<::grpc::ClientAsyncResponseReader<R>> m_reader;
private:
UnaryAsyncClient(const UnaryAsyncClient&) = delete;
UnaryAsyncClient& operator=(const UnaryAsyncClient&) = delete;
};
template<typename T,typename R,typename Q>
class BidirectionalAsyncClient : public AsyncClient<T,R> {
public:
BidirectionalAsyncClient(std::shared_ptr<Channel> shp_channel, std::shared_ptr<CompletionQueue> shp_cq)noexcept;
virtual ~BidirectionalAsyncClient()noexcept;
protected:
virtual void React(bool cq_result) noexcept override;
void AsyncDo(std::function<void(std::shared_ptr<T>&)> req_setter) noexcept;
void WriteDone() noexcept;
protected:
::grpc::ClientAsyncReaderWriter<T,R> m_async_rw;
enum ProcessStage { READ = 1, WRITE = 2, CONNECT = 3, WRITES_DONE = 4, FINISH = 5 };
ProcessStage m_status;
private:
BidirectionalAsyncClient(const BidirectionalAsyncClient&) = delete;
BidirectionalAsyncClient& operator=(const BidirectionalAsyncClient&) = delete;
};
} //end namespace
#include "client/client_framework.cc"
#endif
| 5,952
|
C++
|
.h
| 139
| 39.316547
| 116
| 0.750744
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,395
|
binlog_meta_data.h
|
ppLorins_aurora/src/binlog/binlog_meta_data.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_BIN_LOG_META_DATA_H__
#define __AURORA_BIN_LOG_META_DATA_H__
#include <string>
#include <stdint.h>
#include <memory>
#include <list>
#include "protocol/raft.pb.h"
#include "common/comm_defs.h"
#include "common/log_identifier.h"
#include "tools/lock_free_hash.h"
#define _FILE_META_DATA_MAGIC_STR_ "!@#$binlog$#@!"
namespace RaftCore::BinLog {
using ::RaftCore::Common::LogIdentifier;
using ::RaftCore::Common::TypeBufferInfo;
using ::RaftCore::DataStructure::HashTypeBase;
class FileMetaData final{
public:
struct IdxPair final : LogIdentifier , HashTypeBase<IdxPair>{
uint32_t m_offset;
uint32_t key_crc32;
uint32_t value_crc32;
IdxPair(uint32_t _a, uint64_t _b, uint32_t _c, uint32_t _d, uint32_t _e);
virtual bool operator<(const IdxPair& _other)const noexcept override;
bool operator==(const IdxPair &_other) const noexcept override;
const IdxPair& operator=(const IdxPair &_other) noexcept override;
std::string ToString()const noexcept;
virtual std::size_t Hash() const noexcept override;
virtual bool operator>(const IdxPair& _other)const noexcept;
virtual bool operator>(const LogIdentifier& _other)const noexcept;
virtual bool operator<(const LogIdentifier& _other)const noexcept;
virtual bool operator<=(const LogIdentifier& _other)const noexcept;
virtual bool operator>=(const LogIdentifier& _other)const noexcept;
virtual bool operator<(const ::raft::EntityID &_other)const noexcept;
virtual bool operator==(const ::raft::EntityID &_other)const noexcept;
virtual bool operator!=(const ::raft::EntityID &_other)const noexcept;
virtual bool operator>(const ::raft::EntityID &_other)const noexcept;
};
typedef std::list<std::shared_ptr<FileMetaData::IdxPair>> TypeOffsetList;
public:
FileMetaData() noexcept;
virtual ~FileMetaData() noexcept;
/* This functions will be invoked each time we write a new log entry into the binlog file,
namely,in a multiple threading access environment.
- Support Multiple Thread invoking: True
- Will be invoked simultaneously: False */
void AddLogOffset(uint32_t term,uint64_t log_index, uint32_t file_offset,uint32_t key_crc32,uint32_t value_crc32) noexcept;
/*- Support Multiple Thread invoking: True
- Will be invoked simultaneously: False */
void AddLogOffset(const TypeOffsetList &_list) noexcept;
/*- Support Multiple Thread invoking: True
- Will be invoked simultaneously: False */
void Delete(const IdxPair &_item) noexcept;
/*This functions will be invoked only in the rotating file scenario,namely,
a single thread accessing environment.After return the pointer pointing
to the generated buffer, this function will no longer be responsible
for the memory it allocated, the caller must take care of(freeing) it.
- Support Multiple Thread invoking: True
- Will be invoked simultaneously: False */
TypeBufferInfo GenerateBuffer() const noexcept;
/* - Support Multiple Thread invoking: True
- Will be invoked simultaneously: False */
void ConstructMeta(const unsigned char* _buf, std::size_t _size) noexcept;
/* - Support Multiple Thread invoking: False
- Will be invoked simultaneously: False */
/*Return value:
0 - parsed successfully.
>0 - parsed bytes.Remaining bytes are not parsable.Need to be truncated. */
int ConstructMeta(std::FILE* _handler) noexcept;
/* - Support Multiple Thread invoking: True
- Will be invoked simultaneously: False */
void GetOrderedMeta(TypeOffsetList &_output) const noexcept;
void BackOffset(int offset) noexcept;
private:
::RaftCore::DataStructure::LockFreeHash<IdxPair> m_meta_hash;
private:
FileMetaData(const FileMetaData&) = delete;
FileMetaData& operator=(const FileMetaData&) = delete;
};
std::ostream& operator<<(std::ostream& os, const FileMetaData::IdxPair& obj);
} //end namespace
#endif
| 4,880
|
C++
|
.h
| 96
| 45.84375
| 127
| 0.726062
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,396
|
binlog_singleton.h
|
ppLorins_aurora/src/binlog/binlog_singleton.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_BIN_LOG_SINGLETON_H__
#define __AURORA_BIN_LOG_SINGLETON_H__
#include "binlog/binlog_operator.h"
namespace RaftCore::BinLog {
using ::RaftCore::BinLog::BinLogOperator;
class BinLogGlobal final{
public:
static BinLogOperator m_instance;
private:
BinLogGlobal() = delete;
virtual ~BinLogGlobal() = delete;
BinLogGlobal(const BinLogGlobal&) = delete;
BinLogGlobal& operator=(const BinLogGlobal&) = delete;
};
} //end namespace
#endif
| 1,276
|
C++
|
.h
| 31
| 38.870968
| 73
| 0.747755
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,397
|
binlog_operator.h
|
ppLorins_aurora/src/binlog/binlog_operator.h
|
/*
* <Aurora. A raft based distributed KV storage system.>
* Copyright (C) <2019> <arthur> <pplorins@gmail.com>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __AURORA_BIN_LOG_OPERATOR_H__
#define __AURORA_BIN_LOG_OPERATOR_H__
#include <string>
#include <stdint.h>
#include <memory>
#include "protocol/raft.pb.h"
#include "common/comm_defs.h"
#include "common/log_identifier.h"
#include "follower/memory_log_follower.h"
#include "binlog/binlog_meta_data.h"
#define _AURORA_BINLOG_NAME_ "raft.binlog"
#define _AURORA_BINLOG_NAME_REG_ "raft\\.binlog"
#define _AURORA_BINLOG_OP_MODE_ "ab+"
#define _AURORA_BINLOG_READ_MODE_ "rb"
namespace RaftCore::BinLog {
using ::raft::Entity;
using ::RaftCore::Common::LogIdentifier;
using ::RaftCore::Follower::TypeMemlogFollowerList;
using ::RaftCore::Common::TypeEntityList;
using ::RaftCore::Common::TypeBufferInfo;
using ::RaftCore::BinLog::FileMetaData;
class BinLogOperator final{
public:
enum class BinlogErrorCode {
UNKNOWN = 0,
SUCCEED_TRUNCATED,
SUCCEED_MERGED, //Input logs are all existed in the bin log.
//------Separating line.------//
SUCCEED_MAX,
OVER_BOUNDARY,
NO_CONSISTENT_ERROR,
OTHER_ERROR,
};
enum class BinlogStatus {
//Normal status , could be written new log entries
NORMAL,
//Reverting due a log conflict with (probably new) leader's log.
REVERTING,
//Set the first log entry in the binlog file, used in the SyncData scenario.
SETTING_HEAD
};
public:
BinLogOperator();
virtual ~BinLogOperator()noexcept;
void Initialize(const char* role, bool file_name = false) noexcept;
void UnInitialize() noexcept;
//The '_input' parameter must be ordered by log index in ascending order.
bool AppendEntry(const TypeEntityList &input_entities,bool force=false) noexcept;
/*Although it is supported, reverting log actually won't be executed with AppendEntry simultaneously ,
which is guaranteed by the callers.*/
BinlogErrorCode RevertLog(TypeMemlogFollowerList &log_list, const LogIdentifier &boundary) noexcept;
/*Although it is supported, SetHead log actually won't be executed with AppendEntry simultaneously ,
which is done by the callers.*/
BinlogErrorCode SetHead(std::shared_ptr<::raft::Entity> _shp_entity) noexcept;
bool Clear() noexcept;
LogIdentifier GetLastReplicated() noexcept;
std::string GetBinlogFileName() noexcept;
void GetOrderedMeta(FileMetaData::TypeOffsetList &_output) noexcept;
void AddPreLRLUseCount() noexcept;
void SubPreLRLUseCount() noexcept;
private:
void ParseFile() noexcept;
void DeleteOpenBinlogFile() noexcept;
void RenameOpenBinlogFile() noexcept;
void Truncate(uint32_t new_size) noexcept;
//The following three member functions are helpers of AppendEntry.
TypeBufferInfo PrepareBuffer(const TypeEntityList &input_entities, FileMetaData::TypeOffsetList &offset_list) noexcept;
void AppendBufferToBinlog(TypeBufferInfo &buffer_info, const FileMetaData::TypeOffsetList &offset_list) noexcept;
void RotateFile() noexcept;
private:
LogIdentifier m_zero_log_id;
bool m_initialized = false;
std::atomic<LogIdentifier> m_last_logged;
std::string m_file_name = "";
std::FILE *m_binlog_handler = nullptr;
std::mutex m_cv_mutex;
std::condition_variable m_cv;
std::atomic<FileMetaData*> m_p_meta;
std::atomic<BinlogStatus> m_binlog_status;
std::atomic<int> m_precede_lcl_inuse;
std::atomic<uint32_t> m_log_num;
private:
BinLogOperator(const BinLogOperator&) = delete;
BinLogOperator& operator=(const BinLogOperator&) = delete;
};
} //end namespace
#endif
| 4,539
|
C++
|
.h
| 102
| 40.058824
| 123
| 0.714906
|
ppLorins/aurora
| 37
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,398
|
consistencychecks.cc
|
schirmermischa_THELI/src/consistencychecks.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dockwidgets/confdockwidget.h"
#include "ui_confdockwidget.h"
#include "functions.h"
#include "status.h"
#include "datadir.h"
#include <QDebug>
#include <QMessageBox>
#include <QDir>
bool MainWindow::areAllPathsValid() {
bool test = checkPathsLineEdit(ui->setupBiasLineEdit);
test = test && checkPathsLineEdit(ui->setupDarkLineEdit);
test = test && checkPathsLineEdit(ui->setupFlatoffLineEdit);
test = test && checkPathsLineEdit(ui->setupFlatLineEdit);
test = test && checkPathsLineEdit(ui->setupScienceLineEdit);
test = test && checkPathsLineEdit(ui->setupSkyLineEdit);
test = test && checkPathsLineEdit(ui->setupStandardLineEdit);
return test;
}
bool MainWindow::checkMultipledirConsistency(QString mode)
{
int nbias = datadir2StringList(ui->setupBiasLineEdit).length();
int ndark = datadir2StringList(ui->setupDarkLineEdit).length();
int nflatoff = datadir2StringList(ui->setupFlatoffLineEdit).length();
int nflat = datadir2StringList(ui->setupFlatLineEdit).length();
int nscience = datadir2StringList(ui->setupScienceLineEdit).length();
int nsky = datadir2StringList(ui->setupSkyLineEdit).length();
int nstandard = datadir2StringList(ui->setupStandardLineEdit).length();
int ncorr; // can represent various calibrators
if (mode == "HDUreformat") return true;
if (mode == "ProcessBias") return true;
if (mode == "ProcessDark") return true;
// Flat processing (and a few other checks so we don't have to repeat them)
bool flatcheck = false;
if (mode == "ProcessFlat" || mode == "ProcessScience" || mode == "ProcessSky" || mode == "ProcessStandard") {
// Check if we have a consistent setup to process the flats
// flatoff takes precedence over bias if both are defined:
if (nflatoff > 0 && nbias > 0) ncorr = nflatoff;
else if (nflatoff > 0 && nbias == 0) ncorr = nflatoff;
else { // (nflatoff == 0 && nbias > 0 or both == 0)
ncorr = nbias;
}
// Now check if the setup is consistent:
if (nflat == ncorr) flatcheck = true;
else if (nflat > 1 && ncorr <= 1) flatcheck = true;
else flatcheck = false;
if (mode == "ProcessFlat") {
if (flatcheck) return true;
else {
message(ui->plainTextEdit, "STOP: Inconsistent number of directories for FLAT processing.");
return false;
}
}
}
if ((mode == "ProcessScience" || mode == "ProcessBackground") && nsky > 0) {
if (nscience != nsky && nsky != 1) {
message(ui->plainTextEdit, "STOP: Inconsistent number of SKY directories for SCIENCE.");
message(ui->plainTextEdit, "Must be equal to that of SCIENCE, or one.");
return false;
}
}
if (mode == "ProcessScience" || mode == "ProcessSky" || mode == "ProcessStandard") {
if (mode == "ProcessSky") nscience = nsky;
if (mode == "ProcessStandard") nscience = nstandard;
// We have checked the consistency for flat processing.
if (!flatcheck) {
message(ui->plainTextEdit, "STOP: Inconsistent number of directories for FLAT processing.");
return false;
}
// If darks were specified, then they take precedence over biases!
if ( ndark > 0 && nbias > 0) ncorr = ndark;
else if (ndark > 0 && nbias == 0) ncorr = ndark;
else { // ndark == 0 && nbias > 0 or both == 0
ncorr = nbias;
}
// What remains is to check the consistency science -> flat and science ->bias/dark
// where 'science' can also be 'sky' or 'standard'
if (nscience == nflat && nscience == ncorr) return true;
else if (nscience > 1 && nflat <= 1 && ncorr <= 1) return true;
else if (nscience > 1 && nflat <= 1 && ncorr == nscience) return true;
else if (nscience > 1 && nflat == nscience && ncorr <= 1) return true;
else {
if (mode == "ProcessScience")
message(ui->plainTextEdit, "STOP: Inconsistent number of directories for SCIENCE processing.");
if (mode == "ProcessSky")
message(ui->plainTextEdit, "STOP: Inconsistent number of directories for SKY processing.");
if (mode == "ProcessStandard")
message(ui->plainTextEdit, "STOP: Inconsistent number of directories for STANDARD processing.");
// should we set the 'stop' flag here?
return false;
}
}
// In all other cases (later on during processing) we don't care anymore, hence:
return true;
}
void MainWindow::hasDirCurrentData(DataDir *datadir, bool &stop)
{
QString currentStatus = status.getStatusFromHistory();
// The task does not change the status string. We expect the status to be current
if (!datadir->hasType(currentStatus)) {
message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain expected images (*"+currentStatus+".fits).");
stop = true;
}
}
QString MainWindow::estimateStatusFromFilename(DataDir *datadir)
{
// Get the name of a single fits file
QStringList filterList("*.fits");
QDir dir(datadir->name);
QStringList imageList = dir.entryList(filterList);
QString image;
if (!imageList.isEmpty()) image = imageList.at(0);
// The image extension (e.g. A, or AB)
image = getLastWord(image,'_').remove(".fits").remove(QRegExp("[0-9]{1,3}"));
return image;
}
void MainWindow::check_taskHDUreformat(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
// if (datadir->isEmpty()) {
// if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note");
// skip = true;
// }
if (datadir->hasType("P")) {
if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' already contains HDU reformatted images. Skipping...", "note");
skip = true;
}
if (datadir->numEXT("PA*") > 0) {
if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains preprocessed images. Skipping...", "note");
skip = true;
}
}
void MainWindow::check_taskProcessbias(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
if (datadir->isEmpty()) {
if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note");
skip = true;
}
if (!datadir->hasType("P")
&& !ui->applyHDUreformatCheckBox->isChecked()) {
message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images.");
stop = true;
}
if (!stop
&& datadir->numCHIP < 3
&& !ui->applyHDUreformatCheckBox->isChecked()) {
// message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'.");
// stop = true;
}
}
void MainWindow::check_taskProcessdark(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
if (datadir->isEmpty()) {
if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note");
skip = true;
}
if (!datadir->hasType("P")
&& !ui->applyHDUreformatCheckBox->isChecked()) {
message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images.");
stop = true;
}
if (!stop
&& datadir->numCHIP < 3
&& !ui->applyHDUreformatCheckBox->isChecked()) {
// message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'.");
// stop = true;
}
}
void MainWindow::check_taskProcessflatoff(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
if (datadir->isEmpty()) {
if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note");
skip = true;
}
if (!datadir->hasType("P")
&& !ui->applyHDUreformatCheckBox->isChecked()) {
message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images.");
stop = true;
}
if (!stop
&& datadir->numCHIP < 3
&& !ui->applyHDUreformatCheckBox->isChecked()) {
// message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'.");
// stop = true;
}
}
void MainWindow::check_taskProcessflat(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
if (datadir->isEmpty()) {
if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note");
skip = true;
}
if (!datadir->hasType("P")
&& !ui->applyHDUreformatCheckBox->isChecked()) {
message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images.");
stop = true;
}
if (!stop
&& datadir->numCHIP < 2
&& !ui->applyHDUreformatCheckBox->isChecked()) {
// message(ui->plainTextEdit, "STOP: Need at least 3 exposures in '"+datadir->subdirname+"'.");
// stop = true;
}
}
void MainWindow::check_taskProcessscience(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
if (datadir->isEmpty()) {
if (mode != "execute") message(ui->plainTextEdit, "'"+datadir->subdirname+"' contains no images. Skipping...", "note");
skip = true;
}
if (!datadir->hasType("P")
&& !datadir->hasType("PA")
&& !ui->applyHDUreformatCheckBox->isChecked()) {
message(ui->plainTextEdit, "STOP: '"+datadir->subdirname+"' does not contain HDU reformatted images.");
stop = true;
}
}
void MainWindow::check_taskChopnod(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskBackground(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskCollapse(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskBinnedpreview(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskGlobalweight(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskIndividualweight(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskAbsphotindirect(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
QString standardDir = ui->setupStandardLineEdit->text();
if (standardDir.isEmpty()) {
if (mode != "execute") message(ui->plainTextEdit, "No standard star directory was defined.", "stop");
stop = true;
}
}
void MainWindow::check_taskSeparate(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskCreatesourcecat(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskAstromphotom(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskGetCatalogFromWEB(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskGetCatalogFromIMAGE(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskRestoreHeader(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
hasDirCurrentData(datadir, stop);
// Check that original headers exist
}
void MainWindow::check_taskResolveTargetSidereal(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
QString target = cdw->ui->ARCtargetresolverLineEdit->text();
if (target.isEmpty()) {
message(ui->plainTextEdit, "A target name must be provided for coordinate resolution.", "stop");
stop = true;
cdw->ui->ARCraLineEdit->clear();
cdw->ui->ARCdecLineEdit->clear();
}
}
void MainWindow::check_taskSkysub(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
void MainWindow::check_taskCoaddition(DataDir *datadir, bool &stop, bool &skip, const QString mode)
{
}
| 12,933
|
C++
|
.cc
| 293
| 38.631399
| 148
| 0.659331
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,399
|
tasks.cc
|
schirmermischa_THELI/src/tasks.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_confdockwidget.h"
#include "functions.h"
#include "status.h"
#include "processingExternal/errordialog.h"
#include "datadir.h"
#include <QDebug>
#include <QMessageBox>
#include <QDir>
#include <QMetaObject>
#include <QGenericReturnArgument>
QStringList MainWindow::taskHDUreformat(bool &stop, const QString mode)
{
QString taskBasename = "HDUreformat";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupBiasLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupDarkLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupFlatoffLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupFlatLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskProcessbias(bool &stop, const QString mode)
{
QString taskBasename = "Processbias";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupBiasLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskProcessdark(bool &stop, const QString mode)
{
QString taskBasename = "Processdark";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupDarkLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskProcessflatoff(bool &stop, const QString mode)
{
QString taskBasename = "Processflatoff";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupFlatoffLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskProcessflat(bool &stop, const QString mode)
{
QString taskBasename = "Processflat";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
// Do we use the FLAT OFF/DARK or BIAS (in case one or more are defined);
// FLAT OFF preferred over BIAS
QString bias = ui->setupBiasLineEdit->text();
QString flatoff = ui->setupFlatoffLineEdit->text();
if (!flatoff.isEmpty()) le1 = ui->setupFlatoffLineEdit;
else if (!bias.isEmpty()) le1 = ui->setupBiasLineEdit;
else le1->setText("theli_nobias");
handleDataDirs(goodDirList, ui->setupFlatLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskProcessscience(bool &stop, const QString mode)
{
QString taskBasename = "Processscience";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
// Do we use the FLAT and / or BIAS (in case one or more are defined);
QString bias = ui->setupBiasLineEdit->text();
QString dark = ui->setupDarkLineEdit->text();
QString flat = ui->setupFlatLineEdit->text();
if (!dark.isEmpty()) le1 = ui->setupDarkLineEdit;
else if (!bias.isEmpty()) le1 = ui->setupBiasLineEdit;
else le1->setText("theli_nobias");
if (!flat.isEmpty()) le2 = ui->setupFlatLineEdit;
else le2->setText("theli_noflat");
// append DT_x to tell the internal processor which Data structure we have to work on
// For FLAT and FLAT_OFF we have separate taskBasenames, for SCIENCE we don't.
// I should revisit this and make it more consistent
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "theli_DT_SCIENCE", success);
handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "theli_DT_SKY", success);
handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "theli_DT_STANDARD", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskChopnod(bool &stop, const QString mode)
{
QString taskBasename = "Chopnod";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskBackground(bool &stop, const QString mode)
{
QString taskBasename = "Background";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
// The first argument gets replaced by the sky dir (if any)
QString sky = ui->setupSkyLineEdit->text();
if (!sky.isEmpty()) le1 = ui->setupSkyLineEdit;
else le1->setText("noskydir");
// Standard stars don't have separate sky entries (at least we don't support it)
auto *nosky = new QLineEdit(controller);
nosky->setText("noskydir");
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupStandardLineEdit, nosky, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskCollapse(bool &stop, const QString mode)
{
QString taskBasename = "Collapse";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskBinnedpreview(bool &stop, const QString mode)
{
QString taskBasename = "Binnedpreview";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskGlobalweight(bool &stop, const QString mode)
{
QString taskBasename = "Globalweight";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
// Do we use the FLAT and / or BIAS (in case one or more are defined);
QString bias = ui->setupBiasLineEdit->text();
QString dark = ui->setupDarkLineEdit->text();
QString flat = ui->setupFlatLineEdit->text();
if (!flat.isEmpty()) le1 = ui->setupFlatLineEdit;
else le1->setText("theli_noflat");
if (!dark.isEmpty()) le2 = ui->setupDarkLineEdit;
else if (!bias.isEmpty()) le2 = ui->setupBiasLineEdit;
else le2->setText("theli_nobias");
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskIndividualweight(bool &stop, const QString mode)
{
QString taskBasename = "Individualweight";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
handleDataDirs(goodDirList, ui->setupStandardLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskSeparate(bool &stop, const QString mode)
{
QString taskBasename = "Separate";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskAbsphotindirect(bool &stop, const QString mode)
{
QString taskBasename = "Absphotindirect";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskCreatesourcecat(bool &stop, const QString mode)
{
QString taskBasename = "Createsourcecat";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskAstromphotom(bool &stop, const QString mode)
{
QString taskBasename = "Astromphotom";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskGetCatalogFromWEB(bool &stop, const QString mode)
{
QString taskBasename = "GetCatalogFromWEB";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskGetCatalogFromIMAGE(bool &stop, const QString mode)
{
QString taskBasename = "GetCatalogFromIMAGE";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskRestoreHeader(bool &stop, const QString mode)
{
QString taskBasename = "RestoreHeader";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskSkysub(bool &stop, const QString mode)
{
QString taskBasename = "Skysub";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (processSkyImages) handleDataDirs(goodDirList, ui->setupSkyLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
QStringList MainWindow::taskCoaddition(bool &stop, const QString mode)
{
QString taskBasename = "Coaddition";
QStringList goodDirList;
auto *le1 = new QLineEdit(controller);
auto *le2 = new QLineEdit(controller);
bool success = true;
handleDataDirs(goodDirList, ui->setupScienceLineEdit, le1, le2, "", success);
if (!success) return QStringList();
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
// TODO: go through these tasks and clean up those we don't need anymore, or info therein we don't need
QStringList MainWindow::taskResolveTargetSidereal(bool &stop, const QString mode)
{
QString taskBasename = "ResolveTargetSidereal";
QStringList goodDirList;
// Replace blanks by underscores, and push the target name onto 'gooddirlist', which carries no other information
QString target = cdw->ui->ARCtargetresolverLineEdit->text();
target = target.replace(" ","_");
cdw->ui->ARCraLineEdit->clear();
cdw->ui->ARCdecLineEdit->clear();
goodDirList << target;
return createCommandlistBlock(taskBasename, goodDirList, stop, mode);
}
| 15,207
|
C++
|
.cc
| 326
| 42.337423
| 117
| 0.738669
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,400
|
datadir.cc
|
schirmermischa_THELI/src/datadir.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "datadir.h"
#include "functions.h"
#include <QDebug>
// Constructor
DataDir::DataDir(QString data, QString main)
{
setPaths(data, main);
}
DataDir::DataDir()
{
name = "";
subdirname = "";
numFITS = 0;
numCHIP = 0;
}
void DataDir::setPaths(QString data, QString main)
{
if (data.isEmpty()) {
qDebug() << __func__ << ": sub-directory cannot be an empty string!";
return;
}
if (!main.isEmpty()) {
QDir maindir(main);
if (!maindir.exists()) {
qDebug() << __func__ << ": main directory does not exist!";
return;
}
if (!maindir.isAbsolute()) {
qDebug() << __func__ << ": main directory must be absolute!";
return;
}
}
// If main was not provided but data contains a blank (e.g. MAINDIR SCIENCE)
if (data.contains(" ")) {
QStringList list = data.split(" ");
main = list.at(0);
data = list.at(1);
}
// Concatenate maindir and datadir, collapse multiple slashes etc
name = QDir::cleanPath(main+"/"+data+"/");
subdirname = data;
dir.setPath(name);
if (dir.exists()) {
QStringList fileList;
// How many FITS files do we have in total
QStringList filter;
filter << "*.fits" << "*.fit" << "*.FIT" << "*.FITS" << "*.fits.fz" << "*.fit.fz" << "*.FIT.fz" << "*.FITS.fz";
dir.setNameFilters(filter);
fileList = dir.entryList();
numFITS = fileList.length();
if (numFITS == 0) {
// Check for RAW files instead
filter.clear();
filter << "*.cr2" << "*.CR2" << "*.arw" << "*.ARW" << "*.dng" << "*.DNG" << "*.nef" << "*.NEF" << "*.pef" << "*.PEF";
dir.setNameFilters(filter);
fileList = dir.entryList();
numFITS = fileList.length();
}
// How many FITS files do we have a chip 1 (i.e., number of exposures)
// (needed to create master calibrators)
int chip = 1;
QVector<int> numExposures;
while (chip <= numChips) {
QStringList filterCHIP;
filterCHIP << "*_"+QString::number(chip)+"P.fits";
dir.setNameFilters(filterCHIP);
fileList = dir.entryList();
numExposures << fileList.length();
++chip;
}
numCHIP = maxVec_T(numExposures);
}
else {
numFITS = 0;
numCHIP = 0;
}
}
bool DataDir::hasMaster()
{
// This is to check if a BIAS, DARK etc directory already contains a master BIAS, DARK, etc
QString cleanname = subdirname.remove("/");
QStringList filter;
int chip = 1;
while (chip <= numChips) {
filter << cleanname+"_"+QString::number(chip)+".fits";
++chip;
}
dir.setNameFilters(filter);
QStringList fileList = dir.entryList();
if (fileList.length() > 1) {
return true;
}
else {
return false;
}
}
bool DataDir::isEmpty()
{
if (numFITS == 0) {
return true;
}
else {
return false;
}
}
bool DataDir::exists()
{
return dir.exists();
}
long DataDir::numEXT(QString type)
{
// How many FITS files of a certain type do we have (e.g. "_*AB.fits")
QStringList filter;
filter << "*_*"+type+".fits";
dir.setNameFilters(filter);
QStringList fileList = dir.entryList();
return fileList.length();
}
bool DataDir::hasType(QString type) {
// Do we have FITS files of a certain type (e.g. "_*AB.fits")
QStringList filter;
filter << "*_*"+type+".fits";
dir.setNameFilters(filter);
QStringList fileList = dir.entryList();
if (fileList.length() > 0) {
return true;
} else {
return false;
}
}
| 4,431
|
C++
|
.cc
| 144
| 24.895833
| 129
| 0.596861
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,401
|
preferences.cc
|
schirmermischa_THELI/src/preferences.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "preferences.h"
#include "ui_preferences.h"
#include "functions.h"
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QCloseEvent>
#include <QFontDialog>
#include <QThread>
#include "fitsio.h"
#include <unistd.h>
Preferences::Preferences(bool running, QWidget *parent) :
QDialog(parent),
ui(new Ui::Preferences)
{
ui->setupUi(this);
int maxCPU = QThread::idealThreadCount();
if (maxCPU <= 0) {
emit messageAvailable("Could not determine the number of CPUs for this machine! Max number of CPUs is set to 1.", "warning");
emit warning();
maxCPU = 1;
}
if (!fits_is_reentrant()) maxCPU = 1;
ui->prefCPUSpinBox->setMaximum(maxCPU);
applyStyleSheets();
configureMemory(); // Must do before reading settings
readSettings();
QFont currentFont = this->font();
int fontsize = currentFont.pointSize();
ui->prefFontsizeSpinBox->setValue(fontsize);
// Prevent changes to important parameters while running
if (running) {
ui->parallelizationFrame->setDisabled(true);
ui->memoryFrame->setDisabled(true);
ui->prefIntermediateDataComboBox->setDisabled(true);
}
else {
ui->parallelizationFrame->setEnabled(true);
ui->memoryFrame->setEnabled(true);
ui->prefIntermediateDataComboBox->setEnabled(true);
}
ui->prefServerComboBox->hide();
ui->prefDataServerLabel->hide();
ui->prefProcessSkyCheckBox->hide();
}
void Preferences::configureMemory()
{
// Memory setup. If we have less than 10 GB then we use MB, otherwise GB.
// We always leave 1 GB for the operating system and other tasks
/*
totalMemory = get_memory() / 1024; // [ MB ]
if (totalMemory < 10000) {
maxMemoryUsed = int(totalMemory) - 1024;
ui->prefMemoryLabel->setText("Max usable memory [ MB ]");
ui->prefMemorySpinBox->setMinimum(500);
ui->prefMemorySpinBox->setMaximum(maxMemoryUsed);
}
else {
maxMemoryUsed = int(totalMemory / 1024) - 1;
ui->prefMemoryLabel->setText("Max usable memory [ GB ]");
ui->prefMemorySpinBox->setMinimum(1);
ui->prefMemorySpinBox->setMaximum(maxMemoryUsed);
}
*/
// MB only
totalMemory = get_memory() / 1024; // [ MB ]
maxMemoryUsed = int(totalMemory);
ui->prefMemoryLabel->setText("Max usable memory [ MB ]");
ui->prefMemorySpinBox->setMinimum(1024);
ui->prefMemorySpinBox->setMaximum(maxMemoryUsed);
}
void Preferences::applyStyleSheets()
{
QList<QLabel*> labelList;
labelList.append(ui->generalLabel);
labelList.append(ui->parallelizationLabel);
labelList.append(ui->memoryLabel);
labelList.append(ui->fontLabel);
labelList.append(ui->userInterfaceLabel);
for (auto &it : labelList) {
it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);");
it->setMargin(8);
}
QList<QFrame*> frameList;
frameList.append(ui->generalFrame);
frameList.append(ui->parallelizationFrame);
frameList.append(ui->memoryFrame);
frameList.append(ui->fontFrame);
frameList.append(ui->userInterfaceFrame);
/*
for (auto &it : confFrameList) {
// specify large style sheet?
}
*/
QList<QCheckBox*> checkboxList;
checkboxList.append(ui->prefGPUCheckBox);
checkboxList.append(ui->prefMemoryCheckBox);
checkboxList.append(ui->prefSwitchProcessMonitorCheckBox);
// for (auto &it : checkboxList) {
// it->setStyleSheet("background-color: rgb(190,190,210);");
// }
}
void Preferences::updateParallelization(bool running)
{
if (running) ui->parallelizationFrame->setDisabled(true);
else ui->parallelizationFrame->setEnabled(true);
}
Preferences::~Preferences()
{
delete ui;
}
int Preferences::writeSettings()
{
QSettings settings_lastproject("THELI", "PREFERENCES");
settings_lastproject.setValue("prefServerComboBox", ui->prefServerComboBox->currentText());
settings_lastproject.setValue("prefIntermediateDataComboBox", ui->prefIntermediateDataComboBox->currentText());
settings_lastproject.setValue("prefVerbosityComboBox", ui->prefVerbosityComboBox->currentIndex());
settings_lastproject.setValue("prefDiskspacewarnSpinBox", ui->prefDiskspacewarnSpinBox->value());
settings_lastproject.setValue("prefCPUSpinBox", ui->prefCPUSpinBox->value());
settings_lastproject.setValue("prefGPUCheckBox", ui->prefGPUCheckBox->isChecked());
settings_lastproject.setValue("prefProcessSkyCheckBox", ui->prefProcessSkyCheckBox->isChecked());
settings_lastproject.setValue("prefMemorySpinBox", ui->prefMemorySpinBox->value());
settings_lastproject.setValue("prefMemoryCheckBox", ui->prefMemoryCheckBox->isChecked());
settings_lastproject.setValue("prefFontsizeSpinBox", ui->prefFontsizeSpinBox->value());
settings_lastproject.setValue("prefSwitchProcessMonitorCheckBox", ui->prefSwitchProcessMonitorCheckBox->isChecked());
settings_lastproject.setValue("prefFont", this->font());
return settings_lastproject.status();
}
int Preferences::readSettings()
{
QSettings settings("THELI", "PREFERENCES");
ui->prefDiskspacewarnSpinBox->setValue(settings.value("prefDiskspacewarnSpinBox", 256).toInt());
ui->prefVerbosityComboBox->setCurrentIndex(settings.value("prefVerbosityComboBox", 1).toInt());
ui->prefServerComboBox->setCurrentText(settings.value("prefServerComboBox").toString());
ui->prefCPUSpinBox->setValue(settings.value("prefCPUSpinBox", QThread::idealThreadCount()).toInt());
ui->prefGPUCheckBox->setChecked(settings.value("prefGPUCheckBox", false).toBool());
ui->prefProcessSkyCheckBox->setChecked(settings.value("prefProcessSkyCheckBox", false).toBool());
ui->prefFontsizeSpinBox->setValue(settings.value("prefFontsizeSpinBox").toInt());
ui->prefMemorySpinBox->setValue(settings.value("prefMemorySpinBox", maxMemoryUsed).toInt());
ui->prefSwitchProcessMonitorCheckBox->setChecked(settings.value("prefSwitchProcessMonitorCheckBox", true).toBool());
ui->prefIntermediateDataComboBox->setCurrentText(settings.value("prefIntermediateDataComboBox", "If necessary").toString());
ui->prefMemoryCheckBox->setChecked(settings.value("prefMemoryCheckBox", false).toBool());
this->setFont(settings.value("prefFont").value<QFont>());
return settings.status();
}
void Preferences::on_prefFontdialogPushButton_clicked()
{
bool ok;
QFont currentFont = this->font();
QFont font = QFontDialog::getFont(&ok, QFont(currentFont), this);
if (ok) {
emit fontChanged(font);
this->setFont(font);
}
int fontsize = font.pointSize();
ui->prefFontsizeSpinBox->setValue(fontsize);
}
void Preferences::on_prefFontsizeSpinBox_valueChanged(int arg1)
{
emit fontSizeChanged(arg1);
}
void Preferences::receiveDefaultFont(QFont font)
{
defaultFont = font;
}
void Preferences::on_prefDefaultFontPushButton_clicked()
{
emit fontChanged(defaultFont);
this->setFont(defaultFont);
int fontsize = defaultFont.pointSize();
ui->prefFontsizeSpinBox->setValue(fontsize);
}
void Preferences::on_prefDiskspacewarnSpinBox_valueChanged(int arg1)
{
emit diskspacewarnChanged(arg1);
}
void Preferences::on_prefCPUSpinBox_valueChanged(int arg1)
{
emit numcpuChanged(arg1);
}
void Preferences::on_prefMemoryCheckBox_clicked()
{
if (ui->prefMemoryCheckBox->isChecked()) {
ui->prefIntermediateDataComboBox->setCurrentIndex(1);
ui->prefIntermediateDataComboBox->setDisabled(true);
}
else {
ui->prefIntermediateDataComboBox->setCurrentIndex(1);
ui->prefIntermediateDataComboBox->setDisabled(false);
}
emit memoryUsageChanged(ui->prefMemoryCheckBox->isChecked());
}
void Preferences::on_prefIntermediateDataComboBox_currentTextChanged(const QString &arg1)
{
if (ui->prefIntermediateDataComboBox->currentIndex() == 0) ui->prefMemoryCheckBox->setChecked(false);
emit intermediateDataChanged(arg1);
}
void Preferences::on_prefVerbosityComboBox_currentIndexChanged(int index)
{
emit verbosityLevelChanged(index);
}
void Preferences::on_prefSwitchProcessMonitorCheckBox_clicked()
{
emit switchProcessMonitorChanged(ui->prefSwitchProcessMonitorCheckBox->isChecked());
}
void Preferences::on_prefCancelButton_clicked()
{
close();
}
void Preferences::on_prefCloseButton_clicked()
{
auto result = writeSettings();
if (result== QSettings::AccessError) {
emit messageAvailable("Could not store preferences (access error).", "warning");
emit warning();
}
else if (result == QSettings::FormatError) {
emit messageAvailable("A formatting error occurred while writing the preferences.", "warning");
emit warning();
}
emit preferencesUpdated();
close();
}
| 9,535
|
C++
|
.cc
| 237
| 35.945148
| 133
| 0.738628
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,402
|
status.cc
|
schirmermischa_THELI/src/status.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "status.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
// Constructor
Status::Status()
{
}
// Set the background of the checkboxes according to the processing history
void Status::history2checkbox()
{
int i=0;
QPalette palette;
for (auto &checked : listHistory) {
if (checked) palette.setColor(QPalette::Button,QColor("#33e3cc"));
else palette.setColor(QPalette::Button,QColor("#eeffff"));
// Paint checkbox background
listCheckBox.operator[](i)->setPalette(palette);
listCheckBox.operator[](i)->setAutoFillBackground(true);
++i;
}
}
// Triggered by mainguiworker (everytime a task is finished)
void Status::updateStatusReceived(QString taskBasename, bool success)
{
int index = indexMap.value(taskBasename,-1);
if (index == -1) return;
else {
listHistory.operator[](index) = success;
updateStatus();
}
}
// Triggered by user actions in the main window.
// Repaints the task checkboxes (among others)
void Status::updateStatus()
{
int i=0;
QPalette palette;
for (auto &checked : listHistory) {
if (checked) palette.setColor(QPalette::Button, QColor("#33e3cc"));
else palette.setColor(QPalette::Button, QColor("#eeffff"));
// Paint checkbox background
listCheckBox.operator[](i)->setPalette(palette);
listCheckBox.operator[](i)->setAutoFillBackground(true);
// Only UNCHECK a task checkbox if the history changed to "executed", never CHECK it
// because we don't know whether the user wants to redo it.
if (checked) listCheckBox.operator[](i)->setChecked(false);
++i;
}
}
void Status::clearAllCheckBoxes()
{
for (auto &cb : listCheckBox) cb->setChecked(false);
}
QString Status::getStatusFromHistory(bool keepblanks)
{
QString statusString;
for (int i=0; i<numtasks; ++i) {
if (listHistory.at(i)) statusString.append(listFixedValue.at(i));
else statusString.append(" ");
}
// Return the status string with or without blanks
if (keepblanks) return statusString;
else return statusString.remove(" ");
}
// Find the ID of the last task executed that could have changed the processing status string.
// One could just hardcode the ABCDM chars and see what is the last char in the status, but
// it's better to keep this generic. Too hard to maintain otherwise.
/*
int Status::lastExecutedTaskId()
{
QString statusString = getStatusFromHistory(true);
int lastId = 0;
if (statusString.length() != numtasks) {
qDebug() << __func__ << "The length of the status string must match the number of tasks!";
return 0;
}
for (int i=0; i<numtasks; ++i) {
if (statusString.at(i) != " ") lastId = i;
}
return lastId;
}
*/
// If the status changed, e.g. by restoring a previous processing stage, then
// we must reflect this in the history, the checkboxes, and the action status
void Status::statusstringToHistory(QString &statusstring)
{
// HARDCODING !!!
if (statusstring.contains("P")) listHistory.operator[](0) = true;
else listHistory.operator[](0) = false;
if (statusstring.contains("A")) listHistory.operator[](5) = true;
else listHistory.operator[](5) = false;
if (statusstring.contains("M")) listHistory.operator[](6) = true;
else listHistory.operator[](6) = false;
if (statusstring.contains("B")) listHistory.operator[](7) = true;
else listHistory.operator[](7) = false;
if (statusstring.contains("C")) listHistory.operator[](8) = true;
else listHistory.operator[](8) = false;
if (statusstring.contains("D")) listHistory.operator[](16) = true;
else listHistory.operator[](16) = false;
if (statusstring.contains("S")) listHistory.operator[](17) = true;
else listHistory.operator[](17) = false;
// Update checkboxes and actions
updateStatus();
}
| 4,597
|
C++
|
.cc
| 118
| 34.788136
| 98
| 0.70649
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,403
|
settings.cc
|
schirmermischa_THELI/src/settings.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include <QSettings>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_confdockwidget.h"
int MainWindow::writePreferenceSettings()
{
QSettings settings("THELI", "PREFERENCES");
settings.setValue("setupProjectLineEdit", ui->setupProjectLineEdit->text());
settings.setValue("geometry", saveGeometry());
settings.setValue("windowState", saveState());
settings.sync();
return settings.status();
}
int MainWindow::readPreferenceSettings(QString &projectname)
{
QSettings settings("THELI", "PREFERENCES");
projectname = settings.value("setupProjectLineEdit","").toString();
diskwarnPreference = settings.value("prefDiskspacewarnSpinBox",100).toInt();
switchProcessMonitorPreference = settings.value("prefSwitchProcessMonitorCheckBox", true).toBool();
numCPU = settings.value("prefCPUSpinBox", QThread::idealThreadCount()).toInt();
restoreGeometry(settings.value("myWidget/geometry").toByteArray());
restoreState(settings.value("myWidget/windowState").toByteArray());
return settings.status();
}
QString MainWindow::getStatusForSettings()
{
QString statusString = "";
for (auto &it : status.listHistory) {
if (it) statusString.append("1");
else statusString.append("0");
}
return statusString;
}
void MainWindow::setStatusFromSettings(QString statusString)
{
// Enforce that the status string is no longer than the maximum string
// (this is in case I change the number of task checkboxes at some point)
statusString.truncate(19);
QStringList list = statusString.split("");
// The call above results in empty strings at the first and last place of the list.
// We need to remove them:
list.removeFirst();
list.removeLast();
int i = 0;
for (auto &it : list) {
if (it == "0") status.listHistory.operator[](i) = false;
else status.listHistory.operator[](i) = true;
++i;
}
status.updateStatus();
}
int MainWindow::writeGUISettings()
{
// We have to suppress write GUI settings while GUI settings are loaded.
// For example, this would be triggered by the updates of several setupDataDir LineEdits
// below. A writeGUI() would e.g. overwrite the instrument in the settings file before
// it can be read.
if (preventLoop_WriteSettings) return QSettings::NoError;
// Likewise, settings must not be written anytime during init
if (doingInitialLaunch) return QSettings::NoError;
// I don't like empty chars at the beginning. Not that they hurt so far, but nonetheless
for (auto &it: status.listDataDirs) {
QString text = it->text();
if (!text.isEmpty() && text.operator[](0) == ' ') text.remove(0,1);
it->setText(text);
}
QSettings settings("THELI", ui->setupProjectLineEdit->text());
settings.beginGroup("MainWindow");
QString statusString = getStatusForSettings();
settings.setValue("statusString", statusString);
// CONF DOCK WIDGET
settings.setValue("APDfilterComboBox", cdw->ui->APDfilterComboBox->currentIndex());
settings.setValue("APDmaxphoterrorLineEdit", cdw->ui->APDmaxphoterrorLineEdit->text());
settings.setValue("APDrefcatComboBox", cdw->ui->APDrefcatComboBox->currentIndex());
settings.setValue("APIWCSCheckBox", cdw->ui->APIWCSCheckBox->isChecked());
settings.setValue("APIWCSLineEdit", cdw->ui->APIWCSLineEdit->text());
settings.setValue("APIapertureLineEdit", cdw->ui->APIapertureLineEdit->text());
settings.setValue("APIcalibrationmodeComboBox", cdw->ui->APIcalibrationmodeComboBox->currentIndex());
settings.setValue("APIcolorComboBox", cdw->ui->APIcolorComboBox->currentIndex());
settings.setValue("APIcolortermLineEdit", cdw->ui->APIcolortermLineEdit->text());
settings.setValue("APIconvergenceLineEdit", cdw->ui->APIconvergenceLineEdit->text());
settings.setValue("APIextinctionLineEdit", cdw->ui->APIextinctionLineEdit->text());
settings.setValue("APIfilterComboBox", cdw->ui->APIfilterComboBox->currentIndex());
settings.setValue("APIfilterkeywordLineEdit", cdw->ui->APIfilterkeywordLineEdit->text());
settings.setValue("APIkappaLineEdit", cdw->ui->APIkappaLineEdit->text());
settings.setValue("APIminmagLineEdit", cdw->ui->APIminmagLineEdit->text());
settings.setValue("APInight1ComboBox", cdw->ui->APInight1ComboBox->currentIndex());
settings.setValue("APInight2ComboBox", cdw->ui->APInight2ComboBox->currentIndex());
settings.setValue("APInight3ComboBox", cdw->ui->APInight3ComboBox->currentIndex());
settings.setValue("APInight4ComboBox", cdw->ui->APInight4ComboBox->currentIndex());
settings.setValue("APInight5ComboBox", cdw->ui->APInight5ComboBox->currentIndex());
settings.setValue("APInight6ComboBox", cdw->ui->APInight6ComboBox->currentIndex());
settings.setValue("APInight7ComboBox", cdw->ui->APInight7ComboBox->currentIndex());
settings.setValue("APInight8ComboBox", cdw->ui->APInight8ComboBox->currentIndex());
settings.setValue("APInight9ComboBox", cdw->ui->APInight9ComboBox->currentIndex());
settings.setValue("APIrefcatComboBox", cdw->ui->APIrefcatComboBox->currentIndex());
settings.setValue("APIthresholdLineEdit", cdw->ui->APIthresholdLineEdit->text());
settings.setValue("APIzpmaxLineEdit", cdw->ui->APIzpmaxLineEdit->text());
settings.setValue("APIzpminLineEdit", cdw->ui->APIzpminLineEdit->text());
settings.setValue("ARCDMINLineEdit", cdw->ui->ARCDMINLineEdit->text());
settings.setValue("ARCDTLineEdit", cdw->ui->ARCDTLineEdit->text());
settings.setValue("ARCcatalogComboBox", cdw->ui->ARCcatalogComboBox->currentIndex());
settings.setValue("ARCdecLineEdit", cdw->ui->ARCdecLineEdit->text());
settings.setValue("ARCimageRadioButton", cdw->ui->ARCimageRadioButton->isChecked());
settings.setValue("ARCmaxpmLineEdit", cdw->ui->ARCmaxpmLineEdit->text());
settings.setValue("ARCpmRALineEdit", cdw->ui->ARCpmRALineEdit->text());
settings.setValue("ARCpmDECLineEdit", cdw->ui->ARCpmDECLineEdit->text());
settings.setValue("ARCminmagLineEdit", cdw->ui->ARCminmagLineEdit->text());
settings.setValue("ARCraLineEdit", cdw->ui->ARCraLineEdit->text());
settings.setValue("ARCradiusLineEdit", cdw->ui->ARCradiusLineEdit->text());
settings.setValue("ARCselectimageLineEdit", cdw->ui->ARCselectimageLineEdit->text());
settings.setValue("ARCtargetresolverLineEdit", cdw->ui->ARCtargetresolverLineEdit->text());
settings.setValue("ARCwebRadioButton", cdw->ui->ARCwebRadioButton->isChecked());
settings.setValue("ASTastrefweightLineEdit", cdw->ui->ASTastrefweightLineEdit->text());
settings.setValue("ASTastrinstrukeyLineEdit", cdw->ui->ASTastrinstrukeyLineEdit->text());
settings.setValue("ASTcrossidLineEdit", cdw->ui->ASTcrossidLineEdit->text());
settings.setValue("ASTdistortLineEdit", cdw->ui->ASTdistortLineEdit->text());
settings.setValue("ASTdistortgroupsLineEdit", cdw->ui->ASTdistortgroupsLineEdit->text());
settings.setValue("ASTdistortkeysLineEdit", cdw->ui->ASTdistortkeysLineEdit->text());
settings.setValue("ASTfocalplaneComboBox", cdw->ui->ASTfocalplaneComboBox->currentIndex());
settings.setValue("ASTmatchMethodComboBox", cdw->ui->ASTmatchMethodComboBox->currentIndex());
settings.setValue("ASTmatchflippedCheckBox", cdw->ui->ASTmatchflippedCheckBox->isChecked());
settings.setValue("ASTmethodComboBox", cdw->ui->ASTmethodComboBox->currentIndex());
settings.setValue("ASTmosaictypeComboBox", cdw->ui->ASTmosaictypeComboBox->currentIndex());
settings.setValue("ASTphotinstrukeyLineEdit", cdw->ui->ASTphotinstrukeyLineEdit->text());
settings.setValue("ASTpixscaleLineEdit", cdw->ui->ASTpixscaleLineEdit->text());
settings.setValue("ASTposangleLineEdit", cdw->ui->ASTposangleLineEdit->text());
settings.setValue("ASTpositionLineEdit", cdw->ui->ASTpositionLineEdit->text());
settings.setValue("ASTresolutionLineEdit", cdw->ui->ASTresolutionLineEdit->text());
settings.setValue("ASTsnthreshLineEdit", cdw->ui->ASTsnthreshLineEdit->text());
settings.setValue("ASTstabilityComboBox", cdw->ui->ASTstabilityComboBox->currentIndex());
settings.setValue("ASTxcorrDTLineEdit", cdw->ui->ASTxcorrDTLineEdit->text());
settings.setValue("ASTxcorrDMINLineEdit", cdw->ui->ASTxcorrDMINLineEdit->text());
settings.setValue("BAC1nhighLineEdit", cdw->ui->BAC1nhighLineEdit->text());
settings.setValue("BAC1nlowLineEdit", cdw->ui->BAC1nlowLineEdit->text());
settings.setValue("BAC2nhighLineEdit", cdw->ui->BAC2nhighLineEdit->text());
settings.setValue("BAC2nlowLineEdit", cdw->ui->BAC2nlowLineEdit->text());
settings.setValue("BAC2passCheckBox", cdw->ui->BAC2passCheckBox->isChecked());
settings.setValue("BACDMINLineEdit", cdw->ui->BACDMINLineEdit->text());
settings.setValue("BACDTLineEdit", cdw->ui->BACDTLineEdit->text());
settings.setValue("BACapplyComboBox", cdw->ui->BACapplyComboBox->currentIndex());
settings.setValue("BACbacksmoothscaleLineEdit", cdw->ui->BACbacksmoothscaleLineEdit->text());
settings.setValue("BACconvolutionCheckBox", cdw->ui->BACconvolutionCheckBox->isChecked());
settings.setValue("BACdistLineEdit", cdw->ui->BACdistLineEdit->text());
settings.setValue("BACgapsizeLineEdit", cdw->ui->BACgapsizeLineEdit->text());
settings.setValue("BACmagLineEdit", cdw->ui->BACmagLineEdit->text());
settings.setValue("BACmefLineEdit", cdw->ui->BACmefLineEdit->text());
settings.setValue("BACmethodComboBox", cdw->ui->BACmethodComboBox->currentIndex());
settings.setValue("BACrescaleCheckBox", cdw->ui->BACrescaleCheckBox->isChecked());
settings.setValue("BACwindowLineEdit", cdw->ui->BACwindowLineEdit->text());
settings.setValue("BACminWindowLineEdit", cdw->ui->BACminWindowLineEdit->text());
settings.setValue("BIPSpinBox", cdw->ui->BIPSpinBox->value());
settings.setValue("BIPrejectCheckBox", cdw->ui->BIPrejectCheckBox->isChecked());
settings.setValue("CGWbackclustolLineEdit", cdw->ui->CGWbackclustolLineEdit->text());
settings.setValue("CGWbackcoltolLineEdit", cdw->ui->CGWbackcoltolLineEdit->text());
settings.setValue("CGWbackmaxLineEdit", cdw->ui->CGWbackmaxLineEdit->text());
settings.setValue("CGWbackminLineEdit", cdw->ui->CGWbackminLineEdit->text());
settings.setValue("CGWbackrowtolLineEdit", cdw->ui->CGWbackrowtolLineEdit->text());
settings.setValue("CGWbacksmoothLineEdit", cdw->ui->CGWbacksmoothLineEdit->text());
settings.setValue("CGWdarkmaxLineEdit", cdw->ui->CGWdarkmaxLineEdit->text());
settings.setValue("CGWdarkminLineEdit", cdw->ui->CGWdarkminLineEdit->text());
settings.setValue("CGWflatclustolLineEdit", cdw->ui->CGWflatclustolLineEdit->text());
settings.setValue("CGWflatcoltolLineEdit", cdw->ui->CGWflatcoltolLineEdit->text());
settings.setValue("CGWflatmaxLineEdit", cdw->ui->CGWflatmaxLineEdit->text());
settings.setValue("CGWflatminLineEdit", cdw->ui->CGWflatminLineEdit->text());
settings.setValue("CGWflatrowtolLineEdit", cdw->ui->CGWflatrowtolLineEdit->text());
settings.setValue("CGWflatsmoothLineEdit", cdw->ui->CGWflatsmoothLineEdit->text());
settings.setValue("CGWsameweightCheckBox", cdw->ui->CGWsameweightCheckBox->isChecked());
settings.setValue("CIWsaturationLineEdit", cdw->ui->CIWsaturationLineEdit->text());
settings.setValue("CIWbloomRangeLineEdit", cdw->ui->CIWbloomRangeLineEdit->text());
settings.setValue("CIWbloomMinaduLineEdit", cdw->ui->CIWbloomMinaduLineEdit->text());
settings.setValue("CIWaggressivenessLineEdit", cdw->ui->CIWaggressivenessLineEdit->text());
settings.setValue("CIWmaskbloomingCheckBox", cdw->ui->CIWmaskbloomingCheckBox->isChecked());
settings.setValue("CIWmasksaturationCheckBox", cdw->ui->CIWmasksaturationCheckBox->isChecked());
settings.setValue("CIWmaxaduLineEdit", cdw->ui->CIWmaxaduLineEdit->text());
settings.setValue("CIWminaduLineEdit", cdw->ui->CIWminaduLineEdit->text());
settings.setValue("COAcelestialtypeComboBox", cdw->ui->COAcelestialtypeComboBox->currentIndex());
settings.setValue("COAchipsLineEdit", cdw->ui->COAchipsLineEdit->text());
settings.setValue("COAcombinetypeComboBox", cdw->ui->COAcombinetypeComboBox->currentIndex());
settings.setValue("COAdecLineEdit", cdw->ui->COAdecLineEdit->text());
settings.setValue("COAedgesmoothingLineEdit", cdw->ui->COAedgesmoothingLineEdit->text());
settings.setValue("COAfluxcalibCheckBox", cdw->ui->COAfluxcalibCheckBox->isChecked());
settings.setValue("COAkernelComboBox", cdw->ui->COAkernelComboBox->currentIndex());
settings.setValue("COAoutborderLineEdit", cdw->ui->COAoutborderLineEdit->text());
settings.setValue("COAoutsizeLineEdit", cdw->ui->COAoutsizeLineEdit->text());
settings.setValue("COAoutthreshLineEdit", cdw->ui->COAoutthreshLineEdit->text());
settings.setValue("COApixscaleLineEdit", cdw->ui->COApixscaleLineEdit->text());
settings.setValue("COApmComboBox", cdw->ui->COApmComboBox->currentIndex());
settings.setValue("COApmdecLineEdit", cdw->ui->COApmdecLineEdit->text());
settings.setValue("COApmraLineEdit", cdw->ui->COApmraLineEdit->text());
settings.setValue("COAprojectionComboBox", cdw->ui->COAprojectionComboBox->currentIndex());
settings.setValue("COAraLineEdit", cdw->ui->COAraLineEdit->text());
settings.setValue("COArescaleweightsCheckBox", cdw->ui->COArescaleweightsCheckBox->isChecked());
settings.setValue("COArzpCheckBox", cdw->ui->COArzpCheckBox->isChecked());
settings.setValue("COAminMJDOBSLineEdit", cdw->ui->COAminMJDOBSLineEdit->text());
settings.setValue("COAmaxMJDOBSLineEdit", cdw->ui->COAmaxMJDOBSLineEdit->text());
settings.setValue("COAsizexLineEdit", cdw->ui->COAsizexLineEdit->text());
settings.setValue("COAsizeyLineEdit", cdw->ui->COAsizeyLineEdit->text());
settings.setValue("COAskypaLineEdit", cdw->ui->COAskypaLineEdit->text());
settings.setValue("COAuniqueidLineEdit", cdw->ui->COAuniqueidLineEdit->text());
settings.setValue("COCDMINLineEdit", cdw->ui->COCDMINLineEdit->text());
settings.setValue("COCDTLineEdit", cdw->ui->COCDTLineEdit->text());
settings.setValue("COCdirectionComboBox", cdw->ui->COCdirectionComboBox->currentIndex());
settings.setValue("COCmefLineEdit", cdw->ui->COCmefLineEdit->text());
settings.setValue("COCrejectLineEdit", cdw->ui->COCrejectLineEdit->text());
settings.setValue("COCxmaxLineEdit", cdw->ui->COCxmaxLineEdit->text());
settings.setValue("COCxminLineEdit", cdw->ui->COCxminLineEdit->text());
settings.setValue("COCymaxLineEdit", cdw->ui->COCymaxLineEdit->text());
settings.setValue("COCyminLineEdit", cdw->ui->COCyminLineEdit->text());
settings.setValue("CSCDMINLineEdit", cdw->ui->CSCDMINLineEdit->text());
settings.setValue("CSCDTLineEdit", cdw->ui->CSCDTLineEdit->text());
settings.setValue("CSCFWHMLineEdit", cdw->ui->CSCFWHMLineEdit->text());
settings.setValue("CSCbackgroundLineEdit", cdw->ui->CSCbackgroundLineEdit->text());
settings.setValue("CSCmaxflagLineEdit", cdw->ui->CSCmaxflagLineEdit->text());
settings.setValue("CSCmaxellLineEdit", cdw->ui->CSCmaxellLineEdit->text());
settings.setValue("CSCmincontLineEdit", cdw->ui->CSCmincontLineEdit->text());
settings.setValue("CSCrejectExposureLineEdit", cdw->ui->CSCrejectExposureLineEdit->text());
settings.setValue("CSCconvolutionCheckBox", cdw->ui->CSCconvolutionCheckBox->isChecked());
settings.setValue("CSCsamplingCheckBox", cdw->ui->CSCsamplingCheckBox->isChecked());
settings.setValue("CSCsaturationLineEdit", cdw->ui->CSCsaturationLineEdit->text());
settings.setValue("CSCMethodComboBox", cdw->ui->CSCMethodComboBox->currentIndex());
settings.setValue("SPSlengthLineEdit", cdw->ui->SPSlengthLineEdit->text());
settings.setValue("SPSexcludeLineEdit", cdw->ui->SPSexcludeLineEdit->text());
settings.setValue("SPSnumbergroupsLineEdit", cdw->ui->SPSnumbergroupsLineEdit->text());
settings.setValue("biasMaxLineEdit", cdw->ui->biasMaxLineEdit->text());
settings.setValue("biasMinLineEdit", cdw->ui->biasMinLineEdit->text());
settings.setValue("biasNhighLineEdit", cdw->ui->biasNhighLineEdit->text());
settings.setValue("biasNlowLineEdit", cdw->ui->biasNlowLineEdit->text());
settings.setValue("biasMethodComboBox", cdw->ui->biasMethodComboBox->currentIndex());
settings.setValue("chopnodComboBox", cdw->ui->chopnodComboBox->currentIndex());
settings.setValue("chopnodInvertCheckBox", cdw->ui->chopnodInvertCheckBox->isChecked());
settings.setValue("confStackedWidget", cdw->ui->confStackedWidget->currentIndex());
settings.setValue("darkMaxLineEdit", cdw->ui->darkMaxLineEdit->text());
settings.setValue("darkMinLineEdit", cdw->ui->darkMinLineEdit->text());
settings.setValue("darkNhighLineEdit", cdw->ui->darkNhighLineEdit->text());
settings.setValue("darkNlowLineEdit", cdw->ui->darkNlowLineEdit->text());
settings.setValue("darkMethodComboBox", cdw->ui->darkMethodComboBox->currentIndex());
settings.setValue("excludeDetectorsLineEdit", cdw->ui->excludeDetectorsLineEdit->text());
settings.setValue("flatMaxLineEdit", cdw->ui->flatMaxLineEdit->text());
settings.setValue("flatMinLineEdit", cdw->ui->flatMinLineEdit->text());
settings.setValue("flatNhighLineEdit", cdw->ui->flatNhighLineEdit->text());
settings.setValue("flatNlowLineEdit", cdw->ui->flatNlowLineEdit->text());
settings.setValue("flatMethodComboBox", cdw->ui->flatMethodComboBox->currentIndex());
settings.setValue("flatoffMaxLineEdit", cdw->ui->flatoffMaxLineEdit->text());
settings.setValue("flatoffMinLineEdit", cdw->ui->flatoffMinLineEdit->text());
settings.setValue("flatoffNhighLineEdit", cdw->ui->flatoffNhighLineEdit->text());
settings.setValue("flatoffNlowLineEdit", cdw->ui->flatoffNlowLineEdit->text());
settings.setValue("flatoffMethodComboBox", cdw->ui->flatoffMethodComboBox->currentIndex());
settings.setValue("overscanCheckBox", cdw->ui->overscanCheckBox->isChecked());
settings.setValue("theliRenamingCheckBox", cdw->ui->theliRenamingCheckBox->isChecked());
settings.setValue("nonlinearityCheckBox", cdw->ui->nonlinearityCheckBox->isChecked());
settings.setValue("normalxtalkAmplitudeLineEdit", cdw->ui->normalxtalkAmplitudeLineEdit->text());
settings.setValue("normalxtalkCheckBox", cdw->ui->normalxtalkCheckBox->isChecked());
settings.setValue("overscanMethodComboBox", cdw->ui->overscanMethodComboBox->currentIndex());
settings.setValue("rowxtalkAmplitudeLineEdit", cdw->ui->rowxtalkAmplitudeLineEdit->text());
settings.setValue("rowxtalkCheckBox", cdw->ui->rowxtalkCheckBox->isChecked());
settings.setValue("saturationLineEdit", cdw->ui->saturationLineEdit->text());
settings.setValue("separateTargetLineEdit", cdw->ui->separateTargetLineEdit->text());
settings.setValue("skyAreaComboBox", cdw->ui->skyAreaComboBox->currentIndex());
settings.setValue("skyConstsubRadioButton", cdw->ui->skyConstsubRadioButton->isChecked());
settings.setValue("skyDMINLineEdit", cdw->ui->skyDMINLineEdit->text());
settings.setValue("skyDTLineEdit", cdw->ui->skyDTLineEdit->text());
settings.setValue("skyKernelLineEdit", cdw->ui->skyKernelLineEdit->text());
settings.setValue("skyMefLineEdit", cdw->ui->skyMefLineEdit->text());
settings.setValue("skyModelRadioButton", cdw->ui->skyModelRadioButton->isChecked());
settings.setValue("skyPolynomialRadioButton", cdw->ui->skyPolynomialRadioButton->isChecked());
settings.setValue("skyPolynomialSpinBox", cdw->ui->skyPolynomialSpinBox->value());
settings.setValue("skySavemodelCheckBox", cdw->ui->skySavemodelCheckBox->isChecked());
settings.setValue("splitMIRcubeCheckBox", cdw->ui->splitMIRcubeCheckBox->isChecked());
settings.setValue("xtalk_col_1x2ToolButton", cdw->ui->xtalk_col_1x2ToolButton->isChecked());
settings.setValue("xtalk_col_2x1ToolButton", cdw->ui->xtalk_col_2x1ToolButton->isChecked());
settings.setValue("xtalk_col_2x2ToolButton", cdw->ui->xtalk_col_2x2ToolButton->isChecked());
settings.setValue("xtalk_nor_1x2ToolButton", cdw->ui->xtalk_nor_1x2ToolButton->isChecked());
settings.setValue("xtalk_nor_2x1ToolButton", cdw->ui->xtalk_nor_2x1ToolButton->isChecked());
settings.setValue("xtalk_nor_2x2ToolButton", cdw->ui->xtalk_nor_2x2ToolButton->isChecked());
settings.setValue("xtalk_row_1x2ToolButton", cdw->ui->xtalk_row_1x2ToolButton->isChecked());
settings.setValue("xtalk_row_2x1ToolButton", cdw->ui->xtalk_row_2x1ToolButton->isChecked());
settings.setValue("xtalk_row_2x2ToolButton", cdw->ui->xtalk_row_2x2ToolButton->isChecked());
// MAIN WINDOW
settings.setValue("applyAbsphotindirectCheckBox", ui->applyAbsphotindirectCheckBox->isChecked());
settings.setValue("applyAstromphotomCheckBox", ui->applyAstromphotomCheckBox->isChecked());
settings.setValue("applyBackgroundCheckBox", ui->applyBackgroundCheckBox->isChecked());
settings.setValue("applyBinnedpreviewCheckBox", ui->applyBinnedpreviewCheckBox->isChecked());
settings.setValue("applyChopnodCheckBox", ui->applyChopnodCheckBox->isChecked());
settings.setValue("applyCoadditionCheckBox", ui->applyCoadditionCheckBox->isChecked());
settings.setValue("applyCollapseCheckBox", ui->applyCollapseCheckBox->isChecked());
settings.setValue("applyCreatesourcecatCheckBox", ui->applyCreatesourcecatCheckBox->isChecked());
settings.setValue("applyGlobalweightCheckBox", ui->applyGlobalweightCheckBox->isChecked());
settings.setValue("applyHDUreformatCheckBox", ui->applyHDUreformatCheckBox->isChecked());
settings.setValue("applyIndividualweightCheckBox", ui->applyIndividualweightCheckBox->isChecked());
settings.setValue("applyProcessbiasCheckBox", ui->applyProcessbiasCheckBox->isChecked());
settings.setValue("applyProcessdarkCheckBox", ui->applyProcessdarkCheckBox->isChecked());
settings.setValue("applyProcessflatCheckBox", ui->applyProcessflatCheckBox->isChecked());
settings.setValue("applyProcessflatoffCheckBox", ui->applyProcessflatoffCheckBox->isChecked());
settings.setValue("applyProcessscienceCheckBox", ui->applyProcessscienceCheckBox->isChecked());
settings.setValue("applySeparateCheckBox", ui->applySeparateCheckBox->isChecked());
settings.setValue("applySkysubCheckBox", ui->applySkysubCheckBox->isChecked());
settings.setValue("applyStarflatCheckBox", ui->applyStarflatCheckBox->isChecked());
settings.setValue("processingTabWidget", ui->processingTabWidget->currentIndex());
settings.setValue("setupBiasLineEdit", ui->setupBiasLineEdit->text());
settings.setValue("setupDarkLineEdit", ui->setupDarkLineEdit->text());
settings.setValue("setupFlatLineEdit", ui->setupFlatLineEdit->text());
settings.setValue("setupFlatoffLineEdit", ui->setupFlatoffLineEdit->text());
settings.setValue("setupInstrumentComboBox", ui->setupInstrumentComboBox->currentText());
settings.setValue("setupMainLineEdit", ui->setupMainLineEdit->text());
settings.setValue("setupProjectLineEdit", ui->setupProjectLineEdit->text());
settings.setValue("setupScienceLineEdit", ui->setupScienceLineEdit->text());
settings.setValue("setupSkyLineEdit", ui->setupSkyLineEdit->text());
settings.setValue("setupStandardLineEdit", ui->setupStandardLineEdit->text());
settings.endGroup();
settings.sync();
return settings.status();
}
int MainWindow::readGUISettings(QString projectname)
{
preventLoop_WriteSettings = true;
if (projectname.isEmpty()) {
projectname = "MyProject";
ui->setupProjectLineEdit->setText(projectname);
cdw->loadDefaults();
fill_setupInstrumentComboBox();
preventLoop_WriteSettings = false;
return 3; // not checked
}
QSettings settings("THELI", projectname);
settings.beginGroup("MainWindow");
readingSettings = true;
setStatusFromSettings(settings.value("statusString").toString());
// CONF DOCK WIDGET
cdw->ui->APDfilterComboBox->setCurrentIndex(settings.value("APDfilterComboBox").toInt());
cdw->ui->APDmaxphoterrorLineEdit->setText(settings.value("APDmaxphoterrorLineEdit").toString());
cdw->ui->APDrefcatComboBox->setCurrentIndex(settings.value("APDrefcatComboBox").toInt());
cdw->ui->APIWCSCheckBox->setChecked(settings.value("APIWCSCheckBox").toBool());
cdw->ui->APIWCSLineEdit->setText(settings.value("APIWCSLineEdit").toString());
cdw->ui->APIapertureLineEdit->setText(settings.value("APIapertureLineEdit").toString());
cdw->ui->APIcalibrationmodeComboBox->setCurrentIndex(settings.value("APIcalibrationmodeComboBox").toInt());
cdw->ui->APIcolorComboBox->setCurrentIndex(settings.value("APIcolorComboBox").toInt());
cdw->ui->APIcolortermLineEdit->setText(settings.value("APIcolortermLineEdit").toString());
cdw->ui->APIconvergenceLineEdit->setText(settings.value("APIconvergenceLineEdit").toString());
cdw->ui->APIextinctionLineEdit->setText(settings.value("APIextinctionLineEdit").toString());
cdw->ui->APIfilterComboBox->setCurrentIndex(settings.value("APIfilterComboBox").toInt());
cdw->ui->APIfilterkeywordLineEdit->setText(settings.value("APIfilterkeywordLineEdit").toString());
cdw->ui->APIkappaLineEdit->setText(settings.value("APIkappaLineEdit").toString());
cdw->ui->APIminmagLineEdit->setText(settings.value("APIminmagLineEdit").toString());
cdw->ui->APInight1ComboBox->setCurrentIndex(settings.value("APInight1ComboBox").toInt());
cdw->ui->APInight2ComboBox->setCurrentIndex(settings.value("APInight2ComboBox").toInt());
cdw->ui->APInight3ComboBox->setCurrentIndex(settings.value("APInight3ComboBox").toInt());
cdw->ui->APInight4ComboBox->setCurrentIndex(settings.value("APInight4ComboBox").toInt());
cdw->ui->APInight5ComboBox->setCurrentIndex(settings.value("APInight5ComboBox").toInt());
cdw->ui->APInight6ComboBox->setCurrentIndex(settings.value("APInight6ComboBox").toInt());
cdw->ui->APInight7ComboBox->setCurrentIndex(settings.value("APInight7ComboBox").toInt());
cdw->ui->APInight8ComboBox->setCurrentIndex(settings.value("APInight8ComboBox").toInt());
cdw->ui->APInight9ComboBox->setCurrentIndex(settings.value("APInight9ComboBox").toInt());
cdw->ui->APIrefcatComboBox->setCurrentIndex(settings.value("APIrefcatComboBox").toInt());
cdw->ui->APIthresholdLineEdit->setText(settings.value("APIthresholdLineEdit").toString());
cdw->ui->APIzpmaxLineEdit->setText(settings.value("APIzpmaxLineEdit").toString());
cdw->ui->APIzpminLineEdit->setText(settings.value("APIzpminLineEdit").toString());
cdw->ui->ARCDMINLineEdit->setText(settings.value("ARCDMINLineEdit").toString());
cdw->ui->ARCDTLineEdit->setText(settings.value("ARCDTLineEdit").toString());
cdw->ui->ARCcatalogComboBox->setCurrentIndex(settings.value("ARCcatalogComboBox").toInt());
cdw->ui->ARCdecLineEdit->setText(settings.value("ARCdecLineEdit").toString());
cdw->ui->ARCimageRadioButton->setChecked(settings.value("ARCimageRadioButton").toBool());
cdw->ui->ARCmaxpmLineEdit->setText(settings.value("ARCmaxpmLineEdit").toString());
cdw->ui->ARCpmRALineEdit->setText(settings.value("ARCpmRALineEdit").toString());
cdw->ui->ARCpmDECLineEdit->setText(settings.value("ARCpmDECLineEdit").toString());
cdw->ui->ARCminmagLineEdit->setText(settings.value("ARCminmagLineEdit").toString());
cdw->ui->ARCraLineEdit->setText(settings.value("ARCraLineEdit").toString());
cdw->ui->ARCradiusLineEdit->setText(settings.value("ARCradiusLineEdit").toString());
cdw->ui->ARCselectimageLineEdit->setText(settings.value("ARCselectimageLineEdit").toString());
cdw->ui->ARCtargetresolverLineEdit->setText(settings.value("ARCtargetresolverLineEdit").toString());
cdw->ui->ARCwebRadioButton->setChecked(settings.value("ARCwebRadioButton").toBool());
cdw->ui->ASTastrefweightLineEdit->setText(settings.value("ASTastrefweightLineEdit").toString());
cdw->ui->ASTastrinstrukeyLineEdit->setText(settings.value("ASTastrinstrukeyLineEdit").toString());
cdw->ui->ASTcrossidLineEdit->setText(settings.value("ASTcrossidLineEdit").toString());
cdw->ui->ASTdistortLineEdit->setText(settings.value("ASTdistortLineEdit").toString());
cdw->ui->ASTdistortgroupsLineEdit->setText(settings.value("ASTdistortgroupsLineEdit").toString());
cdw->ui->ASTdistortkeysLineEdit->setText(settings.value("ASTdistortkeysLineEdit").toString());
cdw->ui->ASTfocalplaneComboBox->setCurrentIndex(settings.value("ASTfocalplaneComboBox").toInt());
cdw->ui->ASTmatchMethodComboBox->setCurrentIndex(settings.value("ASTmatchMethodComboBox").toInt());
cdw->ui->ASTmatchflippedCheckBox->setChecked(settings.value("ASTmatchflippedCheckBox").toBool());
cdw->ui->ASTmethodComboBox->setCurrentIndex(settings.value("ASTmethodComboBox").toInt());
cdw->ui->ASTmosaictypeComboBox->setCurrentIndex(settings.value("ASTmosaictypeComboBox").toInt());
cdw->ui->ASTphotinstrukeyLineEdit->setText(settings.value("ASTphotinstrukeyLineEdit").toString());
cdw->ui->ASTpixscaleLineEdit->setText(settings.value("ASTpixscaleLineEdit").toString());
cdw->ui->ASTposangleLineEdit->setText(settings.value("ASTposangleLineEdit").toString());
cdw->ui->ASTpositionLineEdit->setText(settings.value("ASTpositionLineEdit").toString());
cdw->ui->ASTresolutionLineEdit->setText(settings.value("ASTresolutionLineEdit").toString());
cdw->ui->ASTsnthreshLineEdit->setText(settings.value("ASTsnthreshLineEdit").toString());
cdw->ui->ASTstabilityComboBox->setCurrentIndex(settings.value("ASTstabilityComboBox").toInt());
cdw->ui->ASTxcorrDTLineEdit->setText(settings.value("ASTxcorrDTLineEdit").toString());
cdw->ui->ASTxcorrDMINLineEdit->setText(settings.value("ASTxcorrDMINLineEdit").toString());
cdw->ui->BAC1nhighLineEdit->setText(settings.value("BAC1nhighLineEdit").toString());
cdw->ui->BAC1nlowLineEdit->setText(settings.value("BAC1nlowLineEdit").toString());
cdw->ui->BAC2nhighLineEdit->setText(settings.value("BAC2nhighLineEdit").toString());
cdw->ui->BAC2nlowLineEdit->setText(settings.value("BAC2nlowLineEdit").toString());
cdw->ui->BAC2passCheckBox->setChecked(settings.value("BAC2passCheckBox").toBool());
cdw->ui->BACDMINLineEdit->setText(settings.value("BACDMINLineEdit").toString());
cdw->ui->BACDTLineEdit->setText(settings.value("BACDTLineEdit").toString());
cdw->ui->BACapplyComboBox->setCurrentIndex(settings.value("BACapplyComboBox").toInt());
cdw->ui->BACbacksmoothscaleLineEdit->setText(settings.value("BACbacksmoothscaleLineEdit").toString());
cdw->ui->BACconvolutionCheckBox->setChecked(settings.value("BACconvolutionCheckBox").toBool());
cdw->ui->BACdistLineEdit->setText(settings.value("BACdistLineEdit").toString());
cdw->ui->BACgapsizeLineEdit->setText(settings.value("BACgapsizeLineEdit").toString());
cdw->ui->BACmagLineEdit->setText(settings.value("BACmagLineEdit").toString());
cdw->ui->BACmefLineEdit->setText(settings.value("BACmefLineEdit").toString());
cdw->ui->BACmethodComboBox->setCurrentIndex(settings.value("BACmethodComboBox").toInt());
cdw->ui->BACrescaleCheckBox->setChecked(settings.value("BACrescaleCheckBox").toBool());
cdw->ui->BACwindowLineEdit->setText(settings.value("BACwindowLineEdit").toString());
cdw->ui->BACminWindowLineEdit->setText(settings.value("BACminWindowLineEdit").toString());
cdw->ui->BIPSpinBox->setValue(settings.value("BIPSpinBox").toInt());
cdw->ui->BIPrejectCheckBox->setChecked(settings.value("BIPrejectCheckBox").toBool());
cdw->ui->CGWbackclustolLineEdit->setText(settings.value("CGWbackclustolLineEdit").toString());
cdw->ui->CGWbackcoltolLineEdit->setText(settings.value("CGWbackcoltolLineEdit").toString());
cdw->ui->CGWbackmaxLineEdit->setText(settings.value("CGWbackmaxLineEdit").toString());
cdw->ui->CGWbackminLineEdit->setText(settings.value("CGWbackminLineEdit").toString());
cdw->ui->CGWbackrowtolLineEdit->setText(settings.value("CGWbackrowtolLineEdit").toString());
cdw->ui->CGWbacksmoothLineEdit->setText(settings.value("CGWbacksmoothLineEdit").toString());
cdw->ui->CGWdarkmaxLineEdit->setText(settings.value("CGWdarkmaxLineEdit").toString());
cdw->ui->CGWdarkminLineEdit->setText(settings.value("CGWdarkminLineEdit").toString());
cdw->ui->CGWflatclustolLineEdit->setText(settings.value("CGWflatclustolLineEdit").toString());
cdw->ui->CGWflatcoltolLineEdit->setText(settings.value("CGWflatcoltolLineEdit").toString());
cdw->ui->CGWflatmaxLineEdit->setText(settings.value("CGWflatmaxLineEdit").toString());
cdw->ui->CGWflatminLineEdit->setText(settings.value("CGWflatminLineEdit").toString());
cdw->ui->CGWflatrowtolLineEdit->setText(settings.value("CGWflatrowtolLineEdit").toString());
cdw->ui->CGWflatsmoothLineEdit->setText(settings.value("CGWflatsmoothLineEdit").toString());
cdw->ui->CGWsameweightCheckBox->setChecked(settings.value("CGWsameweightCheckBox").toBool());
cdw->ui->CIWsaturationLineEdit->setText(settings.value("CIWsaturationLineEdit").toString());
cdw->ui->CIWbloomRangeLineEdit->setText(settings.value("CIWbloomRangeLineEdit").toString());
cdw->ui->CIWbloomMinaduLineEdit->setText(settings.value("CIWbloomMinaduLineEdit").toString());
cdw->ui->CIWaggressivenessLineEdit->setText(settings.value("CIWaggressivenessLineEdit").toString());
cdw->ui->CIWmaskbloomingCheckBox->setChecked(settings.value("CIWmaskbloomingCheckBox").toBool());
cdw->ui->CIWmasksaturationCheckBox->setChecked(settings.value("CIWmasksaturationCheckBox").toBool());
cdw->ui->CIWmaxaduLineEdit->setText(settings.value("CIWmaxaduLineEdit").toString());
cdw->ui->CIWminaduLineEdit->setText(settings.value("CIWminaduLineEdit").toString());
cdw->ui->COAcelestialtypeComboBox->setCurrentIndex(settings.value("COAcelestialtypeComboBox").toInt());
cdw->ui->COAchipsLineEdit->setText(settings.value("COAchipsLineEdit").toString());
cdw->ui->COAcombinetypeComboBox->setCurrentIndex(settings.value("COAcombinetypeComboBox").toInt());
cdw->ui->COAdecLineEdit->setText(settings.value("COAdecLineEdit").toString());
cdw->ui->COAedgesmoothingLineEdit->setText(settings.value("COAedgesmoothingLineEdit").toString());
cdw->ui->COAfluxcalibCheckBox->setChecked(settings.value("COAfluxcalibCheckBox").toBool());
cdw->ui->COAkernelComboBox->setCurrentIndex(settings.value("COAkernelComboBox").toInt());
cdw->ui->COAoutborderLineEdit->setText(settings.value("COAoutborderLineEdit").toString());
cdw->ui->COAoutsizeLineEdit->setText(settings.value("COAoutsizeLineEdit").toString());
cdw->ui->COAoutthreshLineEdit->setText(settings.value("COAoutthreshLineEdit").toString());
cdw->ui->COApixscaleLineEdit->setText(settings.value("COApixscaleLineEdit").toString());
cdw->ui->COApmComboBox->setCurrentIndex(settings.value("COApmComboBox").toInt());
cdw->ui->COApmdecLineEdit->setText(settings.value("COApmdecLineEdit").toString());
cdw->ui->COApmraLineEdit->setText(settings.value("COApmraLineEdit").toString());
cdw->ui->COAprojectionComboBox->setCurrentIndex(settings.value("COAprojectionComboBox").toInt());
cdw->ui->COAraLineEdit->setText(settings.value("COAraLineEdit").toString());
cdw->ui->COArescaleweightsCheckBox->setChecked(settings.value("COArescaleweightsCheckBox").toBool());
cdw->ui->COArzpCheckBox->setChecked(settings.value("COArzpCheckBox").toBool());
cdw->ui->COAminMJDOBSLineEdit->setText(settings.value("COAminMJDOBSLineEdit").toString());
cdw->ui->COAmaxMJDOBSLineEdit->setText(settings.value("COAmaxMJDOBSLineEdit").toString());
cdw->ui->COAsizexLineEdit->setText(settings.value("COAsizexLineEdit").toString());
cdw->ui->COAsizeyLineEdit->setText(settings.value("COAsizeyLineEdit").toString());
cdw->ui->COAskypaLineEdit->setText(settings.value("COAskypaLineEdit").toString());
cdw->ui->COAuniqueidLineEdit->setText(settings.value("COAuniqueidLineEdit").toString());
cdw->ui->COCDMINLineEdit->setText(settings.value("COCDMINLineEdit").toString());
cdw->ui->COCDTLineEdit->setText(settings.value("COCDTLineEdit").toString());
cdw->ui->COCdirectionComboBox->setCurrentIndex(settings.value("COCdirectionComboBox").toInt());
cdw->ui->COCmefLineEdit->setText(settings.value("COCmefLineEdit").toString());
cdw->ui->COCrejectLineEdit->setText(settings.value("COCrejectLineEdit").toString());
cdw->ui->COCxmaxLineEdit->setText(settings.value("COCxmaxLineEdit").toString());
cdw->ui->COCxminLineEdit->setText(settings.value("COCxminLineEdit").toString());
cdw->ui->COCymaxLineEdit->setText(settings.value("COCymaxLineEdit").toString());
cdw->ui->COCyminLineEdit->setText(settings.value("COCyminLineEdit").toString());
cdw->ui->CSCDMINLineEdit->setText(settings.value("CSCDMINLineEdit").toString());
cdw->ui->CSCDTLineEdit->setText(settings.value("CSCDTLineEdit").toString());
cdw->ui->CSCFWHMLineEdit->setText(settings.value("CSCFWHMLineEdit").toString());
cdw->ui->CSCbackgroundLineEdit->setText(settings.value("CSCbackgroundLineEdit").toString());
cdw->ui->CSCmaxflagLineEdit->setText(settings.value("CSCmaxflagLineEdit").toString());
cdw->ui->CSCmaxellLineEdit->setText(settings.value("CSCmaxellLineEdit").toString());
cdw->ui->CSCMethodComboBox->setCurrentIndex(settings.value("CSCMethodComboBox").toInt());
cdw->ui->CSCmincontLineEdit->setText(settings.value("CSCmincontLineEdit").toString());
cdw->ui->CSCrejectExposureLineEdit->setText(settings.value("CSCrejectExposureLineEdit").toString());
cdw->ui->CSCconvolutionCheckBox->setChecked(settings.value("CSCconvolutionCheckBox").toBool());
cdw->ui->CSCsamplingCheckBox->setChecked(settings.value("CSCsamplingCheckBox").toBool());
cdw->ui->CSCsaturationLineEdit->setText(settings.value("CSCsaturationLineEdit").toString());
cdw->ui->SPSlengthLineEdit->setText(settings.value("SPSlengthLineEdit").toString());
cdw->ui->SPSnumbergroupsLineEdit->setText(settings.value("SPSnumbergroupsLineEdit").toString());
cdw->ui->SPSexcludeLineEdit->setText(settings.value("SPSexcludeLineEdit").toString());
cdw->ui->biasMaxLineEdit->setText(settings.value("biasMaxLineEdit").toString());
cdw->ui->biasMinLineEdit->setText(settings.value("biasMinLineEdit").toString());
cdw->ui->biasNhighLineEdit->setText(settings.value("biasNhighLineEdit").toString());
cdw->ui->biasNlowLineEdit->setText(settings.value("biasNlowLineEdit").toString());
cdw->ui->biasMethodComboBox->setCurrentIndex(settings.value("biasMethodComboBox").toInt());
cdw->ui->chopnodComboBox->setCurrentIndex(settings.value("chopnodComboBox").toInt());
cdw->ui->chopnodInvertCheckBox->setChecked(settings.value("chopnodInvertCheckBox").toBool());
cdw->ui->darkMaxLineEdit->setText(settings.value("darkMaxLineEdit").toString());
cdw->ui->darkMinLineEdit->setText(settings.value("darkMinLineEdit").toString());
cdw->ui->darkNhighLineEdit->setText(settings.value("darkNhighLineEdit").toString());
cdw->ui->darkNlowLineEdit->setText(settings.value("darkNlowLineEdit").toString());
cdw->ui->darkMethodComboBox->setCurrentIndex(settings.value("darkMethodComboBox").toInt());
cdw->ui->excludeDetectorsLineEdit->setText(settings.value("excludeDetectorsLineEdit").toString());
cdw->ui->flatMaxLineEdit->setText(settings.value("flatMaxLineEdit").toString());
cdw->ui->flatMinLineEdit->setText(settings.value("flatMinLineEdit").toString());
cdw->ui->flatNhighLineEdit->setText(settings.value("flatNhighLineEdit").toString());
cdw->ui->flatNlowLineEdit->setText(settings.value("flatNlowLineEdit").toString());
cdw->ui->flatMethodComboBox->setCurrentIndex(settings.value("flatMethodComboBox").toInt());
cdw->ui->flatoffMaxLineEdit->setText(settings.value("flatoffMaxLineEdit").toString());
cdw->ui->flatoffMinLineEdit->setText(settings.value("flatoffMinLineEdit").toString());
cdw->ui->flatoffNhighLineEdit->setText(settings.value("flatoffNhighLineEdit").toString());
cdw->ui->flatoffNlowLineEdit->setText(settings.value("flatoffNlowLineEdit").toString());
cdw->ui->flatoffMethodComboBox->setCurrentIndex(settings.value("flatoffMethodComboBox").toInt());
// Instrument-dependent, see below
// cdw->ui->skyAreaComboBox->setCurrentIndex(settings.value("skyAreaComboBox").toInt());
cdw->ui->skyConstsubRadioButton->setChecked(settings.value("skyConstsubRadioButton").toBool());
cdw->ui->skyDMINLineEdit->setText(settings.value("skyDMINLineEdit").toString());
cdw->ui->skyDTLineEdit->setText(settings.value("skyDTLineEdit").toString());
cdw->ui->skyKernelLineEdit->setText(settings.value("skyKernelLineEdit").toString());
cdw->ui->skyMefLineEdit->setText(settings.value("skyMefLineEdit").toString());
cdw->ui->skyModelRadioButton->setChecked(settings.value("skyModelRadioButton").toBool());
cdw->ui->skyPolynomialRadioButton->setChecked(settings.value("skyPolynomialRadioButton").toBool());
cdw->ui->skyPolynomialSpinBox->setValue(settings.value("skyPolynomialSpinBox").toInt());
cdw->ui->skySavemodelCheckBox->setChecked(settings.value("skySavemodelCheckBox").toBool());
cdw->ui->theliRenamingCheckBox->setChecked(settings.value("theliRenamingCheckBox").toBool());
cdw->ui->overscanCheckBox->setChecked(settings.value("overscanCheckBox").toBool());
cdw->ui->nonlinearityCheckBox->setChecked(settings.value("nonlinearityCheckBox").toBool());
cdw->ui->normalxtalkAmplitudeLineEdit->setText(settings.value("normalxtalkAmplitudeLineEdit").toString());
cdw->ui->normalxtalkCheckBox->setChecked(settings.value("normalxtalkCheckBox").toBool());
cdw->ui->overscanMethodComboBox->setCurrentIndex(settings.value("overscanMethodComboBox").toInt());
cdw->ui->splitMIRcubeCheckBox->setChecked(settings.value("splitMIRcubeCheckBox").toBool());
cdw->ui->xtalk_col_1x2ToolButton->setChecked(settings.value("xtalk_col_1x2ToolButton").toBool());
cdw->ui->xtalk_col_2x1ToolButton->setChecked(settings.value("xtalk_col_2x1ToolButton").toBool());
cdw->ui->xtalk_col_2x2ToolButton->setChecked(settings.value("xtalk_col_2x2ToolButton").toBool());
cdw->ui->xtalk_nor_1x2ToolButton->setChecked(settings.value("xtalk_nor_1x2ToolButton").toBool());
cdw->ui->xtalk_nor_2x1ToolButton->setChecked(settings.value("xtalk_nor_2x1ToolButton").toBool());
cdw->ui->xtalk_nor_2x2ToolButton->setChecked(settings.value("xtalk_nor_2x2ToolButton").toBool());
cdw->ui->xtalk_row_1x2ToolButton->setChecked(settings.value("xtalk_row_1x2ToolButton").toBool());
cdw->ui->xtalk_row_2x1ToolButton->setChecked(settings.value("xtalk_row_2x1ToolButton").toBool());
cdw->ui->xtalk_row_2x2ToolButton->setChecked(settings.value("xtalk_row_2x2ToolButton").toBool());
cdw->ui->confStackedWidget->setCurrentIndex(settings.value("confStackedWidget").toInt());
cdw->ui->rowxtalkAmplitudeLineEdit->setText(settings.value("rowxtalkAmplitudeLineEdit").toString());
cdw->ui->rowxtalkCheckBox->setChecked(settings.value("rowxtalkCheckBox").toBool());
cdw->ui->saturationLineEdit->setText(settings.value("saturationLineEdit").toString());
cdw->ui->separateTargetLineEdit->setText(settings.value("separateTargetLineEdit").toString());
// MAIN WINDOW
ui->applyAbsphotindirectCheckBox->setChecked(settings.value("applyAbsphotindirectCheckBox").toBool());
ui->applyAstromphotomCheckBox->setChecked(settings.value("applyAstromphotomCheckBox").toBool());
ui->applyBackgroundCheckBox->setChecked(settings.value("applyBackgroundCheckBox").toBool());
ui->applyBinnedpreviewCheckBox->setChecked(settings.value("applyBinnedpreviewCheckBox").toBool());
ui->applyChopnodCheckBox->setChecked(settings.value("applyChopnodCheckBox").toBool());
ui->applyCoadditionCheckBox->setChecked(settings.value("applyCoadditionCheckBox").toBool());
ui->applyCollapseCheckBox->setChecked(settings.value("applyCollapseCheckBox").toBool());
ui->applyCreatesourcecatCheckBox->setChecked(settings.value("applyCreatesourcecatCheckBox").toBool());
ui->applyGlobalweightCheckBox->setChecked(settings.value("applyGlobalweightCheckBox").toBool());
ui->applyHDUreformatCheckBox->setChecked(settings.value("applyHDUreformatCheckBox").toBool());
ui->applyIndividualweightCheckBox->setChecked(settings.value("applyIndividualweightCheckBox").toBool());
ui->applyProcessbiasCheckBox->setChecked(settings.value("applyProcessbiasCheckBox").toBool());
ui->applyProcessdarkCheckBox->setChecked(settings.value("applyProcessdarkCheckBox").toBool());
ui->applyProcessflatCheckBox->setChecked(settings.value("applyProcessflatCheckBox").toBool());
ui->applyProcessflatoffCheckBox->setChecked(settings.value("applyProcessflatoffCheckBox").toBool());
ui->applyProcessscienceCheckBox->setChecked(settings.value("applyProcessscienceCheckBox").toBool());
ui->applySeparateCheckBox->setChecked(settings.value("applySeparateCheckBox").toBool());
ui->applySkysubCheckBox->setChecked(settings.value("applySkysubCheckBox").toBool());
ui->applyStarflatCheckBox->setChecked(settings.value("applyStarflatCheckBox").toBool());
ui->processingTabWidget->setCurrentIndex(settings.value("processingTabWidget").toInt());
fill_setupInstrumentComboBox(); // Must be populated first so that the matching entry can be selected
ui->setupInstrumentComboBox->setCurrentText(settings.value("setupInstrumentComboBox").toString());
ui->setupBiasLineEdit->setText(settings.value("setupBiasLineEdit").toString());
ui->setupDarkLineEdit->setText(settings.value("setupDarkLineEdit").toString());
ui->setupFlatLineEdit->setText(settings.value("setupFlatLineEdit").toString());
ui->setupFlatoffLineEdit->setText(settings.value("setupFlatoffLineEdit").toString());
ui->setupMainLineEdit->setText(settings.value("setupMainLineEdit").toString());
ui->setupProjectLineEdit->setText(settings.value("setupProjectLineEdit").toString());
ui->setupScienceLineEdit->setText(settings.value("setupScienceLineEdit").toString());
ui->setupSkyLineEdit->setText(settings.value("setupSkyLineEdit").toString());
ui->setupStandardLineEdit->setText(settings.value("setupStandardLineEdit").toString());
// Now that the instrument is known, we can update instrument-dependent comboboxes etc
cdw->setupInstrumentComboBox_clicked();
cdw->ui->skyAreaComboBox->setCurrentIndex(settings.value("skyAreaComboBox").toInt());
settings.endGroup();
preventLoop_WriteSettings = false;
readingSettings = false;
// Housekeeping for correct display
cdw->updateARCdisplay();
updatePreferences();
updateInstrumentComboBoxBackgroundColor();
return settings.status();
}
| 47,533
|
C++
|
.cc
| 595
| 74.988235
| 111
| 0.765679
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,404
|
taskinfrastructure.cc
|
schirmermischa_THELI/src/taskinfrastructure.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_confdockwidget.h"
#include "functions.h"
#include "status.h"
#include "threading/mainguiworker.h"
#include "processingInternal/data.h"
#include "processingExternal/errordialog.h"
#include "datadir.h"
#include "tools/cfitsioerrorcodes.h"
#include <QDebug>
#include <QMessageBox>
#include <QDir>
#include <QTest>
#include <QMetaObject>
#include <QGenericReturnArgument>
QStringList MainWindow::matchCalibToScience(const QStringList scienceList, const QStringList calibList)
{
// This utility modifies the calib list so that it matches the science list in length.
// Example:
// science list contains S1, S2, S3
// calib list contains F. Then, at the end it will contain F, F, F
// If calib list is empty, then at the end it will contain "", "", ""
int nscience = scienceList.length();
int ncalib = calibList.length();
// Initialize the newCalibList with blanks and the same dimension as the scienceList.
QStringList newCalibList;
for (int i=0; i<nscience; ++i) {
newCalibList << "";
}
// if the calibList was empty
if (ncalib == 0) {
// empty on purpose;
}
else if (ncalib == 1) {
for (int i=0; i<nscience; ++i) {
newCalibList.operator[](i) = calibList.at(0);
}
}
else if (ncalib == nscience && nscience > 1) {
for (int i=0; i<nscience; ++i) {
newCalibList.operator[](i) = calibList.at(i);
}
}
else {
// Invalid config
// Error handled in the caller
return QStringList();
}
return newCalibList;
}
void MainWindow::handleDataDirs(QStringList &goodDirList,
QLineEdit *scienceLineEdit, QLineEdit *calib1LineEdit,
QLineEdit *calib2LineEdit, QString flagString, bool &success)
{
// This function assigns the correct calibration directories (if any) to the science directories.
// Note that "science" could be a flat, and "calib" could be a bias.
if (scienceLineEdit->text().isEmpty()) return;
// Convert data dir(s) to stringlists
QStringList scienceList = datadir2StringList(scienceLineEdit);
QStringList calib1List = datadir2StringList(calib1LineEdit);
QStringList calib2List = datadir2StringList(calib2LineEdit);
QStringList newCalib1List;
QStringList newCalib2List;
// Match the calib list to the science list (increase length if necessary)
// If a LineEdit is not needed, an empty constructor is used in the caller, resulting in an empty stringList;
newCalib1List = matchCalibToScience(scienceList, calib1List);
newCalib2List = matchCalibToScience(scienceList, calib2List);
// Last consistency check:
if (scienceList.length() != newCalib1List.length()
|| scienceList.length() != newCalib2List.length()) {
success = false;
return;
}
QString main = ui->setupMainLineEdit->text();
// QString scriptArg;
QString scriptArg_blank;
QDir scienceDir;
// Loop over directories, prepend maindir if necessary;
// The idea is to produce strings "main science calib" separated by blanks, or "main science flagString".
// We check elsewhere in areAllPathsValid() whether directories are good
for (int i=0; i<scienceList.size(); ++i) {
// scriptArg = main + "/" + scienceList.at(i);
scriptArg_blank = main + " " + scienceList.at(i) + " "
+ newCalib1List.at(i) + " "
+ newCalib2List.at(i) + " " +flagString;
// Clean the strings
// scriptArg = scriptArg.simplified();
scriptArg_blank = scriptArg_blank.simplified();
if (QDir(scienceDir).exists()) goodDirList << scriptArg_blank;
}
}
// Turn the entry/entries of a subdirectory in the data tree to a cleaned stringlist
// This function creates the list of commands for all checked checkboxes.
// It also runs a number of consistency checks.
// The final list of commands is processed if on_startPushButton_clicked().
void MainWindow::updateProcessList(QStringList &commandList, QString taskBasename, QString arg1)
{
// This will show in the overview window which task is currently running
QString message = taskCommentMap.value(taskBasename);
QStringList list = arg1.split(" ");
QString workingDir = "";
if (list.length() >= 2) workingDir = list.at(1);
else workingDir = list.at(0);
commandList.append("MESSAGE::"+message+" "+workingDir);
// The actual task
commandList.append("RUN::"+taskBasename+":: "+arg1);
}
// Like above, but used for processscience, which may operate on science, sky or std
// Also used for create source cat
void MainWindow::updateProcessList(QStringList &commandList, QString taskBasename, QString arg1, QString arg2)
{
// This will show in the overview window which task is currently running
QString message = taskCommentMap.value(taskBasename);
QStringList list = arg1.split(" ");
QString workingDir = "";
if (list.length() >= 2) workingDir = list.at(1);
else workingDir = list.at(0);
commandList.append("MESSAGE::"+message+" "+workingDir);
// The actual task
commandList.append("RUN::"+taskBasename+":: "+arg1+" "+arg2);
}
// This function collects the internal process calls
// NOTE: THIS IS CALLED FOR EACH TASK SEQUENTIALLY
QStringList MainWindow::createCommandlistBlock(QString taskBasename, QStringList goodDirList, bool &stop, const QString mode)
{
// Does the task exist in the checkbox map?
QString taskName;
if (checkboxMap.values().contains(taskBasename)) taskName = checkboxMap.key(taskBasename)->text();
else taskName = "";
if (goodDirList.isEmpty()) {
message(ui->plainTextEdit, "STOP: No data were provided for '"+taskName+"' , or the data tree is inconsistent.");
stop = true;
return QStringList();
}
DataDir datadir;
datadir.numChips = instData.numChips;
QStringList commandList;
// Process science can act on DT_SCIENCE, SKY, STD and thus needs to distinguish between them
QString scienceMode = "";
QString last = goodDirList.last();
if (last == "theli_DT_SCIENCE" || last == "theli_DT_SKY" || last == "theli_DT_STANDARDD") {
scienceMode = last;
goodDirList.removeLast(); // do not interpret the last string as a data directory; in this case it's a flag
}
// Loop over all directories found for the current task
for (auto &it : goodDirList) {
if (taskBasename != "ResolveTargetSidereal") datadir.setPaths(it); // triggers qdebug() message if just resolving a target
// Now call a consistency check by the function's string representation.
// The function name is "check_task<taskBasename>()"
// and it simply updates the 'stop' and 'skip' flags
bool skip = false;
bool test = QMetaObject::invokeMethod(this, ("check_task"+taskBasename).toStdString().c_str(),
Qt::DirectConnection,
Q_ARG(DataDir*, &datadir),
Q_ARG(bool &, stop),
Q_ARG(bool &, skip),
Q_ARG(const QString, mode));
if (!test) {
qDebug() << __func__ << "Could not evaluate QMetaObject.";
stop = true;
return QStringList();
}
// Omit the current task if either skip or stop are true;
// Several commands can be skipped, but we stop everything (at a later point below) at the first stop.
if (stop) continue;
if (skip) continue;
QStringList tmpdirlist = it.split(" ");
QString main = tmpdirlist.at(0);
// Few (1?) exceptions were 'science' is not needed
QString science = "";
if (tmpdirlist.length() >= 2) science = tmpdirlist.at(1);
if (taskBasename == "HDUreformat"
|| taskBasename == "Processbias"
|| taskBasename == "Processdark"
|| taskBasename == "Processflatoff"
|| taskBasename == "Processflat"
|| taskBasename == "Binnedpreview"
|| taskBasename == "Background"
|| taskBasename == "Collapse"
|| taskBasename == "Globalweight"
|| taskBasename == "Individualweight"
|| taskBasename == "Skysub"
|| taskBasename == "ResolveTargetSidereal"
|| taskBasename == "GetCatalogFromIMAGE"
|| taskBasename == "RestoreHeader"
|| taskBasename == "Separate") {
updateProcessList(commandList, taskBasename, it);
}
/*
if (taskBasename == "Background" && mode == "simulate" && ui->applyBackgroundCheckBox->isChecked()) {
QSettings settings("THELI", "PREFERENCES");
int maxCPU = settings.value("prefCPUSpinBox").toInt();
if (maxCPU > 1) {
QMessageBox::warning(this, tr("Parallelization unstable"),
tr("You are running the background modelling with more than 1 CPU. ") +
tr("Parallel background modeling COULD be unstable and might crash THELI, in which case you have to manually delete all *PAB.fits files from the data directory.\n") +
tr("Use a single CPU if you have problems. Once background modeling is done, you can revert to full parallelization."),
QMessageBox::Ok);
}
}
*/
if (taskBasename == "Processscience") {
updateProcessList(commandList, taskBasename, it, scienceMode);
}
if (taskBasename == "Createsourcecat") {
QString coordsMode = manualCoordsUpdate(science, mode);
updateProcessList(commandList, taskBasename, it, coordsMode);
}
if (taskBasename == "GetCatalogFromWEB") {
if (!checkCatalogUsability(mode)) {
stop = true;
return QStringList();
}
updateProcessList(commandList, "GetCatalogFromWEB", it);
}
if (taskBasename == "Astromphotom") {
// do we need to update the reference catalog?
if (!isRefcatRecent(main+"/"+science)) {
if (cdw->ui->ASTmethodComboBox->currentText() == "Scamp"
|| cdw->ui->ASTmethodComboBox->currentText() == "astrometry.net") {
if (cdw->ui->ARCwebRadioButton->isChecked()) {
if (!checkCatalogUsability(mode)) {
stop = true;
return QStringList();
}
updateProcessList(commandList, "GetCatalogFromWEB", it);
}
else {
updateProcessList(commandList, "GetCatalogFromIMAGE", it);
}
}
}
if (cdw->ui->ASTmethodComboBox->currentText() == "Scamp") {
if (!cdw->checkRightScampMode(mode)) {
message(ui->plainTextEdit, "Aborted, please choose a different MOSAIC_TYPE for scamp.", "stop");
stop = true;
return QStringList();
}
}
// TODO
// Put other methods here: a.net, x-corr, header-astrom
updateProcessList(commandList, taskBasename, it);
}
if (taskBasename == "Coaddition") {
// Check how many filters we have in the coadd dir
QString filterChoice;
QStringList filterlist = displayCoaddFilterChoice(main+"/"+science+"/", filterChoice, mode);
// Suggest the user to add reference coordinates for a multi-color data set
if (filterlist.length() > 1) {
QString coordsMode = sameRefCoords(mode);
if (coordsMode == "Cancel") {
stop = true;
return QStringList();
}
}
QString flag = "";
// Loop over all potential filters
for (auto &filter : filterlist) {
QString filterArg = "";
if (filterChoice == "Separately") { // for loop will run over each filter
filterArg = filter;
}
else if (filterChoice == "all") { // for loop will run exactly once, because we break at the end
filterArg = "all";
}
else if (filterChoice == filter) { // for loop will run exactly once, because we break at the end
filterArg = filter;
flag = "individual";
}
else if (filterChoice == "Abort") break;
if (filterArg.isEmpty()) continue;
updateProcessList(commandList, taskBasename, it+" "+filterArg);
if (filterArg == "all" || flag == "individual") break;
}
if (filterlist.isEmpty()) updateProcessList(commandList, taskBasename, it+" "+"all");
}
// TODO
/*
if (taskBasename == "Chopnod") {
updateCommandList(commandList, taskBasename, science, it, count, "process_science_chopnod_para.sh");
}
if (taskBasename == "Absphotindirect") {
QString extension = tmpdirlist.at(2);
QString standard = ui->setupStandardLineEdit->text();
updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension, count, "create_astromcats_phot_para.sh");
if (cdw->ui->APIWCSCheckBox->isChecked()) {
updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension, count, "create_scampcats.sh");
updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension+" photom", count, "create_scamp.sh");
}
updateCommandList(commandList, taskBasename, standard, main+" "+standard+" "+extension, count, "create_stdphotom_prepare_para.sh");
updateCommandList(commandList, taskBasename, science, main+" "+science+" "+standard+" "+extension, count, "create_abs_photo_info.sh");
commandList.append("UPDATESOLUTIONS::"+main+"/"+standard);
// must trigger cdw->updateAPIsolutions()
}
*/
}
commandList.append("UPDATESTATUS::"+taskBasename);
return commandList;
}
void MainWindow::on_yieldToolButton_clicked()
{
// There is only sth to abort if the start button is disabled
if (!ui->startPushButton->isEnabled()) {
controller->userYield = true;
emit messageAvailable("Yield request received ...", "stop");
message(ui->plainTextEdit, "Will stop after current task has finished, please wait ...", "stop");
mainGUIWorker->yield = true;
if (!ui->startPushButton->isEnabled()) {
ui->startPushButton->setEnabled(true);
ui->startPushButton->setText("Start");
}
}
}
void MainWindow::on_stopToolButton_clicked()
{
// There is only sth to abort if the start button is disabled
if (!ui->startPushButton->isEnabled()) {
controller->userStop = true;
emit messageAvailable("Stop request received, finishing current calculations ...", "stop");
message(ui->plainTextEdit, "Stopping current task, please wait ...", "stop");
// Make sure we are not entering next task in the queue
mainGUIWorker->yield = true;
QTest::qWait(50);
// Pause thread
mainGUIWorker->pause();
if (controller->currentData != nullptr
&& controller->taskBasename != "HDUreformat") {
// reformatting falls through because of userAbort flag
controller->currentData->setSuccess(false);
}
mainGUIWorker->resume();
if (controller->taskBasename == "Astromphotom") {
emit messageAvailable("Sending Scamp a kill signal ...", "stop");
if (controller->scampWorker) controller->scampWorker->abort();
if (controller->workerThread) controller->workerThread->quit();
if (controller->workerThread) controller->workerThread->wait();
emit messageAvailable("Successfully detached from Scamp", "stop");
}
if (controller->taskBasename == "Coaddition") {
controller->successProcessing = false; // Must set to false first, to make sure that any subsequent coadd commands exit immediately
emit messageAvailable("Sending Swarp a kill signal ...", "stop");
if (controller->currentSwarpProcess != "swarpPreparation") {
if (controller->swarpWorker) controller->swarpWorker->abort();
if (controller->workerThreadPrepare) controller->workerThreadPrepare->quit();
if (controller->workerThreadPrepare) controller->workerThreadPrepare->wait();
controller->successProcessing = false;
emit messageAvailable("Successfully detached from Swarp", "stop");
}
else if (controller->currentSwarpProcess != "swarpCoaddition") {
if (controller->swarpWorker) controller->swarpWorker->abort();
if (controller->workerThreadCoadd) controller->workerThreadCoadd->quit();
if (controller->workerThreadCoadd) controller->workerThreadCoadd->wait();
controller->successProcessing = false;
emit messageAvailable("Successfully detached from Swarp", "stop");
}
else {
for (int i=0; i<controller->swarpWorkers.length(); ++i) {
emit controller->swarpWorkers[i]->finishedResampling(controller->swarpWorkers[i]->threadID);
if (controller->swarpWorkers[i]) controller->swarpWorkers[i]->abort();
if (controller->workerThreads[i]) controller->workerThreads[i]->quit();
if (controller->workerThreads[i]) controller->workerThreads[i]->wait();
emit messageAvailable("Successfully detached from Swarp", "stop");
}
}
}
workerThread->quit();
workerThread->wait();
if (controller->taskBasename == "Processbias"
|| controller->taskBasename == "Processdark"
|| controller->taskBasename == "Processflatoff"
|| controller->taskBasename == "Processflat"
|| controller->taskBasename == "Binnedpreview"
|| controller->taskBasename == "Globalweight"
|| controller->taskBasename == "Individualweight"
|| controller->taskBasename == "Createsourcecat"
|| controller->taskBasename == "Astromphotom"
|| controller->taskBasename == "Coaddition") {
emit messageAvailable("Hard abort: " + controller->taskBasename, "stop");
emit messageAvailable("Manual clean-up is not required, simply re-run the task for a clean state.", "note");
}
else {
emit messageAvailable("<br>*****************************************************************", "stop");
emit messageAvailable("Hard abort: " + controller->taskBasename, "stop");
emit messageAvailable("Files in " + controller->currentDirName + " likely need manual clean-up.", "stop");
emit messageAvailable("*****************************************************************", "stop");
}
if (!ui->startPushButton->isEnabled()) {
ui->startPushButton->setEnabled(true);
ui->startPushButton->setText("Start");
}
}
}
void MainWindow::on_actionKill_triggered()
{
// There is only sth to abort if the start button is disabled
if (!ui->startPushButton->isEnabled()) {
controller->userKill = true;
emit messageAvailable("Abort request received ...", "stop");
message(ui->plainTextEdit, "Kill signal sent, please wait ...", "stop");
if (controller->taskBasename == "Astromphotom") {
emit messageAvailable("Sending Scamp a kill signal ...", "stop");
if (controller->scampWorker) controller->scampWorker->abort();
if (controller->workerThread) controller->workerThread->quit();
if (controller->workerThread) controller->workerThread->wait();
emit messageAvailable("Successfully detached from Scamp", "stop");
}
if (controller->taskBasename == "Coaddition") {
emit messageAvailable("Sending Swarp a kill signal ...", "stop");
if (controller->swarpWorker) controller->swarpWorker->abort();
if (controller->workerThread) controller->workerThread->quit();
if (controller->workerThread) controller->workerThread->wait();
emit messageAvailable("Successfully detached from Swarp", "stop");
}
workerThread->terminate();
workerThread->wait();
message(ui->plainTextEdit, "Aborted.", "stop");
if (!ui->startPushButton->isEnabled()) {
ui->startPushButton->setEnabled(true);
ui->startPushButton->setText("Start");
}
if (controller->taskBasename == "Processbias"
|| controller->taskBasename == "Processdark"
|| controller->taskBasename == "Processflatoff"
|| controller->taskBasename == "Processflat"
|| controller->taskBasename == "Binnedpreview"
|| controller->taskBasename == "Globalweight"
|| controller->taskBasename == "Individualweight"
|| controller->taskBasename == "Createsourcecat"
|| controller->taskBasename == "Astromphotom"
|| controller->taskBasename == "Coaddition") {
emit messageAvailable("Task killed: " + controller->taskBasename, "warning");
emit messageAvailable("Manual clean-up is not required, simply re-run the task for a clean state.", "note");
}
emit messageAvailable("Task killed: " + controller->taskBasename, "stop");
emit messageAvailable("<br>*****************************************************************", "stop");
emit messageAvailable("Files in " + controller->currentDirName + " need manual clean-up.", "stop");
emit messageAvailable("Data model in RAM in undefined state, recommend THELI restart.", "stop");
emit messageAvailable("*****************************************************************", "stop");
}
}
void MainWindow::startPushButton_clicked_dummy(QString string)
{
on_startPushButton_clicked();
}
// This top level function has two modes: a "simulator" mode, executed when task checkboxes are checked or
// unchecked, or data dirs edited successfully. It goes through all the tests and prints notifications in plainTextEdit,
// but it does not execute anything. Only when the actual start button is clicked, the function goes through with the execution
// but does not print any uncritical information anymore
void MainWindow::on_startPushButton_clicked()
{
if (!doingInitialLaunch) {
controller->progress = 0.;
}
QSettings settings("THELI", "PREFERENCES");
processSkyImages = settings.value("prefProcessSkyCheckBox",false).toBool();
// Do not do anything while tasks are running already
if (!ui->startPushButton->isEnabled()) return;
// Do not simulate during startup (excessive (?) parseing of the directory tree)
// if (doingInitialLaunch || readingSettings) return;
// The current execution mode
QString mode = OSPBC_determineExecutionMode(sender());
// Reset error message box flags
resetProcessingErrorFlags();
// Check whether the directory tree is consistent
if (mode != "simulate") {
if (!OSPBC_multipleDirConsistencyCheck()) return;
}
// Check if all data Dirs are valid. If there is a single one that isn't, abort!
// Exception: mode = ResolveTargetSidereal does not require any data directories
if (! areAllPathsValid()
&& (mode != "ResolveTargetSidereal")
&& !doingInitialLaunch) {
if (QDir(ui->setupMainLineEdit->text()) != QDir::home()) {
message(ui->plainTextEdit, "STOP: Nonexistent entries were found in the data directory tree. "
"They must be fixed or removed.");
}
else {
message(ui->plainTextEdit, "STOP: For safety reasons, your home directory is not permitted as the main directory.");
}
ui->processingTabWidget->setCurrentIndex(0);
return;
}
// Save the setup in case the GUI crashes
writeGUISettings();
// The following list contains all script commands that would be executed
totalCommandList.clear();
bool stop = false;
QString taskBasename;
// Process commands from other buttons than the "start" button
if (mode == "GetCatalogFromWEB"
|| mode == "GetCatalogFromIMAGE"
|| mode == "ResolveTargetSidereal"
|| mode == "RestoreHeader") {
taskBasename = mode;
if (!OSPBC_addCommandBlock(taskBasename, mode, stop)) return; // updates totalCommandList
}
else {
// process commands from the start button (must loop over task checkboxes)
for (auto &it : status.listCheckBox) {
// Include only tasks visible on the currently visible stacked widget page
// if (it->isChecked() && isTaskCurrentlyVisible(it)) {
if (it->isChecked()) {
taskBasename = it->objectName().remove("apply").remove("CheckBox");
if (!OSPBC_addCommandBlock(taskBasename, mode, stop)) return; // updates totalCommandList
}
}
}
totalCommandList.append("END::"+taskBasename);
if (controller->isMainDirHome()) {
message(ui->plainTextEdit, "STOP: For safety reasons, your home directory is not permitted as the main directory.");
stop = true;
return;
}
// If we are not in simulator mode then do the real thing
if (mode != "simulate") {
bool anythingChecked = false;
for (auto &it : status.listCheckBox) {
if (it->isChecked()) {
anythingChecked = true;
}
}
// Leave if no normal task is checked (apart from special buttons)
if (mode != "GetCatalogFromWEB"
&& mode != "GetCatalogFromIMAGE"
&& mode != "ResolveTargetSidereal"
&& mode != "RestoreHeader"
&& !anythingChecked) {
return;
}
// Reset the controller's processing status
controller->successProcessing = true;
controller->userYield = false;
controller->userStop = false;
controller->userKill = false;
controller->abortProcess = false;
controller->swapWarningShown = false;
ui->startPushButton->setText("Running ...");
ui->startPushButton->setDisabled(true);
for (auto &it : status.listDataDirs) {
it->setDisabled(true);
}
cdw->ui->confStackedWidget->setDisabled(true);
emit runningStatusChanged(true);
toggleButtonsWhileRunning();
workerThread = new QThread();
mainGUIWorker = new MainGUIWorker(controller, totalCommandList);
//workerInit = true;
//workerThreadInit = true;
mainGUIWorker->moveToThread(workerThread);
connect(workerThread, &QThread::started, mainGUIWorker, &MainGUIWorker::runTask);
connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater, Qt::DirectConnection);
connect(mainGUIWorker, &MainGUIWorker::finished, this, &MainWindow::taskFinished);
connect(mainGUIWorker, &MainGUIWorker::updateStatus, &status, &Status::updateStatusReceived);
connect(mainGUIWorker, &MainGUIWorker::messageAvailable, this, &MainWindow::displayMessage);
connect(mainGUIWorker, &MainGUIWorker::finished, workerThread, &QThread::quit, Qt::DirectConnection);
connect(mainGUIWorker, &MainGUIWorker::finished, mainGUIWorker, &QObject::deleteLater, Qt::DirectConnection);
// if an error is encountered during scanning, we must end the worker thread
workerThread->start();
// show the process monitor, for normal processing tasks, only
if (taskBasename != "ResolveTargetSidereal") {
if (switchProcessMonitorPreference) monitor->raise();
ui->processProgressBar->setValue(0);
}
// Speed up the CPU and RAM timers
cpuTimer->setInterval(500);
ramTimer->setInterval(500);
driveTimer->setInterval(500);
}
else {
bool anythingChecked = false;
int numTasksChecked = 0;
for (auto &it : status.listCheckBox) {
if (it->isChecked()) {
++numTasksChecked;
anythingChecked = true;
}
}
if (!anythingChecked) {
message(ui->plainTextEdit, "Currently no activated tasks.", "info");
}
else {
if (! stop) {
if (totalCommandList.length() == 1) message(ui->plainTextEdit, "Nothing to be done. Selected tasks already executed.", "info");
else {
if (numTasksChecked == 1) message(ui->plainTextEdit, QString::number(numTasksChecked) + " task activated. Ready !", "info");
else message(ui->plainTextEdit, QString::number(numTasksChecked) + " tasks activated. Ready !", "info");
}
}
}
}
}
void MainWindow::displayMessage(QString messagestring, QString type)
{
message(ui->plainTextEdit, messagestring, type);
}
bool MainWindow::OSPBC_addCommandBlock(const QString taskBasename, const QString mode, bool &stop)
{
QStringList commandblock;
// call the function by its string representation (needs a const char *)
bool test = QMetaObject::invokeMethod(this, ("task"+taskBasename).toStdString().c_str(),
Qt::DirectConnection,
Q_RETURN_ARG(QStringList, commandblock),
Q_ARG(bool &, stop),
Q_ARG(const QString, mode));
if (!test) {
qDebug() << __func__ << "Could not evaluate QMetaObject.";
return false;
}
// Check if the task identified a condition (which it will print to ui->plainTextEdit)
// that should prevent execution (e.g. insufficient number of exposures, etc).
if (stop && mode != "simulate") {
return false;
}
// If an inconsistency in the data tree was detected.
// Instead of checking and reporting this in handleDataDirs(), we just do it once to avoid multiple instances of the readme window shown
if (commandblock.isEmpty() && mode != "simulate") {
QMessageBox::critical(this, tr("THELI: Invalid data dir configuration"),
tr("An incompatible number of directories was detected in the data tree.\n"
"Allowed setups will be displayed next."),
QMessageBox::Ok);
on_setupReadmePushButton_clicked();
return false;
}
// Add the actual processing commands (script calls) to a string list
totalCommandList.append(commandblock);
return true;
}
// UNUSED
// Check if a task is on the currently displayed stack widget page
bool MainWindow::OSPBC_isTaskCurrentlyVisible(QCheckBox *cb)
{
if (ui->processingTabWidget->currentIndex() == 0) return false;
else if (ui->processingTabWidget->currentIndex() == 1) {
if (cb == ui->applyHDUreformatCheckBox
|| cb == ui->applyProcessbiasCheckBox
|| cb == ui->applyProcessdarkCheckBox
|| cb == ui->applyProcessflatoffCheckBox
|| cb == ui->applyProcessflatCheckBox
|| cb == ui->applyProcessscienceCheckBox
|| cb == ui->applyChopnodCheckBox
|| cb == ui->applyBackgroundCheckBox
|| cb == ui->applyCollapseCheckBox
|| cb == ui->applyBinnedpreviewCheckBox) return true;
else return false;
}
else if (ui->processingTabWidget->currentIndex() == 2) {
if (cb == ui->applyGlobalweightCheckBox
|| cb == ui->applyIndividualweightCheckBox
|| cb == ui->applySeparateCheckBox
|| cb == ui->applyAbsphotindirectCheckBox
|| cb == ui->applyCreatesourcecatCheckBox
|| cb == ui->applyAstromphotomCheckBox
|| cb == ui->applyStarflatCheckBox
|| cb == ui->applySkysubCheckBox
|| cb == ui->applyCoadditionCheckBox) return true;
else return false;
}
else {
// never evaluated
return false;
}
}
// Which mode are we in
QString MainWindow::OSPBC_determineExecutionMode(QObject *sender)
{
QString mode;
if (sender == ui->startPushButton) mode = "execute";
else if (sender == cdw->ui->ARCgetcatalogPushButton) {
if (cdw->ui->ARCwebRadioButton->isChecked()) mode = "GetCatalogFromWEB";
if (cdw->ui->ARCimageRadioButton->isChecked()) mode = "GetCatalogFromIMAGE";
}
else if (sender == cdw->ui->restoreHeaderPushButton) mode = "RestoreHeader";
else if (sender == cdw->ui->ARCtargetresolverToolButton) mode = "ResolveTargetSidereal";
else {
mode = "simulate";
ui->plainTextEdit->clear();
}
return mode;
}
bool MainWindow::OSPBC_multipleDirConsistencyCheck()
{
// CONSISTENCY CHECK concerning multiple directories
// Loop over initial checkboxes (0-8, 6&7 don't matter)
// Hardcoded, needs to be adjusted when more tasks are introduced before applyBackgroundCheckBox
int i = 0;
bool test = true;
for (auto &it : status.listCheckBox) {
if (it->isChecked()) {
QString taskBasename = it->objectName().remove("apply").remove("CheckBox");
test = test && checkMultipledirConsistency(taskBasename);
}
++i;
// Don't have to evaluate more checkboxes.
if (i >= 9) break;
}
// If this evaluates to false, then at least one part of the data directory tree is inconsistent.
// In this case warning messages will have been printed to plainTextEdit already by
// checkMultipledirConsistency()
// We just need to show the dialog with the explanation.
if (!test) {
on_setupReadmePushButton_clicked();
return false;
}
else return true;
}
//UNUSED
void MainWindow::appendOK()
{
ui->plainTextEdit->moveCursor (QTextCursor::End);
ui->plainTextEdit->insertPlainText("OK");
ui->plainTextEdit->moveCursor (QTextCursor::End);
}
void MainWindow::taskFinished()
{
cdw->ui->confStackedWidget->setEnabled(true);
if (controller->userYield) {
emit messageAvailable("Task '"+controller->taskBasename + "' finished.\nSoft abort. ", "stop");
emit messageAvailable(controller->currentDirName + " in clean state, no manual clean-up required.", "note");
}
ui->startPushButton->setEnabled(true);
ui->startPushButton->setText("Start");
for (auto &it : status.listDataDirs) {
it->setEnabled(true);
}
monitor->displayMessage("<br> *** DONE ***", "note");
emit runningStatusChanged(false);
// enable various buttons again
toggleButtonsWhileRunning();
// Reset all abort flags to false in the current Data class if the task was aborted.
// Not when we still do splitting, because Data classes have not been instantiated
if (controller->currentData == nullptr) return;
if (controller->userYield
|| controller->userStop
|| controller->userKill) {
controller->currentData->resetUserAbort();
}
// Allow reprocessing after hard aborts
if (controller->userStop
|| controller->userKill) {
controller->currentData->resetSuccessProcessing();
}
// slow down CPU and RAM timers
cpuTimer->setInterval(2000);
ramTimer->setInterval(2000);
driveTimer->setInterval(2000);
// not needed, handled by 'deleteLater'
// delete workerThread;
}
bool MainWindow::isRefcatRecent(QString dirname)
{
QFile file(dirname+"/cat/refcat/.refcatID");
QFile catalog(dirname+"/cat/refcat/theli_mystd.scamp");
if (!file.exists()) return false;
if (!catalog.exists()) return false;
QString id;
QString currentId;
if ( !file.open(QIODevice::ReadOnly)) {
// qDebug() << "QDEBUG: isRefcatRecent(): "+dirname+".refcatID could not be opened.";
return false;
}
else {
// extract the ID string
QTextStream stream( &file );
id = stream.readLine();
id = id.simplified();
file.close();
if (cdw->ui->ARCwebRadioButton->isChecked()) {
QString catalog = cdw->ui->ARCcatalogComboBox->currentText();
QString ra = cdw->ui->ARCraLineEdit->text();
QString dec = cdw->ui->ARCdecLineEdit->text();
if (ra.contains(":")) ra = hmsToDecimal(ra);
if (dec.contains(":")) dec = dmsToDecimal(dec);
QString minmag = cdw->ui->ARCminmagLineEdit->text();
if (minmag.isEmpty()) minmag = cdw->defaultMap["ARCminmagLineEdit"];
QString radius = cdw->ui->ARCradiusLineEdit->text();
currentId = catalog+"_"+ra+"_"+dec+"_"+minmag+"_"+radius;
if (catalog.contains("GAIA")) currentId.append("_"+cdw->ui->ARCmaxpmLineEdit->text());
}
else {
QString image = cdw->ui->ARCselectimageLineEdit->text();
QString dt = cdw->ui->ARCDTLineEdit->text();
QString dmin = cdw->ui->ARCDMINLineEdit->text();
// QString deblend = cdw->ui->ARCmincontLineEdit->text();
currentId = image+"_"+dt+"_"+dmin;
}
// Uncomment this to understand why refcat is downloaded twice
// qDebug() << id << currentId;
if (id != currentId) return false;
else return true;
}
}
void MainWindow::processMessage(QString text, QString type)
{
message(ui->plainTextEdit, text, type);
}
QString MainWindow::manualCoordsUpdate(QString science, QString mode)
{
if (mode != "execute") return "empty";
if (cdw->ui->ARCraLineEdit->text() != "" && cdw->ui->ARCdecLineEdit->text() != "") {
QMessageBox msgBox;
msgBox.setText(science+": Overwrite CRVAL1/2 and CDi_j keywords?");
msgBox.setInformativeText("Manual coordinates were provided. "
"Do you want to overwrite the CRVAL1/2 "
"keywords with the values for RA and DEC entered above?\n"
"Optionally, you can also force the CD matrix to have North up and East left.\n\n");
QAbstractButton *pButtonCrval = msgBox.addButton(tr("Update Ra/DEC"), QMessageBox::YesRole);
QAbstractButton *pButtonCrvalCD = msgBox.addButton(tr("Update RA/DEC, reset CD matrix"), QMessageBox::YesRole);
QAbstractButton *pButtonUnchanged = msgBox.addButton(tr("Leave header unchanged"), QMessageBox::YesRole);
QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
msgBox.exec();
if (msgBox.clickedButton() == pButtonCrval) return "crval";
else if (msgBox.clickedButton() == pButtonCrvalCD) return "crval+cd";
else if (msgBox.clickedButton() == pButtonUnchanged) return "empty";
else if (msgBox.clickedButton() == pButtonCancel) return "Cancel";
}
else return "empty";
return "empty";
}
bool MainWindow::checkCatalogUsability(QString mode)
{
// Confirm the catalog choice if possible not very useful
if (cdw->ui->ARCwebRadioButton->isChecked()) {
if (instData.pixscale > 2.0 && instData.pixscale < 10.0 && mode != "simulate") {
QString refcatName = cdw->ui->ARCcatalogComboBox->currentText();
if (refcatName.contains("GAIA") ||
refcatName.contains("PANSTARRS") ||
refcatName.contains("SKYMAPPER") ||
refcatName.contains("VHS") ||
refcatName.contains("SDSS") ||
refcatName.contains("2MASS")) {
QMessageBox msgBox;
msgBox.setModal(true);
msgBox.setInformativeText(tr("Very large online query detected.\n\n") +
tr("Downloading data from ") + refcatName + tr(" for your data could take very long. ") +
tr("Since your field of view is large and the resolution less than 2 arcsec / pixel, UCAC5 is a better alternative.\n"));
QAbstractButton *pButtonUCAC = msgBox.addButton(tr("Use UCAC5"), QMessageBox::YesRole);
QAbstractButton *pButtonOrig = msgBox.addButton(tr("Use ")+refcatName, QMessageBox::YesRole);
QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
msgBox.exec();
if (msgBox.clickedButton() == pButtonUCAC) cdw->ui->ARCcatalogComboBox->setCurrentText("UCAC5");
else if (msgBox.clickedButton() == pButtonCancel) return false;
else if (msgBox.clickedButton() == pButtonOrig) return true;
}
}
else if (instData.pixscale > 10.0 && mode != "simulate") {
QString refcatName = cdw->ui->ARCcatalogComboBox->currentText();
if (!refcatName.contains("ASCC") && !refcatName.contains("TYC")) {
QMessageBox msgBox;
msgBox.setModal(true);
msgBox.setInformativeText(tr("Very large online query detected.\n\n") +
tr("Downloading data from ") + refcatName + tr(" for your data will take very long. ") +
tr("Since your field of view is large and the resolution less than 2\" / pixel, ASCC is a better alternative.\n"));
QAbstractButton *pButtonUCAC = msgBox.addButton(tr("Use ASCC"), QMessageBox::YesRole);
QAbstractButton *pButtonOrig = msgBox.addButton(tr("Use ")+refcatName, QMessageBox::YesRole);
QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
msgBox.exec();
if (msgBox.clickedButton() == pButtonUCAC) cdw->ui->ARCcatalogComboBox->setCurrentText("ASCC");
else if (msgBox.clickedButton() == pButtonCancel) return false;
else if (msgBox.clickedButton() == pButtonOrig) return true;
}
}
}
return true;
}
QString MainWindow::sameRefCoords(QString coordsMode) {
if (coordsMode != "execute") return "";
if (cdw->ui->COAraLineEdit->text() == "" || cdw->ui->COAdecLineEdit->text() == "") {
QMessageBox msgBox;
msgBox.setText("No reference coordinates provided for multi-color data set");
msgBox.setInformativeText("Several coadditions will be performed for a multi-color data set. "
"It is highly recommended that you use identical RA/DEC reference coordinates for the "
"projection of each coaddition. Images can then be automatically cropped such that "
"the same object appears on the same pixel in all coadded images.\n\n");
QAbstractButton* pButtonAuto = msgBox.addButton(tr("Use field centroid"), QMessageBox::YesRole);
QAbstractButton* pButtonContinue = msgBox.addButton(tr("Continue as is"), QMessageBox::YesRole);
QAbstractButton* pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
msgBox.exec();
if (msgBox.clickedButton() == pButtonAuto) {
QString alphaCenter = "";
QString deltaCenter = "";
if (controller->DT_SCIENCE.length() == 1) {
controller->getFieldCenter(controller->DT_SCIENCE[0], alphaCenter, deltaCenter);
cdw->ui->COAraLineEdit->setText(alphaCenter);
cdw->ui->COAdecLineEdit->setText(deltaCenter);
return "Continue";
}
else {
QMessageBox::warning(this, "THELI", "Multiple science directories. You must specifyy the field centers manually.", QMessageBox::Ok);
return "Cancel";
}
}
else if (msgBox.clickedButton() == pButtonContinue) return "Continue";
else if (msgBox.clickedButton() == pButtonCancel) return "Cancel";
else return "Cancel";
}
else return "";
}
QStringList MainWindow::displayCoaddFilterChoice(QString dirname, QString &filterChoice, QString mode)
{
// QStringList filterList = controller->getFilterList(dirname);
// We look in normal images, then in skysub images for filter string
QDir dir(dirname);
// Figure out a chip that must be present (not excluded by the user
int testChip = -1;
for (int chip=0; chip<instData.numChips; ++chip) {
if (!instData.badChips.contains(chip)) {
testChip = chip;
break;
}
}
if (testChip == -1) {
qDebug() << __func__ << "error: no data left after filtering";
}
QStringList filter("*_"+QString::number(testChip+1)+"*.fits");
dir.setNameFilters(filter);
dir.setSorting(QDir::Name);
QStringList list = dir.entryList();
QStringList filterList;
if (list.isEmpty() && mode != "simulate") {
// emit messageAvailable("MainWindow::displayCoaddFilterChoice(): No files found for coaddition!", "info");
filterChoice = "all";
}
for ( auto &fits : list) {
int status = 0;
fitsfile *fptr = nullptr;
char filter[80];
fits_open_file(&fptr, (dirname+"/"+fits).toUtf8().data(), READONLY, &status);
fits_read_key_str(fptr, "FILTER", filter, NULL, &status);
fits_close_file(fptr, &status);
printCfitsioError(fits+" : " + __func__, status);
QString filterString(filter);
filterString = filterString.simplified();
if (!filterList.contains(filterString)) filterList.append(filterString);
}
int nfilt = filterList.length();
if (nfilt == 0) {
if (mode != "simulate") {
// emit messageAvailable("MainWindow::displayCoaddFilterChoice(): No filter keyword found in coadd image list!", "info");
}
filterChoice = "all";
}
else if (nfilt == 1) {
filterChoice = filterList.at(0);
}
else {
if (mode == "simulate") {
// do not show dialog. use default:
filterChoice = "Separately";
}
else {
// nfilt > 1
QMessageBox msgBox;
msgBox.setText("Different filters are available for coaddition in\n "+dirname);
msgBox.setInformativeText("Choose a method below to coadd these filters :\n");
QAbstractButton *pAllSeparately = msgBox.addButton(tr("Separately"), QMessageBox::YesRole);
pAllSeparately->setToolTip("Create separate coadded images for each filter");
QAbstractButton *pAllTogether = msgBox.addButton(tr("Together"), QMessageBox::YesRole);
pAllTogether->setToolTip("Combine images from all filters into a single coadded image");
for (auto &it : filterList) {
QAbstractButton *button = msgBox.addButton(it, QMessageBox::YesRole);
button->setToolTip("Coadd this filter, only");
}
msgBox.addButton(tr("Abort"), QMessageBox::NoRole);
msgBox.exec();
// WARNING! Some KDE versions / settings make KDE inserts the & char for the shortcut into
// the string returned by text(). HUGE screwup. KDE should never mess with GUI at this level
filterChoice = msgBox.clickedButton()->text().remove('&');
if (filterChoice == "Together") filterChoice = "all";
}
}
return filterList;
}
void MainWindow::printCfitsioError(QString funcName, int status)
{
if (status) {
CfitsioErrorCodes *errorCodes = new CfitsioErrorCodes(this);
emit messageAvailable(funcName+":<br>" + errorCodes->errorKeyMap.value(status), "error");
}
}
void MainWindow::refreshMemoryViewerReceiver()
{
monitor->raise();
memoryViewer->raise();
}
| 49,825
|
C++
|
.cc
| 999
| 39.792793
| 203
| 0.616793
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,405
|
functions.cc
|
schirmermischa_THELI/src/functions.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "functions.h"
#include "preferences.h"
#include "instrumentdata.h"
#include "tools/fitgauss1d.h"
#include <wcs.h>
#include <unordered_map>
#include <QTextStream>
#include <QMessageBox>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <QDebug>
#include <QSysInfo>
#include <QVector>
#include <QSettings>
#include <QStandardItemModel>
#include <QStorageInfo>
#include <QProgressBar>
#include <QStandardPaths>
QString boolToString(bool test)
{
if (test) return "Y";
else return "N";
}
QStringList datadir2StringList(QLineEdit *lineEdit)
{
QStringList list;
QString entrystring = lineEdit->text();
if (entrystring.isEmpty()) {
return list;
}
entrystring.replace(",", " ");
entrystring = entrystring.simplified();
return entrystring.split(" ");
}
QString get_fileparameter(QFile *file, QString parametername, QString warn)
{
if (file->fileName().isEmpty()) return ""; // Suppressing an error when the user launches THELI for the very first time
if(!file->open(QIODevice::ReadOnly)) {
qDebug() << __func__ << file->fileName() << file->errorString();
return "";
}
QTextStream in(file);
while(!in.atEnd()) {
QString line = in.readLine();
if (!line.contains(parametername+"=")) continue;
else {
QString value = line.split("=")[1];
file->close();
return value;
}
}
file->close();
if (!warn.isEmpty()) {
QMessageBox::warning(0, "Error reading parameter from config",
"Did not find variable "+parametername+" in "+file->fileName()+" !\nReturning empty string.");
}
return "";
}
void appendToFile(QString path, QString string)
{
if (path.isEmpty()) return;
QFile file(path);
if(!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) {
qDebug() << __func__ << file.fileName() << file.errorString();
return;
}
QTextStream in(&file);
in << string << "\n";
file.close();
file.setPermissions(QFile::ReadUser | QFile::WriteUser);
}
void replaceLineInFile(const QString& filePath, const QString& searchString, const QString& replacementLine)
{
QFile file(filePath);
if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
qDebug() << __func__ << "Failed to open file " << file.errorString();
return;
}
QTextStream in(&file);
QStringList lines;
while (!in.atEnd()) {
QString line = in.readLine();
if (line.contains(searchString)) {
lines << replacementLine;
} else {
lines << line;
}
}
file.resize(0); // Clear the file content.
QTextStream out(&file);
for (const QString& line : lines) {
out << line << '\n';
}
file.close();
}
double extractFitsKeywordValue(const QString& filePath, const QString& keyword)
{
fitsfile *fitsFile;
int status = 0;
if (fits_open_file(&fitsFile, filePath.toLocal8Bit().constData(), READONLY, &status)) {
fits_report_error(stderr, status);
return -1.0;
}
double extractedValue = 0.0;
fits_read_key(fitsFile, TDOUBLE, keyword.toLocal8Bit().constData(), &extractedValue, NULL, &status);
fits_close_file(fitsFile, &status);
if (status) {
fits_report_error(stderr, status);
return -1.0;
}
return extractedValue;
}
/*
// same as above, but for .head files with additional (undesired) comment strings, and a card length of 8 chars
QString get_fileHeaderParameter(QFile *file, QString parametername)
{
if(!file->open(QIODevice::ReadOnly)) {
qDebug() << "get_fileparameter: "+file->fileName()+" "+file->errorString();
return "";
}
QTextStream in(file);
QString filename = file->fileName();
while(!in.atEnd()) {
QString line = in.readLine();
QString keyName = parametername;
keyName.resize(8, ' ');
if (!line.contains(keyName+"=")) continue;
else {
QString value = line.split("=")[1];
value.truncate(value.lastIndexOf('/'));
value = value.simplified();
file->close();
return value;
}
}
file->close();
QMessageBox::warning(0, "Error reading parameter from config",
"Did not find variable "+parametername+" in "+filename+" !\nReturning empty string.");
return "";
}
*/
QString sanityCheckWCS(const wcsprm *wcs)
{
double det = wcs->cd[0]*wcs->cd[3] - wcs->cd[1]*wcs->cd[2];
if (det == 0.) return "WCS matrix is singular: "+ QString::number(wcs->cd[0],'g',5) + QString::number(wcs->cd[1],'g',5) + QString::number(wcs->cd[2],'g',5) + QString::number(wcs->cd[3],'g',5);
else {
// Test for significant shear
double pscale1 = sqrt(wcs->cd[0]*wcs->cd[0] + wcs->cd[2]*wcs->cd[2]);
double pscale2 = sqrt(wcs->cd[1]*wcs->cd[1] + wcs->cd[3]*wcs->cd[3]);
double meanPlateScale = 0.5*(pscale1+pscale2);
// take out the pixel scale
double cd11 = wcs->cd[0] / meanPlateScale;
double cd12 = wcs->cd[1] / meanPlateScale;
double cd21 = wcs->cd[2] / meanPlateScale;
double cd22 = wcs->cd[3] / meanPlateScale;
// CD matrix should be nearly orthogonal, i.e. det = +/- 1
det = cd11*cd22 - cd12*cd21;
if (fabs(det)-1. > 0.05) {
return "WCS matrix is significantly sheared";
}
}
return "";
}
/*
void listSwapLastPairs(QStringList &stringlist, int n)
{
// At some point during creation of the commandList, we need to swap pairs
// or triplets of execution commands and log scans (meesage, run, scan).
// E.g. Before: ... L3 L2 L1 L0 then: L1 L0 L3 L2
// E.g. Before: ... L5 L4 L3 L2 L1 L0 then: L2 L1 L0 L5 L4 L3
if (n<2 || n>4) {
qDebug() << "listSwapLastPairs: n must be 2, 3 or 4, you have used " << n;
return;
}
int l0 = stringlist.length()-1;
int l1 = l0-1;
int l2 = l0-2;
int l3 = l0-3;
int l4 = l0-4;
int l5 = l0-5;
int l6 = l0-6;
int l7 = l0-7;
if (n==2) {
stringlist.swap(l2,l0);
stringlist.swap(l3,l1);
}
if (n==3) {
stringlist.swap(l3,l0);
stringlist.swap(l4,l1);
stringlist.swap(l5,l2);
}
if (n==4) {
stringlist.swap(l4,l0);
stringlist.swap(l5,l1);
stringlist.swap(l6,l2);
stringlist.swap(l7,l3);
}
}
*/
/*
QString translateServer(QString downloadServer)
{
QString server;
if ( downloadServer == "France" ) server = "vizier.unistra.fr";
else if ( downloadServer == "USA" ) server = "vizier.cfa.harvard.edu";
else if ( downloadServer == "Canada" ) server = "vizier.hia.nrc.ca";
else if ( downloadServer == "Japan" ) server = "vizier.nao.ac.jp";
else if ( downloadServer == "India" ) server = "vizier.iucaa.in";
else if ( downloadServer == "China" ) server = "vizier.china-vo.org";
else if ( downloadServer == "UK" ) server = "vizier.ast.cam.ac.uk";
else server = "vizieridia.saao.ac.za";
return server;
}
*/
// UNUSED
void selectFirstActiveItem(QComboBox *cb)
{
// This function selects the first enabled item in a combobox
// (if the enabled status has changed from the outside)
const QStandardItemModel* model = dynamic_cast< QStandardItemModel * >( cb->model() );
for (int i=0; i<cb->count(); ++i) {
if (model->item(i,0)->isEnabled()) cb->setCurrentIndex(i);
break;
}
}
long numFilesDir(QString path, QString filter)
{
QDir dir(path);
long numFiles;
if (dir.exists()) {
QStringList filterList;
filterList << filter;
dir.setNameFilters(filterList);
QStringList fileList = dir.entryList();
numFiles = fileList.length();
}
else numFiles = 0;
return numFiles;
}
/*
// Get the first vector entry from a parameter in the camera.ini files
QString get_fileparameter_vector(QFile *file, QString parametername, QString warn)
{
if(!file->open(QIODevice::ReadOnly)) {
qDebug() << "QDEBUG:: get_fileparameter_vector: "+file->fileName()+" "+file->errorString();
return "";
}
QTextStream in(file);
while(!in.atEnd()) {
QString line = in.readLine();
if (!line.contains(parametername+"=")) continue;
else {
QString value = line.split("=").at(2).split(" ").at(0);
value.replace(")","");
value = value.simplified();
file->close();
return value;
}
}
file->close();
if (!warn.isEmpty()) {
QMessageBox::warning(0, "Error reading parameter from config",
"Did not find variable "+parametername+" in "+file->fileName()+" !\nReturning empty string.");
}
return "";
}
*/
/*
// Get the full vector entry from a parameter in the camera.ini files
// THE FILE IS OPENED / CLOSED EXTERNALLY to avoid repeated file handle operations
// NOTE: already subtracting -1 to make it conform with C++ indexing
QVector<int> get_fileparameter_FullVector(QFile *file, QString parametername)
{
QVector<int> result;
// Reset file to beginning
file->seek(0);
QTextStream in(file);
while(!in.atEnd()) {
QString line = in.readLine();
if (!line.contains(parametername+"=")) continue;
line = line.replace('=',' ').replace(')',' ').replace(")","");
line = line.simplified();
QStringList values = line.split(" ");
for (int i=2; i<values.length(); i=i+2) {
result.push_back(values.at(i).toInt() - 1);
}
return result;
}
// Return empty vector if nothing found.
return result;
}
*/
void showLogfile(QString logname, QString line)
{
QSettings settings("THELI", "PREFERENCES");
QString editorPreference = settings.value("prefEditorComboBox").toString();
// in case we want to go directly to a specific error line:
if (line != "") {
if (editorPreference == "emacs") editorPreference = editorPreference + " +"+line;
else if (editorPreference == "kate") editorPreference = editorPreference + " -l "+line;
else if (editorPreference == "gedit") editorPreference = editorPreference + " +"+line;
}
QString execstr = editorPreference;
execstr.append(" ");
execstr.append(logname);
if (!QFile(logname).exists()) {
QMessageBox msgBox;
msgBox.setText("The logfile "+logname+" does not yet exist.");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
return;
}
QProcess process;
bool started = process.startDetached(execstr);
if (!started) {
QMessageBox msgBox;
msgBox.setText("The editor could not be launched. Please specify a suitable program in the preferences.\n\n"
"The executable must be found in your PATH variable.");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
// Let the user pick a working editor right away
Preferences *preferences = new Preferences(false);
preferences->show();
}
}
void message(QPlainTextEdit *pte, QString text, QString type)
{
if (type == "ignore") {
pte->appendHtml(text);
return;
}
if (type == "append") {
pte->moveCursor(QTextCursor::End);
pte->appendHtml(" "+text);
pte->moveCursor(QTextCursor::End);
return;
}
QString color;
if (type == "") {
if (text.contains("STOP")) color = "#ee0000";
else if (text.contains("NOTE")) color = "#00aa00";
else if (text.contains("INFO")) color = "#0000dd";
else color = "#000000";
}
else if (type == "stop") color = "#ee0000"; // red
else if (type == "error") color = "#ee0000"; // red
else if (type == "warning") color = "#ee5500"; // orange
else if (type == "note") color = "#009955"; // green
else if (type == "image") color = "#000000"; // black
else if (type == "info") color = "#0033cc"; // blue
else if (type == "data") color = "#0033cc"; // blue
else if (type == "output") color = "#8800aa"; // purple
else if (type == "controller") color = "#8800aa"; // purple
else if (type == "config") color = "#006666"; // turquois
else color = "#000000"; // black
// if (type == "image") text.prepend("IMAG: ");
// if (type == "data") text.prepend("DATA: ");
// else if (type == "controller") text.prepend("CTRL: ");
if (type == "error") text.prepend("ERROR: ");
pte->appendHtml("<font color=\""+color+"\">"+text+"</font>");
}
void fill_combobox(QComboBox *combobox, QString string)
{
QStringList list = string.split(" ");
combobox->clear();
combobox->addItems(list);
}
void paintPathLineEdit(QLineEdit *linedit, QString name, QString check)
{
QPalette palette_exists, palette_notexists, palette_empty;
palette_exists.setColor(QPalette::Base,QColor("#a9ffe6"));
palette_notexists.setColor(QPalette::Base,QColor("#ff99aa"));
palette_empty.setColor(QPalette::Base,QColor(255,255,255));
// White background if field is empty. Return if there is nothing else to do.
if (name.isEmpty()) {
linedit->setPalette(palette_empty);
return;
}
// Green background if dir/file exists, orange otherwise
if (check == "dir") {
QDir dir = QDir(name);
if (dir.exists()) linedit->setPalette(palette_exists);
else linedit->setPalette(palette_notexists);
}
else {
QFile file(name);
QFileInfo fileinfo(file);
if (file.exists() && fileinfo.isFile()) linedit->setPalette(palette_exists);
else linedit->setPalette(palette_notexists);
}
}
long remainingDataDriveSpace(QString maindir)
{
// Remaining space in MB on the data drive
double GBfree_data = 0.;
QStorageInfo storage_data(maindir);
if (storage_data.isValid() && storage_data.isReady()) {
GBfree_data = storage_data.bytesAvailable()/1024./1024.;
}
return long(GBfree_data);
}
/*
// Execute a shell command, ignore output;
// If you want to send it to the background and return immediately, append "&" to shell_command
void exec_system_command(QString shell_command)
{
QProcess process;
process.start("/bin/sh -c \""+shell_command+"\"");
process.waitForFinished(-1);
}
*/
// Execute a shell command, and retrieve single line output
QString read_system_command(QString shell_command)
{
QProcess process;
process.start("/bin/sh -c \""+shell_command+"\"");
process.waitForFinished(-1);
QString result(process.readLine());
return result;
}
/*
// Execute a shell command, and retrieve multiple line output
QString read_MultipleLines_system_command(QString shell_command)
{
QProcess process;
process.start("/bin/sh -c \""+shell_command+"\"");
process.waitForFinished(-1);
QByteArray ba = process.readAllStandardOutput();
QString result = QString::fromStdString(ba.toStdString());
return result;
}
*/
void initEnvironment(QString &thelidir, QString &userdir)
{
// If the THELIDIR variable is NOT set, try finding THELI in the system path
if (!QProcessEnvironment::systemEnvironment().contains("THELIDIR")) {
QDir thelidir1("/usr/share/theli/config/");
QDir thelidir2("/usr/share/theli/python/");
if (thelidir1.exists() && thelidir2.exists()) {
thelidir = "/usr/share/theli/";
}
}
else {
thelidir = QProcessEnvironment::systemEnvironment().value("THELIDIR","");
}
QSysInfo *sysInfo = new QSysInfo;
// Are we running "linux" or "darwin"?
QString kernelType = sysInfo->kernelType(); // returns "linux" or "darwin"
// Capitalize first letter
kernelType.replace(0, 1, kernelType[0].toUpper());
// Are we 64-bit Linux?
QString arch = sysInfo->currentCpuArchitecture();
if (kernelType == "Linux" && arch.contains("64")) kernelType = "Linux_64";
userdir = QDir::homePath()+"/.theli/";
// Simplify strings
thelidir.replace("//","/");
userdir.replace("//","/");
delete sysInfo;
sysInfo = nullptr;
}
QString findExecutableName(QString program)
{
QStringList sourceextractorlist = {"source-extractor", "sex", "sextractor", "SExtractor"};
QStringList scamplist = {"scamp", "Scamp"};
QStringList swarplist = {"SWarp", "Swarp", "swarp"};
QStringList anetlist1 = {"solve-field"};
QStringList anetlist2 = {"build-astrometry-index"};
QStringList pythonlist = {"python3", "python"};
QStringList curllist = {"curl"};
QString commandname = "";
if (program == "source-extractor") {
for (auto &it : sourceextractorlist) {
commandname = QStandardPaths::findExecutable(it);
if (!commandname.isEmpty()) break;
}
}
else if (program == "scamp") {
for (auto &it : scamplist) {
commandname = QStandardPaths::findExecutable(it);
if (!commandname.isEmpty()) break;
}
}
else if (program == "swarp") {
for (auto &it : swarplist) {
commandname = QStandardPaths::findExecutable(it);
if (!commandname.isEmpty()) break;
}
}
else if (program == "solve-field") {
for (auto &it : anetlist1) {
commandname = QStandardPaths::findExecutable(it);
if (commandname.isEmpty()) {
QStringList paths;
paths << "/usr/local/Astrometry/bin/";
paths << "/usr/local/astrometry/bin/";
commandname = QStandardPaths::findExecutable(it, paths);
}
if (!commandname.isEmpty()) break;
}
}
else if (program == "build-astrometry-index") {
for (auto &it : anetlist2) {
commandname = QStandardPaths::findExecutable(it);
if (commandname.isEmpty()) {
QStringList paths;
paths << "/usr/local/Astrometry/bin/";
paths << "/usr/local/astrometry/bin/";
commandname = QStandardPaths::findExecutable(it, paths);
}
if (!commandname.isEmpty()) break;
}
}
else if (program == "python") {
for (auto &it : pythonlist) {
commandname = QStandardPaths::findExecutable(it);
if (!commandname.isEmpty()) {
break;
}
}
}
else if (program == "curl") {
for (auto &it : curllist) {
commandname = QStandardPaths::findExecutable(it);
if (!commandname.isEmpty()) {
break;
}
}
}
return commandname;
}
void killProcessChildren(qint64 parentProcessId) {
QProcess get_children;
QStringList get_children_cmd;
get_children_cmd << "--ppid" << QString::number(parentProcessId) << "-o" << "pid" << "--no-heading";
get_children.start("ps", get_children_cmd);
get_children.waitForFinished();
QString childIds(get_children.readAllStandardOutput());
childIds.replace('\n', ' ');
if (childIds.isEmpty()) return;
QProcess::execute("kill -9 " + childIds);
}
// Returns the memory in kB
long get_memory()
{
QSysInfo *sysInfo = new QSysInfo;
QString kernelType = sysInfo->kernelType();
QString memory;
// TODO: use sysctl interface instead
if (kernelType == "linux") {
QProcess p;
p.start("awk", QStringList() << "/MemTotal/ { print $2 }" << "/proc/meminfo");
p.waitForFinished(-1);
memory = p.readAllStandardOutput();
memory = memory.simplified();
p.close();
}
if (kernelType == "darwin") {
QProcess p;
p.start("sysctl", QStringList() << "hw.memsize"); // alternative: read output from /usr/bin/vm_stat
// or 'hostinfo | grep memory | awk '{print $4}' // returns RAM in GB
p.waitForFinished(-1);
QString system_info = p.readAllStandardOutput();
QStringList list = system_info.split(' ');
QString memory = list[1];
p.close();
delete sysInfo;
sysInfo = nullptr;
return memory.toFloat()/1024; // CHECK normalization!
}
delete sysInfo;
sysInfo = nullptr;
return memory.toLong();
}
/*
bool listContains(QStringList stringList, QString string)
{
bool test = false;
for (auto &it : stringList) {
if (it.contains(string)) test = true;
}
return test;
}
*/
QString removeLastWords(QString string, int n, const QChar sep)
{
int i = 0;
while (i<n) {
string.truncate(string.lastIndexOf(sep));
++i;
}
return string;
}
QString getNthWord(QString string, int n, const QChar sep)
{
QStringList list = string.split(sep);
if (n<1 || n>list.length()) return "";
else return list.at(n-1);
}
QString getLastWord(QString string, const QChar sep)
{
QStringList list = string.split(sep);
return list.last();
}
QString get2ndLastWord(QString string, const QChar sep)
{
QStringList list = string.split(sep);
long index = list.count(); // if using 'int', the compiler throws a 'signed overflow' warning
if (index < 2) return "";
else {
return list.at(index-2);
}
}
void removeLastCharIf(QString &string, const QChar character)
{
int n = string.length();
if (string.at(n-1) == character) string.truncate(n-1);
}
bool hasMatchingPartnerFiles(QString dirname1, QString suffix1, QString dirname2, QString suffix2, QString infomessage)
{
// This function checks whether e.g. all science exposures have a weight, or astrometric header
QDir dir1(dirname1);
QDir dir2(dirname2);
QStringList notMatched;
QStringList filter1("*"+suffix1);
QStringList filter2("*"+suffix2);
dir1.setNameFilters(filter1);
dir2.setNameFilters(filter2);
dir1.setSorting(QDir::Name);
dir2.setSorting(QDir::Name);
QStringList list1 = dir1.entryList();
QStringList list2 = dir2.entryList();
list1.replaceInStrings(suffix1,"");
list2.replaceInStrings(suffix2,"");
// If entries are equal, or list1 is fully contained in list2, then we can leave
// Equal?
if (list1.operator ==(list2)) {
return true;
}
else {
// Fully contained?
for (auto & it : list1) {
// If not contained in list2, add it to the list of missing items
if (!list2.contains(it)) notMatched << it;
}
}
if (notMatched.length() == 0) return true;
else {
QString missingItems;
int i = 0;
for (auto &it: notMatched) {
if (i>19) break;
missingItems.append(it);
missingItems.append(suffix1);
missingItems.append("\n");
++i;
}
QMessageBox msgBox;
msgBox.setText(infomessage);
long nbad = notMatched.length();
if (nbad <= 20) {
msgBox.setInformativeText("The following "+QString::number(nbad)+" files do not have a match:\n"+missingItems);
}
else {
msgBox.setInformativeText("The following is a list of the first 20 (out of "+QString::number(nbad)+") files that did not have a match:\n"+missingItems);
}
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
return false;
}
}
void get_array_subsample(const QVector<float> &data, QVector<double> &datasub, int stepSize)
{
// Select the small array
for (long i=0; i<data.length(); i+=stepSize) {
datasub.append(data[i]);
}
}
// Truncate a list of images for nicer display in error message boxes
QString truncateImageList(QStringList list, int dim)
{
QStringList listCopy = list;
int numbad = listCopy.length();
if (numbad > dim) listCopy.erase(listCopy.begin()+dim, listCopy.end());
QString summary = listCopy.join(" ").replace(" ", "\n");
if (numbad > dim) {
summary.append("\n[...]\n\n");
summary.append("Total number of affected images: "+QString::number(numbad)+"\n");
}
return summary;
}
// Masked mad
double madMask(const QVector<double> &vector_in, const QVector<bool> &mask, QString ignoreZeroes)
{
long maxDim = vector_in.length();
if (maxDim == 0) return 0.;
QVector<double> vector;
vector.reserve(maxDim);
long i = 0;
if (!mask.isEmpty()) {
for (auto &it: vector_in) {
if (!mask[i] && ignoreZeroes == "") vector.append(it);
if (!mask[i] && ignoreZeroes != "" && it != 0.) vector.append(it);
++i;
}
}
else {
for (auto &it: vector_in) {
if (ignoreZeroes == "") vector.append(it);
if (ignoreZeroes != "" && it != 0.) vector.append(it);
++i;
}
}
QVector<double> diff;
diff.reserve(maxDim);
if (vector.size() == 0) return 0.;
else {
double med = straightMedian_T(vector);
for (int i=0; i<vector.size(); ++i) {
diff.append(fabs(vector.at(i)-med));
}
return straightMedian_T(diff);
}
}
// Masked median_err
double medianerrMask(const QVector<double> &vector_in, const QVector<bool> &mask)
{
long maxDim = vector_in.length();
if (maxDim == 0) return 0.;
QVector<double> vector;
vector.reserve(maxDim);
if (!mask.isEmpty()) {
long i = 0;
for (auto &it: vector_in) {
if (!mask[i]) vector.append(it);
++i;
}
}
else {
for (auto &it: vector_in) {
vector.append(it);
}
}
if (vector.size() == 0) return 0.;
else {
// https://en.wikipedia.org/wiki/Median_absolute_deviation#Relation_to_standard_deviation
return madMask(vector)*1.4826 / std::sqrt(vector.size());
}
}
bool moveFiles(QString filter, QString sourceDirName, QString targetDirName)
{
QDir dir1(sourceDirName);
QDir dir2(targetDirName);
if (!dir1.exists() || !dir2.exists()) {
qDebug() << __func__ << "ERROR: One or both of these directories does not exist:" << dir1 << dir2;
return false;
}
QStringList filterList(filter);
QStringList fileList = dir1.entryList(filterList);
for (auto &it: fileList) {
// In Qt5, an existing file must be removed first before a new one with the same name can be moved there
QFile testFile(dir2.absolutePath()+"/"+it);
if (testFile.exists()) {
if (!testFile.remove()) return false;
}
QFile file(dir1.absolutePath()+"/"+it);
if (!file.rename(dir1.absolutePath()+"/"+it, dir2.absolutePath()+"/"+it)) return false;
}
return true;
}
bool deleteFile(QString fileName, QString path)
{
QFile testFile(path+"/"+fileName);
if (testFile.exists()) {
if (!testFile.remove()) return false;
}
return true;
}
bool moveFile(QString filename, QString sourceDirPath, QString targetDirPath, bool skipNonExistingFile)
{
QDir targetDir(targetDirPath);
if (!targetDir.exists()) {
if (!targetDir.mkpath(targetDirPath)) {
qDebug() << __func__ << "ERROR: Could not create directory " << targetDirPath;
// mkpath() returns true if the directory already exists,
// hence if we are here then something really went wrong
return false;
}
}
// In Qt5, an existing file must be removed first before a new one with the same name can be moved there
QFile testFile(targetDirPath+"/"+filename);
if (testFile.exists()) {
if (!testFile.remove()) return false;
}
QFile file(sourceDirPath + "/" + filename);
if (skipNonExistingFile && !file.exists()) return true;
if (!file.rename(targetDirPath + "/" + filename)) {
QString operation = "mv " + sourceDirPath+"/"+filename + " " + targetDirPath+"/"+filename;
qDebug() << __func__ << "ERROR: Could not execute this operation:\n" << operation;
return false;
}
return true;
}
void mkAbsDir(QString absDirName)
{
QDir targetDir(absDirName);
if (!targetDir.exists()) targetDir.mkpath(absDirName);
}
QString hmsToDecimal(QString hms)
{
hms = hms.simplified();
hms = hms.replace(' ',':');
QStringList list = hms.split(':');
double hh = list.at(0).toDouble();
double mm = list.at(1).toDouble();
double ss = list.at(2).toDouble();
if (list.length() != 3) {
qDebug() << "Invalid format for the RA string.";
return "0.0";
}
mm /= 60.;
ss /= 3600.;
double decimal = 15.*(hh+mm+ss);
return QString::number(decimal,'f',12);
}
QString dmsToDecimal(QString dms)
{
dms = dms.simplified();
dms = dms.replace(' ',':');
QStringList list = dms.split(':');
if (list.length() != 3) {
qDebug() << "Invalid format for the Dec string.";
return "0.0";
}
double dd = list.at(0).toDouble();
double mm = list.at(1).toDouble();
double ss = list.at(2).toDouble();
// Cannot use sgn() function here, as it returns 0 when argument is (-0)
int sign = 1;
if (list.at(0).contains("-")) sign = -1;
mm /= 60.;
ss /= 3600.;
double decimal = (fabs(dd)+mm+ss)*sign;
return QString::number(decimal,'f',12);
}
QString decimalSecondsToHms(float value)
{
double h;
double m;
double s;
value /= 3600.;
value = 60.0 * modf(value, &h);
s = 60.0 * modf(value, &m);
QString hh;
QString mm;
QString ss;
if (h<10) hh = '0'+QString::number(int(h));
else hh = QString::number(int(h));
if (m<10) mm = '0'+QString::number(int(m));
else mm = QString::number(int(m));
ss = QString::number(s, 'f', 3);
return hh+":"+mm+":"+ss;
}
QString decimalToHms(float value)
{
double h;
double m;
double s;
value /= 15.;
value = 60.0 * modf(value, &h);
s = 60.0 * modf(value, &m);
QString hh;
QString mm;
QString ss;
if (h<10) hh = '0'+QString::number(int(h));
else hh = QString::number(int(h));
if (m<10) mm = '0'+QString::number(int(m));
else mm = QString::number(int(m));
ss = QString::number(s, 'f', 3);
if (s<10) ss = '0'+ss;
return hh+":"+mm+":"+ss;
}
QString decimalToDms(float value)
{
QString sign = "";
if (value < 0.) {
value *= -1.;
sign = "-";
}
double d;
double m;
double s;
value = 60.0 * modf(value, &d);
s = 60.0 * modf(value, &m);
QString dd;
QString mm;
QString ss;
if (d<10) dd = '0'+QString::number(int(d));
else dd = QString::number(int(d));
if (m<10) mm = '0'+QString::number(int(m));
else mm = QString::number(int(m));
ss = QString::number(s, 'f', 3);
if (s<10) ss = '0'+ss;
return sign+dd+":"+mm+":"+ss;
}
double dateobsToDecimal(QString dateobs)
{
// dateobs format: YYYY-MM-DDTHH:MM:SS.sss
if (!dateobs.contains("T")
|| !dateobs.contains(":")
|| !dateobs.contains("-")) {
qDebug() << __func__ << "ERROR: DATE-OBS string " << dateobs << "does not have YYYY-MM-DDTHH:MM:SS.sss format!";
return 0.;
}
QStringList list = dateobs.split("T");
QString date = list[0];
QString time = list[1];
QStringList datelist = date.split("-");
QStringList timelist = time.split(":");
if (datelist.length() != 3
|| timelist.length() != 3) {
qDebug() << __func__ << "ERROR: DATE-OBS string " << dateobs << "does not have YYYY-MM-DDTHH:MM:SS.sss format!";
return 0.;
}
double year = datelist[0].toDouble();
double month = datelist[1].toDouble();
double day = datelist[2].toDouble();
double hh = timelist[0].toDouble();
double mm = timelist[1].toDouble();
double ss = timelist[2].toDouble();
return year + month/12. + day/365.25 + hh/8766. + mm/525960. + ss/3.15576e7;
}
QVector<float> getSmallSample(const QVector<float> &data, const QVector<bool> &mask)
{
long n = data.length();
// A small sample for quick first estimates
QVector<float> sample;
long step = 1;
// A prime number whose integer multiples do not get close to pow(2^n)
// and therefore it samples a typical detector in a random-like fashion
if (n>10000) {
step = 379;
sample.reserve(n/379);
}
else sample.reserve(n);
if (!mask.isEmpty()) {
for (long i=0; i<n; i+=step) {
if (!std::isnan(data[i]) && !std::isinf(data[i]) && !mask[i])
sample.append(data[i]);
}
}
else {
for (long i=0; i<n; i+=step) {
if (!std::isnan(data[i]) && !std::isinf(data[i]))
sample.append(data[i]);
}
}
return sample;
}
// A fast mode calculator
// Optionally, it also provides an rms estimate based on the truncated histogram
QVector<float> modeMask(const QVector<float> &data, QString mode, const QVector<bool> &mask, bool smooth)
{
QVector<float> sky;
long n = data.length();
if (n == 0) return sky << 0. << -1.;
if (!mask.isEmpty() && n != mask.length()) {
qDebug() << __func__ << "ERROR: Mask is not empty but has different size than data vector." << n << mask.length();
return sky << 0. << -1.;
}
// Work with values within -3 MAD to 3 MAD (about +/- 2 sigma). Estimated from a small sample (at least 10000 data points)
QVector<float> sample = getSmallSample(data, mask);
float medianVal = straightMedian_T(sample);
float madVal = madMask_T(sample);
float minVal = medianVal - 3.*madVal;
float maxVal = medianVal + 3.*madVal;
float skySigma = 1.3*madVal; // estimate of sigma based on MAD value (normally 1.48, but we want the clipped range without astrophysical objects)
// Optimal step size for 100 bins, yielding an average S/N per bin of of 10
int numBins = 100;
int sampleDensity = modeMask_sampleDensity(n, numBins, 10);
// Clip data, use every sampleDensity data point only
QVector<float> dataClipped = modeMask_clipData(data, mask, sampleDensity, minVal, maxVal);
if (dataClipped.isEmpty()) return sky << 0. << -1.;
// Too few data points for mode:
if (dataClipped.length() < 1000) return sky << medianVal << skySigma;
// Build histogram (smoothed by default with a kernel 0.5*madVal wide)
float rescale = 1.0; // the projection factor from the original data to normalized integer range corresponding to [minVal, maxVal]
QVector<long> histogram = modeMask_buildHistogram(dataClipped, rescale, numBins, minVal, maxVal, madVal, smooth);
// Find the histogram peak with various methods (data dependent)
float skyValue = 0.;
if (mode == "classic") modeMask_classic(histogram, skyValue);
else if (mode == "gaussian") modeMask_gaussian(histogram, skyValue);
else if (mode == "stable") modeMask_stable(histogram, skyValue);
else {
// to be implemented
}
// Project back onto original scale
skyValue = skyValue / rescale + minVal;
// skySigma = skySigma / rescale; // if skySigma was estimated from the histogram
return sky << skyValue << skySigma;
}
// MODE: Determine optimal sample density
int modeMask_sampleDensity(long numDataPoints, int numBins, float SNdesired)
{
// We use only every n-th data point (n = sampleDensity) to speed up calculations.
// The sample density is chosen such that it yields, on average, the desired S/N per bin (assuming Poisson distribution)
long sampleDensity = numDataPoints / (numBins * SNdesired * SNdesired);
if (sampleDensity == 0) sampleDensity = 1; // max density for few data points
if (sampleDensity > 10) sampleDensity = 10; // min density; we don't mind good S/N in the histogram
return sampleDensity;
}
// MODE: Clip data, use every sampleDensity data point only
QVector<float> modeMask_clipData(const QVector<float> &data, const QVector<bool> &mask, int sampleDensity, float minVal, float maxVal)
{
QVector<float> dataThresholded;
long n = data.length();
dataThresholded.reserve(n/sampleDensity);
if (!mask.isEmpty()) {
for (long i=0; i<n; i+=sampleDensity) {
float it = data[i];
if (it > minVal && it < maxVal && !mask[i]) {
dataThresholded.append(it);
}
}
}
else {
for (long i=0; i<n; i+=sampleDensity) {
float it = data[i];
if (it > minVal && it < maxVal) {
dataThresholded.append(it);
}
}
}
return dataThresholded;
}
// MODE: Build histogram
QVector<long> modeMask_buildHistogram(QVector<float> &data, float &rescale, const int numBins, const float minVal,
const float maxVal, const float madVal, const bool smooth)
{
// Project data onto integer values, spread numBins over normalized [minVal, maxVal] range
rescale = float(numBins) / (maxVal - minVal);
for (auto &it: data) {
it = int (rescale * (it-minVal));
// Stay within bounds
// It can rarely happen that it == numBins for it=max; floating point round-off issue, causing histogram[it] to fail;
if (it < 0) it = 0;
if (it >= numBins) it = numBins-1;
}
// Now accumulate the histogram (bin 0 corresponds to minVal, bin numBin to maxVal)
QVector<long> histogram(numBins);
for (auto &it : data) {
histogram[it]++;
}
// Optionally, smooth the histogram (true by default)
// The smoothing is done with a Gaussian that is 'width' bins wide, where width is half the MAD value, but at least 3 bins wide
int width = 0.5 * madVal * rescale;
if (width < 3) width = 3;
// if (histogram[20] == 0 && histogram[21] == 0 && histogram[22] == 0 && histogram[23] == 0) {
// qDebug() << data;
// qDebug() << histogram;
// }
if (smooth) smooth_array_T(histogram, width);
// if (histogram[20] == 0 && histogram[21] == 0 && histogram[22] == 0 && histogram[23] == 0) {
// qDebug() << " ";
// qDebug() << data;
// qDebug() << histogram;
// }
return histogram;
}
// Classical way to find peak in the histogram: look for the highest bin
void modeMask_classic(const QVector<long> histogram, float &skyValue)
{
float hist_max = 0.;
int hist_x = 0;
long i = 0;
for (auto &it : histogram) {
if (it > hist_max) {
hist_x = i;
hist_max = it;
}
++i;
}
skyValue = hist_x;
}
// Find the peak in the histogram using a Gaussian fit
// WARNING: Does not work if image contains large number of padded or constant pixels,
// creating (multiple) huge histogram spikes, failing the GSL fit.
void modeMask_gaussian(QVector<long> histogram, float &skyValue)
{
int numBins = histogram.length();
// Starting values
double amplitude = maxVec_T(histogram);
double meanVal = numBins/2;
double sigmaVal = rmsMask_T(histogram);
// Arguments 2, 3 and 4 are starting values for amplitude, mean and sigma
QVector<float> fitResult = fitGauss1D(histogram, amplitude, meanVal, sigmaVal);
skyValue = fitResult[1];
// skySigma = fitResult[2];
}
// Robust way: determine 50% cut-on and cut-off values, and return the mean of data points in between
// This will work if the data is not unimodular (e.g. if gradients are present in an image)
void modeMask_stable(const QVector<long> histogram, float &skyValue)
{
int numBins = histogram.length();
double amplitude = maxVec_T(histogram);
// Locate the classic peak
modeMask_classic(histogram, skyValue);
// Extreme limits
int cutOn = 0;
int cutOff = numBins - 1;
// Update limits
// Take the peak and go left until the 50% value is reached
for (int i=skyValue; i>=0; --i) {
if (histogram[i] <= 0.5*amplitude) {
cutOn = i;
break;
}
}
// Take the peak and go right until the 50% value is reached
for (int i=skyValue; i<numBins; ++i) {
if (histogram[i] <= 0.5*amplitude) {
cutOff = i;
break;
}
}
// Image might have a strong tail towards high values, and the upper 50% limit isn't found.
// In this case, use a symmetric cut off:
if (cutOff == numBins-1) {
cutOff = skyValue + skyValue - cutOn;
if (cutOff >= numBins) cutOff = numBins-1;
}
/*
if (cutOn == 0 || cutOff == numBins) {
qDebug() << "QDEBUG: functions:modeMask_stable(): Could not locate 50% cut-on and cut-off values for image statistics. Using full range.";
}
*/
if (cutOn == cutOff) {
qDebug() << __func__ << "Error determining 50% cut-on and cut-off values for image statistics. Using middle quantile.";
cutOn = 0.25*numBins;
cutOff = 0.75*numBins;
}
// qDebug() << cutOn << cutOff;
// Calculate mean value within cutOn and cutOff
skyValue = 0.;
float weights = 0.;
for (int i=cutOn; i<=cutOff; ++i) {
skyValue += i*histogram[i];
weights += histogram[i];
}
skyValue /= weights;
}
//***************************************************************************
// DUPLICATED from templates because I need them in connection with functors.
// These functions may call template functions themselves, though
//***************************************************************************
// Masked median
float medianMask(const QVector<float> &vector_in, const QVector<bool> &mask, long maxLength)
{
long maxDim = vector_in.length();
if (maxDim == 0) return 0.;
// fast-track
if (mask.isEmpty()) {
return straightMedian_T(vector_in, maxLength);
}
// Usually, we take all elements in a vector.
// However, in some cases it may be that elements are masked and the vector is not entirely filled.
// In this case, an optional maxLength argument is provided
if (maxLength > 0 && maxLength < maxDim) maxDim = maxLength;
QVector<float> vector;
vector.reserve(maxDim);
for (int i=0; i<maxDim; ++i) {
if (!mask[i]) vector.append(vector_in[i]);
}
if (vector.size() == 0) return 0.;
else {
return straightMedian_T(vector, maxLength);
}
}
// Changes data!
float straightMedian_MinMax(QVector<float> &data, const int nlow, const int nhigh)
{
long maxDim = data.length();
if (maxDim == 0) return 0.;
if (nlow+nhigh >= maxDim) return 0;
std::sort(data.begin(), data.end());
float med;
if (nhigh > 0) data.remove(maxDim-nhigh, nhigh);
if (nlow > 0) data.remove(0, nlow);
// Calculate average of central two elements if number is even
long dsize = data.size();
med = (dsize % 2)
? data[dsize / 2]
: ((float)data[dsize / 2 - 1] + data[dsize / 2]) * .5;
return med;
}
// Changes data!
float straightMedian_MinMax(QList<float> &data, const int nlow, const int nhigh)
{
long maxDim = data.length();
if (maxDim == 0) return 0.;
if (nlow+nhigh >= maxDim) return 0;
std::sort(data.begin(), data.end());
float med;
if (nhigh > 0) {
for (int i=0; i<nhigh; ++i) data.pop_back();
}
if (nlow > 0) {
for (int i=0; i<nhigh; ++i) data.pop_front();
}
// Calculate average of central two elements if number is even
long dsize = data.size();
med = (dsize % 2)
? data[dsize / 2.]
: ((float)data[dsize / 2. - 1] + data[dsize / 2.]) * .5;
return med;
}
// Masked mean
float meanMask(const QVector<float> &vector_in, const QVector<bool> &mask, long maxLength)
{
long maxDim = vector_in.length();
// Usually, we take all elements in a vector.
// However, in some cases it may be that elements get masked and the vector is not entirely filled.
// In this case, an optional maxLength argument is provided
if (maxLength > 0 && maxLength < maxDim) maxDim = maxLength;
// fast-track
if (vector_in.size() == 0) return 0.;
if (mask.isEmpty()) {
float meanVal = 0.;
for (long i=0; i<maxDim; ++i) meanVal += vector_in[i];
return meanVal / maxDim;
}
else {
QVector<float> vector;
vector.reserve(maxDim);
for (int i=0; i<maxDim; ++i) {
if (!mask[i]) vector.append(vector_in[i]);
}
if (vector.size() == 0) return 0.;
else
return std::accumulate(vector.begin(), vector.end(), .0) / vector.size();
}
}
// Calculate an iterative mean using sigma outlier rejection.
// The algorithm terminates after iterMax iterations, or if converged.
// Data points can re-enter the process.
float meanIterative(const QVector<float> data, float kappa, int iterMax)
{
long dim = data.length();
if (dim == 0) return 0.;
QVector<bool> mask(dim,false);
// Calculate first estimate of mean and rms; all masks are false
float meanVal = meanMask_T(data, mask);
float rmsVal = rmsMask_T(data, mask);
if (kappa == 0. || iterMax == 0) return meanVal;
int iter = 0;
while (iter < iterMax) {
// Calculate mean and rms
meanVal = meanMask_T(data, mask);
rmsVal = rmsMask_T(data, mask);
// Recalculate mask
bool masksChanged = false;
long i = 0;
for (auto & it : data) {
bool currentMask = mask[i];
// reject an outlier
if (!currentMask && fabs(it - meanVal) >= kappa*rmsVal) {
mask[i] = true;
masksChanged = true;
}
// include a previous outlier again
if (currentMask && fabs(it - meanVal) < kappa*rmsVal) {
mask[i] = false;
masksChanged = true;
}
++i;
}
// Leave if masks haven't changed
if (masksChanged == false) break;
++iter;
}
return meanVal;
}
bool readData3D(QString path, QVector<double> &x, QVector<double> &y, QVector<double> &z)
{
QFile file(path);
if (!file.exists()) {
return false;
}
if ( !file.open(QIODevice::ReadOnly)) {
return false;
}
QTextStream in(&(file));
while(!in.atEnd()) {
QString line = in.readLine().simplified();
if (line.isEmpty() || line.contains("#")) continue;
QStringList values = line.split(" ");
if (values.length() != 3) continue;
x.append(values[0].toDouble());
y.append(values[1].toDouble());
z.append(values[2].toDouble());
}
file.close();
return true;
}
// Angles are always passed / returned in degrees
double getPosAnglefromCD(double cd11, double cd12, double cd21, double cd22, bool lock)
{
// In case CD matrix is undefined (e.g. binned images)
if (cd11 == 0. && cd12 == 0. && cd21 == 0. && cd22 == 0.) return 0.;
// the pixel scale
double pscale1 = sqrt(cd11 * cd11 + cd21 * cd21);
double pscale2 = sqrt(cd12 * cd12 + cd22 * cd22);
// take out the pixel scale
cd11 /= pscale1;
cd12 /= pscale2;
cd21 /= pscale1;
cd22 /= pscale2;
// sqrt(CD elements) is very close to one, but not perfectly
// as coordinate system is not necessarily orthogonal (shear + contraction)
double nfac1 = sqrt(cd11 * cd11 + cd21 * cd21);
double nfac2 = sqrt(cd12 * cd12 + cd22 * cd22);
// make sure sqrt(CD elements) = 1,
// so that we can do the inverse trig functions
cd11 /= nfac1;
cd21 /= nfac1;
cd12 /= nfac2;
cd22 /= nfac2;
// due to flipping the rotation angle is ambiguous.
// possibly, the following could be simplified with det(CD),
// but at the moment i don't see how to identify the additional 2*PI easily
double pa = 0.;
double PI = 3.1415926535;
// normal
if (cd11 < 0 && cd12 <= 0 && cd21 <= 0 && cd22 > 0) pa = acos(-cd11); // 0 <= phi < 90
else if (cd11 >= 0 && cd12 < 0 && cd21 < 0 && cd22 <= 0) pa = acos(-cd11); // 90 <= phi < 180
else if (cd11 > 0 && cd12 >= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(-cd11); // 180 <= phi < 270
else if (cd11 <= 0 && cd12 > 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(-cd11); // 270 <= phi < 360
// flipped
else if (cd11 >= 0 && cd12 >= 0 && cd21 <= 0 && cd22 >= 0) pa = acos(cd11); // 0 <= phi < 90
else if (cd11 < 0 && cd12 > 0 && cd21 < 0 && cd22 < 0) pa = acos(cd11); // 90 <= phi < 180
else if (cd11 < 0 && cd12 <= 0 && cd21 >= 0 && cd22 < 0) pa = 2.*PI-acos(cd11); // 180 <= phi < 270
else if (cd11 >= 0 && cd12 < 0 && cd21 > 0 && cd22 >= 0) pa = 2.*PI-acos(cd11); // 270 <= phi < 360
else {
if (lock) {
// we are very likely close to 0, 90, 180 or 270 degrees, and the CD matrix is slightly non-orthogonal.
// In this case, lock onto 0, 90, 180 or 270 degrees. Otherwise, exit with an error.
double cd11cd12 = fabs(cd11/cd12);
double cd22cd21 = fabs(cd22/cd21);
if (cd11cd12 > 20. && cd22cd21 > 20.) {
if (cd11 > 0. && cd22 > 0.) pa = 0.*PI/2.;
if (cd11 < 0. && cd22 > 0.) pa = 0.*PI/2.;
if (cd11 > 0. && cd22 < 0.) pa = 2.*PI/2.;
if (cd11 < 0. && cd22 < 0.) pa = 2.*PI/2.;
}
else if (cd11cd12 < 0.05 && cd22cd21 < 0.05) {
if (cd12 > 0. && cd21 < 0.) pa = 1.*PI/2.;
if (cd12 < 0. && cd21 < 0.) pa = 1.*PI/2.;
if (cd12 > 0. && cd21 > 0.) pa = 3.*PI/2.;
if (cd12 < 0. && cd21 > 0.) pa = 3.*PI/2.;
}
else {
// should print to command line only if in debug mode
// qDebug() << __func__ << "ERROR: Could not determine position angle from CD matrix!";
}
}
}
double rad = PI / 180.;
return (pa / rad); // return in degrees
}
// Angles are always passed / returned in degrees
void rotateCDmatrix(double &cd11, double &cd12, double &cd21, double &cd22, double PAnew)
{
double rad = 3.1415926535 / 180.;
// the current position angle of the CD matrix
double PAold = getPosAnglefromCD(cd11, cd12, cd21, cd22);
// is the matrix flipped (det(CD) > 0 if flipped)
double det = cd11*cd22 - cd12*cd21;
double f11 = 0.;
if (det < 0) f11 = 1.;
else f11 = -1.;
double f12 = 0.;
double f21 = 0.;
double f22 = 1.;
// unflip the matrix
matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22);
// rotate the matrix to the new position angle
double dPA = rad * (PAnew - PAold);
matrixMult_T(cos(dPA), -sin(dPA), sin(dPA), cos(dPA), cd11, cd12, cd21, cd22);
// flip the matrix
matrixMult_T(f11, f12, f21, f22, cd11, cd12, cd21, cd22);
}
// Angles are always passed / returned in degrees
void get_rotimsize(long naxis1, long naxis2, double PAold, double PAnew, long &Nnew, long &Mnew)
{
double n = naxis1;
double m = naxis2;
double r = 0.5 * sqrt(n*n+m*m) + 1.;
double rad = 3.1415926535 / 180.;
double phi = atan(m/n) / rad;
QVector<double> xarr(4);
QVector<double> yarr(4);
xarr[0] = r * cos(rad * (PAnew - PAold + phi));
xarr[1] = r * cos(rad * (PAnew - PAold - phi + 180.));
xarr[2] = r * cos(rad * (PAnew - PAold + phi + 180.));
xarr[3] = r * cos(rad * (PAnew - PAold - phi + 360.));
yarr[0] = r * sin(rad * (PAnew - PAold + phi));
yarr[1] = r * sin(rad * (PAnew - PAold - phi + 180.));
yarr[2] = r * sin(rad * (PAnew - PAold + phi + 180.));
yarr[3] = r * sin(rad * (PAnew - PAold - phi + 360.));
long xmin = (long) minVec_T(xarr);
long xmax = (long) maxVec_T(xarr);
long ymin = (long) minVec_T(yarr);
long ymax = (long) maxVec_T(yarr);
Nnew = xmax - xmin;
Mnew = ymax - ymin;
}
int gauss_f(const gsl_vector* x, void* params, gsl_vector* f)
{
size_t nx = ((struct dataGSL *) params)->nx;
size_t ny = ((struct dataGSL *) params)->ny;
double *z = ((struct dataGSL *) params)->z;
double *sigma = ((struct dataGSL *) params)->sigma;
// extract parameters from x
double b = gsl_vector_get(x,0);
double x0 = gsl_vector_get(x,1);
double y0 = gsl_vector_get(x,2);
double s = gsl_vector_get(x,3);
for (size_t yi=0; yi<ny; ++yi) {
for (size_t xi=0; xi<nx; ++xi) {
int indx = xi + nx*yi;
// calculate Fxy based on parameters
double Fxy = b * exp(-0.5*( (xi-x0)*(xi-x0) + (yi-y0)*(yi-y0)) / (s*s));
gsl_vector_set(f, indx, (Fxy - z[indx])/sigma[indx]);
}
}
return GSL_SUCCESS;
}
int gauss_df(const gsl_vector *x, void *params, gsl_matrix *J)
{
size_t nx = ((struct dataGSL *)params)->nx;
size_t ny = ((struct dataGSL *)params)->ny;
double *sigma = ((struct dataGSL *)params)->sigma;
double x0 = gsl_vector_get(x,1);
double y0 = gsl_vector_get(x,2);
double s = gsl_vector_get(x,3);
for (size_t yi=0; yi<ny; ++yi) {
for (size_t xi=0; xi<nx; ++xi) {
int indx = xi + nx*yi;
double f0 = exp(-0.5*( (xi-x0)*(xi-x0) + (yi-y0)*(yi-y0)) / (s*s));
// The Jacobian matrix
gsl_matrix_set (J, indx, 0, 1./sigma[indx] * f0);
gsl_matrix_set (J, indx, 1, 1./(s*s*sigma[indx]) * (xi - x0) * f0);
gsl_matrix_set (J, indx, 2, 1./(s*s*sigma[indx]) * (yi - y0) * f0);
gsl_matrix_set (J, indx, 3, 1./(s*s*s*sigma[indx]) * (pow(xi-x0,2) + pow(yi-y0,2)) * f0);
}
}
return GSL_SUCCESS;
}
int gauss_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *J)
{
gauss_f(x, params, f);
gauss_df(x, params, J);
return GSL_SUCCESS;
}
void flipData(QVector<float> &data, const QString dir, const int naxis1, const int naxis2)
{
QVector<float> copy;
copy.resize(naxis1*naxis2);
long k = 0;
if (dir == "x") {
for (int j=0; j<naxis2; ++j) {
for (int i=0; i<naxis1; ++i) {
copy[k++] = data[naxis1-1-i + naxis1*j];
}
}
}
else if (dir == "y") {
for (int j=0; j<naxis2; ++j) {
for (int i=0; i<naxis1; ++i) {
copy[k++] = data[i + naxis1*(naxis2-1-j)];
}
}
}
else if (dir == "xy") {
for (int j=0; j<naxis2; ++j) {
for (int i=0; i<naxis1; ++i) {
copy[k++] = data[naxis1-i-1+naxis1*(naxis2-j-1)];
}
}
}
else {
// nothing yet
}
data.swap(copy);
}
void flipSections(QVector<long> §ions, const QString dir, const int naxis1, const int naxis2)
{
QVector<long> copy = sections;
if (dir == "x") {
copy[1] = naxis1-1-sections[0];
copy[0] = naxis1-1-sections[1];
}
else if (dir == "y") {
copy[3] = naxis2-1-sections[2];
copy[2] = naxis2-1-sections[3];
}
else if (dir == "xy") {
copy[1] = naxis1-1-sections[0];
copy[0] = naxis1-1-sections[1];
copy[3] = naxis2-1-sections[2];
copy[2] = naxis2-1-sections[3];
}
sections = copy;
}
// In case the user has deactivated some chips, we need to find one that is valid
int getValidChip(const instrumentDataType *instData)
{
/*
int testChip = -1;
for (int chip=0; chip<instData->numChips; ++chip) {
if (!instData->badChips.contains(chip)) {
testChip = chip;
break;
}
}
if (testChip == -1) {
qDebug() << __func__ << "error: no data left after filtering";
}
return testChip;
*/
if (instData->goodChips.isEmpty()) return 0; // error message is printed by MainWindow::updateExcludedDetectors(QString badDetectors)
else return instData->goodChips[0]; // return the first valid chip
}
| 56,623
|
C++
|
.cc
| 1,548
| 30.466408
| 196
| 0.602768
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,406
|
deepmessages.cc
|
schirmermischa_THELI/src/deepmessages.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mainwindow.h"
#include <QDebug>
#include <QMessageBox>
// This source file handles signals emitted from within the processing threads
// Show error messages
void MainWindow::showMessageBoxReceived(QString trigger, QString part1, QString part2)
{
if (trigger == "Controller::GAP_DYNAMIC_FOUND" && !GAP_DYNAMIC_FOUND_shown) {
GAP_DYNAMIC_FOUND_shown = true;
QMessageBox::warning(this, tr("Significant gap found in background image series"),
tr("A gap of ")+part1+tr(" hours was found ")+
tr("in the dynamic series of background images, exceeding the maximum ")+
tr("allowed gap size of ")+part2+
tr(" hours.\nUsually, a gap size does not need to be defined with dynamic background modeling."),
QMessageBox::Ok);
}
else if (trigger == "Controller::INSUFFICIENT_BACKGROUND_NUMBER" && !INSUFFICIENT_BACKGROUND_NUMBER_shown) {
INSUFFICIENT_BACKGROUND_NUMBER_shown = true;
QMessageBox::warning(this, tr("Insufficient number of suitable background images."),
part1+tr(" images were found to construct a background model. ")+
tr("This is less than the required minimum of ")+part2+tr(" images."),
QMessageBox::Ok);
}
else if (trigger == "Controller::WINDOWSIZE_TOO_LARGE" && !WINDOWSIZE_TOO_LARGE_shown) {
WINDOWSIZE_TOO_LARGE_shown = true;
QMessageBox::warning(this, tr("Window size too large"),
tr("The currently selected window size of ")+part1+tr(" images is larger than the number")+
tr("of images (")+part2+tr(") available for background correction. Aborting."),
QMessageBox::Ok);
}
else if (trigger == "Controller::SKY_FILE_NOT_FOUND" && !SKY_FILE_NOT_FOUND_shown) {
SKY_FILE_NOT_FOUND_shown = true;
QMessageBox::warning(this, tr("File not found / no sky positions selected"),
tr("The file with blank sky positions could not be found or is empty:")+"\n"+
part1+"/skysamples.dat\n"+
tr("Click on \"Select sky area(s)\" to open iView and select at least one empty sky area with the middle mouse button."),
QMessageBox::Ok);
}
else if (trigger == "Controller::NO_OVERLAP_WITH_SKYAREA" && !NO_OVERLAP_WITH_SKYAREA_shown) {
NO_OVERLAP_WITH_SKYAREA_shown = true;
QMessageBox::warning(this, tr("Insufficient sky data"),
tr("The following exposure did not overlap with any of the manually defined sky positions:")+"\n"+
part1+"\nAborting.",
QMessageBox::Ok);
}
else if (trigger == "Controller::POOR_COORD") {
QMessageBox::warning(this, tr("Inconsistent coaddition coordinates"),
tr("The manually provided coordinates for the sky projection do not fall within any of the exposures:")+"\n"+
"R.A. = "+part1+"\n"+
"DEC = "+part2+"\nEither provide correct coordinates, or leave the fields empty. Aborting.",
QMessageBox::Ok);
}
else if (trigger == "Controller::MASTER_BIAS_NOT_FOUND" && !MASTER_BIAS_NOT_FOUND_shown) {
MASTER_BIAS_NOT_FOUND_shown = true;
QMessageBox::warning(this, tr("Master BIAS not found"),
tr("The following master BIAS or DARK was not found for calibrating science images:")+"\n"+
part1+"\n"+
tr("\nYou must create it first."),
QMessageBox::Ok);
}
else if (trigger == "Controller::MASTER_FLAT_NOT_FOUND" && !MASTER_FLAT_NOT_FOUND_shown) {
MASTER_FLAT_NOT_FOUND_shown = true;
QMessageBox::warning(this, tr("Master FLAT not found"),
tr("The following master FLAT was not found for calibrating science images:")+"\n"+
part1+"\n"+
tr("\nYou must create it first."),
QMessageBox::Ok);
}
else if (trigger == "Controller::MASTER_FLATOFF_NOT_FOUND" && !MASTER_FLATOFF_NOT_FOUND_shown) {
MASTER_FLATOFF_NOT_FOUND_shown = true;
QMessageBox::warning(this, tr("Master Calibrator not found"),
tr("Master BIAS or FLAT_OFF not found for creation of master FLAT!")+"\n"+
part1+"\n"+
tr("You must create it first."),
QMessageBox::Ok);
}
else if (trigger == "Controller::MASTER_BIAS_NOT_FOUND_GLOBW" && !MASTER_BIAS_NOT_FOUND_GLOBW_shown) {
MASTER_BIAS_NOT_FOUND_GLOBW_shown = true;
QMessageBox::warning(this, tr("Master BIAS or FLATOFF not found"),
tr("Master BIAS or FLATOFF not found, needed to create the global weight.")+"\n"+
part1+"\n"+
tr("You must create it first."),
QMessageBox::Ok);
}
else if (trigger == "Controller::MASTER_FLAT_NOT_FOUND_GLOBW" && !MASTER_FLAT_NOT_FOUND_GLOBW_shown) {
MASTER_FLAT_NOT_FOUND_GLOBW_shown = true;
QMessageBox::warning(this, tr("Master FLAT not found"),
tr("Master FLAT not found, needed to create the global weight.")+"\n"+
part1+"\n"+
tr("You must create it first."),
QMessageBox::Ok);
}
else if (trigger == "Controller::NO_MJDOBS_FOR_PM" && !NO_MJDOBS_FOR_PM_shown) {
NO_MJDOBS_FOR_PM_shown = true;
QMessageBox::warning(this, tr("MJD-OBS not found"),
tr("The MJD-OBS keyword was not found or zero in at least one of the exposures.")+"\n"+
tr("It is required for the requested non-sidereal motion correction. Aborting."),
QMessageBox::Ok);
}
else if (trigger == "Controller::CANNOT_UPDATE_HEADER_WITH_PM_READ" && !CANNOT_UPDATE_HEADER_WITH_PM_READ_shown) {
CANNOT_UPDATE_HEADER_WITH_PM_READ_shown = true;
QMessageBox::warning(this, tr("Cannot read header file"),
tr("The header file") + part1 + tr("\ncould not be opened for reading. Needed to update with the non-sidereal proper motion.")+"\n"+
tr("Error is: ") + part2 + "\nAborting.",
QMessageBox::Ok);
}
else if (trigger == "Controller::CANNOT_UPDATE_HEADER_WITH_PM_WRITE" && !CANNOT_UPDATE_HEADER_WITH_PM_WRITE_shown) {
CANNOT_UPDATE_HEADER_WITH_PM_WRITE_shown = true;
QMessageBox::warning(this, tr("Cannot write header file"),
tr("The header file\n") + part1 + tr("\ncould not be opened for writing. Needs to be updated with the non-sidereal proper motion.")+"\n"+
tr("Error is: ") + part2 + "\nAborting.",
QMessageBox::Ok);
}
else if (trigger == "Controller::CANNOT_UPDATE_HEADER_WITH_PA" && !CANNOT_UPDATE_HEADER_WITH_PA_shown) {
CANNOT_UPDATE_HEADER_WITH_PA_shown = true;
QMessageBox::warning(this, tr("Cannot read header file"),
part1 + tr("\ncould not be opened to read the CD matrix. This is needed for the update it with the new position angle.")+"\n"+
tr("Error is: ") + part2 + "\nAborting.",
QMessageBox::Ok);
}
else if (trigger == "Controller::CANNOT_WRITE_RESAMPLE_LIST" && !CANNOT_WRITE_RESAMPLE_LIST_shown) {
CANNOT_WRITE_RESAMPLE_LIST_shown = true;
QMessageBox::warning(this, tr("Cannot write file"),
tr("Coaddition: Could not append image names to ")+part1+"<br>"+
tr("Error is: ") + part2 + "<br>Aborting.",
QMessageBox::Ok);
}
else if (trigger == "Controller::CANNOT_OPEN_FILE" && !CANNOT_OPEN_FILE_shown) {
CANNOT_OPEN_FILE_shown = true;
QMessageBox::warning(this, tr("Cannot open file for read/write"),
tr("The following file could not be opened: ")+part1+"<br><br>"+
tr("The Error is: \"") + part2 + "\"<br>Aborting.",
QMessageBox::Ok);
}
else if (trigger == "Data::CANNOT_READ_HEADER_KEYS" && !CANNOT_READ_HEADER_KEYS_shown) {
CANNOT_READ_HEADER_KEYS_shown = true;
QMessageBox::warning(this, tr("Could not read one or more of the following keywords:\nNAXIS1, NAXIS2, FILTER, MJD-OBS"),
tr("Add the keywords manually, or the remove the corrupted images.\n")+part1,
QMessageBox::Ok);
}
else if (trigger == "Data::INCONSISTENT_DATA_STATUS" && INCONSISTENT_DATA_STATUS_shown) {
INCONSISTENT_DATA_STATUS_shown = true;
QMessageBox::warning(this, tr("Inconsistent data status detected in ")+part1,
part1 + " : " + tr("The FITS files found do not match the recorded status (*") + part2 +".fits).\n"+
tr("Either restore the files manually, or use the 'Processing status' menu to reflect the current status. A restart is recommended."),
QMessageBox::Ok);
}
else if (trigger == "Data::Duplicate_MJDOBS" && !DUPLICATE_MJDOBS_shown) {
DUPLICATE_MJDOBS_shown = true;
QMessageBox::warning(this, tr("One or more images have identical MJD-OBS header keywords."),
tr("THELI cannot build a list of contemporal images for the background model in")+part1+
tr("<br>nor construct correct source catalogs for the astrometric solution.")+
tr("<br>You must first fix the MJD-OBS keywords to their correct values, or the DATE-OBS keyword in the raw data."),
QMessageBox::Ok);
}
else if (trigger == "Data::IMAGES_NOT_FOUND" && !IMAGES_NOT_FOUND_shown) {
IMAGES_NOT_FOUND_shown = true;
QMessageBox::warning(this, tr("ERROR: Images not found"),
tr("Could not find any images of type :<br>")+"*"+part1+".fits" + "<br>in "+part2 +
tr("<br>Check that the recorded processing status matches the currently present images."),
QMessageBox::Ok);
}
else if (trigger == "Controller::TARGET_UNRESOLVED") {
QMessageBox::warning(this, tr("Target not found"),
tr("The coordinates of ") + part1 + tr(" could not be resolved.")+
tr("<br>Check for typos, or try a different name of the same target."),
QMessageBox::Ok);
}
else if (trigger == "Controller::RESET_REQUESTED") {
const QMessageBox::StandardButton ret
= QMessageBox::warning(this, tr("Clearing error status?"),
tr("The data in ") + part1 + tr(" is in an error state due to an earlier processing failure.")+
tr("<br>Do you want to clear the error state to allow reprocessing (you must re-execute the task)?"),
QMessageBox::Ok | QMessageBox::Cancel);
switch (ret) {
case QMessageBox::Ok:
emit resetErrorStatus(part1);
break;
default:
break;
}
}
else if (trigger == "Colorpicture::EmptySelection") {
QMessageBox::warning(this, tr("Empty selection"),
tr("At least two images must be chosen from the list of coadded images."),
QMessageBox::Ok);
}
else if (trigger == "Splitter::IncompatibleSizeRAW" && !IncompatibleSizeRAW_shown) {
IncompatibleSizeRAW_shown = true;
QMessageBox::warning(this, tr("Incompatible detector geometry in setup"),
tr("You must adjust the SIZEX and SIZEY parameters in ")+part1+
tr(" to match the geometry defined in the RAW file: ")+part2,
QMessageBox::Ok);
}
else if (trigger == "Data::WEIGHT_DATA_NOT_FOUND") {
QMessageBox::warning(this, tr("Missing weight images"),
tr("The following ")+part1+tr(" images do not have a matching weight image (WEIGHTS/*weight.fits):\n")+part2,
QMessageBox::Ok);
}
else if (trigger == "Data::HEADER_DATA_NOT_FOUND") {
QMessageBox::warning(this, tr("Missing astrometric headers"),
tr("The following ")+part1+tr(" images do not have matching astrometric headers (headers/*.head):\n")+part2,
QMessageBox::Ok);
}
else if (trigger == "Data::SCAMP_CATS_NOT_FOUND") {
QMessageBox::warning(this, tr("Missing scamp catalogs"),
tr("The following ")+part1+tr(" images do not have matching scamp catalogs (cat/*.scamp). The corresponding exposures will be deactivated:\n")+part2,
QMessageBox::Ok);
}
else if (trigger == "Controller::BACKGROUND_PARALLELIZATION") {
QMessageBox::warning(this, tr("Parallelization unstable"),
tr("You are running the background modelling with more than 1 CPU. ") +
tr("Currently, this is the only task that is still unstable when run in parallel, and random crashes may occur. ") +
tr("Use a single CPU if you have problems. Once background modeling is done, you can revert to full parallelization."),
QMessageBox::Ok);
}
else if (trigger == "DATA::RAW_AND_PROCESSED_FOUND") {
QMessageBox::warning(this, tr("Invalid data mix"),
tr("Both processed and RAW files were found. This status is not allowed. ") +
tr("You must manually clean up the data in ") + part1,
QMessageBox::Ok);
}
else if (trigger == "Data::BACKUP_DATA_NOT_FOUND") {
QString warningText = "";
warningText = tr("You were about to repeat a processing task.") + " "
+tr("However, THELI could not find the data with the previous processing state, neither in memory nor in the backup folders on your drive.") + " "
+tr("You have the following options:")
+ "\n(1) "+tr("Do not repeat this task and continue processing")
+ "\n(2) "+tr("Restore a previous state from within the memory viewer")
+ "\n(3) "+tr("Manually restore FITS files from a backup directory and restart THELI");
QMessageBox::warning(this, tr("ERROR: Failed to locate backup data"), warningText, QMessageBox::Ok);
}
}
void MainWindow::resetProcessingErrorFlags()
{
GAP_DYNAMIC_FOUND_shown = false;
WINDOWSIZE_TOO_LARGE_shown = false;
INSUFFICIENT_BACKGROUND_NUMBER_shown = false;
SKY_FILE_NOT_FOUND_shown = false;
NO_OVERLAP_WITH_SKYAREA_shown = false;
}
| 16,254
|
C++
|
.cc
| 255
| 48.282353
| 178
| 0.572295
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,407
|
instrumentdefinition.cc
|
schirmermischa_THELI/src/instrumentdefinition.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "instrumentdefinition.h"
#include "ui_instrumentdefinition.h"
#include "functions.h"
#include "libraw/libraw.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QTimer>
Instrument::Instrument(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Instrument)
{
ui->setupUi(this);
geometryList.append(ui->overscanxMinLineEdit);
geometryList.append(ui->overscanxMaxLineEdit);
geometryList.append(ui->overscanyMinLineEdit);
geometryList.append(ui->overscanyMaxLineEdit);
geometryList.append(ui->startxLineEdit);
geometryList.append(ui->startyLineEdit);
geometryList.append(ui->sizexLineEdit);
geometryList.append(ui->sizeyLineEdit);
geometryList.append(ui->crpix1LineEdit);
geometryList.append(ui->crpix2LineEdit);
geometryNumList.append(ui->overscanxMinNumLineEdit);
geometryNumList.append(ui->overscanxMaxNumLineEdit);
geometryNumList.append(ui->overscanyMinNumLineEdit);
geometryNumList.append(ui->overscanyMaxNumLineEdit);
geometryNumList.append(ui->startxNumLineEdit);
geometryNumList.append(ui->startyNumLineEdit);
geometryNumList.append(ui->sizexNumLineEdit);
geometryNumList.append(ui->sizeyNumLineEdit);
geometryNumList.append(ui->crpix1NumLineEdit);
geometryNumList.append(ui->crpix2NumLineEdit);
for (auto &it: geometryList) {
connect(it, &QLineEdit::textChanged, this, &Instrument::validate);
connect(it, &QLineEdit::textChanged, this, &Instrument::paintNumLineEdits);
}
connect(ui->latitudeLineEdit, &QLineEdit::textChanged, this, &Instrument::validate);
connect(ui->longitudeLineEdit, &QLineEdit::textChanged, this, &Instrument::validate);
connect(ui->plateScaleLineEdit, &QLineEdit::textChanged, this, &Instrument::validate);
connect(ui->instrumentNameLineEdit, &QLineEdit::textChanged, this, &Instrument::validate);
connect(ui->bayerRGGBToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons);
connect(ui->bayerGBRGToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons);
connect(ui->bayerBGGRToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons);
connect(ui->bayerGRBGToolButton, &QToolButton::clicked, this, &Instrument::toggle_bayer_ToolButtons);
initEnvironment(thelidir, userdir);
ui->bayerCheckBox->setChecked(false);
bayerButtonGroup->addButton(ui->bayerGBRGToolButton);
bayerButtonGroup->addButton(ui->bayerRGGBToolButton);
bayerButtonGroup->addButton(ui->bayerBGGRToolButton);
bayerButtonGroup->addButton(ui->bayerGRBGToolButton);
bayerButtonGroup->setExclusive(true);
ui->bayerGBRGToolButton->setIcon(QIcon(":/icons/bayer_gbrg.png"));
ui->bayerRGGBToolButton->setIcon(QIcon(":/icons/bayer_rggb.png"));
ui->bayerBGGRToolButton->setIcon(QIcon(":/icons/bayer_bggr.png"));
ui->bayerGRBGToolButton->setIcon(QIcon(":/icons/bayer_grbg.png"));
ui->buttonFrame->hide();
paintNumLineEdits("");
setWindowIcon(QIcon(":/icons/addInst.png"));
applyStyleSheets();
QButtonGroup formatButtonGroup;
formatButtonGroup.addButton(ui->formatFITSRadioButton);
formatButtonGroup.addButton(ui->formatRAWRadioButton);
formatButtonGroup.setExclusive(true);
connect(ui->formatFITSRadioButton, &QRadioButton::clicked, this, &Instrument::toggleFormatPushButton);
connect(ui->formatRAWRadioButton, &QRadioButton::clicked, this, &Instrument::toggleFormatPushButton);
toggleFormatPushButton();
}
Instrument::~Instrument()
{
delete ui;
}
void Instrument::applyStyleSheets()
{
/*
QList<QLabel*> titleList;
titleList.append(ui->title1Label);
for (auto &it : titleList) {
it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);");
it->setMargin(8);
}
*/
QList<QLabel*> subtitleList;
subtitleList.append(ui->subtitle1Label);
subtitleList.append(ui->subtitle2Label);
for (auto &it : subtitleList) {
it->setStyleSheet("color: rgb(150, 240, 240); background-color: rgb(58, 78, 98);");
it->setMargin(8);
// it->setStyleSheet("background-color: rgb(190,190,210);");
// it->setMargin(4);
}
QList<QFrame*> frameList;
frameList.append(ui->inst1Frame);
frameList.append(ui->inst2Frame);
frameList.append(ui->inst6Frame);
/*
for (auto &it : frameList) {
// it->setStyleSheet("background-color: #ebebee;");
// nothing yet
}
*/
QList<QToolButton*> buttonList;
buttonList.append(ui->bayerBGGRToolButton);
buttonList.append(ui->bayerRGGBToolButton);
buttonList.append(ui->bayerGBRGToolButton);
buttonList.append(ui->bayerGRBGToolButton);
/*
for (auto &it : buttonList) {
//
}
*/
}
void Instrument::toggleFormatPushButton()
{
if (ui->formatFITSRadioButton->isChecked()) {
ui->readRAWgeometryPushButton->setDisabled(true);
ui->overscanxMinLineEdit->setEnabled(true);
ui->overscanxMaxLineEdit->setEnabled(true);
ui->overscanyMinLineEdit->setEnabled(true);
ui->overscanyMaxLineEdit->setEnabled(true);
ui->startxLineEdit->setEnabled(true);
ui->startyLineEdit->setEnabled(true);
ui->sizexLineEdit->setEnabled(true);
ui->sizeyLineEdit->setEnabled(true);
ui->crpix1LineEdit->setEnabled(true);
ui->crpix2LineEdit->setEnabled(true);
}
else {
ui->readRAWgeometryPushButton->setEnabled(true);
ui->overscanxMinLineEdit->setDisabled(true);
ui->overscanxMaxLineEdit->setDisabled(true);
ui->overscanyMinLineEdit->setDisabled(true);
ui->overscanyMaxLineEdit->setDisabled(true);
ui->startxLineEdit->setDisabled(true);
ui->startyLineEdit->setDisabled(true);
ui->sizexLineEdit->setDisabled(true);
ui->sizeyLineEdit->setDisabled(true);
ui->crpix1LineEdit->setDisabled(true);
ui->crpix2LineEdit->setDisabled(true);
}
}
void Instrument::toggle_bayer_ToolButtons()
{
QToolButton *toolbutton = qobject_cast<QToolButton*>(sender());
QString sender_name = toolbutton->objectName();
if (toolbutton->isChecked()) this->setStyleSheet("QToolButton#"+sender_name+" { background-color: black }");
else this->setStyleSheet("QToolButton#"+sender_name+" { background-color: #ddddddd }");
}
void Instrument::paintNumLineEdits(QString geometry)
{
QPalette paletteMatch;
QPalette paletteNoMatch;
paletteMatch.setColor(QPalette::Base,QColor("#a9ffe6"));
paletteNoMatch.setColor(QPalette::Base,QColor("#ff99aa"));
int numEntries;
geometry = geometry.simplified();
// Triggered by LineEdit changed
QLineEdit *le = qobject_cast<QLineEdit*>(sender());
if (le != 0) {
if (geometry.isEmpty()) numEntries = 0;
else numEntries = geometry.split(' ').length();
for (int i=0; i<geometryList.length(); ++i) {
if (le->objectName() == geometryList.at(i)->objectName()) {
if (numEntries == ui->numchipSpinBox->value()) geometryNumList.at(i)->setPalette(paletteMatch);
else geometryNumList.at(i)->setPalette(paletteNoMatch);
geometryNumList.at(i)->setText(QString::number(numEntries));
}
}
}
else {
// Triggered by numchipSpinBox value changed
for (int i=0; i<geometryList.length(); ++i) {
if (geometryList.at(i)->text().isEmpty()) numEntries = 0;
else numEntries = geometryList.at(i)->text().split(' ').length();
if (numEntries == ui->numchipSpinBox->value()) geometryNumList.at(i)->setPalette(paletteMatch);
else geometryNumList.at(i)->setPalette(paletteNoMatch);
geometryNumList.at(i)->setText(QString::number(numEntries));
}
}
}
void Instrument::on_numchipSpinBox_valueChanged(int arg1)
{
numChips = arg1;
paintNumLineEdits("");
if (arg1 == 1) ui->flipComboBox->setEnabled(true);
else ui->flipComboBox->setDisabled(true);
}
void Instrument::validate(QString arg1)
{
if (arg1.isEmpty()) return;
QRegExp rf1( "[-0-9.]+" );
QValidator* validator_float = new QRegExpValidator(rf1, this );
QRegExp re( "[-0-9e.]+" );
QRegExp rf2( "[0-9.]+" );
QValidator* validator_floatpos = new QRegExpValidator(rf2, this );
QRegExp ri3( "[0-9\\s]+" );
QValidator* validator_intposblank = new QRegExpValidator(ri3, this );
QRegExp ri4( "[-0-9\\s]+" );
QValidator* validator_intblank = new QRegExpValidator(ri4, this );
ui->latitudeLineEdit->setValidator( validator_float );
ui->longitudeLineEdit->setValidator( validator_float );
// ui->gainLineEdit->setValidator( validator_floatpos );
ui->plateScaleLineEdit->setValidator( validator_floatpos );
ui->overscanxMinLineEdit->setValidator( validator_intposblank );
ui->overscanxMaxLineEdit->setValidator( validator_intposblank);
ui->overscanyMinLineEdit->setValidator( validator_intposblank );
ui->overscanyMaxLineEdit->setValidator( validator_intposblank);
ui->startxLineEdit->setValidator( validator_intposblank );
ui->startyLineEdit->setValidator( validator_intposblank );
ui->sizexLineEdit->setValidator( validator_intposblank );
ui->sizeyLineEdit->setValidator( validator_intposblank );
ui->crpix1LineEdit->setValidator( validator_intblank );
ui->crpix2LineEdit->setValidator( validator_intblank );
// instrument name must not accept blank characters
// QRegExp rx2( "^\\S+$" );
QRegExp rx2( "[A-Za-z0-9@_-+]+" );
QValidator* validator_string2 = new QRegExpValidator( rx2, this );
ui->instrumentNameLineEdit->setValidator( validator_string2 );
}
QString Instrument::geometryToConfig(QString geometry)
{
// Transforms the entered blank-separated geometry to a bash array
QStringList list = geometry.simplified().split(' ');
QString bashArray = "";
int i=1;
for (auto &it : list) {
bashArray.append("["+QString::number(i)+"]="+it+" ");
++i;
}
bashArray = bashArray.simplified();
bashArray.prepend("(");
bashArray.append(")");
return bashArray;
}
QString Instrument::configToGeometry(QString config)
{
// Transforms the bash vector to a blank-separated list
config = config.remove("(");
config = config.remove(")");
config = config.remove("[");
config = config.remove("]");
config = config.replace('=',' ');
QStringList list = config.simplified().split(' ');
QString geometry = "";
// Keep every second word, only
int i=1;
for (auto &it : list) {
if (! (i%2)) geometry.append(it+" ");
++i;
}
return geometry.simplified();
}
void Instrument::on_saveConfigPushButton_clicked()
{
QString instrumentName = ui->instrumentNameLineEdit->text();
QString filePath = QDir::homePath()+"/.theli/instruments_user/"+instrumentName+".ini";
QFile configfile(filePath);
if (!compareChipNumbers()) {
QMessageBox::warning( this, "Mismatch in detector numbers",
"<b>Warning:</b><br> The number of entries in one or more of the\n"
"detector geometries does not match the number of chips declared for the camera.<br>\n");
return;
}
if (configfile.exists()) {
QMessageBox msgBox;
msgBox.setText("A configuration file for "+instrumentName+" already exists.");
QAbstractButton* overwrite = msgBox.addButton(tr("Overwrite"), QMessageBox::YesRole);
QAbstractButton* cancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole);
msgBox.exec();
if (msgBox.clickedButton() == overwrite) {
// do nothing
}
else if (msgBox.clickedButton() == cancel) return;
}
QString pixscale = ui->plateScaleLineEdit->text();
if (pixscale.isEmpty() || pixscale.toFloat() <= 0.) {
QMessageBox msgBox;
msgBox.setText("Invalid pixel scale provided: "+pixscale+"\nSet to 1.0 arcsec / pixel.");
QAbstractButton* ok = msgBox.addButton(tr("OK"), QMessageBox::YesRole);
QAbstractButton* cancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole);
msgBox.exec();
if (msgBox.clickedButton() == ok) {
ui->plateScaleLineEdit->setText("1.0");
}
else if (msgBox.clickedButton() == cancel) return;
}
if (configfile.open(QIODevice::WriteOnly)) {
QTextStream outputStream(&configfile);
outputStream << "INSTRUMENT=" << instrumentName << "\n";
outputStream << "NCHIPS=" << ui->numchipSpinBox->value() << "\n";
outputStream << "# Geographic location\n";
outputStream << "OBSLAT=" << ui->latitudeLineEdit->text() << "\n";
outputStream << "OBSLONG=" << ui->longitudeLineEdit->text() << "\n\n";
outputStream << "# Plate scale\n";
outputStream << "PIXSCALE=" << ui->plateScaleLineEdit->text().toFloat() << "\n\n";
outputStream << "# Detector gain (lowest gain for a multi-detector instrument, i.e. brightest image)\n";
outputStream << "# Detector geometries\n";
outputStream << "OVSCANX1=" << geometryToConfig(ui->overscanxMinLineEdit->text()) << "\n";
outputStream << "OVSCANX2=" << geometryToConfig(ui->overscanxMaxLineEdit->text()) << "\n";
outputStream << "OVSCANY1=" << geometryToConfig(ui->overscanyMinLineEdit->text()) << "\n";
outputStream << "OVSCANY2=" << geometryToConfig(ui->overscanyMaxLineEdit->text()) << "\n";
if (!ui->bayerCheckBox->isChecked()) {
outputStream << "CUTX=" << geometryToConfig(ui->startxLineEdit->text()) << "\n";
outputStream << "CUTY=" << geometryToConfig(ui->startyLineEdit->text()) << "\n";
outputStream << "SIZEX=" << geometryToConfig(ui->sizexLineEdit->text()) << "\n";
outputStream << "SIZEY=" << geometryToConfig(ui->sizeyLineEdit->text()) << "\n";
}
else {
// WARNING: foregoing multi-chip support, assuming single chip
long cutx = ui->startxLineEdit->text().simplified().toLong();
long cuty = ui->startyLineEdit->text().simplified().toLong();
long sizex = ui->sizexLineEdit->text().simplified().toLong();
long sizey = ui->sizeyLineEdit->text().simplified().toLong();
// enforcing even-numbered geometry
if (sizex % 2 != 0) {
ui->startxLineEdit->setText(QString::number(cutx+1));
ui->sizexLineEdit->setText(QString::number(sizex-1));
}
if (sizey % 2 != 0) {
ui->startyLineEdit->setText(QString::number(cuty+1));
ui->sizeyLineEdit->setText(QString::number(sizey-1));
}
outputStream << "CUTX=" << geometryToConfig(ui->startxLineEdit->text()) << "\n";
outputStream << "CUTY=" << geometryToConfig(ui->startyLineEdit->text()) << "\n";
outputStream << "SIZEX=" << geometryToConfig(ui->sizexLineEdit->text()) << "\n";
outputStream << "SIZEY=" << geometryToConfig(ui->sizeyLineEdit->text()) << "\n";
}
outputStream << "REFPIXX=" << geometryToConfig(ui->crpix1LineEdit->text()) << "\n";
outputStream << "REFPIXY=" << geometryToConfig(ui->crpix2LineEdit->text()) << "\n\n";
outputStream << "# Camera type\n";
QString type;
if (ui->instrumentTypeComboBox->currentIndex() == 0) type = "OPT";
else if (ui->instrumentTypeComboBox->currentIndex() == 1) type = "NIR";
else if (ui->instrumentTypeComboBox->currentIndex() == 2) type = "NIRMIR";
else if (ui->instrumentTypeComboBox->currentIndex() == 3) type = "MIR";
else type = "OPT";
outputStream << "TYPE=" << type << "\n";
if (ui->bayerCheckBox->isChecked()) {
int checkedId = bayerButtonGroup->checkedId();
if (checkedId == -1) checkedId = 1;
QString bayerPattern = bayerButtonGroup->button(checkedId)->objectName().remove("bayer").remove("ToolButton");
outputStream << "BAYER=" << bayerPattern << "\n";
}
if (ui->flipComboBox->currentIndex() == 0) outputStream << "FLIP=NOFLIP" << "\n";
else if (ui->flipComboBox->currentIndex() == 1) outputStream << "FLIP=FLIPX" << "\n";
else if (ui->flipComboBox->currentIndex() == 2) outputStream << "FLIP=FLIPY" << "\n";
else if (ui->flipComboBox->currentIndex() == 3) outputStream << "FLIP=ROT180" << "\n";
configfile.close();
// change the text label of the pushbutton for a short while
ui->saveConfigPushButton->setText("Done");
QTimer *timer = new QTimer();
connect( timer, SIGNAL(timeout()), SLOT(timerConfigDone()) );
timer->start(1000);
}
else {
QMessageBox msgBox;
msgBox.setText(filePath+" could not be opened for writing!");
msgBox.exec();
return;
}
QMessageBox::information( this, "Restart required",
tr("User-defined instrument configurations can be found at the bottom of the instrument selection menu after restarting THELI.\n") +
tr("If you edited an existing configuration, you must also restart THELI."));
}
void Instrument::on_instrumentTypeComboBox_currentIndexChanged(int index)
{
if (index == 0) {
ui->bayerCheckBox->setEnabled(true);
if (ui->bayerCheckBox->isChecked()) ui->buttonFrame->show();
ui->overscanxMinLineEdit->setEnabled(true);
ui->overscanxMaxLineEdit->setEnabled(true);
ui->overscanyMinLineEdit->setEnabled(true);
ui->overscanyMaxLineEdit->setEnabled(true);
ui->overscanxMinNumLineEdit->setEnabled(true);
ui->overscanxMaxNumLineEdit->setEnabled(true);
ui->overscanyMinNumLineEdit->setEnabled(true);
ui->overscanyMaxNumLineEdit->setEnabled(true);
}
else {
// Turn off ovserscan for NIR data
ui->bayerCheckBox->setDisabled(true);
ui->bayerCheckBox->setChecked(false);
ui->buttonFrame->hide();
ui->overscanxMinLineEdit->setEnabled(false);
ui->overscanxMaxLineEdit->setEnabled(false);
ui->overscanyMinLineEdit->setEnabled(false);
ui->overscanyMaxLineEdit->setEnabled(false);
ui->overscanxMinNumLineEdit->setEnabled(false);
ui->overscanxMaxNumLineEdit->setEnabled(false);
ui->overscanyMinNumLineEdit->setEnabled(false);
ui->overscanyMaxNumLineEdit->setEnabled(false);
}
}
void Instrument::on_loadConfigPushButton_clicked()
{
QString instrumentDir;
QMessageBox msgBox;
msgBox.setText("Which instrument type do you want to load?");
QAbstractButton* observatory = msgBox.addButton(tr("Observatory"), QMessageBox::YesRole);
QAbstractButton* userdefined = msgBox.addButton(tr("User defined"), QMessageBox::YesRole);
QAbstractButton* cancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole);
msgBox.exec();
if (msgBox.clickedButton() == observatory) instrumentDir = thelidir+"/config/instruments/";
else if (msgBox.clickedButton() == userdefined) instrumentDir = QDir::homePath()+"/.theli/instruments_user/";
else if (msgBox.clickedButton() == cancel) return;
QString instrumentFilename =
QFileDialog::getOpenFileName(this, tr("Select instrument configuration file"), instrumentDir,
tr("Instrument configuration file (*.ini)"));
if ( instrumentFilename.isEmpty()) return;
// Parse the configuration file
QString line;
QStringList list;
QString keyword;
QString keyvalue;
QFile instrumentFile(instrumentFilename);
if ( instrumentFile.open(QIODevice::ReadOnly)) {
QTextStream stream( &instrumentFile );
// For backwards compatibility (not all config files contain these keywords):
ui->bayerCheckBox->setChecked(false);
// ui->gainLineEdit->setText("1.0");
ui->longitudeLineEdit->setText("0");
ui->flipComboBox->setCurrentIndex(0);
while ( !stream.atEnd() ) {
line = stream.readLine().simplified();
// skip comments
if (line.contains("#") || line.isEmpty() || !line.contains("=")) continue;
if (line.contains("=(")) {
list = line.split("=(");
keyword = list.at(0);
keyvalue = list.at(1);
keyvalue = configToGeometry(keyvalue);
}
else {
list = line.split("=");
keyword = list.at(0);
keyvalue = list.at(1);
}
if (keyword == "INSTRUMENT") ui->instrumentNameLineEdit->setText(keyvalue);
if (keyword == "NCHIPS") {
ui->numchipSpinBox->setValue(keyvalue.toInt());
numChips = keyvalue.toInt();
}
if (keyword == "OBSLAT") ui->latitudeLineEdit->setText(keyvalue);
if (keyword == "OBSLONG") ui->longitudeLineEdit->setText(keyvalue);
if (keyword == "PIXSCALE") ui->plateScaleLineEdit->setText(keyvalue);
// if (keyword == "GAIN") ui->gainLineEdit->setText(keyvalue);
if (keyword == "OVSCANX1") ui->overscanxMinLineEdit->setText(keyvalue);
if (keyword == "OVSCANX2") ui->overscanxMaxLineEdit->setText(keyvalue);
if (keyword == "OVSCANY1") ui->overscanyMinLineEdit->setText(keyvalue);
if (keyword == "OVSCANY2") ui->overscanyMaxLineEdit->setText(keyvalue);
if (keyword == "CUTX") ui->startxLineEdit->setText(keyvalue);
if (keyword == "CUTY") ui->startyLineEdit->setText(keyvalue);
if (keyword == "SIZEX") ui->sizexLineEdit->setText(keyvalue);
if (keyword == "SIZEY") ui->sizeyLineEdit->setText(keyvalue);
if (keyword == "REFPIXX") ui->crpix1LineEdit->setText(keyvalue);
if (keyword == "REFPIXY") ui->crpix2LineEdit->setText(keyvalue);
if (keyword == "TYPE") {
if (keyvalue == "OPT") ui->instrumentTypeComboBox->setCurrentIndex(0);
else if (keyvalue == "NIR") ui->instrumentTypeComboBox->setCurrentIndex(1);
else if (keyvalue == "NIRMIR") ui->instrumentTypeComboBox->setCurrentIndex(2);
else if (keyvalue == "MIR") ui->instrumentTypeComboBox->setCurrentIndex(3);
else ui->instrumentTypeComboBox->setCurrentIndex(0);
if (keyvalue == "OPT") ui->bayerCheckBox->setEnabled(true);
else ui->bayerCheckBox->setDisabled(true);
}
if (keyword == "BAYER") {
if (keyvalue == "N") ui->bayerCheckBox->setChecked(false);
else {
ui->bayerCheckBox->setChecked(true);
ui->buttonFrame->show();
}
}
if (keyword == "FLIP") {
if (keyvalue == "NOFLIP") ui->flipComboBox->setCurrentIndex(0);
else if (keyvalue == "FLIPX") ui->flipComboBox->setCurrentIndex(1);
else if (keyvalue == "FLIPY") ui->flipComboBox->setCurrentIndex(2);
else if (keyvalue == "ROT180") ui->flipComboBox->setCurrentIndex(3);
}
}
instrumentFile.close();
}
}
bool Instrument::compareChipNumbers()
{
bool comparison = true;
int count = 0;
for (auto &it: geometryNumList) {
// skip the first four entries for overscans for NIR detectors
if (ui->instrumentTypeComboBox->currentIndex() != 0 && count < 4) continue;
if (numChips != it->text().toInt()) comparison = false;
++count;
}
return comparison;
}
void Instrument::altStream(QTextStream &stream, QString keyword, QString altValue)
{
stream << " if [ \"${"+keyword+"}\"_A = \"_A\" ]; then\n";
stream << " "+keyword+"="+altValue+"\n";
stream << " fi\n\n";
}
void Instrument::getKey(QTextStream &stream, QString bashkey, QString fitsKey, QString mode)
{
if (mode.isEmpty()) {
stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\"`\n";
}
else if (mode == "cleanstring") {
stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\" | ${P_CLEANSTRING}`\n";
}
else if (mode == "cleancolon") {
stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\" cleancolon`\n";
}
else if (mode == "equinox") {
// Remove first char if not numeric
stream << " "+bashkey+"=`get_key ${FILE} \""+fitsKey+"\" | sed 's/[^0-9.]//g'`\n";
}
}
void Instrument::truncateFITSkey(QString &key)
{
int length = key.length();
if (length == 8) return;
if (length > 8) {
key = key.left(8);
return;
}
if (length < 8) {
while (length < 8) {
key = key.append(" ");
length = key.length();
}
}
}
void Instrument::timerConfigDone()
{
ui->saveConfigPushButton->setText("Save instrument config");
}
void Instrument::on_clearPushButton_clicked()
{
QList<QLineEdit*> lineeditList;
lineeditList.append(ui->crpix1LineEdit);
lineeditList.append(ui->crpix1NumLineEdit);
lineeditList.append(ui->crpix2LineEdit);
lineeditList.append(ui->crpix2NumLineEdit);
// lineeditList.append(ui->gainLineEdit);
lineeditList.append(ui->instrumentNameLineEdit);
lineeditList.append(ui->latitudeLineEdit);
lineeditList.append(ui->longitudeLineEdit);
lineeditList.append(ui->optionalKeysLineEdit);
lineeditList.append(ui->overscanxMaxLineEdit);
lineeditList.append(ui->overscanxMaxNumLineEdit);
lineeditList.append(ui->overscanxMinLineEdit);
lineeditList.append(ui->overscanxMinNumLineEdit);
lineeditList.append(ui->overscanyMaxLineEdit);
lineeditList.append(ui->overscanyMaxNumLineEdit);
lineeditList.append(ui->overscanyMinLineEdit);
lineeditList.append(ui->overscanyMinNumLineEdit);
lineeditList.append(ui->plateScaleLineEdit);
lineeditList.append(ui->sizexLineEdit);
lineeditList.append(ui->sizexNumLineEdit);
lineeditList.append(ui->sizeyLineEdit);
lineeditList.append(ui->sizeyNumLineEdit);
lineeditList.append(ui->startxLineEdit);
lineeditList.append(ui->startxNumLineEdit);
lineeditList.append(ui->startyLineEdit);
lineeditList.append(ui->startyNumLineEdit);
// Clear line edits
for (auto &it : lineeditList) {
it->clear();
}
}
void Instrument::on_bayerCheckBox_clicked(bool checked)
{
if (checked) {
ui->bayerRGGBToolButton->setDown(true); // not effective?
ui->buttonFrame->show();
}
else ui->buttonFrame->hide();
}
void Instrument::on_actionClose_triggered()
{
this->close();
}
void Instrument::on_readRAWgeometryPushButton_clicked()
{
QString rawFileName = QFileDialog::getOpenFileName(this, tr("Select a CMOS RAW file"), QDir::homePath(),
tr("CMOS RAW files (*.CR2 *.ARW *.DNG *.NEF *.PEF *.cr2 *.arw *.dng *.nef *.pef);; Other (*.*)"));
// Try opening as RAW
LibRaw rawProcessor;
int ret = rawProcessor.open_file((rawFileName).toUtf8().data());
if (ret == LIBRAW_SUCCESS) {
// Opened. Try unpacking
bool unpack = rawProcessor.unpack();
if (unpack != LIBRAW_SUCCESS) {
QMessageBox::warning( this, "Unknown RAW format",
"The file chosen does not have a recognized CMOS RAW format.");
return;
}
}
#define S rawProcessor.imgdata.sizes
// Extract pixels
/*
long naxis1Raw = S.raw_width;
long naxis2Raw = S.raw_height;
long naxis1 = S.iwidth;
long naxis2 = S.iheight;
*/
ui->overscanxMinLineEdit->setText("1");
ui->overscanxMaxLineEdit->setText(QString::number(S.left_margin));
ui->overscanyMinLineEdit->setText("1");
ui->overscanyMaxLineEdit->setText(QString::number(S.top_margin));
// enforce even geometry
if (S.iwidth % 2 != 0) {
S.iwidth -= 1;
S.left_margin += 1;
}
if (S.iheight % 2 != 0) {
S.iheight -= 1;
S.top_margin += 1;
}
ui->startxLineEdit->setText(QString::number(S.left_margin+1));
ui->startyLineEdit->setText(QString::number(S.top_margin+1));
ui->sizexLineEdit->setText(QString::number(S.iwidth));
ui->sizeyLineEdit->setText(QString::number(S.iheight));
ui->crpix1LineEdit->setText(QString::number(S.iwidth/2));
ui->crpix2LineEdit->setText(QString::number(S.iheight/2));
}
| 29,332
|
C++
|
.cc
| 638
| 38.62069
| 162
| 0.652343
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,408
|
main.cc
|
schirmermischa_THELI/src/main.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mainwindow.h"
#include "functions.h"
#include <QApplication>
#include <QMessageBox>
#include <QDir>
#include <QFile>
#include <QDebug>
#include <QString>
#include <QStringList>
#include <QDebug>
#include <QCoreApplication>
#include <QStandardPaths>
#include <omp.h>
#include "fitsio.h"
void dependencyCheck();
void compatibilityCheck();
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
std::locale::global( std::locale( "C" ) );
// Read the THELIDIR environment variable
if (!QProcessEnvironment::systemEnvironment().contains("THELIDIR")) {
// See if we can find it under /usr/share/theli/
QDir thelidir1("/usr/share/theli/config/");
QDir thelidir2("/usr/share/theli/python/");
if (thelidir1.exists() && thelidir2.exists()) {
// system-wide installation found, we are good!
}
else {
QMessageBox::critical(0,"THELI","THELI configuration files not found under /usr/share/theli/\n\n"
"You can fix this by setting the THELIDIR environment variable. For example, if the THELI source tree was installed under \n"
""+QDir::homePath()+"/THELI/ and you are using the 'bash' shell, "
"then you would include the following line in your .bashrc file:\n\n"
"export THELIDIR="+QDir::homePath()+"/THELI/",
QMessageBox::Ok);
exit (1);
}
}
// Dependency checks
dependencyCheck();
// Compatibility checks
compatibilityCheck();
// Required when starting the first time
QString dotTheliName = QDir::homePath()+"/.theli/";
QDir dotTheli(dotTheliName);
dotTheli.mkdir(dotTheliName);
dotTheli.mkdir(dotTheliName+"/instruments_user");
// Fetch the process ID of the main program
QString mainPID = QString::number(QCoreApplication::applicationPid());
MainWindow w(mainPID);
w.show();
return a.exec();
}
void dependencyCheck()
{
// Dependency checks
QString scamp = findExecutableName("scamp"); // testing different executable names
QString swarp = findExecutableName("swarp");
QString sourceExtractor = findExecutableName("source-extractor");
QString python = findExecutableName("python");
QString anet1 = findExecutableName("build-astrometry-index");
QString anet2 = findExecutableName("solve-field");
QString anet3 = findExecutableName("astrometry-engine");
QString scampDep = "";
QString swarpDep = "";
QString sourceExtractorDep = "";
QString anetDep = "";
QString pythonDep = "";
int missingDep = 0;
if (anet1.isEmpty()) {
anetDep += "astrometry.net 'build-astrometry-index' not found.\n";
}
if (anet2.isEmpty()) {
anetDep = "astrometry.net 'solve-field' not found.\n";
}
// if (anet3.isEmpty()) {
// anetDep += "astrometry.net 'astrometry-engine' not found.\n";
// }
if (python.isEmpty()) {
pythonDep = "python v3 required (working binary names: 'python3' or 'python').\n";
}
else {
// Check that we are using python3
QString pythonCommand = python + " --version";
QString result = read_system_command(pythonCommand);
QStringList list = result.split(" ");
if (list.length() > 1) {
int version = list.at(1).split('.').at(0).toInt();
if (version < 3) {
pythonDep = "python v3 or later required. Installed version: " + result + "\n";
++missingDep;
}
}
}
if (!anetDep.isEmpty()) {
qDebug() << "Astrometry.net installation was not found. Corresponding solvers are deactivated.";
qDebug() << "Astrometry.net is available at https://github.com/dstndstn/astrometry.net/releases\n";
}
if (scamp.isEmpty()) {
scampDep = "'Scamp' v2.0.4 or later required (working binary names: 'scamp' or 'Scamp').\n\nhttps://github.com/astromatic/scamp\n";
++missingDep;
}
else {
// Check if scamp has the right version
QString scampCommand = scamp + " -v";
QString result = read_system_command(scampCommand);
QStringList list = result.split(" ");
if (list.length() < 3) {
qDebug() << "WARNING: Unexpected output format when checking Scamp version:" << result;
qDebug() << "WARNING: Required version: 2.0.4 or later";
}
else {
// Minimum scamp version required: 2.0.4
int version = list[2].remove('.').toInt();
if (version < 204) {
scampDep = "'Scamp' v2.0.4 or later required.\n\nhttps://github.com/astromatic/scamp\nInstalled: " + result + "\n";
++missingDep;
}
}
}
if (swarp.isEmpty()) {
swarpDep = "'Swarp' v2.38.0 or later required (working binary names: 'swarp', 'Swarp' or 'SWarp').\n\nhttps://github.com/astromatic/swarp\n";
++missingDep;
}
else {
// Check if swarp has the right version
QString swarpCommand = swarp + " -v";
QString result = read_system_command(swarpCommand);
QStringList list = result.split(" ");
if (list.length() < 3) {
qDebug() << "WARNING: Unexpected output format when checking swarp version:" << result;
qDebug() << "WARNING: Required version: 2.38.0 or later";
}
else {
// Minimum swarp version required: 2.38.0
int version = list[2].remove('.').toInt();
if (version < 2380) {
swarpDep = "'swarp' v2.38.0 or later required.\n\nhttps://github.com/astromatic/swarp\nInstalled: " + result + "\n";
++missingDep;
}
}
}
if (sourceExtractor.isEmpty()) {
sourceExtractorDep = "'Source Extractor' v2.19.5 or later required (working binary names: 'source-extractor', 'sextractor', 'SExtractor', or 'sex'), available from\nhttps://github.com/astromatic/sextractor\n";
++missingDep;
}
else {
// Check if Source Extractor has the right version
// expected formats are:
// Source Extractor version 2.25.0 (2020-03-19)
// Source Extractor version 2.25.0 (2018-02-08)
QString sourceExtractorCommand = sourceExtractor + " -v";
QString result = read_system_command(sourceExtractorCommand);
QString resultOrig = result;
result.remove("SExtractor", Qt::CaseInsensitive);
result.remove("Source", Qt::CaseInsensitive);
result.remove("Extractor", Qt::CaseInsensitive);
result.remove("version", Qt::CaseInsensitive);
result = result.simplified();
QStringList list = result.split(" ");
if (list.length() != 2) {
qDebug() << "WARNING: Unexpected output format when checking Source Extractor version:" << resultOrig;
qDebug() << "WARNING: Required version: 2.19.5 or later";
}
else {
// Minimum Source Extractor version required: 2.19.5
int version = list[0].remove('.').toInt();
if (version < 2195) {
sourceExtractorDep = "'Source Extractor' v2.19.5 or later required.\n\nhttps://github.com/astromatic/sextractor\nInstalled: " + result + "\n";
++missingDep;
}
}
}
if (missingDep == 0) return;
QString title = "Missing dependency:\n\n";
if (missingDep > 1) title = "Missing dependencies:\n\n";
QMessageBox::critical(0, "THELI", title
+scampDep
+swarpDep
+pythonDep
+sourceExtractorDep,
QMessageBox::Ok);
exit (1);
}
void compatibilityCheck()
{
if (!fits_is_reentrant()) {
QMessageBox msgBox;
msgBox.setText("CFITSIO library not reentrant!");
msgBox.setInformativeText("Your cfitsio library does not support parallelization. The maximum number of usable CPUs has been limited to 1.\n\n"
"To use parallelization, recompile the cfitsio library using\n\n"
"./configure --enable-reentrant");
msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Abort);
msgBox.setDefaultButton(QMessageBox::Ok);
int ret = msgBox.exec();
switch (ret) {
case QMessageBox::Abort:
exit (1);
case QMessageBox::Ok:
break;
default:
// should never be reached
break;
}
}
}
| 9,476
|
C++
|
.cc
| 220
| 34.118182
| 217
| 0.608545
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,409
|
validators.cc
|
schirmermischa_THELI/src/validators.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QValidator>
#include <QRegExpValidator>
void MainWindow::validate()
{
QRegExp rx1( "^\\S+$" );
QRegExp rx2( "^[A-Z0-9a-z-+._, ]+$" );
QValidator *validator_string = new QRegExpValidator( rx1, this );
QValidator *validator_stringdir = new QRegExpValidator( rx2, this );
ui->setupBiasLineEdit->setValidator( validator_stringdir );
ui->setupDarkLineEdit->setValidator( validator_stringdir );
ui->setupFlatLineEdit->setValidator( validator_stringdir );
ui->setupFlatoffLineEdit->setValidator( validator_stringdir );
ui->setupMainLineEdit->setValidator( validator_string );
ui->setupProjectLineEdit->setValidator( validator_string );
ui->setupScienceLineEdit->setValidator( validator_stringdir );
ui->setupSkyLineEdit->setValidator( validator_stringdir );
ui->setupStandardLineEdit->setValidator( validator_stringdir);
}
void MainWindow::connect_validators()
{
connect(ui->setupBiasLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupDarkLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupFlatLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupFlatoffLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupMainLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupProjectLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupScienceLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupSkyLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
connect(ui->setupStandardLineEdit, &QLineEdit::textChanged, this, &MainWindow::validate);
}
| 2,475
|
C++
|
.cc
| 46
| 50.695652
| 93
| 0.771901
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,410
|
mainwindow.cc
|
schirmermischa_THELI/src/mainwindow.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "functions.h"
#include "status.h"
#include "iview/iview.h"
#include "colorpicture/colorpicture.h"
#include "instrumentdefinition.h"
#include "tools/tools.h"
#include "instrumentdata.h"
#include "processingInternal/controller.h"
#include "processingInternal/data.h"
#include "dockwidgets/confdockwidget.h"
#include "dockwidgets/monitor.h"
#include "dockwidgets/memoryviewer.h"
#include "tools/cpu.h"
#include "tools/ram.h"
#include "ui_confdockwidget.h"
#include "ui_memoryviewer.h"
#include <QDebug>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <QString>
#include <QStringList>
#include <QStringListModel>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QThread>
#include <QProgressBar>
#include <QStorageInfo>
#include <QTimer>
#include <QPixmap>
#include <QScreen>
MainWindow::MainWindow(QString pid, QWidget *parent) :
QMainWindow(parent),
mainPID(pid),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// WARNING! THIS IS A VERY CAREFULLY BALANCED SETUP
// TO DO THINGS IN THE RIGHT ORDER.
// some of the routines called here are also used later on, e.g.
// changing settings parameters and so on. For some of them we don't want
// them to execute all of their code, for example when they are called during the first init of the GUI.
doingInitialLaunch = true;
initProcessingStatus();
initEnvironment(thelidir, userdir);
instrument_userDir = userdir+"/instruments_user/";
instrument_dir = thelidir+"/config/instruments/";
// Setup hardware
QSysInfo *sysInfo = new QSysInfo;
kernelType = sysInfo->kernelType(); // returns "linux" or "darwin"
productName = sysInfo->prettyProductName().replace(" ","_");
systemRAM = get_memory();
delete sysInfo;
QPalette palette;
palette.setColor(QPalette::Base,QColor("#ffffff"));
palette.setColor(QPalette::Background,QColor("#cccccc"));
ui->statusBar->setPalette(palette);
ui->statusBar->setAutoFillBackground(true);
ui->menuBar->setPalette(palette);
ui->menuBar->setAutoFillBackground(true);
addProgressBars();
establish_connections();
// Meaningful overview comments shown when running a task
populateTaskCommentMap();
// must populate the instrument listview before reading the settings
QString projectname;
readPreferenceSettings(projectname);
// the next one can be adjusted when manually loading a project file
// actually, think it is not needed here because it must also be invoked by readGUIsettings() below
// fill_setupInstrumentComboBox();
// Create dock widgets (before reading settings)
cdw = new ConfDockWidget(this);
monitor = new Monitor(this);
// perhaps before initializeGuiLayout?
// Also calls fill_setupInstrumentComboBox()
readGUISettings(projectname);
// Update some confdockwidget displays according to settings
cdw->toggle_skyparams();
cdw->toggle_skyparamThresholds("");
// If the user launches THELI the very first time, then on_setupInstrumentComboBox_clicked does
// not get triggered (don't know why not); do it manually:
if (instData.name.isEmpty()) on_setupInstrumentComboBox_clicked();
// Fix some paint events triggered by readSettings().
// The reason is that the settings are not written in order.
// Settings change the dir names, triggering a paint event,
// which results in red background for some elements because
// the main dir is not set first. Hence the repaint.
repaintDataDirs();
// The entity that keeps track of the data, incl connections
QString statusOld = status.getStatusFromHistory();
// NOTE: setting up the controller may take a while (when creating object masks)
controller = new Controller(&instData, statusOld, cdw, monitor, this);
// LineEdit changes update controller
for (auto &it : status.listDataDirs) {
// connect(it, &QLineEdit::textChanged, controller, &Controller::updateSingle);
connect(it, &QLineEdit::editingFinished, controller, &Controller::dataTreeEditedReceived);
// editing finished not emitted if dirs are empty (because of the validator)
connect(it, &QLineEdit::textChanged, this, &MainWindow::emitEditingFinished);
}
// Initial configuration of MainWindow
initGUI();
// Repaint background of previously executed tasks.
// initGUI loads the style sheet, thus defaulting to backgrounds
status.history2checkbox();
// this->setStyleSheet("QComboBox:hover { background-color: #99ccff };");
// The entity that keeps track of the data, incl connections
// QString statusOld = status.getStatusFromHistory();
// Another dock widget, must be done after instantiating the controller
memoryViewer = new MemoryViewer(controller, this);
controller->memoryViewer = memoryViewer;
controller->instrument_dir = instrument_dir;
controller->connectDataWithMemoryViewer();
connect(controller, &Controller::clearMemoryView, memoryViewer, &MemoryViewer::clearMemoryViewReceived, Qt::DirectConnection);
connect(controller, &Controller::populateMemoryView, memoryViewer, &MemoryViewer::populateMemoryViewReceived);
connect(controller, &Controller::addBackupDirToMemoryviewer, memoryViewer, &MemoryViewer::addBackupDirReceived);
// Combine mode changes update controller
connect(cdw->ui->overscanMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors);
connect(cdw->ui->biasMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors);
connect(cdw->ui->darkMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors);
connect(cdw->ui->flatoffMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors);
connect(cdw->ui->flatMethodComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateControllerFunctors);
connect(ui->setupInstrumentComboBox, &QComboBox::currentTextChanged, this, &MainWindow::updateController);
// Initiate the controller functors;
updateControllerFunctors("");
// Internal processing
connect(controller, &Controller::loadViewer, this, &MainWindow::launchViewer);
connect(controller, &Controller::loadAbsZP, this, &MainWindow::loadCoaddAbsZP);
connect(controller, &Controller::messageAvailable, monitor, &Monitor::displayMessage);
connect(controller, &Controller::appendOK, monitor, &Monitor::appendOK);
connect(controller, &Controller::showMessageBox, this, &MainWindow::showMessageBoxReceived);
connect(controller, &Controller::progressUpdate, this, &MainWindow::progressUpdateReceived);
connect(controller, &Controller::resetProgressBar, this, &MainWindow::resetProgressBarReceived);
connect(controller, &Controller::targetResolved, cdw, &ConfDockWidget::targetResolvedReceived);
connect(controller, &Controller::scienceDataDirUpdated, this, &MainWindow::scienceDataDirUpdatedReceived);
connect(controller, &Controller::updateMemoryProgressBar, this, &MainWindow::updateMemoryProgressBarReceived);
connect(controller, &Controller::forceFinish, this, &MainWindow::taskFinished);
connect(controller, &Controller::refreshMemoryViewer, this, &MainWindow::refreshMemoryViewerReceiver);
// controller->isMainDirHome();
connect(this, &MainWindow::resetErrorStatus, controller, &Controller::resetErrorStatusReceived);
connect(this, &MainWindow::rereadScienceDataDir, controller, &Controller::rereadScienceDataDirReceived);
connect(this, &MainWindow::newProjectLoaded, controller, &Controller::newProjectLoadedReceived);
connect(this, &MainWindow::messageAvailable, monitor, &Monitor::displayMessage);
connect(this, &MainWindow::warning, monitor, &Monitor::raise);
connect(ui->setupMainLineEdit, &QLineEdit::textChanged, cdw, &ConfDockWidget::updateAPIsolutions);
connect(ui->setupStandardLineEdit, &QLineEdit::textChanged, cdw, &ConfDockWidget::updateAPIsolutions);
connect(cdw, &QDockWidget::dockLocationChanged, this, &MainWindow::cdw_dockLocationChanged);
connect(cdw, &QDockWidget::topLevelChanged, this, &MainWindow::cdw_topLevelChanged);
// Must be done after readGUIsettings()
addDockWidgets();
doingInitialLaunch = false;
memoryViewer->populate();
// Need this after connecting status dirs to paint checkboxes correctly.
// Doesn't work if done further above, not sure why
// Does the right thing (repaint check boxes), but it seems random at best. Only updates tabwidet shown
status.updateStatus();
// repaint; doesn't seem to help in painting the checkboxes correctly
// update();
startProgressBars(); // must (or should) be done after settings are read and controller is live
estimateBinningFactor();
setHomeDir(); // mostly first time launch, only
updateExcludedDetectors(cdw->ui->excludeDetectorsLineEdit->text());
}
void MainWindow::closeEvent(QCloseEvent *event)
{
bool accept = true;
QString filepath;
if (kernelType == "linux") filepath = QDir::homePath()+"/.config/THELI/";
else if (kernelType == "darwin") filepath = QDir::homePath()+"/Library/Preferences/THELI/";
if (writePreferenceSettings() != QSettings::NoError) {
qDebug() << "closeEvent: Could not save preference settings.";
}
if (writeGUISettings() == QSettings::NoError) accept = accept && true;
else if (writeGUISettings() == QSettings::AccessError) {
const QMessageBox::StandardButton ret
= QMessageBox::warning(this, tr("Application"),
tr("A file access error occurred while writing the project configuration to\n")+
filepath+"\n",
QMessageBox::Ok | QMessageBox::Cancel);
switch (ret) {
case QMessageBox::Ok:
accept = accept && true;
break;
case QMessageBox::Cancel:
accept = accept && false;
break;
default:
break;
}
}
else if (writeGUISettings() == QSettings::FormatError) {
const QMessageBox::StandardButton ret
= QMessageBox::warning(this, tr("Application"),
tr("A formatting error occurred when writing the project configuration to\n")+
filepath+"\n",
QMessageBox::Ok | QMessageBox::Cancel);
switch (ret) {
case QMessageBox::Ok:
accept = accept && true;
break;
case QMessageBox::Cancel:
accept = accept && false;
break;
default:
break;
}
}
// write out data in memory
long numUnsavedImagesLatestStage = 0;
long numUnsavedImagesBackup = 0;
controller->checkForUnsavedImages(numUnsavedImagesLatestStage, numUnsavedImagesBackup);
if (numUnsavedImagesLatestStage > 0 || numUnsavedImagesBackup > 0) {
long mBytesLatest = numUnsavedImagesLatestStage*instData.storage;
long mBytesBackup = numUnsavedImagesBackup*instData.storage;
long mBytesAll = mBytesLatest + mBytesBackup;
QString saveLatestString = "";
QString saveAllString = "";
if (numUnsavedImagesLatestStage > 0) saveLatestString = "The current project keeps "+QString::number(numUnsavedImagesLatestStage)
+ " unsaved images of the latest processing stage in memory.\n";
if (numUnsavedImagesBackup > 0) saveAllString = "The current project keeps "+QString::number(numUnsavedImagesBackup)
+ " unsaved images with earlier processing stages in memory.\n";
QMessageBox msgBox;
msgBox.setModal(true);
msgBox.setInformativeText(tr("Unsaved images detected.\n") +
saveLatestString + saveAllString + "\n");
QAbstractButton *pButtonSaveLatest = msgBox.addButton(tr("Save latest images (")+QString::number(mBytesLatest)+" MB) and close", QMessageBox::YesRole);
QAbstractButton *pButtonSaveAll = msgBox.addButton(tr("Save all images (")+QString::number(mBytesAll)+" MB) and close", QMessageBox::YesRole);
QAbstractButton *pButtonContinue = msgBox.addButton(tr("Close without saving"), QMessageBox::YesRole);
QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
if (numUnsavedImagesLatestStage == 0) pButtonSaveLatest->hide();
if (numUnsavedImagesBackup == 0) pButtonSaveAll->hide();
msgBox.exec();
if (msgBox.clickedButton() == pButtonSaveLatest) {
if (sufficientSpaceAvailable(mBytesLatest)) { // sufficientSpaceAvailable() displays a warning message
controller->writeUnsavedImagesToDrive(false);
accept = accept && true;
}
else {
accept = accept && false;
}
}
else if (msgBox.clickedButton() == pButtonSaveAll) {
if (sufficientSpaceAvailable(mBytesAll)) {
controller->writeUnsavedImagesToDrive(true);
accept = accept && true;
}
else {
accept = accept && false;
}
}
else if (msgBox.clickedButton() == pButtonContinue) {
accept = accept && true;
}
else if (msgBox.clickedButton() == pButtonCancel) {
accept = accept && false;
}
}
if (accept) event->accept();
else event->ignore();
}
void MainWindow::emitEditingFinished(const QString &arg1)
{
QLineEdit* lineedit = qobject_cast<QLineEdit*>(sender());
if (arg1.isEmpty()) lineedit->editingFinished();
}
MainWindow::~MainWindow()
{
// delete class variables that have been assigned with 'new':
delete instrument_model;
instrument_model = nullptr;
delete ui;
}
void MainWindow::addProgressBars()
{
// Add diskspace progress bar to the status bar and connect it to a timer that updates it repeatedly.
// Don't have to delete the statusBar separately because it is a child of 'ui' and constructed after 'ui'
driveProgressBar = new QProgressBar(this);
driveProgressBar->setMinimumWidth(200);
driveProgressBar->setMaximumWidth(200);
cpuProgressBar = new QProgressBar(this);
cpuProgressBar->setMinimumWidth(200);
cpuProgressBar->setMaximumWidth(200);
memoryProgressBar = new QProgressBar(this);
memoryProgressBar->setMinimumWidth(200);
memoryProgressBar->setMaximumWidth(200);
ui->processProgressBar->setMinimumWidth(200);
ui->processProgressBar->setMaximumWidth(200);
// progress bars cannot be added to menuBar under MacOs (at least in 2011)
/*
if (kernelType == "darwin") ui->statusBar->addPermanentWidget(driveProgressBar, 0);
else {
// bar doesnt show under linux, either
QWidgetAction* actionProgressBar = new QWidgetAction(this);
actionProgressBar->setDefaultWidget(driveProgressBar);
ui->menuBar->addAction(actionProgressBar);
}
*/
QSysInfo *sysInfo = new QSysInfo;
QString kernelType = sysInfo->kernelType();
// Push the progress bars to the right, with little spacers in between;
QWidget* empty = new QWidget();
QWidget* empty1 = new QWidget();
QWidget* empty2 = new QWidget();
empty->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
empty1->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
empty2->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
empty1->setMinimumWidth(10);
empty2->setMinimumWidth(10);
if (kernelType == "linux") {
ui->toolBar->addWidget(empty);
ui->toolBar->addWidget(driveProgressBar);
ui->toolBar->addWidget(empty1);
ui->toolBar->addWidget(cpuProgressBar);
ui->toolBar->addWidget(empty2);
ui->toolBar->addWidget(memoryProgressBar);
}
else if (kernelType == "darwin") { // Progress Bars not supported in macOS in the top toolBar
ui->statusBar->addWidget(empty);
ui->statusBar->addWidget(driveProgressBar);
ui->statusBar->addWidget(empty1);
ui->statusBar->addWidget(cpuProgressBar);
ui->statusBar->addWidget(empty2);
ui->statusBar->addWidget(memoryProgressBar);
}
delete sysInfo;
sysInfo = nullptr;
}
// should be done after controller has been established and settings have been read
void MainWindow::startProgressBars()
{
// Start the progress bars
myCPU = new CPU(this);
myRAM = new RAM(this);
// Memory and CPU bars get updated every 2 seconds
// Must be declared / launched after data tree has been mapped.
ramTimer = new QTimer(this);
cpuTimer = new QTimer(this);
driveTimer = new QTimer(this);
connect(ramTimer, SIGNAL(timeout()), SLOT(displayRAMload()));
connect(cpuTimer, SIGNAL(timeout()), SLOT(displayCPUload()));
connect(driveTimer, SIGNAL(timeout()), SLOT(displayDriveSpace()));
ramTimer->start(2000);
cpuTimer->start(2000);
driveTimer->start(2000);
cpuProgressBar->setRange(0, 100*QThread::idealThreadCount());
long totalMemory = get_memory();
myRAM->totalRAM = totalMemory;
memoryProgressBar->setRange(0, totalMemory / 1024); // [MB]
memoryProgressBar->setValue(0);
}
void MainWindow::displayCPUload()
{
// int CPUload = myCPU->getCPUload();
float CPUload = myCPU->getCurrentValue();
QString CPUstring = QString::number(int(CPUload)) + " %";
cpuProgressBar->setFormat("CPU: "+CPUstring);
cpuProgressBar->setValue(int(CPUload));
}
void MainWindow::displayRAMload()
{
float RAMload = myRAM->getCurrentValue();
QString RAMstring = QString::number(long(RAMload)) + " MB";
memoryProgressBar->setFormat("RAM: %p% ("+RAMstring+")");
memoryProgressBar->setValue(int(RAMload));
}
void MainWindow::displayDriveSpace()
{
// Storage space in the main/home directory
QString maindir = ui->setupMainLineEdit->text();
double GBtotal_data, GBfree_data, GBused_data;
double GBtotal_home, GBfree_home, GBused_home;
QStorageInfo storage_home(QDir::homePath());
if (storage_home.isValid() && storage_home.isReady()) {
GBtotal_home = storage_home.bytesTotal()/1024./1024./1024.;
GBfree_home = storage_home.bytesAvailable()/1024./1024./1024.;
GBused_home = GBtotal_home - GBfree_home;
}
else {
emit messageAvailable("Controller::displayDriveSpace(): Cannot determine home directory!", "error");
return;
}
QStorageInfo storage_data(maindir);
if (storage_data.isValid() && storage_data.isReady()) {
GBtotal_data = storage_data.bytesTotal()/1024./1024./1024.;
GBfree_data = storage_data.bytesAvailable()/1024./1024./1024.;
GBused_data = GBtotal_data - GBfree_data;
}
else {
GBtotal_data = GBtotal_home;
GBfree_data = GBfree_home;
GBused_data = GBused_home;
}
driveProgressBar->setRange(0, GBtotal_data);
QString datadiskstring = QString::number(GBfree_data,'f',2) + " GB left";
// check if the data disk warning should be activated
if (GBfree_data <= diskwarnPreference/1024.) { // preference is given in MB
if (!datadiskspace_warned) {
datadiskspace_warned = true;
if (maindir.isEmpty()) maindir = QDir::homePath();
QMessageBox::warning( this, "THELI: DATA DISK SPACE LOW",
"The remaining disk space on\n\n"
+ maindir+"\n\nis less than your warning threshold of "
+ QString::number(diskwarnPreference)+" MB.\n"
"The threshold can be set under Edit->Preferences in the main menu. "
"This warning will not be shown anymore in this session, "
"unless you update the threshold to a new value.");
}
}
else datadiskspace_warned = false;
if (GBfree_home <= 0.1) {
if (!homediskspace_warned) {
homediskspace_warned = true;
QMessageBox::warning( this, "THELI: HOME DISK SPACE LOW",
"THELI: You are running low (<100 MB) on disk space in your home directory!\n");
}
}
else homediskspace_warned = false;
driveProgressBar->setFormat("Drive: "+datadiskstring);
driveProgressBar->setValue(GBused_data);
}
void MainWindow::addDockWidgets()
{
addDockWidget(Qt::RightDockWidgetArea, cdw);
cdw->setFloating(false);
addDockWidget(Qt::RightDockWidgetArea, monitor);
monitor->setFloating(false);
addDockWidget(Qt::RightDockWidgetArea, memoryViewer);
memoryViewer->setFloating(false);
// Create tabbed dock widgets
tabifyDockWidget(cdw, monitor);
tabifyDockWidget(monitor, memoryViewer);
cdw->raise();
}
void MainWindow::resetProgressBarReceived()
{
ui->processProgressBar->setValue(0);
}
void MainWindow::updateController()
{
controller->instData = &instData;
controller->updateAll();
}
void MainWindow::updateControllerFunctors(QString text)
{
if (cdw->ui->overscanMethodComboBox->currentText() == "Line median") controller->combineOverscan_ptr = &medianMask;
else if (cdw->ui->overscanMethodComboBox->currentText() == "Line mean") controller->combineOverscan_ptr = &meanMask;
else controller->combineOverscan_ptr = nullptr;
if (cdw->ui->biasMethodComboBox->currentText() == "Median")
controller->combineBias_ptr = &medianMask;
else controller->combineBias_ptr = &meanMask;
if (cdw->ui->darkMethodComboBox->currentText() == "Median")
controller->combineDark_ptr = &medianMask;
else controller->combineDark_ptr = &meanMask;
if (cdw->ui->flatoffMethodComboBox->currentText() == "Median")
controller->combineFlatoff_ptr = &medianMask;
else controller->combineFlatoff_ptr = &meanMask;
if (cdw->ui->flatMethodComboBox->currentText() == "Median")
controller->combineFlat_ptr = &medianMask;
else controller->combineFlat_ptr = &meanMask;
if (cdw->ui->BACmethodComboBox->currentText() == "Median")
controller->combineBackground_ptr = &medianMask;
else controller->combineBackground_ptr = &meanMask;
}
// currently not in use
/*
bool MainWindow::maybeSave()
{
const QMessageBox::StandardButton ret
= QMessageBox::question(this, tr("Application"),
tr("Reduced enough data ?"),
QMessageBox::Ok | QMessageBox::Cancel);
switch (ret) {
case QMessageBox::Ok:
return true;
case QMessageBox::Cancel:
return false;
default:
break;
}
return true;
}
*/
void MainWindow::initGUI()
{
QFile file(":/qss/default.qss");
file.open(QFile::ReadOnly);
QString styleSheet = QString::fromLatin1(file.readAll());
qApp->setStyleSheet(styleSheet);
QIcon key(":/icons/key.png");
QIcon redoarrow(":/icons/redoarrow.png");
QIcon projectLoad(":/icons/open_project.png");
QIcon projectReset(":/icons/db-restart-icon.png");
QIcon projectDataReset(":/icons/db-reset.png");
// configuration dialog
ui->HDUreformatConfigureToolButton->setIcon(key);
ui->calibratorConfigureToolButton->setIcon(key);
ui->BACconfigureToolButton->setIcon(key);
ui->chopnodConfigureToolButton->setIcon(key);
ui->COCconfigureToolButton->setIcon(key);
ui->binnedPreviewConfigureToolButton->setIcon(key);
ui->globalweightConfigureToolButton->setIcon(key);
ui->individualweightConfigureToolButton->setIcon(key);
ui->separateConfigureToolButton->setIcon(key);
ui->absphotomindirectConfigureToolButton->setIcon(key);
ui->absphotomdirectConfigureToolButton->setIcon(key);
ui->astromphotomConfigureToolButton->setIcon(key);
ui->createsourcecatConfigureToolButton->setIcon(key);
ui->skysubConfigureToolButton->setIcon(key);
ui->coadditionConfigureToolButton->setIcon(key);
ui->setupProjectLoadToolButton->setIcon(projectLoad);
ui->setupProjectResetToolButton->setIcon(projectReset);
ui->setupProjectResetDataToolButton->setIcon(projectDataReset);
this->setWindowTitle("THELI "+GUIVERSION+" Project: "+ui->setupProjectLineEdit->text());
// Check the status of currently selected tasks (if any; simulator mode)
// and push a suitable message to plainTextedit
on_startPushButton_clicked();
// Mandatory checkboxes have yellow background
// Don't know the parameter referring to the background color of the checkbox marker alone
/*
QList<QCheckBox*> mandatoryCheckboxList;
mandatoryCheckboxList.append(ui->applyHDUreformatCheckBox);
mandatoryCheckboxList.append(ui->applyGlobalweightCheckBox);
mandatoryCheckboxList.append(ui->applyIndividualweightCheckBox);
mandatoryCheckboxList.append(ui->applyCreatesourcecatCheckBox);
mandatoryCheckboxList.append(ui->applyAstromphotomCheckBox);
mandatoryCheckboxList.append(ui->applyCoadditionCheckBox);
for (auto &it : mandatoryCheckboxList) {
it->setStyleSheet("base: #fff669;");
}
*/
QIcon yield(":/icons/Signal-yield-icon.png");
QIcon stop(":/icons/Actions-process-stop-icon.png");
ui->yieldToolButton->setIcon(yield);
ui->stopToolButton->setIcon(stop);
}
void MainWindow::establish_connections()
{
// Other, 'singular' connectors
// Data dirs
for (auto &it : status.listDataDirs) {
// LineEdits adjust their background color
connect(it, &QLineEdit::textChanged, this, &MainWindow::repaintDataDirs);
// LineEdits editing finished must update GUI settings
connect(it, &QLineEdit::editingFinished, this, &MainWindow::writeGUISettings);
}
// TODO: move to confdockwidget
// connect(ui->ARCselectimageLineEdit, &QLineEdit::textChanged, this, &MainWindow::repaintDataDirs);
// Close the main GUI
connect(ui->actionClose, &QAction::triggered, this, &MainWindow::shutDown);
// Connect configureToolButtons with the confStackedWidget
for (auto &it : status.listToolButtons) {
connect(it, &QToolButton::clicked, this, &MainWindow::link_ConfToolButtons_confStackedWidget);
}
// Connect task checkboxes (load corresponding config page, and run simulator mode)
for (auto &it : status.listCheckBox) {
connect(it, &QCheckBox::clicked, this, &MainWindow::link_taskCheckBoxes_confStackedWidget);
connect(it, &QCheckBox::clicked, this, &MainWindow::on_startPushButton_clicked);
}
// Connect actions
connect(ui->actionPreferences, &QAction::triggered, this, &MainWindow::loadPreferences);
connect(ui->actionAbsZP, &QAction::triggered, this, &MainWindow::load_dialog_abszeropoint);
connect(ui->actioniView, &QAction::triggered, this, &MainWindow::loadIView);
connect(ui->actionNew_instrument, &QAction::triggered, this, &MainWindow::load_dialog_newinst);
connect(ui->actionColor_picture, &QAction::triggered, this, &MainWindow::load_dialog_colorpicture);
connect(ui->actionImage_statistics, &QAction::triggered, this, &MainWindow::load_dialog_imageStatistics);
// Connect validators
connect_validators();
connect(ui->setupProjectResetToolButton, &QPushButton::clicked, this, &MainWindow::resetParameters);
connect(ui->setupProjectResetDataToolButton, &QPushButton::clicked, this, &MainWindow::restoreOriginalData);
}
void MainWindow::cdw_dockLocationChanged(const Qt::DockWidgetArea &area)
{
if (cdw->isFloating()) this->adjustSize();
}
void MainWindow::cdw_topLevelChanged(bool topLevel)
{
// Minimum size for the MainWindow after DockWidget goes floating
if (topLevel) this->adjustSize();
}
void MainWindow::updateDiskspaceWarning(int newLimit)
{
diskwarnPreference = newLimit;
datadiskspace_warned = false;
}
void MainWindow::updateNumcpu(int cpu)
{
numCPU = cpu;
}
void MainWindow::link_ConfToolButtons_confStackedWidget()
{
QObject* obj = sender();
cdw->raise();
if (obj == ui->HDUreformatConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->calibratorConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->chopnodConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(1);
else if (obj == ui->BACconfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(1);
else if (obj == ui->COCconfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(2);
else if (obj == ui->binnedPreviewConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(2);
else if (obj == ui->globalweightConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(3);
else if (obj == ui->individualweightConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(3);
else if (obj == ui->separateConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(3);
else if (obj == ui->absphotomindirectConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(4);
else if (obj == ui->absphotomdirectConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(5);
else if (obj == ui->createsourcecatConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(5);
else if (obj == ui->astromphotomConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(6);
else if (obj == ui->skysubConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(7);
else if (obj == ui->coadditionConfigureToolButton) cdw->ui->confStackedWidget->setCurrentIndex(8);
}
void MainWindow::link_taskCheckBoxes_confStackedWidget()
{
QObject* obj = sender();
if (obj == ui->applyHDUreformatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->applyProcessbiasCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->applyProcessdarkCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->applyProcessflatoffCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->applyProcessflatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->applyProcessscienceCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(0);
else if (obj == ui->applyChopnodCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(1);
else if (obj == ui->applyBackgroundCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(1);
else if (obj == ui->applyCollapseCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(2);
else if (obj == ui->applyBinnedpreviewCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(2);
else if (obj == ui->applyGlobalweightCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(3);
else if (obj == ui->applyIndividualweightCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(3);
else if (obj == ui->applySeparateCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(3);
else if (obj == ui->applyAbsphotindirectCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(4);
else if (obj == ui->applyStarflatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(5);
else if (obj == ui->applyCreatesourcecatCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(5);
else if (obj == ui->applyAstromphotomCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(6);
else if (obj == ui->applySkysubCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(7);
else if (obj == ui->applyCoadditionCheckBox) cdw->ui->confStackedWidget->setCurrentIndex(8);
// Show the configuration tab (in case e.g. currently the monitor is displayed)
cdw->raise();
}
void MainWindow::checkPaths()
{
// Cast sender to LineEdit because we know it's a LineEdit.
// Then we have access to its content.
QLineEdit* lineedit = qobject_cast<QLineEdit*>(sender());
checkPathsLineEdit(lineedit);
}
bool MainWindow::checkPathsLineEdit(QLineEdit *lineEdit)
{
// Checks whether the entries in this lineEdit exist as directories.
// The return value is ignored in some cases.
// Turn the lineEdit to a stringList
QStringList list = datadir2StringList(lineEdit);
QString dirname = lineEdit->text();
// The following does not make much sense if we have multiple entries in a LineEdit.
// But we catch that with the following two ifs
QDir dir = QDir(dirname);
// Process path fields if
// -- unrelated to the data tree
// -- the main data dir itself = QFile(
// -- they are absolute paths
// -- baddir string is empty
if (lineEdit == cdw->ui->ARCselectimageLineEdit) {
paintPathLineEdit(lineEdit, dirname, "file");
return true;
}
if (lineEdit == ui->setupMainLineEdit) {
if (dir.isAbsolute()) {
QString mainDirName = lineEdit->text();
if (QDir(mainDirName) != QDir::home()) {
paintPathLineEdit(lineEdit, dirname);
return true;
}
else {
QPalette palette;
palette.setColor(QPalette::Base,QColor("#ffffaa"));
lineEdit->setPalette(palette);
return false;
}
}
else {
QPalette palette;
palette.setColor(QPalette::Base,QColor("#ff99aa"));
lineEdit->setPalette(palette);
return false;
}
}
if (dir.isAbsolute() || dirname.isEmpty()) {
paintPathLineEdit(lineEdit, dirname);
return true;
}
// Process the remaining data paths (BIAS, FLAT etc.), all relative.
QString baddir_summary = "";
QString main = ui->setupMainLineEdit->text();
// Loop over the directories and check whether they are good or bad.
// If a bad one is found, we paint the background red after the loop, otherwise green.
for (int i=0; i<list.size(); ++i) {
// check if path is absolute, if not, prepend main path
dirname = list.at(i);
dir = QDir(dirname);
if (!dir.isAbsolute()) {
dirname = main + "/" + dirname;
dir = QDir(dirname);
}
if (!dir.exists()) baddir_summary = baddir_summary + ", " + dirname;
}
// Paint LineEdit accordingly:
// paintPathLineEdit() does not change or read the text in a lineEdit;
// It merely evaluates if the second arg (a QString) exists as a QDir or not, and
// paints the LineEdit accordingly.
// For the purpose here we just use either an existing or a non-existing directory.
if (!baddir_summary.isEmpty()) {
paintPathLineEdit(lineEdit, baddir_summary);
return false;
}
else {
paintPathLineEdit(lineEdit, dirname);
return true;
}
}
// Can be called from a slot, hence sender() exists, but is also called directly
// in the MainWindow constructor
void MainWindow::repaintDataDirs()
{
// do not repaint while reading GUI settings (unnecessary load due to self-triggered calls)
if (doingInitialLaunch && readingSettings) return;
bool test = false;
if (sender() == 0 || sender() == ui->setupMainLineEdit) {
// Check subdirs as well
for ( auto &it : status.listDataDirs) {
test = checkPathsLineEdit(it);
// Simulate a run if maindir exists (to repaint the command lists)
if (test && sender() !=0 && it == ui->setupMainLineEdit) {
on_startPushButton_clicked();
}
}
}
else {
QLineEdit* lineEdit = qobject_cast<QLineEdit*>(sender());
if (lineEdit != 0) {
test = checkPathsLineEdit(lineEdit);
if (test) on_startPushButton_clicked();
}
else {
emit messageAvailable("MainWindow::repaintDataDirs(): bad LineEdit", "warning");
emit warning();
}
}
}
// invoked when changing the instrument category in the preference dialog
void MainWindow::linkPrefInst_with_MainInst(int index)
{
instrumentPreference = index;
fill_setupInstrumentComboBox();
}
// invoked when reading a project requires a change of category in the preference dialog
// (the inst combobox is populated correctly already)
void MainWindow::updatePreferences()
{
QSettings settings("THELI", "PREFERENCES");
settings.setValue("setupProjectLineEdit", ui->setupProjectLineEdit->text());
settings.sync();
if (settings.status() != QSettings::NoError) {
emit messageAvailable("MainWindow::updatePreferences(): Failed updating the instrument category preference. Settings status = " + settings.status(), "error");
emit warning();
}
}
void MainWindow::updateFontSize(int index)
{
QFont currentFont = this->font();
currentFont.setPointSize(index);
this->setFont(currentFont);
}
void MainWindow::updateFont(QFont font)
{
this->setFont(font);
}
void MainWindow::resetInstrumentData()
{
instData.numChips = 1;
instData.numUsedChips = 1;
instData.name = "";
instData.shortName = "";
instData.nameFullPath = "";
instData.obslat = 0.;
instData.obslon = 0.;
instData.bayer = "";
instData.flip = "";
instData.type = "OPT";
instData.pixscale = 1.0; // in arcsec
// instData.gain = 1.0;
instData.radius = 0.1; // exposure coverage radius in degrees
instData.storage = 0; // MB used for a single image
instData.storageExposure = 0.; // MB used for the entire (multi-chip) exposure
instData.overscan_xmin.clear();
instData.overscan_xmax.clear();
instData.overscan_ymin.clear();
instData.overscan_ymax.clear();
instData.cutx.clear();
instData.cuty.clear();
instData.sizex.clear();
instData.sizey.clear();
instData.crpix1.clear();
instData.crpix2.clear();
}
void MainWindow::initInstrumentData(QString instrumentNameFullPath)
{
resetInstrumentData();
QFile instDataFile(instrumentNameFullPath);
instDataFile.setFileName(instrumentNameFullPath);
instData.nameFullPath = instrumentNameFullPath;
// read the instrument specific data
if( !instDataFile.open(QIODevice::ReadOnly)) {
emit messageAvailable("MainWindow::initInstrumentData(): "+instrumentNameFullPath+" "+instDataFile.errorString(), "error");
emit warning(); // to raise the monitor
return;
}
instData.flip = "";
bool bayerFound = false;
QTextStream in(&(instDataFile));
while(!in.atEnd()) {
QString line = in.readLine().simplified();
if (line.isEmpty() || line.contains("#")) continue;
// scalars
if (line.contains("INSTRUMENT=")) instData.name = line.split("=")[1];
if (line.contains("INSTSHORT=")) instData.shortName = line.split("=")[1];
if (line.contains("NCHIPS=")) instData.numChips = line.split("=")[1].toInt();
if (line.contains("TYPE=")) instData.type = line.split("=")[1];
if (line.contains("BAYER=")) {
// BAYER is not mandatory; if not found, we must set it to blank
instData.bayer = line.split("=")[1];
bayerFound = true;
}
if (line.contains("OBSLAT=")) instData.obslat = line.split("=")[1].toFloat();
if (line.contains("OBSLONG=")) instData.obslon = line.split("=")[1].toFloat();
if (line.contains("PIXSCALE=")) instData.pixscale = line.split("=")[1].toFloat();
// if (line.contains("GAIN=")) instData.gain = line.split("=")[1].toFloat();
QString tmp = "";
if (line.contains("FLIP=")) {
tmp = line.split("=")[1];
if (tmp == "NOFLIP") instData.flip = "";
else instData.flip = tmp;
}
// vectors
if (line.contains("OVSCANX1=")
|| line.contains("OVSCANX2=")
|| line.contains("OVSCANY1=")
|| line.contains("OVSCANY2=")
|| line.contains("CUTX=")
|| line.contains("CUTY=")
|| line.contains("SIZEX=")
|| line.contains("SIZEY=")
|| line.contains("REFPIXX=")
|| line.contains("REFPIXY=")) {
line = line.replace('=',' ').replace(')',' ').replace(')',"");
line = line.simplified();
QStringList values = line.split(" ");
QVector<int> vecData;
// NOTE: already subtracting -1 to make it conform with C++ indexing
// (apart from SIZEX/Y, which is the actual number of pixels per axis and not a coordinate)
for (int i=2; i<values.length(); i=i+2) {
if (line.contains("SIZE")) vecData.push_back(values.at(i).toInt());
else vecData.push_back(values.at(i).toInt() - 1);
// vecData.push_back(values.at(i).toInt() - 1);
}
if (line.contains("OVSCANX1")) instData.overscan_xmin = vecData;
if (line.contains("OVSCANX2")) instData.overscan_xmax = vecData;
if (line.contains("OVSCANY1")) instData.overscan_ymin = vecData;
if (line.contains("OVSCANY2")) instData.overscan_ymax = vecData;
if (line.contains("CUTX")) instData.cutx = vecData;
if (line.contains("CUTY")) instData.cuty = vecData;
if (line.contains("SIZEX")) instData.sizex = vecData;
if (line.contains("SIZEY")) instData.sizey = vecData;
if (line.contains("REFPIXX")) instData.crpix1 = vecData;
if (line.contains("REFPIXY")) instData.crpix2 = vecData;
}
}
if (!bayerFound) instData.bayer = "";
// Backwards compatibility:
if (instData.type.isEmpty()) instData.type = "OPT";
QString shortstring = instData.name.split('@').at(0);
if (instData.shortName.isEmpty()) instData.shortName = shortstring;
instDataFile.close();
// The overscan needs special treatment:
// if it is consistently -1, or the string wasn't found,
// then the vector must be empty
testOverscan(instData.overscan_xmin);
testOverscan(instData.overscan_xmax);
testOverscan(instData.overscan_ymin);
testOverscan(instData.overscan_ymax);
// Determine the radius covered by a single exposure
int nGlobal;
int mGlobal;
int xminOffset;
int yminOffset;
int binFactor = 1;
QVector< QVector<int>> Tmatrices;
for (int chip=0; chip<instData.numChips; ++chip) {
QVector<int> tm = {1,0,0,1};
Tmatrices << tm;
}
getBinnedSize(&instData, Tmatrices, nGlobal, mGlobal, binFactor, xminOffset, yminOffset); // used to retrieve nglobal and mglobal
instData.nGlobal = nGlobal;
instData.mGlobal = mGlobal;
instData.radius = 0.5 * sqrt(nGlobal*nGlobal + mGlobal*mGlobal)*instData.pixscale / 3600.; // in degrees
// Lastly, how many MB does a single detector occupy
instData.storage = instData.sizex[0]*instData.sizey[0]*sizeof(float) / 1024. / 1024.;
instData.storageExposure = instData.storage * instData.numChips; // Always use full storage. This is computed before user may change number of used chips
updateExcludedDetectors(cdw->ui->excludeDetectorsLineEdit->text());
}
void MainWindow::testOverscan(QVector<int> &overscan)
{
if (overscan.isEmpty()) return;
// if the overscan is consistently -1, then the vector must be empty
bool flag = true;
for (auto &it : overscan) {
if (it != -1) {
flag = false;
break;
}
}
if (flag) overscan.clear();
}
void MainWindow::fill_setupInstrumentComboBox()
{
// UNCOMMENT to see how the GUI is initialized
// qDebug() << "fill_setupInstrumentComboBox";
QStringList instDirList;
instDirList << thelidir+"/config/instruments/"
<< QDir::homePath()+"/.theli/instruments_user/";
// Loop over pre-defined and user-defined instruments
instrument_model = new MyStringListModel;
QStringList allInstrumentList;
for (auto &instDirName : instDirList) {
QDir instDir = QDir(instDirName);
QStringList filter("*.ini");
instDir.setNameFilters(filter);
instDir.setSorting(QDir::Name);
QStringList currentInstrumentList = instDir.entryList();
if (currentInstrumentList.isEmpty()) continue;
currentInstrumentList.replaceInStrings(".ini","");
allInstrumentList.append(currentInstrumentList);
// instrument_model only used here, but it needs to exist throughpout the lifetime of the GUI.
if (instDirName.contains("instruments_user")) instrument_model->instrument_userDir = instDirName;
else instrument_model->instrument_dir = instDirName;
}
if (allInstrumentList.isEmpty()) {
QMessageBox::critical(this, tr("THELI"),
tr("No instrument configurations were found in /usr/share/theli/config/! Did you set the THELIDIR environment variable correctly?\n")
+tr("If you are not using a system wide installation, then THELIDIR should point to the installation directory (where you find the src/ sub-directory)."),
QMessageBox::Ok);
return;
}
// allInstrumentList.sort();
instrument_model->setStringList(allInstrumentList);
// CAREFUL! the following line also triggers
// on_setupInstrumentComboBox_clicked()
// and repaintDataDirs() (why??)
ui->setupInstrumentComboBox->setModel(instrument_model);
ui->setupInstrumentComboBox->setCurrentIndex(0);
// We always do a software click as well. Unnecessary?
// on_setupInstrumentComboBox_clicked();
// Override user's desktop preferences, to avoid a ComboBox to fill the entire screen
// from top to bottom. Only show 20 items max (designer setting, but needs to be activated here)
ui->setupInstrumentComboBox->setStyleSheet("combobox-popup: 0;");
}
void MainWindow::updateInstrumentComboBoxBackgroundColor()
{
QPalette palette;
if (instrument_type == "OPT") palette.setColor(QPalette::Button,QColor("#40acff"));
else if (instrument_type == "NIR") palette.setColor(QPalette::Button,QColor("#70ffd4"));
else if (instrument_type == "NIRMIR") palette.setColor(QPalette::Button,QColor("#ffe167"));
else if (instrument_type == "MIR") palette.setColor(QPalette::Button,QColor("#ff616b"));
else palette.setColor(QPalette::Button,QColor("#40acff")); // backwards compatibility; if undefined, use optical color
ui->setupInstrumentComboBox->setPalette(palette);
}
void MainWindow::toggleButtonsWhileRunning()
{
if (!ui->startPushButton->isEnabled()) {
ui->setupInstrumentComboBox->setDisabled(true);
ui->setupProjectLineEdit->setDisabled(true);
ui->setupProjectLoadToolButton->setDisabled(true);
ui->setupProjectResetToolButton->setDisabled(true);
ui->setupProjectResetDataToolButton->setDisabled(true);
cdw->ui->ARCgetcatalogPushButton->setDisabled(true);
cdw->ui->restoreHeaderPushButton->setDisabled(true);
}
else {
ui->setupInstrumentComboBox->setEnabled(true);
ui->setupProjectLineEdit->setEnabled(true);
ui->setupProjectLoadToolButton->setEnabled(true);
ui->setupProjectResetToolButton->setEnabled(true);
ui->setupProjectResetDataToolButton->setEnabled(true);
cdw->ui->ARCgetcatalogPushButton->setEnabled(true);
cdw->ui->restoreHeaderPushButton->setEnabled(true);
}
}
QString MainWindow::getInstDir(QString instname)
{
instrument_name = ui->setupInstrumentComboBox->currentText();
QFile file;
file.setFileName(instrument_dir+instname);
if (file.exists()) return instrument_dir;
else {
file.setFileName(instrument_userDir+instname);
if (file.exists()) return instrument_userDir;
else {
emit messageAvailable("Could not find instrument "+ instname +" config file in either of", "error");
emit messageAvailable(instrument_dir, "error");
emit messageAvailable(instrument_userDir, "error");
emit warning();
}
}
return "";
}
void MainWindow::checkMemoryConstraints()
{
// systemRAM is in kB;
if (instData.storageExposure >= systemRAM / 1024.) {
QMessageBox::warning( this, "Low physical RAM detected",
"A single "+instData.name + " exposure occupies "
+ QString::number(long(instData.storageExposure)) + " MB in memory.\n"
+ "Your machine has only "+QString::number(long(systemRAM/1024)) + " MB installed. "
+ "Processing might be fine, but performance will be significantly reduced.");
}
}
void MainWindow::on_setupInstrumentComboBox_clicked()
{
// Read some instrument parameters and the file path
instrument_name = ui->setupInstrumentComboBox->currentText();
if (instrument_name.isEmpty()) return; // can happen if e.g. there are no user-defined instruments
QString matchingInstDir = getInstDir(instrument_name+".ini");
instrument_file.setFileName(matchingInstDir+instrument_name+".ini");
instrument_bayer = get_fileparameter(&instrument_file, "BAYER");
instrument_type = get_fileparameter(&instrument_file, "TYPE");
instrument_nchips = get_fileparameter(&instrument_file, "NCHIPS").toInt();
// Pass on to ConfDockWidget
cdw->instrument_dir = matchingInstDir;
cdw->instrument_name = instrument_name;
cdw->instrument_type = instrument_type;
cdw->instrument_bayer = instrument_bayer; // UNUSED?
cdw->instrument_nchips = instrument_nchips;
cdw->instrument_file.setFileName(matchingInstDir+instrument_name+".ini");
// The structure holding the content of the instrument file
initInstrumentData(matchingInstDir+instrument_name+".ini");
updateInstrumentComboBoxBackgroundColor();
if (!readingSettings) {
// TODO: rather, look into the image headers and calculate the most likely pixel scale (dropping into 1x1 or 2x2 binning mode)
cdw->ui->COApixscaleLineEdit->setText(get_fileparameter(&instrument_file, "PIXSCALE"));
if (instData.pixscale < 0.1) cdw->ui->ASTcrossidLineEdit->setText(QString::number(10.*instData.pixscale, 'f', 2));
else if (instData.pixscale < 0.5) cdw->ui->ASTcrossidLineEdit->setText(QString::number(5.*instData.pixscale, 'f', 1));
else cdw->ui->ASTcrossidLineEdit->setText(QString::number(int(5.*instData.pixscale)));
}
if (instrument_type == "MIR") {
// UNCOMMENT to see how the GUI is initialized
// qDebug() << "U0 - MIR setup";
ui->applyChopnodCheckBox->show();
ui->chopnodConfigureToolButton->show();
ui->applyBackgroundCheckBox->hide();
ui->BACconfigureToolButton->hide();
cdw->ui->overscanCheckBox->setDisabled(true);
cdw->ui->overscanMethodComboBox->setDisabled(true);
}
else if (instrument_type == "NIR") {
// UNCOMMENT to see how the GUI is initialized
// qDebug() << "U0 - NIR setup";
ui->applyChopnodCheckBox->hide();
ui->chopnodConfigureToolButton->hide();
ui->applyBackgroundCheckBox->show();
ui->BACconfigureToolButton->show();
cdw->ui->overscanCheckBox->setDisabled(true);
cdw->ui->overscanMethodComboBox->setDisabled(true);
}
else if (instrument_type == "NIRMIR") {
// UNCOMMENT to see how the GUI is initialized
// qDebug() << "U0 - NIRMIR setup";
ui->applyChopnodCheckBox->show();
ui->chopnodConfigureToolButton->show();
ui->applyBackgroundCheckBox->show();
ui->BACconfigureToolButton->show();
cdw->ui->overscanCheckBox->setDisabled(true);
cdw->ui->overscanMethodComboBox->setDisabled(true);
}
else if (instrument_type == "OPT" || instrument_type == "") {
// UNCOMMENT to see how the GUI is initialized
// qDebug() << "U0 - OPT setup";
ui->applyChopnodCheckBox->hide();
ui->chopnodConfigureToolButton->hide();
ui->applyBackgroundCheckBox->show();
ui->BACconfigureToolButton->show();
cdw->ui->overscanCheckBox->setEnabled(true);
cdw->ui->overscanMethodComboBox->setEnabled(true);
if (cdw->ui->saturationLineEdit->text().isEmpty()) cdw->ui->saturationLineEdit->setText("65535");
}
cdw->ui->BIPSpinBox->setValue(estimateBinningFactor());
// Update settings
writeGUISettings();
checkMemoryConstraints();
}
void MainWindow::scienceDataDirUpdatedReceived(QString allDirs)
{
ui->setupScienceLineEdit->setText(allDirs);
emit rereadScienceDataDir();
}
void MainWindow::progressUpdateReceived(float progressReceived)
{
controller->progress = progressReceived;
ui->processProgressBar->setValue(int(progressReceived));
}
bool MainWindow::sufficientSpaceAvailable(long spaceNeeded)
{
QString unitsNeeded = " MB";
QString unitsFree = " MB";
long spaceFree = remainingDataDriveSpace(ui->setupMainLineEdit->text()); // in MBytes
QString spaceNeededString = QString::number(spaceNeeded) + unitsNeeded;
QString spaceFreeString = QString::number(spaceFree) + unitsFree;
// Unit conversions
if (spaceNeeded > 1024.) {
float spaceNeededFloat = spaceNeeded / 1024.;
unitsNeeded = " GB";
spaceNeededString = QString::number(spaceNeededFloat, 'f', 1) + unitsNeeded;
}
if (spaceFree > 1024.) {
float spaceFreeFloat = spaceFree / 1024.;
unitsFree = " GB";
spaceFreeString = QString::number(spaceFreeFloat, 'f', 1) + unitsFree;
}
if (spaceNeeded > spaceFree) {
QMessageBox::warning( this, tr("Insufficient space on drive"),
tr("The current operation needs to write ") + spaceNeededString +
tr(" to drive, however only") + spaceFreeString +
tr(" are available on ")+ui->setupMainLineEdit->text());
return false;
}
return true;
}
void MainWindow::on_setupProjectLoadToolButton_clicked()
{
// First of all, check if we have unsaved images in memory
long numUnsavedImagesLatestStage = 0;
long numUnsavedImagesBackup = 0;
controller->checkForUnsavedImages(numUnsavedImagesLatestStage, numUnsavedImagesBackup);
if (numUnsavedImagesLatestStage > 0 || numUnsavedImagesBackup > 0) {
long mBytesLatest = numUnsavedImagesLatestStage*instData.storage;
long mBytesBackup = numUnsavedImagesBackup*instData.storage;
long mBytesAll = mBytesLatest + mBytesBackup;
QString saveLatestString = "";
QString saveAllString = "";
if (numUnsavedImagesLatestStage > 0) saveLatestString = "The current project keeps "+QString::number(numUnsavedImagesLatestStage)
+ " unsaved images of the latest processing stage in memory.\n";
if (numUnsavedImagesBackup > 0) saveAllString = "The current project keeps "+QString::number(numUnsavedImagesBackup)
+ " unsaved images with earlier processing stages in memory.\n";
QMessageBox msgBox;
msgBox.setModal(true);
msgBox.setInformativeText(tr("A new project is about to be loaded.\n") +
saveLatestString + saveAllString + "\n");
QAbstractButton *pButtonSaveLatest = msgBox.addButton(tr("Save latest images (")+QString::number(mBytesLatest)+" MB) and close", QMessageBox::YesRole);
QAbstractButton *pButtonSaveAll = msgBox.addButton(tr("Save all images (")+QString::number(mBytesAll)+" MB) and close", QMessageBox::YesRole);
QAbstractButton *pButtonContinue = msgBox.addButton(tr("Close without saving"), QMessageBox::YesRole);
QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
if (numUnsavedImagesLatestStage == 0) pButtonSaveLatest->hide();
if (numUnsavedImagesBackup == 0) pButtonSaveAll->hide();
msgBox.exec();
if (msgBox.clickedButton() == pButtonSaveLatest) {
if (sufficientSpaceAvailable(mBytesLatest)) { // sufficientSpaceAvailable() displays a warning message
controller->writeUnsavedImagesToDrive(false);
}
else return;
}
else if (msgBox.clickedButton() == pButtonSaveAll) {
if (sufficientSpaceAvailable(mBytesAll)) {
controller->writeUnsavedImagesToDrive(true);
}
else return;
}
else if (msgBox.clickedButton() == pButtonContinue) {
// see below
}
else if (msgBox.clickedButton() == pButtonCancel) {
return;
}
}
QString projectname;
if (kernelType == "linux") {
projectname = QFileDialog::getOpenFileName(this, tr("Select THELI Project"), QDir::homePath()+"/.config/THELI/",
tr("THELI projects (*.conf)"));
}
else {
// kernelType == "darwin"
projectname = QFileDialog::getOpenFileName(this, tr("Select THELI Project"), QDir::homePath()+"/Library/Preferences/THELI/",
tr("THELI projects (*.plist)"));
}
// Truncate the suffix (OS dependent; Linux: .conf; MacOS Mojave: com.theli.<project>.plist)
QFileInfo projectFileInfo(projectname);
QString projectBaseName = projectFileInfo.completeBaseName();
if (kernelType == "darwin") projectBaseName.remove("com.theli.");
if ( projectBaseName.isEmpty() ) {
return;
}
// Before wiping the data tree, we must switch away from the memory view (if currently raised).
// Even though we display an empty model, it still tries to access the old ones, even though everything should be protected.
// So, we just switch to the config view and then back (until I sorted this out)
bool viewSwitched = false;
if (memoryViewer->isVisible()) {
cdw->raise();
viewSwitched = true;
}
monitor->displayMessage("Freeing memory ...", "ignore");
controller->wipeDataTree();
// Now load the new GUI settings
// ui->plainTextEdit->clear(); // Not effective. Why?
ui->setupProjectLineEdit->setText(projectBaseName);
int settingsStatus = readGUISettings(projectBaseName);
if (settingsStatus == 0) {
// everything is OK
}
else if (settingsStatus == 1) {
QMessageBox::warning( this, "THELI: Access error",
"An access error occurred while reading the configuration file for project '"+projectBaseName+"'!\n");
}
else if (settingsStatus == 2) {
QMessageBox::warning( this, "THELI: Format error",
"A format error occurred while reading the configuration file for project '"+projectBaseName+"'!\n");
}
// Could also directly call controller->newProjectLoadedReceived() instead
emit newProjectLoaded();
// Show memory view again (if it was hidden before)
if (viewSwitched) memoryViewer->raise();
}
void MainWindow::loadPreferences()
{
// send instrument name and project name (why?)
updatePreferences();
// would have to set combobox, because the dialog exists already
bool taskRunning;
if (ui->startPushButton->isEnabled()) taskRunning = false;
else taskRunning = true;
preferences = new Preferences(taskRunning, this);
connect(preferences, &Preferences::instPreferenceChanged, this, &MainWindow::linkPrefInst_with_MainInst);
connect(preferences, &Preferences::fontSizeChanged, this, &MainWindow::updateFontSize);
connect(preferences, &Preferences::fontChanged, this, &MainWindow::updateFont);
connect(preferences, &Preferences::diskspacewarnChanged, this, &MainWindow::updateDiskspaceWarning);
connect(preferences, &Preferences::numcpuChanged, this, &MainWindow::updateNumcpu);
connect(preferences, &Preferences::memoryUsageChanged, controller, &Controller::updateMemoryPreference);
connect(preferences, &Preferences::switchProcessMonitorChanged, this, &MainWindow::updateSwitchProcessMonitorPreference);
connect(preferences, &Preferences::intermediateDataChanged, controller, &Controller::updateIntermediateDataPreference);
connect(preferences, &Preferences::verbosityLevelChanged, controller, &Controller::updateVerbosity);
connect(preferences, &Preferences::preferencesUpdated, controller, &Controller::loadPreferences);
connect(preferences, &Preferences::warning, monitor, &Monitor::raise);
connect(preferences, &Preferences::messageAvailable, monitor, &Monitor::displayMessage);
connect(this, &MainWindow::runningStatusChanged, preferences, &Preferences::updateParallelization);
connect(this, &MainWindow::sendingDefaultFont, preferences, &Preferences::receiveDefaultFont);
QFont defaultFont = this->font();
emit sendingDefaultFont(defaultFont); // to preferences
preferences->show();
}
void MainWindow::updateSwitchProcessMonitorPreference(bool switchToMonitor)
{
switchProcessMonitorPreference = switchToMonitor;
}
void MainWindow::statusChangedReceived(QString newStatus)
{
status.statusstringToHistory(newStatus);
}
void MainWindow::updateExcludedDetectors(QString badDetectors)
{
if (doingInitialLaunch && readingSettings) return;
if (controller) controller->successProcessing = true; // function called at launch when controller does not yet exist
instData.badChips.clear();
QStringList chipStringList = badDetectors.replace(","," ").simplified().split(" ");
if (!badDetectors.isEmpty()) {
for (auto &chip : chipStringList) instData.badChips.append(chip.toInt()-1);
}
instData.numUsedChips = instData.numChips - instData.badChips.length();
instData.goodChips.clear();
for (int chip=0; chip<instData.numChips; ++chip) {
if (!instData.badChips.contains(chip)) instData.goodChips.append(chip);
}
if (instData.goodChips.isEmpty()) {
if (controller) controller->successProcessing = false;
QMessageBox::critical(this, tr("THELI"),
tr("No valid detectors remain after filtering bad detectors. Review the list of user-defined unusable detectors."),
QMessageBox::Ok);
}
else {
instData.validChip = instData.goodChips[0];
}
// Map the chip numbers to the number in which they appear in order (e.g. in .scamp catalogs)
int countGoodChip = 0;
for (int chip=0; chip<instData.numChips; ++chip) {
if (instData.badChips.contains(chip)) continue;
instData.chipMap.insert(chip, countGoodChip);
++countGoodChip;
}
}
void MainWindow::load_dialog_abszeropoint()
{
AbsZeroPoint *abszeropoint = new AbsZeroPoint("", this);
// crashes, probably because 'preferences' doesn't exist yet.
// connect(preferences, &Preferences::verbosityLevelChanged, abszeropoint, &AbsZeroPoint::updateVerbosity);
abszeropoint->show();
}
void MainWindow::loadCoaddAbsZP(QString coaddImage, float maxVal)
{
AbsZeroPoint *abszeropoint = new AbsZeroPoint(coaddImage, this);
abszeropoint->updateSaturationValue(maxVal);
connect(abszeropoint, &AbsZeroPoint::abszpClosed, controller, &Controller::absZeroPointCloseReceived);
abszeropoint->show();
}
void MainWindow::load_dialog_imageStatistics()
{
QString mainDir = ui->setupMainLineEdit->text();
Data *scienceData = nullptr;
if (controller->DT_SCIENCE.length() == 1) {
scienceData = controller->DT_SCIENCE.at(0);
}
else if (controller->DT_SCIENCE.length() == 0) {
QMessageBox::information(this, tr("Missing data"),
tr("Image statistics:<br>No SCIENCE data were specified in the data tree.\n"),
QMessageBox::Ok);
return;
}
else {
QMessageBox msgBox;
msgBox.setInformativeText(tr("Image statistics: Choose SCIENCE data\n\n") +
tr("The current SCIENCE data tree contains several entries. ") +
tr("Select one for the statistics module:\n\n"));
for (auto &data : controller->DT_SCIENCE) {
msgBox.addButton(data->subDirName, QMessageBox::YesRole);
}
QAbstractButton *pCancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole);
msgBox.exec();
QString choice = msgBox.clickedButton()->text().remove('&'); // remove & is a fix of unwanted KDE behaviour (KDE may insert '&' into button text)
if (msgBox.clickedButton()== pCancel) return;
for (auto &data : controller->DT_SCIENCE) {
if (data->subDirName == choice) {
scienceData = data;
break;
}
}
}
ImageStatistics *imagestatistics = new ImageStatistics(controller->DT_SCIENCE, mainDir, scienceData->subDirName, &instData, this);
// Inform image statistics when the user manually (de)activates an image. Must be connected here, as imagestatistics does not know about mainGUI
connect(memoryViewer, &MemoryViewer::activationChanged, imagestatistics, &ImageStatistics::activationChangedReceiver);
imagestatistics->show();
}
void MainWindow::load_dialog_colorpicture()
{
ColorPicture *colorPicture = new ColorPicture(ui->setupMainLineEdit->text(), this);
connect(colorPicture, &ColorPicture::showMessageBox, this, &MainWindow::showMessageBoxReceived);
colorPicture->show();
}
void MainWindow::load_dialog_newinst()
{
instrument->show();
}
/*
void MainWindow::loadIView()
{
QString main = ui->setupMainLineEdit->text();
QString science = ui->setupScienceLineEdit->text().split(" ").at(0);
QString dirname = main+"/"+science;
if (!QDir(dirname).exists()) dirname = QDir::homePath();
IView *iView = new IView("FITSmonochrome", dirname, "*.fits *.fit *.FITS *.FIT", this);
iView->show();
}
*/
void MainWindow::loadIView()
{
QString main = ui->setupMainLineEdit->text();
QStringList scienceList = ui->setupScienceLineEdit->text().split(" ");
QString dirName = "";
if (scienceList.length() == 1) dirName = main+"/"+scienceList.at(0);
else {
QMessageBox msgBox;
msgBox.setInformativeText(tr("The current SCIENCE data tree contains several entries. ") +
tr("Select one for which to display images:\n\n"));
for (auto &name : scienceList) {
msgBox.addButton(name, QMessageBox::YesRole);
}
QAbstractButton *pCancel = msgBox.addButton(tr("Cancel"), QMessageBox::NoRole);
msgBox.exec();
QString choice = msgBox.clickedButton()->text().remove('&'); // remove & is a KDE fix
if (msgBox.clickedButton()== pCancel) return;
for (auto &name : scienceList) {
if (name == choice) {
dirName = main + "/" + name;
break;
}
}
}
if (!QDir(dirName).exists()) dirName = QDir::homePath();
IView *iView = new IView("FITSmonochrome", dirName, "*.fits", this);
iView->show();
}
// Used for displaying:
// (*) binned mosaics, coadded images (filter = file name)
void MainWindow::launchViewer(QString dirname, QString filter, QString mode)
{
// Load the FITS viewer
IView *iView = new IView("FITSmonochrome", dirname, filter, this);
connect(iView, &IView::closed, iView, &IView::deleteLater);
iView->show();
iView->setMiddleMouseMode(mode);
}
/*
void MainWindow::launchCoaddFluxcal(QString coaddImage)
{
AbsZeroPoint *abszeropoint = new AbsZeroPoint(coaddImage, &instData, this);
abszeropoint->show();
}
*/
void MainWindow::resetParameters()
{
// First of all, check if we have unsaved images in memory
long numUnsavedImagesLatestStage = 0;
long numUnsavedImagesBackup = 0;
controller->checkForUnsavedImages(numUnsavedImagesLatestStage, numUnsavedImagesBackup);
if (numUnsavedImagesLatestStage > 0 || numUnsavedImagesBackup > 0) {
long mBytesLatest = numUnsavedImagesLatestStage*instData.storage;
long mBytesBackup = numUnsavedImagesBackup*instData.storage;
long mBytesAll = mBytesLatest + mBytesBackup;
QString saveLatestString = "";
QString saveAllString = "";
if (numUnsavedImagesLatestStage > 0) saveLatestString = "The current project keeps "+QString::number(numUnsavedImagesLatestStage)
+ " unsaved images of the latest processing stage in memory.\n";
if (numUnsavedImagesBackup > 0) saveAllString = "The current project keeps "+QString::number(numUnsavedImagesBackup)
+ " unsaved images with earlier processing stages in memory.\n";
QMessageBox msgBox;
msgBox.setModal(true);
msgBox.setInformativeText(tr("The parameters in the current project are about to be reset.\n") +
saveLatestString + saveAllString +
tr("\nAll processing parameters will be reset to their default values.") +
tr(" Processing will continue with the FITS files currently found on your drive.") +
tr(" Data currently kept in memory can be saved and thus included in reprocessing.\n\n"));
QAbstractButton *pButtonSaveLatest = msgBox.addButton(tr("Save latest images (")+QString::number(mBytesLatest)+" MB) and close", QMessageBox::YesRole);
QAbstractButton *pButtonSaveAll = msgBox.addButton(tr("Save all images (")+QString::number(mBytesAll)+" MB) and close", QMessageBox::YesRole);
QAbstractButton *pButtonContinue = msgBox.addButton(tr("Close without saving"), QMessageBox::YesRole);
QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
if (numUnsavedImagesLatestStage == 0) pButtonSaveLatest->hide();
if (numUnsavedImagesBackup == 0) pButtonSaveAll->hide();
msgBox.exec();
if (msgBox.clickedButton() == pButtonSaveLatest) {
if (sufficientSpaceAvailable(mBytesLatest)) { // sufficientSpaceAvailable() displays a warning message
controller->writeUnsavedImagesToDrive(false);
}
else return;
}
else if (msgBox.clickedButton() == pButtonSaveAll) {
if (sufficientSpaceAvailable(mBytesAll)) {
controller->writeUnsavedImagesToDrive(true);
}
else return;
}
else if (msgBox.clickedButton() == pButtonContinue) {
// see below
}
else if (msgBox.clickedButton() == pButtonCancel) {
return;
}
}
else {
QMessageBox msgBox;
msgBox.setModal(true);
msgBox.setInformativeText(tr("The parameters in the current project are about to be reset.\n") +
tr(" All processing parameters will be reset to their default values. Processing will continue with the FITS files found on disk.\n"));
QAbstractButton *pButtonOK = msgBox.addButton(tr("OK"), QMessageBox::YesRole);
QAbstractButton *pButtonCancel = msgBox.addButton(tr("Cancel"), QMessageBox::YesRole);
msgBox.exec();
if (msgBox.clickedButton() == pButtonCancel) return;
else if (msgBox.clickedButton() == pButtonOK) {
// see below
}
}
// Purge all data from memory
monitor->displayMessage("Freeing memory ...", "ignore");
controller->wipeDataTree();
// Reread data tree from disk
monitor->displayMessage("Reading data structure from drive ...", "ignore");
controller->mapDataTree();
// Load defaults
monitor->displayMessage("Restoring defaults ...", "ignore");
cdw->loadDefaults();
for (auto &it : status.listHistory) {
it = false;
}
status.updateStatus();
writeGUISettings();
monitor->displayMessage("<br>*** DONE ***", "note");
}
void MainWindow::populateTaskCommentMap()
{
taskCommentMap.clear();
taskCommentMap.insert("HDUreformat", "HDU reformatting");
taskCommentMap.insert("Processbias", "Processing biases in");
taskCommentMap.insert("Processdark", "Processing darks in");
taskCommentMap.insert("Processflatoff", "Processing flat off/darks in");
taskCommentMap.insert("Processflat", "Processing flats in");
taskCommentMap.insert("Processscience", "Debiasing and flatfielding data in");
taskCommentMap.insert("Chopnod", "Doing chopnod background correction for");
taskCommentMap.insert("Background", "Applying background model to");
taskCommentMap.insert("Collapse", "Applying collapse correction to");
taskCommentMap.insert("Binnedpreview", "Creating binned previews for");
taskCommentMap.insert("Globalweight", "Creating global weights for");
taskCommentMap.insert("Individualweight", "Creating individual weights for");
taskCommentMap.insert("Separate", "Separating different targes in");
taskCommentMap.insert("Absphotindirect", "Performing indirect absolute photometry");
taskCommentMap.insert("Createsourcecat", "Creating source catalogs for");
taskCommentMap.insert("Astromphotom", "Calculating astrometric solution for");
taskCommentMap.insert("Skysub", "Subtracting the sky for");
taskCommentMap.insert("Coaddition", "Performing coaddition for");
taskCommentMap.insert("GetCatalogFromWEB", "Downloading astrometric reference catalog for");
taskCommentMap.insert("GetCatalogFromIMAGE", "Extracting astrometric reference catalog for");
taskCommentMap.insert("Resolvetarget", "Resolving target coordinates for");
}
void MainWindow::initProcessingStatus()
{
// Initialize the status' collective widget lists
// the order is important!!!
status.listCheckBox.append(ui->applyHDUreformatCheckBox);
status.listCheckBox.append(ui->applyProcessbiasCheckBox);
status.listCheckBox.append(ui->applyProcessdarkCheckBox);
status.listCheckBox.append(ui->applyProcessflatoffCheckBox);
status.listCheckBox.append(ui->applyProcessflatCheckBox);
status.listCheckBox.append(ui->applyProcessscienceCheckBox);
status.listCheckBox.append(ui->applyChopnodCheckBox);
status.listCheckBox.append(ui->applyBackgroundCheckBox);
status.listCheckBox.append(ui->applyCollapseCheckBox);
status.listCheckBox.append(ui->applyBinnedpreviewCheckBox);
status.listCheckBox.append(ui->applyGlobalweightCheckBox);
status.listCheckBox.append(ui->applyIndividualweightCheckBox);
status.listCheckBox.append(ui->applySeparateCheckBox);
status.listCheckBox.append(ui->applyAbsphotindirectCheckBox);
status.listCheckBox.append(ui->applyCreatesourcecatCheckBox);
status.listCheckBox.append(ui->applyAstromphotomCheckBox);
status.listCheckBox.append(ui->applyStarflatCheckBox);
status.listCheckBox.append(ui->applySkysubCheckBox);
status.listCheckBox.append(ui->applyCoadditionCheckBox);
status.listToolButtons.append(ui->HDUreformatConfigureToolButton);
status.listToolButtons.append(ui->calibratorConfigureToolButton);
status.listToolButtons.append(ui->BACconfigureToolButton);
status.listToolButtons.append(ui->chopnodConfigureToolButton);
status.listToolButtons.append(ui->COCconfigureToolButton);
status.listToolButtons.append(ui->binnedPreviewConfigureToolButton);
status.listToolButtons.append(ui->globalweightConfigureToolButton);
status.listToolButtons.append(ui->individualweightConfigureToolButton);
status.listToolButtons.append(ui->separateConfigureToolButton);
status.listToolButtons.append(ui->absphotomindirectConfigureToolButton);
status.listToolButtons.append(ui->absphotomdirectConfigureToolButton);
status.listToolButtons.append(ui->astromphotomConfigureToolButton);
status.listToolButtons.append(ui->createsourcecatConfigureToolButton);
status.listToolButtons.append(ui->skysubConfigureToolButton);
status.listToolButtons.append(ui->coadditionConfigureToolButton);
status.listDataDirs.append(ui->setupMainLineEdit);
status.listDataDirs.append(ui->setupBiasLineEdit);
status.listDataDirs.append(ui->setupDarkLineEdit);
status.listDataDirs.append(ui->setupFlatoffLineEdit);
status.listDataDirs.append(ui->setupFlatLineEdit);
status.listDataDirs.append(ui->setupScienceLineEdit);
status.listDataDirs.append(ui->setupSkyLineEdit);
status.listDataDirs.append(ui->setupStandardLineEdit);
// Populate the map that associates CheckBoxes and their texts
// (so that we can lookup the CheckBox based on its string representation,
// needed for some messages being sent to plainTextEdit when executing tasks.
// Also, populate the index map;
QString taskBasename;
int i=0;
for (auto &it: status.listCheckBox) {
taskBasename = it->objectName().remove("apply").remove("CheckBox");
checkboxMap.insert(it, taskBasename);
status.indexMap.insert(taskBasename, i);
++i;
}
// List name contains the taskBasename;
// The Boolean list goes to false,
// the value list to empy strings
QString name;
for (int i=0; i<status.numtasks; ++i) {
name = status.listCheckBox.at(i)->objectName();
name.remove("apply");
name.remove("CheckBox");
status.listName << name;
status.listHistory << false;
status.listCurrentValue << " ";
status.listFixedValue << " "; // just to create a QList with 'numtasks' elements
}
for (int i=0; i<status.numtasks; ++i) {
// HARDCODING!!! This must be updated if the order of tasks
// is changed, or if new task checkboxes are added to the GUI
if (i==0) status.listFixedValue.operator[](i) = "P";
else if (i==5) status.listFixedValue.operator[](i) = "A";
else if (i==6) status.listFixedValue.operator[](i) = "M";
else if (i==7) status.listFixedValue.operator[](i) = "B";
else if (i==8) status.listFixedValue.operator[](i) = "C";
else if (i==16) status.listFixedValue.operator[](i) = "D";
else if (i==17) status.listFixedValue.operator[](i) = "S";
}
}
void MainWindow::on_setupReadmePushButton_clicked()
{
multidirReadme = new MultidirReadme(this);
multidirReadme->show();
}
void MainWindow::on_setupInstrumentComboBox_currentTextChanged(const QString &arg1)
{
// UNCOMMENT to see how the GUI is built up
// qDebug() << "on_setupInstrumentComboBox_currentTextChanged()";
on_setupInstrumentComboBox_clicked();
}
void MainWindow::on_processingTabWidget_currentChanged(int index)
{
if (index == 0 || index == 1) {
cdw->ui->confStackedWidget->setCurrentIndex(0);
cdw->ui->confBackwardPushButton->setDisabled(true);
}
// else if (index == 2) {
// cdw->ui->confStackedWidget->setCurrentIndex(1);
// cdw->ui->confBackwardPushButton->setEnabled(true);
// }
else {
cdw->ui->confStackedWidget->setCurrentIndex(3);
cdw->ui->confBackwardPushButton->setEnabled(true);
// Fill the coadd filter combobox with values
}
writeGUISettings();
update();
}
void MainWindow::shutDown()
{
this->close();
}
void MainWindow::on_actionAdd_new_instrument_configuration_triggered()
{
load_dialog_newinst();
}
void MainWindow::on_actionEdit_preferences_triggered()
{
loadPreferences();
}
void MainWindow::restoreOriginalData()
{
bool accept = true;
const QMessageBox::StandardButton ret
= QMessageBox::warning(this, tr("Full data reset"),
tr("WARNING: You are about to restore all raw data.\n\n") +
tr("All processed data, both in memory and on drive, will be lost!\n"),
QMessageBox::Ok | QMessageBox::Cancel);
switch (ret) {
case QMessageBox::Ok:
accept = accept && true;
break;
case QMessageBox::Cancel:
accept = accept && false;
break;
default:
break;
}
if (!accept) return;
QString newStatus = "";
status.statusstringToHistory(newStatus);
// Reset status
for (auto &it : status.listHistory) {
it = false;
}
status.updateStatus();
// Restore data
monitor->displayMessage("Freeing memory, restoring raw data ...", "ignore");
controller->restoreAllRawData();
memoryViewer->projectResetReceived();
// Switch to first processing tab page
ui->processingTabWidget->setCurrentIndex(1);
}
void MainWindow::on_actionLicense_triggered()
{
license = new License(this);
license->show();
}
void MainWindow::on_actionAcknowledging_triggered()
{
acknowledging = new Acknowledging(this);
acknowledging->show();
}
void MainWindow::on_actionDocumentation_triggered()
{
tutorials = new Tutorials(this);
tutorials->show();
}
int MainWindow::estimateBinningFactor()
{
QScreen *screen = QGuiApplication::primaryScreen();
int x = screen->availableSize().width() - 240; // subtracting margins for the iview UI
int y = screen->availableSize().height() - 120;
int binFactorX = instData.nGlobal / x + 1;
int binFactorY = instData.mGlobal / y + 1;
int binFactor = binFactorX > binFactorY ? binFactorX : binFactorY;
if (binFactor < 1) binFactor = 1;
return binFactor;
}
void MainWindow::updateMemoryProgressBarReceived(long memoryUsed)
{
QString memoryString = QString::number(long(memoryUsed)) + " MB";
memoryProgressBar->setFormat("RAM: %p% ("+memoryString+")");
memoryProgressBar->setValue(memoryUsed);
}
void MainWindow::on_setupProjectLineEdit_textChanged(const QString &arg1)
{
this->setWindowTitle("THELI "+GUIVERSION+" Project: "+arg1);
}
// Used e.g. when user starts the very first time and nothing has been defined yet
void MainWindow::setHomeDir()
{
if (ui->setupBiasLineEdit->text().isEmpty()
&& ui->setupDarkLineEdit->text().isEmpty()
&& ui->setupFlatoffLineEdit->text().isEmpty()
&& ui->setupFlatLineEdit->text().isEmpty()
&& ui->setupScienceLineEdit->text().isEmpty()
&& ui->setupSkyLineEdit->text().isEmpty()
&& ui->setupStandardLineEdit->text().isEmpty()
&& ui->setupMainLineEdit->text().isEmpty())
ui->setupMainLineEdit->setText(QDir::homePath());
}
| 83,463
|
C++
|
.cc
| 1,729
| 41.313476
| 184
| 0.688017
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,411
|
transformations.cc
|
schirmermischa_THELI/src/iview/transformations.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "iview.h"
#include "ui_iview.h"
// qimage: the coordinate system of the displayed QImage
// myimage: the coordinate system of the FITS image
void IView::qimageToBinned(qreal qx, qreal qy, qreal &bx, qreal &by)
{
qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1;
bx = qx * qreal(icdw->navigator_binned_nx) / norm;
by = qy * qreal(icdw->navigator_binned_ny) / norm;
}
QPointF IView::qimageToBinned(const QPointF qpoint)
{
qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1;
qreal qx = qpoint.x();
qreal qy = qpoint.y();
qreal bx = qx * qreal(icdw->navigator_binned_nx) / norm;
qreal by = qy * qreal(icdw->navigator_binned_ny) / norm;
QPointF bpoint;
bpoint.setX(bx);
bpoint.setY(by);
return bpoint;
}
QRect IView::qimageToBinned(const QRectF qrect)
{
qreal qx1 = 0.;
qreal qy1 = 0.;
qreal qx2 = 0.;
qreal qy2 = 0.;
qrect.getCoords(&qx1, &qy1, &qx2, &qy2);
qreal bx1;
qreal bx2;
qreal by1;
qreal by2;
qimageToBinned(qx1, qy1, bx1, by1);
qimageToBinned(qx2, qy2, bx2, by2);
QRect brect;
brect.setCoords(bx1, by1, bx2, by2);
return brect;
}
void IView::binnedToQimage(qreal bx, qreal by, qreal &qx, qreal &qy)
{
qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1;
qx = bx * norm / qreal(icdw->navigator_binned_nx);
qy = by * norm / qreal(icdw->navigator_binned_ny);
}
QPointF IView::binnedToQimage(const QPointF bpoint)
{
qreal norm = naxis2 >= naxis1 ? naxis2 : naxis1;
qreal bx = bpoint.x();
qreal by = bpoint.y();
qreal qx = bx * norm / qreal(icdw->navigator_binned_nx);
qreal qy = by * norm / qreal(icdw->navigator_binned_ny);
QPointF qpoint;
qpoint.setX(qx);
qpoint.setY(qy);
return qpoint;
}
| 2,433
|
C++
|
.cc
| 71
| 30.943662
| 75
| 0.701575
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,412
|
actions.cc
|
schirmermischa_THELI/src/iview/actions.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "iview.h"
#include "ui_iview.h"
#include "ui_ivfinderdockwidget.h"
void IView::checkFinder()
{
if (!finderdw->isVisible()) return;
// Both name fields empty
if (finderdw->ui->targetNameSiderealLineEdit->text().isEmpty()
&& finderdw->ui->targetNameNonsiderealLineEdit->text().isEmpty()
&& !finderdw->ui->targetAlphaLineEdit->text().isEmpty()
&& !finderdw->ui->targetDeltaLineEdit->text().isEmpty() ) {
finderdw->bypassResolver();
}
// sidereal field empty, nonsidereal not empty
if (!finderdw->ui->targetNameNonsiderealLineEdit->text().isEmpty()
&& finderdw->ui->targetNameSiderealLineEdit->text().isEmpty()) {
finderdw->on_MPCresolverToolButton_clicked();
}
// sidereal field not empty, nonsidereal empty, coords empty
if (!finderdw->ui->targetNameSiderealLineEdit->text().isEmpty()
&& finderdw->ui->targetNameNonsiderealLineEdit->text().isEmpty()) {
if (finderdw->ui->targetAlphaLineEdit->text().isEmpty()
||finderdw->ui->targetDeltaLineEdit->text().isEmpty()) {
finderdw->on_locatePushButton_clicked();
}
if (!finderdw->ui->targetAlphaLineEdit->text().isEmpty()
&& !finderdw->ui->targetDeltaLineEdit->text().isEmpty()) {
finderdw->bypassResolver();
}
}
}
void IView::checkFinderBypass()
{
if (!finderdw->isVisible()) return;
finderdw->bypassResolver();
}
void IView::previousAction_triggered()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (currentId > 0) {
currentId --;
if (displayMode == "FITSmonochrome") loadFITS("", currentId);
else if (displayMode == "CLEAR") loadFITS("", currentId);
else if (displayMode.contains("SCAMP")) loadPNG("", currentId);
else if (displayMode == "MEMview") {
// Check if the selected image is active. If not, search for one
while (myImageList[currentId]->activeState == MyImage::INACTIVE && currentId > 0) --currentId;
loadFromRAM(myImageList[currentId], 0);
}
ui->actionNext->setEnabled(true);
ui->actionEnd->setEnabled(true);
ui->actionForward->setEnabled(true);
}
if (currentId == 0) {
ui->actionPrevious->setDisabled(true);
ui->actionStart->setDisabled(true);
ui->actionBack->setDisabled(true);
}
showReferenceCat();
showSourceCat();
timer->stop();
ui->actionBack->setChecked(false);
ui->actionForward->setChecked(false);
emit currentlyDisplayedIndex(currentId);
checkFinder();
}
void IView::nextAction_triggered()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (currentId < numImages-1) {
currentId ++;
if (displayMode == "FITSmonochrome") loadFITS("", currentId);
else if (displayMode == "CLEAR") loadFITS("", currentId);
else if (displayMode.contains("SCAMP")) loadPNG("", currentId);
else if (displayMode == "MEMview") {
// Check if the selected image is active. If not, search for one
while (currentId < numImages-1 && myImageList[currentId]->activeState == MyImage::INACTIVE) ++currentId;
loadFromRAM(myImageList[currentId], 0);
}
ui->actionPrevious->setEnabled(true);
ui->actionStart->setEnabled(true);
ui->actionBack->setEnabled(true);
}
if (currentId == numImages-1) {
ui->actionNext->setDisabled(true);
ui->actionEnd->setDisabled(true);
ui->actionForward->setDisabled(true);
}
showReferenceCat();
showSourceCat();
timer->stop();
ui->actionBack->setChecked(false);
ui->actionForward->setChecked(false);
emit currentlyDisplayedIndex(currentId);
checkFinder();
}
void IView::forwardAction_triggered()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (ui->actionForward->isChecked()) timer->start(1000/speedSpinBox->value());
else return;
if (currentId < numImages - 1 && ui->actionForward->isChecked()) {
ui->actionBack->setChecked(false);
currentId ++;
if (displayMode == "FITSmonochrome") loadFITS("", currentId);
else if (displayMode == "CLEAR") loadFITS("", currentId);
else if (displayMode.contains("SCAMP")) loadPNG("", currentId);
else if (displayMode == "MEMview") {
// Check if the selected image is active. If not, search for one
while (currentId < numImages-1 && myImageList[currentId]->activeState == MyImage::INACTIVE) ++currentId;
loadFromRAM(myImageList[currentId], 0);
}
ui->actionPrevious->setEnabled(true);
ui->actionStart->setEnabled(true);
}
if (currentId == numImages-1) {
timer->stop();
ui->actionBack->setChecked(false);
ui->actionBack->setEnabled(true);
ui->actionForward->setChecked(false);
ui->actionForward->setDisabled(true);
ui->actionNext->setDisabled(true);
ui->actionEnd->setDisabled(true);
}
showReferenceCat();
showSourceCat();
emit currentlyDisplayedIndex(currentId);
checkFinder();
}
void IView::backAction_triggered()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (ui->actionBack->isChecked()) timer->start(1000/speedSpinBox->value());
else return;
if (currentId > 0 && ui->actionBack->isChecked()) {
ui->actionForward->setChecked(false);
currentId --;
if (displayMode == "FITSmonochrome") loadFITS("", currentId);
else if (displayMode == "CLEAR") loadFITS("", currentId);
else if (displayMode.contains("SCAMP")) loadPNG("", currentId);
else if (displayMode == "MEMview") {
// Check if the selected image is active. If not, search for one
while (currentId > 0 && myImageList[currentId]->activeState == MyImage::INACTIVE) --currentId;
loadFromRAM(myImageList[currentId], 0);
}
ui->actionNext->setEnabled(true);
ui->actionEnd->setEnabled(true);
}
if (currentId == 0) {
timer->stop();
ui->actionBack->setChecked(false);
ui->actionBack->setDisabled(true);
ui->actionForward->setChecked(false);
ui->actionForward->setEnabled(true);
ui->actionPrevious->setDisabled(true);
ui->actionStart->setDisabled(true);
}
showReferenceCat();
showSourceCat();
emit currentlyDisplayedIndex(currentId);
checkFinder();
}
void IView::startAction_triggered()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
currentId = 0;
if (displayMode == "FITSmonochrome") loadFITS("", currentId);
else if (displayMode == "CLEAR") loadFITS("", currentId);
else if (displayMode.contains("SCAMP")) loadPNG("", currentId);
else if (displayMode == "MEMview") {
// Check if the selected image is active. If not, search for one
while (myImageList[currentId]->activeState == MyImage::INACTIVE && currentId < numImages-1) ++currentId;
loadFromRAM(myImageList[currentId], 0);
}
ui->actionNext->setEnabled(true);
ui->actionForward->setEnabled(true);
ui->actionEnd->setEnabled(true);
ui->actionStart->setDisabled(true);
ui->actionPrevious->setDisabled(true);
ui->actionBack->setDisabled(true);
showReferenceCat();
showSourceCat();
timer->stop();
ui->actionBack->setChecked(false);
ui->actionForward->setChecked(false);
emit currentlyDisplayedIndex(currentId);
checkFinder();
}
void IView::endAction_triggered()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
currentId = numImages - 1;
if (displayMode == "FITSmonochrome") loadFITS("", currentId);
else if (displayMode == "CLEAR") loadFITS("", currentId);
else if (displayMode.contains("SCAMP")) loadPNG("", currentId);
else if (displayMode == "MEMview") {
// Check if the selected image is active. If not, search for one
while (myImageList[currentId]->activeState == MyImage::INACTIVE && currentId > 0) --currentId;
loadFromRAM(myImageList[currentId], 0);
}
ui->actionNext->setDisabled(true);
ui->actionForward->setDisabled(true);
ui->actionEnd->setDisabled(true);
ui->actionStart->setEnabled(true);
ui->actionPrevious->setEnabled(true);
ui->actionBack->setEnabled(true);
showReferenceCat();
showSourceCat();
timer->stop();
ui->actionBack->setChecked(false);
ui->actionForward->setChecked(false);
emit currentlyDisplayedIndex(currentId);
checkFinder();
}
void IView::on_actionDragMode_triggered()
{
setMiddleMouseMode("DragMode"); // exclusive button group in c'tor does not work!
emit middleMouseModeChanged("DragMode");
}
void IView::on_actionSkyMode_triggered()
{
setMiddleMouseMode("SkyMode"); // exclusive button group in c'tor does not work!
emit middleMouseModeChanged("SkyMode");
}
void IView::on_actionWCSMode_triggered()
{
setMiddleMouseMode("WCSMode"); // exclusive button group in c'tor does not work!
emit middleMouseModeChanged("WCSMode");
}
void IView::on_actionMaskingMode_triggered()
{
setMiddleMouseMode("MaskingMode"); // exclusive button group in c'tor does not work!
emit middleMouseModeChanged("MaskingMode");
}
void IView::on_actionImage_statistics_triggered()
{
if (statdw->isVisible()) {
removeDockWidget(statdw);
statdw->hide();
}
else {
statdw->init();
statdw->setFloating(false);
statdw->raise();
statdw->show();
}
}
void IView::on_actionFinder_triggered()
{
if (finderdw->isVisible()) {
removeDockWidget(finderdw);
finderdw->hide();
}
else {
finderdw->setFloating(false);
finderdw->raise();
finderdw->show();
finderdw->ui->targetNameSiderealLineEdit->setFocus();
}
}
void IView::on_actionRedshift_triggered()
{
if (zdw->isVisible()) {
clearAxes();
removeDockWidget(zdw);
zdw->hide();
}
else {
// Do not display the dialog if no image is loaded
if (!currentMyImage) {
ui->actionRedshift->setChecked(false);
return;
}
zdw->setFloating(false);
zdw->raise();
zdw->show();
zdw->init();
updateAxes();
}
}
| 11,280
|
C++
|
.cc
| 300
| 31.396667
| 116
| 0.654617
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,413
|
constructors.cc
|
schirmermischa_THELI/src/iview/constructors.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "iview.h"
#include "ui_iview.h"
#include "../functions.h"
#include "mygraphicsview.h"
#include "mygraphicsellipseitem.h"
#include "mygraphicsscene.h"
#include "ui_ivconfdockwidget.h"
#include "ui_ivcolordockwidget.h"
#include "ui_ivredshiftdockwidget.h"
#include "dockwidgets/ivscampdockwidget.h"
#include "dockwidgets/ivcolordockwidget.h"
#include "dockwidgets/ivredshiftdockwidget.h"
#include "../tools/tools.h"
#include "fitsio2.h"
#include <QDir>
#include <QSettings>
#include <QGraphicsPixmapItem>
#include <QPixmap>
#include <QGraphicsGridLayout>
#include <QDebug>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QToolBar>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPointF>
#include <QScrollBar>
#include <QTimer>
#include <QScreen>
// Various constructors
// Open the window without loading an image
// Not sure I'm using that anywhere
// mode = CLEAR
IView::IView(QWidget *parent) :
QMainWindow(parent),
displayMode("CLEAR"),
ui(new Ui::IView)
{
// qDebug() << "mode 1";
ui->setupUi(this);
initGUI();
icdw->zoom2scale(zoomLevel);
// get a list of all FITS files in the current directory
QDir dir = dir.current();
dirName = dir.absolutePath();
filterName = "*.fits";
setImageList(filterName);
makeConnections();
switchMode();
initGUIstep2();
}
// MEMview, single MyImage
IView::IView(QString mode, QWidget *parent) :
QMainWindow(parent),
displayMode(mode), // "MEMview", set externally
ui(new Ui::IView)
{
ui->setupUi(this);
initGUI();
// Hide redshift action
ui->actionRedshift->setVisible(false);
// qDebug() << "mode memview single image:" << mode;
icdw->zoom2scale(zoomLevel);
/*
// get a list of all FITS files in the current directory
QDir dir = dir.current();
dirName = dir.absolutePath();
filterName = "*.fits";
setImageList(filterName);
*/
makeConnections();
switchMode();
initGUIstep2();
fromMemory = true;
// Can't use these in memory mode (ensuring internal consistency, and avoiding very complex code)
// filterLabel->hide();
// filterLineEdit->hide();
}
// MEMview, list of MyImages
IView::IView(QString mode, QList<MyImage*> &list, QString dirname, QWidget *parent) :
QMainWindow(parent),
displayMode(mode),
ui(new Ui::IView)
{
ui->setupUi(this);
initGUI();
// Hide redshift action
ui->actionRedshift->setVisible(false);
// qDebug() << "mode memview list of images:" << mode;
icdw->zoom2scale(zoomLevel);
myImageList = list;
numImages = myImageList.length();
setImageListFromMemory();
dirName = dirname;
fromMemory = true;
// 'currentId' is initialised externally in memoryViewer
/*
// get a list of all FITS files in the current directory
QDir dir = dir.current();
dirName = dir.absolutePath();
filterName = "*.fits";
setImageList(filterName);
*/
makeConnections();
switchMode();
initGUIstep2();
// Can't use these in memory mode (ensuring internal consistency, and avoiding very complex code)
// filterLabel->hide();
// filterLineEdit->hide();
}
// FITS viewer, commandline invocation, with or without an argument
// mode == FITSmonochrome
IView::IView(QString mode, QString name, QWidget *parent) :
QMainWindow(parent),
displayMode(mode),
ui(new Ui::IView)
{
ui->setupUi(this);
initGUI();
if (displayMode == "FITSmonochrome") {
icdw->zoom2scale(zoomLevel);
QFileInfo fileInfo(name);
QString suffix = fileInfo.suffix();
QDir dir;
if (suffix == "") dir = dir.current();
else dir = fileInfo.absoluteDir();
dirName = dir.absolutePath();
filterName = "*.fits";
setImageList(filterName);
makeConnections();
switchMode();
currentFileName = name;
if (!name.isEmpty()) loadFITS(name);
}
else if (displayMode == "SCAMP") {
dirName = name;
scampInteractiveMode = true;
filterName = "*.png";
setImageList(filterName);
makeConnections();
switchMode();
currentId = 0;
loadPNG("", currentId);
}
else if (displayMode == "SCAMP_VIEWONLY") { // just to display the plots, whenever
dirName = name;
scampInteractiveMode = false;
filterName = "*.png";
setImageList(filterName);
makeConnections();
switchMode();
currentId = 0;
loadPNG("", currentId);
}
// TODO: if no refcat subdir found then hide the sourcecat / refcat buttons
initGUIstep2();
}
/*
// FITS viewer, commandline invocation, with or without an argument
// mode == FITSmonochrome
IView::IView(QString mode, QString fileName, QWidget *parent) :
QMainWindow(parent),
displayMode(mode),
ui(new Ui::IView)
{
ui->setupUi(this);
initGUI();
QFileInfo fileInfo(fileName);
QString suffix = fileInfo.suffix();
QDir dir;
if (suffix == "") dir = dir.current();
else dir = fileInfo.absoluteDir();
dirName = dir.absolutePath();
filterName = "*.fits";
setImageList(filterName);
makeConnections();
switchMode();
if (!fileName.isEmpty()) loadFITS(fileName);
// TODO: if no refcat subdir found then hide the sourcecat / refcat buttons
initGUIstep2();
}
*/
/*
// Scamp checkplot viewer
// mode == "SCAMP"
IView::IView(QString mode, QString dirname, QWidget *parent) :
QMainWindow(parent),
dirName(dirname),
displayMode(mode),
scampInteractiveMode(true),
ui(new Ui::IView)
{
ui->setupUi(this);
initGUI();
// get a list of all PNG files in this directory
filterName = "*.png";
setImageList(filterName);
makeConnections();
currentId = 0;
switchMode();
loadPNG("", currentId);
initGUIstep2();
}
*/
// Used by imstatistics (opening iview without data point selection)
// mode = FITSmonochrome
// Used to display coadded images
IView::IView(QString mode, QString dirname, QString filter, QWidget *parent) :
QMainWindow(parent),
dirName(dirname),
filterName(filter),
displayMode(mode),
ui(new Ui::IView)
{
ui->setupUi(this);
initGUI();
filterLineEdit->setText(filterName);
// Hide redshift action
ui->actionRedshift->setVisible(false);
icdw->zoom2scale(zoomLevel);
// get a list of all FITS files in this directory
setImageList(filterName);
pageLabel->setText("? / "+QString::number(numImages));
makeConnections();
switchMode();
if (numImages > 0) {
currentFileName = imageList[0];
loadFITS(dirName+'/'+imageList[0]);
}
initGUIstep2();
}
// Used by imstatistics (opening iview with a data point selected)
// mode = FITSmonochrome
IView::IView(QString mode, QString dirname, QString fileName, QString filter, QWidget *parent) :
QMainWindow(parent),
dirName(dirname),
filterName(filter),
currentFileName(fileName),
displayMode(mode),
ui(new Ui::IView)
{
ui->setupUi(this);
initGUI();
// Hide redshift action
ui->actionRedshift->setVisible(false);
// qDebug() << "mode imstatistics 2:" << mode << filterName;
filterLineEdit->setText(filterName);
icdw->zoom2scale(zoomLevel);
// get a list of all FITS files in this directory
setImageList(filterName);
pageLabel->setText("? / "+QString::number(numImages));
makeConnections();
switchMode();
loadFITS(dirName+'/'+fileName);
initGUIstep2();
}
// Displaying color images
// mode = FITScolor
IView::IView(QString mode, QString dirname, QString rChannel, QString gChannel, QString bChannel,
float factorR, float factorB, QWidget *parent) :
QMainWindow(parent),
dirName(dirname),
filterName("*.fits"),
displayMode(mode),
ui(new Ui::IView),
ChannelR(rChannel),
ChannelG(gChannel),
ChannelB(bChannel)
{
ui->setupUi(this);
initGUI();
// Hide redshift action
ui->actionRedshift->setVisible(false);
// The list of the three FITS images
imageList << ChannelR << ChannelG << ChannelB;
numImages = imageList.length();
// Update the dockwidget
colordw->colorFactorZeropoint[0] = factorR;
colordw->colorFactorZeropoint[1] = 1.0;
colordw->colorFactorZeropoint[2] = factorB;
colordw->colorFactorApplied[0] = factorR;
colordw->colorFactorApplied[1] = 1.0;
colordw->colorFactorApplied[2] = factorB;
colordw->ui->redFactorLineEdit->setText(QString::number(factorR, 'f', 3));
colordw->ui->blueFactorLineEdit->setText(QString::number(factorB, 'f', 3));
makeConnections();
switchMode();
loadColorFITS(icdw->zoom2scale(zoomLevel));
initGUIstep2();
/*
ui->toolBar->addWidget(redResetPushButton);
ui->toolBar->addWidget(redFactorLineEdit);
ui->toolBar->addWidget(redSlider);
ui->toolBar->addSeparator();
ui->toolBar->addWidget(blueResetPushButton);
ui->toolBar->addWidget(blueFactorLineEdit);
ui->toolBar->addWidget(blueSlider);
redSlider->setMinimum(0);
redSlider->setMaximum(sliderSteps);
redSlider->setValue(sliderSteps/2);
redSlider->setMinimumWidth(150);
redSlider->setMaximumWidth(250);
redFactorLineEdit->setText(QString::number(factorR, 'f', 3));
redFactorLineEdit->setMinimumWidth(120);
redFactorLineEdit->setMaximumWidth(120);
redResetPushButton->setText("Reset red factor");
blueSlider->setMinimum(0);
blueSlider->setMaximum(sliderSteps);
blueSlider->setValue(sliderSteps/2);
blueSlider->setMinimumWidth(150);
blueSlider->setMaximumWidth(250);
blueFactorLineEdit->setText(QString::number(factorB, 'f', 3));
blueFactorLineEdit->setMinimumWidth(120);
blueFactorLineEdit->setMaximumWidth(120);
blueResetPushButton->setText("Reset blue factor");
*/
}
// Force the user to make a decision in case we are in interactive mode
// viewing the scamp checkplots, and the user wants to close the dialog
// by closing the window directly, not by accepting or rejecting a solution
void IView::closeEvent(QCloseEvent *event)
{
// qDebug() << fitsData.capacity();
// fitsData.clear();
// fitsData.squeeze();
timer->stop();
if (scampInteractiveMode && !scampCorrectlyClosed) {
QMessageBox msgBox;
msgBox.setText("Accept or reject the astrometric solution.");
msgBox.setInformativeText("THELI needs to know whether to update the FITS headers with "
"the astrometric solution or not. If in doubt, click reject. "
"You can re-run the astrometric solution at any time. \n\n");
QAbstractButton *pButtonAccept = msgBox.addButton(tr("Accept"), QMessageBox::YesRole);
QAbstractButton *pButtonReject = msgBox.addButton(tr("Reject"), QMessageBox::YesRole);
QAbstractButton *pButtonAgain = msgBox.addButton(tr("Show me again"), QMessageBox::YesRole);
msgBox.exec();
if (msgBox.clickedButton()==pButtonAccept) emit solutionAcceptanceState(true);
else if (msgBox.clickedButton()==pButtonReject) emit solutionAcceptanceState(false);
else if (msgBox.clickedButton()==pButtonAgain) {
event->ignore();
return;
}
}
writePreferenceSettings();
emit closed();
event->accept();
}
IView::~IView()
{
if (dataIntSet) {
delete [] dataInt;
dataInt = nullptr;
}
if (dataIntRSet) {
delete [] dataIntR;
dataIntR = nullptr;
}
if (dataIntGSet) {
delete [] dataIntG;
dataIntG = nullptr;
}
if (dataIntBSet) {
delete [] dataIntB;
dataIntB = nullptr;
}
if (dataBinnedIntSet) {
delete [] dataBinnedInt;
dataBinnedInt = nullptr;
}
if (dataBinnedIntRSet) {
delete [] dataBinnedIntR;
dataBinnedIntR = nullptr;
}
if (dataBinnedIntGSet) {
delete [] dataBinnedIntG;
dataBinnedIntG = nullptr;
}
if (dataBinnedIntBSet) {
delete [] dataBinnedIntB;
dataBinnedIntB = nullptr;
}
// It appears that 'scene' does not take ownership of the pixmapitem.
// nullptr if e.g. closing the GUI without saving the images. Don't know how that can be related, but here we go ...
if (pixmapItem != nullptr) {
delete pixmapItem;
pixmapItem = nullptr;
}
// if (binnedPixmapItem != nullptr) {
// delete binnedPixmapItem;
// binnedPixmapItem = nullptr;
// }
if (magnifiedPixmapItem != nullptr) {
// delete magnifiedPixmapItem;
// magnifiedPixmapItem = nullptr;
}
delete ui;
// if (icdwDefined) delete icdw;
// if (scampdwDefined) delete scampdw;
if (!fromMemory) {
if (wcsInit) wcsfree(wcs); // wcs is a pointer to MyImage if loaded from memory, hence we must not delete it here!
}
// delete wcs;
delete myGraphicsView;
delete scene;
myGraphicsView = nullptr;
scene = nullptr;
}
void IView::makeConnections()
{
connect(ui->actionClose, &QAction::triggered, this, &IView::close);
connect(ui->actionLoadImageFromDrive, &QAction::triggered, this, &IView::loadImage);
connect(ui->actionStart, &QAction::triggered, this, &IView::startAction_triggered);
connect(ui->actionEnd, &QAction::triggered, this, &IView::endAction_triggered);
connect(ui->actionPrevious, &QAction::triggered, this, &IView::previousAction_triggered);
connect(ui->actionNext, &QAction::triggered, this, &IView::nextAction_triggered);
connect(ui->actionForward, &QAction::triggered, this, &IView::forwardAction_triggered);
connect(ui->actionBack, &QAction::triggered, this, &IView::backAction_triggered);
connect(ui->actionSourceCat, &QAction::triggered, this, &IView::showSourceCat);
connect(ui->actionRefCat, &QAction::triggered, this, &IView::showReferenceCat);
// myGraphicsView = new MyGraphicsView(this);
myGraphicsView = new MyGraphicsView();
QPalette backgroundPalette;
backgroundPalette.setColor(QPalette::Base, QColor("#000000"));
myGraphicsView->setPalette(backgroundPalette);
myGraphicsView->setMouseTracking(true);
ui->graphicsLayout->addWidget(myGraphicsView);
connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::showCurrentMousePos);
connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::collectLocalStatisticsSample);
connect(myGraphicsView, &MyGraphicsView::rightDragTravelled, this, &IView::adjustBrightnessContrast);
connect(myGraphicsView, &MyGraphicsView::leftDragTravelled, this, &IView::drawSeparationVector);
connect(myGraphicsView, &MyGraphicsView::middleSkyDragTravelled, this, &IView::drawSkyCircle);
connect(myGraphicsView, &MyGraphicsView::middleMaskingDragTravelled, this, &IView::drawMaskingPolygon);
connect(myGraphicsView, &MyGraphicsView::middleWCSTravelled, this, &IView::updateCRPIX);
connect(myGraphicsView, &MyGraphicsView::middleWCSreleased, this, &IView::updateCRPIXFITS);
connect(myGraphicsView, &MyGraphicsView::middlePressResetCRPIX, this, &IView::middlePressResetCRPIXreceived);
connect(myGraphicsView, &MyGraphicsView::rightPress, this, &IView::initDynrangeDrag);
connect(myGraphicsView, &MyGraphicsView::leftPress, this, &IView::initSeparationVector);
connect(myGraphicsView, &MyGraphicsView::leftPress, this, &IView::sendStatisticsCenter);
connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, this, &IView::clearSeparationVector);
connect(myGraphicsView, &MyGraphicsView::middleButtonReleased, this, &IView::appendSkyCircle);
connect(myGraphicsView, &MyGraphicsView::rightButtonReleased, this, &IView::redrawSkyCirclesAndCats);
connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, this, &IView::updateSkyCircles);
connect(myGraphicsView, &MyGraphicsView::mouseEnteredView, icdw, &IvConfDockWidget::mouseEnteredViewReceived);
connect(myGraphicsView, &MyGraphicsView::mouseLeftView, icdw, &IvConfDockWidget::mouseLeftViewReceived);
connect(myGraphicsView, &MyGraphicsView::viewportChanged, this, &IView::viewportChangedReceived);
connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::updateNavigatorMagnifiedReceived);
connect(myGraphicsView, &MyGraphicsView::currentMousePos, this, &IView::showWavelength);
connect(myGraphicsView, &MyGraphicsView::leftDragTravelled, &restframeAxis, &MyAxis::redshiftSpectrum);
connect(myGraphicsView, &MyGraphicsView::leftDragTravelled, &spectrumAxis, &MyAxis::redshiftSpectrum);
connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, &restframeAxis, &MyAxis::closeRedshift);
connect(myGraphicsView, &MyGraphicsView::leftButtonReleased, &spectrumAxis, &MyAxis::closeRedshift);
connect(scene, &MyGraphicsScene::itemDeleted, this, &IView::updateSkyCircles);
connect(scene, &MyGraphicsScene::mouseLeftScene, icdw, &IvConfDockWidget::mouseLeftViewReceived);
connect(wcsdw, &IvWCSDockWidget::CDmatrixChanged, this, &IView::updateCDmatrix);
connect(wcsdw, &IvWCSDockWidget::CDmatrixChangedFITS, this, &IView::updateCDmatrixFITS);
connect(wcsdw, &IvWCSDockWidget::CDmatrixChanged, icdw, &IvConfDockWidget::drawCompass);
connect(statdw, &IvStatisticsDockWidget::visibilityChanged, this, &IView::updateStatisticsButton);
connect(zdw, &IvRedshiftDockWidget::visibilityChanged, this, &IView::updateRedshiftButton);
connect(finderdw, &IvFinderDockWidget::visibilityChanged, this, &IView::updateFinderButton);
connect(finderdw, &IvFinderDockWidget::targetResolved, this, &IView::targetResolvedReceived);
connect(finderdw, &IvFinderDockWidget::clearTargetResolved, scene, &MyGraphicsScene::removeCrosshair);
connect(timer, &QTimer::timeout, this, &IView::forwardAction_triggered);
connect(timer, &QTimer::timeout, this, &IView::backAction_triggered);
connect(this, &IView::middleMouseModeChanged, myGraphicsView, &MyGraphicsView::updateMiddleMouseMode);
connect(this, &IView::updateNavigatorMagnified, icdw, &IvConfDockWidget::updateNavigatorMagnifiedReceived);
connect(this, &IView::updateNavigatorBinned, icdw, &IvConfDockWidget::updateNavigatorBinnedReceived);
connect(this, &IView::updateNavigatorBinnedViewport, icdw, &IvConfDockWidget::updateNavigatorBinnedViewportReceived);
connect(this, &IView::statisticsSampleAvailable, statdw, &IvStatisticsDockWidget::statisticsSampleReceiver);
connect(this, &IView::statisticsSampleColorAvailable, statdw, &IvStatisticsDockWidget::statisticsSampleColorReceiver);
connect(filterLineEdit, &QLineEdit::textChanged, this, &IView::filterLineEdit_textChanged);
connect(icdw->binnedGraphicsView, &MyBinnedGraphicsView::fovRectCenterChanged, this, &IView::fovCenterChangedReceiver);
connect(this, &IView::updateNavigatorBinnedWCS, icdw, &IvConfDockWidget::receiveWCS);
connect(this, &IView::clearMagnifiedScene, icdw, &IvConfDockWidget::clearMagnifiedSceneReceiver);
connect(this, &IView::newImageLoaded, this, &IView::updateAxes);
connect(this, &IView::newImageLoaded, this, &IView::resetRedshift);
connect(this, &IView::wavelengthUpdated, zdw, &IvRedshiftDockWidget::showWavelength);
connect(&restframeAxis, &MyAxis::redshiftRecomputed, this, &IView::updateAxes);
connect(&spectrumAxis, &MyAxis::redshiftRecomputed, this, &IView::updateAxes);
connect(&spectrumAxis, &MyAxis::redshiftUpdated, zdw, &IvRedshiftDockWidget::redshiftUpdatedReceiver);
}
void IView::switchMode(QString mode)
{
if (!mode.isEmpty()) displayMode = mode;
ui->actionClose->setVisible(true);
if (displayMode.contains("SCAMP")) {
this->setWindowTitle("iView --- Scamp check plots");
// Disable file menu. Must stay within interactive mode. Also, 'close' will cause segfault.
ui->menuFile->setVisible(false);
middleMouseActionGroup->setVisible(false);
// many of the settings below are handled by the modeStackedWidget already!
ui->actionSourceCat->setVisible(false);
ui->actionRefCat->setVisible(false);
ui->actionBack->setVisible(false);
ui->actionForward->setVisible(false);
pageLabel->show();
speedLabel->hide();
speedSpinBox->hide();
ui->actionBack->setEnabled(true);
ui->actionForward->setEnabled(true);
ui->actionPrevious->setEnabled(true);
ui->actionNext->setEnabled(true);
ui->actionStart->setEnabled(true);
ui->actionEnd->setEnabled(true);
}
else if (displayMode == "FITSmonochrome") {
this->setWindowTitle("iView --- FITS file viewer");
middleMouseActionGroup->setVisible(true);
ui->actionSourceCat->setVisible(true);
ui->actionRefCat->setVisible(true);
pageLabel->show();
speedLabel->show();
speedSpinBox->show();
ui->actionBack->setEnabled(true);
ui->actionForward->setEnabled(true);
ui->actionPrevious->setEnabled(true);
ui->actionNext->setEnabled(true);
ui->actionStart->setEnabled(true);
ui->actionEnd->setEnabled(true);
}
else if (displayMode == "MEMview") {
this->setWindowTitle("iView --- Memory viewer");
middleMouseActionGroup->setVisible(true);
ui->actionSourceCat->setVisible(true);
ui->actionRefCat->setVisible(true);
pageLabel->show();
speedLabel->show();
speedSpinBox->show();
ui->actionLoadImageFromDrive->setDisabled(true);
ui->actionBack->setEnabled(true);
ui->actionForward->setEnabled(true);
ui->actionPrevious->setEnabled(true);
ui->actionNext->setEnabled(true);
ui->actionStart->setEnabled(true);
ui->actionEnd->setEnabled(true);
}
else if (displayMode == "FITScolor") {
this->setWindowTitle("iView --- FITS file viewer");
middleMouseActionGroup->setVisible(false);
ui->actionSourceCat->setVisible(false);
ui->actionRefCat->setVisible(false);
pageLabel->hide();
speedLabel->hide();
speedSpinBox->hide();
ui->actionBack->setVisible(false);
ui->actionForward->setVisible(false);
ui->actionPrevious->setVisible(false);
ui->actionNext->setVisible(false);
ui->actionStart->setVisible(false);
ui->actionEnd->setVisible(false);
}
else if (displayMode == "CLEAR") {
this->setWindowTitle("iView --- FITS file viewer");
middleMouseActionGroup->setVisible(true);
ui->actionBack->setDisabled(true);
ui->actionForward->setDisabled(true);
ui->actionPrevious->setDisabled(true);
ui->actionNext->setDisabled(true);
ui->actionStart->setDisabled(true);
ui->actionEnd->setDisabled(true);
ui->actionSourceCat->setDisabled(true);
ui->actionRefCat->setDisabled(true);
}
// Also adjust the dockwidgets
// NOT in SCAMP mode, because there it is not initialized!
if (!displayMode.contains("SCAMP")) icdw->switchMode(displayMode);
}
void IView::initGUI()
{
addDockWidgets(); // Widgets must be alive early on
// QRect rec = QApplication::desktop()->screenGeometry(); // deprecated in Qt5.14
QScreen *screen = QGuiApplication::screens().at(0);
QRect rec = screen->geometry();
screenHeight = rec.height();
screenWidth = rec.width();
middleMouseActionGroup->setExclusive(true);
middleMouseActionGroup->addAction(ui->actionDragMode);
middleMouseActionGroup->addAction(ui->actionSkyMode);
middleMouseActionGroup->addAction(ui->actionMaskingMode);
middleMouseActionGroup->addAction(ui->actionWCSMode);
ui->actionDragMode->setChecked(true);
wcsdw->hide();
if (displayMode.contains("SCAMP")) {
middleMouseActionGroup->setVisible(false); // NOTE: must add actions above before we can "hide" them simply by hiding the group
}
else {
middleMouseActionGroup->setVisible(true);
}
readPreferenceSettings();
setWindowIcon(QIcon(":/icons/iview.png"));
// QFile file(":/qss/default.qss");
// file.open(QFile::ReadOnly);
// QString styleSheet = QString::fromLatin1(file.readAll());
// qApp->setStyleSheet(styleSheet);
this->setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
}
void IView::initGUIstep2()
{
// update the startDirName
if (!startDirNameSet) {
startDirName = dirName;
startDirNameSet = true;
}
if (!displayMode.contains("SCAMP")) {
// ui->toolBar->addWidget(speedLabel);
// speedLabel->setText(" Frame rate");
ui->toolBar->addWidget(speedSpinBox);
speedSpinBox->setValue(2);
speedSpinBox->setMinimum(1);
speedSpinBox->setMaximum(10);
speedSpinBox->setSuffix(" Hz");
speedSpinBox->setToolTip("Frame rate for forward / backward playing");
ui->toolBar->addWidget(filterLabel);
filterLabel->setText(" Filter");
ui->toolBar->addWidget(filterLineEdit);
filterLineEdit->setStatusTip("Only these images will be selected when using the yellow navigation buttons at the top.");
}
pageLabel->setMaximumWidth(200);
pageLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
ui->toolBar->addWidget(pageLabel);
ui->toolBar->addSeparator();
QWidget* empty = new QWidget();
empty->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Preferred);
ui->toolBar->addWidget(empty);
}
void IView::addDockWidgets()
{
setDockOptions(DockOption::AllowNestedDocks);
if (displayMode == "FITSmonochrome" || displayMode == "MEMview") {
icdw = new IvConfDockWidget(this);
addDockWidget(Qt::LeftDockWidgetArea, icdw);
icdw->setFloating(false);
icdw->raise();
}
else if (displayMode == "FITScolor") {
icdw = new IvConfDockWidget(this);
addDockWidget(Qt::LeftDockWidgetArea, icdw);
icdw->setFloating(false);
icdw->raise();
colordw = new IvColorDockWidget(this);
addDockWidget(Qt::LeftDockWidgetArea, colordw);
colordw->setFloating(false);
colordw->raise();
}
else if (displayMode == "CLEAR") {
icdw = new IvConfDockWidget(this);
addDockWidget(Qt::LeftDockWidgetArea, icdw);
icdw->setFloating(false);
icdw->raise();
}
else if (displayMode == "SCAMP") {
scampdw = new IvScampDockWidget(this);
icdw = new IvConfDockWidget(this);
addDockWidget(Qt::LeftDockWidgetArea, scampdw);
scampdw->setFloating(false);
icdw->hide();
scampdw->raise();
finderdw->hide();
statdw->hide();
zdw->hide();
}
else if (displayMode == "SCAMP_VIEWONLY") {
icdw = new IvConfDockWidget(this);
icdw->hide();
finderdw->hide();
statdw->hide();
zdw->hide();
}
// Connections
if (displayMode == "SCAMP") {
scampdwDefined = true;
connect(scampdw, &IvScampDockWidget::solutionAcceptanceState, this, &IView::solutionAcceptanceStateReceived);
}
else if (displayMode == "SCAMP_VIEWONLY") {
scampdwDefined = false;
}
else {
icdwDefined = true;
connect(icdw, &IvConfDockWidget::autoContrastPushButton_toggled, this, &IView::autoContrastPushButton_toggled_receiver);
connect(icdw, &IvConfDockWidget::minmaxLineEdit_returnPressed, this, &IView::minmaxLineEdit_returnPressed_receiver);
connect(icdw, &IvConfDockWidget::minmaxLineEdit_returnPressed, this, &IView::minmaxLineEdit_returnPressed_receiver);
connect(icdw, &IvConfDockWidget::zoomFitPushButton_clicked, this, &IView::zoomFitPushButton_clicked_receiver);
connect(icdw, &IvConfDockWidget::zoomInPushButton_clicked, this, &IView::zoomInPushButton_clicked_receiver);
connect(icdw, &IvConfDockWidget::zoomOutPushButton_clicked, this, &IView::zoomOutPushButton_clicked_receiver);
connect(icdw, &IvConfDockWidget::zoomZeroPushButton_clicked, this, &IView::zoomZeroPushButton_clicked_receiver);
connect(icdw, &IvConfDockWidget::zoomFitPushButton_clicked, this, &IView::updateAxes);
connect(icdw, &IvConfDockWidget::zoomInPushButton_clicked, this, &IView::updateAxes);
connect(icdw, &IvConfDockWidget::zoomOutPushButton_clicked, this, &IView::updateAxes);
connect(icdw, &IvConfDockWidget::zoomZeroPushButton_clicked, this, &IView::updateAxes);
connect(icdw, &IvConfDockWidget::closeIview, this, &IView::close);
}
if (!displayMode.contains("SCAMP")) {
addDockWidget(Qt::LeftDockWidgetArea, statdw);
statdw->hide();
addDockWidget(Qt::LeftDockWidgetArea, finderdw);
finderdw->hide();
addDockWidget(Qt::LeftDockWidgetArea, zdw);
zdw->hide();
}
}
void IView::updateStatisticsButton()
{
if (statdw->isVisible()) ui->actionImage_statistics->setChecked(true);
else ui->actionImage_statistics->setChecked(false);
}
void IView::updateRedshiftButton()
{
if (zdw->isVisible()) ui->actionRedshift->setChecked(true);
else ui->actionRedshift->setChecked(false);
}
void IView::updateFinderButton()
{
if (finderdw->isVisible()) {
ui->actionFinder->setChecked(true);
}
else {
ui->actionFinder->setChecked(false);
scene->removeCrosshair();
}
}
| 30,293
|
C++
|
.cc
| 733
| 35.638472
| 139
| 0.699837
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,414
|
events.cc
|
schirmermischa_THELI/src/iview/events.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "iview.h"
#include "ui_iview.h"
#include "../functions.h"
#include "mygraphicsview.h"
#include "mygraphicsellipseitem.h"
#include "mygraphicsscene.h"
#include "ui_ivconfdockwidget.h"
#include <QDir>
#include <QSettings>
#include <QGraphicsPixmapItem>
#include <QPixmap>
#include <QGraphicsGridLayout>
#include <QDebug>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QToolBar>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPointF>
#include <QScrollBar>
#include <QTimer>
void IView::initSeparationVector(QPointF pointStart)
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
startLeftClickInsideItem = false;
QList<QGraphicsItem*> listStart = scene->items(pointStart, Qt::IntersectsItemShape);
for (auto & it : listStart) {
if (it->type() == QGraphicsEllipseItem::Type) startLeftClickInsideItem = true;
}
}
void IView::initDynrangeDrag()
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
dynRangeMinDragStart = dynRangeMin;
dynRangeMaxDragStart = dynRangeMax;
// Must clear all items on the scene, then redraw afterwards
if (!skyCircleItems.isEmpty()) skyCircleItems.clear();
if (!sourceCatItems.isEmpty()) sourceCatItems.clear();
if (!refCatItems.isEmpty()) refCatItems.clear();
if (!acceptedSkyCircleItems.isEmpty()) {
for (auto &it : acceptedSkyCircleItems) {
scene->removeItem(it);
}
}
if (scene->crosshairShown) scene->removeCrosshair();
clearAxes();
}
void IView::showCurrentMousePos(QPointF point)
{
// This function receives the image coords from a mouseMoveEvent
// and translates them
// Cursor coordinates:
// Still have to mirror in y, and add a half pixel correction
// to be conform with the FITS standard
if (displayMode == "CLEAR"
|| displayMode.contains("SCAMP")
|| !currentMyImage) return;
float x_cursor;
float y_cursor;
// constant offsets required to show same coordinates as in skycat / ds9
x_cursor = point.x() + 0.5;
y_cursor = naxis2 - point.y() + 0.5;
// Display the information
QString xpos = QString::number(x_cursor);
QString ypos = QString::number(y_cursor);
icdw->ui->xposLabel->setText(xpos);
icdw->ui->yposLabel->setText(ypos);
// Pixel index in the 2D image
long i = x_cursor - 0.5;
long j = y_cursor - 0.5;
if (i<naxis1 && i>=0 && j<naxis2 && j>=0) {
if (displayMode == "FITSmonochrome" || displayMode == "MEMview") {
QString value = QString::number(fitsData[i+naxis1*j]) + " " + currentMyImage->bunit;
icdw->ui->valueLabel->setText(value);
}
else {
// Color FITS
QString rval = QString::number(fitsDataR[i+naxis1*j]) + " " + currentMyImage->bunit;
QString gval = QString::number(fitsDataG[i+naxis1*j]) + " " + currentMyImage->bunit;
QString bval = QString::number(fitsDataB[i+naxis1*j]) + " " + currentMyImage->bunit;
icdw->ui->valueLabel->setText(rval);
icdw->ui->valueGreenLabel->setText(gval);
icdw->ui->valueBlueLabel->setText(bval);
}
}
else {
if (displayMode == "FITSmonochrome" || displayMode == "MEMview") {
icdw->ui->valueLabel->setText("");
}
else {
icdw->ui->valueLabel->setText("");
icdw->ui->valueGreenLabel->setText("");
icdw->ui->valueBlueLabel->setText("");
}
}
xy2sky(x_cursor, y_cursor);
// Show the magnified area in the magnify window
// Translate FITS pixel position in the large window to the magnify window
icdw->magnifiedGraphicsView->mapFromScene(point.x(),point.y());
icdw->magnifiedGraphicsView->setScene(icdw->magnifiedScene);
icdw->magnifiedGraphicsView->show();
}
void IView::collectLocalStatisticsSample(QPointF point)
{
if (!statdw->isVisible()) return;
// Pixel index in the 2D image
long x = point.x();
long y = naxis2 - point.y();
int s = statdw->statWidth;
int imin = x-s;
int imax = x+s;
int jmin = y-s;
int jmax = y+s;
if (imin < 0) imin = 0;
if (imax >= naxis1) imax = naxis1-1;
if (jmin < 0) jmin = 0;
if (jmax >= naxis2) jmax = naxis2-1;
if (displayMode == "FITSmonochrome" || displayMode == "MEMview") {
QVector<float> sample;
for (int j = jmin; j<=jmax; ++j) {
for (int i = imin; i<=imax; ++i) {
sample.append(fitsData[i+naxis1*j]);
}
}
emit statisticsSampleAvailable(sample);
}
else if (displayMode == "FITScolor") {
QVector<float> sampleR;
QVector<float> sampleG;
QVector<float> sampleB;
for (int j = jmin; j<=jmax; ++j) {
for (int i = imin; i<=imax; ++i) {
sampleR.append(fitsDataR[i+naxis1*j]);
sampleG.append(fitsDataG[i+naxis1*j]);
sampleB.append(fitsDataB[i+naxis1*j]);
}
}
emit statisticsSampleColorAvailable(sampleR, sampleG, sampleB);
}
}
void IView::adjustBrightnessContrast(QPointF point)
{
if (displayMode.contains("SCAMP")
|| displayMode == "CLEAR"
|| !currentMyImage) return;
// Also leave if actively cycling through images
// (will crash because the scene items become unavailable while dragging)
// Or (NOT IMPLEMENTED): stop cycling through images
if (ui->actionForward->isChecked()) return;
if (ui->actionBack->isChecked()) return;
icdw->ui->autocontrastPushButton->setChecked(false);
// This slot receives the right-click drag vector
int dx = point.x();
int dy = point.y();
// Adjust brightness level (shift lower bound of dynamic range)
// Adjust contrast symmetrically around
float range = dynRangeMaxDragStart - dynRangeMinDragStart;
// dynRangeMin = dynRangeMinDragStart * (1.1*(100.+dy)/100.+0.01) - 7*dx;
// dynRangeMax = dynRangeMaxDragStart / (1.1*(100.+dy)/100.+0.01);
float cutoff = 0.95;
float scaling = dy/100.*cutoff;
if (scaling > cutoff) scaling = cutoff;
if (scaling < -cutoff) scaling = -cutoff;
float deltaRange = - 0.5 * range * scaling;
dynRangeMax = dynRangeMaxDragStart - deltaRange;
// dynRangeMin = dynRangeMinDragStart + deltaRange + 7*dx;
dynRangeMin = dynRangeMinDragStart + deltaRange + range*0.4*dx/100;
// qDebug() << dynRangeMinDragStart << deltaRange << 7*dx << scaling << dy;
// if (dynRangeMin <= 1.01*dynRangeMin) dynRangeMax = 1.01*dynRangeMin;
int validDigits = 3-log(fabs(dynRangeMax))/log(10);
if (validDigits<0) validDigits = 0;
icdw->ui->minLineEdit->setText(QString::number(dynRangeMin,'f',validDigits));
icdw->ui->maxLineEdit->setText(QString::number(dynRangeMax,'f',validDigits));
mapFITS();
myGraphicsView->setScene(scene);
myGraphicsView->show();
// Show the magnified area in the magnify window
icdw->magnifiedGraphicsView->setScene(icdw->magnifiedScene);
icdw->magnifiedGraphicsView->show();
emit updateNavigatorBinned(binnedPixmapItem);
if (wcs != nullptr && wcsInit != false) {
emit updateNavigatorBinnedWCS(wcs, wcsInit);
}
}
double IView::haversine(double x1, double y1, double x2, double y2)
{
if (!wcsInit) return 0.;
double world1[2];
double world2[2];
double phi;
double theta;
double imgcrd[2];
double pixcrd[2];
int stat[1];
// zero-indexing of C++ vectors can be ignored when measuring distances.
pixcrd[0] = x1;
pixcrd[1] = y1;
wcsp2s(wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world1, stat);
double alpha1 = world1[0] * rad;
double delta1 = world1[1] * rad;
// Get alpha / delta for the 2nd point
pixcrd[0] = x2;
pixcrd[1] = y2;
wcsp2s(wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world2, stat);
double alpha2 = world2[0] * rad;
double delta2 = world2[1] * rad;
double dDelta = delta2 - delta1;
double dAlpha = alpha2 - alpha1;
// Haversine formula to calculate angular distance between two points on a sphere in degrees, also works for very small separations
return 2.*asin( sqrt( pow(sin(dDelta/2.),2) + cos(delta1)*cos(delta2)*pow(sin(dAlpha/2.),2))) / rad;
}
void IView::measureAngularSeparations(QPointF pointStart, QPointF pointEnd, double &sepX, double &sepY, double &sepD)
{
qreal x1 = pointStart.x();
qreal y1 = pointStart.y();
qreal x2 = pointEnd.x();
qreal y2 = pointEnd.y();
// The "diagonal"
sepD = haversine(x1, y1, x2, y2) * 3600.;
// The "horizontal"
sepX = haversine(x1, y1, x2, y1) * 3600.;
// The "vertical"
sepY = haversine(x1, y1, x1, y2) * 3600.;
}
void IView::drawSeparationVector(QPointF pointStart, QPointF pointEnd)
{
if (displayMode.contains("SCAMP")
|| displayMode == "CLEAR"
|| !currentMyImage) return;
if (zdw->isVisible()) return;
// (will crash because the scene items become unavailable while dragging)
if (ui->actionForward->isChecked()) return;
if (ui->actionBack->isChecked()) return;
// don't draw the vector if there is an ellipse underneath
if (startLeftClickInsideItem) return;
// QPen pen(QColor("#ffaa00"));
QPen pen(QColor("#35ffff"));
pen.setWidth(0);
// QPen penDashed(QColor("#ffaa00"));
QPen penDashed(QColor("#35ffff"));
penDashed.setWidth(0);
QVector<qreal> dashes;
dashes << 5 << 5;
penDashed.setDashPattern(dashes);
qreal x1 = pointStart.x();
qreal y1 = pointStart.y();
qreal x2 = pointEnd.x();
qreal y2 = pointEnd.y();
qreal dy = y2-y1;
qreal dx = x2-x1;
double sepX = 0.;
double sepY = 0.;
double sepD = 0.;
measureAngularSeparations(pointStart, pointEnd, sepX, sepY, sepD);
QString sepXString = getVectorLabel(sepX);
QString sepYString = getVectorLabel(sepY);
QString sepDString = getVectorLabel(sepD);
clearVectorItems();
QGraphicsTextItem *labelX = scene->addText(sepXString);
QGraphicsTextItem *labelY = scene->addText(sepYString);
QGraphicsTextItem *labelD = scene->addText(sepDString);
QFont currentFont = this->font();
qreal rescale;
if (!icdw->ui->zoomFitPushButton->isChecked()) rescale = icdw->zoom2scale(zoomLevel);
else rescale = myGraphicsView->transform().m11();
currentFont.setPointSize(int(float(currentFont.pointSize())/rescale));
labelX->setFont(currentFont);
labelY->setFont(currentFont);
labelD->setFont(currentFont);
//labelX->setDefaultTextColor(QColor("#ffff00"));
//labelY->setDefaultTextColor(QColor("#ffff00"));
//labelD->setDefaultTextColor(QColor("#ffff00"));
// use an orange background (same as #ffaa00) for the angular distances
labelX->setHtml(QString("<div style='background:rgba(53, 255, 255, 50%);'>" + QString(" ") + sepXString + QString(" ") + QString("</div>") ));
labelY->setHtml(QString("<div style='background:rgba(53, 255, 255, 50%);'>" + QString(" ") + sepYString + QString(" ") + QString("</div>") ));
labelD->setHtml(QString("<div style='background:rgba(53, 255, 255, 50%);'>" + QString(" ") + sepDString + QString(" ") + QString("</div>") ));
// labelX->setHtml(QString("<div style='background:rgba(255, 170, 0, 100%);'>" + QString(" ") + sepXString + QString(" ") + QString("</div>") ));
// labelY->setHtml(QString("<div style='background:rgba(255, 170, 0, 100%);'>" + QString(" ") + sepYString + QString(" ") + QString("</div>") ));
// labelD->setHtml(QString("<div style='background:rgba(255, 170, 0, 100%);'>" + QString(" ") + sepDString + QString(" ") + QString("</div>") ));
labelX->setDefaultTextColor(QColor("#000000"));
labelY->setDefaultTextColor(QColor("#000000"));
labelD->setDefaultTextColor(QColor("#000000"));
qreal xpos = 0.5*(x1+x2);
qreal ypos = 0.5*(y1+y2);
qreal x_yoffset = 0.;
qreal y_xoffset = 0.;
qreal d_xoffset = 0;
qreal d_yoffset = 0;
getVectorOffsets(dx, dy, x_yoffset, y_xoffset, d_xoffset, d_yoffset);
labelX->setPos(xpos-20/icdw->zoom2scale(zoomLevel), y1+x_yoffset);
labelY->setPos(x2+y_xoffset, ypos-10/icdw->zoom2scale(zoomLevel));
labelD->setPos(xpos+d_xoffset, ypos+d_yoffset);
vectorLineItems.append(scene->addLine(x1, y1, x2, y2, pen)); // diagonal
vectorLineItems.append(scene->addLine(x1, y1, x2, y1, penDashed)); // horizontal
vectorLineItems.append(scene->addLine(x2, y1, x2, y2, penDashed)); // vertical
vectorTextItems.append(labelX);
vectorTextItems.append(labelY);
vectorTextItems.append(labelD);
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
// Used to draw separation vectors
void IView::getVectorOffsets(const qreal dx, const qreal dy, qreal &x_yoffset,
qreal &y_xoffset, qreal &d_xoffset, qreal &d_yoffset)
{
qreal s;
if (!icdw->ui->zoomFitPushButton->isChecked()) {
s = icdw->zoom2scale(zoomLevel);
}
else {
s = myGraphicsView->transform().m11();
}
if (dy < 0) x_yoffset = 10/s;
else x_yoffset = -30/s;
if (dx < 0) y_xoffset = -70/s;
else y_xoffset = 10/s;
if (dx>=0 && dy>=0) {
d_xoffset = -50/s;
d_yoffset = 10/s;
}
else if (dx<0 && dy>=0) {
d_xoffset = 10/s;
d_yoffset = 10/s;
}
else if (dx<0 && dy<0) {
d_xoffset = 10/s;
d_yoffset = -25/s;
}
else {
// (dx>=0 && dy<0)
d_xoffset = -50/s;
d_yoffset = -50/s;
}
}
void IView::clearVectorItems()
{
if (!vectorLineItems.isEmpty()) {
for (auto &it : vectorLineItems ) scene->removeItem(it);
vectorLineItems.clear();
}
if (!vectorTextItems.isEmpty()) {
for (auto &it : vectorTextItems ) scene->removeItem(it);
vectorTextItems.clear();
}
}
void IView::clearSkyRectItems()
{
if (!skyRectItems.isEmpty()) {
for (auto &it : skyRectItems ) scene->removeItem(it);
skyRectItems.clear();
}
if (!skyTextItems.isEmpty()) {
for (auto &it : skyTextItems ) scene->removeItem(it);
skyTextItems.clear();
}
}
void IView::clearMaskPolygonItems()
{
if (!maskPolygonItems.isEmpty()) {
for (auto &it : maskPolygonItems ) scene->removeItem(it);
maskPolygonItems.clear();
}
}
void IView::clearMaskRectItems()
{
if (!maskRectItems.isEmpty()) {
for (auto &it : maskRectItems ) scene->removeItem(it);
maskRectItems.clear();
}
}
void IView::clearSkyCircleItems()
{
if (!skyCircleItems.isEmpty()) {
for (auto &it : skyCircleItems ) scene->removeItem(it);
skyCircleItems.clear();
}
}
// currently unused
void IView::drawSkyRectangle(QPointF pointStart, QPointF pointEnd)
{
if (displayMode.contains("SCAMP")
|| displayMode == "CLEAR"
|| !currentMyImage) return;
if (displayMode == "FITScolor") return;
// (will crash because the scene items become unavailable while dragging)
if (ui->actionForward->isChecked()) return;
if (ui->actionBack->isChecked()) return;
QPen pen(QColor("#00ff00"));
pen.setWidth(0);
qreal x1 = pointStart.x();
qreal y1 = pointStart.y();
qreal x2 = pointEnd.x();
qreal y2 = pointEnd.y();
qreal dx = fabs(x2-x1);
qreal dy = fabs(y2-y1);
// Collect alpha and delta of the four vertices
QVector<double> alphaValues;
QVector<double> deltaValues;
// TODO if routine is activated: must translate x/y to FITS coordinate system before computing sky coordinates!
xy2sky(x1,y1,"middleButton");
alphaValues.append(skyRa);
deltaValues.append(skyDec);
xy2sky(x2,y1,"middleButton");
alphaValues.append(skyRa);
deltaValues.append(skyDec);
xy2sky(x2,y2,"middleButton");
alphaValues.append(skyRa);
deltaValues.append(skyDec);
xy2sky(x1,y2,"middleButton");
alphaValues.append(skyRa);
deltaValues.append(skyDec);
double alphaMin = minVec_T(alphaValues);
double alphaMax = maxVec_T(alphaValues);
double deltaMin = minVec_T(deltaValues);
double deltaMax = maxVec_T(deltaValues);
QString raMin = QString::number(alphaMin,'f',6);
QString raMax = QString::number(alphaMax,'f',6);
QString decMin = QString::number(deltaMin,'f',6);
QString decMax = QString::number(deltaMax,'f',6);
QString skyBox = "R.A. min = "+raMin+"\n";
skyBox.append("R.A. max = "+raMax+"\n");
skyBox.append("DEC min = "+decMin+"\n");
skyBox.append("DEC max = "+decMax);
QGraphicsTextItem *labelSkyBox = scene->addText(skyBox);
QFont currentFont = this->font();
qreal rescale;
if (!icdw->ui->zoomFitPushButton->isChecked()) rescale = icdw->zoom2scale(zoomLevel);
else rescale = myGraphicsView->transform().m11();
currentFont.setPointSize(int(float(currentFont.pointSize())/rescale));
labelSkyBox->setFont(currentFont);
labelSkyBox->setDefaultTextColor(QColor("#00ff00"));
labelSkyBox->setPos(x1, y1-100/rescale);
clearSkyRectItems();
qreal xmin = pointStart.x();
qreal ymin = pointStart.y();
if (pointEnd.x() < xmin) xmin = pointEnd.x();
if (pointEnd.y() < ymin) ymin = pointEnd.y();
skyRectItems.append(scene->addRect(xmin, ymin, dx, dy, pen));
skyTextItems.append(labelSkyBox);
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::middlePressResetCRPIXreceived()
{
if (!wcsInit) return;
crpix1_start = wcs->crpix[0];
crpix2_start = wcs->crpix[1];
}
/*
// Receiver for the event when the mouse enters the main graphics view
void IView::mouseEnteredViewReceived()
{
// icdw->ui->navigatorStackedWidget->setCurrentIndex(1);
emit updateNavigatorBinned(binnedPixmapItem);
}
// Receiver for the event when the mouse leaves the main graphics view
void IView::mouseLeftViewReceived()
{
// icdw->ui->navigatorStackedWidget->setCurrentIndex(0);
emit updateNavigatorBinned(binnedPixmapItem);
}
*/
void IView::viewportChangedReceived(QRect viewport_rect)
{
// the currently shown image area, in QImage coordinates
QRectF rect = myGraphicsView->mapToScene(viewport_rect).boundingRect();
// the matching area, in QImage coordinates of the binned overview image
QRect rectBinned = qimageToBinned(rect);
// send the binned rect to the binned navigator window
emit updateNavigatorBinnedViewport(rectBinned);
}
void IView::updateCRPIX(QPointF pointStart, QPointF pointEnd)
{
if (!wcsInit) return;
// Do nothing if no refcat items are displayed.
if (refCatItems.isEmpty()) return;
// Remove items from display
for (auto &it: refCatItems) scene->removeItem(it);
refCatItems.clear();
scene->removeCrosshair();
myGraphicsView->setScene(scene);
myGraphicsView->show();
scene->removeCrosshair();
// Recalculate CRPIX offset
qreal dx = pointEnd.x() - pointStart.x();
qreal dy = -(pointEnd.y() - pointStart.y()); // Image y-axis flipped in graphics view
wcs->crpix[0] = crpix1_start + dx;
wcs->crpix[1] = crpix2_start + dy;
wcs->flag = 0; // force an update of internal wcs params.
showReferenceCat();
checkFinder();
}
void IView::updateCDmatrix(double cd11, double cd12, double cd21, double cd22)
{
if (!wcsInit) return;
// Do nothing if no refcat items are displayed.
if (refCatItems.isEmpty()) return;
// Remove items from display
for (auto &it: refCatItems) scene->removeItem(it);
refCatItems.clear();
scene->removeCrosshair();
myGraphicsView->setScene(scene);
myGraphicsView->show();
// Update CD matrix
wcs->cd[0] = cd11;
wcs->cd[1] = cd12;
wcs->cd[2] = cd21;
wcs->cd[3] = cd22;
wcs->flag = 0; // force an update of internal wcs params.
icdw->cd11 = cd11;
icdw->cd12 = cd12;
icdw->cd21 = cd21;
icdw->cd22 = cd22;
showReferenceCat();
checkFinder();
}
// Called when middle mouse button is released in wcs mode
void IView::updateCRPIXFITS()
{
if (!wcsInit) return;
if (!currentMyImage) return;
// Do nothing if no refcat items are displayed.
if (refCatItems.isEmpty()) return;
int status = 0;
if (currentFileName.isEmpty()) currentFileName = currentMyImage->baseName+".fits";
// force drive dump if FITS file does not exist yet
if (!currentMyImage->imageOnDrive) currentMyImage->writeImage();
// Identical way to reconstruct filenames
// TODO: uniformize
// qDebug() << currentFileName;
// qDebug() << currentMyImage->path+"/"+currentMyImage->chipName+currentMyImage->processingStatus->statusString+".fits";
fitsfile *fptr = nullptr;
fits_open_file(&fptr, (dirName+"/"+currentMyImage->pathExtension+"/"+currentFileName).toUtf8().data(), READWRITE, &status);
fits_update_key_flt(fptr, "CRPIX1", wcs->crpix[0], -5, nullptr, &status);
fits_update_key_flt(fptr, "CRPIX2", wcs->crpix[1], -5, nullptr, &status);
fits_close_file(fptr, &status);
if (status > 0) qDebug() << "IView::updateCRPIXFITS(): cfitsio error code = " << status << dirName+"/"+currentFileName;
}
// Called when slider is released in wcs mode
void IView::updateCDmatrixFITS()
{
if (!wcsInit) return;
if (!currentMyImage) return;
// Do nothing if no refcat items are displayed.
if (refCatItems.isEmpty()) return;
int status = 0;
if (currentFileName.isEmpty()) currentFileName = currentMyImage->baseName+".fits";
fitsfile *fptr = nullptr;
fits_open_file(&fptr, (dirName+"/"+currentMyImage->pathExtension+"/"+currentFileName).toUtf8().data(), READWRITE, &status);
fits_update_key_dbl(fptr, "CD1_1", wcs->cd[0], 8, nullptr, &status);
fits_update_key_dbl(fptr, "CD1_2", wcs->cd[1], 8, nullptr, &status);
fits_update_key_dbl(fptr, "CD2_1", wcs->cd[2], 8, nullptr, &status);
fits_update_key_dbl(fptr, "CD2_2", wcs->cd[3], 8, nullptr, &status);
fits_close_file(fptr, &status);
if (status > 0) qDebug() << "IView::updateCDmatrixFITS(): cfitsio error code = " << status << dirName+"/"+currentFileName;
}
void IView::drawSkyCircle(QPointF pointStart, QPointF pointEnd)
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
if (displayMode == "FITScolor") return;
QPen pen(QColor("#00ff00"));
pen.setWidth(0);
QVector<qreal> dashes;
dashes << 3 << 3;
pen.setDashPattern(dashes);
qreal x1 = pointStart.x();
qreal y1 = pointStart.y();
qreal x2 = pointEnd.x();
qreal y2 = pointEnd.y();
qreal xcen = 0.5*(x1+x2);
qreal ycen = 0.5*(y1+y2);
qreal dx = fabs(x2-x1);
qreal dy = fabs(y2-y1);
qreal radius = sqrt(dx*dx+dy*dy);
// Collect alpha and delta of the first click
// Set 'skyRa' and 'skyDec'
xy2sky(xcen,ycen,"middleButton");
clearSkyCircleItems();
QGraphicsEllipseItem *ellipse = scene->addEllipse(x1-radius, y1-radius, 2.*radius, 2.*radius, pen);
ellipse->setFlags(QGraphicsEllipseItem::ItemIsSelectable | QGraphicsEllipseItem::ItemIsMovable);
skyCircleItems.append(ellipse);
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::drawMaskingPolygon(QPointF pointStart, QPointF pointEnd)
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
if (displayMode == "FITScolor") return;
QPen pen(QColor("#00ff00"));
pen.setWidth(0);
qreal x1 = pointStart.x();
qreal y1 = pointStart.y();
qreal x2 = pointEnd.x();
qreal y2 = pointEnd.y();
clearMaskRectItems();
QRectF rect;
QGraphicsRectItem *rectItem = scene->addRect(QRectF(QPoint(x1,y1), QPoint(x2,y2)));
rectItem->setPen(pen);
rectItem->setFlags(QGraphicsRectItem::ItemIsSelectable | QGraphicsRectItem::ItemIsMovable);
maskRectItems.append(rectItem);
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
/*
void IView::drawMaskingPolygon(QPointF pointStart, QPointF pointEnd)
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
if (displayMode == "FITScolor") return;
QPen pen(QColor("#00ff00"));
pen.setWidth(0);
qreal x1 = pointStart.x();
qreal y1 = pointStart.y();
qreal x2 = pointEnd.x();
qreal y2 = pointEnd.y();
clearMaskPolygonItems();
QPolygonF polygon;
polygon << QPoint(x1,y1) << QPoint(x2,y2);
QGraphicsPolygonItem *polygonItem = scene->addPolygon(polygon);
polygonItem->setPen(pen);
polygonItem->setFlags(QGraphicsPolygonItem::ItemIsSelectable | QGraphicsPolygonItem::ItemIsMovable);
maskPolygonItems.append(polygonItem);
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
*/
void IView::appendSkyCircle()
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
if (displayMode == "FITScolor") return;
// Fetch the last item drawn and add it to the permanent list
QGraphicsItem *lastItem = scene->items(Qt::AscendingOrder).last();
QPen pen(QColor("#00ff00"));
pen.setWidth(0);
if (lastItem->type() == QGraphicsEllipseItem::Type) {
QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(lastItem);
ellipse->setPen(pen);
acceptedSkyCircleItems.append(ellipse);
}
// Clear the temporary display (ellipses shown while dragging)
clearSkyCircleItems();
// Add the last state of the drawn ellipse item to the scene
if (!acceptedSkyCircleItems.isEmpty()) {
scene->addItem(acceptedSkyCircleItems.last());
}
// Update the data record in the external file
dumpSkyCircleCoordinates();
}
void IView::updateSkyCircles()
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
if (displayMode == "FITScolor") return;
// A selected sky circle has been removed by a key press event, or moved by mouse drag
// Update the underlying QList by fetching all visible sky circles
acceptedSkyCircleItems.clear();
QList<QGraphicsItem *> list = scene->items();
for (auto &it : list) {
if (it->type() == QGraphicsEllipseItem::Type) {
acceptedSkyCircleItems.append(qgraphicsitem_cast<QGraphicsEllipseItem *>(it));
}
}
// Update the data record in the external file
dumpSkyCircleCoordinates();
}
// invoked e.g. when dynamic range is changed
void IView::redrawSkyCirclesAndCats()
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
if (displayMode == "FITScolor") return;
if (!acceptedSkyCircleItems.isEmpty()) {
for (auto &it: acceptedSkyCircleItems) {
scene->addItem(it);
}
}
showSourceCat();
showReferenceCat();
checkFinderBypass();
redrawUpdateAxes();
}
void IView::dumpSkyCircleCoordinates()
{
// Dump the centers and radii of the sky circles to an external file
QFile skysamples(startDirName+"/skysamples.dat");
if (skysamples.open(QIODevice::WriteOnly)) {
QTextStream outputStream(&skysamples);
for (auto &it : acceptedSkyCircleItems)
{
// Store the coordinates in decimal Ra Dec radius [arcsec]
QRectF bound = it->sceneBoundingRect();
double xcen = bound.center().x();
double ycen = naxis2-bound.center().y();
xy2sky(xcen, ycen, "middleButton");
double radius = bound.height()/2.*plateScale;
outputStream.setRealNumberPrecision(9);
outputStream << skyRa << " " << skyDec << " " << radius << "\n";
}
skysamples.close();
}
// Create a copy in the parent folder (if we have several science directories of the same target)
QFile copy(startDirName+"/../skysamples.dat");
if (copy.exists()) copy.remove();
skysamples.copy(startDirName+"/../skysamples.dat");
}
void IView::clearSeparationVector()
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
clearVectorItems();
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::xy2sky(double x, double y, QString button)
{
if (!wcsInit) return;
double world[2];
double phi;
double theta;
double imgcrd[2];
double pixcrd[2];
pixcrd[0] = x;
pixcrd[1] = y;
int stat[1];
wcsp2s(wcs, 1, 2, pixcrd, imgcrd, &phi, &theta, world, stat);
// not used by all calls to this function
if (button == "middleButton") {
skyRa = world[0];
skyDec = world[1];
return;
}
QString alphaDec = QString::number(world[0],'f',6);
QString deltaDec = QString::number(world[1],'f',6);
QString alphaHex = dec2hex(world[0]/15.).remove("+");
QString deltaHex = dec2hex(world[1]);
icdw->ui->alphaDecLabel->setText(alphaDec);
icdw->ui->alphaHexLabel->setText(alphaHex);
icdw->ui->deltaDecLabel->setText(deltaDec);
icdw->ui->deltaHexLabel->setText(deltaHex);
}
// Unused
/*
void IView::xy2sky_linear(double x, double y, QString button)
{
double pi = 3.14159265;
double dx = x - crpix1;
double dy = y - crpix2;
double xt = cd1_1*dx + cd2_1*dy;
double yt = cd1_2*dx + cd2_2*dy;
double delta = crval2 + yt;
double alpha = crval1 + xt / cos(delta * pi/180.);
// not used by all calls to this function
if (button == "middleButton") {
skyRa = alpha;
skyDec = delta;
return;
}
QString alphaDec = QString::number(alpha,'f',6);
QString deltaDec = QString::number(delta,'f',6);
QString alphaHex = dec2hex(alpha/15.).remove("+");
QString deltaHex = dec2hex(delta);
icdw->ui->alphaDecLabel->setText("R.A. = "+alphaDec);
icdw->ui->alphaHexLabel->setText("R.A. = "+alphaHex);
icdw->ui->deltaDecLabel->setText("Dec = "+deltaDec);
icdw->ui->deltaHexLabel->setText("Dec = "+deltaHex);
}
*/
| 30,588
|
C++
|
.cc
| 777
| 34.177606
| 162
| 0.664545
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,415
|
myqgraphicsrectitem.cc
|
schirmermischa_THELI/src/iview/myqgraphicsrectitem.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "myqgraphicsrectitem.h"
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QRect>
MyQGraphicsRectItem::MyQGraphicsRectItem() : QGraphicsRectItem()
{
}
// Constrains the rectangle movement to the scene range
QVariant MyQGraphicsRectItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange && scene()) {
// value is the new position.
QPointF newPos = value.toPointF();
QRectF rect = scene()->sceneRect();
if (!rect.contains(newPos)) {
// Keep the item inside the scene rect.
newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
| 1,522
|
C++
|
.cc
| 37
| 37.162162
| 90
| 0.734915
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,416
|
mybinnedgraphicsview.cc
|
schirmermischa_THELI/src/iview/mybinnedgraphicsview.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mybinnedgraphicsview.h"
#include "iview.h"
#include "wcs.h"
MyBinnedGraphicsView::MyBinnedGraphicsView() : QGraphicsView()
{
QBrush brush(QColor("#000000"));
brush.setStyle(Qt::SolidPattern);
this->setBackgroundBrush(brush);
}
void MyBinnedGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
QPoint currentPos = event->pos();
// Display the current pixel coordinates under the cursor
QPointF currentPoint = mapToScene(currentPos);
emit currentMousePos(currentPoint);
if (leftButtonPressed) {
// scroll main view only if rectangle is within binnedPixMap
qreal x1;
qreal x2;
qreal y1;
qreal y2;
binnedSceneRect.getCoords(&x1, &y1, &x2, &y2);
qreal halfSceneWidth = (x2-x1) / 2.;
qreal halfSceneHeight = (y2-y1) / 2.;
qreal xcen = fovRectItem->scenePos().x() + nx / 2.;
qreal ycen = fovRectItem->scenePos().y() + ny / 2.;
qreal xcen1 = fovRectItem->scenePos().x() + halfSceneWidth;
qreal ycen1 = fovRectItem->scenePos().y() + halfSceneHeight;
qreal xr1 = xcen1 - fovRectItem->rect().width() / 2.;
qreal xr2 = xcen1 + fovRectItem->rect().width() / 2.;
qreal yr1 = ycen1 - fovRectItem->rect().height() / 2.;
qreal yr2 = ycen1 + fovRectItem->rect().height() / 2.;
qreal vxmin = x1 <= x2 ? x1 : x2;
qreal vxmax = x1 >= x2 ? x1 : x2;
qreal vymin = y1 <= y2 ? y1 : y2;
qreal vymax = y1 >= y2 ? y1 : y2;
if (xr1 > vxmin && xr2 < vxmax && yr1 > vymin && yr2 < vymax) {
fovBeingDragged = true;
fovRectItem->setFlags(QGraphicsEllipseItem::ItemIsMovable);
QPoint rectCenter = QPoint(xcen, ycen);
QPointF rectCenterQimage = mapToScene(rectCenter);
emit fovRectCenterChanged(rectCenterQimage);
}
}
QGraphicsView::mouseMoveEvent(event);
}
void MyBinnedGraphicsView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
rightDragStartPos = event->pos();
rightButtonPressed = true;
emit rightPress();
}
if (event->button() == Qt::LeftButton) {
leftDragStartPos = event->pos();
QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y());
leftButtonPressed = true;
emit leftPress(pointStart);
}
if (event->button() == Qt::MiddleButton) {
// setDragMode(QGraphicsView::ScrollHandDrag);
// previousMousePoint = event->pos();
if (middleMouseMode == "DragMode") {
middleButtonPressed = true;
_pan = true;
_panStartX = event->x();
_panStartY = event->y();
setCursor(Qt::OpenHandCursor);
// event->accept();
}
}
QGraphicsView::mousePressEvent(event);
}
void MyBinnedGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
rightButtonPressed = false;
emit rightButtonReleased();
}
if (event->button() == Qt::LeftButton) {
leftButtonPressed = false;
fovBeingDragged = false;
// old_x = fovRectItem->scenePos().x() + nx/2.;
// old_y = fovRectItem->scenePos().y() + ny/2.;
// qDebug() << "OLD" << old_x << old_y;
emit leftButtonReleased();
}
if (event->button() == Qt::MiddleButton) {
middleButtonPressed = false;
if (middleMouseMode == "DragMode") {
_pan = false;
setCursor(Qt::ArrowCursor);
// event->accept();
// return;
}
}
QGraphicsView::mouseReleaseEvent(event);
}
void MyBinnedGraphicsView::updateMiddleMouseMode(QString mode)
{
middleMouseMode = mode;
}
| 4,468
|
C++
|
.cc
| 116
| 32.163793
| 84
| 0.637013
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,417
|
iview.cc
|
schirmermischa_THELI/src/iview/iview.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "iview.h"
#include "ui_iview.h"
#include "../functions.h"
#include "mygraphicsview.h"
#include "mygraphicsellipseitem.h"
#include "mygraphicsscene.h"
#include "dockwidgets/ivconfdockwidget.h"
#include "dockwidgets/ivscampdockwidget.h"
#include "dockwidgets/ivcolordockwidget.h"
#include "dockwidgets/ivwcsdockwidget.h"
#include "dockwidgets/ivstatisticsdockwidget.h"
#include "dockwidgets/ivfinderdockwidget.h"
#include "ui_ivconfdockwidget.h"
#include "ui_ivcolordockwidget.h"
#include "ui_ivstatisticsdockwidget.h"
#include "ui_ivfinderdockwidget.h"
#include "../tools/tools.h"
#include "../myimage/myimage.h"
#include "fitsio2.h"
#include "wcs.h"
#include "wcshdr.h"
#include <omp.h>
#include <QDir>
#include <QSettings>
#include <QGraphicsPixmapItem>
#include <QPixmap>
#include <QGraphicsGridLayout>
#include <QDebug>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QToolBar>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPointF>
#include <QScrollBar>
#include <QTimer>
#include <QModelIndex>
void IView::setMiddleMouseMode(QString mode)
{
if (mode == "SkyMode") {
ui->actionSkyMode->setChecked(true);
ui->actionDragMode->setChecked(false);
ui->actionWCSMode->setChecked(false);
ui->actionMaskingMode->setChecked(false);
myGraphicsView->middleMouseMode = "SkyMode";
hideWCSdockWidget();
icdw->ui->quitPushButton->show();
}
else if (mode == "DragMode") {
ui->actionDragMode->setChecked(true);
ui->actionSkyMode->setChecked(false);
ui->actionWCSMode->setChecked(false);
ui->actionMaskingMode->setChecked(false);
middleMouseMode = "DragMode";
hideWCSdockWidget();
icdw->ui->quitPushButton->hide();
}
else if (mode == "WCSMode") {
ui->actionWCSMode->setChecked(true);
ui->actionSkyMode->setChecked(false);
ui->actionDragMode->setChecked(false);
ui->actionMaskingMode->setChecked(false);
middleMouseMode = "WCSMode";
showWCSdockWidget();
icdw->ui->quitPushButton->hide();
}
else if (mode == "MaskingMode") {
ui->actionMaskingMode->setChecked(true);
ui->actionSkyMode->setChecked(false);
ui->actionDragMode->setChecked(false);
ui->actionWCSMode->setChecked(false);
middleMouseMode = "MaskingMode";
hideWCSdockWidget();
icdw->ui->quitPushButton->hide();
}
}
void IView::sendWCStoWCSdockWidget()
{
if (!wcsInit) return;
// Catching spectroscopic exposures or other exposures with invalid "imaging" WCS
if (!wcs) {
wcsdw->init();
return;
}
// Copy the CD matrix to the WCS dock widget and init()
wcsdw->cd11_orig = wcs->cd[0];
wcsdw->cd12_orig = wcs->cd[1];
wcsdw->cd21_orig = wcs->cd[2];
wcsdw->cd22_orig = wcs->cd[3];
wcsdw->crpix1_orig = wcs->crpix[0];
wcsdw->crpix2_orig = wcs->crpix[1];
wcsdw->crval1_orig = wcs->crval[0];
wcsdw->crval2_orig = wcs->crval[1];
wcsdw->init();
}
void IView::showWCSdockWidget()
{
if (!wcs || ! wcsInit) {
QMessageBox msgBox;
msgBox.setText("WCS not found");
msgBox.setInformativeText("This image does not contain any WCS information. The WCS dialog will not be shown.\n\n");
msgBox.addButton(tr("Ok"), QMessageBox::YesRole);
msgBox.exec();
wcsdw->setDisabled(true);
ui->actionWCSMode->setChecked(false);
return;
}
if (wcsdw->isVisible()) return;
sendWCStoWCSdockWidget();
addDockWidget(Qt::LeftDockWidgetArea, wcsdw);
wcsdw->setFloating(false);
wcsdw->raise();
wcsdw->show();
if (!ui->actionRefCat->isChecked()) {
// otherwise showReferenceCat() exits
ui->actionRefCat->setChecked(true);
}
showReferenceCat();
if (refCatItems.isEmpty()) {
QMessageBox msgBox;
msgBox.setText("No reference sources available");
msgBox.setInformativeText("You must retrieve a reference catalog first before using the WCS module.\n\n");
msgBox.addButton(tr("Ok"), QMessageBox::YesRole);
msgBox.exec();
wcsdw->setDisabled(true);
ui->actionRefCat->setChecked(false);
return;
}
}
void IView::hideWCSdockWidget()
{
removeDockWidget(wcsdw);
wcsdw->hide();
}
void IView::resizeEvent(QResizeEvent * event)
{
event->accept();
if (icdw->ui->zoomFitPushButton->isChecked()) icdw->on_zoomFitPushButton_clicked();
}
void IView::sendStatisticsCenter(QPointF point)
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") return;
long x = point.x();
long y = naxis2 - point.y();
emit statisticsRequested(x, y);
}
QString IView::getVectorLabel(double separation)
{
QString units;
if (separation < 60) {
units = "\"";
}
else if (separation>=60. && separation < 3600.) {
separation /= 60.;
units = "\'";
}
else if (separation > 3600.) {
separation /= 3600.;
units = "°";
}
return QString::number(separation,'f',2)+" "+units;
}
QRect IView::adjustGeometry()
{
QRect geometry = myGraphicsView->geometry();
// if the graphics is larger than what the screen can accomodate:
int minMargin = 150;
myGraphicsView->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
if (naxis2 > screenHeight-minMargin) {
myGraphicsView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
geometry.setHeight(screenHeight-minMargin);
}
else {
// myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
if (naxis1 > screenWidth-minMargin) {
myGraphicsView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
geometry.setWidth(screenWidth-minMargin);
}
else {
// myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
return geometry;
}
void IView::setImageList(QString filter)
{
QDir dir(dirName);
QStringList filterList = filter.split(" ");
if (dir.exists()) {
// filterList << filter;
dir.setNameFilters(filterList);
imageList = dir.entryList();
}
numImages = imageList.length();
// we also need a list of chip names (without the status string)
imageListToChipName();
}
void IView::setImageListFromMemory()
{
imageList.clear();
imageListChipName.clear();
for (auto &it : myImageList) {
QString imageName = it->chipName + it->processingStatus->statusString + ".fits";
imageList.append(imageName);
imageListChipName.append(it->chipName);
}
}
void IView::imageListToChipName()
{
imageListChipName.clear();
for (auto &it : imageList) {
QString rootName = it;
rootName.truncate(rootName.lastIndexOf('_'));
QStringList list = it.split('_');
QString chipnr = list.last().remove(".fits");
chipnr.remove(QRegExp("[A-Z]"));
rootName.append("_"+chipnr);
imageListChipName.append(rootName);
}
}
void IView::setCurrentId(QString filename)
{
// The number of the file in the list of all images (PNG or FITS) in this directory
if (filterName.isEmpty() || filterLineEdit->text().isEmpty()) {
if (!displayMode.contains("SCAMP")) filterName = "*.fits";
else filterName = "*.png";
filterLineEdit->setText(filterName);
}
setImageList(filterName);
currentId = imageList.indexOf(QFileInfo(filename).fileName());
if (currentId == -1) {
qDebug() << "IView::getCurrentId(): Image not found in list." << filterName << numImages << filename;
}
}
void IView::loadImage()
{
QString filter = filterLineEdit->text();
if (filter.isEmpty()
|| !filter.contains(".fit")
|| !filter.contains("*")) {
filter = "*.fits";
filterLineEdit->setText(filter);
}
if (!QDir(dirName).exists()) dirName = QDir::homePath();
if (displayMode.contains("SCAMP")) {
currentFileName =
QFileDialog::getOpenFileName(this, tr("Select image"), dirName,
tr("Images and Scamp checkplots (")+filter+" *.png)");
}
else {
filter = "*.fits *.fit";
currentFileName =
QFileDialog::getOpenFileName(this, tr("Select image"), dirName,
tr("Images ")+filter);
}
if (currentFileName.isEmpty()) return;
// Identify file type by suffix
QFileInfo fi(currentFileName);
QString suffix = fi.suffix();
// update the dirname
dirName = fi.absolutePath();
// Update the filter string
filterName = "*."+suffix;
filterLineEdit->setText(filter);
if (suffix == "fits") {
switchMode("FITSmonochrome");
// Delete catalog displays, if any
clearItems();
// reset the startDirname if in PNG or CLEAR mode previously
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") startDirNameSet = false;
loadFITS(currentFileName);
}
else if (suffix == "png") {
switchMode("SCAMP");
loadPNG(currentFileName);
myGraphicsView->fitInView(scene->items(Qt::AscendingOrder).at(0), Qt::KeepAspectRatio);
icdw->on_zoomZeroPushButton_clicked();
}
else {
switchMode("CLEAR");
}
// update the startDirName
if (!startDirNameSet) {
startDirName = dirName;
startDirNameSet = true;
}
}
void IView::clearItems() {
// Delete any catalog displays
if (!sourceCatItems.isEmpty()) {
for (auto &it: sourceCatItems) scene->removeItem(it);
sourceCatItems.clear();
sourcecatSourcesShown = false;
ui->actionSourceCat->setChecked(false);
}
if (!refCatItems.isEmpty()) {
for (auto &it: refCatItems) scene->removeItem(it);
refCatItems.clear();
refcatSourcesShown = false;
ui->actionRefCat->setChecked(false);
}
if (!acceptedSkyCircleItems.isEmpty()) {
for (auto &it: acceptedSkyCircleItems) scene->removeItem(it);
acceptedSkyCircleItems.clear();
}
scene->removeCrosshair();
}
void IView::setCatalogOverlaysExternally(bool sourcecatShown, bool refcatShown)
{
ui->actionSourceCat->setChecked(sourcecatShown);
ui->actionRefCat->setChecked(refcatShown);
sourcecatSourcesShown = sourcecatShown;
refcatSourcesShown = refcatShown;
}
// Used by imagestatistics
void IView::clearAll()
{
clearItems();
scene->clear();
myGraphicsView->setScene(scene);
myGraphicsView->show();
this->setWindowTitle("iView");
pageLabel->clear();
switchMode("CLEAR");
icdw->clearBinnedSceneReceiver();
icdw->clearMagnifiedSceneReceiver();
}
void IView::loadFITSexternal(QString fileName, QString filter)
{
if (!fileName.isEmpty()) {
switchMode("FITSmonochrome");
filterName = filter;
filterLineEdit->setText(filterName);
loadFITS(fileName);
}
else {
switchMode("CLEAR");
filterName = filter;
filterLineEdit->setText(filterName);
}
}
// invoked when clicking a data point in image statistics
void IView::loadFITSexternalRAM(int index)
{
switchMode("MEMview");
bool sourcecatShown = sourcecatSourcesShown;
bool refcatShown = refcatSourcesShown;
clearItems();
loadFromRAM(myImageList[index], 0);
currentId = index;
setCatalogOverlaysExternally(sourcecatShown, refcatShown);
redrawSkyCirclesAndCats();
}
void IView::loadPNG(QString filename, int currentId)
{
if (imageList.isEmpty() || dirName.isEmpty()) {
qDebug() << __func__ << " No scamp checkplots found!";
return;
}
if (filename.isEmpty()) filename = dirName+"/"+imageList.at(currentId);
else {
setCurrentId(filename);
if (currentId == -1) return;
}
QFileInfo fi(filename);
QString showName = fi.fileName();
QPixmap pixmap = QPixmap(filename);
naxis1 = pixmap.width();
naxis2 = pixmap.height();
zoomLevel = 0;
// icdw->zoom2scale(zoomLevel); // uninitialized
myGraphicsView->resetMatrix();
// QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
pixmapItem = new QGraphicsPixmapItem(pixmap);
// Update the view
// QRect geometry = adjustGeometry();
scene->clear();
scene->addItem(pixmapItem);
myGraphicsView->setScene(scene);
myGraphicsView->scale(1.0,1.0);
// myGraphicsView->setGeometry(geometry);
myGraphicsView->show();
QString prependPath = dirName;
removeLastCharIf(prependPath, '/');
QString path = get2ndLastWord(prependPath,'/')+"/"+getLastWord(prependPath,'/');
this->setWindowTitle("iView --- "+path+"/ --- "+showName);
pageLabel->setText(QString::number(currentId+1)+" / "+QString::number(numImages));
// icdw->zoom2scale(zoomLevel);
myGraphicsView->resetMatrix();
myGraphicsView->setMinimumSize(naxis1,naxis2);
myGraphicsView->setMaximumSize(naxis1,naxis2);
myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
myGraphicsView->resize(naxis1,naxis2);
}
void IView::loadFITS(QString filename, int currentId, qreal scaleFactor)
{
if (filename.isEmpty()) {
filename = dirName+"/"+imageList.at(currentId);
currentFileName = imageList.at(currentId);
}
else {
setCurrentId(filename);
if (currentId == -1) return;
}
QFileInfo fi(filename);
QString showName = fi.fileName();
if (loadFITSdata(filename, fitsData)) {
// Map dynamic range to INT, update the scene
mapFITS();
// Update the view
QRect geometry = adjustGeometry();
myGraphicsView->setScene(scene);
myGraphicsView->scale(scaleFactor, scaleFactor);
myGraphicsView->setGeometry(geometry);
// myGraphicsView->centerOn(pixmapItem);
myGraphicsView->show();
myGraphicsView->setMinimumSize(200,200);
myGraphicsView->setMaximumSize(10000,10000);
QString prependPath = dirName;
removeLastCharIf(prependPath, '/');
QString path = getLastWord(prependPath,'/');
this->setWindowTitle("iView --- "+path+"/ --- "+showName);
pageLabel->setText(QString::number(currentId+1)+" / "+QString::number(numImages));
// Load the binned image to the navigator
emit updateNavigatorBinned(binnedPixmapItem); // binnedPixmapItem created in mapFITS()
emit updateNavigatorBinnedWCS(wcs, wcsInit);
emit newImageLoaded();
}
else {
// At end of file list, or file does not exist anymore.
// Update file list
filterLineEdit_textChanged("dummy");
return;
}
}
/*
void IView::loadFromRAMlist(const QModelIndex &index)
{
loadFromRAM(myImageList[index.row()], index.column());
// Get the center image poststamp; copy() refers to the top left corner, and then width and height
QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(naxis1/2.-icdw->navigator_magnified_nx/2.,
naxis2/2.-icdw->navigator_magnified_ny/2.,
icdw->navigator_magnified_nx, icdw->navigator_magnified_ny);
magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap);
// Update the navigator magnified window with the center image poststamp
emit updateNavigatorMagnified(magnifiedPixmapItem, icdw->zoom2scale(zoomLevel)*magnify, 0., 0.);
}
*/
// Receiver of Navigator currentMousePos Eevent
void IView::updateNavigatorMagnifiedReceived(QPointF point)
{
// Cap the magnification
qreal magnification = icdw->zoom2scale(zoomLevel)*magnify;
if (magnification > magnify) magnification = magnify;
float dx = 0.;
float dy = 0.;
if (point.x() < 0 || point.x() > naxis1 || point.y() < 0 || point.y() > naxis2) {
emit clearMagnifiedScene();
return;
}
if (displayMode == "FITSmonochrome" || displayMode == "MEMview") {
// qDebug() << point.x() + 1. - icdw->navigator_magnified_nx/2./magnification << point.y() + 1. - icdw->navigator_magnified_ny/2./magnification <<
// icdw->navigator_magnified_nx/magnification << icdw->navigator_magnified_ny/magnification;
if (point.x() + 1. - icdw->navigator_magnified_nx/2./magnification < 0) dx = point.x() + 1. - icdw->navigator_magnified_nx/2./magnification;
if (point.x() + 1. - icdw->navigator_magnified_nx/2./magnification >= naxis1) dx = point.x() + 1. - icdw->navigator_magnified_nx/2./magnification;
QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(point.x() + 1. - icdw->navigator_magnified_nx/2./magnification,
point.y() + 1. - icdw->navigator_magnified_ny/2./magnification,
icdw->navigator_magnified_nx/magnification, icdw->navigator_magnified_ny/magnification);
magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap);
// qDebug() << magnifiedPixmap.width() << magnifiedPixmap.height() << icdw->navigator_magnified_nx/magnification << icdw->navigator_magnified_ny/magnification;
}
else if (displayMode == "FITScolor") {
QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(point.x() + 1. - icdw->navigator_magnified_nx/2/magnification,
point.y() + 1. - icdw->navigator_magnified_ny/2/magnification,
icdw->navigator_magnified_nx/magnification, icdw->navigator_magnified_ny/magnification);
magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap);
}
else {
// Do not emit signal for PNG mode
return;
}
emit updateNavigatorMagnified(magnifiedPixmapItem, magnification, dx, dy);
}
void IView::loadFromRAM(MyImage *it, int indexColumn)
{
scene->removeCrosshair();
clearAxes();
currentMyImage = it;
if (indexColumn == 0 || indexColumn == 3) {
// Load image into memory if not yet present
if (!weightMode) {
it->readImage(false);
fitsData = it->dataCurrent;
}
else {
it->readWeight();
fitsData = it->dataWeight;
it->weightInMemory = true;
}
}
else if (indexColumn == 4 && it->backupL1InMemory) fitsData = it->dataBackupL1;
else if (indexColumn == 5 && it->backupL2InMemory) fitsData = it->dataBackupL2;
else if (indexColumn == 6 && it->backupL3InMemory) fitsData = it->dataBackupL3;
else {
return;
}
naxis1 = it->naxis1;
naxis2 = it->naxis2;
plateScale = it->plateScale;
naxis1 = it->naxis1;
naxis2 = it->naxis2;
wcs = it->wcs;
wcsInit = it->wcsInit;
finderdw->dateObs = it->dateobs;
finderdw->geoLon = it->geolon;
finderdw->geoLat = it->geolat;
sendWCStoWCSdockWidget();
this->setWindowTitle("iView --- Memory viewer : "+it->chipName);
connect(currentMyImage, &MyImage::WCSupdated, this, &IView::WCSupdatedReceived);
// Get the dynamic range
// Normal viewer mode
if (dataIntSet) {
delete[] dataInt;
dataInt = nullptr;
}
dataInt = new unsigned char[naxis1*naxis2];
dataIntSet = true;
getGlobalImageStatistics();
// AUTO
if (icdw->ui->minLineEdit->text().isEmpty()
|| icdw->ui->maxLineEdit->text().isEmpty()
|| icdw->ui->autocontrastPushButton->isChecked()) {
autoContrast();
}
// MANUAL
else {
// get background statisics (median and sd)
dynRangeMin = icdw->ui->minLineEdit->text().toFloat();
dynRangeMax = icdw->ui->maxLineEdit->text().toFloat();
}
mapFITS();
// Update the view
QRect geometry = adjustGeometry();
myGraphicsView->setScene(scene);
myGraphicsView->scale(icdw->zoom2scale(0),icdw->zoom2scale(0));
myGraphicsView->setGeometry(geometry);
myGraphicsView->show();
myGraphicsView->setMinimumSize(200,200);
myGraphicsView->setMaximumSize(10000,10000);
currentMyImage = it; // For later use, in particular when updating CRPIX1/2
currentFileName = currentMyImage->baseName+".fits";
// Get the center image poststamp; copy() refers to the top left corner, and then width and height
QPixmap magnifiedPixmap = pixmapItem->pixmap().copy(naxis1/2.-icdw->navigator_magnified_nx/2.,
naxis2/2.-icdw->navigator_magnified_ny/2.,
icdw->navigator_magnified_nx, icdw->navigator_magnified_ny);
magnifiedPixmapItem = new QGraphicsPixmapItem(magnifiedPixmap);
// Update the navigator magnified window with the center image poststamp
emit updateNavigatorMagnified(magnifiedPixmapItem, icdw->zoom2scale(zoomLevel)*magnify, 0., 0.);
// Update the navigator binned window with the binned poststamp
emit updateNavigatorBinned(binnedPixmapItem);
emit updateNavigatorBinnedWCS(wcs, wcsInit);
emit newImageLoaded();
}
void IView::loadColorFITS(qreal scaleFactor)
{
QFile redFile(dirName+'/'+ChannelR);
QFile greenFile(dirName+'/'+ChannelG);
QFile blueFile(dirName+'/'+ChannelB);
if (!redFile.exists()
|| !greenFile.exists()
|| !blueFile.exists())
return;
QString showName = "Color calibrated preview";
bool testR = loadFITSdata(dirName+'/'+ChannelR, fitsDataR, "redChannel");
bool testG = loadFITSdata(dirName+'/'+ChannelG, fitsDataG, "greenChannel");
bool testB = loadFITSdata(dirName+'/'+ChannelB, fitsDataB, "blueChannel");
if (!testR || !testG || !testB) {
qDebug() << __func__ << "One or more of the three color channels could not be read!";
qDebug() << ChannelR << ChannelG << ChannelB;
return;
}
allChannelsRead = true;
// Map dynamic range to INT, update the scene
mapFITS();
// Update the view
QRect geometry = adjustGeometry();
myGraphicsView->setScene(scene);
myGraphicsView->scale(scaleFactor, scaleFactor);
myGraphicsView->setGeometry(geometry);
myGraphicsView->show();
myGraphicsView->setMinimumSize(200,200);
myGraphicsView->setMaximumSize(10000,10000);
QString prependPath = dirName;
removeLastCharIf(prependPath, '/');
QString path = getLastWord(prependPath,'/');
this->setWindowTitle("iView --- "+path+"/ --- "+showName);
icdw->ui->quitPushButton->hide();
// Update the navigator binned window with the binned poststamp
emit updateNavigatorBinned(binnedPixmapItem);
emit updateNavigatorBinnedWCS(wcs, wcsInit);
}
bool IView::loadFITSdata(QString filename, QVector<float> &data, QString colorMode)
{
if (displayMode.contains("SCAMP") || displayMode == "CLEAR") {
return false;
}
scene->removeCrosshair();
clearAxes();
if (weightMode) {
filename.replace(".fits", ".weight.fits");
}
// Setup the MyImage
int verbose = 0;
if (currentMyImage != nullptr) {
delete currentMyImage;
currentMyImage = nullptr;
}
QVector<bool> dummyMask;
dummyMask.clear();
currentMyImage = new MyImage(filename, dummyMask, &verbose);
currentMyImage->loadHeader(filename);
currentMyImage->readImage(filename);
plateScale = currentMyImage->plateScale;
naxis1 = currentMyImage->naxis1;
naxis2 = currentMyImage->naxis2;
fullheader = currentMyImage->fullheader;
wcs = currentMyImage->wcs;
finderdw->dateObs = currentMyImage->dateobs;
finderdw->geoLon = currentMyImage->geolon;
finderdw->geoLat = currentMyImage->geolat;
(void) wcsset(wcs);
wcsInit = true;
sendWCStoWCSdockWidget();
connect(currentMyImage, &MyImage::WCSupdated, this, &IView::WCSupdatedReceived);
// Move the data from the transient MyImage over to the class member.
data.swap(currentMyImage->dataCurrent); // 'fitsData' in the rest of the code
// Get the dynamic range
// Normal viewer mode
if (displayMode == "FITSmonochrome") {
if (dataIntSet) {
delete[] dataInt;
dataInt = nullptr;
}
dataInt = new unsigned char[naxis1*naxis2];
dataIntSet = true;
// determine best dynamic range for display (not yet applied)
// AUTO
getGlobalImageStatistics();
if (icdw->ui->minLineEdit->text().isEmpty()
|| icdw->ui->maxLineEdit->text().isEmpty()
|| icdw->ui->autocontrastPushButton->isChecked()) {
autoContrast();
}
// MANUAL
else {
// get background statisics (medVal and rmsVal)
dynRangeMin = icdw->ui->minLineEdit->text().toFloat();
dynRangeMax = icdw->ui->maxLineEdit->text().toFloat();
}
}
else if (displayMode == "FITScolor") {
if (colorMode == "redChannel" && dataIntRSet) {
delete[] dataIntR;
dataIntR = nullptr;
}
if (colorMode == "greenChannel" && dataIntGSet) {
delete[] dataIntG;
dataIntG = nullptr;
}
if (colorMode == "blueChannel" && dataIntBSet) {
delete[] dataIntB;
dataIntB = nullptr;
}
if (colorMode == "redChannel") {
dataIntR = new unsigned char[naxis1*naxis2];
dataIntRSet = true;
}
if (colorMode == "greenChannel") {
dataIntG = new unsigned char[naxis1*naxis2];
dataIntGSet = true;
}
if (colorMode == "blueChannel") {
dataIntB = new unsigned char[naxis1*naxis2];
dataIntBSet = true;
}
// Loading a color view of the RGB FITS channels
// (only executes fully once all channels have been read)
icdw->ui->autocontrastPushButton->setChecked(true);
getGlobalImageStatistics(colorMode);
autoContrast();
}
return true;
}
void IView::mapFITS()
{
// record the source/ref catalog states
bool sourceCatShown = ui->actionSourceCat->isChecked();
bool refCatShown = ui->actionRefCat->isChecked();
bool G2shown = false;
if (displayMode == "FITScolor") {
G2shown = colordw->ui->G2referencesPushButton->isChecked();
}
//**************************************************
// ADDITIONAL SECTION TO TEST TRANSFORMATIONS
// QTransform *transform = nullptr; // transformation maxtrix
if(wcs) {
// Transformation prameters, to be filled explicitly from WCS matrix
// Must be computed with respect to global reference system valid for all images. Not sure how to do this
/*
qreal scale = 1.; // scaling factor
qreal phi = 0.; // rotation angle
qreal dx = 0.; // translation
qreal dy = 0.; // translation
transform = new QTransform();
// Adjust according to CD matrix
qreal matrix[][3] = {
{cd11, cd21, 0.0},
{cd12, cd22, 0.0},
{crpix1, crpix2, 1.0},
};
qreal matrix[][3] = {
{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0},
};
transform->setMatrix(matrix[0][0], matrix[0][1], matrix[0][2],
matrix[1][0], matrix[1][1], matrix[1][2],
matrix[2][0], matrix[2][1], matrix[2][2]);
transform->rotate(0.);
dx = naxis1/2. - (transform->m11()*naxis1/2.+transform->m21()*naxis2/2.);
dy = naxis2/2. - (transform->m12()*naxis1/2.+transform->m22()*naxis2/2.);
transform->translate(-wcs->crpix[0], -wcs->crpix[1]);
*/
}
else {
// A WCS lock toggle button should be deactivated
}
// the scene MUST have it's final size BEFORE we add an item
// WARNING: with some images (large coadds) then these images appear shifted to the right and cannot be viewed completely.
// if(scene->width() < 1 || scene->height() < 1)
// scene->setSceneRect( 0, 0, naxis1, naxis2);
// end additional section
//**************************************************
clearItems();
if (displayMode == "FITSmonochrome" || displayMode == "MEMview") {
compressDynrange(fitsData, dataInt);
QImage fitsImage(dataInt, naxis1, naxis2, naxis1, QImage::Format_Grayscale8);
fitsImage = fitsImage.mirrored(false, true);
// apply transformation if there is one
// if(transform) fitsImage = fitsImage.transformed(*transform,Qt::SmoothTransformation);
pixmapItem = new QGraphicsPixmapItem(QPixmap::fromImage(fitsImage));
// while transformation the translations gets lost because the image is cropped to its contents, so we have to translate afterwards
// if(transform) pixmapItem->setOffset(transform->m31(), transform->m32());
// qDebug() << transform->m11() << transform->m12() << transform->m13();
// qDebug() << transform->m21() << transform->m22() << transform->m23();
// qDebug() << transform->m31() << transform->m32() << transform->m33();
scene->clear();
scene->addItem(pixmapItem);
myGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
myGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
}
else if (displayMode == "FITScolor") {
compressDynrange(fitsDataR, dataIntR, colordw->colorFactorApplied[0]);
compressDynrange(fitsDataG, dataIntG, colordw->colorFactorApplied[1]);
compressDynrange(fitsDataB, dataIntB, colordw->colorFactorApplied[2]);
QImage colorFitsImage(naxis1, naxis2, QImage::Format_ARGB32);
for (long i=0; i<naxis1*naxis2; ++i) {
QRgb argb = qRgba( dataIntR[i], dataIntG[i], dataIntB[i], 255);
QRgb* rowData = (QRgb*) colorFitsImage.scanLine(i/naxis1);
rowData[i%naxis1] = argb;
}
colorFitsImage = colorFitsImage.mirrored(false, true);
// if (transform) colorFitsImage = colorFitsImage.transformed(*transform,Qt::SmoothTransformation);
// QGraphicsPixmapItem *item = new QGraphicsPixmapItem( QPixmap::fromImage(colorFitsImage));
// CHECK if that works
pixmapItem = new QGraphicsPixmapItem(QPixmap::fromImage(colorFitsImage));
// if(transform) pixmapItem->setOffset(transform->m31(), transform->m32());
scene->clear();
scene->addItem(pixmapItem);
}
else {
qDebug() << __func__ << "Invalid mode in mapFITS()";
}
binnedPixmapItem = new QGraphicsPixmapItem(pixmapItem->pixmap().scaled(icdw->navigator_binned_nx, icdw->navigator_binned_ny, Qt::KeepAspectRatio, Qt::FastTransformation));
/*
if (transform) {
delete transform;
transform = nullptr;
}
*/
// Replot the source and reference catalogs (if the corresponding actions are checked)
if (sourceCatShown && ui->actionSourceCat->isVisible()) {
ui->actionSourceCat->setChecked(true);
showSourceCat();
}
if (refCatShown && ui->actionRefCat->isVisible()) {
ui->actionRefCat->setChecked(true);
showReferenceCat();
}
if (displayMode == "FITScolor") {
if (G2shown) {
colordw->ui->G2referencesPushButton->setChecked(true);
showG2References(true);
}
}
finderdw->bypassResolver();
}
void IView::compressDynrange(const QVector<float> &fitsdata, unsigned char *intdata, float colorCorrectionFactor)
{
float rescale = 255. / (dynRangeMax - dynRangeMin);
float tmpdata;
// NOT THREADSAFE!
//#pragma omp parallel for
long i=0;
for (auto &it : fitsdata) {
// Truncate dynamic range
float fitsdataCorrected = it * colorCorrectionFactor;
if (fitsdataCorrected > dynRangeMax) tmpdata = dynRangeMax;
else if (fitsdataCorrected < dynRangeMin) tmpdata = dynRangeMin;
else tmpdata = fitsdataCorrected;
// Compress to uchar (not thread safe)
intdata[i] = (unsigned char) ((tmpdata-dynRangeMin) * rescale);
++i;
}
}
void IView::updateColorViewExternal(float redFactor, float blueFactor)
{
colordw->colorFactorZeropoint[0] = redFactor;
colordw->colorFactorZeropoint[1] = 1.0;
colordw->colorFactorZeropoint[2] = blueFactor;
QString red = QString::number(redFactor, 'f', 3);
QString blue = QString::number(blueFactor, 'f', 3);
colordw->ui->redFactorLineEdit->setText(red);
colordw->ui->blueFactorLineEdit->setText(blue);
colordw->textToSlider(red, "red");
colordw->textToSlider(blue, "blue");
updateColorViewInternal(redFactor, blueFactor);
}
void IView::updateColorViewInternal(float redFactor, float blueFactor)
{
if (displayMode != "FITScolor") return;
colordw->colorFactorApplied[0] = redFactor;
colordw->colorFactorApplied[1] = 1.0;
colordw->colorFactorApplied[2] = blueFactor;
mapFITS();
}
void IView::showSourceCat()
{
// Leave if no image is displayed
sourcecatSourcesShown = false;
if (scene->items().isEmpty()) return;
if (ui->actionSourceCat->isChecked()) {
/*
QString imageName = imageList.at(currentId);
QFileInfo fi(imageName);
QString baseName = fi.completeBaseName();
// The catalog is also valid for skysubtracted images
if (baseName.endsWith(".sub")) baseName.chop(4);
*/
QString chipName = imageListChipName.at(currentId);
QFile catalog(dirName+"/cat/iview/"+chipName+".iview");
QString line;
QStringList lineList;
qreal x;
qreal y;
qreal size;
QPen pen(QColor("#00ff66"));
int penWidth = 2./icdw->zoom2scale(zoomLevel);
penWidth = penWidth < 1 ? 1 : penWidth;
pen.setWidth(penWidth);
QPoint point;
// Refresh item list
sourceCatItems.clear();
// Read all source positions
if ( catalog.open(QIODevice::ReadOnly)) {
QTextStream stream( &catalog );
while ( !stream.atEnd() ) {
line = stream.readLine().simplified();
// skip header lines
if (line.contains("#")) continue;
lineList = line.split(" ");
x = lineList.at(0).toFloat();
// must flip y
y = naxis2 - lineList.at(1).toFloat();
size = 10.*lineList.at(2).toFloat(); // (factor 3 if using flux radius)
// correct for an offset introduced by where the scene draws the ellipses
if (size<5.) size = 5.; // Lower limit for symbol size
if (size>20.) size = 20.; // Upper limit for symbol size
point.setX(x-0.5*size);
// Not sure where the +1 comes from. Perhaps from the flip and counting from 0 or one?
point.setY(y-0.5*size+1.);
myGraphicsView->mapToScene(point); // Not sure this is needed; Uncomment if objects are not plotted in the right position
sourceCatItems.append(scene->addEllipse(point.x(), point.y(), size, size, pen));
/*
// Does not draw ellipses in the right position. Some offset...
qreal aell = 6.*lineList.at(2).toFloat();
qreal bell = 6.*lineList.at(3).toFloat();
qreal theta = lineList.at(4).toFloat();
QGraphicsEllipseItem *ellipse = scene->addEllipse(point.x(), point.y(), aell, bell, pen);
ellipse->setTransformOriginPoint(x+1,y+1.);
ellipse->setRotation(-theta);
sourceCatItems.append(ellipse);
*/
}
catalog.close();
}
}
else {
if (!sourceCatItems.isEmpty()) {
for (auto &it: sourceCatItems) scene->removeItem(it);
sourceCatItems.clear();
}
}
if (!sourceCatItems.isEmpty()) sourcecatSourcesShown = true;
else sourcecatSourcesShown = false;
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::showReferenceCat()
{
refcatSourcesShown = false;
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
QColor color = QColor("#ff3300");
int width = 2. / icdw->zoom2scale(zoomLevel);
width = width < 1 ? 1 : width;
if (!refCatItems.isEmpty()) {
for (auto &it: refCatItems) scene->removeItem(it);
refCatItems.clear();
}
if (ui->actionRefCat->isChecked()) {
refCatItems.clear();
// Try and read the reference catalog in the standard relative position
int symbolSize = 15;
if (!readRaDecCatalog(dirName+"/cat/refcat/theli_mystd.iview", refCatItems, symbolSize, width, color)) {
// Perhaps we are looking at a coadded image. Then go one directory up first
if (!readRaDecCatalog(dirName+"/../cat/refcat/theli_mystd.iview", refCatItems, symbolSize, width, color)) {
// No overlap with data field? Let the user provide one manually:
QString refcatFileName =
QFileDialog::getOpenFileName(this, tr("Select reference catalog (theli_mystd.iview)"), dirName,
"theli_mystd.iview");
if (QFile(refcatFileName).exists()) {
if (!readRaDecCatalog(refcatFileName, refCatItems, symbolSize, width, color)) {
qDebug() << __func__ << " : Could not read manually provided reference catalog.";
// Remove any previous catalog display.
if (!refCatItems.isEmpty()) {
for (auto &it: refCatItems) scene->removeItem(it);
refCatItems.clear();
}
}
}
}
}
}
else {
// Remove any previous catalog display.
if (!refCatItems.isEmpty()) {
for (auto &it: refCatItems) scene->removeItem(it);
refCatItems.clear();
}
wcsdw->setDisabled(true);
}
if (!refCatItems.isEmpty()) {
refcatSourcesShown = true;
wcsdw->setEnabled(true);
}
else {
refcatSourcesShown = false;
wcsdw->setDisabled(true);
}
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::showG2References(bool checked)
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (G2referencePathName.isEmpty()) return;
if (checked) {
QDir calibDir(G2referencePathName);
QStringList calibSourcesList = calibDir.entryList(QStringList("PHOTCAT_sources_matched*.iview"));
// Clear the item list
G2refCatItems.clear();
// Read the catalogs, append to the item list with different symbols
int width = 2;
for (auto &it : calibSourcesList) {
if (it.contains("SDSS")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 29, width, QColor("#ee0000"));
if (it.contains("PANSTARRS")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 24, width, QColor("#00eeee"));
if (it.contains("ATLAS-REFCAT2")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 19, width, QColor("#00ee00"));
if (it.contains("SKYMAPPER")) readRaDecCatalog(G2referencePathName+it, G2refCatItems, 29, width, QColor("#eeee00"));
}
}
else {
// Remove any previous catalog display.
if (!G2refCatItems.isEmpty()) {
for (auto &it: G2refCatItems) scene->removeItem(it);
G2refCatItems.clear();
}
}
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::showAbsPhotReferences(bool checked)
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (checked) {
// Clear previous items
if (!AbsPhotRefCatItems.isEmpty()) {
for (auto &it: AbsPhotRefCatItems) scene->removeItem(it);
AbsPhotRefCatItems.clear();
}
QString dirName = AbsPhotReferencePathName;
QString catNameMatched = "ABSPHOT_sources_matched.iview";
QString catNameDownloaded = "ABSPHOT_sources_downloaded.iview";
if (AbsPhotReferencePathName.isEmpty()) {
qDebug() << __func__ << "No path name defined for absolute reference catalog. AbsPhot references will not be displayed.";
return;
}
// Clear the item list
AbsPhotRefCatItems.clear();
int width = 2;
readRaDecCatalog(dirName+"/"+catNameDownloaded, AbsPhotRefCatItems, 20, width, QColor("#ee0000"));
// readRaDecCatalog(dirName+"/"+catNameDownloaded, AbsPhotRefCatItems, 18, width, QColor("#000000"));
readRaDecCatalog(dirName+"/"+catNameMatched, AbsPhotRefCatItems, 20, width, QColor("#eeee00"));
// readRaDecCatalog(dirName+"/"+catNameMatched, AbsPhotRefCatItems, 18, width, QColor("#000000"));
}
else {
// Remove any previous catalog display.
if (!AbsPhotRefCatItems.isEmpty()) {
for (auto &it: AbsPhotRefCatItems) scene->removeItem(it);
AbsPhotRefCatItems.clear();
}
}
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
bool IView::readRaDecCatalog(QString fileName, QList<QGraphicsRectItem*> &items, double size, int width, QColor color)
{
QString line;
QStringList lineList;
QPen pen(color);
pen.setWidth(width);
QPoint point;
// Read all source positions
QFile file(fileName);
if ( file.open(QIODevice::ReadOnly)) {
QTextStream stream( &file );
while ( !stream.atEnd() ) {
line = stream.readLine().simplified();
// skip header lines
if (line.contains("#")) continue;
lineList = line.split(" ");
double ra = lineList.at(0).toDouble();
double dec = lineList.at(1).toDouble();
double x = 0.;
double y = 0.;
sky2xyQImage(ra, dec, x, y);
// correct for an offset introduced by where the scene draws the ellipses (or rectangles)
point.setX(x-0.5*size);
point.setY(y-0.5*size);
myGraphicsView->mapToScene(point);
// qDebug() << point.x() << naxis1 << point.y() << naxis2 << ra << dec << x << y << size;
// only show reference sources within the image boundaries
if (point.x() >= 0 && point.x() <= naxis1
&& point.y() >= 0 && point.y() <= naxis2) {
// qDebug() << x << point.x() << y << point.y() << ra << dec;
items.append(scene->addRect(point.x(), point.y(), size, size, pen));
// qDebug() << "itemAdded";
}
}
file.close();
if (!items.isEmpty()) return true;
else {
return false;
}
}
else {
// error handling in caller function
return false;
}
}
// returns coordinates in QImage system!
void IView::sky2xyQImage(double alpha, double delta, double &x, double &y)
{
if (!wcsInit) return;
double world[2];
double phi;
double theta;
double imgcrd[2];
double pixcrd[2];
world[0] = alpha;
world[1] = delta;
int stat[1];
wcss2p(wcs, 1, 2, world, &phi, &theta, imgcrd, pixcrd, stat);
x = pixcrd[0];
y = naxis2 - pixcrd[1];
}
// returns coordinates in FITS
void IView::sky2xyFITS(double alpha, double delta, double &x, double &y)
{
if (!wcsInit) return;
double world[2];
double phi;
double theta;
double imgcrd[2];
double pixcrd[2];
world[0] = alpha;
world[1] = delta;
int stat[1];
wcss2p(wcs, 1, 2, world, &phi, &theta, imgcrd, pixcrd, stat);
x = pixcrd[0];
y = pixcrd[1];
}
QString IView::dec2hex(double angle)
{
double hh;
double mm;
double ss;
int sign;
sign = (angle < 0.0 ? -1 : 1);
angle *= sign;
angle = 60.0 * modf(angle, &hh);
ss = 60.0 * modf(angle, &mm);
QString h = QString::number(hh, 'f', 0);
QString m = QString::number(mm, 'f', 0);
QString s = QString::number(ss, 'f', 3);
if (hh < 10) h.prepend("0");
if (mm < 10) m.prepend("0");
if (ss < 10) s.prepend("0");
QString p;
if (sign > 0) p = "+";
else p = "-";
return p+h+":"+m+":"+s;
}
void IView::getGlobalImageStatistics(QString colorMode)
{
// Quasi-random sampling an array at every dim_small pixel
int ranStep = 2./3.*naxis1 + sqrt(naxis1);
QVector<double> subSample;
if (displayMode == "FITSmonochrome" || displayMode == "MEMview") {
get_array_subsample(fitsData, subSample, ranStep);
// GLOBAL statistics
globalMedian = medianMask_T(subSample, QVector<bool>(), "ignoreZeroes");
globalMean = meanMask_T(subSample, QVector<bool>());
globalRMS = 1.486*madMask_T(subSample, QVector<bool>(), "ignoreZeroes");
}
else if (displayMode == "FITScolor") {
QVector<double> subSampleR;
QVector<double> subSampleG;
QVector<double> subSampleB;
if (colorMode == "redChannel") {
get_array_subsample(fitsDataR, subSampleR, ranStep);
globalMedianR = medianMask_T(subSampleR, QVector<bool>(), "ignoreZeroes");
}
if (colorMode == "greenChannel") {
get_array_subsample(fitsDataG, subSampleG, ranStep);
globalMedianG = medianMask_T(subSampleG, QVector<bool>(), "ignoreZeroes");
}
if (colorMode == "blueChannel") {
get_array_subsample(fitsDataB, subSampleB, ranStep);
globalMedianB = medianMask_T(subSampleB, QVector<bool>(), "ignoreZeroes");
// In addition, compute overall statistics across all three bands (once the blue is read, we have all of them available)
get_array_subsample(fitsDataR, subSampleR, ranStep);
get_array_subsample(fitsDataG, subSampleG, ranStep);
for (long i=0; i<subSampleR.length(); ++i) {
subSampleR[i] += (subSampleG[i] + subSampleB[i]);
}
globalMedian = medianMask_T(subSampleR, QVector<bool>(), "ignoreZeroes");
globalMean = meanMask_T(subSampleR, QVector<bool>());
globalRMS = 1.486*madMask_T(subSampleR, QVector<bool>(), "ignoreZeroes");
}
}
}
void IView::autoContrast()
{
dynRangeMin = globalMedian - 2.*globalRMS;
dynRangeMax = globalMedian + 10.*globalRMS;
int validDigits = 3-log(fabs(dynRangeMax))/log(10);
if (validDigits<0) validDigits = 0;
icdw->ui->minLineEdit->setText(QString::number(dynRangeMin,'f',validDigits));
icdw->ui->maxLineEdit->setText(QString::number(dynRangeMax,'f',validDigits));
}
void IView::writePreferenceSettings()
{
QSettings settings("IVIEW", "PREFERENCES");
settings.setValue("zoomFitPushButton", icdw->ui->zoomFitPushButton->isChecked());
settings.setValue("autocontrastPushButton", icdw->ui->autocontrastPushButton->isChecked());
}
// TODO: make this dependent on which dockwidget is shown, otherwise we'll get valgrind issues
void IView::readPreferenceSettings()
{
QSettings settings("IVIEW", "PREFERENCES");
if (!displayMode.contains("SCAMP")) {
icdw->ui->zoomFitPushButton->setChecked(settings.value("zoomFitPushButton").toBool());
icdw->ui->autocontrastPushButton->setChecked(settings.value("autocontrastPushButton").toBool());
}
}
void IView::solutionAcceptanceStateReceived(bool state)
{
emit solutionAcceptanceState(state);
scampCorrectlyClosed = true;
this->close();
}
void IView::autoContrastPushButton_toggled_receiver(bool checked)
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (checked) {
autoContrast();
// Must clear all items (sky circles) on the scene, then redraw afterwards
clearAxes();
scene->removeCrosshair();
if (!skyCircleItems.isEmpty()) skyCircleItems.clear();
if (!acceptedSkyCircleItems.isEmpty()) {
for (auto &it : acceptedSkyCircleItems) {
scene->removeItem(it);
}
}
mapFITS();
myGraphicsView->setScene(scene);
myGraphicsView->show();
redrawSkyCirclesAndCats();
emit updateNavigatorBinned(binnedPixmapItem);
emit updateNavigatorBinnedWCS(wcs, wcsInit);
}
}
void IView::replotCatalogAfterZoom()
{
bool sourceCatShown = ui->actionSourceCat->isChecked();
bool refCatShown = ui->actionRefCat->isChecked();
clearItems();
if (sourceCatShown && ui->actionSourceCat->isVisible()) {
ui->actionSourceCat->setChecked(true);
showSourceCat();
}
if (refCatShown && ui->actionRefCat->isVisible()) {
ui->actionRefCat->setChecked(true);
showReferenceCat();
}
scene->zoomScale = icdw->zoom2scale(zoomLevel);
finderdw->bypassResolver();
}
void IView::zoomFitPushButton_clicked_receiver(bool checked)
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
if (checked) {
myGraphicsView->fitInView(scene->items(Qt::AscendingOrder).at(0), Qt::KeepAspectRatio);
double scale = myGraphicsView->transform().m11();
QString scaleFactor;
if (scale > 1.) scaleFactor = QString::number(scale,'f',2)+":1";
else scaleFactor = "1:"+QString::number(1./scale,'f',2);
// icdw->ui->zoomValueLabel->setText(scaleFactor);
}
replotCatalogAfterZoom();
}
void IView::zoomInPushButton_clicked_receiver()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
++zoomLevel;
myGraphicsView->resetMatrix();
myGraphicsView->scale(icdw->zoom2scale(zoomLevel), icdw->zoom2scale(zoomLevel));
replotCatalogAfterZoom();
}
void IView::zoomOutPushButton_clicked_receiver()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
--zoomLevel;
myGraphicsView->resetMatrix();
myGraphicsView->scale(icdw->zoom2scale(zoomLevel), icdw->zoom2scale(zoomLevel));
replotCatalogAfterZoom();
}
void IView::zoomZeroPushButton_clicked_receiver()
{
// Leave if no image is displayed
if (scene->items().isEmpty()) return;
zoomLevel = 0;
// Do this to update the zoom label
icdw->zoom2scale(zoomLevel);
myGraphicsView->resetMatrix();
replotCatalogAfterZoom();
}
void IView::minmaxLineEdit_returnPressed_receiver(QString rangeMin, QString rangeMax)
{
clearAxes();
dynRangeMin = rangeMin.toFloat();
dynRangeMax = rangeMax.toFloat();
mapFITS();
redrawUpdateAxes(); // redshift axes
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::colorFactorChanged_receiver(QString redFactor, QString blueFactor)
{
// Re-emit the signal from the dock widget to the color calibration dialog
emit colorFactorChanged(redFactor, blueFactor);
// Apply color factors:
mapFITS();
}
void IView::filterLineEdit_textChanged(const QString &arg1)
{
QString filter = arg1;
if (filter.isEmpty()
|| !filter.contains(".fits")
|| !filter.contains("*")) {
filter = "*.fits";
filterLineEdit->setText(filter);
}
setImageList(filter);
numImages = imageList.length();
pageLabel->setText("? / "+QString::number(numImages));
// Rewind
// iview->startAction_triggered();
}
void IView::fovCenterChangedReceiver(QPointF newCenter)
{
QPointF center = binnedToQimage(newCenter);
// qDebug() << newCenter << center;
myGraphicsView->centerOn(center);
}
void IView::targetResolvedReceived(QString alphaStr, QString deltaStr)
{
if (alphaStr.contains(":")) alphaStr = hmsToDecimal(alphaStr);
if (deltaStr.contains(":")) deltaStr = dmsToDecimal(deltaStr);
double x = 0.;
double y = 0.;
sky2xyQImage(alphaStr.toDouble(), deltaStr.toDouble(), x, y);
if (x > 0. && x < naxis1-1 && y > 0. && y < naxis2-1) {
myGraphicsView->centerOn(QPointF(x,y));
scene->addCrosshair(x,y);
}
else {
/*
* if (sender() == finderdw->ui->targetresolverToolButton) {
finderdw->ui->targetNameNonsiderealLineEdit->setText("outside f.o.v");
}
if (sender() == finderdw->ui->MPCresolverToolButton) {
finderdw->ui->targetNameSiderealLineEdit->setText("outside f.o.v");
}
*/
}
}
void IView::WCSupdatedReceived()
{
sendWCStoWCSdockWidget();
icdw->receiveWCS(wcs, wcsInit);
}
| 54,138
|
C++
|
.cc
| 1,369
| 32.303871
| 175
| 0.637209
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,418
|
mymagnifiedgraphicsview.cc
|
schirmermischa_THELI/src/iview/mymagnifiedgraphicsview.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mymagnifiedgraphicsview.h"
#include "iview.h"
MyMagnifiedGraphicsView::MyMagnifiedGraphicsView() : QGraphicsView()
{
QBrush brush(QColor("#000000"));
brush.setStyle(Qt::SolidPattern);
this->setBackgroundBrush(brush);
}
void MyMagnifiedGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
QPoint currentPos = event->pos();
// Display the current pixel coordinates under the cursor
QPointF currentPoint = mapToScene(currentPos);
emit currentMousePos(currentPoint);
// Also, if the right mouse button is pressed while moving,
// adjust brightness and contrast
if (rightButtonPressed) {
emit rightDragTravelled(rightDragStartPos - currentPos);
}
if (middleButtonPressed) {
// emit middleDragTravelled(previousMousePoint - currentPos);
// emit middleDragTravelled(currentPos);
if (middleMouseMode == "DragMode") {
if (_pan) {
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - 2.*(event->x() - _panStartX));
verticalScrollBar()->setValue(verticalScrollBar()->value() - 2.*(event->y() - _panStartY));
_panStartX = event->x();
_panStartY = event->y();
// event->accept();
// return;
}
}
}
if (leftButtonPressed) {
QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y());
emit leftDragTravelled(pointStart, currentPoint);
}
QGraphicsView::mouseMoveEvent(event);
}
void MyMagnifiedGraphicsView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
rightDragStartPos = event->pos();
rightButtonPressed = true;
emit rightPress();
}
if (event->button() == Qt::LeftButton) {
leftDragStartPos = event->pos();
QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y());
leftButtonPressed = true;
emit leftPress(pointStart);
}
if (event->button() == Qt::MiddleButton) {
// setDragMode(QGraphicsView::ScrollHandDrag);
// previousMousePoint = event->pos();
if (middleMouseMode == "DragMode") {
middleButtonPressed = true;
_pan = true;
_panStartX = event->x();
_panStartY = event->y();
setCursor(Qt::OpenHandCursor);
// event->accept();
}
}
QGraphicsView::mousePressEvent(event);
}
void MyMagnifiedGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
rightButtonPressed = false;
emit rightButtonReleased();
}
if (event->button() == Qt::LeftButton) {
leftButtonPressed = false;
emit leftButtonReleased();
}
if (event->button() == Qt::MiddleButton) {
middleButtonPressed = false;
if (middleMouseMode == "DragMode") {
_pan = false;
setCursor(Qt::ArrowCursor);
// event->accept();
// return;
}
}
QGraphicsView::mouseReleaseEvent(event);
}
void MyMagnifiedGraphicsView::updateMiddleMouseMode(QString mode)
{
middleMouseMode = mode;
}
| 3,936
|
C++
|
.cc
| 105
| 31.009524
| 111
| 0.654712
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,419
|
mygraphicsscene.cc
|
schirmermischa_THELI/src/iview/mygraphicsscene.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mygraphicsscene.h"
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsItem>
#include <QList>
#include <QDebug>
MyGraphicsScene::MyGraphicsScene()
{
}
// Override key event to delete selected items with the backspace or delete key
void MyGraphicsScene::keyReleaseEvent(QKeyEvent * keyEvent)
{
if(keyEvent->key() == Qt::Key_Backspace || keyEvent->key() == Qt::Key_Delete)
{
QList<QGraphicsItem*> selectedItems = this->selectedItems(); // get list of selected items
foreach(QGraphicsItem* item, selectedItems)
{
removeItem(item);
delete item;
item = nullptr;
}
emit itemDeleted();
}
}
void MyGraphicsScene::leaveEvent(QEvent *event)
{
if (event->type() == QEvent::Leave) {
emit mouseLeftScene();
QGraphicsScene::event(event);
}
}
void MyGraphicsScene::addCrosshair(double x, double y)
{
removeCrosshair();
QPen pen(QColor("#00ffaa"));
pen.setWidth(0);
QPen penBlack(QColor("#000000"));
penBlack.setWidth(0);
double width = 20/zoomScale;
double widthBlack = (width - 2/zoomScale);
crosshairCircleItem = addEllipse(x-width/2, y-width/2, width, width, pen);
crosshairCircleBlackItem = addEllipse(x-widthBlack/2, y-widthBlack/2, widthBlack, widthBlack, penBlack);
crosshairLineNItem = addLine(x, y-width/2, x, y-width, pen);
crosshairLineSItem = addLine(x, y+width/2, x, y+width, pen);
crosshairLineEItem = addLine(x-width/2, y, x-width, y, pen);
crosshairLineWItem = addLine(x+width/2, y, x+width, y, pen);
crosshairShown = true;
}
void MyGraphicsScene::removeCrosshair()
{
if (crosshairCircleItem != nullptr) {
removeItem(crosshairCircleItem);
crosshairCircleItem = nullptr;
}
if (crosshairCircleBlackItem != nullptr) {
removeItem(crosshairCircleBlackItem);
crosshairCircleBlackItem = nullptr;
}
if (crosshairLineNItem != nullptr) {
removeItem(crosshairLineNItem);
crosshairLineNItem = nullptr;
}
if (crosshairLineSItem != nullptr) {
removeItem(crosshairLineSItem);
crosshairLineSItem = nullptr;
}
if (crosshairLineEItem != nullptr) {
removeItem(crosshairLineEItem);
crosshairLineEItem = nullptr;
}
if (crosshairLineWItem != nullptr) {
removeItem(crosshairLineWItem);
crosshairLineWItem = nullptr;
}
crosshairShown = false;
}
| 3,158
|
C++
|
.cc
| 90
| 30.411111
| 108
| 0.711759
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,420
|
redshift.cc
|
schirmermischa_THELI/src/iview/redshift.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "iview.h"
#include "ui_iview.h"
#include "ui_ivredshiftdockwidget.h"
#include "ui_ivconfdockwidget.h"
#include "../functions.h"
#include "mygraphicsview.h"
#include "mygraphicsscene.h"
#include <QTransform>
void IView::updateAxesHelper()
{
observedAxis.init(currentMyImage->wcs->crval[0], currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, 75, "down", QColor("#00aaff"));
restframeAxis.init(currentMyImage->wcs->crval[0], currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, 25, "down", QColor("#ffdd00"));
spectrumAxis.init(currentMyImage->wcs->crval[0], currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, -25, "down", QColor("#ffdd00"), "spectrum");
// observedAxis.init(currentMyImage->crval1, currentMyImage->header., currentMyImage->naxis1, currentMyImage->naxis2, 75, "down", QColor("#00aaff"));
// restframeAxis.init(currentMyImage->crval1, currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, 25, "down", QColor("#ffdd00"));
// spectrumAxis.init(currentMyImage->crval1, currentMyImage->wcs->cd[0], currentMyImage->naxis1, currentMyImage->naxis2, -25, "down", QColor("#ffdd00"), "spectrum");
// Populate the spectrum axis with emission lines
spectrumAxis.tickLength = 20.;
if (zdw->ui->HCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->HList);
if (zdw->ui->NCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->NList);
if (zdw->ui->OCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->OList);
if (zdw->ui->SCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->SList);
if (zdw->ui->CCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->CList);
if (zdw->ui->HeCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->HeList);
if (zdw->ui->ArCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->ArList);
if (zdw->ui->NeCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->NeList);
if (zdw->ui->MgCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->MgList);
if (zdw->ui->NaCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->NaList);
if (zdw->ui->CaCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->CaList);
if (zdw->ui->FeCheckBox->isChecked()) spectrumAxis.addSpecies(zdw->FeList);
}
void IView::updateAxes()
{
if (!zdw->isVisible()) return;
// This slot is invoked (among others) everytime a new image is loaded
clearAxes();
updateAxesHelper();
// Do not show axes if redshift Dockwidget is not visible
if (!zdw->isVisible()) return;
showAxes();
}
// Invoked e.g. after right-click dragging. Must not redraw graphics scene, as this is done in main iView
void IView::redrawUpdateAxes()
{
if (!zdw->isVisible()) return;
updateAxesHelper();
showAxesHelper(observedAxisLineItems, observedAxisMainLineItems, observedAxisTextItems, observedAxis, "observed");
showAxesHelper(restframeAxisLineItems, restframeAxisMainLineItems, restframeAxisTextItems, restframeAxis, "restframe");
showAxesHelper(spectrumAxisLineItems, spectrumAxisMainLineItems, spectrumAxisTextItems, spectrumAxis, "spectrum");
}
void IView::showAxes()
{
if (!zdw->isVisible()) return;
showAxesHelper(observedAxisLineItems, observedAxisMainLineItems, observedAxisTextItems, observedAxis, "observed");
showAxesHelper(restframeAxisLineItems, restframeAxisMainLineItems, restframeAxisTextItems, restframeAxis, "restframe");
showAxesHelper(spectrumAxisLineItems, spectrumAxisMainLineItems, spectrumAxisTextItems, spectrumAxis, "spectrum");
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::showAxesHelper(QList<QGraphicsLineItem*> &lineItemList, QList<QGraphicsLineItem*> &mainLineItemList, QList<QGraphicsTextItem*> &textItemList, const MyAxis &axis, QString type)
{
// Remove all previously displayed items
// Tickmarks
if (!lineItemList.isEmpty()) {
for (auto &it: lineItemList) scene->removeItem(it);
lineItemList.clear();
}
// Main axis
if (!mainLineItemList.isEmpty()) {
for (auto &it: mainLineItemList) scene->removeItem(it);
mainLineItemList.clear();
}
// Add the main axis line if requested (not for the emission line tickmarks)
if (type != "spectrum") mainLineItemList.append(scene->addLine(axis.axisLine));
for (auto &it: axis.tickMarks) {
lineItemList.append(scene->addLine(it));
}
for (auto &it: lineItemList) {
it->setPen(axis.pen);
}
for (auto &it: mainLineItemList) {
it->setPen(axis.pen);
}
// Add the labels; this is in the same order as the line items, so the matching is preserved
for (auto &it : axis.tickLabels) {
textItemList.append(scene->addText(it));
}
// Setup the font
QFont currentFont = this->font();
qreal rescale;
if (!icdw->ui->zoomFitPushButton->isChecked()) rescale = icdw->zoom2scale(zoomLevel);
else rescale = myGraphicsView->transform().m11();
currentFont.setPointSize(int(float(currentFont.pointSize())/rescale));
int i=0;
QTransform transform;
transform.rotate(-45);
for (auto &it : textItemList) {
it->setFont(currentFont);
QString plainText = it->toPlainText();
// use a semi-transparent background
if (type != "observed") it->setHtml(QString("<div style='background:rgba(255, 220, 0, 50%);'>" + QString(" ") + plainText + QString(" ") + QString("</div>") ));
else it->setHtml(QString("<div style='background:rgba(0, 200, 255, 50%);'>" + QString(" ") + plainText + QString(" ") + QString("</div>") ));
it->setDefaultTextColor(QColor("#000000"));
qreal xpos = lineItemList.at(i)->line().x1();
qreal ypos = lineItemList.at(i)->line().y1();
++i;
int offset = 0;
if (type == "observed") offset = 5;
if (type == "restframe") offset = 5;
if (type == "spectrum") offset = -10;
it->setPos(xpos-20/icdw->zoom2scale(zoomLevel), ypos+offset/icdw->zoom2scale(zoomLevel));
if (type == "spectrum") it->setTransform(transform);
}
}
void IView::clearAxes()
{
if (!zdw->isVisible()) return;
observedAxis.clear();
restframeAxis.clear();
spectrumAxis.clear();
clearAxesHelper(observedAxisLineItems, observedAxisMainLineItems, observedAxisTextItems);
clearAxesHelper(restframeAxisLineItems, restframeAxisMainLineItems, restframeAxisTextItems);
clearAxesHelper(spectrumAxisLineItems, spectrumAxisMainLineItems, spectrumAxisTextItems);
myGraphicsView->setScene(scene);
myGraphicsView->show();
}
void IView::clearAxesHelper(QList<QGraphicsLineItem*> &lineItemList, QList<QGraphicsLineItem*> &mainLineItemList, QList<QGraphicsTextItem*> &textItemList)
{
// Remove all previously displayed items
if (!lineItemList.isEmpty()) {
for (auto &it: lineItemList) scene->removeItem(it);
lineItemList.clear();
}
if (!mainLineItemList.isEmpty()) {
for (auto &it: mainLineItemList) scene->removeItem(it);
mainLineItemList.clear();
}
if (!textItemList.isEmpty()) {
for (auto &it: textItemList) scene->removeItem(it);
textItemList.clear();
}
}
// Sends the wavelength under the cursor to redshiftDockWidget
void IView::showWavelength(QPointF point)
{
if (!zdw->isVisible()) return;
// This function receives the image coords from a mouseMoveEvent
// and translates them to wavelengths
// constant offsets required to show same coordinates as in skycat / ds9
float x_cursor = point.x() + 0.5;
double lambdaObs = observedAxis.pixelToWavelength(x_cursor);
double lambdaRest = restframeAxis.pixelToWavelength(x_cursor);
emit wavelengthUpdated(QString::number(lambdaObs, 'f', 1), QString::number(lambdaRest, 'f', 1));
}
void IView::updateFinesse(int value)
{
restframeAxis.finesse = 2000.*pow(2,value-5)/(1.+restframeAxis.z);
spectrumAxis.finesse = 2000.*pow(2,value-5)/(1.+restframeAxis.z);
}
void IView::resetRedshift()
{
restframeAxis.z = 0.;
restframeAxis.z_0 = 0.;
spectrumAxis.z = 0.;
spectrumAxis.z_0 = 0.;
zdw->ui->zLineEdit->setText("0.000");
}
void IView::redshiftChanged(QString text)
{
float z = 0.;
if (text.isEmpty()) z = 0.;
else z = text.toFloat();
restframeAxis.z = z;
spectrumAxis.z = z;
restframeAxis.z_0 = z;
spectrumAxis.z_0 = z;
updateAxes();
}
| 9,135
|
C++
|
.cc
| 192
| 43.041667
| 187
| 0.714751
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,421
|
mygraphicsview.cc
|
schirmermischa_THELI/src/iview/mygraphicsview.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mygraphicsview.h"
#include "iview.h"
#include <QTest>
MyGraphicsView::MyGraphicsView() : QGraphicsView()
{
QBrush brush(QColor("#000000"));
brush.setStyle(Qt::SolidPattern);
this->setBackgroundBrush(brush);
}
void MyGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
QPoint currentPos = event->pos();
// Display the current pixel coordinates under the cursor
QPointF currentPoint = mapToScene(currentPos);
emit currentMousePos(currentPoint);
// Also, if the right mouse button is pressed while moving,
// adjust brightness and contrast
if (rightButtonPressed) {
emit rightDragTravelled(rightDragStartPos - currentPos);
}
if (middleButtonPressed) {
// emit middleDragTravelled(previousMousePoint - currentPos);
// emit middleDragTravelled(currentPos);
if (middleMouseMode == "SkyMode") {
QPointF pointStart = mapToScene(middleDragStartPos.x(), middleDragStartPos.y());
emit middleSkyDragTravelled(pointStart, currentPoint);
}
else if (middleMouseMode == "DragMode") {
if (_pan) {
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - 2.*(event->x() - _panStartX));
verticalScrollBar()->setValue(verticalScrollBar()->value() - 2.*(event->y() - _panStartY));
_panStartX = event->x();
_panStartY = event->y();
// event->accept();
// return;
}
}
else if (middleMouseMode == "WCSMode") {
QPointF pointStart = mapToScene(wcsStart);
emit middleWCSTravelled(pointStart, currentPoint);
}
else if (middleMouseMode == "MaskingMode") {
QPointF pointStart = mapToScene(middleDragStartPos.x(), middleDragStartPos.y());
emit middleMaskingDragTravelled(pointStart, currentPoint);
}
}
if (leftButtonPressed) {
QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y());
emit leftDragTravelled(pointStart, currentPoint);
}
QGraphicsView::mouseMoveEvent(event);
}
void MyGraphicsView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
rightDragStartPos = event->pos();
rightButtonPressed = true;
emit rightPress();
}
if (event->button() == Qt::LeftButton) {
leftDragStartPos = event->pos();
QPointF pointStart = mapToScene(leftDragStartPos.x(), leftDragStartPos.y());
leftButtonPressed = true;
emit leftPress(pointStart);
}
if (event->button() == Qt::MiddleButton) {
// setDragMode(QGraphicsView::ScrollHandDrag);
// previousMousePoint = event->pos();
if (middleMouseMode == "SkyMode") {
middleDragStartPos = event->pos();
middleButtonPressed = true;
emit middlePress(middleDragStartPos);
}
if (middleMouseMode == "MaskingMode") {
middleDragStartPos = event->pos();
middleButtonPressed = true;
emit middlePress(middleDragStartPos);
}
else if (middleMouseMode == "DragMode") {
middleButtonPressed = true;
_pan = true;
_panStartX = event->x();
_panStartY = event->y();
setCursor(Qt::OpenHandCursor);
// event->accept();
}
else if (middleMouseMode == "WCSMode") {
emit middlePressResetCRPIX();
middleButtonPressed = true;
wcsStart = event->pos();
setCursor(Qt::SizeAllCursor);
}
}
QGraphicsView::mousePressEvent(event);
}
void MyGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
rightButtonPressed = false;
emit rightButtonReleased();
}
if (event->button() == Qt::LeftButton) {
leftButtonPressed = false;
emit leftButtonReleased();
}
if (event->button() == Qt::MiddleButton) {
middleButtonPressed = false;
if (middleMouseMode == "SkyMode") {
// setDragMode(QGraphicsView::NoDrag);
emit middleButtonReleased();
}
if (middleMouseMode == "MaskingMode") {
emit middleButtonReleased();
}
else if (middleMouseMode == "DragMode") {
_pan = false;
setCursor(Qt::ArrowCursor);
// event->accept();
// return;
}
else if (middleMouseMode == "WCSMode") {
emit middleWCSreleased();
setCursor(Qt::ArrowCursor);
// event->accept();
// return;
}
}
QGraphicsView::mouseReleaseEvent(event);
}
void MyGraphicsView::leaveEvent(QEvent *event)
{
emit mouseLeftView();
QGraphicsView::leaveEvent(event);
}
void MyGraphicsView::enterEvent(QEvent *event)
{
emit mouseEnteredView();
QGraphicsView::enterEvent(event);
}
void MyGraphicsView::paintEvent(QPaintEvent *event)
{
QRect viewport_rect(0, 0, viewport()->width(), viewport()->height());
emit viewportChanged(viewport_rect);
QGraphicsView::paintEvent(event);
}
void MyGraphicsView::updateMiddleMouseMode(QString mode)
{
middleMouseMode = mode;
}
| 6,030
|
C++
|
.cc
| 163
| 29.699387
| 111
| 0.636426
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,422
|
mygraphicsellipseitem.cc
|
schirmermischa_THELI/src/iview/mygraphicsellipseitem.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "mygraphicsellipseitem.h"
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsEllipseItem>
MyGraphicsEllipseItem::MyGraphicsEllipseItem()
{
this->setAcceptedMouseButtons(Qt::LeftButton);
}
void MyGraphicsEllipseItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
this->setSelected(true);
}
QGraphicsEllipseItem::mousePressEvent(event);
}
| 1,101
|
C++
|
.cc
| 28
| 37.178571
| 76
| 0.802817
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,423
|
myaxis.cc
|
schirmermischa_THELI/src/iview/myaxis.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "myaxis.h"
#include <QDebug>
MyAxis::MyAxis(QObject *parent) : QObject(parent)
{
}
void MyAxis::init(double crval_in, double cd_in, long naxis1_in, long naxis2_in, int offset, QString direction, QColor color, QString type)
{
pen.setColor(color);
pen.setWidth(0);
axisOffset = offset;
tickDirection = direction;
crval = crval_in;
cd = cd_in;
naxis1 = naxis1_in;
naxis2 = naxis2_in;
getWavelengthRange();
ybase = naxis2/2 + axisOffset;
axisLine.setLine(1, ybase, naxis1, ybase);
if (type.isEmpty()) getTickmarks();
if (type == "spectrum") initSpectrumTickmarks();
}
double MyAxis::pixelToWavelength(double x)
{
return (crval + cd * x) / (1.+z_0);
}
double MyAxis::wavelengthToPixel(double lambda)
{
return (lambda*(1.+z_0) - crval) / cd;
}
void MyAxis::getTickmarks()
{
tickLabels.clear();
tickMarks.clear();
// Step size depends on resolution
if (cd < 1.0) tickstep = 100;
else if (cd < 2.0 && cd >= 1.0) tickstep = 200;
else if (cd < 4.0 && cd >= 2.0) tickstep = 500;
else tickstep = 1000;
// Redshift correction, and lock onto even numbered tick values
tickstep /= (1.+z);
if (tickstep < 50) tickstep = 50;
else if (tickstep >= 50 && tickstep < 150) tickstep = 100;
else if (tickstep >= 150 && tickstep < 250) tickstep = 200;
else if (tickstep >= 250 && tickstep < 750) tickstep = 500;
else tickstep = 1000;
int start = floor(lambdaMin/tickstep) * tickstep;
int stop = ceil(lambdaMax/tickstep) * tickstep;
// The following takes into account that the y-axis in QPixmap is flipped.
int flip = -1;
if (tickDirection == "up") flip = 1;
for (int i=start; i<=stop; i=i+tickstep) {
float xpos = wavelengthToPixel(i);
if (i>=lambdaMin && i<=lambdaMax) {
tickLabels.append(QString::number(i));
QLineF line = QLineF(xpos, ybase, xpos, ybase+flip*tickLength);
tickMarks.append(line);
}
}
}
void MyAxis::initSpectrumTickmarks()
{
tickLabels.clear();
tickMarks.clear();
}
void MyAxis::addSpecies(const QList<QPair<QString, float> > &list)
{
// The following takes into account that the y-axis in QPixmap is flipped.
int flip = -1;
if (tickDirection == "up") flip = 1;
for (auto &it : list) {
float lambda = it.second;
float xpos = wavelengthToPixel(it.second);
if (lambda >= lambdaMin && lambda <= lambdaMax) {
tickLabels.append(it.first + " " + QString::number(it.second, 'f', 0));
QLineF line = QLineF(xpos, ybase, xpos, ybase-flip*tickLength);
tickMarks.append(line);
}
}
}
// must be updated everytime z changes
void MyAxis::getWavelengthRange()
{
float lambda1 = pixelToWavelength(0);
float lambda2 = pixelToWavelength(naxis1);
lambdaMin = lambda1 < lambda2 ? lambda1 : lambda2;
lambdaMax = lambda1 > lambda2 ? lambda1 : lambda2;
}
void MyAxis::redshiftChangedReceiver(QString zstring)
{
z = zstring.toFloat();
}
void MyAxis::clear()
{
tickLabels.clear();
tickMarks.clear();
}
void MyAxis::initRedshift(QPointF pointStart)
{
z_0 = z;
}
void MyAxis::closeRedshift()
{
z = z_0;
}
void MyAxis::redshiftSpectrum(QPointF pointStart, QPointF currentPoint)
{
float dx = currentPoint.x() - pointStart.x();
float dz = dx / finesse * (1.+z);
float z_tmp = z + dz;
if (z_tmp < 0) z_tmp = 0.;
z_0 = z_tmp;
getWavelengthRange();
emit redshiftRecomputed();
emit redshiftUpdated(z_0);
}
| 4,249
|
C++
|
.cc
| 129
| 28.829457
| 139
| 0.675391
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,424
|
ivwcsdockwidget.cc
|
schirmermischa_THELI/src/iview/dockwidgets/ivwcsdockwidget.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "ivwcsdockwidget.h"
#include "ui_ivwcsdockwidget.h"
#include "../../functions.h"
IvWCSDockWidget::IvWCSDockWidget(QWidget *parent) :
QDockWidget(parent),
ui(new Ui::IvWCSDockWidget)
{
ui->setupUi(this);
}
IvWCSDockWidget::~IvWCSDockWidget()
{
delete ui;
}
void IvWCSDockWidget::init()
{
cd11 = cd11_orig;
cd12 = cd12_orig;
cd21 = cd21_orig;
cd22 = cd22_orig;
updateLineEdits();
}
void IvWCSDockWidget::on_cd11Slider_sliderMoved(int position)
{
QSlider *slider = qobject_cast<QSlider*>(sender());
float weight = calcCDweight();
if (weight > 1.) weight = 1.;
cd11 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd11_orig;
emit CDmatrixChanged(cd11, cd12, cd21, cd22);
ui->cd11LineEdit->setText(QString::number(cd11, 'e', 6));
}
void IvWCSDockWidget::on_cd12Slider_sliderMoved(int position)
{
QSlider *slider = qobject_cast<QSlider*>(sender());
float weight = calcCDweight();
if (weight < 1.) weight = 1.;
weight = 5.;
cd12 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd12_orig;
emit CDmatrixChanged(cd11, cd12, cd21, cd22);
ui->cd12LineEdit->setText(QString::number(cd12, 'e', 6));
}
void IvWCSDockWidget::on_cd21Slider_sliderMoved(int position)
{
QSlider *slider = qobject_cast<QSlider*>(sender());
float weight = calcCDweight();
if (weight < 1.) weight = 1.;
weight = 5.;
cd21 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd21_orig;
emit CDmatrixChanged(cd11, cd12, cd21, cd22);
ui->cd21LineEdit->setText(QString::number(cd21, 'e', 6));
}
void IvWCSDockWidget::on_cd22Slider_sliderMoved(int position)
{
QSlider *slider = qobject_cast<QSlider*>(sender());
float weight = calcCDweight();
if (weight > 1.) weight = 1.;
cd22 = translateCDmatrixSlider(position, slider->maximum() / weight) * cd22_orig;
emit CDmatrixChanged(cd11, cd12, cd21, cd22);
ui->cd22LineEdit->setText(QString::number(cd22, 'e', 6));
}
// Calculate a weight that makes the WCS slider more sensitive to smaller CD values
float IvWCSDockWidget::calcCDweight()
{
float ratio = 1.0;
if (cd12_orig != 0. && cd11_orig != 0) ratio = fabs(cd11_orig / cd12_orig);
else if (cd11_orig == 0. && cd12_orig != 0.) ratio = 0.001; // effective
else if (cd12_orig == 0. && cd11_orig != 0.) ratio = 1000.; // effective
else ratio = 1.;
float weight = sqrt(ratio);
// return 1.; // deactivated
return weight;
}
// Translates the integer slider position to a relative change, non-linearly
double IvWCSDockWidget::translateCDmatrixSlider(int position, int maxRange)
{
double pos = position;
double range = maxRange;
return pow(2., 0.5*pos/range); // from 0.7 to 1.4
}
// Translates the integer slider position to a relative change, non-linearly using a cosh dependence
double IvWCSDockWidget::translatePlateScaleSlider(int position, int maxRange)
{
double pos = position;
double range = maxRange;
return pow(2., 0.5*pos/range); // from 0.7 to 1.4
}
// Translates the integer slider position to a relative change, non-linearly using a cosh dependence
double IvWCSDockWidget::translatePosAngleSlider(int position, int maxRange)
{
double pos = position;
double range = maxRange;
return 10.*(pos/range); // from -10 to 10
}
void IvWCSDockWidget::on_plateScaleSlider_sliderMoved(int position)
{
QSlider *slider = qobject_cast<QSlider*>(sender());
double rescaleFactor = translatePlateScaleSlider(position, slider->maximum());
cd11 = cd11_orig * rescaleFactor;
cd12 = cd12_orig * rescaleFactor;
cd21 = cd21_orig * rescaleFactor;
cd22 = cd22_orig * rescaleFactor;
emit CDmatrixChanged(cd11, cd12, cd21, cd22);
updateLineEdits();
}
void IvWCSDockWidget::on_posAngleSlider_sliderMoved(int position)
{
QSlider *slider = qobject_cast<QSlider*>(sender());
double oldPA = getPosAnglefromCD(cd11_orig, cd12_orig, cd21_orig, cd22_orig, true); // in [deg]
double newPA = oldPA + translatePosAngleSlider(position, slider->maximum()); // in [deg]
cd11 = cd11_orig;
cd12 = cd12_orig;
cd21 = cd21_orig;
cd22 = cd22_orig;
rotateCDmatrix(cd11, cd12, cd21, cd22, newPA);
emit CDmatrixChanged(cd11, cd12, cd21, cd22);
updateLineEdits();
}
void IvWCSDockWidget::on_resetPushButton_clicked()
{
cd11 = cd11_orig;
cd12 = cd12_orig;
cd21 = cd21_orig;
cd22 = cd22_orig;
updateLineEdits();
restoreSliders();
emit CDmatrixChanged(cd11, cd12, cd21, cd22);
}
void IvWCSDockWidget::updateLineEdits()
{
ui->cd11LineEdit->setText(QString::number(cd11, 'e', 6));
ui->cd12LineEdit->setText(QString::number(cd12, 'e', 6));
ui->cd21LineEdit->setText(QString::number(cd21, 'e', 6));
ui->cd22LineEdit->setText(QString::number(cd22, 'e', 6));
double pscale1 = sqrt(cd11 * cd11 + cd21 * cd21);
double pscale2 = sqrt(cd12 * cd12 + cd22 * cd22);
QString pscale = QString::number(0.5*(pscale1+pscale2)*3600., 'f', 6);
ui->plateScaleLineEdit->setText(pscale);
QString PA = QString::number(getPosAnglefromCD(cd11, cd12, cd21, cd22), 'f', 2); // in [deg]
ui->posAngleLineEdit->setText(PA);
}
void IvWCSDockWidget::restoreSliders()
{
ui->cd11Slider->setValue(0);
ui->cd12Slider->setValue(0);
ui->cd21Slider->setValue(0);
ui->cd22Slider->setValue(0);
ui->plateScaleSlider->setValue(0);
ui->posAngleSlider->setValue(0);
}
void IvWCSDockWidget::on_cd11Slider_sliderReleased()
{
emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22);
}
void IvWCSDockWidget::on_cd12Slider_sliderReleased()
{
emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22);
}
void IvWCSDockWidget::on_cd21Slider_sliderReleased()
{
emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22);
}
void IvWCSDockWidget::on_cd22Slider_sliderReleased()
{
emit CDmatrixChangedFITS(cd11, cd12, cd21, cd22);
}
| 6,637
|
C++
|
.cc
| 178
| 33.91573
| 101
| 0.712973
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,425
|
ivconfdockwidget.cc
|
schirmermischa_THELI/src/iview/dockwidgets/ivconfdockwidget.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "ivconfdockwidget.h"
#include "ui_ivconfdockwidget.h"
#include "../iview.h"
#include <QPainter>
#include <math.h>
IvConfDockWidget::IvConfDockWidget(IView *parent) :
QDockWidget(parent),
ui(new Ui::IvConfDockWidget)
{
ui->setupUi(this);
iview = parent;
// Populate the navigator widget
QPalette backgroundPalette;
backgroundPalette.setColor(QPalette::Base, QColor("#000000"));
magnifiedGraphicsView = new MyMagnifiedGraphicsView();
magnifiedGraphicsView->setPalette(backgroundPalette);
magnifiedGraphicsView->setMouseTracking(true);
magnifiedGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
magnifiedGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
binnedGraphicsView = new MyBinnedGraphicsView();
binnedGraphicsView->setPalette(backgroundPalette);
binnedGraphicsView->setMouseTracking(true);
binnedGraphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
binnedGraphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// binnedGraphicsView->setRenderHint(QPainter::Antialiasing);
// ui->navigatorStackedWidget->setContentsMargins(0,0,0,0);
ui->binnedGraphicsLayout->insertWidget(0, binnedGraphicsView);
ui->magnifiedGraphicsLayout->insertWidget(1, magnifiedGraphicsView);
navigator_binned_nx = ui->binnedFrame->width();
navigator_binned_ny = ui->binnedFrame->height();
navigator_magnified_nx = ui->magnifiedFrame->width();
navigator_magnified_ny = ui->magnifiedFrame->height();
binnedGraphicsView->nx = navigator_binned_nx;
binnedGraphicsView->ny = navigator_binned_ny;
ui->quitPushButton->hide();
connect(binnedGraphicsView, &MyBinnedGraphicsView::currentMousePos, this, &IvConfDockWidget::showCurrentMousePosBinned);
// connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftDragTravelled, this, &IView::drawSeparationVector);
// connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftPress, this, &IView::initSeparationVector);
// connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftPress, this, &IView::sendStatisticsCenter);
// connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftButtonReleased, this, &IView::clearSeparationVector);
// connect(magnifyGraphicsView, &MyBinnedGraphicsView::leftButtonReleased, this, &IView::updateSkyCircles);
}
IvConfDockWidget::~IvConfDockWidget()
{
delete ui;
}
void IvConfDockWidget::switchMode(QString mode)
{
if (mode == "FITSmonochrome" || mode == "MEMview") {
ui->valueGreenLabel->hide();
ui->valueBlueLabel->hide();
ui->valueGreenLeftLabel->hide();
ui->valueBlueLeftLabel->hide();
}
else if (mode == "FITScolor") {
ui->valueGreenLabel->show();
ui->valueBlueLabel->show();
ui->valueGreenLeftLabel->show();
ui->valueBlueLeftLabel->show();
ui->valueLeftLabel->setText("R = ");
}
else if (mode == "CLEAR") {
ui->xposLabel->setText("");
ui->yposLabel->setText("");
ui->alphaDecLabel->setText("");
ui->alphaHexLabel->setText("");
ui->deltaDecLabel->setText("");
ui->deltaHexLabel->setText("");
ui->valueLabel->setText("");
// ui->zoomValueLabel->setText("");
ui->valueGreenLabel->hide();
ui->valueBlueLabel->hide();
ui->valueGreenLeftLabel->hide();
ui->valueBlueLeftLabel->hide();
}
}
double IvConfDockWidget::zoom2scale(int zoomlevel)
{
// Translates the integer zoom level to a scaling factor.
// Update the zoom label
if (zoomlevel > 0) {
// ui->zoomValueLabel->setText(QString::number(zoomlevel+1)+":1");
iview->scene->zoomScale = zoomlevel+1.;
return zoomlevel+1.;
}
else if (zoomlevel == 0) {
// ui->zoomValueLabel->setText("1:1");
iview->scene->zoomScale = 1.;
return 1.;
}
else {
// ui->zoomValueLabel->setText("1:"+QString::number(-zoomlevel+1));
iview->scene->zoomScale = 1./(-zoomlevel+1.);
return 1./(-zoomlevel+1.);
}
}
void IvConfDockWidget::on_zoomInPushButton_clicked()
{
ui->zoomFitPushButton->setChecked(false);
emit zoomInPushButton_clicked();
}
void IvConfDockWidget::on_zoomOutPushButton_clicked()
{
ui->zoomFitPushButton->setChecked(false);
emit zoomOutPushButton_clicked();
}
void IvConfDockWidget::on_zoomZeroPushButton_clicked()
{
ui->zoomFitPushButton->setChecked(false);
emit zoomZeroPushButton_clicked();
}
void IvConfDockWidget::on_zoomFitPushButton_clicked()
{
emit zoomFitPushButton_clicked(ui->zoomFitPushButton->isChecked());
}
void IvConfDockWidget::on_minLineEdit_returnPressed()
{
ui->autocontrastPushButton->setChecked(false);
emit minmaxLineEdit_returnPressed(ui->minLineEdit->text(), ui->maxLineEdit->text());
}
void IvConfDockWidget::on_maxLineEdit_returnPressed()
{
//QPixmap magnifiedPixmap = QPixmap("/home/mischa/euclid_logo.png");
//icdw->magnifiedGraphicsView->resetMatrix();
//QGraphicsPixmapItem *newItem = new QGraphicsPixmapItem(magnifiedPixmap);
ui->autocontrastPushButton->setChecked(false);
emit minmaxLineEdit_returnPressed(ui->minLineEdit->text(), ui->maxLineEdit->text());
}
void IvConfDockWidget::on_autocontrastPushButton_toggled(bool checked)
{
emit autoContrastPushButton_toggled(checked);
}
void IvConfDockWidget::on_quitPushButton_clicked()
{
emit closeIview();
}
// receiver from mouse pos hovering in binned vew
void IvConfDockWidget::showCurrentMousePosBinned(QPointF currentMousePos)
{
QPointF qpoint = iview->binnedToQimage(currentMousePos);
long i = qpoint.x();
long j = iview->naxis2 - qpoint.y();
ui->xposLabel->setText(QString::number(i));
ui->yposLabel->setText(QString::number(j));
// display sky coords
iview->xy2sky(qpoint.x(), iview->naxis2 - qpoint.y());
// Display pixel values: respect image boundaries
if (i<0 || j<0 || i>= iview->naxis1 || j>= iview->naxis2) {
if (iview->displayMode == "FITSmonochrome" || iview->displayMode == "MEMview") {
ui->valueLeftLabel->setText("Value = ");
ui->valueLabel->setText("");
}
else if (iview->displayMode == "FITScolor") {
ui->valueLeftLabel->setText("R = ");
ui->valueLabel->setText("");
ui->valueGreenLabel->setText("");
ui->valueBlueLabel->setText("");
}
}
else {
if (iview->displayMode == "FITSmonochrome" || iview->displayMode == "MEMview") {
ui->valueLabel->setText(QString::number(iview->fitsData[i+iview->naxis1*j]) + " " + iview->currentMyImage->bunit);
}
else if (iview->displayMode == "FITScolor") {
ui->valueLeftLabel->setText("R = "+QString::number(iview->fitsDataR[i+iview->naxis1*j]));
ui->valueLabel->setText(QString::number(iview->fitsDataR[i+iview->naxis1*j]) + " " + iview->currentMyImage->bunit);
ui->valueGreenLabel->setText(QString::number(iview->fitsDataG[i+iview->naxis1*j]) + " " + iview->currentMyImage->bunit);
ui->valueBlueLabel->setText(QString::number(iview->fitsDataB[i+iview->naxis1*j]) + " " + iview->currentMyImage->bunit);
}
}
}
void IvConfDockWidget::updateNavigatorMagnifiedReceived(QGraphicsPixmapItem *magnifiedPixmapItem, qreal magnification, float dx, float dy)
{
magnifiedGraphicsView->resetMatrix();
magnifiedScene->clear();
magnifiedScene->addItem(magnifiedPixmapItem);
magnifiedGraphicsView->setScene(magnifiedScene);
magnifiedGraphicsView->scale(magnification, magnification);
magnifiedGraphicsView->centerOn(magnifiedPixmapItem);
QPen pen(QColor("#00ffff"));
pen.setCosmetic(true);
float x1 = navigator_magnified_nx / magnification / 2.;
float y1 = navigator_magnified_ny / magnification / 2.;
QPoint p1 = QPoint(x1, y1);
QPoint p2 = QPoint(x1, y1);
// dx and dy intended to realign pixmap when cursor moves out of image boundary, but it is not working.
// magnifiedGraphicsView->centerOn(x1+dx, y1+dy);
magnifiedScene->addRect(QRect(p1,p2), pen);
magnifiedGraphicsView->show();
// ui->navigatorStackedWidget->setCurrentIndex(1);
}
void IvConfDockWidget::clearMagnifiedSceneReceiver()
{
magnifiedScene->clear();
magnifiedGraphicsView->show();
}
void IvConfDockWidget::clearBinnedSceneReceiver()
{
binnedScene->clear();
binnedGraphicsView->show();
}
void IvConfDockWidget::updateNavigatorBinnedReceived(QGraphicsPixmapItem *binnedPixmapItem)
{
// binnedGraphicsView->resetMatrix();
binnedScene->clear();
binnedScene->addItem(binnedPixmapItem);
// needed to prevent binnedView from scrolling
binnedScene->setSceneRect(binnedPixmapItem->boundingRect());
// panning movement restricted to fov, half offset, if the following line is commented. Unclear why
binnedGraphicsView->binnedSceneRect = binnedScene->sceneRect();
binnedGraphicsView->setScene(binnedScene);
binnedGraphicsView->show();
}
// Receiver for the event when the mouse enters the main graphics view
void IvConfDockWidget::mouseEnteredViewReceived()
{
// ui->navigatorStackedWidget->setCurrentIndex(1);
}
// Receiver for the event when the mouse leaves the main graphics view
void IvConfDockWidget::mouseLeftViewReceived()
{
// when the mouse cursor leaves the scene
magnifiedScene->clear();
magnifiedGraphicsView->show();
// ui->navigatorStackedWidget->setCurrentIndex(0);
}
// whenever the user scrolls or zooms in the main window , this slot is invoked
void IvConfDockWidget::updateNavigatorBinnedViewportReceived(QRect rect)
{
// leave if the user scrolls by dragging the fov rectangle in the binned window
if (binnedGraphicsView->fovBeingDragged) return;
// delete the old display of the rect
QList<QGraphicsItem*> items = binnedScene->items();
for (auto &it : items) {
QGraphicsRectItem *rect = qgraphicsitem_cast<QGraphicsRectItem*>(it);
if (rect) binnedScene->removeItem(it);
}
// draw the new rect
QPen pen(QColor("#00ffff"));
pen.setCosmetic(true);
pen.setWidth(0);
binnedGraphicsView->fovRectItem = new MyQGraphicsRectItem(rect, nullptr);
binnedGraphicsView->fovRectItem->setPen(pen);
binnedGraphicsView->fovRectItem->setFlags(QGraphicsEllipseItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges);
binnedScene->addItem(binnedGraphicsView->fovRectItem);
// binnedGraphicsView->fovRectItem->setFlags(QGraphicsEllipseItem::ItemIsMovable | QGraphicsRectItem::ItemSendsGeometryChanges);
// binnedGraphicsView->fovRectItem->setFlags(QGraphicsRectItem::ItemSendsGeometryChanges);
binnedGraphicsView->setScene(binnedScene);
binnedGraphicsView->show();
}
void IvConfDockWidget::updateNavigatorMagnifiedViewportReceived()
{
return;
// remove old rects
QList<QGraphicsItem*> items = magnifiedScene->items();
for (auto &it : items) {
QGraphicsRectItem *rectcast = qgraphicsitem_cast<QGraphicsRectItem*>(it);
if (rectcast) magnifiedScene->removeItem(it);
}
QPen pen(QColor("#aaffff"));
pen.setCosmetic(true);
pen.setWidth(0);
int x1 = navigator_magnified_nx/2-0.5;
int x2 = navigator_magnified_nx/2+0.5;
int y1 = navigator_magnified_ny/2-0.5;
int y2 = navigator_magnified_ny/2+0.5;
QPoint p1 = magnifiedGraphicsView->mapFromScene(QPoint(x1, y1));
QPoint p2 = magnifiedGraphicsView->mapFromScene(QPoint(x2, y2));
magnifiedScene->addRect(QRect(p1, p2), pen);
magnifiedGraphicsView->setScene(magnifiedScene);
magnifiedGraphicsView->show();
}
void IvConfDockWidget::receiveWCS(wcsprm *WCS, bool wcsinit)
{
if (!wcsinit) return;
wcs = WCS;
// Catching spectroscopic exposures or others with invalid "imaging" WCS
if (!wcs) return;
cd11 = wcs->cd[0];
cd12 = wcs->cd[1];
cd21 = wcs->cd[2];
cd22 = wcs->cd[3];
if (cd11 == 0. && cd12 == 0. && cd21 == 0. && cd22 == 0.) return;
drawCompass();
}
void IvConfDockWidget::drawCompass()
{
// delete old compass elements
QList<QGraphicsItem*> items = binnedScene->items();
for (auto &it : items) {
QGraphicsLineItem *line = qgraphicsitem_cast<QGraphicsLineItem*>(it);
if (line) binnedScene->removeItem(it);
QGraphicsTextItem *text = qgraphicsitem_cast<QGraphicsTextItem*>(it);
if (text) binnedScene->removeItem(it);
}
double norm = sqrt(cd11*cd11+cd12*cd12);
double length = navigator_binned_nx / 5.;
QPointF start = iview->qimageToBinned(QPointF(iview->naxis1/2, iview->naxis2/2));
QPen pen(QColor("#ffff00"));
pen.setCosmetic(true);
pen.setWidth(0);
// Arrows
QPointF eastEnd;
QPointF northEnd;
eastEnd.setX(start.x() + cd11/norm * length);
eastEnd.setY(start.y() - cd12/norm * length); // y axis is inverted in QImage wrt FITS, hence -cd12
northEnd.setX(start.x() + cd21/norm * length);
northEnd.setY(start.y() - cd22/norm * length); // y axis is inverted in QImage wrt FITS, hence -cd22
QLineF eastArrow = QLineF(start, eastEnd);
QLineF northArrow = QLineF(start, northEnd);
binnedScene->addLine(eastArrow, pen);
binnedScene->addLine(northArrow, pen);
// Labels
QGraphicsTextItem *labelEast = binnedScene->addText("E");
QGraphicsTextItem *labelNorth = binnedScene->addText("N");
labelEast->setDefaultTextColor(QColor("#ffff00"));
labelNorth->setDefaultTextColor(QColor("#ffff00"));
int exoffset = labelEast->boundingRect().width()/2;
int eyoffset = labelEast->boundingRect().height()/2;
int nxoffset = labelNorth->boundingRect().width()/2;
int nyoffset = labelNorth->boundingRect().height()/2;
int exspace = 0.3*(eastEnd.x() - start.x());
int eyspace = 0.3*(eastEnd.y() - start.y());
int nxspace = 0.3*(northEnd.x() - start.x());
int nyspace = 0.3*(northEnd.y() - start.y());
labelEast->setPos(eastEnd.x()-exoffset+exspace, eastEnd.y()-eyoffset+eyspace);
labelNorth->setPos(northEnd.x()-nxoffset+nxspace, northEnd.y()-nyoffset+nyspace);
binnedGraphicsView->show();
}
| 14,920
|
C++
|
.cc
| 343
| 38.650146
| 138
| 0.712967
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,426
|
ivscampdockwidget.cc
|
schirmermischa_THELI/src/iview/dockwidgets/ivscampdockwidget.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "ivscampdockwidget.h"
#include "ui_ivscampdockwidget.h"
#include "../iview.h"
#include <QObject>
IvScampDockWidget::IvScampDockWidget(IView *parent) :
QDockWidget(parent),
ui(new Ui::IvScampDockWidget)
{
ui->setupUi(this);
iview = parent;
}
IvScampDockWidget::~IvScampDockWidget()
{
delete ui;
}
void IvScampDockWidget::on_acceptSolution_clicked()
{
emit solutionAcceptanceState(true);
}
void IvScampDockWidget::on_rejectSolution_clicked()
{
emit solutionAcceptanceState(false);
}
| 1,202
|
C++
|
.cc
| 37
| 30.432432
| 75
| 0.793761
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,427
|
ivredshiftdockwidget.cc
|
schirmermischa_THELI/src/iview/dockwidgets/ivredshiftdockwidget.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "ivredshiftdockwidget.h"
#include "ui_ivredshiftdockwidget.h"
#include "../iview.h"
#include "../../functions.h"
#include <math.h>
#include <QString>
#include <QSpinBox>
#include <QList>
#include <QPair>
IvRedshiftDockWidget::IvRedshiftDockWidget(IView *parent) :
QDockWidget(parent),
ui(new Ui::IvRedshiftDockWidget)
{
ui->setupUi(this);
iview = parent;
populateWavelengthMaps();
init();
QString lambda = QString(QChar(0xbb, 0x03));
QString angstrom = QString(QChar(0x2b, 0x21));
ui->lambdaObsLabel->setText(lambda+"<sub>observed</sub>"+" ["+angstrom+"]");
ui->lambdaRestLabel->setText(lambda+"<sub>restframe</sub>"+" ["+angstrom+"]");
}
IvRedshiftDockWidget::~IvRedshiftDockWidget()
{
delete ui;
}
void IvRedshiftDockWidget::populateWavelengthMaps()
{
HList.append(qMakePair(QString("Lya"), 1215));
HList.append(qMakePair(QString("Lyb"), 1025));
HList.append(qMakePair(QString("Lyg"), 972));
HList.append(qMakePair(QString("Hd"), 4103));
HList.append(qMakePair(QString("Hg"), 4343));
HList.append(qMakePair(QString("Hb"), 4864));
HList.append(qMakePair(QString("Ha"), 6565));
HList.append(qMakePair(QString("Paa"), 18746));
HList.append(qMakePair(QString("Pab"), 12815));
HList.append(qMakePair(QString("Pag"), 10935));
HList.append(qMakePair(QString("Brg"), 21650));
HList.append(qMakePair(QString("H2_1-0"), 21220));
HList.append(qMakePair(QString("H2_2-1"), 22480));
HeList.append(qMakePair(QString("HeII"), 1640));
HeList.append(qMakePair(QString("HeII"), 2733));
HeList.append(qMakePair(QString("HeI"), 2945));
HeList.append(qMakePair(QString("HeII"), 3204));
HeList.append(qMakePair(QString("HeI"), 3889));
HeList.append(qMakePair(QString("HeI"), 4471));
HeList.append(qMakePair(QString("HeII"), 4687));
HeList.append(qMakePair(QString("HeII"), 5413));
HeList.append(qMakePair(QString("HeI"), 5877));
HeList.append(qMakePair(QString("HeI"), 6680));
HeList.append(qMakePair(QString("HeI"), 10830));
HeList.append(qMakePair(QString("HeI"), 20581));
OList.append(qMakePair(QString("OVI"), 1032));
OList.append(qMakePair(QString("OVI"), 1038));
OList.append(qMakePair(QString("OVI]"), 1402));
OList.append(qMakePair(QString("OIII]"), 1666));
OList.append(qMakePair(QString("OIII"), 3133));
OList.append(qMakePair(QString("[OII]"), 3727));
OList.append(qMakePair(QString("[OIII]"), 4363));
OList.append(qMakePair(QString("[OIII]"), 4960));
OList.append(qMakePair(QString("[OIII]"), 5008));
OList.append(qMakePair(QString("[OI]"), 6302));
OList.append(qMakePair(QString("[OI]"), 6366));
OList.append(qMakePair(QString("[OII]"), 7321));
NList.append(qMakePair(QString("NV"), 1240));
NList.append(qMakePair(QString("[NII]"), 6550));
NList.append(qMakePair(QString("[NII]"), 6586));
CList.append(qMakePair(QString("CIII"), 977));
CList.append(qMakePair(QString("CIII]"), 1909));
CList.append(qMakePair(QString("CIV"), 1549));
CList.append(qMakePair(QString("CII"), 2326));
ArList.append(qMakePair(QString("[ArIII]"), 7138));
SList.append(qMakePair(QString("[SII]"), 1812));
SList.append(qMakePair(QString("[SII]"), 1822));
SList.append(qMakePair(QString("[SII]"), 4069));
SList.append(qMakePair(QString("[SII]"), 4076));
SList.append(qMakePair(QString("SII"), 5203));
SList.append(qMakePair(QString("[SII]"), 6718));
SList.append(qMakePair(QString("[SII]"), 6733));
SList.append(qMakePair(QString("[SIII]"), 9071));
SList.append(qMakePair(QString("[SIII]"), 9533));
NaList.append(qMakePair(QString("NaD2"), 5890));
NaList.append(qMakePair(QString("NaD1"), 5896));
NeList.append(qMakePair(QString("[NeIV]"), 2424));
NeList.append(qMakePair(QString("[NeV]"), 3347));
NeList.append(qMakePair(QString("[NeV]"), 3427));
NeList.append(qMakePair(QString("[NeIII]"), 3869));
NeList.append(qMakePair(QString("[NeIII]"), 3968));
CaList.append(qMakePair(QString("CaH"), 3934));
CaList.append(qMakePair(QString("CaK"), 3969));
CaList.append(qMakePair(QString("CaT1"), 8499));
CaList.append(qMakePair(QString("CaT2"), 8542));
CaList.append(qMakePair(QString("CaT3"), 8662));
MgList.append(qMakePair(QString("Mg"), 2799));
MgList.append(qMakePair(QString("Mg"), 5167));
MgList.append(qMakePair(QString("Mg"), 5173));
MgList.append(qMakePair(QString("Mg"), 5184));
FeList.append(qMakePair(QString("FeI"), 2745));
FeList.append(qMakePair(QString("FeI"), 2807));
FeList.append(qMakePair(QString("FeI"), 2950));
FeList.append(qMakePair(QString("FeI"), 5725));
FeList.append(qMakePair(QString("[FeVII]"), 6089));
FeList.append(qMakePair(QString("FeI"), 11887));
}
void IvRedshiftDockWidget::init()
{
connect(ui->HCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->HeCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->NCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->CCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->OCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->SCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->NeCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->NaCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->CaCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->MgCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->ArCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->FeCheckBox, &QCheckBox::clicked, iview, &IView::updateAxes);
connect(ui->finesseSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), iview, &IView::updateFinesse); // QSpinBox has two valueChanged(), signals with int and string arguments; we need int
connect(ui->zLineEdit, &QLineEdit::textEdited, iview, &IView::redshiftChanged);
connect(ui->zLineEdit, &QLineEdit::textChanged, this, &IvRedshiftDockWidget::validate);
}
void IvRedshiftDockWidget::showWavelength(QString lobs, QString lrest)
{
// Display the wavelengths
ui->lambdaObsLineEdit->setText(lobs);
ui->lambdaRestLineEdit->setText(lrest);
}
void IvRedshiftDockWidget::on_zLineEdit_textChanged(const QString &arg1)
{
emit redshiftEdited(ui->zLineEdit->text());
}
void IvRedshiftDockWidget::redshiftUpdatedReceiver(float z_0)
{
ui->zLineEdit->setText(QString::number(z_0, 'f', 4));
}
void IvRedshiftDockWidget::validate()
{
QRegExp rf( "^[0-9]*[.]{0,1}[0-9]+" );
QValidator* validator_float_pos = new QRegExpValidator(rf, this );
ui->zLineEdit->setValidator(validator_float_pos);
}
| 7,511
|
C++
|
.cc
| 157
| 43.840764
| 221
| 0.70777
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,428
|
ivstatisticsdockwidget.cc
|
schirmermischa_THELI/src/iview/dockwidgets/ivstatisticsdockwidget.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "ivstatisticsdockwidget.h"
#include "ui_ivstatisticsdockwidget.h"
#include "../iview.h"
#include "../../functions.h"
#include <math.h>
IvStatisticsDockWidget::IvStatisticsDockWidget(IView *parent) :
QDockWidget(parent),
ui(new Ui::IvStatisticsDockWidget)
{
ui->setupUi(this);
iview = parent;
}
IvStatisticsDockWidget::~IvStatisticsDockWidget()
{
delete ui;
}
void IvStatisticsDockWidget::init()
{
QString sigma = QChar(0xc3, 0x03);
int validDigits = 4 - log( fabs(iview->globalMedian)) / log(10.);
if (validDigits < 0) validDigits = 0;
if (iview->displayMode == "FITSmonochrome" || iview->displayMode == "MEMview") {
ui->globalSigmaLeftLabel->setText(sigma + " = ");
ui->localSigmaLeftLabel->setText(sigma + " = ");
ui->globalMedianLabel->setText(QString::number(iview->globalMedian, 'f', validDigits));
ui->globalMeanLabel->setText(QString::number(iview->globalMean, 'f', validDigits));
ui->globalSigmaLabel->setText(QString::number(iview->globalRMS, 'f', validDigits));
ui->localMedianLabel->clear();
ui->localMeanLabel->clear();
ui->localSigmaLabel->clear();
}
if (iview->displayMode == "FITScolor") {
ui->globalMedianLeftLabel->setText("Median R = ");
ui->globalMeanLeftLabel->setText("Median G = ");
ui->globalSigmaLeftLabel->setText("Median B = ");
ui->globalMedianLabel->setText(QString::number(iview->globalMedianR, 'f', validDigits));
ui->globalMeanLabel->setText(QString::number(iview->globalMedianG, 'f', validDigits));
ui->globalSigmaLabel->setText(QString::number(iview->globalMedianB, 'f', validDigits));
ui->localMedianLeftLabel->setText("Median R = ");
ui->localMeanLeftLabel->setText("Median G = ");
ui->localSigmaLeftLabel->setText("Median B = ");
ui->localMedianLabel->clear();
ui->localMeanLabel->clear();
ui->localSigmaLabel->clear();
}
ui->localWindowComboBox->setCurrentText("9x9");
}
void IvStatisticsDockWidget::statisticsSampleReceiver(const QVector<float> &sample)
{
if (!this->isVisible()) return;
localMedian = straightMedian_T(sample);
localMean = meanMask_T(sample, QVector<bool>());
localSigma = 1.486*madMask_T(sample, QVector<bool>(), "ignoreZeroes");
int validDigits = 4 - log( fabs(localMedian)) / log(10.);
if (validDigits < 0) validDigits = 0;
ui->localMedianLabel->setText(QString::number(localMedian, 'f', validDigits));
ui->localMeanLabel->setText(QString::number(localMean, 'f', validDigits));
ui->localSigmaLabel->setText(QString::number(localSigma, 'f', validDigits));
}
void IvStatisticsDockWidget::statisticsSampleColorReceiver(const QVector<float> &sampleR, const QVector<float> &sampleG, const QVector<float> &sampleB)
{
if (!this->isVisible()) return;
localMedianR = straightMedian_T(sampleR);
localMedianG = straightMedian_T(sampleG);
localMedianB = straightMedian_T(sampleB);
/*
float localMeanR = meanMask_T(sampleR, QVector<bool>());
float localMeanG = meanMask_T(sampleG, QVector<bool>());
float localMeanB = meanMask_T(sampleB, QVector<bool>());
float localSigmaR = 1.486*madMask_T(sampleR, QVector<bool>(), "ignoreZeroes");
float localSigmaG = 1.486*madMask_T(sampleG, QVector<bool>(), "ignoreZeroes");
float localSigmaB = 1.486*madMask_T(sampleB, QVector<bool>(), "ignoreZeroes");
*/
int validDigits = 4 - log( fabs(localMedianG)) / log(10.);
if (validDigits < 0) validDigits = 0;
// re-purposing default labels:
ui->localMedianLabel->setText(QString::number(localMedianR, 'f', validDigits));
ui->localMeanLabel->setText(QString::number(localMedianG, 'f', validDigits));
ui->localSigmaLabel->setText(QString::number(localMedianB, 'f', validDigits));
}
void IvStatisticsDockWidget::on_localWindowComboBox_currentIndexChanged(const QString &arg1)
{
statWidth = ui->localWindowComboBox->currentText().split('x').at(0).toInt();
}
| 4,709
|
C++
|
.cc
| 98
| 43.540816
| 151
| 0.715313
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,534,429
|
ivfinderdockwidget.cc
|
schirmermischa_THELI/src/iview/dockwidgets/ivfinderdockwidget.cc
|
/*
Copyright (C) 2019 Mischa Schirmer
This file is part of THELI.
THELI is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program in the LICENSE file.
If not, see https://www.gnu.org/licenses/ .
*/
#include "ivfinderdockwidget.h"
#include "ui_ivfinderdockwidget.h"
#include "../iview.h"
#include "../../query/query.h"
#include <QMessageBox>
// To implement MPC cone search using 'skybot'
// https://astroquery.readthedocs.io/en/latest/imcce/imcce.html
IvFinderDockWidget::IvFinderDockWidget(QWidget *parent) :
QDockWidget(parent),
ui(new Ui::IvFinderDockWidget)
{
ui->setupUi(this);
QIcon star(":/icons/star_icon.png");
ui->targetresolverToolButton->setIcon(star);
QIcon asteroid(":/icons/asteroid_icon.png");
ui->MPCresolverToolButton->setIcon(asteroid);
connect(this, &IvFinderDockWidget::targetResolved, this, &IvFinderDockWidget::targetResolvedReceived);
connect(ui->targetAlphaLineEdit, &QLineEdit::textChanged, this, &IvFinderDockWidget::validate);
connect(ui->targetDeltaLineEdit, &QLineEdit::textChanged, this, &IvFinderDockWidget::validate);
}
IvFinderDockWidget::~IvFinderDockWidget()
{
delete ui;
}
void IvFinderDockWidget::on_targetresolverToolButton_clicked()
{
ui->targetAlphaLineEdit->clear();
ui->targetDeltaLineEdit->clear();
QString targetName = ui->targetNameSiderealLineEdit->text();
if (targetName.isEmpty()) return;
targetName = targetName.simplified().replace(" ", "_");
int verbosity = 0;
Query *query = new Query(&verbosity);
QString check = query->resolveTargetSidereal(targetName);
if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta);
else if (check == "Unresolved") {
QMessageBox::information(this, "THELI: Target unresolved",
"The target " + targetName + " could not be resolved.");
}
else {
// nothing yet.
}
delete query;
query = nullptr;
}
// Query updates RA/DEC fields if successful
void IvFinderDockWidget::targetResolvedReceived(QString alpha, QString delta)
{
ui->targetAlphaLineEdit->setText(alpha);
ui->targetDeltaLineEdit->setText(delta);
}
// Coords were entered manually, then user clicks the "locate" button
void IvFinderDockWidget::on_locatePushButton_clicked()
{
QString alpha = ui->targetAlphaLineEdit->text();
QString delta = ui->targetDeltaLineEdit->text();
if (alpha.isEmpty() || delta.isEmpty()) return;
emit targetResolved(alpha, delta);
}
void IvFinderDockWidget::validate()
{
QRegExp RA( "[0-9.:]+" );
QRegExp DEC( "^[-]{0,1}[0-9.:]+" );
QValidator* validator_ra = new QRegExpValidator( RA, this );
QValidator* validator_dec = new QRegExpValidator( DEC, this );
ui->targetAlphaLineEdit->setValidator( validator_ra );
ui->targetDeltaLineEdit->setValidator( validator_dec );
}
void IvFinderDockWidget::on_clearPushButton_clicked()
{
ui->targetNameSiderealLineEdit->clear();
ui->targetNameNonsiderealLineEdit->clear();
ui->targetAlphaLineEdit->clear();
ui->targetDeltaLineEdit->clear();
emit clearTargetResolved();
}
void IvFinderDockWidget::on_MPCresolverToolButton_clicked()
{
ui->targetAlphaLineEdit->clear();
ui->targetDeltaLineEdit->clear();
QString targetName = ui->targetNameNonsiderealLineEdit->text();
if (targetName.isEmpty()) return;
// targetName = targetName.simplified().replace(" ", "_");
targetName = targetName.simplified();
int verbosity = 0;
Query *query = new Query(&verbosity);
QString check = query->resolveTargetNonsidereal(targetName, dateObs, geoLon, geoLat);
if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta);
else if (check == "Unresolved") {
// Test if there is a blank in the string, and try without the blank:
if (targetName.contains(' ')) {
QString targetOrig = targetName;
targetName.remove(QChar(' '));
QString check = query->resolveTargetNonsidereal(targetName, dateObs, geoLon, geoLat);
if (check == "Resolved") emit targetResolved(query->targetAlpha, query->targetDelta);
else {
QMessageBox::information(this, "THELI: Target unresolved",
"The target names \"" + targetOrig + "\" and " +"\"" + targetName + "\"" + " could not be resolved.");
}
}
else {
QMessageBox::information(this, "THELI: Target unresolved",
"The target name \"" + targetName + "\" could not be resolved.");
}
}
else {
// nothing yet.
}
delete query;
query = nullptr;
}
void IvFinderDockWidget::updateDateObsAndGeo(QString dateobs, float geolon, float geolat)
{
dateObs = dateobs;
geoLon = geolon;
geoLat = geolat;
}
// just show a crosshair at the coordinates, don't resolve anything
void IvFinderDockWidget::bypassResolver()
{
emit targetResolved(ui->targetAlphaLineEdit->text(), ui->targetDeltaLineEdit->text());
}
| 5,555
|
C++
|
.cc
| 136
| 35.904412
| 135
| 0.704267
|
schirmermischa/THELI
| 35
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:44:10 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.