repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
null
ceph-main/src/tools/rbd_mirror/image_deleter/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_DELETER_TYPES_H #define CEPH_RBD_MIRROR_IMAGE_DELETER_TYPES_H #include "include/Context.h" #include "librbd/journal/Policy.h" #include <string> struct utime_t; namespace rbd { namespace mirror { namespace image_deleter { enum ErrorResult { ERROR_RESULT_COMPLETE, ERROR_RESULT_RETRY, ERROR_RESULT_RETRY_IMMEDIATELY }; struct TrashListener { TrashListener() { } TrashListener(const TrashListener&) = delete; TrashListener& operator=(const TrashListener&) = delete; virtual ~TrashListener() { } virtual void handle_trash_image(const std::string& image_id, const ceph::real_clock::time_point& deferment_end_time) = 0; }; struct JournalPolicy : public librbd::journal::Policy { bool append_disabled() const override { return true; } bool journal_disabled() const override { return true; } void allocate_tag_on_lock(Context *on_finish) override { on_finish->complete(0); } }; } // namespace image_deleter } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_IMAGE_DELETER_TYPES_H
1,177
20.418182
70
h
null
ceph-main/src/tools/rbd_mirror/image_map/LoadRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_MAP_LOAD_REQUEST_H #define CEPH_RBD_MIRROR_IMAGE_MAP_LOAD_REQUEST_H #include "cls/rbd/cls_rbd_types.h" #include "include/rados/librados.hpp" class Context; namespace librbd { class ImageCtx; } namespace rbd { namespace mirror { namespace image_map { template<typename ImageCtxT = librbd::ImageCtx> class LoadRequest { public: static LoadRequest *create(librados::IoCtx &ioctx, std::map<std::string, cls::rbd::MirrorImageMap> *image_mapping, Context *on_finish) { return new LoadRequest(ioctx, image_mapping, on_finish); } void send(); private: /** * @verbatim * * <start> * | . . . . . . . . * v v . MAX_RETURN * IMAGE_MAP_LIST. . . . . . . * | * v * MIRROR_IMAGE_LIST * | * v * CLEANUP_IMAGE_MAP * | * v * <finish> * * @endverbatim */ LoadRequest(librados::IoCtx &ioctx, std::map<std::string, cls::rbd::MirrorImageMap> *image_mapping, Context *on_finish); librados::IoCtx &m_ioctx; std::map<std::string, cls::rbd::MirrorImageMap> *m_image_mapping; Context *m_on_finish; std::set<std::string> m_global_image_ids; bufferlist m_out_bl; std::string m_start_after; void image_map_list(); void handle_image_map_list(int r); void mirror_image_list(); void handle_mirror_image_list(int r); void cleanup_image_map(); void finish(int r); }; } // namespace image_map } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_IMAGE_MAP_LOAD_REQUEST_H
1,758
21.551282
92
h
null
ceph-main/src/tools/rbd_mirror/image_map/Policy.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_MAP_POLICY_H #define CEPH_RBD_MIRROR_IMAGE_MAP_POLICY_H #include <map> #include <tuple> #include <boost/optional.hpp> #include "cls/rbd/cls_rbd_types.h" #include "include/rados/librados.hpp" #include "tools/rbd_mirror/image_map/StateTransition.h" #include "tools/rbd_mirror/image_map/Types.h" class Context; namespace rbd { namespace mirror { namespace image_map { class Policy { public: Policy(librados::IoCtx &ioctx); virtual ~Policy() { } // init -- called during initialization void init( const std::map<std::string, cls::rbd::MirrorImageMap> &image_mapping); // lookup an image from the map LookupInfo lookup(const std::string &global_image_id); // add, remove bool add_image(const std::string &global_image_id); bool remove_image(const std::string &global_image_id); // shuffle images when instances are added/removed void add_instances(const InstanceIds &instance_ids, GlobalImageIds* global_image_ids); void remove_instances(const InstanceIds &instance_ids, GlobalImageIds* global_image_ids); ActionType start_action(const std::string &global_image_id); bool finish_action(const std::string &global_image_id, int r); protected: typedef std::map<std::string, std::set<std::string> > InstanceToImageMap; bool is_dead_instance(const std::string instance_id) { ceph_assert(ceph_mutex_is_locked(m_map_lock)); return m_dead_instances.find(instance_id) != m_dead_instances.end(); } bool is_image_shuffling(const std::string &global_image_id); bool can_shuffle_image(const std::string &global_image_id); // map an image (global image id) to an instance virtual std::string do_map(const InstanceToImageMap& map, const std::string &global_image_id) = 0; // shuffle images when instances are added/removed virtual void do_shuffle_add_instances( const InstanceToImageMap& map, size_t image_count, std::set<std::string> *remap_global_image_ids) = 0; private: struct ImageState { std::string instance_id = UNMAPPED_INSTANCE_ID; utime_t mapped_time; ImageState() {} ImageState(const std::string& instance_id, const utime_t& mapped_time) : instance_id(instance_id), mapped_time(mapped_time) { } // active state and action StateTransition::State state = StateTransition::STATE_UNASSOCIATED; StateTransition::Transition transition; // next scheduled state boost::optional<StateTransition::State> next_state = boost::none; }; typedef std::map<std::string, ImageState> ImageStates; librados::IoCtx &m_ioctx; ceph::shared_mutex m_map_lock; // protects m_map InstanceToImageMap m_map; // instance_id -> global_id map ImageStates m_image_states; std::set<std::string> m_dead_instances; bool m_initial_update = true; void remove_instances(const ceph::shared_mutex& lock, const InstanceIds &instance_ids, GlobalImageIds* global_image_ids); bool set_state(ImageState* image_state, StateTransition::State state, bool ignore_current_state); void execute_policy_action(const std::string& global_image_id, ImageState* image_state, StateTransition::PolicyAction policy_action); void map(const std::string& global_image_id, ImageState* image_state); void unmap(const std::string &global_image_id, ImageState* image_state); bool is_state_scheduled(const ImageState& image_state, StateTransition::State state) const; }; } // namespace image_map } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_IMAGE_MAP_POLICY_H
3,826
30.113821
76
h
null
ceph-main/src/tools/rbd_mirror/image_map/SimplePolicy.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_MAP_SIMPLE_POLICY_H #define CEPH_RBD_MIRROR_IMAGE_MAP_SIMPLE_POLICY_H #include "Policy.h" namespace rbd { namespace mirror { namespace image_map { class SimplePolicy : public Policy { public: static SimplePolicy *create(librados::IoCtx &ioctx) { return new SimplePolicy(ioctx); } protected: SimplePolicy(librados::IoCtx &ioctx); std::string do_map(const InstanceToImageMap& map, const std::string &global_image_id) override; void do_shuffle_add_instances( const InstanceToImageMap& map, size_t image_count, std::set<std::string> *remap_global_image_ids) override; private: size_t calc_images_per_instance(const InstanceToImageMap& map, size_t image_count); }; } // namespace image_map } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_IMAGE_MAP_SIMPLE_POLICY_H
1,000
24.025
70
h
null
ceph-main/src/tools/rbd_mirror/image_map/StateTransition.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_MAP_STATE_TRANSITION_H #define CEPH_RBD_MIRROR_IMAGE_MAP_STATE_TRANSITION_H #include "tools/rbd_mirror/image_map/Types.h" #include <boost/optional.hpp> #include <map> namespace rbd { namespace mirror { namespace image_map { class StateTransition { public: enum State { STATE_UNASSOCIATED, STATE_INITIALIZING, STATE_ASSOCIATING, STATE_ASSOCIATED, STATE_SHUFFLING, STATE_DISSOCIATING }; enum PolicyAction { POLICY_ACTION_MAP, POLICY_ACTION_UNMAP, POLICY_ACTION_REMOVE }; struct Transition { // image map action ActionType action_type = ACTION_TYPE_NONE; // policy internal action boost::optional<PolicyAction> start_policy_action; boost::optional<PolicyAction> finish_policy_action; // state machine complete boost::optional<State> finish_state; Transition() { } Transition(ActionType action_type, const boost::optional<PolicyAction>& start_policy_action, const boost::optional<PolicyAction>& finish_policy_action, const boost::optional<State>& finish_state) : action_type(action_type), start_policy_action(start_policy_action), finish_policy_action(finish_policy_action), finish_state(finish_state) { } }; static bool is_idle(State state) { return (state == STATE_UNASSOCIATED || state == STATE_ASSOCIATED); } static void transit(State state, Transition* transition); private: typedef std::pair<State, ActionType> TransitionKey; typedef std::map<TransitionKey, Transition> TransitionTable; // image transition table static const TransitionTable s_transition_table; }; std::ostream &operator<<(std::ostream &os, const StateTransition::State &state); std::ostream &operator<<(std::ostream &os, const StateTransition::PolicyAction &policy_action); } // namespace image_map } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_IMAGE_MAP_STATE_TRANSITION_H
2,103
26.324675
80
h
null
ceph-main/src/tools/rbd_mirror/image_map/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_MAP_TYPES_H #define CEPH_RBD_MIRROR_IMAGE_MAP_TYPES_H #include <iosfwd> #include <map> #include <set> #include <string> #include <boost/variant.hpp> #include "include/buffer.h" #include "include/encoding.h" #include "include/utime.h" #include "tools/rbd_mirror/Types.h" struct Context; namespace ceph { class Formatter; } namespace rbd { namespace mirror { namespace image_map { extern const std::string UNMAPPED_INSTANCE_ID; struct Listener { virtual ~Listener() { } virtual void acquire_image(const std::string &global_image_id, const std::string &instance_id, Context* on_finish) = 0; virtual void release_image(const std::string &global_image_id, const std::string &instance_id, Context* on_finish) = 0; virtual void remove_image(const std::string &mirror_uuid, const std::string &global_image_id, const std::string &instance_id, Context* on_finish) = 0; }; struct LookupInfo { std::string instance_id = UNMAPPED_INSTANCE_ID; utime_t mapped_time; }; enum ActionType { ACTION_TYPE_NONE, ACTION_TYPE_MAP_UPDATE, ACTION_TYPE_MAP_REMOVE, ACTION_TYPE_ACQUIRE, ACTION_TYPE_RELEASE }; typedef std::vector<std::string> InstanceIds; typedef std::set<std::string> GlobalImageIds; typedef std::map<std::string, ActionType> ImageActionTypes; enum PolicyMetaType { POLICY_META_TYPE_NONE = 0, }; struct PolicyMetaNone { static const PolicyMetaType TYPE = POLICY_META_TYPE_NONE; PolicyMetaNone() { } void encode(bufferlist& bl) const { } void decode(__u8 version, bufferlist::const_iterator& it) { } void dump(Formatter *f) const { } }; struct PolicyMetaUnknown { static const PolicyMetaType TYPE = static_cast<PolicyMetaType>(-1); PolicyMetaUnknown() { } void encode(bufferlist& bl) const { ceph_abort(); } void decode(__u8 version, bufferlist::const_iterator& it) { } void dump(Formatter *f) const { } }; typedef boost::variant<PolicyMetaNone, PolicyMetaUnknown> PolicyMeta; struct PolicyData { PolicyData() : policy_meta(PolicyMetaUnknown()) { } PolicyData(const PolicyMeta &policy_meta) : policy_meta(policy_meta) { } PolicyMeta policy_meta; PolicyMetaType get_policy_meta_type() const; void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& it); void dump(Formatter *f) const; static void generate_test_instances(std::list<PolicyData *> &o); }; WRITE_CLASS_ENCODER(PolicyData); std::ostream &operator<<(std::ostream &os, const ActionType &action_type); } // namespace image_map } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_IMAGE_MAP_TYPES_H
2,955
21.564885
74
h
null
ceph-main/src/tools/rbd_mirror/image_map/UpdateRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_MAP_UPDATE_REQUEST_H #define CEPH_RBD_MIRROR_IMAGE_MAP_UPDATE_REQUEST_H #include "cls/rbd/cls_rbd_types.h" #include "include/rados/librados.hpp" class Context; namespace librbd { class ImageCtx; } namespace rbd { namespace mirror { namespace image_map { template<typename ImageCtxT = librbd::ImageCtx> class UpdateRequest { public: // accepts an image map for updation and a collection of // global image ids to purge. static UpdateRequest *create(librados::IoCtx &ioctx, std::map<std::string, cls::rbd::MirrorImageMap> &&update_mapping, std::set<std::string> &&remove_global_image_ids, Context *on_finish) { return new UpdateRequest(ioctx, std::move(update_mapping), std::move(remove_global_image_ids), on_finish); } void send(); private: /** * @verbatim * * <start> * | . . . . . . . . * v v . MAX_UPDATE * UPDATE_IMAGE_MAP. . . . . . . * | * v * <finish> * * @endverbatim */ UpdateRequest(librados::IoCtx &ioctx, std::map<std::string, cls::rbd::MirrorImageMap> &&update_mapping, std::set<std::string> &&remove_global_image_ids, Context *on_finish); librados::IoCtx &m_ioctx; std::map<std::string, cls::rbd::MirrorImageMap> m_update_mapping; std::set<std::string> m_remove_global_image_ids; Context *m_on_finish; void update_image_map(); void handle_update_image_map(int r); void finish(int r); }; } // namespace image_map } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_IMAGE_MAP_UPDATE_REQUEST_H
1,811
26.454545
101
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/BootstrapRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_BOOTSTRAP_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_BOOTSTRAP_REQUEST_H #include "include/int_types.h" #include "include/rados/librados.hpp" #include "common/ceph_mutex.h" #include "common/Timer.h" #include "cls/rbd/cls_rbd_types.h" #include "librbd/mirror/Types.h" #include "tools/rbd_mirror/CancelableRequest.h" #include "tools/rbd_mirror/Types.h" #include <string> class Context; namespace journal { class CacheManagerHandler; } namespace librbd { class ImageCtx; } namespace rbd { namespace mirror { class ProgressContext; template <typename> class ImageSync; template <typename> class InstanceWatcher; struct PoolMetaCache; template <typename> struct Threads; namespace image_replayer { template <typename> class StateBuilder; template <typename ImageCtxT = librbd::ImageCtx> class BootstrapRequest : public CancelableRequest { public: typedef rbd::mirror::ProgressContext ProgressContext; static BootstrapRequest* create( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, librados::IoCtx& remote_io_ctx, InstanceWatcher<ImageCtxT>* instance_watcher, const std::string& global_image_id, const std::string& local_mirror_uuid, const RemotePoolMeta& remote_pool_meta, ::journal::CacheManagerHandler* cache_manager_handler, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>** state_builder, bool* do_resync, Context* on_finish) { return new BootstrapRequest( threads, local_io_ctx, remote_io_ctx, instance_watcher, global_image_id, local_mirror_uuid, remote_pool_meta, cache_manager_handler, pool_meta_cache, progress_ctx, state_builder, do_resync, on_finish); } BootstrapRequest( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, librados::IoCtx& remote_io_ctx, InstanceWatcher<ImageCtxT>* instance_watcher, const std::string& global_image_id, const std::string& local_mirror_uuid, const RemotePoolMeta& remote_pool_meta, ::journal::CacheManagerHandler* cache_manager_handler, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>** state_builder, bool* do_resync, Context* on_finish); bool is_syncing() const; void send() override; void cancel() override; std::string get_local_image_name() const; private: /** * @verbatim * * <start> * | * v (error) * PREPARE_LOCAL_IMAGE * * * * * * * * * * * * * * * * * * * | * * v (error) * * PREPARE_REMOTE_IMAGE * * * * * * * * * * * * * * * * * * * | * * v (error) * * OPEN_REMOTE_IMAGE * * * * * * * * * * * * * * * * * * * * | * * | * * \----> CREATE_LOCAL_IMAGE * * * * * * * * * * * * * * | | ^ * * * | | . * * * | v . (image DNE) * * * \----> OPEN_LOCAL_IMAGE * * * * * * * * * * * * * * * | * * * | * * * v * * * PREPARE_REPLAY * * * * * * * * * * * * * * * * | * * * | * * * v (skip if not needed) * * * IMAGE_SYNC * * * * * * * * * * * * * * * * * * | * * * | * * * /---------/ * * * | * * * v * * * CLOSE_REMOTE_IMAGE < * * * * * * * * * * * * * * * * * * | * * v * * <finish> < * * * * * * * * * * * * * * * * * * * * * * * * * @endverbatim */ Threads<ImageCtxT>* m_threads; librados::IoCtx &m_local_io_ctx; librados::IoCtx &m_remote_io_ctx; InstanceWatcher<ImageCtxT> *m_instance_watcher; std::string m_global_image_id; std::string m_local_mirror_uuid; RemotePoolMeta m_remote_pool_meta; ::journal::CacheManagerHandler *m_cache_manager_handler; PoolMetaCache* m_pool_meta_cache; ProgressContext *m_progress_ctx; StateBuilder<ImageCtxT>** m_state_builder; bool *m_do_resync; mutable ceph::mutex m_lock; bool m_canceled = false; int m_ret_val = 0; std::string m_local_image_name; std::string m_prepare_local_image_name; bool m_syncing = false; ImageSync<ImageCtxT> *m_image_sync = nullptr; void prepare_local_image(); void handle_prepare_local_image(int r); void prepare_remote_image(); void handle_prepare_remote_image(int r); void open_remote_image(); void handle_open_remote_image(int r); void open_local_image(); void handle_open_local_image(int r); void create_local_image(); void handle_create_local_image(int r); void prepare_replay(); void handle_prepare_replay(int r); void image_sync(); void handle_image_sync(int r); void close_remote_image(); void handle_close_remote_image(int r); void update_progress(const std::string &description); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::BootstrapRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_BOOTSTRAP_REQUEST_H
6,112
32.587912
86
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/CreateImageRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_CREATE_IMAGE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_CREATE_IMAGE_REQUEST_H #include "include/int_types.h" #include "include/types.h" #include "include/rados/librados.hpp" #include "cls/rbd/cls_rbd_types.h" #include "librbd/Types.h" #include <string> class Context; namespace librbd { class ImageCtx; } namespace librbd { class ImageOptions; } namespace rbd { namespace mirror { class PoolMetaCache; template <typename> struct Threads; namespace image_replayer { template <typename ImageCtxT = librbd::ImageCtx> class CreateImageRequest { public: static CreateImageRequest *create( Threads<ImageCtxT> *threads, librados::IoCtx &local_io_ctx, const std::string &global_image_id, const std::string &remote_mirror_uuid, const std::string &local_image_name, const std::string &local_image_id, ImageCtxT *remote_image_ctx, PoolMetaCache* pool_meta_cache, cls::rbd::MirrorImageMode mirror_image_mode, Context *on_finish) { return new CreateImageRequest(threads, local_io_ctx, global_image_id, remote_mirror_uuid, local_image_name, local_image_id, remote_image_ctx, pool_meta_cache, mirror_image_mode, on_finish); } CreateImageRequest( Threads<ImageCtxT> *threads, librados::IoCtx &local_io_ctx, const std::string &global_image_id, const std::string &remote_mirror_uuid, const std::string &local_image_name, const std::string &local_image_id, ImageCtxT *remote_image_ctx, PoolMetaCache* pool_meta_cache, cls::rbd::MirrorImageMode mirror_image_mode, Context *on_finish); void send(); private: /** * @verbatim * * <start> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * | * * | (non-clone) * * |\------------> CREATE_IMAGE ---------------------\ * (error) * | | * * | (clone) | * * \-------------> GET_PARENT_GLOBAL_IMAGE_ID * * * | * * * * * | | * * * v | * * GET_LOCAL_PARENT_IMAGE_ID * * * * | * * * * * | | * * * v | * * OPEN_REMOTE_PARENT * * * * * * * | * * * * * | | * * * v | * * CLONE_IMAGE | * * | | * * v | * * CLOSE_REMOTE_PARENT | * * | v * * \------------------------> <finish> < * * * @endverbatim */ Threads<ImageCtxT> *m_threads; librados::IoCtx &m_local_io_ctx; std::string m_global_image_id; std::string m_remote_mirror_uuid; std::string m_local_image_name; std::string m_local_image_id; ImageCtxT *m_remote_image_ctx; PoolMetaCache* m_pool_meta_cache; cls::rbd::MirrorImageMode m_mirror_image_mode; Context *m_on_finish; librados::IoCtx m_remote_parent_io_ctx; ImageCtxT *m_remote_parent_image_ctx = nullptr; cls::rbd::ParentImageSpec m_remote_parent_spec; librados::IoCtx m_local_parent_io_ctx; cls::rbd::ParentImageSpec m_local_parent_spec; bufferlist m_out_bl; std::string m_parent_global_image_id; std::string m_parent_pool_name; int m_ret_val = 0; void create_image(); void handle_create_image(int r); void get_parent_global_image_id(); void handle_get_parent_global_image_id(int r); void get_local_parent_image_id(); void handle_get_local_parent_image_id(int r); void open_remote_parent_image(); void handle_open_remote_parent_image(int r); void clone_image(); void handle_clone_image(int r); void close_remote_parent_image(); void handle_close_remote_parent_image(int r); void error(int r); void finish(int r); int validate_parent(); void populate_image_options(librbd::ImageOptions* image_options); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::CreateImageRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_CREATE_IMAGE_REQUEST_H
4,941
33.082759
88
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/GetMirrorImageIdRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_GET_MIRROR_IMAGE_ID_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_GET_MIRROR_IMAGE_ID_REQUEST_H #include "include/buffer.h" #include "include/rados/librados_fwd.hpp" #include <string> namespace librbd { struct ImageCtx; } struct Context; namespace rbd { namespace mirror { namespace image_replayer { template <typename ImageCtxT = librbd::ImageCtx> class GetMirrorImageIdRequest { public: static GetMirrorImageIdRequest *create(librados::IoCtx &io_ctx, const std::string &global_image_id, std::string *image_id, Context *on_finish) { return new GetMirrorImageIdRequest(io_ctx, global_image_id, image_id, on_finish); } GetMirrorImageIdRequest(librados::IoCtx &io_ctx, const std::string &global_image_id, std::string *image_id, Context *on_finish) : m_io_ctx(io_ctx), m_global_image_id(global_image_id), m_image_id(image_id), m_on_finish(on_finish) { } void send(); private: /** * @verbatim * * <start> * | * v * GET_IMAGE_ID * | * v * <finish> * @endverbatim */ librados::IoCtx &m_io_ctx; std::string m_global_image_id; std::string *m_image_id; Context *m_on_finish; bufferlist m_out_bl; void get_image_id(); void handle_get_image_id(int r); void finish(int r); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::GetMirrorImageIdRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_GET_MIRROR_IMAGE_ID_REQUEST_H
1,873
23.657895
93
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/OpenImageRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_OPEN_IMAGE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_OPEN_IMAGE_REQUEST_H #include "include/int_types.h" #include "librbd/ImageCtx.h" #include <string> class Context; namespace librbd { class ImageCtx; } namespace rbd { namespace mirror { namespace image_replayer { template <typename ImageCtxT = librbd::ImageCtx> class OpenImageRequest { public: static OpenImageRequest* create(librados::IoCtx &io_ctx, ImageCtxT **image_ctx, const std::string &image_id, bool read_only, Context *on_finish) { return new OpenImageRequest(io_ctx, image_ctx, image_id, read_only, on_finish); } OpenImageRequest(librados::IoCtx &io_ctx, ImageCtxT **image_ctx, const std::string &image_id, bool read_only, Context *on_finish); void send(); private: /** * @verbatim * * <start> * | * v * OPEN_IMAGE * | * v * <finish> * * @endverbatim */ librados::IoCtx &m_io_ctx; ImageCtxT **m_image_ctx; std::string m_image_id; bool m_read_only; Context *m_on_finish; void send_open_image(); void handle_open_image(int r); void send_close_image(int r); void handle_close_image(int r); void finish(int r); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::OpenImageRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_OPEN_IMAGE_REQUEST_H
1,692
22.513889
86
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/OpenLocalImageRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_OPEN_LOCAL_IMAGE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_OPEN_LOCAL_IMAGE_REQUEST_H #include "include/int_types.h" #include "cls/rbd/cls_rbd_types.h" #include "librbd/ImageCtx.h" #include "librbd/mirror/Types.h" #include <string> class Context; namespace librbd { class ImageCtx; namespace asio { struct ContextWQ; } } // namespace librbd namespace rbd { namespace mirror { namespace image_replayer { template <typename ImageCtxT = librbd::ImageCtx> class OpenLocalImageRequest { public: static OpenLocalImageRequest* create(librados::IoCtx &local_io_ctx, ImageCtxT **local_image_ctx, const std::string &local_image_id, librbd::asio::ContextWQ *work_queue, Context *on_finish) { return new OpenLocalImageRequest(local_io_ctx, local_image_ctx, local_image_id, work_queue, on_finish); } OpenLocalImageRequest(librados::IoCtx &local_io_ctx, ImageCtxT **local_image_ctx, const std::string &local_image_id, librbd::asio::ContextWQ *work_queue, Context *on_finish); void send(); private: /** * @verbatim * * <start> * | * v * OPEN_IMAGE * * * * * * * * * | * * v * * GET_MIRROR_INFO * * * * * * | * * v (skip if primary) v * LOCK_IMAGE * * * > CLOSE_IMAGE * | | * v | * <finish> <---------------/ * * @endverbatim */ librados::IoCtx &m_local_io_ctx; ImageCtxT **m_local_image_ctx; std::string m_local_image_id; librbd::asio::ContextWQ *m_work_queue; Context *m_on_finish; cls::rbd::MirrorImage m_mirror_image; librbd::mirror::PromotionState m_promotion_state = librbd::mirror::PROMOTION_STATE_NON_PRIMARY; std::string m_primary_mirror_uuid; int m_ret_val = 0; void send_open_image(); void handle_open_image(int r); void send_get_mirror_info(); void handle_get_mirror_info(int r); void send_lock_image(); void handle_lock_image(int r); void send_close_image(int r); void handle_close_image(int r); void finish(int r); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::OpenLocalImageRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_OPEN_LOCAL_IMAGE_REQUEST_H
2,718
26.744898
91
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/PrepareLocalImageRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_PREPARE_LOCAL_IMAGE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_PREPARE_LOCAL_IMAGE_REQUEST_H #include "include/buffer.h" #include "include/rados/librados_fwd.hpp" #include "cls/rbd/cls_rbd_types.h" #include "librbd/mirror/Types.h" #include <string> struct Context; namespace librbd { struct ImageCtx; namespace asio { struct ContextWQ; } } // namespace librbd namespace rbd { namespace mirror { namespace image_replayer { template <typename> class StateBuilder; template <typename ImageCtxT = librbd::ImageCtx> class PrepareLocalImageRequest { public: static PrepareLocalImageRequest *create( librados::IoCtx &io_ctx, const std::string &global_image_id, std::string *local_image_name, StateBuilder<ImageCtxT>** state_builder, librbd::asio::ContextWQ *work_queue, Context *on_finish) { return new PrepareLocalImageRequest(io_ctx, global_image_id, local_image_name, state_builder, work_queue, on_finish); } PrepareLocalImageRequest( librados::IoCtx &io_ctx, const std::string &global_image_id, std::string *local_image_name, StateBuilder<ImageCtxT>** state_builder, librbd::asio::ContextWQ *work_queue, Context *on_finish) : m_io_ctx(io_ctx), m_global_image_id(global_image_id), m_local_image_name(local_image_name), m_state_builder(state_builder), m_work_queue(work_queue), m_on_finish(on_finish) { } void send(); private: /** * @verbatim * * <start> * | * v * GET_LOCAL_IMAGE_ID * | * v * GET_LOCAL_IMAGE_NAME * | * v * GET_MIRROR_INFO * | * | (if the image mirror state is CREATING) * v * TRASH_MOVE * | * v * <finish> * * @endverbatim */ librados::IoCtx &m_io_ctx; std::string m_global_image_id; std::string *m_local_image_name; StateBuilder<ImageCtxT>** m_state_builder; librbd::asio::ContextWQ *m_work_queue; Context *m_on_finish; bufferlist m_out_bl; std::string m_local_image_id; cls::rbd::MirrorImage m_mirror_image; librbd::mirror::PromotionState m_promotion_state; std::string m_primary_mirror_uuid; void get_local_image_id(); void handle_get_local_image_id(int r); void get_local_image_name(); void handle_get_local_image_name(int r); void get_mirror_info(); void handle_get_mirror_info(int r); void move_to_trash(); void handle_move_to_trash(int r); void finish(int r); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::PrepareLocalImageRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_PREPARE_LOCAL_IMAGE_REQUEST_H
2,893
23.948276
94
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/PrepareRemoteImageRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_PREPARE_REMOTE_IMAGE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_PREPARE_REMOTE_IMAGE_REQUEST_H #include "include/buffer_fwd.h" #include "include/rados/librados_fwd.hpp" #include "cls/journal/cls_journal_types.h" #include "cls/rbd/cls_rbd_types.h" #include "librbd/journal/Types.h" #include "librbd/journal/TypeTraits.h" #include "librbd/mirror/Types.h" #include "tools/rbd_mirror/Types.h" #include <string> namespace journal { class Journaler; } namespace journal { struct CacheManagerHandler; } namespace librbd { struct ImageCtx; } namespace librbd { namespace journal { struct MirrorPeerClientMeta; } } struct Context; namespace rbd { namespace mirror { template <typename> struct Threads; namespace image_replayer { template <typename> class StateBuilder; template <typename ImageCtxT = librbd::ImageCtx> class PrepareRemoteImageRequest { public: typedef librbd::journal::TypeTraits<ImageCtxT> TypeTraits; typedef typename TypeTraits::Journaler Journaler; typedef librbd::journal::MirrorPeerClientMeta MirrorPeerClientMeta; static PrepareRemoteImageRequest *create( Threads<ImageCtxT> *threads, librados::IoCtx &local_io_ctx, librados::IoCtx &remote_io_ctx, const std::string &global_image_id, const std::string &local_mirror_uuid, const RemotePoolMeta& remote_pool_meta, ::journal::CacheManagerHandler *cache_manager_handler, StateBuilder<ImageCtxT>** state_builder, Context *on_finish) { return new PrepareRemoteImageRequest(threads, local_io_ctx, remote_io_ctx, global_image_id, local_mirror_uuid, remote_pool_meta, cache_manager_handler, state_builder, on_finish); } PrepareRemoteImageRequest( Threads<ImageCtxT> *threads, librados::IoCtx &local_io_ctx, librados::IoCtx &remote_io_ctx, const std::string &global_image_id, const std::string &local_mirror_uuid, const RemotePoolMeta& remote_pool_meta, ::journal::CacheManagerHandler *cache_manager_handler, StateBuilder<ImageCtxT>** state_builder, Context *on_finish) : m_threads(threads), m_local_io_ctx(local_io_ctx), m_remote_io_ctx(remote_io_ctx), m_global_image_id(global_image_id), m_local_mirror_uuid(local_mirror_uuid), m_remote_pool_meta(remote_pool_meta), m_cache_manager_handler(cache_manager_handler), m_state_builder(state_builder), m_on_finish(on_finish) { } void send(); private: /** * @verbatim * * <start> * | * v * GET_REMOTE_IMAGE_ID * | * v * GET_REMOTE_MIRROR_INFO * | * | (journal) * \-----------> GET_CLIENT * | | * | v (skip if not needed) * | REGISTER_CLIENT * | | * | | * |/----------------/ * | * v * <finish> * * @endverbatim */ Threads<ImageCtxT> *m_threads; librados::IoCtx &m_local_io_ctx; librados::IoCtx &m_remote_io_ctx; std::string m_global_image_id; std::string m_local_mirror_uuid; RemotePoolMeta m_remote_pool_meta; ::journal::CacheManagerHandler *m_cache_manager_handler; StateBuilder<ImageCtxT>** m_state_builder; Context *m_on_finish; bufferlist m_out_bl; std::string m_remote_image_id; cls::rbd::MirrorImage m_mirror_image; librbd::mirror::PromotionState m_promotion_state = librbd::mirror::PROMOTION_STATE_UNKNOWN; std::string m_primary_mirror_uuid; // journal-based mirroring Journaler *m_remote_journaler = nullptr; cls::journal::Client m_client; void get_remote_image_id(); void handle_get_remote_image_id(int r); void get_mirror_info(); void handle_get_mirror_info(int r); void get_client(); void handle_get_client(int r); void register_client(); void handle_register_client(int r); void finalize_journal_state_builder(cls::journal::ClientState client_state, const MirrorPeerClientMeta& client_meta); void finalize_snapshot_state_builder(); void finish(int r); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::PrepareRemoteImageRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_PREPARE_REMOTE_IMAGE_REQUEST_H
4,596
28.850649
95
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/Replayer.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_REPLAYER_H #define RBD_MIRROR_IMAGE_REPLAYER_REPLAYER_H #include <string> struct Context; namespace rbd { namespace mirror { namespace image_replayer { struct Replayer { virtual ~Replayer() {} virtual void destroy() = 0; virtual void init(Context* on_finish) = 0; virtual void shut_down(Context* on_finish) = 0; virtual void flush(Context* on_finish) = 0; virtual bool get_replay_status(std::string* description, Context* on_finish) = 0; virtual bool is_replaying() const = 0; virtual bool is_resync_requested() const = 0; virtual int get_error_code() const = 0; virtual std::string get_error_description() const = 0; }; } // namespace image_replayer } // namespace mirror } // namespace rbd #endif // RBD_MIRROR_IMAGE_REPLAYER_REPLAYER_H
937
22.45
70
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/ReplayerListener.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_REPLAYER_LISTENER_H #define RBD_MIRROR_IMAGE_REPLAYER_REPLAYER_LISTENER_H namespace rbd { namespace mirror { namespace image_replayer { struct ReplayerListener { virtual ~ReplayerListener() {} virtual void handle_notification() = 0; }; } // namespace image_replayer } // namespace mirror } // namespace rbd #endif // RBD_MIRROR_IMAGE_REPLAYER_REPLAYER_LISTENER_H
505
22
70
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/StateBuilder.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_REPLAYER_STATE_BUILDER_H #define CEPH_RBD_MIRROR_IMAGE_REPLAYER_STATE_BUILDER_H #include "include/rados/librados_fwd.hpp" #include "cls/rbd/cls_rbd_types.h" #include "librbd/mirror/Types.h" struct Context; namespace librbd { struct ImageCtx; } namespace rbd { namespace mirror { struct BaseRequest; template <typename> class InstanceWatcher; struct PoolMetaCache; struct ProgressContext; template <typename> class Threads; namespace image_sync { struct SyncPointHandler; } namespace image_replayer { struct Replayer; struct ReplayerListener; template <typename ImageCtxT> class StateBuilder { public: StateBuilder(const StateBuilder&) = delete; StateBuilder& operator=(const StateBuilder&) = delete; virtual ~StateBuilder(); virtual void destroy() { delete this; } virtual void close(Context* on_finish) = 0; virtual bool is_disconnected() const = 0; bool is_local_primary() const; bool is_remote_primary() const; bool is_linked() const; virtual cls::rbd::MirrorImageMode get_mirror_image_mode() const = 0; virtual image_sync::SyncPointHandler* create_sync_point_handler() = 0; void destroy_sync_point_handler(); virtual bool replay_requires_remote_image() const = 0; void close_remote_image(Context* on_finish); virtual BaseRequest* create_local_image_request( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, const std::string& global_image_id, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, Context* on_finish) = 0; virtual BaseRequest* create_prepare_replay_request( const std::string& local_mirror_uuid, ProgressContext* progress_ctx, bool* resync_requested, bool* syncing, Context* on_finish) = 0; virtual Replayer* create_replayer( Threads<ImageCtxT>* threads, InstanceWatcher<ImageCtxT>* instance_watcher, const std::string& local_mirror_uuid, PoolMetaCache* pool_meta_cache, ReplayerListener* replayer_listener) = 0; std::string global_image_id; std::string local_image_id; librbd::mirror::PromotionState local_promotion_state = librbd::mirror::PROMOTION_STATE_UNKNOWN; ImageCtxT* local_image_ctx = nullptr; std::string remote_mirror_uuid; std::string remote_image_id; librbd::mirror::PromotionState remote_promotion_state = librbd::mirror::PROMOTION_STATE_UNKNOWN; ImageCtxT* remote_image_ctx = nullptr; protected: image_sync::SyncPointHandler* m_sync_point_handler = nullptr; StateBuilder(const std::string& global_image_id); void close_local_image(Context* on_finish); private: virtual bool is_linked_impl() const = 0; void handle_close_local_image(int r, Context* on_finish); void handle_close_remote_image(int r, Context* on_finish); }; } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::StateBuilder<librbd::ImageCtx>; #endif // CEPH_RBD_MIRROR_IMAGE_REPLAYER_STATE_BUILDER_H
3,121
26.147826
82
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/TimeRollingMean.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_TIME_ROLLING_MEAN_H #define RBD_MIRROR_IMAGE_REPLAYER_TIME_ROLLING_MEAN_H #include "include/utime.h" #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/rolling_mean.hpp> namespace rbd { namespace mirror { namespace image_replayer { class TimeRollingMean { public: void operator()(uint32_t value); double get_average() const; private: typedef boost::accumulators::accumulator_set< uint64_t, boost::accumulators::stats< boost::accumulators::tag::rolling_mean>> RollingMean; utime_t m_last_time; uint64_t m_sum = 0; RollingMean m_rolling_mean{ boost::accumulators::tag::rolling_window::window_size = 30}; }; } // namespace image_replayer } // namespace mirror } // namespace rbd #endif // RBD_MIRROR_IMAGE_REPLAYER_TIME_ROLLING_MEAN_H
989
23.146341
70
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/Utils.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_UTILS_H #define RBD_MIRROR_IMAGE_REPLAYER_UTILS_H #include "include/rados/librados_fwd.hpp" #include <string> namespace cls { namespace journal { struct Client; } } namespace librbd { namespace journal { struct MirrorPeerClientMeta; } } namespace rbd { namespace mirror { namespace image_replayer { namespace util { std::string compute_image_spec(librados::IoCtx& io_ctx, const std::string& image_name); bool decode_client_meta(const cls::journal::Client& client, librbd::journal::MirrorPeerClientMeta* client_meta); } // namespace util } // namespace image_replayer } // namespace mirror } // namespace rbd #endif // RBD_MIRROR_IMAGE_REPLAYER_UTILS_H
847
27.266667
76
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/journal/CreateLocalImageRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_CREATE_LOCAL_IMAGE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_CREATE_LOCAL_IMAGE_REQUEST_H #include "include/rados/librados_fwd.hpp" #include "tools/rbd_mirror/BaseRequest.h" #include <string> struct Context; namespace journal { class Journaler; } namespace librbd { class ImageCtx; } namespace rbd { namespace mirror { class PoolMetaCache; class ProgressContext; template <typename> struct Threads; namespace image_replayer { namespace journal { template <typename> class StateBuilder; template <typename ImageCtxT> class CreateLocalImageRequest : public BaseRequest { public: typedef rbd::mirror::ProgressContext ProgressContext; static CreateLocalImageRequest* create( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, ImageCtxT* remote_image_ctx, const std::string& global_image_id, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, Context* on_finish) { return new CreateLocalImageRequest(threads, local_io_ctx, remote_image_ctx, global_image_id, pool_meta_cache, progress_ctx, state_builder, on_finish); } CreateLocalImageRequest( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, ImageCtxT* remote_image_ctx, const std::string& global_image_id, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, Context* on_finish) : BaseRequest(on_finish), m_threads(threads), m_local_io_ctx(local_io_ctx), m_remote_image_ctx(remote_image_ctx), m_global_image_id(global_image_id), m_pool_meta_cache(pool_meta_cache), m_progress_ctx(progress_ctx), m_state_builder(state_builder) { } void send(); private: /** * @verbatim * * <start> * | * v * UNREGISTER_CLIENT < * * * * * * * * * | * * v * * REGISTER_CLIENT * * | * * v (id exists) * * CREATE_LOCAL_IMAGE * * * * * * * * * * | * v * <finish> * * @endverbatim */ Threads<ImageCtxT>* m_threads; librados::IoCtx& m_local_io_ctx; ImageCtxT* m_remote_image_ctx; std::string m_global_image_id; PoolMetaCache* m_pool_meta_cache; ProgressContext* m_progress_ctx; StateBuilder<ImageCtxT>* m_state_builder; void unregister_client(); void handle_unregister_client(int r); void register_client(); void handle_register_client(int r); void create_local_image(); void handle_create_local_image(int r); void update_progress(const std::string& description); }; } // namespace journal } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::journal::CreateLocalImageRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_CREATE_LOCAL_IMAGE_REQUEST_H
3,223
26.555556
102
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/journal/EventPreprocessor.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_EVENT_PREPROCESSOR_H #define RBD_MIRROR_IMAGE_REPLAYER_EVENT_PREPROCESSOR_H #include "include/int_types.h" #include "librbd/journal/Types.h" #include "librbd/journal/TypeTraits.h" #include <map> #include <string> #include <boost/variant/static_visitor.hpp> struct Context; namespace journal { class Journaler; } namespace librbd { class ImageCtx; namespace asio { struct ContextWQ; } } // namespace librbd namespace rbd { namespace mirror { namespace image_replayer { namespace journal { template <typename ImageCtxT = librbd::ImageCtx> class EventPreprocessor { public: using Journaler = typename librbd::journal::TypeTraits<ImageCtxT>::Journaler; using EventEntry = librbd::journal::EventEntry; using MirrorPeerClientMeta = librbd::journal::MirrorPeerClientMeta; static EventPreprocessor *create(ImageCtxT &local_image_ctx, Journaler &remote_journaler, const std::string &local_mirror_uuid, MirrorPeerClientMeta *client_meta, librbd::asio::ContextWQ *work_queue) { return new EventPreprocessor(local_image_ctx, remote_journaler, local_mirror_uuid, client_meta, work_queue); } static void destroy(EventPreprocessor* processor) { delete processor; } EventPreprocessor(ImageCtxT &local_image_ctx, Journaler &remote_journaler, const std::string &local_mirror_uuid, MirrorPeerClientMeta *client_meta, librbd::asio::ContextWQ *work_queue); ~EventPreprocessor(); bool is_required(const EventEntry &event_entry); void preprocess(EventEntry *event_entry, Context *on_finish); private: /** * @verbatim * * <start> * | * v (skip if not required) * REFRESH_IMAGE * | * v (skip if not required) * PREPROCESS_EVENT * | * v (skip if not required) * UPDATE_CLIENT * * @endverbatim */ typedef std::map<uint64_t, uint64_t> SnapSeqs; class PreprocessEventVisitor : public boost::static_visitor<int> { public: EventPreprocessor *event_preprocessor; PreprocessEventVisitor(EventPreprocessor *event_preprocessor) : event_preprocessor(event_preprocessor) { } template <typename T> inline int operator()(T&) const { return 0; } inline int operator()(librbd::journal::SnapRenameEvent &event) const { return event_preprocessor->preprocess_snap_rename(event); } }; ImageCtxT &m_local_image_ctx; Journaler &m_remote_journaler; std::string m_local_mirror_uuid; MirrorPeerClientMeta *m_client_meta; librbd::asio::ContextWQ *m_work_queue; bool m_in_progress = false; EventEntry *m_event_entry = nullptr; Context *m_on_finish = nullptr; SnapSeqs m_snap_seqs; bool m_snap_seqs_updated = false; bool prune_snap_map(SnapSeqs *snap_seqs); void refresh_image(); void handle_refresh_image(int r); void preprocess_event(); int preprocess_snap_rename(librbd::journal::SnapRenameEvent &event); void update_client(); void handle_update_client(int r); void finish(int r); }; } // namespace journal } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::journal::EventPreprocessor<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_EVENT_PREPROCESSOR_H
3,562
26.835938
96
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/journal/PrepareReplayRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_PREPARE_REPLAY_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_PREPARE_REPLAY_REQUEST_H #include "include/int_types.h" #include "cls/journal/cls_journal_types.h" #include "librbd/journal/Types.h" #include "librbd/mirror/Types.h" #include "tools/rbd_mirror/BaseRequest.h" #include <list> #include <string> struct Context; namespace librbd { struct ImageCtx; } namespace rbd { namespace mirror { class ProgressContext; namespace image_replayer { namespace journal { template <typename> class StateBuilder; template <typename ImageCtxT> class PrepareReplayRequest : public BaseRequest { public: static PrepareReplayRequest* create( const std::string& local_mirror_uuid, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, bool* resync_requested, bool* syncing, Context* on_finish) { return new PrepareReplayRequest( local_mirror_uuid, progress_ctx, state_builder, resync_requested, syncing, on_finish); } PrepareReplayRequest( const std::string& local_mirror_uuid, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, bool* resync_requested, bool* syncing, Context* on_finish) : BaseRequest(on_finish), m_local_mirror_uuid(local_mirror_uuid), m_progress_ctx(progress_ctx), m_state_builder(state_builder), m_resync_requested(resync_requested), m_syncing(syncing) { } void send() override; private: /** * @verbatim * * <start> * | * v * UPDATE_CLIENT_STATE * | * v * GET_REMOTE_TAG_CLASS * | * v * GET_REMOTE_TAGS * | * v * <finish> * * @endverbatim */ typedef std::list<cls::journal::Tag> Tags; std::string m_local_mirror_uuid; ProgressContext* m_progress_ctx; StateBuilder<ImageCtxT>* m_state_builder; bool* m_resync_requested; bool* m_syncing; uint64_t m_local_tag_tid = 0; librbd::journal::TagData m_local_tag_data; uint64_t m_remote_tag_class = 0; Tags m_remote_tags; cls::journal::Client m_client; void update_client_state(); void handle_update_client_state(int r); void get_remote_tag_class(); void handle_get_remote_tag_class(int r); void get_remote_tags(); void handle_get_remote_tags(int r); void update_progress(const std::string& description); }; } // namespace journal } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::journal::PrepareReplayRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_PREPARE_REPLAY_REQUEST_H
2,768
22.87069
99
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/journal/ReplayStatusFormatter.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_REPLAY_STATUS_FORMATTER_H #define RBD_MIRROR_IMAGE_REPLAYER_REPLAY_STATUS_FORMATTER_H #include "include/Context.h" #include "common/ceph_mutex.h" #include "cls/journal/cls_journal_types.h" #include "librbd/journal/Types.h" #include "librbd/journal/TypeTraits.h" #include "tools/rbd_mirror/image_replayer/TimeRollingMean.h" namespace journal { class Journaler; } namespace librbd { class ImageCtx; } namespace rbd { namespace mirror { namespace image_replayer { namespace journal { template <typename ImageCtxT = librbd::ImageCtx> class ReplayStatusFormatter { public: typedef typename librbd::journal::TypeTraits<ImageCtxT>::Journaler Journaler; static ReplayStatusFormatter* create(Journaler *journaler, const std::string &mirror_uuid) { return new ReplayStatusFormatter(journaler, mirror_uuid); } static void destroy(ReplayStatusFormatter* formatter) { delete formatter; } ReplayStatusFormatter(Journaler *journaler, const std::string &mirror_uuid); void handle_entry_processed(uint32_t bytes); bool get_or_send_update(std::string *description, Context *on_finish); private: Journaler *m_journaler; std::string m_mirror_uuid; ceph::mutex m_lock; Context *m_on_finish = nullptr; cls::journal::ObjectPosition m_master_position; cls::journal::ObjectPosition m_mirror_position; int64_t m_entries_behind_master = 0; cls::journal::Tag m_tag; std::map<uint64_t, librbd::journal::TagData> m_tag_cache; TimeRollingMean m_bytes_per_second; TimeRollingMean m_entries_per_second; bool calculate_behind_master_or_send_update(); void send_update_tag_cache(uint64_t master_tag_tid, uint64_t mirror_tag_tid); void handle_update_tag_cache(uint64_t master_tag_tid, uint64_t mirror_tag_tid, int r); void format(std::string *description); }; } // namespace journal } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::journal::ReplayStatusFormatter<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_REPLAY_STATUS_FORMATTER_H
2,204
30.056338
100
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/journal/Replayer.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_REPLAYER_H #define RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_REPLAYER_H #include "tools/rbd_mirror/image_replayer/Replayer.h" #include "include/utime.h" #include "common/AsyncOpTracker.h" #include "common/ceph_mutex.h" #include "common/RefCountedObj.h" #include "cls/journal/cls_journal_types.h" #include "journal/ReplayEntry.h" #include "librbd/ImageCtx.h" #include "librbd/journal/Types.h" #include "librbd/journal/TypeTraits.h" #include <string> #include <type_traits> namespace journal { class Journaler; } namespace librbd { struct ImageCtx; namespace journal { template <typename I> class Replay; } } // namespace librbd namespace rbd { namespace mirror { template <typename> struct Threads; namespace image_replayer { struct ReplayerListener; namespace journal { template <typename> class EventPreprocessor; template <typename> class ReplayStatusFormatter; template <typename> class StateBuilder; template <typename ImageCtxT> class Replayer : public image_replayer::Replayer { public: typedef typename librbd::journal::TypeTraits<ImageCtxT>::Journaler Journaler; static Replayer* create( Threads<ImageCtxT>* threads, const std::string& local_mirror_uuid, StateBuilder<ImageCtxT>* state_builder, ReplayerListener* replayer_listener) { return new Replayer(threads, local_mirror_uuid, state_builder, replayer_listener); } Replayer( Threads<ImageCtxT>* threads, const std::string& local_mirror_uuid, StateBuilder<ImageCtxT>* state_builder, ReplayerListener* replayer_listener); ~Replayer(); void destroy() override { delete this; } void init(Context* on_finish) override; void shut_down(Context* on_finish) override; void flush(Context* on_finish) override; bool get_replay_status(std::string* description, Context* on_finish) override; bool is_replaying() const override { std::unique_lock locker{m_lock}; return (m_state == STATE_REPLAYING); } bool is_resync_requested() const override { std::unique_lock locker(m_lock); return m_resync_requested; } int get_error_code() const override { std::unique_lock locker(m_lock); return m_error_code; } std::string get_error_description() const override { std::unique_lock locker(m_lock); return m_error_description; } std::string get_image_spec() const { std::unique_lock locker(m_lock); return m_image_spec; } private: /** * @verbatim * * <init> * | * v (error) * INIT_REMOTE_JOURNALER * * * * * * * * * * * * * * * * * * * * | * * v (error) * * START_EXTERNAL_REPLAY * * * * * * * * * * * * * * * * * * * * | * * | /--------------------------------------------\ * * | | | * * v v (asok flush) | * * REPLAYING -------------> LOCAL_REPLAY_FLUSH | * * | \ | | * * | | v | * * | | FLUSH_COMMIT_POSITION | * * | | | | * * | | \--------------------/| * * | | | * * | | (entries available) | * * | \-----------> REPLAY_READY | * * | | | * * | | (skip if not | * * | v needed) (error) * * | REPLAY_FLUSH * * * * * * * * * * * | | | * * * | | (skip if not | * * * | v needed) (error) * * * | GET_REMOTE_TAG * * * * * * * * * * | | | * * * | | (skip if not | * * * | v needed) (error) * * * | ALLOCATE_LOCAL_TAG * * * * * * * * | | | * * * | v (error) * * * | PREPROCESS_ENTRY * * * * * * * * * | | | * * * | v (error) * * * | PROCESS_ENTRY * * * * * * * * * * * | | | * * * | \---------------------/ * * * v (shutdown) * * * REPLAY_COMPLETE < * * * * * * * * * * * * * * * * * * * * * | * * v * * WAIT_FOR_FLUSH * * | * * v * * SHUT_DOWN_LOCAL_JOURNAL_REPLAY * * | * * v * * WAIT_FOR_REPLAY * * | * * v * * CLOSE_LOCAL_IMAGE < * * * * * * * * * * * * * * * * * * * * * | * v (skip if not started) * STOP_REMOTE_JOURNALER_REPLAY * | * v * WAIT_FOR_IN_FLIGHT_OPS * | * v * <shutdown> * * @endverbatim */ typedef typename librbd::journal::TypeTraits<ImageCtxT>::ReplayEntry ReplayEntry; enum State { STATE_INIT, STATE_REPLAYING, STATE_COMPLETE }; struct C_ReplayCommitted; struct RemoteJournalerListener; struct RemoteReplayHandler; struct LocalJournalListener; Threads<ImageCtxT>* m_threads; std::string m_local_mirror_uuid; StateBuilder<ImageCtxT>* m_state_builder; ReplayerListener* m_replayer_listener; mutable ceph::mutex m_lock; std::string m_image_spec; Context* m_on_init_shutdown = nullptr; State m_state = STATE_INIT; int m_error_code = 0; std::string m_error_description; bool m_resync_requested = false; ceph::ref_t<typename std::remove_pointer<decltype(ImageCtxT::journal)>::type> m_local_journal; RemoteJournalerListener* m_remote_listener = nullptr; librbd::journal::Replay<ImageCtxT>* m_local_journal_replay = nullptr; EventPreprocessor<ImageCtxT>* m_event_preprocessor = nullptr; ReplayStatusFormatter<ImageCtxT>* m_replay_status_formatter = nullptr; RemoteReplayHandler* m_remote_replay_handler = nullptr; LocalJournalListener* m_local_journal_listener = nullptr; PerfCounters *m_perf_counters = nullptr; ReplayEntry m_replay_entry; uint64_t m_replay_bytes = 0; utime_t m_replay_start_time; bool m_replay_tag_valid = false; uint64_t m_replay_tag_tid = 0; cls::journal::Tag m_replay_tag; librbd::journal::TagData m_replay_tag_data; librbd::journal::EventEntry m_event_entry; AsyncOpTracker m_flush_tracker; AsyncOpTracker m_event_replay_tracker; Context *m_delayed_preprocess_task = nullptr; AsyncOpTracker m_in_flight_op_tracker; Context *m_flush_local_replay_task = nullptr; void handle_remote_journal_metadata_updated(); void schedule_flush_local_replay_task(); void cancel_flush_local_replay_task(); void handle_flush_local_replay_task(int r); void flush_local_replay(Context* on_flush); void handle_flush_local_replay(Context* on_flush, int r); void flush_commit_position(Context* on_flush); void handle_flush_commit_position(Context* on_flush, int r); void init_remote_journaler(); void handle_init_remote_journaler(int r); void start_external_replay(std::unique_lock<ceph::mutex>& locker); void handle_start_external_replay(int r); bool add_local_journal_listener(std::unique_lock<ceph::mutex>& locker); bool notify_init_complete(std::unique_lock<ceph::mutex>& locker); void wait_for_flush(); void handle_wait_for_flush(int r); void shut_down_local_journal_replay(); void handle_shut_down_local_journal_replay(int r); void wait_for_event_replay(); void handle_wait_for_event_replay(int r); void close_local_image(); void handle_close_local_image(int r); void stop_remote_journaler_replay(); void handle_stop_remote_journaler_replay(int r); void wait_for_in_flight_ops(); void handle_wait_for_in_flight_ops(int r); void replay_flush(); void handle_replay_flush_shut_down(int r); void handle_replay_flush(int r); void get_remote_tag(); void handle_get_remote_tag(int r); void allocate_local_tag(); void handle_allocate_local_tag(int r); void handle_replay_error(int r, const std::string &error); bool is_replay_complete() const; bool is_replay_complete(const std::unique_lock<ceph::mutex>& locker) const; void handle_replay_complete(int r, const std::string &error_desc); void handle_replay_complete(const std::unique_lock<ceph::mutex>&, int r, const std::string &error_desc); void handle_replay_ready(); void handle_replay_ready(std::unique_lock<ceph::mutex>& locker); void preprocess_entry(); void handle_delayed_preprocess_task(int r); void handle_preprocess_entry_ready(int r); void handle_preprocess_entry_safe(int r); void process_entry(); void handle_process_entry_ready(int r); void handle_process_entry_safe(const ReplayEntry& replay_entry, uint64_t relay_bytes, const utime_t &replay_start_time, int r); void handle_resync_image(); void notify_status_updated(); void cancel_delayed_preprocess_task(); int validate_remote_client_state( const cls::journal::Client& remote_client, librbd::journal::MirrorPeerClientMeta* remote_client_meta, bool* resync_requested, std::string* error); void register_perf_counters(); void unregister_perf_counters(); }; } // namespace journal } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::journal::Replayer<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_REPLAYER_H
10,900
32.645062
87
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/journal/StateBuilder.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_STATE_BUILDER_H #define CEPH_RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_STATE_BUILDER_H #include "tools/rbd_mirror/image_replayer/StateBuilder.h" #include "cls/journal/cls_journal_types.h" #include "librbd/journal/Types.h" #include "librbd/journal/TypeTraits.h" #include <string> struct Context; namespace librbd { struct ImageCtx; } namespace rbd { namespace mirror { namespace image_replayer { namespace journal { template <typename> class SyncPointHandler; template <typename ImageCtxT> class StateBuilder : public image_replayer::StateBuilder<ImageCtxT> { public: typedef librbd::journal::TypeTraits<ImageCtxT> TypeTraits; typedef typename TypeTraits::Journaler Journaler; static StateBuilder* create(const std::string& global_image_id) { return new StateBuilder(global_image_id); } StateBuilder(const std::string& global_image_id); ~StateBuilder() override; void close(Context* on_finish) override; bool is_disconnected() const override; cls::rbd::MirrorImageMode get_mirror_image_mode() const override; image_sync::SyncPointHandler* create_sync_point_handler() override; bool replay_requires_remote_image() const override { return false; } BaseRequest* create_local_image_request( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, const std::string& global_image_id, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, Context* on_finish) override; BaseRequest* create_prepare_replay_request( const std::string& local_mirror_uuid, ProgressContext* progress_ctx, bool* resync_requested, bool* syncing, Context* on_finish) override; image_replayer::Replayer* create_replayer( Threads<ImageCtxT>* threads, InstanceWatcher<ImageCtxT>* instance_watcher, const std::string& local_mirror_uuid, PoolMetaCache* pool_meta_cache, ReplayerListener* replayer_listener) override; std::string local_primary_mirror_uuid; Journaler* remote_journaler = nullptr; cls::journal::ClientState remote_client_state = cls::journal::CLIENT_STATE_CONNECTED; librbd::journal::MirrorPeerClientMeta remote_client_meta; SyncPointHandler<ImageCtxT>* sync_point_handler = nullptr; private: bool is_linked_impl() const override; void shut_down_remote_journaler(Context* on_finish); void handle_shut_down_remote_journaler(int r, Context* on_finish); }; } // namespace journal } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::journal::StateBuilder<librbd::ImageCtx>; #endif // CEPH_RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_STATE_BUILDER_H
2,810
28.589474
91
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/journal/SyncPointHandler.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_SYNC_POINT_HANDLER_H #define RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_SYNC_POINT_HANDLER_H #include "tools/rbd_mirror/image_sync/Types.h" #include "librbd/journal/Types.h" struct Context; namespace librbd { struct ImageCtx; } namespace rbd { namespace mirror { namespace image_replayer { namespace journal { template <typename> class StateBuilder; template <typename ImageCtxT> class SyncPointHandler : public image_sync::SyncPointHandler { public: using SyncPoint = image_sync::SyncPoint; using SyncPoints = image_sync::SyncPoints; static SyncPointHandler* create(StateBuilder<ImageCtxT>* state_builder) { return new SyncPointHandler(state_builder); } SyncPointHandler(StateBuilder<ImageCtxT>* state_builder); SyncPoints get_sync_points() const override; librbd::SnapSeqs get_snap_seqs() const override; void update_sync_points(const librbd::SnapSeqs& snap_seqs, const SyncPoints& sync_points, bool sync_complete, Context* on_finish) override; private: StateBuilder<ImageCtxT>* m_state_builder; librbd::journal::MirrorPeerClientMeta m_client_meta_copy; void handle_update_sync_points(int r, Context* on_finish); }; } // namespace journal } // namespace image_sync } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::journal::SyncPointHandler<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_SYNC_POINT_HANDLER_H
1,620
27.946429
95
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/snapshot/ApplyImageStateRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_APPLY_IMAGE_STATE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_APPLY_IMAGE_STATE_REQUEST_H #include "common/ceph_mutex.h" #include "librbd/mirror/snapshot/Types.h" #include <map> #include <string> struct Context; namespace librbd { struct ImageCtx; } // namespace librbd namespace rbd { namespace mirror { namespace image_replayer { namespace snapshot { template <typename> class EventPreprocessor; template <typename> class ReplayStatusFormatter; template <typename> class StateBuilder; template <typename ImageCtxT> class ApplyImageStateRequest { public: static ApplyImageStateRequest* create( const std::string& local_mirror_uuid, const std::string& remote_mirror_uuid, ImageCtxT* local_image_ctx, ImageCtxT* remote_image_ctx, librbd::mirror::snapshot::ImageState image_state, Context* on_finish) { return new ApplyImageStateRequest(local_mirror_uuid, remote_mirror_uuid, local_image_ctx, remote_image_ctx, image_state, on_finish); } ApplyImageStateRequest( const std::string& local_mirror_uuid, const std::string& remote_mirror_uuid, ImageCtxT* local_image_ctx, ImageCtxT* remote_image_ctx, librbd::mirror::snapshot::ImageState image_state, Context* on_finish); void send(); private: /** * @verbatim * * <start> * | * v * RENAME_IMAGE * | * | /---------\ * | | | * v v | * UPDATE_FEATURES -----/ * | * v * GET_IMAGE_META * | * | /---------\ * | | | * v v | * UPDATE_IMAGE_META ---/ * | * | /---------\ * | | | * v v | * UNPROTECT_SNAPSHOT | * | | * v | * REMOVE_SNAPSHOT | * | | * v | * PROTECT_SNAPSHOT | * | | * v | * RENAME_SNAPSHOT -----/ * | * v * SET_SNAPSHOT_LIMIT * | * v * <finish> * * @endverbatim */ std::string m_local_mirror_uuid; std::string m_remote_mirror_uuid; ImageCtxT* m_local_image_ctx; ImageCtxT* m_remote_image_ctx; librbd::mirror::snapshot::ImageState m_image_state; Context* m_on_finish; std::map<uint64_t, uint64_t> m_local_to_remote_snap_ids; uint64_t m_features = 0; std::map<std::string, bufferlist> m_metadata; uint64_t m_prev_snap_id = 0; std::string m_snap_name; void rename_image(); void handle_rename_image(int r); void update_features(); void handle_update_features(int r); void get_image_meta(); void handle_get_image_meta(int r); void update_image_meta(); void handle_update_image_meta(int r); void unprotect_snapshot(); void handle_unprotect_snapshot(int r); void remove_snapshot(); void handle_remove_snapshot(int r); void protect_snapshot(); void handle_protect_snapshot(int r); void rename_snapshot(); void handle_rename_snapshot(int r); void set_snapshot_limit(); void handle_set_snapshot_limit(int r); void finish(int r); uint64_t compute_remote_snap_id(uint64_t snap_id); void compute_local_to_remote_snap_ids(); }; } // namespace snapshot } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::snapshot::ApplyImageStateRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_APPLY_IMAGE_STATE_REQUEST_H
3,754
23.070513
102
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/snapshot/CreateLocalImageRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_CREATE_LOCAL_IMAGE_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_CREATE_LOCAL_IMAGE_REQUEST_H #include "include/rados/librados_fwd.hpp" #include "tools/rbd_mirror/BaseRequest.h" #include <string> struct Context; namespace librbd { class ImageCtx; } namespace rbd { namespace mirror { class PoolMetaCache; class ProgressContext; template <typename> struct Threads; namespace image_replayer { namespace snapshot { template <typename> class StateBuilder; template <typename ImageCtxT> class CreateLocalImageRequest : public BaseRequest { public: typedef rbd::mirror::ProgressContext ProgressContext; static CreateLocalImageRequest* create( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, ImageCtxT* remote_image_ctx, const std::string& global_image_id, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, Context* on_finish) { return new CreateLocalImageRequest(threads, local_io_ctx, remote_image_ctx, global_image_id, pool_meta_cache, progress_ctx, state_builder, on_finish); } CreateLocalImageRequest( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, ImageCtxT* remote_image_ctx, const std::string& global_image_id, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, Context* on_finish) : BaseRequest(on_finish), m_threads(threads), m_local_io_ctx(local_io_ctx), m_remote_image_ctx(remote_image_ctx), m_global_image_id(global_image_id), m_pool_meta_cache(pool_meta_cache), m_progress_ctx(progress_ctx), m_state_builder(state_builder) { } void send(); private: /** * @verbatim * * <start> * | * v * DISABLE_MIRROR_IMAGE < * * * * * * * | * * v * * REMOVE_MIRROR_IMAGE * * | * * v * * ADD_MIRROR_IMAGE * * | * * v (id exists) * * CREATE_LOCAL_IMAGE * * * * * * * * * | * v * <finish> * * @endverbatim */ Threads<ImageCtxT>* m_threads; librados::IoCtx& m_local_io_ctx; ImageCtxT* m_remote_image_ctx; std::string m_global_image_id; PoolMetaCache* m_pool_meta_cache; ProgressContext* m_progress_ctx; StateBuilder<ImageCtxT>* m_state_builder; void disable_mirror_image(); void handle_disable_mirror_image(int r); void remove_mirror_image(); void handle_remove_mirror_image(int r); void add_mirror_image(); void handle_add_mirror_image(int r); void create_local_image(); void handle_create_local_image(int r); void update_progress(const std::string& description); }; } // namespace snapshot } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::snapshot::CreateLocalImageRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_CREATE_LOCAL_IMAGE_REQUEST_H
3,377
26.688525
103
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/snapshot/PrepareReplayRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_PREPARE_REPLAY_REQUEST_H #define RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_PREPARE_REPLAY_REQUEST_H #include "include/int_types.h" #include "librbd/mirror/Types.h" #include "tools/rbd_mirror/BaseRequest.h" #include <list> #include <string> struct Context; namespace librbd { struct ImageCtx; } namespace rbd { namespace mirror { class ProgressContext; namespace image_replayer { namespace snapshot { template <typename> class StateBuilder; template <typename ImageCtxT> class PrepareReplayRequest : public BaseRequest { public: static PrepareReplayRequest* create( const std::string& local_mirror_uuid, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, bool* resync_requested, bool* syncing, Context* on_finish) { return new PrepareReplayRequest( local_mirror_uuid, progress_ctx, state_builder, resync_requested, syncing, on_finish); } PrepareReplayRequest( const std::string& local_mirror_uuid, ProgressContext* progress_ctx, StateBuilder<ImageCtxT>* state_builder, bool* resync_requested, bool* syncing, Context* on_finish) : BaseRequest(on_finish), m_local_mirror_uuid(local_mirror_uuid), m_progress_ctx(progress_ctx), m_state_builder(state_builder), m_resync_requested(resync_requested), m_syncing(syncing) { } void send() override; private: // TODO /** * @verbatim * * <start> * | * v * LOAD_LOCAL_IMAGE_META * | * v * <finish> * * @endverbatim */ std::string m_local_mirror_uuid; ProgressContext* m_progress_ctx; StateBuilder<ImageCtxT>* m_state_builder; bool* m_resync_requested; bool* m_syncing; void load_local_image_meta(); void handle_load_local_image_meta(int r); }; } // namespace snapshot } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::snapshot::PrepareReplayRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_JOURNAL_PREPARE_REPLAY_REQUEST_H
2,212
22.795699
100
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/snapshot/Replayer.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_REPLAYER_H #define RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_REPLAYER_H #include "tools/rbd_mirror/image_replayer/Replayer.h" #include "common/ceph_mutex.h" #include "common/AsyncOpTracker.h" #include "cls/rbd/cls_rbd_types.h" #include "librbd/mirror/snapshot/Types.h" #include "tools/rbd_mirror/image_replayer/TimeRollingMean.h" #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/rolling_mean.hpp> #include <string> #include <type_traits> namespace librbd { struct ImageCtx; namespace snapshot { template <typename I> class Replay; } } // namespace librbd namespace rbd { namespace mirror { template <typename> struct InstanceWatcher; class PoolMetaCache; template <typename> struct Threads; namespace image_replayer { struct ReplayerListener; namespace snapshot { template <typename> class EventPreprocessor; template <typename> class ReplayStatusFormatter; template <typename> class StateBuilder; template <typename ImageCtxT> class Replayer : public image_replayer::Replayer { public: static Replayer* create( Threads<ImageCtxT>* threads, InstanceWatcher<ImageCtxT>* instance_watcher, const std::string& local_mirror_uuid, PoolMetaCache* pool_meta_cache, StateBuilder<ImageCtxT>* state_builder, ReplayerListener* replayer_listener) { return new Replayer(threads, instance_watcher, local_mirror_uuid, pool_meta_cache, state_builder, replayer_listener); } Replayer( Threads<ImageCtxT>* threads, InstanceWatcher<ImageCtxT>* instance_watcher, const std::string& local_mirror_uuid, PoolMetaCache* pool_meta_cache, StateBuilder<ImageCtxT>* state_builder, ReplayerListener* replayer_listener); ~Replayer(); void destroy() override { delete this; } void init(Context* on_finish) override; void shut_down(Context* on_finish) override; void flush(Context* on_finish) override; bool get_replay_status(std::string* description, Context* on_finish) override; bool is_replaying() const override { std::unique_lock locker{m_lock}; return (m_state == STATE_REPLAYING || m_state == STATE_IDLE); } bool is_resync_requested() const override { std::unique_lock locker{m_lock}; return m_resync_requested; } int get_error_code() const override { std::unique_lock locker(m_lock); return m_error_code; } std::string get_error_description() const override { std::unique_lock locker(m_lock); return m_error_description; } std::string get_image_spec() const { std::unique_lock locker(m_lock); return m_image_spec; } private: /** * @verbatim * * <init> * | * v * REGISTER_LOCAL_UPDATE_WATCHER * | * v * REGISTER_REMOTE_UPDATE_WATCHER * | * v * LOAD_LOCAL_IMAGE_META <----------------------------\ * | | * v (skip if not needed) | * REFRESH_LOCAL_IMAGE | * | | * v (skip if not needed) | * REFRESH_REMOTE_IMAGE | * | | * | (unused non-primary snapshot) | * |\--------------> PRUNE_NON_PRIMARY_SNAPSHOT---/| * | | * | (interrupted sync) | * |\--------------> GET_LOCAL_IMAGE_STATE ------\ | * | | | * | (new snapshot) | | * |\--------------> COPY_SNAPSHOTS | | * | | | | * | v | | * | GET_REMOTE_IMAGE_STATE | | * | | | | * | v | | * | CREATE_NON_PRIMARY_SNAPSHOT | | * | | | | * | v (skip if not needed)| | * | UPDATE_MIRROR_IMAGE_STATE | | * | | | | * | |/--------------------/ | * | | | * | v | * | REQUEST_SYNC | * | | | * | v | * | COPY_IMAGE | * | | | * | v | * | APPLY_IMAGE_STATE | * | | | * | v | * | UPDATE_NON_PRIMARY_SNAPSHOT | * | | | * | v | * | NOTIFY_IMAGE_UPDATE | * | | | * | (interrupted unlink) v | * |\--------------> UNLINK_PEER | * | | | * | v | * | NOTIFY_LISTENER | * | | | * | \----------------------/| * | | * | (remote demoted) | * \---------------> NOTIFY_LISTENER | * | | | * |/--------------------/ | * | | * | (update notification) | * <idle> --------------------------------------------/ * | * v * <shut down> * | * v * UNREGISTER_REMOTE_UPDATE_WATCHER * | * v * UNREGISTER_LOCAL_UPDATE_WATCHER * | * v * WAIT_FOR_IN_FLIGHT_OPS * | * v * <finish> * * @endverbatim */ enum State { STATE_INIT, STATE_REPLAYING, STATE_IDLE, STATE_COMPLETE }; struct C_UpdateWatchCtx; struct DeepCopyHandler; Threads<ImageCtxT>* m_threads; InstanceWatcher<ImageCtxT>* m_instance_watcher; std::string m_local_mirror_uuid; PoolMetaCache* m_pool_meta_cache; StateBuilder<ImageCtxT>* m_state_builder; ReplayerListener* m_replayer_listener; mutable ceph::mutex m_lock; State m_state = STATE_INIT; std::string m_image_spec; Context* m_on_init_shutdown = nullptr; bool m_resync_requested = false; int m_error_code = 0; std::string m_error_description; C_UpdateWatchCtx* m_update_watch_ctx = nullptr; uint64_t m_local_update_watcher_handle = 0; uint64_t m_remote_update_watcher_handle = 0; bool m_image_updated = false; AsyncOpTracker m_in_flight_op_tracker; uint64_t m_local_snap_id_start = 0; uint64_t m_local_snap_id_end = CEPH_NOSNAP; cls::rbd::MirrorSnapshotNamespace m_local_mirror_snap_ns; uint64_t m_local_object_count = 0; std::string m_remote_mirror_peer_uuid; uint64_t m_remote_snap_id_start = 0; uint64_t m_remote_snap_id_end = CEPH_NOSNAP; cls::rbd::MirrorSnapshotNamespace m_remote_mirror_snap_ns; librbd::mirror::snapshot::ImageState m_image_state; DeepCopyHandler* m_deep_copy_handler = nullptr; TimeRollingMean m_bytes_per_second; uint64_t m_last_snapshot_sync_seconds = 0; uint64_t m_snapshot_bytes = 0; uint64_t m_last_snapshot_bytes = 0; boost::accumulators::accumulator_set< uint64_t, boost::accumulators::stats< boost::accumulators::tag::rolling_mean>> m_bytes_per_snapshot{ boost::accumulators::tag::rolling_window::window_size = 2}; utime_t m_snapshot_replay_start; uint32_t m_pending_snapshots = 0; bool m_remote_image_updated = false; bool m_updating_sync_point = false; bool m_sync_in_progress = false; PerfCounters *m_perf_counters = nullptr; void load_local_image_meta(); void handle_load_local_image_meta(int r); void refresh_local_image(); void handle_refresh_local_image(int r); void refresh_remote_image(); void handle_refresh_remote_image(int r); void scan_local_mirror_snapshots(std::unique_lock<ceph::mutex>* locker); void scan_remote_mirror_snapshots(std::unique_lock<ceph::mutex>* locker); void prune_non_primary_snapshot(uint64_t snap_id); void handle_prune_non_primary_snapshot(int r); void copy_snapshots(); void handle_copy_snapshots(int r); void get_remote_image_state(); void handle_get_remote_image_state(int r); void get_local_image_state(); void handle_get_local_image_state(int r); void create_non_primary_snapshot(); void handle_create_non_primary_snapshot(int r); void update_mirror_image_state(); void handle_update_mirror_image_state(int r); void request_sync(); void handle_request_sync(int r); void copy_image(); void handle_copy_image(int r); void handle_copy_image_progress(uint64_t object_number, uint64_t object_count); void handle_copy_image_read(uint64_t bytes_read); void apply_image_state(); void handle_apply_image_state(int r); void update_non_primary_snapshot(bool complete); void handle_update_non_primary_snapshot(bool complete, int r); void notify_image_update(); void handle_notify_image_update(int r); void unlink_peer(uint64_t remote_snap_id); void handle_unlink_peer(int r); void finish_sync(); void register_local_update_watcher(); void handle_register_local_update_watcher(int r); void register_remote_update_watcher(); void handle_register_remote_update_watcher(int r); void unregister_remote_update_watcher(); void handle_unregister_remote_update_watcher(int r); void unregister_local_update_watcher(); void handle_unregister_local_update_watcher(int r); void wait_for_in_flight_ops(); void handle_wait_for_in_flight_ops(int r); void handle_image_update_notify(); void handle_replay_complete(int r, const std::string& description); void handle_replay_complete(std::unique_lock<ceph::mutex>* locker, int r, const std::string& description); void notify_status_updated(); bool is_replay_interrupted(); bool is_replay_interrupted(std::unique_lock<ceph::mutex>* lock); void register_perf_counters(); void unregister_perf_counters(); }; } // namespace snapshot } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::snapshot::Replayer<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_REPLAYER_H
11,210
31.031429
88
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/snapshot/StateBuilder.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_STATE_BUILDER_H #define CEPH_RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_STATE_BUILDER_H #include "tools/rbd_mirror/image_replayer/StateBuilder.h" #include <string> struct Context; namespace librbd { struct ImageCtx; namespace mirror { namespace snapshot { template <typename> class ImageMeta; } // namespace snapshot } // namespace mirror } // namespace librbd namespace rbd { namespace mirror { namespace image_replayer { namespace snapshot { template <typename> class SyncPointHandler; template <typename ImageCtxT> class StateBuilder : public image_replayer::StateBuilder<ImageCtxT> { public: static StateBuilder* create(const std::string& global_image_id) { return new StateBuilder(global_image_id); } StateBuilder(const std::string& global_image_id); ~StateBuilder() override; void close(Context* on_finish) override; bool is_disconnected() const override; cls::rbd::MirrorImageMode get_mirror_image_mode() const override; image_sync::SyncPointHandler* create_sync_point_handler() override; bool replay_requires_remote_image() const override { return true; } BaseRequest* create_local_image_request( Threads<ImageCtxT>* threads, librados::IoCtx& local_io_ctx, const std::string& global_image_id, PoolMetaCache* pool_meta_cache, ProgressContext* progress_ctx, Context* on_finish) override; BaseRequest* create_prepare_replay_request( const std::string& local_mirror_uuid, ProgressContext* progress_ctx, bool* resync_requested, bool* syncing, Context* on_finish) override; image_replayer::Replayer* create_replayer( Threads<ImageCtxT>* threads, InstanceWatcher<ImageCtxT>* instance_watcher, const std::string& local_mirror_uuid, PoolMetaCache* pool_meta_cache, ReplayerListener* replayer_listener) override; SyncPointHandler<ImageCtxT>* sync_point_handler = nullptr; std::string remote_mirror_peer_uuid; librbd::mirror::snapshot::ImageMeta<ImageCtxT>* local_image_meta = nullptr; private: bool is_linked_impl() const override; }; } // namespace snapshot } // namespace image_replayer } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_replayer::snapshot::StateBuilder<librbd::ImageCtx>; #endif // CEPH_RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_STATE_BUILDER_H
2,490
25.5
92
h
null
ceph-main/src/tools/rbd_mirror/image_replayer/snapshot/Utils.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_UTILS_H #define RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_UTILS_H #include "include/int_types.h" #include "include/rados/librados.hpp" #include "common/ceph_mutex.h" #include "librbd/Types.h" #include <map> namespace rbd { namespace mirror { namespace image_replayer { namespace snapshot { namespace util { uint64_t compute_remote_snap_id( const ceph::shared_mutex& local_image_lock, const std::map<librados::snap_t, librbd::SnapInfo>& local_snap_infos, uint64_t local_snap_id, const std::string& remote_mirror_uuid); } // namespace util } // namespace snapshot } // namespace image_replayer } // namespace mirror } // namespace rbd #endif // RBD_MIRROR_IMAGE_REPLAYER_SNAPSHOT_UTILS_H
838
26.064516
73
h
null
ceph-main/src/tools/rbd_mirror/image_sync/SyncPointCreateRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_SYNC_SYNC_POINT_CREATE_REQUEST_H #define RBD_MIRROR_IMAGE_SYNC_SYNC_POINT_CREATE_REQUEST_H #include "librbd/internal.h" #include "Types.h" #include <string> class Context; namespace journal { class Journaler; } namespace librbd { class ImageCtx; } namespace librbd { namespace journal { struct MirrorPeerClientMeta; } } namespace rbd { namespace mirror { namespace image_sync { template <typename ImageCtxT = librbd::ImageCtx> class SyncPointCreateRequest { public: static SyncPointCreateRequest* create( ImageCtxT *remote_image_ctx, const std::string &local_mirror_uuid, SyncPointHandler* sync_point_handler, Context *on_finish) { return new SyncPointCreateRequest(remote_image_ctx, local_mirror_uuid, sync_point_handler, on_finish); } SyncPointCreateRequest( ImageCtxT *remote_image_ctx, const std::string &local_mirror_uuid, SyncPointHandler* sync_point_handler, Context *on_finish); void send(); private: /** * @verbatim * * <start> * | * v * UPDATE_SYNC_POINTS < . . * | . * v . * REFRESH_IMAGE . * | . (repeat on EEXIST) * v . * CREATE_SNAP . . . . . . * | * v * REFRESH_IMAGE * | * v * <finish> * * @endverbatim */ ImageCtxT *m_remote_image_ctx; std::string m_local_mirror_uuid; SyncPointHandler* m_sync_point_handler; Context *m_on_finish; SyncPoints m_sync_points_copy; librbd::NoOpProgressContext m_prog_ctx; void send_update_sync_points(); void handle_update_sync_points(int r); void send_refresh_image(); void handle_refresh_image(int r); void send_create_snap(); void handle_create_snap(int r); void send_final_refresh_image(); void handle_final_refresh_image(int r); void finish(int r); }; } // namespace image_sync } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_sync::SyncPointCreateRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_SYNC_SYNC_POINT_CREATE_REQUEST_H
2,266
23.117021
88
h
null
ceph-main/src/tools/rbd_mirror/image_sync/SyncPointPruneRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_SYNC_SYNC_POINT_PRUNE_REQUEST_H #define RBD_MIRROR_IMAGE_SYNC_SYNC_POINT_PRUNE_REQUEST_H #include "tools/rbd_mirror/image_sync/Types.h" #include <list> #include <string> class Context; namespace journal { class Journaler; } namespace librbd { class ImageCtx; } namespace librbd { namespace journal { struct MirrorPeerClientMeta; } } namespace rbd { namespace mirror { namespace image_sync { template <typename ImageCtxT = librbd::ImageCtx> class SyncPointPruneRequest { public: static SyncPointPruneRequest* create( ImageCtxT *remote_image_ctx, bool sync_complete, SyncPointHandler* sync_point_handler, Context *on_finish) { return new SyncPointPruneRequest(remote_image_ctx, sync_complete, sync_point_handler, on_finish); } SyncPointPruneRequest( ImageCtxT *remote_image_ctx, bool sync_complete, SyncPointHandler* sync_point_handler, Context *on_finish); void send(); private: /** * @verbatim * * <start> * | * | . . . . . * | . . * v v . (repeat if from snap * REMOVE_SNAP . . . unused by other sync) * | * v * REFRESH_IMAGE * | * v * UPDATE_CLIENT * | * v * <finish> * * @endverbatim */ ImageCtxT *m_remote_image_ctx; bool m_sync_complete; SyncPointHandler* m_sync_point_handler; Context *m_on_finish; SyncPoints m_sync_points_copy; std::list<std::string> m_snap_names; bool m_invalid_master_sync_point = false; void send_remove_snap(); void handle_remove_snap(int r); void send_refresh_image(); void handle_refresh_image(int r); void send_update_sync_points(); void handle_update_sync_points(int r); void finish(int r); }; } // namespace image_sync } // namespace mirror } // namespace rbd extern template class rbd::mirror::image_sync::SyncPointPruneRequest<librbd::ImageCtx>; #endif // RBD_MIRROR_IMAGE_SYNC_SYNC_POINT_PRUNE_REQUEST_H
2,121
22.065217
87
h
null
ceph-main/src/tools/rbd_mirror/image_sync/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_IMAGE_SYNC_TYPES_H #define RBD_MIRROR_IMAGE_SYNC_TYPES_H #include "cls/rbd/cls_rbd_types.h" #include "librbd/Types.h" #include <list> #include <string> #include <boost/optional.hpp> struct Context; namespace rbd { namespace mirror { namespace image_sync { struct SyncPoint { typedef boost::optional<uint64_t> ObjectNumber; SyncPoint() { } SyncPoint(const cls::rbd::SnapshotNamespace& snap_namespace, const std::string& snap_name, const std::string& from_snap_name, const ObjectNumber& object_number) : snap_namespace(snap_namespace), snap_name(snap_name), from_snap_name(from_snap_name), object_number(object_number) { } cls::rbd::SnapshotNamespace snap_namespace = {cls::rbd::UserSnapshotNamespace{}}; std::string snap_name; std::string from_snap_name; ObjectNumber object_number = boost::none; bool operator==(const SyncPoint& rhs) const { return (snap_namespace == rhs.snap_namespace && snap_name == rhs.snap_name && from_snap_name == rhs.from_snap_name && object_number == rhs.object_number); } }; typedef std::list<SyncPoint> SyncPoints; struct SyncPointHandler { public: SyncPointHandler(const SyncPointHandler&) = delete; SyncPointHandler& operator=(const SyncPointHandler&) = delete; virtual ~SyncPointHandler() {} virtual void destroy() { delete this; } virtual SyncPoints get_sync_points() const = 0; virtual librbd::SnapSeqs get_snap_seqs() const = 0; virtual void update_sync_points(const librbd::SnapSeqs& snap_seq, const SyncPoints& sync_points, bool sync_complete, Context* on_finish) = 0; protected: SyncPointHandler() {} }; } // namespace image_sync } // namespace mirror } // namespace rbd #endif // RBD_MIRROR_IMAGE_SYNC_TYPES_H
2,017
25.906667
70
h
null
ceph-main/src/tools/rbd_mirror/instance_watcher/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_INSTANCE_WATCHER_TYPES_H #define RBD_MIRROR_INSTANCE_WATCHER_TYPES_H #include <string> #include <set> #include <boost/variant.hpp> #include "include/buffer_fwd.h" #include "include/encoding.h" #include "include/int_types.h" namespace ceph { class Formatter; } namespace rbd { namespace mirror { namespace instance_watcher { enum NotifyOp { NOTIFY_OP_IMAGE_ACQUIRE = 0, NOTIFY_OP_IMAGE_RELEASE = 1, NOTIFY_OP_PEER_IMAGE_REMOVED = 2, NOTIFY_OP_SYNC_REQUEST = 3, NOTIFY_OP_SYNC_START = 4 }; struct PayloadBase { uint64_t request_id; PayloadBase() : request_id(0) { } PayloadBase(uint64_t request_id) : request_id(request_id) { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; struct ImagePayloadBase : public PayloadBase { std::string global_image_id; ImagePayloadBase() : PayloadBase() { } ImagePayloadBase(uint64_t request_id, const std::string &global_image_id) : PayloadBase(request_id), global_image_id(global_image_id) { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; struct ImageAcquirePayload : public ImagePayloadBase { static const NotifyOp NOTIFY_OP = NOTIFY_OP_IMAGE_ACQUIRE; ImageAcquirePayload() { } ImageAcquirePayload(uint64_t request_id, const std::string &global_image_id) : ImagePayloadBase(request_id, global_image_id) { } }; struct ImageReleasePayload : public ImagePayloadBase { static const NotifyOp NOTIFY_OP = NOTIFY_OP_IMAGE_RELEASE; ImageReleasePayload() { } ImageReleasePayload(uint64_t request_id, const std::string &global_image_id) : ImagePayloadBase(request_id, global_image_id) { } }; struct PeerImageRemovedPayload : public PayloadBase { static const NotifyOp NOTIFY_OP = NOTIFY_OP_PEER_IMAGE_REMOVED; std::string global_image_id; std::string peer_mirror_uuid; PeerImageRemovedPayload() { } PeerImageRemovedPayload(uint64_t request_id, const std::string& global_image_id, const std::string& peer_mirror_uuid) : PayloadBase(request_id), global_image_id(global_image_id), peer_mirror_uuid(peer_mirror_uuid) { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; struct SyncPayloadBase : public PayloadBase { std::string sync_id; SyncPayloadBase() : PayloadBase() { } SyncPayloadBase(uint64_t request_id, const std::string &sync_id) : PayloadBase(request_id), sync_id(sync_id) { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; struct SyncRequestPayload : public SyncPayloadBase { static const NotifyOp NOTIFY_OP = NOTIFY_OP_SYNC_REQUEST; SyncRequestPayload() : SyncPayloadBase() { } SyncRequestPayload(uint64_t request_id, const std::string &sync_id) : SyncPayloadBase(request_id, sync_id) { } }; struct SyncStartPayload : public SyncPayloadBase { static const NotifyOp NOTIFY_OP = NOTIFY_OP_SYNC_START; SyncStartPayload() : SyncPayloadBase() { } SyncStartPayload(uint64_t request_id, const std::string &sync_id) : SyncPayloadBase(request_id, sync_id) { } }; struct UnknownPayload { static const NotifyOp NOTIFY_OP = static_cast<NotifyOp>(-1); UnknownPayload() { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; typedef boost::variant<ImageAcquirePayload, ImageReleasePayload, PeerImageRemovedPayload, SyncRequestPayload, SyncStartPayload, UnknownPayload> Payload; struct NotifyMessage { NotifyMessage(const Payload &payload = UnknownPayload()) : payload(payload) { } Payload payload; void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& it); void dump(Formatter *f) const; static void generate_test_instances(std::list<NotifyMessage *> &o); }; WRITE_CLASS_ENCODER(NotifyMessage); std::ostream &operator<<(std::ostream &out, const NotifyOp &op); struct NotifyAckPayload { std::string instance_id; uint64_t request_id; int ret_val; NotifyAckPayload() : request_id(0), ret_val(0) { } NotifyAckPayload(const std::string &instance_id, uint64_t request_id, int ret_val) : instance_id(instance_id), request_id(request_id), ret_val(ret_val) { } void encode(bufferlist &bl) const; void decode(bufferlist::const_iterator& it); void dump(Formatter *f) const; }; WRITE_CLASS_ENCODER(NotifyAckPayload); } // namespace instance_watcher } // namespace mirror } // namespace librbd using rbd::mirror::instance_watcher::encode; using rbd::mirror::instance_watcher::decode; #endif // RBD_MIRROR_INSTANCE_WATCHER_TYPES_H
5,146
24.994949
79
h
null
ceph-main/src/tools/rbd_mirror/instances/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_INSTANCES_TYPES_H #define CEPH_RBD_MIRROR_INSTANCES_TYPES_H #include <string> #include <vector> namespace rbd { namespace mirror { namespace instances { struct Listener { typedef std::vector<std::string> InstanceIds; virtual ~Listener() { } virtual void handle_added(const InstanceIds& instance_ids) = 0; virtual void handle_removed(const InstanceIds& instance_ids) = 0; }; } // namespace instances } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_INSTANCES_TYPES_H
624
20.551724
70
h
null
ceph-main/src/tools/rbd_mirror/leader_watcher/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef RBD_MIRROR_LEADER_WATCHER_TYPES_H #define RBD_MIRROR_LEADER_WATCHER_TYPES_H #include "include/int_types.h" #include "include/buffer_fwd.h" #include "include/encoding.h" #include <string> #include <vector> #include <boost/variant.hpp> struct Context; namespace ceph { class Formatter; } namespace rbd { namespace mirror { namespace leader_watcher { struct Listener { typedef std::vector<std::string> InstanceIds; virtual ~Listener() { } virtual void post_acquire_handler(Context *on_finish) = 0; virtual void pre_release_handler(Context *on_finish) = 0; virtual void update_leader_handler( const std::string &leader_instance_id) = 0; virtual void handle_instances_added(const InstanceIds& instance_ids) = 0; virtual void handle_instances_removed(const InstanceIds& instance_ids) = 0; }; enum NotifyOp { NOTIFY_OP_HEARTBEAT = 0, NOTIFY_OP_LOCK_ACQUIRED = 1, NOTIFY_OP_LOCK_RELEASED = 2, }; struct HeartbeatPayload { static const NotifyOp NOTIFY_OP = NOTIFY_OP_HEARTBEAT; HeartbeatPayload() { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; struct LockAcquiredPayload { static const NotifyOp NOTIFY_OP = NOTIFY_OP_LOCK_ACQUIRED; LockAcquiredPayload() { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; struct LockReleasedPayload { static const NotifyOp NOTIFY_OP = NOTIFY_OP_LOCK_RELEASED; LockReleasedPayload() { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; struct UnknownPayload { static const NotifyOp NOTIFY_OP = static_cast<NotifyOp>(-1); UnknownPayload() { } void encode(bufferlist &bl) const; void decode(__u8 version, bufferlist::const_iterator &iter); void dump(Formatter *f) const; }; typedef boost::variant<HeartbeatPayload, LockAcquiredPayload, LockReleasedPayload, UnknownPayload> Payload; struct NotifyMessage { NotifyMessage(const Payload &payload = UnknownPayload()) : payload(payload) { } Payload payload; void encode(bufferlist& bl) const; void decode(bufferlist::const_iterator& it); void dump(Formatter *f) const; static void generate_test_instances(std::list<NotifyMessage *> &o); }; WRITE_CLASS_ENCODER(NotifyMessage); std::ostream &operator<<(std::ostream &out, const NotifyOp &op); } // namespace leader_watcher } // namespace mirror } // namespace librbd using rbd::mirror::leader_watcher::encode; using rbd::mirror::leader_watcher::decode; #endif // RBD_MIRROR_LEADER_WATCHER_TYPES_H
2,870
23.330508
79
h
null
ceph-main/src/tools/rbd_mirror/pool_watcher/RefreshImagesRequest.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_POOL_WATCHER_REFRESH_IMAGES_REQUEST_H #define CEPH_RBD_MIRROR_POOL_WATCHER_REFRESH_IMAGES_REQUEST_H #include "include/buffer.h" #include "include/rados/librados.hpp" #include "tools/rbd_mirror/Types.h" #include <string> struct Context; namespace librbd { struct ImageCtx; } namespace rbd { namespace mirror { namespace pool_watcher { template <typename ImageCtxT = librbd::ImageCtx> class RefreshImagesRequest { public: static RefreshImagesRequest *create(librados::IoCtx &remote_io_ctx, ImageIds *image_ids, Context *on_finish) { return new RefreshImagesRequest(remote_io_ctx, image_ids, on_finish); } RefreshImagesRequest(librados::IoCtx &remote_io_ctx, ImageIds *image_ids, Context *on_finish) : m_remote_io_ctx(remote_io_ctx), m_image_ids(image_ids), m_on_finish(on_finish) { } void send(); private: /** * @verbatim * * <start> * | * | /-------------\ * | | | * v v | (more images) * MIRROR_IMAGE_LIST ---/ * | * v * <finish> * * @endverbatim */ librados::IoCtx &m_remote_io_ctx; ImageIds *m_image_ids; Context *m_on_finish; bufferlist m_out_bl; std::string m_start_after; void mirror_image_list(); void handle_mirror_image_list(int r); void finish(int r); }; } // namespace pool_watcher } // namespace mirror } // namespace rbd extern template class rbd::mirror::pool_watcher::RefreshImagesRequest<librbd::ImageCtx>; #endif // CEPH_RBD_MIRROR_POOL_WATCHER_REFRESH_IMAGES_REQUEST_H
1,718
22.22973
88
h
null
ceph-main/src/tools/rbd_mirror/pool_watcher/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_POOL_WATCHER_TYPES_H #define CEPH_RBD_MIRROR_POOL_WATCHER_TYPES_H #include "tools/rbd_mirror/Types.h" #include <string> namespace rbd { namespace mirror { namespace pool_watcher { struct Listener { virtual ~Listener() { } virtual void handle_update(const std::string &mirror_uuid, ImageIds &&added_image_ids, ImageIds &&removed_image_ids) = 0; }; } // namespace pool_watcher } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_POOL_WATCHER_TYPES_H
656
22.464286
70
h
null
ceph-main/src/tools/rbd_mirror/service_daemon/Types.h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef CEPH_RBD_MIRROR_SERVICE_DAEMON_TYPES_H #define CEPH_RBD_MIRROR_SERVICE_DAEMON_TYPES_H #include "include/int_types.h" #include <iosfwd> #include <string> #include <boost/variant.hpp> namespace rbd { namespace mirror { namespace service_daemon { typedef uint64_t CalloutId; const uint64_t CALLOUT_ID_NONE {0}; enum CalloutLevel { CALLOUT_LEVEL_INFO, CALLOUT_LEVEL_WARNING, CALLOUT_LEVEL_ERROR }; std::ostream& operator<<(std::ostream& os, const CalloutLevel& callout_level); typedef boost::variant<bool, uint64_t, std::string> AttributeValue; } // namespace service_daemon } // namespace mirror } // namespace rbd #endif // CEPH_RBD_MIRROR_SERVICE_DAEMON_TYPES_H
782
22.029412
78
h
null
ceph-main/src/tools/rbd_nbd/nbd-netlink.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2017 Facebook. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * 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, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #ifndef _UAPILINUX_NBD_NETLINK_H #define _UAPILINUX_NBD_NETLINK_H #define NBD_GENL_FAMILY_NAME "nbd" #define NBD_GENL_VERSION 0x1 #define NBD_GENL_MCAST_GROUP_NAME "nbd_mc_group" /* Configuration policy attributes, used for CONNECT */ enum { NBD_ATTR_UNSPEC, NBD_ATTR_INDEX, NBD_ATTR_SIZE_BYTES, NBD_ATTR_BLOCK_SIZE_BYTES, NBD_ATTR_TIMEOUT, NBD_ATTR_SERVER_FLAGS, NBD_ATTR_CLIENT_FLAGS, NBD_ATTR_SOCKETS, NBD_ATTR_DEAD_CONN_TIMEOUT, NBD_ATTR_DEVICE_LIST, NBD_ATTR_BACKEND_IDENTIFIER, __NBD_ATTR_MAX, }; #define NBD_ATTR_MAX (__NBD_ATTR_MAX - 1) /* * This is the format for multiple devices with NBD_ATTR_DEVICE_LIST * * [NBD_ATTR_DEVICE_LIST] * [NBD_DEVICE_ITEM] * [NBD_DEVICE_INDEX] * [NBD_DEVICE_CONNECTED] */ enum { NBD_DEVICE_ITEM_UNSPEC, NBD_DEVICE_ITEM, __NBD_DEVICE_ITEM_MAX, }; #define NBD_DEVICE_ITEM_MAX (__NBD_DEVICE_ITEM_MAX - 1) enum { NBD_DEVICE_UNSPEC, NBD_DEVICE_INDEX, NBD_DEVICE_CONNECTED, __NBD_DEVICE_MAX, }; #define NBD_DEVICE_ATTR_MAX (__NBD_DEVICE_MAX - 1) /* * This is the format for multiple sockets with NBD_ATTR_SOCKETS * * [NBD_ATTR_SOCKETS] * [NBD_SOCK_ITEM] * [NBD_SOCK_FD] * [NBD_SOCK_ITEM] * [NBD_SOCK_FD] */ enum { NBD_SOCK_ITEM_UNSPEC, NBD_SOCK_ITEM, __NBD_SOCK_ITEM_MAX, }; #define NBD_SOCK_ITEM_MAX (__NBD_SOCK_ITEM_MAX - 1) enum { NBD_SOCK_UNSPEC, NBD_SOCK_FD, __NBD_SOCK_MAX, }; #define NBD_SOCK_MAX (__NBD_SOCK_MAX - 1) enum { NBD_CMD_UNSPEC, NBD_CMD_CONNECT, NBD_CMD_DISCONNECT, NBD_CMD_RECONFIGURE, NBD_CMD_LINK_DEAD, NBD_CMD_STATUS, __NBD_CMD_MAX, }; #define NBD_CMD_MAX (__NBD_CMD_MAX - 1) #endif /* _UAPILINUX_NBD_NETLINK_H */
2,423
23
68
h
null
ceph-main/src/tools/rbd_wnbd/rbd_wnbd.h
/* * Ceph - scalable distributed file system * * Copyright (C) 2020 SUSE LINUX GmbH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef RBD_WNBD_H #define RBD_WNBD_H #include <string.h> #include <iostream> #include <vector> #include "include/compat.h" #include "common/win32/registry.h" #include "wnbd_handler.h" #define SERVICE_REG_KEY "SYSTEM\\CurrentControlSet\\Services\\rbd-wnbd" #define SERVICE_PIPE_NAME "\\\\.\\pipe\\rbd-wnbd" #define SERVICE_PIPE_TIMEOUT_MS 5000 #define SERVICE_PIPE_BUFFSZ 4096 #define DEFAULT_MAP_TIMEOUT_MS 30000 #define RBD_WNBD_BLKSIZE 512UL #define DEFAULT_SERVICE_START_TIMEOUT 120 #define DEFAULT_IMAGE_MAP_TIMEOUT 20 #define HELP_INFO 1 #define VERSION_INFO 2 #define WNBD_STATUS_ACTIVE "active" #define WNBD_STATUS_INACTIVE "inactive" #define DEFAULT_SERVICE_THREAD_COUNT 8 static WnbdHandler* handler = nullptr; ceph::mutex shutdown_lock = ceph::make_mutex("RbdWnbd::ShutdownLock"); struct Config { bool exclusive = false; bool readonly = false; std::string parent_pipe; std::string poolname; std::string nsname; std::string imgname; std::string snapname; std::string devpath; std::string format; bool pretty_format = false; bool hard_disconnect = false; int soft_disconnect_timeout = DEFAULT_SOFT_REMOVE_TIMEOUT; bool hard_disconnect_fallback = true; int service_start_timeout = DEFAULT_SERVICE_START_TIMEOUT; int image_map_timeout = DEFAULT_IMAGE_MAP_TIMEOUT; bool remap_failure_fatal = false; bool adapter_monitoring_enabled = false; // TODO: consider moving those fields to a separate structure. Those // provide connection information without actually being configurable. // The disk number is provided by Windows. int disk_number = -1; int pid = 0; std::string serial_number; bool active = false; bool wnbd_mapped = false; std::string command_line; std::string admin_sock_path; WnbdLogLevel wnbd_log_level = WnbdLogLevelInfo; int io_req_workers = DEFAULT_IO_WORKER_COUNT; int io_reply_workers = DEFAULT_IO_WORKER_COUNT; int service_thread_count = DEFAULT_SERVICE_THREAD_COUNT; // register the mapping, recreating it when the Ceph service starts. bool persistent = true; }; enum Command { None, Connect, Disconnect, List, Show, Service, Stats }; typedef struct { Command command; BYTE arguments[1]; } ServiceRequest; typedef struct { int status; } ServiceReply; bool is_process_running(DWORD pid); void unmap_at_exit(); int disconnect_all_mappings( bool unregister, bool hard_disconnect, int soft_disconnect_timeout, int worker_count); int restart_registered_mappings( int worker_count, int total_timeout, int image_map_timeout); int map_device_using_suprocess(std::string command_line); int construct_devpath_if_missing(Config* cfg); int save_config_to_registry(Config* cfg); int remove_config_from_registry(Config* cfg); int load_mapping_config_from_registry(std::string devpath, Config* cfg); BOOL WINAPI console_handler_routine(DWORD dwCtrlType); static int parse_args(std::vector<const char*>& args, std::ostream *err_msg, Command *command, Config *cfg); static int do_unmap(Config *cfg, bool unregister); class BaseIterator { public: virtual ~BaseIterator() {}; virtual bool get(Config *cfg) = 0; int get_error() { return error; } protected: int error = 0; int index = -1; }; // Iterate over mapped devices, retrieving info from the driver. class WNBDActiveDiskIterator : public BaseIterator { public: WNBDActiveDiskIterator(); ~WNBDActiveDiskIterator(); bool get(Config *cfg); private: PWNBD_CONNECTION_LIST conn_list = NULL; static DWORD fetch_list(PWNBD_CONNECTION_LIST* conn_list); }; // Iterate over the Windows registry key, retrieving registered mappings. class RegistryDiskIterator : public BaseIterator { public: RegistryDiskIterator(); ~RegistryDiskIterator() { delete reg_key; } bool get(Config *cfg); private: DWORD subkey_count = 0; char subkey_name[MAX_PATH]; RegistryKey* reg_key = NULL; }; // Iterate over all RBD mappings, getting info from the registry and driver. class WNBDDiskIterator : public BaseIterator { public: bool get(Config *cfg); private: // We'll keep track of the active devices. std::set<std::string> active_devices; WNBDActiveDiskIterator active_iterator; RegistryDiskIterator registry_iterator; }; #endif // RBD_WNBD_H
4,685
23.154639
76
h
null
ceph-main/src/tools/rbd_wnbd/wnbd_handler.h
/* * Ceph - scalable distributed file system * * Copyright (C) 2020 SUSE LINUX GmbH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef WNBD_HANDLER_H #define WNBD_HANDLER_H #include <wnbd.h> #include "common/admin_socket.h" #include "common/ceph_context.h" #include "common/Thread.h" #include "include/rbd/librbd.hpp" #include "include/xlist.h" #include "global/global_context.h" // TODO: make this configurable. #define RBD_WNBD_MAX_TRANSFER 2 * 1024 * 1024 #define SOFT_REMOVE_RETRY_INTERVAL 2 #define DEFAULT_SOFT_REMOVE_TIMEOUT 15 #define DEFAULT_IO_WORKER_COUNT 4 // Not defined by mingw. #ifndef SCSI_ADSENSE_UNRECOVERED_ERROR #define SCSI_ADSENSE_UNRECOVERED_ERROR 0x11 #endif // The following will be assigned to the "Owner" field of the WNBD // parameters, which can be used to determine the application managing // a disk. We'll ignore other disks. #define RBD_WNBD_OWNER_NAME "ceph-rbd-wnbd" class WnbdHandler; class WnbdAdminHook : public AdminSocketHook { WnbdHandler *m_handler; public: explicit WnbdAdminHook(WnbdHandler *handler) : m_handler(handler) { g_ceph_context->get_admin_socket()->register_command( "wnbd stats", this, "get WNBD stats"); } ~WnbdAdminHook() override { g_ceph_context->get_admin_socket()->unregister_commands(this); } int call(std::string_view command, const cmdmap_t& cmdmap, const bufferlist&, Formatter *f, std::ostream& errss, bufferlist& out) override; }; class WnbdHandler { private: librbd::Image &image; std::string instance_name; uint64_t block_count; uint32_t block_size; bool readonly; bool rbd_cache_enabled; uint32_t io_req_workers; uint32_t io_reply_workers; WnbdAdminHook* admin_hook; boost::asio::thread_pool* reply_tpool; public: WnbdHandler(librbd::Image& _image, std::string _instance_name, uint64_t _block_count, uint32_t _block_size, bool _readonly, bool _rbd_cache_enabled, uint32_t _io_req_workers, uint32_t _io_reply_workers) : image(_image) , instance_name(_instance_name) , block_count(_block_count) , block_size(_block_size) , readonly(_readonly) , rbd_cache_enabled(_rbd_cache_enabled) , io_req_workers(_io_req_workers) , io_reply_workers(_io_reply_workers) { admin_hook = new WnbdAdminHook(this); // Instead of relying on librbd's own thread pool, we're going to use a // separate one. This allows us to make assumptions on the threads that // are going to send the IO replies and thus be able to cache Windows // OVERLAPPED structures. reply_tpool = new boost::asio::thread_pool(_io_reply_workers); } int resize(uint64_t new_size); int start(); // Wait for the handler to stop, which normally happens when the driver // passes the "Disconnect" request. int wait(); void shutdown(); int dump_stats(Formatter *f); ~WnbdHandler(); static VOID LogMessage( WnbdLogLevel LogLevel, const char* Message, const char* FileName, UINT32 Line, const char* FunctionName); private: ceph::mutex shutdown_lock = ceph::make_mutex("WnbdHandler::DisconnectLocker"); bool started = false; bool terminated = false; WNBD_DISK* wnbd_disk = nullptr; struct IOContext { xlist<IOContext*>::item item; WnbdHandler *handler = nullptr; WNBD_STATUS wnbd_status = {0}; WnbdRequestType req_type = WnbdReqTypeUnknown; uint64_t req_handle = 0; uint32_t err_code = 0; size_t req_size; uint64_t req_from; bufferlist data; IOContext() : item(this) {} void set_sense(uint8_t sense_key, uint8_t asc, uint64_t info); void set_sense(uint8_t sense_key, uint8_t asc); }; friend std::ostream &operator<<(std::ostream &os, const IOContext &ctx); void send_io_response(IOContext *ctx); static void aio_callback(librbd::completion_t cb, void *arg); // WNBD IO entry points static void Read( PWNBD_DISK Disk, UINT64 RequestHandle, PVOID Buffer, UINT64 BlockAddress, UINT32 BlockCount, BOOLEAN ForceUnitAccess); static void Write( PWNBD_DISK Disk, UINT64 RequestHandle, PVOID Buffer, UINT64 BlockAddress, UINT32 BlockCount, BOOLEAN ForceUnitAccess); static void Flush( PWNBD_DISK Disk, UINT64 RequestHandle, UINT64 BlockAddress, UINT32 BlockCount); static void Unmap( PWNBD_DISK Disk, UINT64 RequestHandle, PWNBD_UNMAP_DESCRIPTOR Descriptors, UINT32 Count); static constexpr WNBD_INTERFACE RbdWnbdInterface = { Read, Write, Flush, Unmap, }; }; std::ostream &operator<<(std::ostream &os, const WnbdHandler::IOContext &ctx); #endif // WNBD_HANDLER_H
4,886
24.857143
80
h
null
ceph-main/src/tracing/cyg_profile_functions.c
#include "acconfig.h" #ifdef WITH_LTTNG #define TRACEPOINT_DEFINE #define TRACEPOINT_PROBE_DYNAMIC_LINKAGE #include "tracing/cyg_profile.h" #undef TRACEPOINT_PROBE_DYNAMIC_LINKAGE #undef TRACEPOINT_DEFINE #endif void __cyg_profile_func_enter(void *this_fn, void *call_site) __attribute__((no_instrument_function)); void __cyg_profile_func_exit(void *this_fn, void *call_site) __attribute__((no_instrument_function)); void __cyg_profile_func_enter(void *this_fn, void *call_site) { #ifdef WITH_LTTNG tracepoint(lttng_ust_cyg_profile, func_entry, this_fn, call_site); #endif } void __cyg_profile_func_exit(void *this_fn, void *call_site) { #ifdef WITH_LTTNG tracepoint(lttng_ust_cyg_profile, func_exit, this_fn, call_site); #endif }
754
22.59375
70
c
AMG
AMG-master/HYPRE.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for HYPRE library * *****************************************************************************/ #ifndef HYPRE_HEADER #define HYPRE_HEADER #define HYPRE_NO_GLOBAL_PARTITION 1 /*-------------------------------------------------------------------------- * Type definitions *--------------------------------------------------------------------------*/ #ifdef HYPRE_BIGINT typedef long long int HYPRE_Int; #define HYPRE_MPI_INT MPI_LONG_LONG #else typedef int HYPRE_Int; #define HYPRE_MPI_INT MPI_INT #endif /*-------------------------------------------------------------------------- * Constants *--------------------------------------------------------------------------*/ #define HYPRE_UNITIALIZED -999 #define HYPRE_PETSC_MAT_PARILUT_SOLVER 222 #define HYPRE_PARILUT 333 #define HYPRE_STRUCT 1111 #define HYPRE_SSTRUCT 3333 #define HYPRE_PARCSR 5555 #define HYPRE_ISIS 9911 #define HYPRE_PETSC 9933 #define HYPRE_PFMG 10 #define HYPRE_SMG 11 #define HYPRE_Jacobi 17 #endif
2,050
30.553846
81
h
AMG
AMG-master/IJ_mv/HYPRE_IJVector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_IJVector interface * *****************************************************************************/ #include "./_hypre_IJ_mv.h" #include "../HYPRE.h" /*-------------------------------------------------------------------------- * HYPRE_IJVectorCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorCreate( MPI_Comm comm, HYPRE_Int jlower, HYPRE_Int jupper, HYPRE_IJVector *vector ) { hypre_IJVector *vec; HYPRE_Int num_procs, my_id, *partitioning; #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int row0, rowN; #else HYPRE_Int *recv_buf; HYPRE_Int *info; HYPRE_Int i, i2; #endif vec = hypre_CTAlloc(hypre_IJVector, 1); if (!vec) { hypre_error(HYPRE_ERROR_MEMORY); return hypre_error_flag; } hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (jlower > jupper+1 || jlower < 0) { hypre_error_in_arg(2); hypre_TFree(vec); return hypre_error_flag; } if (jupper < -1) { hypre_error_in_arg(3); return hypre_error_flag; } #ifdef HYPRE_NO_GLOBAL_PARTITION partitioning = hypre_CTAlloc(HYPRE_Int, 2); partitioning[0] = jlower; partitioning[1] = jupper+1; /* now we need the global number of rows as well as the global first row index */ /* proc 0 has the first row */ if (my_id==0) { row0 = jlower; } hypre_MPI_Bcast(&row0, 1, HYPRE_MPI_INT, 0, comm); /* proc (num_procs-1) has the last row */ if (my_id == (num_procs-1)) { rowN = jupper; } hypre_MPI_Bcast(&rowN, 1, HYPRE_MPI_INT, num_procs-1, comm); hypre_IJVectorGlobalFirstRow(vec) = row0; hypre_IJVectorGlobalNumRows(vec) = rowN - row0 + 1; #else info = hypre_CTAlloc(HYPRE_Int,2); recv_buf = hypre_CTAlloc(HYPRE_Int, 2*num_procs); partitioning = hypre_CTAlloc(HYPRE_Int, num_procs+1); info[0] = jlower; info[1] = jupper; hypre_MPI_Allgather(info, 2, HYPRE_MPI_INT, recv_buf, 2, HYPRE_MPI_INT, comm); partitioning[0] = recv_buf[0]; for (i=0; i < num_procs-1; i++) { i2 = i+i; if (recv_buf[i2+1] != (recv_buf[i2+2]-1)) { /*hypre_printf("Inconsistent partitioning -- HYPRE_IJVectorCreate\n"); */ hypre_error(HYPRE_ERROR_GENERIC); hypre_TFree(info); hypre_TFree(recv_buf); hypre_TFree(partitioning); hypre_TFree(vec); return hypre_error_flag; } else partitioning[i+1] = recv_buf[i2+2]; } i2 = (num_procs-1)*2; partitioning[num_procs] = recv_buf[i2+1]+1; hypre_TFree(info); hypre_TFree(recv_buf); hypre_IJVectorGlobalFirstRow(vec) = partitioning[0]; hypre_IJVectorGlobalNumRows(vec)= partitioning[num_procs]-partitioning[0]; #endif hypre_IJVectorComm(vec) = comm; hypre_IJVectorPartitioning(vec) = partitioning; hypre_IJVectorObjectType(vec) = HYPRE_UNITIALIZED; hypre_IJVectorObject(vec) = NULL; hypre_IJVectorTranslator(vec) = NULL; hypre_IJVectorAssumedPart(vec) = NULL; hypre_IJVectorPrintLevel(vec) = 0; *vector = (HYPRE_IJVector) vec; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorDestroy( HYPRE_IJVector vector ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } if (hypre_IJVectorPartitioning(vec)) hypre_TFree(hypre_IJVectorPartitioning(vec)); if (hypre_IJVectorAssumedPart(vec)) hypre_AssumedPartitionDestroy((hypre_IJAssumedPart*)hypre_IJVectorAssumedPart(vec)); if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) { hypre_IJVectorDestroyPar(vec) ; if (hypre_IJVectorTranslator(vec)) { hypre_AuxParVectorDestroy((hypre_AuxParVector *) (hypre_IJVectorTranslator(vec))); } } else if ( hypre_IJVectorObjectType(vec) != -1 ) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_TFree(vec); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorInitialize( HYPRE_IJVector vector ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) { if (!hypre_IJVectorObject(vec)) hypre_IJVectorCreatePar(vec, hypre_IJVectorPartitioning(vec)); hypre_IJVectorInitializePar(vec); } else { hypre_error_in_arg(1); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorSetPrintLevel *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorSetPrintLevel( HYPRE_IJVector vector, HYPRE_Int print_level ) { hypre_IJVector *ijvector = (hypre_IJVector *) vector; if (!ijvector) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_IJVectorPrintLevel(ijvector) = 1; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorSetValues *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorSetValues( HYPRE_IJVector vector, HYPRE_Int nvalues, const HYPRE_Int *indices, const HYPRE_Complex *values ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (nvalues == 0) return hypre_error_flag; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } if (nvalues < 0) { hypre_error_in_arg(2); return hypre_error_flag; } if (!values) { hypre_error_in_arg(4); return hypre_error_flag; } if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) { return( hypre_IJVectorSetValuesPar(vec, nvalues, indices, values) ); } else { hypre_error_in_arg(1); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorAddToValues *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorAddToValues( HYPRE_IJVector vector, HYPRE_Int nvalues, const HYPRE_Int *indices, const HYPRE_Complex *values ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (nvalues == 0) return hypre_error_flag; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } if (nvalues < 0) { hypre_error_in_arg(2); return hypre_error_flag; } if (!values) { hypre_error_in_arg(4); return hypre_error_flag; } if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) { return( hypre_IJVectorAddToValuesPar(vec, nvalues, indices, values) ); } else { hypre_error_in_arg(1); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorAssemble *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorAssemble( HYPRE_IJVector vector ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) { return( hypre_IJVectorAssemblePar(vec) ); } else { hypre_error_in_arg(1); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorGetValues *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorGetValues( HYPRE_IJVector vector, HYPRE_Int nvalues, const HYPRE_Int *indices, HYPRE_Complex *values ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (nvalues == 0) return hypre_error_flag; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } if (nvalues < 0) { hypre_error_in_arg(2); return hypre_error_flag; } if (!values) { hypre_error_in_arg(4); return hypre_error_flag; } if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) { return( hypre_IJVectorGetValuesPar(vec, nvalues, indices, values) ); } else { hypre_error_in_arg(1); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorSetMaxOffProcElmts *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorSetMaxOffProcElmts( HYPRE_IJVector vector, HYPRE_Int max_off_proc_elmts ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) { return( hypre_IJVectorSetMaxOffProcElmtsPar(vec, max_off_proc_elmts)); } else { hypre_error_in_arg(1); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorSetObjectType *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorSetObjectType( HYPRE_IJVector vector, HYPRE_Int type ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_IJVectorObjectType(vec) = type; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorGetObjectType *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorGetObjectType( HYPRE_IJVector vector, HYPRE_Int *type ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } *type = hypre_IJVectorObjectType(vec); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorGetLocalRange *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorGetLocalRange( HYPRE_IJVector vector, HYPRE_Int *jlower, HYPRE_Int *jupper ) { hypre_IJVector *vec = (hypre_IJVector *) vector; MPI_Comm comm; HYPRE_Int *partitioning; HYPRE_Int my_id; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } comm = hypre_IJVectorComm(vec); partitioning = hypre_IJVectorPartitioning(vec); hypre_MPI_Comm_rank(comm, &my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION *jlower = partitioning[0]; *jupper = partitioning[1]-1; #else *jlower = partitioning[my_id]; *jupper = partitioning[my_id+1]-1; #endif return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorGetObject *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorGetObject( HYPRE_IJVector vector, void **object ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (!vec) { hypre_error_in_arg(1); return hypre_error_flag; } *object = hypre_IJVectorObject(vec); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorRead *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorRead( const char *filename, MPI_Comm comm, HYPRE_Int type, HYPRE_IJVector *vector_ptr ) { HYPRE_IJVector vector; HYPRE_Int jlower, jupper, j; HYPRE_Complex value; HYPRE_Int myid, ret; char new_filename[255]; FILE *file; hypre_MPI_Comm_rank(comm, &myid); hypre_sprintf(new_filename,"%s.%05d", filename, myid); if ((file = fopen(new_filename, "r")) == NULL) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_fscanf(file, "%d %d", &jlower, &jupper); HYPRE_IJVectorCreate(comm, jlower, jupper, &vector); HYPRE_IJVectorSetObjectType(vector, type); HYPRE_IJVectorInitialize(vector); /* It is important to ensure that whitespace follows the index value to help * catch mistakes in the input file. This is done with %*[ \t]. Using a * space here causes an input line with a single decimal value on it to be * read as if it were an integer followed by a decimal value. */ while ( (ret = hypre_fscanf(file, "%d%*[ \t]%le", &j, &value)) != EOF ) { if (ret != 2) { hypre_error_w_msg(HYPRE_ERROR_GENERIC, "Error in IJ vector input file."); return hypre_error_flag; } if (j < jlower || j > jupper) HYPRE_IJVectorAddToValues(vector, 1, &j, &value); else HYPRE_IJVectorSetValues(vector, 1, &j, &value); } HYPRE_IJVectorAssemble(vector); fclose(file); *vector_ptr = vector; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_IJVectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_IJVectorPrint( HYPRE_IJVector vector, const char *filename ) { MPI_Comm comm; HYPRE_Int *partitioning; HYPRE_Int jlower, jupper, j; HYPRE_Complex value; HYPRE_Int myid; char new_filename[255]; FILE *file; if (!vector) { hypre_error_in_arg(1); return hypre_error_flag; } comm = hypre_IJVectorComm(vector); hypre_MPI_Comm_rank(comm, &myid); hypre_sprintf(new_filename,"%s.%05d", filename, myid); if ((file = fopen(new_filename, "w")) == NULL) { hypre_error_in_arg(2); return hypre_error_flag; } partitioning = hypre_IJVectorPartitioning(vector); #ifdef HYPRE_NO_GLOBAL_PARTITION jlower = partitioning[0]; jupper = partitioning[1] - 1; #else jlower = partitioning[myid]; jupper = partitioning[myid+1] - 1; #endif hypre_fprintf(file, "%d %d\n", jlower, jupper); for (j = jlower; j <= jupper; j++) { HYPRE_IJVectorGetValues(vector, 1, &j, &value); hypre_fprintf(file, "%d %.14e\n", j, value); } fclose(file); return hypre_error_flag; }
16,347
24.464174
88
c
AMG
AMG-master/IJ_mv/HYPRE_IJ_mv.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef HYPRE_IJ_MV_HEADER #define HYPRE_IJ_MV_HEADER #include "HYPRE_utilities.h" #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name IJ System Interface * * This interface represents a linear-algebraic conceptual view of a * linear system. The 'I' and 'J' in the name are meant to be * mnemonic for the traditional matrix notation A(I,J). * * @memo A linear-algebraic conceptual interface **/ /*@{*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name IJ Matrices **/ /*@{*/ struct hypre_IJMatrix_struct; /** * The matrix object. **/ typedef struct hypre_IJMatrix_struct *HYPRE_IJMatrix; /** * Create a matrix object. Each process owns some unique consecutive * range of rows, indicated by the global row indices {\tt ilower} and * {\tt iupper}. The row data is required to be such that the value * of {\tt ilower} on any process $p$ be exactly one more than the * value of {\tt iupper} on process $p-1$. Note that the first row of * the global matrix may start with any integer value. In particular, * one may use zero- or one-based indexing. * * For square matrices, {\tt jlower} and {\tt jupper} typically should * match {\tt ilower} and {\tt iupper}, respectively. For rectangular * matrices, {\tt jlower} and {\tt jupper} should define a * partitioning of the columns. This partitioning must be used for * any vector $v$ that will be used in matrix-vector products with the * rectangular matrix. The matrix data structure may use {\tt jlower} * and {\tt jupper} to store the diagonal blocks (rectangular in * general) of the matrix separately from the rest of the matrix. * * Collective. **/ HYPRE_Int HYPRE_IJMatrixCreate(MPI_Comm comm, HYPRE_Int ilower, HYPRE_Int iupper, HYPRE_Int jlower, HYPRE_Int jupper, HYPRE_IJMatrix *matrix); /** * Destroy a matrix object. An object should be explicitly destroyed * using this destructor when the user's code no longer needs direct * access to it. Once destroyed, the object must not be referenced * again. Note that the object may not be deallocated at the * completion of this call, since there may be internal package * references to the object. The object will then be destroyed when * all internal reference counts go to zero. **/ HYPRE_Int HYPRE_IJMatrixDestroy(HYPRE_IJMatrix matrix); /** * Prepare a matrix object for setting coefficient values. This * routine will also re-initialize an already assembled matrix, * allowing users to modify coefficient values. **/ HYPRE_Int HYPRE_IJMatrixInitialize(HYPRE_IJMatrix matrix); /** * Sets values for {\tt nrows} rows or partial rows of the matrix. * The arrays {\tt ncols} * and {\tt rows} are of dimension {\tt nrows} and contain the number * of columns in each row and the row indices, respectively. The * array {\tt cols} contains the column indices for each of the {\tt * rows}, and is ordered by rows. The data in the {\tt values} array * corresponds directly to the column entries in {\tt cols}. Erases * any previous values at the specified locations and replaces them * with new ones, or, if there was no value there before, inserts a * new one if set locally. Note that it is not possible to set values * on other processors. If one tries to set a value from proc i on proc j, * proc i will erase all previous occurrences of this value in its stack * (including values generated with AddToValues), and treat it like * a zero value. The actual value needs to be set on proc j. * * Note that a threaded version (threaded over the number of rows) * will be called if * HYPRE_IJMatrixSetOMPFlag is set to a value != 0. * This requires that rows[i] != rows[j] for i!= j * and is only efficient if a large number of rows is set in one call * to HYPRE_IJMatrixSetValues. * * Not collective. * **/ HYPRE_Int HYPRE_IJMatrixSetValues(HYPRE_IJMatrix matrix, HYPRE_Int nrows, HYPRE_Int *ncols, const HYPRE_Int *rows, const HYPRE_Int *cols, const HYPRE_Complex *values); /** * Adds to values for {\tt nrows} rows or partial rows of the matrix. * Usage details are analogous to \Ref{HYPRE_IJMatrixSetValues}. * Adds to any previous values at the specified locations, or, if * there was no value there before, inserts a new one. * AddToValues can be used to add to values on other processors. * * Note that a threaded version (threaded over the number of rows) * will be called if * HYPRE_IJMatrixSetOMPFlag is set to a value != 0. * This requires that rows[i] != rows[j] for i!= j * and is only efficient if a large number of rows is added in one call * to HYPRE_IJMatrixAddToValues. * * Not collective. * **/ HYPRE_Int HYPRE_IJMatrixAddToValues(HYPRE_IJMatrix matrix, HYPRE_Int nrows, HYPRE_Int *ncols, const HYPRE_Int *rows, const HYPRE_Int *cols, const HYPRE_Complex *values); /** * Finalize the construction of the matrix before using. **/ HYPRE_Int HYPRE_IJMatrixAssemble(HYPRE_IJMatrix matrix); /** * Gets number of nonzeros elements for {\tt nrows} rows specified in {\tt rows} * and returns them in {\tt ncols}, which needs to be allocated by the * user. **/ HYPRE_Int HYPRE_IJMatrixGetRowCounts(HYPRE_IJMatrix matrix, HYPRE_Int nrows, HYPRE_Int *rows, HYPRE_Int *ncols); /** * Gets values for {\tt nrows} rows or partial rows of the matrix. * Usage details are * analogous to \Ref{HYPRE_IJMatrixSetValues}. **/ HYPRE_Int HYPRE_IJMatrixGetValues(HYPRE_IJMatrix matrix, HYPRE_Int nrows, HYPRE_Int *ncols, HYPRE_Int *rows, HYPRE_Int *cols, HYPRE_Complex *values); /** * Set the storage type of the matrix object to be constructed. * Currently, {\tt type} can only be {\tt HYPRE\_PARCSR}. * * Not collective, but must be the same on all processes. * * @see HYPRE_IJMatrixGetObject **/ HYPRE_Int HYPRE_IJMatrixSetObjectType(HYPRE_IJMatrix matrix, HYPRE_Int type); /** * Get the storage type of the constructed matrix object. **/ HYPRE_Int HYPRE_IJMatrixGetObjectType(HYPRE_IJMatrix matrix, HYPRE_Int *type); /** * Gets range of rows owned by this processor and range * of column partitioning for this processor. **/ HYPRE_Int HYPRE_IJMatrixGetLocalRange(HYPRE_IJMatrix matrix, HYPRE_Int *ilower, HYPRE_Int *iupper, HYPRE_Int *jlower, HYPRE_Int *jupper); /** * Get a reference to the constructed matrix object. * * @see HYPRE_IJMatrixSetObjectType **/ HYPRE_Int HYPRE_IJMatrixGetObject(HYPRE_IJMatrix matrix, void **object); /** * (Optional) Set the max number of nonzeros to expect in each row. * The array {\tt sizes} contains estimated sizes for each row on this * process. This call can significantly improve the efficiency of * matrix construction, and should always be utilized if possible. * * Not collective. **/ HYPRE_Int HYPRE_IJMatrixSetRowSizes(HYPRE_IJMatrix matrix, const HYPRE_Int *sizes); /** * (Optional) Sets the exact number of nonzeros in each row of * the diagonal and off-diagonal blocks. The diagonal block is the * submatrix whose column numbers correspond to rows owned by this * process, and the off-diagonal block is everything else. The arrays * {\tt diag\_sizes} and {\tt offdiag\_sizes} contain estimated sizes * for each row of the diagonal and off-diagonal blocks, respectively. * This routine can significantly improve the efficiency of matrix * construction, and should always be utilized if possible. * * Not collective. **/ HYPRE_Int HYPRE_IJMatrixSetDiagOffdSizes(HYPRE_IJMatrix matrix, const HYPRE_Int *diag_sizes, const HYPRE_Int *offdiag_sizes); /** * (Optional) Sets the maximum number of elements that are expected to be set * (or added) on other processors from this processor * This routine can significantly improve the efficiency of matrix * construction, and should always be utilized if possible. * * Not collective. **/ HYPRE_Int HYPRE_IJMatrixSetMaxOffProcElmts(HYPRE_IJMatrix matrix, HYPRE_Int max_off_proc_elmts); /** * (Optional) Sets the print level, if the user wants to print * error messages. The default is 0, i.e. no error messages are printed. * **/ HYPRE_Int HYPRE_IJMatrixSetPrintLevel(HYPRE_IJMatrix matrix, HYPRE_Int print_level); /** * (Optional) if set, will use a threaded version of * HYPRE_IJMatrixSetValues and HYPRE_IJMatrixAddToValues. * This is only useful if a large number of rows is set or added to * at once. * * NOTE that the values in the rows array of HYPRE_IJMatrixSetValues * or HYPRE_IJMatrixAddToValues must be different from each other !!! * * This option is VERY inefficient if only a small number of rows * is set or added at once and/or * if reallocation of storage is required and/or * if values are added to off processor values. * **/ HYPRE_Int HYPRE_IJMatrixSetOMPFlag(HYPRE_IJMatrix matrix, HYPRE_Int omp_flag); /** * Read the matrix from file. This is mainly for debugging purposes. **/ HYPRE_Int HYPRE_IJMatrixRead(const char *filename, MPI_Comm comm, HYPRE_Int type, HYPRE_IJMatrix *matrix); /** * Print the matrix to file. This is mainly for debugging purposes. **/ HYPRE_Int HYPRE_IJMatrixPrint(HYPRE_IJMatrix matrix, const char *filename); /*@}*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name IJ Vectors **/ /*@{*/ struct hypre_IJVector_struct; /** * The vector object. **/ typedef struct hypre_IJVector_struct *HYPRE_IJVector; /** * Create a vector object. Each process owns some unique consecutive * range of vector unknowns, indicated by the global indices {\tt * jlower} and {\tt jupper}. The data is required to be such that the * value of {\tt jlower} on any process $p$ be exactly one more than * the value of {\tt jupper} on process $p-1$. Note that the first * index of the global vector may start with any integer value. In * particular, one may use zero- or one-based indexing. * * Collective. **/ HYPRE_Int HYPRE_IJVectorCreate(MPI_Comm comm, HYPRE_Int jlower, HYPRE_Int jupper, HYPRE_IJVector *vector); /** * Destroy a vector object. An object should be explicitly destroyed * using this destructor when the user's code no longer needs direct * access to it. Once destroyed, the object must not be referenced * again. Note that the object may not be deallocated at the * completion of this call, since there may be internal package * references to the object. The object will then be destroyed when * all internal reference counts go to zero. **/ HYPRE_Int HYPRE_IJVectorDestroy(HYPRE_IJVector vector); /** * Prepare a vector object for setting coefficient values. This * routine will also re-initialize an already assembled vector, * allowing users to modify coefficient values. **/ HYPRE_Int HYPRE_IJVectorInitialize(HYPRE_IJVector vector); /** * (Optional) Sets the maximum number of elements that are expected to be set * (or added) on other processors from this processor * This routine can significantly improve the efficiency of matrix * construction, and should always be utilized if possible. * * Not collective. **/ HYPRE_Int HYPRE_IJVectorSetMaxOffProcElmts(HYPRE_IJVector vector, HYPRE_Int max_off_proc_elmts); /** * Sets values in vector. The arrays {\tt values} and {\tt indices} * are of dimension {\tt nvalues} and contain the vector values to be * set and the corresponding global vector indices, respectively. * Erases any previous values at the specified locations and replaces * them with new ones. Note that it is not possible to set values * on other processors. If one tries to set a value from proc i on proc j, * proc i will erase all previous occurrences of this value in its stack * (including values generated with AddToValues), and treat it like * a zero value. The actual value needs to be set on proc j. * * Not collective. **/ HYPRE_Int HYPRE_IJVectorSetValues(HYPRE_IJVector vector, HYPRE_Int nvalues, const HYPRE_Int *indices, const HYPRE_Complex *values); /** * Adds to values in vector. Usage details are analogous to * \Ref{HYPRE_IJVectorSetValues}. * Adds to any previous values at the specified locations, or, if * there was no value there before, inserts a new one. * AddToValues can be used to add to values on other processors. * * Not collective. **/ HYPRE_Int HYPRE_IJVectorAddToValues(HYPRE_IJVector vector, HYPRE_Int nvalues, const HYPRE_Int *indices, const HYPRE_Complex *values); /** * Finalize the construction of the vector before using. **/ HYPRE_Int HYPRE_IJVectorAssemble(HYPRE_IJVector vector); /** * Gets values in vector. Usage details are analogous to * \Ref{HYPRE_IJVectorSetValues}. * * Not collective. **/ HYPRE_Int HYPRE_IJVectorGetValues(HYPRE_IJVector vector, HYPRE_Int nvalues, const HYPRE_Int *indices, HYPRE_Complex *values); /** * Set the storage type of the vector object to be constructed. * Currently, {\tt type} can only be {\tt HYPRE\_PARCSR}. * * Not collective, but must be the same on all processes. * * @see HYPRE_IJVectorGetObject **/ HYPRE_Int HYPRE_IJVectorSetObjectType(HYPRE_IJVector vector, HYPRE_Int type); /** * Get the storage type of the constructed vector object. **/ HYPRE_Int HYPRE_IJVectorGetObjectType(HYPRE_IJVector vector, HYPRE_Int *type); /** * Returns range of the part of the vector owned by this processor. **/ HYPRE_Int HYPRE_IJVectorGetLocalRange(HYPRE_IJVector vector, HYPRE_Int *jlower, HYPRE_Int *jupper); /** * Get a reference to the constructed vector object. * * @see HYPRE_IJVectorSetObjectType **/ HYPRE_Int HYPRE_IJVectorGetObject(HYPRE_IJVector vector, void **object); /** * (Optional) Sets the print level, if the user wants to print * error messages. The default is 0, i.e. no error messages are printed. * **/ HYPRE_Int HYPRE_IJVectorSetPrintLevel(HYPRE_IJVector vector, HYPRE_Int print_level); /** * Read the vector from file. This is mainly for debugging purposes. **/ HYPRE_Int HYPRE_IJVectorRead(const char *filename, MPI_Comm comm, HYPRE_Int type, HYPRE_IJVector *vector); /** * Print the vector to file. This is mainly for debugging purposes. **/ HYPRE_Int HYPRE_IJVectorPrint(HYPRE_IJVector vector, const char *filename); /*@}*/ /*@}*/ #ifdef __cplusplus } #endif #endif
17,922
37.297009
81
h
AMG
AMG-master/IJ_mv/IJMatrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * hypre_IJMatrix interface * *****************************************************************************/ #include "./_hypre_IJ_mv.h" #include "../HYPRE.h" /*-------------------------------------------------------------------------- * hypre_IJMatrixGetRowPartitioning *--------------------------------------------------------------------------*/ /** Returns a pointer to the row partitioning @return integer error code @param IJMatrix [IN] The ijmatrix to be pointed to. */ HYPRE_Int hypre_IJMatrixGetRowPartitioning( HYPRE_IJMatrix matrix , HYPRE_Int **row_partitioning ) { hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix; if (!ijmatrix) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Variable ijmatrix is NULL -- hypre_IJMatrixGetRowPartitioning\n"); return hypre_error_flag; } if ( hypre_IJMatrixRowPartitioning(ijmatrix)) *row_partitioning = hypre_IJMatrixRowPartitioning(ijmatrix); else { hypre_error(HYPRE_ERROR_GENERIC); return hypre_error_flag; } return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_IJMatrixGetColPartitioning *--------------------------------------------------------------------------*/ /** Returns a pointer to the column partitioning @return integer error code @param IJMatrix [IN] The ijmatrix to be pointed to. */ HYPRE_Int hypre_IJMatrixGetColPartitioning( HYPRE_IJMatrix matrix , HYPRE_Int **col_partitioning ) { hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix; if (!ijmatrix) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Variable ijmatrix is NULL -- hypre_IJMatrixGetColPartitioning\n"); return hypre_error_flag; } if ( hypre_IJMatrixColPartitioning(ijmatrix)) *col_partitioning = hypre_IJMatrixColPartitioning(ijmatrix); else { hypre_error(HYPRE_ERROR_GENERIC); return hypre_error_flag; } return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_IJMatrixSetObject *--------------------------------------------------------------------------*/ HYPRE_Int hypre_IJMatrixSetObject( HYPRE_IJMatrix matrix, void *object ) { hypre_IJMatrix *ijmatrix = (hypre_IJMatrix *) matrix; if (hypre_IJMatrixObject(ijmatrix) != NULL) { /*hypre_printf("Referencing a new IJMatrix object can orphan an old -- "); hypre_printf("hypre_IJMatrixSetObject\n");*/ hypre_error(HYPRE_ERROR_GENERIC); return hypre_error_flag; } hypre_IJMatrixObject(ijmatrix) = object; return hypre_error_flag; }
3,668
29.322314
111
c
AMG
AMG-master/IJ_mv/IJVector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * hypre_IJVector interface * *****************************************************************************/ #include "./_hypre_IJ_mv.h" #include "../HYPRE.h" /*-------------------------------------------------------------------------- * hypre_IJVectorDistribute *--------------------------------------------------------------------------*/ HYPRE_Int hypre_IJVectorDistribute( HYPRE_IJVector vector, const HYPRE_Int *vec_starts ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (vec == NULL) { hypre_printf("Vector variable is NULL -- hypre_IJVectorDistribute\n"); exit(1); } if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) return( hypre_IJVectorDistributePar(vec, vec_starts) ); else { hypre_printf("Unrecognized object type -- hypre_IJVectorDistribute\n"); exit(1); } return -99; } /*-------------------------------------------------------------------------- * hypre_IJVectorZeroValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_IJVectorZeroValues( HYPRE_IJVector vector ) { hypre_IJVector *vec = (hypre_IJVector *) vector; if (vec == NULL) { hypre_printf("Vector variable is NULL -- hypre_IJVectorZeroValues\n"); exit(1); } /* if ( hypre_IJVectorObjectType(vec) == HYPRE_PETSC ) return( hypre_IJVectorZeroValuesPETSc(vec) ); else if ( hypre_IJVectorObjectType(vec) == HYPRE_ISIS ) return( hypre_IJVectorZeroValuesISIS(vec) ); else */ if ( hypre_IJVectorObjectType(vec) == HYPRE_PARCSR ) return( hypre_IJVectorZeroValuesPar(vec) ); else { hypre_printf("Unrecognized object type -- hypre_IJVectorZeroValues\n"); exit(1); } return -99; }
2,778
27.947917
81
c
AMG
AMG-master/IJ_mv/IJ_assumed_part.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*---------------------------------------------------- * Functions for the IJ assumed partition fir IJ_Matrix *-----------------------------------------------------*/ #include "_hypre_IJ_mv.h" /*------------------------------------------------------------------ * hypre_IJMatrixCreateAssumedPartition - * Each proc gets it own range. Then * each needs to reconcile its actual range with its assumed * range - the result is essentila a partition of its assumed range - * this is the assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_IJMatrixCreateAssumedPartition( hypre_IJMatrix *matrix) { HYPRE_Int global_num_rows; HYPRE_Int global_first_row; HYPRE_Int myid; HYPRE_Int row_start = 0, row_end = 0; HYPRE_Int *row_partitioning = hypre_IJMatrixRowPartitioning(matrix); MPI_Comm comm; hypre_IJAssumedPart *apart; global_num_rows = hypre_IJMatrixGlobalNumRows(matrix); global_first_row = hypre_IJMatrixGlobalFirstRow(matrix); comm = hypre_IJMatrixComm(matrix); /* find out my actual range of rows and rowumns */ row_start = row_partitioning[0]; row_end = row_partitioning[1]-1; hypre_MPI_Comm_rank(comm, &myid ); /* allocate space */ apart = hypre_CTAlloc(hypre_IJAssumedPart, 1); /* get my assumed partitioning - we want row partitioning of the matrix for off processor values - so we use the row start and end Note that this is different from the assumed partitioning for the parcsr matrix which needs it for matvec multiplications and therefore needs to do it for the col partitioning */ hypre_GetAssumedPartitionRowRange( comm, myid, global_first_row, global_num_rows, &(apart->row_start), &(apart->row_end)); /*allocate some space for the partition of the assumed partition */ apart->length = 0; /*room for 10 owners of the assumed partition*/ apart->storage_length = 10; /*need to be >=1 */ apart->proc_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_start_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_end_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); /* now we want to reconcile our actual partition with the assumed partition */ hypre_LocateAssummedPartition(comm, row_start, row_end, global_first_row, global_num_rows, apart, myid); /* this partition will be saved in the matrix data structure until the matrix is destroyed */ hypre_IJMatrixAssumedPart(matrix) = apart; return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_IJVectorCreateAssumedPartition - * Essentially the same as for a matrix! * Each proc gets it own range. Then * each needs to reconcile its actual range with its assumed * range - the result is essentila a partition of its assumed range - * this is the assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_IJVectorCreateAssumedPartition( hypre_IJVector *vector) { HYPRE_Int global_num, global_first_row; HYPRE_Int myid; HYPRE_Int start=0, end=0; HYPRE_Int *partitioning = hypre_IJVectorPartitioning(vector); MPI_Comm comm; hypre_IJAssumedPart *apart; global_num = hypre_IJVectorGlobalNumRows(vector); global_first_row = hypre_IJVectorGlobalFirstRow(vector); comm = hypre_ParVectorComm(vector); /* find out my actualy range of rows */ start = partitioning[0]; end = partitioning[1]-1; hypre_MPI_Comm_rank(comm, &myid ); /* allocate space */ apart = hypre_CTAlloc(hypre_IJAssumedPart, 1); /* get my assumed partitioning - we want partitioning of the vector that the matrix multiplies - so we use the col start and end */ hypre_GetAssumedPartitionRowRange( comm, myid, global_first_row, global_num, &(apart->row_start), &(apart->row_end)); /*allocate some space for the partition of the assumed partition */ apart->length = 0; /*room for 10 owners of the assumed partition*/ apart->storage_length = 10; /*need to be >=1 */ apart->proc_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_start_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_end_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); /* now we want to reconcile our actual partition with the assumed partition */ hypre_LocateAssummedPartition(comm, start, end, global_first_row, global_num, apart, myid); /* this partition will be saved in the vector data structure until the vector is destroyed */ hypre_IJVectorAssumedPart(vector) = apart; return hypre_error_flag; }
5,686
35.22293
97
c
AMG
AMG-master/IJ_mv/IJ_matrix.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for the hypre_IJMatrix structures * *****************************************************************************/ #ifndef hypre_IJ_MATRIX_HEADER #define hypre_IJ_MATRIX_HEADER /*-------------------------------------------------------------------------- * hypre_IJMatrix: *--------------------------------------------------------------------------*/ typedef struct hypre_IJMatrix_struct { MPI_Comm comm; HYPRE_Int *row_partitioning; /* distribution of rows across processors */ HYPRE_Int *col_partitioning; /* distribution of columns */ HYPRE_Int object_type; /* Indicates the type of "object" */ void *object; /* Structure for storing local portion */ void *translator; /* optional storage_type specfic structure for holding additional local info */ void *assumed_part; /* IJMatrix assumed partition */ HYPRE_Int assemble_flag; /* indicates whether matrix has been assembled */ HYPRE_Int global_first_row; /* these for data items are necessary */ HYPRE_Int global_first_col; /* to be able to avoind using the global */ HYPRE_Int global_num_rows; /* global partition */ HYPRE_Int global_num_cols; HYPRE_Int omp_flag; HYPRE_Int print_level; } hypre_IJMatrix; /*-------------------------------------------------------------------------- * Accessor macros: hypre_IJMatrix *--------------------------------------------------------------------------*/ #define hypre_IJMatrixComm(matrix) ((matrix) -> comm) #define hypre_IJMatrixRowPartitioning(matrix) ((matrix) -> row_partitioning) #define hypre_IJMatrixColPartitioning(matrix) ((matrix) -> col_partitioning) #define hypre_IJMatrixObjectType(matrix) ((matrix) -> object_type) #define hypre_IJMatrixObject(matrix) ((matrix) -> object) #define hypre_IJMatrixTranslator(matrix) ((matrix) -> translator) #define hypre_IJMatrixAssumedPart(matrix) ((matrix) -> assumed_part) #define hypre_IJMatrixAssembleFlag(matrix) ((matrix) -> assemble_flag) #define hypre_IJMatrixGlobalFirstRow(matrix) ((matrix) -> global_first_row) #define hypre_IJMatrixGlobalFirstCol(matrix) ((matrix) -> global_first_col) #define hypre_IJMatrixGlobalNumRows(matrix) ((matrix) -> global_num_rows) #define hypre_IJMatrixGlobalNumCols(matrix) ((matrix) -> global_num_cols) #define hypre_IJMatrixOMPFlag(matrix) ((matrix) -> omp_flag) #define hypre_IJMatrixPrintLevel(matrix) ((matrix) -> print_level) /*-------------------------------------------------------------------------- * prototypes for operations on local objects *--------------------------------------------------------------------------*/ #ifdef PETSC_AVAILABLE /* IJMatrix_petsc.c */ HYPRE_Int hypre_GetIJMatrixParCSRMatrix( HYPRE_IJMatrix IJmatrix, Mat *reference ) #endif #ifdef ISIS_AVAILABLE /* IJMatrix_isis.c */ HYPRE_Int hypre_GetIJMatrixISISMatrix( HYPRE_IJMatrix IJmatrix, RowMatrix *reference ) #endif #endif
4,194
41.373737
87
h
AMG
AMG-master/IJ_mv/IJ_vector.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for the hypre_IJMatrix structures * *****************************************************************************/ #ifndef hypre_IJ_VECTOR_HEADER #define hypre_IJ_VECTOR_HEADER /*-------------------------------------------------------------------------- * hypre_IJVector: *--------------------------------------------------------------------------*/ typedef struct hypre_IJVector_struct { MPI_Comm comm; HYPRE_Int *partitioning; /* Indicates partitioning over tasks */ HYPRE_Int object_type; /* Indicates the type of "local storage" */ void *object; /* Structure for storing local portion */ void *translator; /* Structure for storing off processor information */ void *assumed_part; /* IJ Vector assumed partition */ HYPRE_Int global_first_row; /* these for data items are necessary */ HYPRE_Int global_num_rows; /* to be able to avoid using the global */ /* global partition */ HYPRE_Int print_level; } hypre_IJVector; /*-------------------------------------------------------------------------- * Accessor macros: hypre_IJVector *--------------------------------------------------------------------------*/ #define hypre_IJVectorComm(vector) ((vector) -> comm) #define hypre_IJVectorPartitioning(vector) ((vector) -> partitioning) #define hypre_IJVectorObjectType(vector) ((vector) -> object_type) #define hypre_IJVectorObject(vector) ((vector) -> object) #define hypre_IJVectorTranslator(vector) ((vector) -> translator) #define hypre_IJVectorAssumedPart(vector) ((vector) -> assumed_part) #define hypre_IJVectorGlobalFirstRow(vector) ((vector) -> global_first_row) #define hypre_IJVectorGlobalNumRows(vector) ((vector) -> global_num_rows) #define hypre_IJVectorPrintLevel(vector) ((vector) -> print_level) /*-------------------------------------------------------------------------- * prototypes for operations on local objects *--------------------------------------------------------------------------*/ /* #include "./internal_protos.h" */ #endif
3,239
36.674419
86
h
AMG
AMG-master/IJ_mv/aux_par_vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_AuxParVector class. * *****************************************************************************/ #include "_hypre_IJ_mv.h" #include "aux_par_vector.h" /*-------------------------------------------------------------------------- * hypre_AuxParVectorCreate *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParVectorCreate( hypre_AuxParVector **aux_vector) { hypre_AuxParVector *vector; vector = hypre_CTAlloc(hypre_AuxParVector, 1); /* set defaults */ hypre_AuxParVectorMaxOffProcElmts(vector) = 0; hypre_AuxParVectorCurrentNumElmts(vector) = 0; /* stash for setting or adding off processor values */ hypre_AuxParVectorOffProcI(vector) = NULL; hypre_AuxParVectorOffProcData(vector) = NULL; *aux_vector = vector; return 0; } /*-------------------------------------------------------------------------- * hypre_AuxParVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParVectorDestroy( hypre_AuxParVector *vector ) { HYPRE_Int ierr=0; if (vector) { if (hypre_AuxParVectorOffProcI(vector)) hypre_TFree(hypre_AuxParVectorOffProcI(vector)); if (hypre_AuxParVectorOffProcData(vector)) hypre_TFree(hypre_AuxParVectorOffProcData(vector)); hypre_TFree(vector); } return ierr; } /*-------------------------------------------------------------------------- * hypre_AuxParVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParVectorInitialize( hypre_AuxParVector *vector ) { HYPRE_Int max_off_proc_elmts = hypre_AuxParVectorMaxOffProcElmts(vector); /* allocate stash for setting or adding off processor values */ if (max_off_proc_elmts > 0) { hypre_AuxParVectorOffProcI(vector) = hypre_CTAlloc(HYPRE_Int, max_off_proc_elmts); hypre_AuxParVectorOffProcData(vector) = hypre_CTAlloc(HYPRE_Complex, max_off_proc_elmts); } return 0; } /*-------------------------------------------------------------------------- * hypre_AuxParVectorSetMaxOffProcElmts *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParVectorSetMaxOffPRocElmts( hypre_AuxParVector *vector, HYPRE_Int max_off_proc_elmts ) { HYPRE_Int ierr = 0; hypre_AuxParVectorMaxOffProcElmts(vector) = max_off_proc_elmts; return ierr; }
3,643
33.704762
81
c
AMG
AMG-master/IJ_mv/aux_par_vector.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for Auxiliary Parallel Vector data structures * * Note: this vector currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_AUX_PAR_VECTOR_HEADER #define hypre_AUX_PAR_VECTOR_HEADER /*-------------------------------------------------------------------------- * Auxiliary Parallel Vector *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Int max_off_proc_elmts; /* length of off processor stash for SetValues and AddToValues*/ HYPRE_Int current_num_elmts; /* current no. of elements stored in stash */ HYPRE_Int *off_proc_i; /* contains column indices */ HYPRE_Complex *off_proc_data; /* contains corresponding data */ HYPRE_Int cancel_indx; /* number of elements that have to be deleted due to setting values from another processor */ } hypre_AuxParVector; /*-------------------------------------------------------------------------- * Accessor functions for the Parallel Vector structure *--------------------------------------------------------------------------*/ #define hypre_AuxParVectorMaxOffProcElmts(matrix) ((matrix) -> max_off_proc_elmts) #define hypre_AuxParVectorCurrentNumElmts(matrix) ((matrix) -> current_num_elmts) #define hypre_AuxParVectorOffProcI(matrix) ((matrix) -> off_proc_i) #define hypre_AuxParVectorOffProcData(matrix) ((matrix) -> off_proc_data) #define hypre_AuxParVectorCancelIndx(matrix) ((matrix) -> cancel_indx) #endif
2,631
46.854545
83
h
AMG
AMG-master/IJ_mv/aux_parcsr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_AuxParCSRMatrix class. * *****************************************************************************/ #include "_hypre_IJ_mv.h" #include "aux_parcsr_matrix.h" /*-------------------------------------------------------------------------- * hypre_AuxParCSRMatrixCreate *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParCSRMatrixCreate( hypre_AuxParCSRMatrix **aux_matrix, HYPRE_Int local_num_rows, HYPRE_Int local_num_cols, HYPRE_Int *sizes) { hypre_AuxParCSRMatrix *matrix; matrix = hypre_CTAlloc(hypre_AuxParCSRMatrix, 1); hypre_AuxParCSRMatrixLocalNumRows(matrix) = local_num_rows; hypre_AuxParCSRMatrixLocalNumCols(matrix) = local_num_cols; if (sizes) { hypre_AuxParCSRMatrixRowSpace(matrix) = sizes; } else { hypre_AuxParCSRMatrixRowSpace(matrix) = NULL; } /* set defaults */ hypre_AuxParCSRMatrixNeedAux(matrix) = 1; hypre_AuxParCSRMatrixMaxOffProcElmts(matrix) = 0; hypre_AuxParCSRMatrixCurrentNumElmts(matrix) = 0; hypre_AuxParCSRMatrixOffProcIIndx(matrix) = 0; hypre_AuxParCSRMatrixRowLength(matrix) = NULL; hypre_AuxParCSRMatrixAuxJ(matrix) = NULL; hypre_AuxParCSRMatrixAuxData(matrix) = NULL; hypre_AuxParCSRMatrixIndxDiag(matrix) = NULL; hypre_AuxParCSRMatrixIndxOffd(matrix) = NULL; /* stash for setting or adding off processor values */ hypre_AuxParCSRMatrixOffProcI(matrix) = NULL; hypre_AuxParCSRMatrixOffProcJ(matrix) = NULL; hypre_AuxParCSRMatrixOffProcData(matrix) = NULL; *aux_matrix = matrix; return 0; } /*-------------------------------------------------------------------------- * hypre_AuxParCSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParCSRMatrixDestroy( hypre_AuxParCSRMatrix *matrix ) { HYPRE_Int ierr=0; HYPRE_Int i; HYPRE_Int num_rows; if (matrix) { num_rows = hypre_AuxParCSRMatrixLocalNumRows(matrix); if (hypre_AuxParCSRMatrixRowLength(matrix)) hypre_TFree(hypre_AuxParCSRMatrixRowLength(matrix)); if (hypre_AuxParCSRMatrixRowSpace(matrix)) hypre_TFree(hypre_AuxParCSRMatrixRowSpace(matrix)); if (hypre_AuxParCSRMatrixAuxJ(matrix)) { for (i=0; i < num_rows; i++) hypre_TFree(hypre_AuxParCSRMatrixAuxJ(matrix)[i]); hypre_TFree(hypre_AuxParCSRMatrixAuxJ(matrix)); } if (hypre_AuxParCSRMatrixAuxData(matrix)) { for (i=0; i < num_rows; i++) hypre_TFree(hypre_AuxParCSRMatrixAuxData(matrix)[i]); hypre_TFree(hypre_AuxParCSRMatrixAuxData(matrix)); } if (hypre_AuxParCSRMatrixIndxDiag(matrix)) hypre_TFree(hypre_AuxParCSRMatrixIndxDiag(matrix)); if (hypre_AuxParCSRMatrixIndxOffd(matrix)) hypre_TFree(hypre_AuxParCSRMatrixIndxOffd(matrix)); if (hypre_AuxParCSRMatrixOffProcI(matrix)) hypre_TFree(hypre_AuxParCSRMatrixOffProcI(matrix)); if (hypre_AuxParCSRMatrixOffProcJ(matrix)) hypre_TFree(hypre_AuxParCSRMatrixOffProcJ(matrix)); if (hypre_AuxParCSRMatrixOffProcData(matrix)) hypre_TFree(hypre_AuxParCSRMatrixOffProcData(matrix)); hypre_TFree(matrix); } return ierr; } /*-------------------------------------------------------------------------- * hypre_AuxParCSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParCSRMatrixInitialize( hypre_AuxParCSRMatrix *matrix ) { HYPRE_Int local_num_rows = hypre_AuxParCSRMatrixLocalNumRows(matrix); HYPRE_Int *row_space = hypre_AuxParCSRMatrixRowSpace(matrix); HYPRE_Int max_off_proc_elmts = hypre_AuxParCSRMatrixMaxOffProcElmts(matrix); HYPRE_Int **aux_j; HYPRE_Complex **aux_data; HYPRE_Int i; if (local_num_rows < 0) return -1; if (local_num_rows == 0) return 0; /* allocate stash for setting or adding off processor values */ if (max_off_proc_elmts > 0) { hypre_AuxParCSRMatrixOffProcI(matrix) = hypre_CTAlloc(HYPRE_Int, 2*max_off_proc_elmts); hypre_AuxParCSRMatrixOffProcJ(matrix) = hypre_CTAlloc(HYPRE_Int, max_off_proc_elmts); hypre_AuxParCSRMatrixOffProcData(matrix) = hypre_CTAlloc(HYPRE_Complex, max_off_proc_elmts); } if (hypre_AuxParCSRMatrixNeedAux(matrix)) { aux_j = hypre_CTAlloc(HYPRE_Int *, local_num_rows); aux_data = hypre_CTAlloc(HYPRE_Complex *, local_num_rows); if (!hypre_AuxParCSRMatrixRowLength(matrix)) hypre_AuxParCSRMatrixRowLength(matrix) = hypre_CTAlloc(HYPRE_Int, local_num_rows); if (row_space) { for (i=0; i < local_num_rows; i++) { aux_j[i] = hypre_CTAlloc(HYPRE_Int, row_space[i]); aux_data[i] = hypre_CTAlloc(HYPRE_Complex, row_space[i]); } } else { row_space = hypre_CTAlloc(HYPRE_Int, local_num_rows); for (i=0; i < local_num_rows; i++) { row_space[i] = 30; aux_j[i] = hypre_CTAlloc(HYPRE_Int, 30); aux_data[i] = hypre_CTAlloc(HYPRE_Complex, 30); } hypre_AuxParCSRMatrixRowSpace(matrix) = row_space; } hypre_AuxParCSRMatrixAuxJ(matrix) = aux_j; hypre_AuxParCSRMatrixAuxData(matrix) = aux_data; } else { hypre_AuxParCSRMatrixIndxDiag(matrix) = hypre_CTAlloc(HYPRE_Int,local_num_rows); hypre_AuxParCSRMatrixIndxOffd(matrix) = hypre_CTAlloc(HYPRE_Int,local_num_rows); } return 0; } /*-------------------------------------------------------------------------- * hypre_AuxParCSRMatrixSetMaxOffProcElmts *--------------------------------------------------------------------------*/ HYPRE_Int hypre_AuxParCSRMatrixSetMaxOffPRocElmts( hypre_AuxParCSRMatrix *matrix, HYPRE_Int max_off_proc_elmts ) { HYPRE_Int ierr = 0; hypre_AuxParCSRMatrixMaxOffProcElmts(matrix) = max_off_proc_elmts; return ierr; }
7,057
34.646465
86
c
AMG
AMG-master/IJ_mv/aux_parcsr_matrix.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for Auxiliary Parallel CSR Matrix data structures * * Note: this matrix currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_AUX_PARCSR_MATRIX_HEADER #define hypre_AUX_PARCSR_MATRIX_HEADER /*-------------------------------------------------------------------------- * Auxiliary Parallel CSR Matrix *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Int local_num_rows; /* defines number of rows on this processors */ HYPRE_Int local_num_cols; /* defines number of cols of diag */ HYPRE_Int need_aux; /* if need_aux = 1, aux_j, aux_data are used to generate the parcsr matrix (default), for need_aux = 0, data is put directly into parcsr structure (requires the knowledge of offd_i and diag_i ) */ HYPRE_Int *row_length; /* row_length_diag[i] contains number of stored elements in i-th row */ HYPRE_Int *row_space; /* row_space_diag[i] contains space allocated to i-th row */ HYPRE_Int **aux_j; /* contains collected column indices */ HYPRE_Complex **aux_data; /* contains collected data */ HYPRE_Int *indx_diag; /* indx_diag[i] points to first empty space of portion in diag_j , diag_data assigned to row i */ HYPRE_Int *indx_offd; /* indx_offd[i] points to first empty space of portion in offd_j , offd_data assigned to row i */ HYPRE_Int max_off_proc_elmts; /* length of off processor stash set for SetValues and AddTOValues */ HYPRE_Int current_num_elmts; /* current no. of elements stored in stash */ HYPRE_Int off_proc_i_indx; /* pointer to first empty space in set_off_proc_i_set */ HYPRE_Int *off_proc_i; /* length 2*num_off_procs_elmts, contains info pairs (code, no. of elmts) where code contains global row no. if SetValues, and (-global row no. -1) if AddToValues*/ HYPRE_Int *off_proc_j; /* contains column indices */ HYPRE_Complex *off_proc_data; /* contains corresponding data */ HYPRE_Int cancel_indx; /* number of elements that have to be deleted due to setting values from another processor */ } hypre_AuxParCSRMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the Parallel CSR Matrix structure *--------------------------------------------------------------------------*/ #define hypre_AuxParCSRMatrixLocalNumRows(matrix) ((matrix) -> local_num_rows) #define hypre_AuxParCSRMatrixLocalNumCols(matrix) ((matrix) -> local_num_cols) #define hypre_AuxParCSRMatrixNeedAux(matrix) ((matrix) -> need_aux) #define hypre_AuxParCSRMatrixRowLength(matrix) ((matrix) -> row_length) #define hypre_AuxParCSRMatrixRowSpace(matrix) ((matrix) -> row_space) #define hypre_AuxParCSRMatrixAuxJ(matrix) ((matrix) -> aux_j) #define hypre_AuxParCSRMatrixAuxData(matrix) ((matrix) -> aux_data) #define hypre_AuxParCSRMatrixIndxDiag(matrix) ((matrix) -> indx_diag) #define hypre_AuxParCSRMatrixIndxOffd(matrix) ((matrix) -> indx_offd) #define hypre_AuxParCSRMatrixMaxOffProcElmts(matrix) ((matrix) -> max_off_proc_elmts) #define hypre_AuxParCSRMatrixCurrentNumElmts(matrix) ((matrix) -> current_num_elmts) #define hypre_AuxParCSRMatrixOffProcIIndx(matrix) ((matrix) -> off_proc_i_indx) #define hypre_AuxParCSRMatrixOffProcI(matrix) ((matrix) -> off_proc_i) #define hypre_AuxParCSRMatrixOffProcJ(matrix) ((matrix) -> off_proc_j) #define hypre_AuxParCSRMatrixOffProcData(matrix) ((matrix) -> off_proc_data) #define hypre_AuxParCSRMatrixCancelIndx(matrix) ((matrix) -> cancel_indx) #endif
5,131
53.021053
86
h
AMG
AMG-master/IJ_mv/headers.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "_hypre_IJ_mv.h" #include "HYPRE_IJ_mv.h"
1,038
36.107143
81
h
AMG
AMG-master/krylov/HYPRE_MatvecFunctions.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef HYPRE_MATVEC_FUNCTIONS #define HYPRE_MATVEC_FUNCTIONS typedef struct { void* (*MatvecCreate) ( void *A, void *x ); HYPRE_Int (*Matvec) ( void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ); HYPRE_Int (*MatvecDestroy) ( void *matvec_data ); void* (*MatMultiVecCreate) ( void *A, void *x ); HYPRE_Int (*MatMultiVec) ( void *data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ); HYPRE_Int (*MatMultiVecDestroy) ( void *data ); } HYPRE_MatvecFunctions; #endif
1,565
42.5
81
h
AMG
AMG-master/krylov/HYPRE_gmres.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_GMRES interface * *****************************************************************************/ #include "krylov.h" /*-------------------------------------------------------------------------- * HYPRE_GMRESDestroy *--------------------------------------------------------------------------*/ /* to do, not trivial */ /* HYPRE_Int HYPRE_ParCSRGMRESDestroy( HYPRE_Solver solver ) { return( hypre_GMRESDestroy( (void *) solver ) ); } */ /*-------------------------------------------------------------------------- * HYPRE_GMRESSetup *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetup( HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x ) { return( hypre_GMRESSetup( solver, A, b, x ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSolve *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSolve( HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x ) { return( hypre_GMRESSolve( solver, A, b, x ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetKDim, HYPRE_GMRESGetKDim *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetKDim( HYPRE_Solver solver, HYPRE_Int k_dim ) { return( hypre_GMRESSetKDim( (void *) solver, k_dim ) ); } HYPRE_Int HYPRE_GMRESGetKDim( HYPRE_Solver solver, HYPRE_Int * k_dim ) { return( hypre_GMRESGetKDim( (void *) solver, k_dim ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetTol, HYPRE_GMRESGetTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetTol( HYPRE_Solver solver, HYPRE_Real tol ) { return( hypre_GMRESSetTol( (void *) solver, tol ) ); } HYPRE_Int HYPRE_GMRESGetTol( HYPRE_Solver solver, HYPRE_Real * tol ) { return( hypre_GMRESGetTol( (void *) solver, tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetAbsoluteTol, HYPRE_GMRESGetAbsoluteTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetAbsoluteTol( HYPRE_Solver solver, HYPRE_Real a_tol ) { return( hypre_GMRESSetAbsoluteTol( (void *) solver, a_tol ) ); } HYPRE_Int HYPRE_GMRESGetAbsoluteTol( HYPRE_Solver solver, HYPRE_Real * a_tol ) { return( hypre_GMRESGetAbsoluteTol( (void *) solver, a_tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetConvergenceFactorTol, HYPRE_GMRESGetConvergenceFactorTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetConvergenceFactorTol( HYPRE_Solver solver, HYPRE_Real cf_tol ) { return( hypre_GMRESSetConvergenceFactorTol( (void *) solver, cf_tol ) ); } HYPRE_Int HYPRE_GMRESGetConvergenceFactorTol( HYPRE_Solver solver, HYPRE_Real * cf_tol ) { return( hypre_GMRESGetConvergenceFactorTol( (void *) solver, cf_tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetMinIter, HYPRE_GMRESGetMinIter *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetMinIter( HYPRE_Solver solver, HYPRE_Int min_iter ) { return( hypre_GMRESSetMinIter( (void *) solver, min_iter ) ); } HYPRE_Int HYPRE_GMRESGetMinIter( HYPRE_Solver solver, HYPRE_Int * min_iter ) { return( hypre_GMRESGetMinIter( (void *) solver, min_iter ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetMaxIter, HYPRE_GMRESGetMaxIter *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetMaxIter( HYPRE_Solver solver, HYPRE_Int max_iter ) { return( hypre_GMRESSetMaxIter( (void *) solver, max_iter ) ); } HYPRE_Int HYPRE_GMRESGetMaxIter( HYPRE_Solver solver, HYPRE_Int * max_iter ) { return( hypre_GMRESGetMaxIter( (void *) solver, max_iter ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetStopCrit, HYPRE_GMRESGetStopCrit - OBSOLETE *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetStopCrit( HYPRE_Solver solver, HYPRE_Int stop_crit ) { return( hypre_GMRESSetStopCrit( (void *) solver, stop_crit ) ); } HYPRE_Int HYPRE_GMRESGetStopCrit( HYPRE_Solver solver, HYPRE_Int * stop_crit ) { return( hypre_GMRESGetStopCrit( (void *) solver, stop_crit ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetRelChange, HYPRE_GMRESGetRelChange *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetRelChange( HYPRE_Solver solver, HYPRE_Int rel_change ) { return( hypre_GMRESSetRelChange( (void *) solver, rel_change ) ); } HYPRE_Int HYPRE_GMRESGetRelChange( HYPRE_Solver solver, HYPRE_Int * rel_change ) { return( hypre_GMRESGetRelChange( (void *) solver, rel_change ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetSkipRealResidualCheck, HYPRE_GMRESGetSkipRealResidualCheck *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetSkipRealResidualCheck( HYPRE_Solver solver, HYPRE_Int skip_real_r_check ) { return( hypre_GMRESSetSkipRealResidualCheck( (void *) solver, skip_real_r_check ) ); } HYPRE_Int HYPRE_GMRESGetSkipRealResidualCheck( HYPRE_Solver solver, HYPRE_Int *skip_real_r_check ) { return( hypre_GMRESGetSkipRealResidualCheck( (void *) solver, skip_real_r_check ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetPrecond( HYPRE_Solver solver, HYPRE_PtrToSolverFcn precond, HYPRE_PtrToSolverFcn precond_setup, HYPRE_Solver precond_solver ) { return( hypre_GMRESSetPrecond( (void *) solver, (HYPRE_Int (*)(void*, void*, void*, void*))precond, (HYPRE_Int (*)(void*, void*, void*, void*))precond_setup, (void *) precond_solver ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESGetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESGetPrecond( HYPRE_Solver solver, HYPRE_Solver *precond_data_ptr ) { return( hypre_GMRESGetPrecond( (void *) solver, (HYPRE_Solver *) precond_data_ptr ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetPrintLevel, HYPRE_GMRESGetPrintLevel *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetPrintLevel( HYPRE_Solver solver, HYPRE_Int level ) { return( hypre_GMRESSetPrintLevel( (void *) solver, level ) ); } HYPRE_Int HYPRE_GMRESGetPrintLevel( HYPRE_Solver solver, HYPRE_Int * level ) { return( hypre_GMRESGetPrintLevel( (void *) solver, level ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESSetLogging, HYPRE_GMRESGetLogging *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESSetLogging( HYPRE_Solver solver, HYPRE_Int level ) { return( hypre_GMRESSetLogging( (void *) solver, level ) ); } HYPRE_Int HYPRE_GMRESGetLogging( HYPRE_Solver solver, HYPRE_Int * level ) { return( hypre_GMRESGetLogging( (void *) solver, level ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESGetNumIterations *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESGetNumIterations( HYPRE_Solver solver, HYPRE_Int *num_iterations ) { return( hypre_GMRESGetNumIterations( (void *) solver, num_iterations ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESGetConverged *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESGetConverged( HYPRE_Solver solver, HYPRE_Int *converged ) { return( hypre_GMRESGetConverged( (void *) solver, converged ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESGetFinalRelativeResidualNorm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESGetFinalRelativeResidualNorm( HYPRE_Solver solver, HYPRE_Real *norm ) { return( hypre_GMRESGetFinalRelativeResidualNorm( (void *) solver, norm ) ); } /*-------------------------------------------------------------------------- * HYPRE_GMRESGetResidual *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_GMRESGetResidual( HYPRE_Solver solver, void **residual ) { /* returns a pointer to the residual vector */ return hypre_GMRESGetResidual( (void *) solver, residual ); }
11,615
33.064516
87
c
AMG
AMG-master/krylov/HYPRE_krylov.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef HYPRE_KRYLOV_HEADER #define HYPRE_KRYLOV_HEADER #include "HYPRE_utilities.h" #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name Krylov Solvers * * These solvers support many of the matrix/vector storage schemes in hypre. * They should be used in conjunction with the storage-specific interfaces, * particularly the specific Create() and Destroy() functions. * * @memo A basic interface for Krylov solvers **/ /*@{*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name Krylov Solvers **/ /*@{*/ #ifndef HYPRE_SOLVER_STRUCT #define HYPRE_SOLVER_STRUCT struct hypre_Solver_struct; /** * The solver object. **/ typedef struct hypre_Solver_struct *HYPRE_Solver; #endif #ifndef HYPRE_MATRIX_STRUCT #define HYPRE_MATRIX_STRUCT struct hypre_Matrix_struct; /** * The matrix object. **/ typedef struct hypre_Matrix_struct *HYPRE_Matrix; #endif #ifndef HYPRE_VECTOR_STRUCT #define HYPRE_VECTOR_STRUCT struct hypre_Vector_struct; /** * The vector object. **/ typedef struct hypre_Vector_struct *HYPRE_Vector; #endif typedef HYPRE_Int (*HYPRE_PtrToSolverFcn)(HYPRE_Solver, HYPRE_Matrix, HYPRE_Vector, HYPRE_Vector); #ifndef HYPRE_MODIFYPC #define HYPRE_MODIFYPC typedef HYPRE_Int (*HYPRE_PtrToModifyPCFcn)(HYPRE_Solver, HYPRE_Int, HYPRE_Real); #endif /*@}*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name PCG Solver **/ /*@{*/ /** * Prepare to solve the system. The coefficient data in {\tt b} and {\tt x} is * ignored here, but information about the layout of the data may be used. **/ HYPRE_Int HYPRE_PCGSetup(HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x); /** * Solve the system. **/ HYPRE_Int HYPRE_PCGSolve(HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x); /** * (Optional) Set the relative convergence tolerance. **/ HYPRE_Int HYPRE_PCGSetTol(HYPRE_Solver solver, HYPRE_Real tol); /** * (Optional) Set the absolute convergence tolerance (default is * 0). If one desires the convergence test to check the absolute * convergence tolerance {\it only}, then set the relative convergence * tolerance to 0.0. (The default convergence test is $ <C*r,r> \leq$ * max(relative$\_$tolerance$^{2} \ast <C*b, b>$, absolute$\_$tolerance$^2$).) **/ HYPRE_Int HYPRE_PCGSetAbsoluteTol(HYPRE_Solver solver, HYPRE_Real a_tol); /** * (Optional) Set a residual-based convergence tolerance which checks if * $\|r_{old}-r_{new}\| < rtol \|b\|$. This is useful when trying to converge to * very low relative and/or absolute tolerances, in order to bail-out before * roundoff errors affect the approximation. **/ HYPRE_Int HYPRE_PCGSetResidualTol(HYPRE_Solver solver, HYPRE_Real rtol); /* * RE-VISIT **/ HYPRE_Int HYPRE_PCGSetAbsoluteTolFactor(HYPRE_Solver solver, HYPRE_Real abstolf); /* * RE-VISIT **/ HYPRE_Int HYPRE_PCGSetConvergenceFactorTol(HYPRE_Solver solver, HYPRE_Real cf_tol); /* * RE-VISIT **/ HYPRE_Int HYPRE_PCGSetStopCrit(HYPRE_Solver solver, HYPRE_Int stop_crit); /** * (Optional) Set maximum number of iterations. **/ HYPRE_Int HYPRE_PCGSetMaxIter(HYPRE_Solver solver, HYPRE_Int max_iter); /** * (Optional) Use the two-norm in stopping criteria. **/ HYPRE_Int HYPRE_PCGSetTwoNorm(HYPRE_Solver solver, HYPRE_Int two_norm); /** * (Optional) Additionally require that the relative difference in * successive iterates be small. **/ HYPRE_Int HYPRE_PCGSetRelChange(HYPRE_Solver solver, HYPRE_Int rel_change); /** * (Optional) Recompute the residual at the end to double-check convergence. **/ HYPRE_Int HYPRE_PCGSetRecomputeResidual(HYPRE_Solver solver, HYPRE_Int recompute_residual); /** * (Optional) Periodically recompute the residual while iterating. **/ HYPRE_Int HYPRE_PCGSetRecomputeResidualP(HYPRE_Solver solver, HYPRE_Int recompute_residual_p); /** * (Optional) Set the preconditioner to use. **/ HYPRE_Int HYPRE_PCGSetPrecond(HYPRE_Solver solver, HYPRE_PtrToSolverFcn precond, HYPRE_PtrToSolverFcn precond_setup, HYPRE_Solver precond_solver); /** * (Optional) Set the amount of logging to do. **/ HYPRE_Int HYPRE_PCGSetLogging(HYPRE_Solver solver, HYPRE_Int logging); /** * (Optional) Set the amount of printing to do to the screen. **/ HYPRE_Int HYPRE_PCGSetPrintLevel(HYPRE_Solver solver, HYPRE_Int level); /** * Return the number of iterations taken. **/ HYPRE_Int HYPRE_PCGGetNumIterations(HYPRE_Solver solver, HYPRE_Int *num_iterations); /** * Return the norm of the final relative residual. **/ HYPRE_Int HYPRE_PCGGetFinalRelativeResidualNorm(HYPRE_Solver solver, HYPRE_Real *norm); /** * Return the residual. **/ HYPRE_Int HYPRE_PCGGetResidual(HYPRE_Solver solver, void **residual); /** **/ HYPRE_Int HYPRE_PCGGetTol(HYPRE_Solver solver, HYPRE_Real *tol); /** **/ HYPRE_Int HYPRE_PCGGetResidualTol(HYPRE_Solver solver, HYPRE_Real *rtol); /* * RE-VISIT **/ HYPRE_Int HYPRE_PCGGetAbsoluteTolFactor(HYPRE_Solver solver, HYPRE_Real *abstolf); /* * RE-VISIT **/ HYPRE_Int HYPRE_PCGGetConvergenceFactorTol(HYPRE_Solver solver, HYPRE_Real *cf_tol); /* * RE-VISIT **/ HYPRE_Int HYPRE_PCGGetStopCrit(HYPRE_Solver solver, HYPRE_Int *stop_crit); /** **/ HYPRE_Int HYPRE_PCGGetMaxIter(HYPRE_Solver solver, HYPRE_Int *max_iter); /** **/ HYPRE_Int HYPRE_PCGGetTwoNorm(HYPRE_Solver solver, HYPRE_Int *two_norm); /** **/ HYPRE_Int HYPRE_PCGGetRelChange(HYPRE_Solver solver, HYPRE_Int *rel_change); /** **/ HYPRE_Int HYPRE_GMRESGetSkipRealResidualCheck(HYPRE_Solver solver, HYPRE_Int *skip_real_r_check); /** **/ HYPRE_Int HYPRE_PCGGetPrecond(HYPRE_Solver solver, HYPRE_Solver *precond_data_ptr); /** **/ HYPRE_Int HYPRE_PCGGetLogging(HYPRE_Solver solver, HYPRE_Int *level); /** **/ HYPRE_Int HYPRE_PCGGetPrintLevel(HYPRE_Solver solver, HYPRE_Int *level); /** **/ HYPRE_Int HYPRE_PCGGetConverged(HYPRE_Solver solver, HYPRE_Int *converged); /*@}*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name GMRES Solver **/ /*@{*/ /** * Prepare to solve the system. The coefficient data in {\tt b} and {\tt x} is * ignored here, but information about the layout of the data may be used. **/ HYPRE_Int HYPRE_GMRESSetup(HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x); /** * Solve the system. **/ HYPRE_Int HYPRE_GMRESSolve(HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x); /** * (Optional) Set the relative convergence tolerance. **/ HYPRE_Int HYPRE_GMRESSetTol(HYPRE_Solver solver, HYPRE_Real tol); /** * (Optional) Set the absolute convergence tolerance (default is 0). * If one desires * the convergence test to check the absolute convergence tolerance {\it only}, then * set the relative convergence tolerance to 0.0. (The convergence test is * $\|r\| \leq$ max(relative$\_$tolerance$\ast \|b\|$, absolute$\_$tolerance).) * **/ HYPRE_Int HYPRE_GMRESSetAbsoluteTol(HYPRE_Solver solver, HYPRE_Real a_tol); /* * RE-VISIT **/ HYPRE_Int HYPRE_GMRESSetConvergenceFactorTol(HYPRE_Solver solver, HYPRE_Real cf_tol); /* * RE-VISIT **/ HYPRE_Int HYPRE_GMRESSetStopCrit(HYPRE_Solver solver, HYPRE_Int stop_crit); /* * RE-VISIT **/ HYPRE_Int HYPRE_GMRESSetMinIter(HYPRE_Solver solver, HYPRE_Int min_iter); /** * (Optional) Set maximum number of iterations. **/ HYPRE_Int HYPRE_GMRESSetMaxIter(HYPRE_Solver solver, HYPRE_Int max_iter); /** * (Optional) Set the maximum size of the Krylov space. **/ HYPRE_Int HYPRE_GMRESSetKDim(HYPRE_Solver solver, HYPRE_Int k_dim); /** * (Optional) Additionally require that the relative difference in * successive iterates be small. **/ HYPRE_Int HYPRE_GMRESSetRelChange(HYPRE_Solver solver, HYPRE_Int rel_change); /** * (Optional) By default, hypre checks for convergence by evaluating the actual * residual before returnig from GMRES (with restart if the true residual does * not indicate convergence). This option allows users to skip the evaluation * and the check of the actual residual for badly conditioned problems where * restart is not expected to be beneficial. **/ HYPRE_Int HYPRE_GMRESSetSkipRealResidualCheck(HYPRE_Solver solver, HYPRE_Int skip_real_r_check); /** * (Optional) Set the preconditioner to use. **/ HYPRE_Int HYPRE_GMRESSetPrecond(HYPRE_Solver solver, HYPRE_PtrToSolverFcn precond, HYPRE_PtrToSolverFcn precond_setup, HYPRE_Solver precond_solver); /** * (Optional) Set the amount of logging to do. **/ HYPRE_Int HYPRE_GMRESSetLogging(HYPRE_Solver solver, HYPRE_Int logging); /** * (Optional) Set the amount of printing to do to the screen. **/ HYPRE_Int HYPRE_GMRESSetPrintLevel(HYPRE_Solver solver, HYPRE_Int level); /** * Return the number of iterations taken. **/ HYPRE_Int HYPRE_GMRESGetNumIterations(HYPRE_Solver solver, HYPRE_Int *num_iterations); /** * Return the norm of the final relative residual. **/ HYPRE_Int HYPRE_GMRESGetFinalRelativeResidualNorm(HYPRE_Solver solver, HYPRE_Real *norm); /** * Return the residual. **/ HYPRE_Int HYPRE_GMRESGetResidual(HYPRE_Solver solver, void **residual); /** **/ HYPRE_Int HYPRE_GMRESGetTol(HYPRE_Solver solver, HYPRE_Real *tol); /** **/ HYPRE_Int HYPRE_GMRESGetAbsoluteTol(HYPRE_Solver solver, HYPRE_Real *tol); /* * RE-VISIT **/ HYPRE_Int HYPRE_GMRESGetConvergenceFactorTol(HYPRE_Solver solver, HYPRE_Real *cf_tol); /* * OBSOLETE **/ HYPRE_Int HYPRE_GMRESGetStopCrit(HYPRE_Solver solver, HYPRE_Int *stop_crit); /* * RE-VISIT **/ HYPRE_Int HYPRE_GMRESGetMinIter(HYPRE_Solver solver, HYPRE_Int *min_iter); /** **/ HYPRE_Int HYPRE_GMRESGetMaxIter(HYPRE_Solver solver, HYPRE_Int *max_iter); /** **/ HYPRE_Int HYPRE_GMRESGetKDim(HYPRE_Solver solver, HYPRE_Int *k_dim); /** **/ HYPRE_Int HYPRE_GMRESGetRelChange(HYPRE_Solver solver, HYPRE_Int *rel_change); /** **/ HYPRE_Int HYPRE_GMRESGetPrecond(HYPRE_Solver solver, HYPRE_Solver *precond_data_ptr); /** **/ HYPRE_Int HYPRE_GMRESGetLogging(HYPRE_Solver solver, HYPRE_Int *level); /** **/ HYPRE_Int HYPRE_GMRESGetPrintLevel(HYPRE_Solver solver, HYPRE_Int *level); /** **/ HYPRE_Int HYPRE_GMRESGetConverged(HYPRE_Solver solver, HYPRE_Int *converged); /*@}*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /*@}*/ #ifdef __cplusplus } #endif #endif
13,743
27.279835
86
h
AMG
AMG-master/krylov/HYPRE_pcg.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_PCG interface * *****************************************************************************/ #include "krylov.h" /*-------------------------------------------------------------------------- * HYPRE_PCGCreate: Call class-specific function, e.g. HYPRE_ParCSRPCGCreate *--------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- * HYPRE_PCGDestroy: Call class-specific function *--------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- * HYPRE_PCGSetup *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetup( HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x ) { return( hypre_PCGSetup( solver, A, b, x ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSolve *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSolve( HYPRE_Solver solver, HYPRE_Matrix A, HYPRE_Vector b, HYPRE_Vector x ) { return( hypre_PCGSolve( (void *) solver, (void *) A, (void *) b, (void *) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetTol, HYPRE_PCGGetTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetTol( HYPRE_Solver solver, HYPRE_Real tol ) { return( hypre_PCGSetTol( (void *) solver, tol ) ); } HYPRE_Int HYPRE_PCGGetTol( HYPRE_Solver solver, HYPRE_Real *tol ) { return( hypre_PCGGetTol( (void *) solver, tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetAbsoluteTol, HYPRE_PCGGetAbsoluteTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetAbsoluteTol( HYPRE_Solver solver, HYPRE_Real a_tol ) { return( hypre_PCGSetAbsoluteTol( (void *) solver, a_tol ) ); } HYPRE_Int HYPRE_PCGGetAbsoluteTol( HYPRE_Solver solver, HYPRE_Real *a_tol ) { return( hypre_PCGGetAbsoluteTol( (void *) solver, a_tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetResidualTol, HYPRE_PCGGetResidualTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetResidualTol( HYPRE_Solver solver, HYPRE_Real rtol ) { return( hypre_PCGSetResidualTol( (void *) solver, rtol ) ); } HYPRE_Int HYPRE_PCGGetResidualTol( HYPRE_Solver solver, HYPRE_Real *rtol ) { return( hypre_PCGGetResidualTol( (void *) solver, rtol ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetAbsoluteTolFactor, HYPRE_PCGGetAbsoluteTolFactor *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetAbsoluteTolFactor( HYPRE_Solver solver, HYPRE_Real abstolf ) { return( hypre_PCGSetAbsoluteTolFactor( (void *) solver, abstolf ) ); } HYPRE_Int HYPRE_PCGGetAbsoluteTolFactor( HYPRE_Solver solver, HYPRE_Real *abstolf ) { return( hypre_PCGGetAbsoluteTolFactor( (void *) solver, abstolf ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetConvergenceFactorTol, HYPRE_PCGGetConvergenceFactorTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetConvergenceFactorTol( HYPRE_Solver solver, HYPRE_Real cf_tol ) { return hypre_PCGSetConvergenceFactorTol( (void *) solver, cf_tol ); } HYPRE_Int HYPRE_PCGGetConvergenceFactorTol( HYPRE_Solver solver, HYPRE_Real *cf_tol ) { return hypre_PCGGetConvergenceFactorTol( (void *) solver, cf_tol ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetMaxIter, HYPRE_PCGGetMaxIter *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetMaxIter( HYPRE_Solver solver, HYPRE_Int max_iter ) { return( hypre_PCGSetMaxIter( (void *) solver, max_iter ) ); } HYPRE_Int HYPRE_PCGGetMaxIter( HYPRE_Solver solver, HYPRE_Int *max_iter ) { return( hypre_PCGGetMaxIter( (void *) solver, max_iter ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetStopCrit, HYPRE_PCGGetStopCrit *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetStopCrit( HYPRE_Solver solver, HYPRE_Int stop_crit ) { return( hypre_PCGSetStopCrit( (void *) solver, stop_crit ) ); } HYPRE_Int HYPRE_PCGGetStopCrit( HYPRE_Solver solver, HYPRE_Int *stop_crit ) { return( hypre_PCGGetStopCrit( (void *) solver, stop_crit ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetTwoNorm, HYPRE_PCGGetTwoNorm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetTwoNorm( HYPRE_Solver solver, HYPRE_Int two_norm ) { return( hypre_PCGSetTwoNorm( (void *) solver, two_norm ) ); } HYPRE_Int HYPRE_PCGGetTwoNorm( HYPRE_Solver solver, HYPRE_Int *two_norm ) { return( hypre_PCGGetTwoNorm( (void *) solver, two_norm ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetRelChange, HYPRE_PCGGetRelChange *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetRelChange( HYPRE_Solver solver, HYPRE_Int rel_change ) { return( hypre_PCGSetRelChange( (void *) solver, rel_change ) ); } HYPRE_Int HYPRE_PCGGetRelChange( HYPRE_Solver solver, HYPRE_Int *rel_change ) { return( hypre_PCGGetRelChange( (void *) solver, rel_change ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetRecomputeResidual, HYPRE_PCGGetRecomputeResidual *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetRecomputeResidual( HYPRE_Solver solver, HYPRE_Int recompute_residual ) { return( hypre_PCGSetRecomputeResidual( (void *) solver, recompute_residual ) ); } HYPRE_Int HYPRE_PCGGetRecomputeResidual( HYPRE_Solver solver, HYPRE_Int *recompute_residual ) { return( hypre_PCGGetRecomputeResidual( (void *) solver, recompute_residual ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetRecomputeResidualP, HYPRE_PCGGetRecomputeResidualP *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetRecomputeResidualP( HYPRE_Solver solver, HYPRE_Int recompute_residual_p ) { return( hypre_PCGSetRecomputeResidualP( (void *) solver, recompute_residual_p ) ); } HYPRE_Int HYPRE_PCGGetRecomputeResidualP( HYPRE_Solver solver, HYPRE_Int *recompute_residual_p ) { return( hypre_PCGGetRecomputeResidualP( (void *) solver, recompute_residual_p ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetPrecond( HYPRE_Solver solver, HYPRE_PtrToSolverFcn precond, HYPRE_PtrToSolverFcn precond_setup, HYPRE_Solver precond_solver ) { return( hypre_PCGSetPrecond( (void *) solver, (HYPRE_Int (*)(void*, void*, void*, void*))precond, (HYPRE_Int (*)(void*, void*, void*, void*))precond_setup, (void *) precond_solver ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGGetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGGetPrecond( HYPRE_Solver solver, HYPRE_Solver *precond_data_ptr ) { return( hypre_PCGGetPrecond( (void *) solver, (HYPRE_Solver *) precond_data_ptr ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetLogging, HYPRE_PCGGetLogging * SetLogging sets both the print and log level, for backwards compatibility. * Soon the SetPrintLevel call should be deleted. *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetLogging( HYPRE_Solver solver, HYPRE_Int level ) { return ( hypre_PCGSetLogging( (void *) solver, level ) ); } HYPRE_Int HYPRE_PCGGetLogging( HYPRE_Solver solver, HYPRE_Int * level ) { return ( hypre_PCGGetLogging( (void *) solver, level ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGSetPrintLevel, HYPRE_PCGGetPrintLevel *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGSetPrintLevel( HYPRE_Solver solver, HYPRE_Int level ) { return( hypre_PCGSetPrintLevel( (void *) solver, level ) ); } HYPRE_Int HYPRE_PCGGetPrintLevel( HYPRE_Solver solver, HYPRE_Int *level ) { return( hypre_PCGGetPrintLevel( (void *) solver, level ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGGetNumIterations *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGGetNumIterations( HYPRE_Solver solver, HYPRE_Int *num_iterations ) { return( hypre_PCGGetNumIterations( (void *) solver, num_iterations ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGGetConverged *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGGetConverged( HYPRE_Solver solver, HYPRE_Int *converged ) { return( hypre_PCGGetConverged( (void *) solver, converged ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGGetFinalRelativeResidualNorm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGGetFinalRelativeResidualNorm( HYPRE_Solver solver, HYPRE_Real *norm ) { return( hypre_PCGGetFinalRelativeResidualNorm( (void *) solver, norm ) ); } /*-------------------------------------------------------------------------- * HYPRE_PCGGetResidual *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_PCGGetResidual( HYPRE_Solver solver, void **residual ) { /* returns a pointer to the residual vector */ return hypre_PCGGetResidual( (void *) solver, residual ); }
12,762
33.034667
85
c
AMG
AMG-master/krylov/gmres.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * GMRES gmres * *****************************************************************************/ #ifndef hypre_KRYLOV_GMRES_HEADER #define hypre_KRYLOV_GMRES_HEADER /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name Generic GMRES Interface * * A general description of the interface goes here... * * @memo A generic GMRES linear solver interface * @version 0.1 * @author Jeffrey F. Painter **/ /*@{*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- * hypre_GMRESData and hypre_GMRESFunctions *--------------------------------------------------------------------------*/ /** * @name GMRES structs * * Description... **/ /*@{*/ /** * The {\tt hypre\_GMRESFunctions} object ... **/ typedef struct { char * (*CAlloc) ( size_t count, size_t elt_size ); HYPRE_Int (*Free) ( char *ptr ); HYPRE_Int (*CommInfo) ( void *A, HYPRE_Int *my_id, HYPRE_Int *num_procs ); void * (*CreateVector) ( void *vector ); void * (*CreateVectorArray) ( HYPRE_Int size, void *vectors ); HYPRE_Int (*DestroyVector) ( void *vector ); void * (*MatvecCreate) ( void *A, void *x ); HYPRE_Int (*Matvec) ( void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ); HYPRE_Int (*MatvecDestroy) ( void *matvec_data ); HYPRE_Real (*InnerProd) ( void *x, void *y ); HYPRE_Int (*CopyVector) ( void *x, void *y ); HYPRE_Int (*ClearVector) ( void *x ); HYPRE_Int (*ScaleVector) ( HYPRE_Complex alpha, void *x ); HYPRE_Int (*Axpy) ( HYPRE_Complex alpha, void *x, void *y ); HYPRE_Int (*precond) (); HYPRE_Int (*precond_setup) (); } hypre_GMRESFunctions; /** * The {\tt hypre\_GMRESData} object ... **/ typedef struct { HYPRE_Int k_dim; HYPRE_Int min_iter; HYPRE_Int max_iter; HYPRE_Int rel_change; HYPRE_Int skip_real_r_check; HYPRE_Int stop_crit; HYPRE_Int converged; HYPRE_Real tol; HYPRE_Real cf_tol; HYPRE_Real a_tol; HYPRE_Real rel_residual_norm; void *A; void *r; void *w; void *w_2; void **p; void *matvec_data; void *precond_data; hypre_GMRESFunctions * functions; /* log info (always logged) */ HYPRE_Int num_iterations; HYPRE_Int print_level; /* printing when print_level>0 */ HYPRE_Int logging; /* extra computations for logging when logging>0 */ HYPRE_Real *norms; char *log_file_name; } hypre_GMRESData; #ifdef __cplusplus extern "C" { #endif /** * @name generic GMRES Solver * * Description... **/ /*@{*/ /** * Description... * * @param param [IN] ... **/ hypre_GMRESFunctions * hypre_GMRESFunctionsCreate( char * (*CAlloc) ( size_t count, size_t elt_size ), HYPRE_Int (*Free) ( char *ptr ), HYPRE_Int (*CommInfo) ( void *A, HYPRE_Int *my_id, HYPRE_Int *num_procs ), void * (*CreateVector) ( void *vector ), void * (*CreateVectorArray) ( HYPRE_Int size, void *vectors ), HYPRE_Int (*DestroyVector) ( void *vector ), void * (*MatvecCreate) ( void *A, void *x ), HYPRE_Int (*Matvec) ( void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ), HYPRE_Int (*MatvecDestroy) ( void *matvec_data ), HYPRE_Real (*InnerProd) ( void *x, void *y ), HYPRE_Int (*CopyVector) ( void *x, void *y ), HYPRE_Int (*ClearVector) ( void *x ), HYPRE_Int (*ScaleVector) ( HYPRE_Complex alpha, void *x ), HYPRE_Int (*Axpy) ( HYPRE_Complex alpha, void *x, void *y ), HYPRE_Int (*PrecondSetup) ( void *vdata, void *A, void *b, void *x ), HYPRE_Int (*Precond) ( void *vdata, void *A, void *b, void *x ) ); /** * Description... * * @param param [IN] ... **/ void * hypre_GMRESCreate( hypre_GMRESFunctions *gmres_functions ); #ifdef __cplusplus } #endif #endif
5,459
30.37931
83
h
AMG
AMG-master/krylov/pcg.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Preconditioned conjugate gradient (Omin) headers * *****************************************************************************/ #ifndef hypre_KRYLOV_PCG_HEADER #define hypre_KRYLOV_PCG_HEADER /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /** * @name Generic PCG Interface * * A general description of the interface goes here... * * @memo A generic PCG linear solver interface * @version 0.1 * @author Jeffrey F. Painter **/ /*@{*/ /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- * hypre_PCGData and hypre_PCGFunctions *--------------------------------------------------------------------------*/ /** * @name PCG structs * * Description... **/ /*@{*/ /** * The {\tt hypre\_PCGSFunctions} object ... **/ typedef struct { char * (*CAlloc) ( size_t count, size_t elt_size ); HYPRE_Int (*Free) ( char *ptr ); HYPRE_Int (*CommInfo) ( void *A, HYPRE_Int *my_id, HYPRE_Int *num_procs ); void * (*CreateVector) ( void *vector ); HYPRE_Int (*DestroyVector) ( void *vector ); void * (*MatvecCreate) ( void *A, void *x ); HYPRE_Int (*Matvec) ( void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ); HYPRE_Int (*MatvecDestroy) ( void *matvec_data ); HYPRE_Real (*InnerProd) ( void *x, void *y ); HYPRE_Int (*CopyVector) ( void *x, void *y ); HYPRE_Int (*ClearVector) ( void *x ); HYPRE_Int (*ScaleVector) ( HYPRE_Complex alpha, void *x ); HYPRE_Int (*Axpy) ( HYPRE_Complex alpha, void *x, void *y ); HYPRE_Int (*precond)(); HYPRE_Int (*precond_setup)(); } hypre_PCGFunctions; /** * The {\tt hypre\_PCGData} object ... **/ /* Summary of Parameters to Control Stopping Test: - Standard (default) error tolerance: |delta-residual|/|right-hand-side|<tol where the norm is an energy norm wrt preconditioner, |r|=sqrt(<Cr,r>). - two_norm!=0 means: the norm is the L2 norm, |r|=sqrt(<r,r>) - rel_change!=0 means: if pass the other stopping criteria, also check the relative change in the solution x. Pass iff this relative change is small. - tol = relative error tolerance, as above -a_tol = absolute convergence tolerance (default is 0.0) If one desires the convergence test to check the absolute convergence tolerance *only*, then set the relative convergence tolerance to 0.0. (The default convergence test is <C*r,r> <= max(relative_tolerance^2 * <C*b, b>, absolute_tolerance^2) - cf_tol = convergence factor tolerance; if >0 used for special test for slow convergence - stop_crit!=0 means (TO BE PHASED OUT): pure absolute error tolerance rather than a pure relative error tolerance on the residual. Never applies if rel_change!=0 or atolf!=0. - atolf = absolute error tolerance factor to be used _together_ with the relative error tolerance, |delta-residual| / ( atolf + |right-hand-side| ) < tol (To BE PHASED OUT) - recompute_residual means: when the iteration seems to be converged, recompute the residual from scratch (r=b-Ax) and use this new residual to repeat the convergence test. This can be expensive, use this only if you have seen a problem with the regular residual computation. - recompute_residual_p means: recompute the residual from scratch (r=b-Ax) every "recompute_residual_p" iterations. This can be expensive and degrade the convergence. Use it only if you have seen a problem with the regular residual computation. */ typedef struct { HYPRE_Real tol; HYPRE_Real atolf; HYPRE_Real cf_tol; HYPRE_Real a_tol; HYPRE_Real rtol; HYPRE_Int max_iter; HYPRE_Int two_norm; HYPRE_Int rel_change; HYPRE_Int recompute_residual; HYPRE_Int recompute_residual_p; HYPRE_Int stop_crit; HYPRE_Int converged; void *A; void *p; void *s; void *r; /* ...contains the residual. This is currently kept permanently. If that is ever changed, it still must be kept if logging>1 */ HYPRE_Int owns_matvec_data; /* normally 1; if 0, don't delete it */ void *matvec_data; void *precond_data; hypre_PCGFunctions * functions; /* log info (always logged) */ HYPRE_Int num_iterations; HYPRE_Real rel_residual_norm; HYPRE_Int print_level; /* printing when print_level>0 */ HYPRE_Int logging; /* extra computations for logging when logging>0 */ HYPRE_Real *norms; HYPRE_Real *rel_norms; } hypre_PCGData; #define hypre_PCGDataOwnsMatvecData(pcgdata) ((pcgdata) -> owns_matvec_data) #ifdef __cplusplus extern "C" { #endif /** * @name generic PCG Solver * * Description... **/ /*@{*/ /** * Description... * * @param param [IN] ... **/ hypre_PCGFunctions * hypre_PCGFunctionsCreate( char * (*CAlloc) ( size_t count, size_t elt_size ), HYPRE_Int (*Free) ( char *ptr ), HYPRE_Int (*CommInfo) ( void *A, HYPRE_Int *my_id, HYPRE_Int *num_procs ), void * (*CreateVector) ( void *vector ), HYPRE_Int (*DestroyVector) ( void *vector ), void * (*MatvecCreate) ( void *A, void *x ), HYPRE_Int (*Matvec) ( void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ), HYPRE_Int (*MatvecDestroy) ( void *matvec_data ), HYPRE_Real (*InnerProd) ( void *x, void *y ), HYPRE_Int (*CopyVector) ( void *x, void *y ), HYPRE_Int (*ClearVector) ( void *x ), HYPRE_Int (*ScaleVector) ( HYPRE_Complex alpha, void *x ), HYPRE_Int (*Axpy) ( HYPRE_Complex alpha, void *x, void *y ), HYPRE_Int (*PrecondSetup) ( void *vdata, void *A, void *b, void *x ), HYPRE_Int (*Precond) ( void *vdata, void *A, void *b, void *x ) ); /** * Description... * * @param param [IN] ... **/ void * hypre_PCGCreate( hypre_PCGFunctions *pcg_functions ); #ifdef __cplusplus } #endif #endif
7,406
34.440191
89
h
AMG
AMG-master/parcsr_ls/HYPRE_parcsr_gmres.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESCreate( MPI_Comm comm, HYPRE_Solver *solver ) { hypre_GMRESFunctions * gmres_functions; if (!solver) { hypre_error_in_arg(2); return hypre_error_flag; } gmres_functions = hypre_GMRESFunctionsCreate( hypre_CAlloc, hypre_ParKrylovFree, hypre_ParKrylovCommInfo, hypre_ParKrylovCreateVector, hypre_ParKrylovCreateVectorArray, hypre_ParKrylovDestroyVector, hypre_ParKrylovMatvecCreate, hypre_ParKrylovMatvec, hypre_ParKrylovMatvecDestroy, hypre_ParKrylovInnerProd, hypre_ParKrylovCopyVector, hypre_ParKrylovClearVector, hypre_ParKrylovScaleVector, hypre_ParKrylovAxpy, hypre_ParKrylovIdentitySetup, hypre_ParKrylovIdentity ); *solver = ( (HYPRE_Solver) hypre_GMRESCreate( gmres_functions ) ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESDestroy( HYPRE_Solver solver ) { return( hypre_GMRESDestroy( (void *) solver ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetup *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetup( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector b, HYPRE_ParVector x ) { return( HYPRE_GMRESSetup( solver, (HYPRE_Matrix) A, (HYPRE_Vector) b, (HYPRE_Vector) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSolve *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSolve( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector b, HYPRE_ParVector x ) { return( HYPRE_GMRESSolve( solver, (HYPRE_Matrix) A, (HYPRE_Vector) b, (HYPRE_Vector) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetKDim *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetKDim( HYPRE_Solver solver, HYPRE_Int k_dim ) { return( HYPRE_GMRESSetKDim( solver, k_dim ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetTol( HYPRE_Solver solver, HYPRE_Real tol ) { return( HYPRE_GMRESSetTol( solver, tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetAbsoluteTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetAbsoluteTol( HYPRE_Solver solver, HYPRE_Real a_tol ) { return( HYPRE_GMRESSetAbsoluteTol( solver, a_tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetMinIter *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetMinIter( HYPRE_Solver solver, HYPRE_Int min_iter ) { return( HYPRE_GMRESSetMinIter( solver, min_iter ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetMaxIter *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetMaxIter( HYPRE_Solver solver, HYPRE_Int max_iter ) { return( HYPRE_GMRESSetMaxIter( solver, max_iter ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetStopCrit - OBSOLETE *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetStopCrit( HYPRE_Solver solver, HYPRE_Int stop_crit ) { return( HYPRE_GMRESSetStopCrit( solver, stop_crit ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetPrecond( HYPRE_Solver solver, HYPRE_PtrToParSolverFcn precond, HYPRE_PtrToParSolverFcn precond_setup, HYPRE_Solver precond_solver ) { return( HYPRE_GMRESSetPrecond( solver, (HYPRE_PtrToSolverFcn) precond, (HYPRE_PtrToSolverFcn) precond_setup, precond_solver ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESGetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESGetPrecond( HYPRE_Solver solver, HYPRE_Solver *precond_data_ptr ) { return( HYPRE_GMRESGetPrecond( solver, precond_data_ptr ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetLogging *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetLogging( HYPRE_Solver solver, HYPRE_Int logging) { return( HYPRE_GMRESSetLogging( solver, logging ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESSetPrintLevel *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESSetPrintLevel( HYPRE_Solver solver, HYPRE_Int print_level) { return( HYPRE_GMRESSetPrintLevel( solver, print_level ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESGetNumIterations *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESGetNumIterations( HYPRE_Solver solver, HYPRE_Int *num_iterations ) { return( HYPRE_GMRESGetNumIterations( solver, num_iterations ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRGMRESGetFinalRelativeResidualNorm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRGMRESGetFinalRelativeResidualNorm( HYPRE_Solver solver, HYPRE_Real *norm ) { return( HYPRE_GMRESGetFinalRelativeResidualNorm( solver, norm ) ); }
8,273
35.449339
81
c
AMG
AMG-master/parcsr_ls/HYPRE_parcsr_pcg.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGCreate( MPI_Comm comm, HYPRE_Solver *solver ) { hypre_PCGFunctions * pcg_functions; if (!solver) { hypre_error_in_arg(2); return hypre_error_flag; } pcg_functions = hypre_PCGFunctionsCreate( hypre_CAlloc, hypre_ParKrylovFree, hypre_ParKrylovCommInfo, hypre_ParKrylovCreateVector, hypre_ParKrylovDestroyVector, hypre_ParKrylovMatvecCreate, hypre_ParKrylovMatvec, hypre_ParKrylovMatvecDestroy, hypre_ParKrylovInnerProd, hypre_ParKrylovCopyVector, hypre_ParKrylovClearVector, hypre_ParKrylovScaleVector, hypre_ParKrylovAxpy, hypre_ParKrylovIdentitySetup, hypre_ParKrylovIdentity ); *solver = ( (HYPRE_Solver) hypre_PCGCreate( pcg_functions ) ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGDestroy( HYPRE_Solver solver ) { return( hypre_PCGDestroy( (void *) solver ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetup *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetup( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector b, HYPRE_ParVector x ) { return( HYPRE_PCGSetup( solver, (HYPRE_Matrix) A, (HYPRE_Vector) b, (HYPRE_Vector) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSolve *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSolve( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector b, HYPRE_ParVector x ) { return( HYPRE_PCGSolve( solver, (HYPRE_Matrix) A, (HYPRE_Vector) b, (HYPRE_Vector) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetTol( HYPRE_Solver solver, HYPRE_Real tol ) { return( HYPRE_PCGSetTol( solver, tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetAbsoluteTol *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetAbsoluteTol( HYPRE_Solver solver, HYPRE_Real a_tol ) { return( HYPRE_PCGSetAbsoluteTol( solver, a_tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetMaxIter *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetMaxIter( HYPRE_Solver solver, HYPRE_Int max_iter ) { return( HYPRE_PCGSetMaxIter( solver, max_iter ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetStopCrit *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetStopCrit( HYPRE_Solver solver, HYPRE_Int stop_crit ) { return( HYPRE_PCGSetStopCrit( solver, stop_crit ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetTwoNorm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetTwoNorm( HYPRE_Solver solver, HYPRE_Int two_norm ) { return( HYPRE_PCGSetTwoNorm( solver, two_norm ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetRelChange *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetRelChange( HYPRE_Solver solver, HYPRE_Int rel_change ) { return( HYPRE_PCGSetRelChange( solver, rel_change ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetPrecond( HYPRE_Solver solver, HYPRE_PtrToParSolverFcn precond, HYPRE_PtrToParSolverFcn precond_setup, HYPRE_Solver precond_solver ) { return( HYPRE_PCGSetPrecond( solver, (HYPRE_PtrToSolverFcn) precond, (HYPRE_PtrToSolverFcn) precond_setup, precond_solver ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGGetPrecond *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGGetPrecond( HYPRE_Solver solver, HYPRE_Solver *precond_data_ptr ) { return( HYPRE_PCGGetPrecond( solver, precond_data_ptr ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetPrintLevel * an obsolete function; use HYPRE_PCG* functions instead *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetPrintLevel( HYPRE_Solver solver, HYPRE_Int level ) { return( HYPRE_PCGSetPrintLevel( solver, level ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGSetLogging * an obsolete function; use HYPRE_PCG* functions instead *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGSetLogging( HYPRE_Solver solver, HYPRE_Int level ) { return( HYPRE_PCGSetLogging( solver, level ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGGetNumIterations *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGGetNumIterations( HYPRE_Solver solver, HYPRE_Int *num_iterations ) { return( HYPRE_PCGGetNumIterations( solver, num_iterations ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRPCGGetFinalRelativeResidualNorm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRPCGGetFinalRelativeResidualNorm( HYPRE_Solver solver, HYPRE_Real *norm ) { return( HYPRE_PCGGetFinalRelativeResidualNorm( solver, norm ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRDiagScaleSetup *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRDiagScaleSetup( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector y, HYPRE_ParVector x ) { return 0; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRDiagScale *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRDiagScale( HYPRE_Solver solver, HYPRE_ParCSRMatrix HA, HYPRE_ParVector Hy, HYPRE_ParVector Hx ) { hypre_ParCSRMatrix *A = (hypre_ParCSRMatrix *) HA; hypre_ParVector *y = (hypre_ParVector *) Hy; hypre_ParVector *x = (hypre_ParVector *) Hx; HYPRE_Real *x_data = hypre_VectorData(hypre_ParVectorLocalVector(x)); HYPRE_Real *y_data = hypre_VectorData(hypre_ParVectorLocalVector(y)); HYPRE_Real *A_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A)); HYPRE_Int *A_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A)); HYPRE_Int local_size = hypre_VectorSize(hypre_ParVectorLocalVector(x)); HYPRE_Int i, ierr = 0; for (i=0; i < local_size; i++) { x_data[i] = y_data[i]/A_data[A_i[i]]; } return ierr; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRSymPrecondSetup *--------------------------------------------------------------------------*/ /* HYPRE_Int HYPRE_ParCSRSymPrecondSetup( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector b, HYPRE_ParVector x ) { hypre_ParCSRMatrix *A = (hypre_ParCSRMatrix *) A; hypre_ParVector *y = (hypre_ParVector *) b; hypre_ParVector *x = (hypre_ParVector *) x; HYPRE_Real *x_data = hypre_VectorData(hypre_ParVectorLocalVector(x)); HYPRE_Real *y_data = hypre_VectorData(hypre_ParVectorLocalVector(y)); HYPRE_Real *A_diag = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A)); HYPRE_Real *A_offd = hypre_CSRMatrixData(hypre_ParCSRMatrixOffD(A)); HYPRE_Int i, ierr = 0; hypre_ParCSRMatrix *Asym; MPI_Comm comm; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int *row_starts; HYPRE_Int *col_starts; HYPRE_Int num_cols_offd; HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd; Asym = hypre_ParCSRMatrixCreate(comm, global_num_rows, global_num_cols, row_starts, col_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); for (i=0; i < hypre_VectorSize(hypre_ParVectorLocalVector(x)); i++) { x_data[i] = y_data[i]/A_data[A_i[i]]; } return ierr; } */
11,088
34.428115
81
c
AMG
AMG-master/parcsr_ls/ams.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_AMS_DATA_HEADER #define hypre_AMS_DATA_HEADER /*-------------------------------------------------------------------------- * Auxiliary space Maxwell Solver data *--------------------------------------------------------------------------*/ typedef struct { /* Space dimension (2 or 3) */ HYPRE_Int dim; /* Edge element (ND1) stiffness matrix */ hypre_ParCSRMatrix *A; /* Discrete gradient matrix (vertex-to-edge) */ hypre_ParCSRMatrix *G; /* Coarse grid matrix on the range of G^T */ hypre_ParCSRMatrix *A_G; /* AMG solver for A_G */ HYPRE_Solver B_G; /* Is the mass term coefficient zero? */ HYPRE_Int beta_is_zero; /* Nedelec nodal interpolation matrix (vertex^dim-to-edge) */ hypre_ParCSRMatrix *Pi; /* Coarse grid matrix on the range of Pi^T */ hypre_ParCSRMatrix *A_Pi; /* AMG solver for A_Pi */ HYPRE_Solver B_Pi; /* Components of the Nedelec interpolation matrix (vertex-to-edge each) */ hypre_ParCSRMatrix *Pix, *Piy, *Piz; /* Coarse grid matrices on the ranges of Pi{x,y,z}^T */ hypre_ParCSRMatrix *A_Pix, *A_Piy, *A_Piz; /* AMG solvers for A_Pi{x,y,z} */ HYPRE_Solver B_Pix, B_Piy, B_Piz; /* Does the solver own the Nedelec interpolations? */ HYPRE_Int owns_Pi; /* Does the solver own the coarse grid matrices? */ HYPRE_Int owns_A_G, owns_A_Pi; /* Coordinates of the vertices (z = 0 if dim == 2) */ hypre_ParVector *x, *y, *z; /* Representations of the constant vectors in the Nedelec basis */ hypre_ParVector *Gx, *Gy, *Gz; /* Nodes in the interior of the zero-conductivity region */ hypre_ParVector *interior_nodes; /* Discrete gradient matrix for the interior nodes only */ hypre_ParCSRMatrix *G0; /* Coarse grid matrix on the interior nodes */ hypre_ParCSRMatrix *A_G0; /* AMG solver for A_G0 */ HYPRE_Solver B_G0; /* How frequently to project the r.h.s. onto Ker(G0^T)? */ HYPRE_Int projection_frequency; /* Internal counter to use with projection_frequency in PCG */ HYPRE_Int solve_counter; /* Solver options */ HYPRE_Int maxit; HYPRE_Real tol; HYPRE_Int cycle_type; HYPRE_Int print_level; /* Smoothing options for A */ HYPRE_Int A_relax_type; HYPRE_Int A_relax_times; HYPRE_Real *A_l1_norms; HYPRE_Real A_relax_weight; HYPRE_Real A_omega; HYPRE_Real A_max_eig_est; HYPRE_Real A_min_eig_est; HYPRE_Int A_cheby_order; HYPRE_Real A_cheby_fraction; /* AMG options for B_G */ HYPRE_Int B_G_coarsen_type; HYPRE_Int B_G_agg_levels; HYPRE_Int B_G_relax_type; HYPRE_Int B_G_coarse_relax_type; HYPRE_Real B_G_theta; HYPRE_Int B_G_interp_type; HYPRE_Int B_G_Pmax; /* AMG options for B_Pi */ HYPRE_Int B_Pi_coarsen_type; HYPRE_Int B_Pi_agg_levels; HYPRE_Int B_Pi_relax_type; HYPRE_Int B_Pi_coarse_relax_type; HYPRE_Real B_Pi_theta; HYPRE_Int B_Pi_interp_type; HYPRE_Int B_Pi_Pmax; /* Temporary vectors */ hypre_ParVector *r0, *g0, *r1, *g1, *r2, *g2; /* Output log info */ HYPRE_Int num_iterations; HYPRE_Real rel_resid_norm; } hypre_AMSData; /* Space dimension */ #define hypre_AMSDataDimension(ams_data) ((ams_data)->dim) /* Edge stiffness matrix */ #define hypre_AMSDataA(ams_data) ((ams_data)->A) /* Vertex space data */ #define hypre_AMSDataDiscreteGradient(ams_data) ((ams_data)->G) #define hypre_AMSDataPoissonBeta(ams_data) ((ams_data)->A_G) #define hypre_AMSDataPoissonBetaAMG(ams_data) ((ams_data)->B_G) #define hypre_AMSDataOwnsPoissonBeta(ams_data) ((ams_data)->owns_A_G) #define hypre_AMSDataBetaIsZero(ams_data) ((ams_data)->beta_is_zero) /* Vector vertex space data */ #define hypre_AMSDataPiInterpolation(ams_data) ((ams_data)->Pi) #define hypre_AMSDataOwnsPiInterpolation(ams_data) ((ams_data)->owns_Pi) #define hypre_AMSDataPoissonAlpha(ams_data) ((ams_data)->A_Pi) #define hypre_AMSDataPoissonAlphaAMG(ams_data) ((ams_data)->B_Pi) #define hypre_AMSDataOwnsPoissonAlpha(ams_data) ((ams_data)->owns_A_Pi) /* Coordinates of the vertices */ #define hypre_AMSDataVertexCoordinateX(ams_data) ((ams_data)->x) #define hypre_AMSDataVertexCoordinateY(ams_data) ((ams_data)->y) #define hypre_AMSDataVertexCoordinateZ(ams_data) ((ams_data)->z) /* Representations of the constant vectors in the Nedelec basis */ #define hypre_AMSDataEdgeConstantX(ams_data) ((ams_data)->Gx) #define hypre_AMSDataEdgeConstantY(ams_data) ((ams_data)->Gy) #define hypre_AMSDataEdgeConstantZ(ams_data) ((ams_data)->Gz) /* Solver options */ #define hypre_AMSDataMaxIter(ams_data) ((ams_data)->maxit) #define hypre_AMSDataTol(ams_data) ((ams_data)->tol) #define hypre_AMSDataCycleType(ams_data) ((ams_data)->cycle_type) #define hypre_AMSDataPrintLevel(ams_data) ((ams_data)->print_level) /* Smoothing and AMG options */ #define hypre_AMSDataARelaxType(ams_data) ((ams_data)->A_relax_type) #define hypre_AMSDataARelaxTimes(ams_data) ((ams_data)->A_relax_times) #define hypre_AMSDataAL1Norms(ams_data) ((ams_data)->A_l1_norms) #define hypre_AMSDataARelaxWeight(ams_data) ((ams_data)->A_relax_weight) #define hypre_AMSDataAOmega(ams_data) ((ams_data)->A_omega) #define hypre_AMSDataAMaxEigEst(ams_data) ((ams_data)->A_max_eig_est) #define hypre_AMSDataAMinEigEst(ams_data) ((ams_data)->A_min_eig_est) #define hypre_AMSDataAChebyOrder(ams_data) ((ams_data)->A_cheby_order) #define hypre_AMSDataAChebyFraction(ams_data) ((ams_data)->A_cheby_fraction) #define hypre_AMSDataPoissonAlphaAMGCoarsenType(ams_data) ((ams_data)->B_Pi_coarsen_type) #define hypre_AMSDataPoissonAlphaAMGAggLevels(ams_data) ((ams_data)->B_Pi_agg_levels) #define hypre_AMSDataPoissonAlphaAMGRelaxType(ams_data) ((ams_data)->B_Pi_relax_type) #define hypre_AMSDataPoissonAlphaAMGStrengthThreshold(ams_data) ((ams_data)->B_Pi_theta) #define hypre_AMSDataPoissonBetaAMGCoarsenType(ams_data) ((ams_data)->B_G_coarsen_type) #define hypre_AMSDataPoissonBetaAMGAggLevels(ams_data) ((ams_data)->B_G_agg_levels) #define hypre_AMSDataPoissonBetaAMGRelaxType(ams_data) ((ams_data)->B_G_relax_type) #define hypre_AMSDataPoissonBetaAMGStrengthThreshold(ams_data) ((ams_data)->B_G_theta) /* Temporary vectors */ #define hypre_AMSDataTempEdgeVectorR(ams_data) ((ams_data)->r0) #define hypre_AMSDataTempEdgeVectorG(ams_data) ((ams_data)->g0) #define hypre_AMSDataTempVertexVectorR(ams_data) ((ams_data)->r1) #define hypre_AMSDataTempVertexVectorG(ams_data) ((ams_data)->g1) #define hypre_AMSDataTempVecVertexVectorR(ams_data) ((ams_data)->r2) #define hypre_AMSDataTempVecVertexVectorG(ams_data) ((ams_data)->g2) #endif
7,471
37.715026
89
h
AMG
AMG-master/parcsr_ls/gen_redcs_mat.c
#include "_hypre_parcsr_ls.h" #include "par_amg.h" #define USE_ALLTOALL 0 /* here we have the sequential setup and solve - called from the * parallel one - for the coarser levels */ HYPRE_Int hypre_seqAMGSetup( hypre_ParAMGData *amg_data, HYPRE_Int p_level, HYPRE_Int coarse_threshold) { /* Par Data Structure variables */ hypre_ParCSRMatrix **Par_A_array = hypre_ParAMGDataAArray(amg_data); MPI_Comm comm = hypre_ParCSRMatrixComm(Par_A_array[0]); MPI_Comm new_comm, seq_comm; hypre_ParCSRMatrix *A_seq = NULL; hypre_CSRMatrix *A_seq_diag; hypre_CSRMatrix *A_seq_offd; hypre_ParVector *F_seq = NULL; hypre_ParVector *U_seq = NULL; hypre_ParCSRMatrix *A; HYPRE_Int **dof_func_array; HYPRE_Int num_procs, my_id; HYPRE_Int level; HYPRE_Int redundant; HYPRE_Int num_functions; HYPRE_Solver coarse_solver; /* misc */ dof_func_array = hypre_ParAMGDataDofFuncArray(amg_data); num_functions = hypre_ParAMGDataNumFunctions(amg_data); redundant = hypre_ParAMGDataRedundant(amg_data); /*MPI Stuff */ hypre_MPI_Comm_size(comm, &num_procs); /*initial */ level = p_level; /* convert A at this level to sequential */ A = Par_A_array[level]; { HYPRE_Real *A_seq_data = NULL; HYPRE_Int *A_seq_i = NULL; HYPRE_Int *A_seq_offd_i = NULL; HYPRE_Int *A_seq_j = NULL; HYPRE_Int *seq_dof_func = NULL; HYPRE_Real *A_tmp_data = NULL; HYPRE_Int *A_tmp_i = NULL; HYPRE_Int *A_tmp_j = NULL; HYPRE_Int *info = NULL; HYPRE_Int *displs = NULL; HYPRE_Int *displs2 = NULL; HYPRE_Int i, j, size, num_nonzeros, total_nnz, cnt; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int first_row_index = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int new_num_procs, *row_starts; hypre_GenerateSubComm(comm, num_rows, &new_comm); /*hypre_MPI_Group orig_group, new_group; HYPRE_Int *ranks, new_num_procs, *row_starts; info = hypre_CTAlloc(HYPRE_Int, num_procs); hypre_MPI_Allgather(&num_rows, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, comm); ranks = hypre_CTAlloc(HYPRE_Int, num_procs); new_num_procs = 0; for (i=0; i < num_procs; i++) if (info[i]) { ranks[new_num_procs] = i; info[new_num_procs++] = info[i]; } hypre_MPI_Comm_group(comm, &orig_group); hypre_MPI_Group_incl(orig_group, new_num_procs, ranks, &new_group); hypre_MPI_Comm_create(comm, new_group, &new_comm); hypre_MPI_Group_free(&new_group); hypre_MPI_Group_free(&orig_group); */ if (num_rows) { hypre_ParAMGDataParticipate(amg_data) = 1; hypre_MPI_Comm_size(new_comm, &new_num_procs); hypre_MPI_Comm_rank(new_comm, &my_id); info = hypre_CTAlloc(HYPRE_Int, new_num_procs); if (redundant) hypre_MPI_Allgather(&num_rows, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, new_comm); else hypre_MPI_Gather(&num_rows, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, 0, new_comm); /* alloc space in seq data structure only for participating procs*/ if (redundant || my_id == 0) { HYPRE_BoomerAMGCreate(&coarse_solver); HYPRE_BoomerAMGSetMaxRowSum(coarse_solver, hypre_ParAMGDataMaxRowSum(amg_data)); HYPRE_BoomerAMGSetStrongThreshold(coarse_solver, hypre_ParAMGDataStrongThreshold(amg_data)); HYPRE_BoomerAMGSetCoarsenType(coarse_solver, hypre_ParAMGDataCoarsenType(amg_data)); HYPRE_BoomerAMGSetInterpType(coarse_solver, hypre_ParAMGDataInterpType(amg_data)); HYPRE_BoomerAMGSetTruncFactor(coarse_solver, hypre_ParAMGDataTruncFactor(amg_data)); HYPRE_BoomerAMGSetPMaxElmts(coarse_solver, hypre_ParAMGDataPMaxElmts(amg_data)); if (hypre_ParAMGDataUserRelaxType(amg_data) > -1) HYPRE_BoomerAMGSetRelaxType(coarse_solver, hypre_ParAMGDataUserRelaxType(amg_data)); HYPRE_BoomerAMGSetRelaxOrder(coarse_solver, hypre_ParAMGDataRelaxOrder(amg_data)); HYPRE_BoomerAMGSetRelaxWt(coarse_solver, hypre_ParAMGDataUserRelaxWeight(amg_data)); if (hypre_ParAMGDataUserNumSweeps(amg_data) > -1) HYPRE_BoomerAMGSetNumSweeps(coarse_solver, hypre_ParAMGDataUserNumSweeps(amg_data)); HYPRE_BoomerAMGSetNumFunctions(coarse_solver, num_functions); HYPRE_BoomerAMGSetMaxIter(coarse_solver, 1); HYPRE_BoomerAMGSetTol(coarse_solver, 0); } /* Create CSR Matrix, will be Diag part of new matrix */ A_tmp_i = hypre_CTAlloc(HYPRE_Int, num_rows+1); A_tmp_i[0] = 0; for (i=1; i < num_rows+1; i++) A_tmp_i[i] = A_diag_i[i]-A_diag_i[i-1]+A_offd_i[i]-A_offd_i[i-1]; num_nonzeros = A_offd_i[num_rows]+A_diag_i[num_rows]; A_tmp_j = hypre_CTAlloc(HYPRE_Int, num_nonzeros); A_tmp_data = hypre_CTAlloc(HYPRE_Real, num_nonzeros); cnt = 0; for (i=0; i < num_rows; i++) { for (j=A_diag_i[i]; j < A_diag_i[i+1]; j++) { A_tmp_j[cnt] = A_diag_j[j]+first_row_index; A_tmp_data[cnt++] = A_diag_data[j]; } for (j=A_offd_i[i]; j < A_offd_i[i+1]; j++) { A_tmp_j[cnt] = col_map_offd[A_offd_j[j]]; A_tmp_data[cnt++] = A_offd_data[j]; } } displs = hypre_CTAlloc(HYPRE_Int, new_num_procs+1); displs[0] = 0; for (i=1; i < new_num_procs+1; i++) displs[i] = displs[i-1]+info[i-1]; size = displs[new_num_procs]; if (redundant || my_id == 0) { A_seq_i = hypre_CTAlloc(HYPRE_Int, size+1); A_seq_offd_i = hypre_CTAlloc(HYPRE_Int, size+1); if (num_functions > 1) seq_dof_func = hypre_CTAlloc(HYPRE_Int, size); } if (redundant) { hypre_MPI_Allgatherv ( &A_tmp_i[1], num_rows, HYPRE_MPI_INT, &A_seq_i[1], info, displs, HYPRE_MPI_INT, new_comm ); if (num_functions > 1) { hypre_MPI_Allgatherv ( dof_func_array[level], num_rows, HYPRE_MPI_INT, seq_dof_func, info, displs, HYPRE_MPI_INT, new_comm ); HYPRE_BoomerAMGSetDofFunc(coarse_solver, seq_dof_func); } } else { if (A_seq_i) hypre_MPI_Gatherv ( &A_tmp_i[1], num_rows, HYPRE_MPI_INT, &A_seq_i[1], info, displs, HYPRE_MPI_INT, 0, new_comm ); else hypre_MPI_Gatherv ( &A_tmp_i[1], num_rows, HYPRE_MPI_INT, A_seq_i, info, displs, HYPRE_MPI_INT, 0, new_comm ); if (num_functions > 1) { hypre_MPI_Gatherv ( dof_func_array[level], num_rows, HYPRE_MPI_INT, seq_dof_func, info, displs, HYPRE_MPI_INT, 0, new_comm ); if (my_id == 0) HYPRE_BoomerAMGSetDofFunc(coarse_solver, seq_dof_func); } } if (redundant || my_id == 0) { displs2 = hypre_CTAlloc(HYPRE_Int, new_num_procs+1); A_seq_i[0] = 0; displs2[0] = 0; for (j=1; j < displs[1]; j++) A_seq_i[j] = A_seq_i[j]+A_seq_i[j-1]; for (i=1; i < new_num_procs; i++) { for (j=displs[i]; j < displs[i+1]; j++) { A_seq_i[j] = A_seq_i[j]+A_seq_i[j-1]; } } A_seq_i[size] = A_seq_i[size]+A_seq_i[size-1]; displs2[new_num_procs] = A_seq_i[size]; for (i=1; i < new_num_procs+1; i++) { displs2[i] = A_seq_i[displs[i]]; info[i-1] = displs2[i] - displs2[i-1]; } total_nnz = displs2[new_num_procs]; A_seq_j = hypre_CTAlloc(HYPRE_Int, total_nnz); A_seq_data = hypre_CTAlloc(HYPRE_Real, total_nnz); } if (redundant) { hypre_MPI_Allgatherv ( A_tmp_j, num_nonzeros, HYPRE_MPI_INT, A_seq_j, info, displs2, HYPRE_MPI_INT, new_comm ); hypre_MPI_Allgatherv ( A_tmp_data, num_nonzeros, HYPRE_MPI_REAL, A_seq_data, info, displs2, HYPRE_MPI_REAL, new_comm ); } else { hypre_MPI_Gatherv ( A_tmp_j, num_nonzeros, HYPRE_MPI_INT, A_seq_j, info, displs2, HYPRE_MPI_INT, 0, new_comm ); hypre_MPI_Gatherv ( A_tmp_data, num_nonzeros, HYPRE_MPI_REAL, A_seq_data, info, displs2, HYPRE_MPI_REAL, 0, new_comm ); } hypre_TFree(info); hypre_TFree(displs); hypre_TFree(A_tmp_i); hypre_TFree(A_tmp_j); hypre_TFree(A_tmp_data); if (redundant || my_id == 0) { hypre_TFree(displs2); row_starts = hypre_CTAlloc(HYPRE_Int,2); row_starts[0] = 0; row_starts[1] = size; /* Create 1 proc communicator */ seq_comm = hypre_MPI_COMM_SELF; A_seq = hypre_ParCSRMatrixCreate(seq_comm,size,size, row_starts, row_starts, 0,total_nnz,0); A_seq_diag = hypre_ParCSRMatrixDiag(A_seq); A_seq_offd = hypre_ParCSRMatrixOffd(A_seq); hypre_CSRMatrixData(A_seq_diag) = A_seq_data; hypre_CSRMatrixI(A_seq_diag) = A_seq_i; hypre_CSRMatrixJ(A_seq_diag) = A_seq_j; hypre_CSRMatrixI(A_seq_offd) = A_seq_offd_i; F_seq = hypre_ParVectorCreate(seq_comm, size, row_starts); U_seq = hypre_ParVectorCreate(seq_comm, size, row_starts); hypre_ParVectorOwnsPartitioning(F_seq) = 0; hypre_ParVectorOwnsPartitioning(U_seq) = 0; hypre_ParVectorInitialize(F_seq); hypre_ParVectorInitialize(U_seq); hypre_BoomerAMGSetup(coarse_solver,A_seq,F_seq,U_seq); hypre_ParAMGDataCoarseSolver(amg_data) = coarse_solver; hypre_ParAMGDataACoarse(amg_data) = A_seq; hypre_ParAMGDataFCoarse(amg_data) = F_seq; hypre_ParAMGDataUCoarse(amg_data) = U_seq; } hypre_ParAMGDataNewComm(amg_data) = new_comm; } } return 0; } /*-------------------------------------------------------------------------- * hypre_seqAMGCycle *--------------------------------------------------------------------------*/ HYPRE_Int hypre_seqAMGCycle( hypre_ParAMGData *amg_data, HYPRE_Int p_level, hypre_ParVector **Par_F_array, hypre_ParVector **Par_U_array ) { hypre_ParVector *Aux_U; hypre_ParVector *Aux_F; /* Local variables */ HYPRE_Int Solve_err_flag = 0; HYPRE_Int n; HYPRE_Int i; hypre_Vector *u_local; HYPRE_Real *u_data; HYPRE_Int first_index; /* Acquire seq data */ MPI_Comm new_comm = hypre_ParAMGDataNewComm(amg_data); HYPRE_Solver coarse_solver = hypre_ParAMGDataCoarseSolver(amg_data); hypre_ParCSRMatrix *A_coarse = hypre_ParAMGDataACoarse(amg_data); hypre_ParVector *F_coarse = hypre_ParAMGDataFCoarse(amg_data); hypre_ParVector *U_coarse = hypre_ParAMGDataUCoarse(amg_data); HYPRE_Int redundant = hypre_ParAMGDataRedundant(amg_data); Aux_U = Par_U_array[p_level]; Aux_F = Par_F_array[p_level]; first_index = hypre_ParVectorFirstIndex(Aux_U); u_local = hypre_ParVectorLocalVector(Aux_U); u_data = hypre_VectorData(u_local); n = hypre_VectorSize(u_local); /*if (A_coarse)*/ if (hypre_ParAMGDataParticipate(amg_data)) { HYPRE_Real *f_data; hypre_Vector *f_local; hypre_Vector *tmp_vec; HYPRE_Int nf; HYPRE_Int local_info; HYPRE_Real *recv_buf = NULL; HYPRE_Int *displs = NULL; HYPRE_Int *info = NULL; HYPRE_Int new_num_procs, my_id; hypre_MPI_Comm_size(new_comm, &new_num_procs); hypre_MPI_Comm_rank(new_comm, &my_id); f_local = hypre_ParVectorLocalVector(Aux_F); f_data = hypre_VectorData(f_local); nf = hypre_VectorSize(f_local); /* first f */ info = hypre_CTAlloc(HYPRE_Int, new_num_procs); local_info = nf; if (redundant) hypre_MPI_Allgather(&local_info, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, new_comm); else hypre_MPI_Gather(&local_info, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, 0, new_comm); if (redundant || my_id ==0) { displs = hypre_CTAlloc(HYPRE_Int, new_num_procs+1); displs[0] = 0; for (i=1; i < new_num_procs+1; i++) displs[i] = displs[i-1]+info[i-1]; if (F_coarse) { tmp_vec = hypre_ParVectorLocalVector(F_coarse); recv_buf = hypre_VectorData(tmp_vec); } } if (redundant) hypre_MPI_Allgatherv ( f_data, nf, HYPRE_MPI_REAL, recv_buf, info, displs, HYPRE_MPI_REAL, new_comm ); else hypre_MPI_Gatherv ( f_data, nf, HYPRE_MPI_REAL, recv_buf, info, displs, HYPRE_MPI_REAL, 0, new_comm ); if (redundant || my_id ==0) { tmp_vec = hypre_ParVectorLocalVector(U_coarse); recv_buf = hypre_VectorData(tmp_vec); } /*then u */ if (redundant) { hypre_MPI_Allgatherv ( u_data, n, HYPRE_MPI_REAL, recv_buf, info, displs, HYPRE_MPI_REAL, new_comm ); hypre_TFree(displs); hypre_TFree(info); } else hypre_MPI_Gatherv ( u_data, n, HYPRE_MPI_REAL, recv_buf, info, displs, HYPRE_MPI_REAL, 0, new_comm ); /* clean up */ if (redundant || my_id ==0) { hypre_BoomerAMGSolve(coarse_solver, A_coarse, F_coarse, U_coarse); } /*copy my part of U to parallel vector */ if (redundant) { HYPRE_Real *local_data; local_data = hypre_VectorData(hypre_ParVectorLocalVector(U_coarse)); for (i = 0; i < n; i++) { u_data[i] = local_data[first_index+i]; } } else { HYPRE_Real *local_data=NULL; if (my_id == 0) local_data = hypre_VectorData(hypre_ParVectorLocalVector(U_coarse)); hypre_MPI_Scatterv ( local_data, info, displs, HYPRE_MPI_REAL, u_data, n, HYPRE_MPI_REAL, 0, new_comm ); /*if (my_id == 0) local_data = hypre_VectorData(hypre_ParVectorLocalVector(F_coarse)); hypre_MPI_Scatterv ( local_data, info, displs, HYPRE_MPI_REAL, f_data, n, HYPRE_MPI_REAL, 0, new_comm );*/ if (my_id == 0) hypre_TFree(displs); hypre_TFree(info); } } return(Solve_err_flag); } /* generate sub communicator, which contains no idle processors */ HYPRE_Int hypre_GenerateSubComm(MPI_Comm comm, HYPRE_Int participate, MPI_Comm *new_comm_ptr) { MPI_Comm new_comm; hypre_MPI_Group orig_group, new_group; hypre_MPI_Op hypre_MPI_MERGE; HYPRE_Int *info, *ranks, new_num_procs, my_info, my_id, num_procs; HYPRE_Int *list_len; hypre_MPI_Comm_rank(comm,&my_id); if (participate) my_info = 1; else my_info = 0; hypre_MPI_Allreduce(&my_info, &new_num_procs, 1, HYPRE_MPI_INT, hypre_MPI_SUM, comm); if (new_num_procs == 0) { new_comm = hypre_MPI_COMM_NULL; *new_comm_ptr = new_comm; return 0; } ranks = hypre_CTAlloc(HYPRE_Int, new_num_procs+2); if (new_num_procs == 1) { if (participate) my_info = my_id; hypre_MPI_Allreduce(&my_info, &ranks[2], 1, HYPRE_MPI_INT, hypre_MPI_SUM, comm); } else { info = hypre_CTAlloc(HYPRE_Int, new_num_procs+2); list_len = hypre_CTAlloc(HYPRE_Int, 1); if (participate) { info[0] = 1; info[1] = 1; info[2] = my_id; } else info[0] = 0; list_len[0] = new_num_procs + 2; hypre_MPI_Op_create((hypre_MPI_User_function *)hypre_merge_lists, 0, &hypre_MPI_MERGE); hypre_MPI_Allreduce(info, ranks, list_len[0], HYPRE_MPI_INT, hypre_MPI_MERGE, comm); hypre_MPI_Op_free (&hypre_MPI_MERGE); hypre_TFree(list_len); hypre_TFree(info); } hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_group(comm, &orig_group); hypre_MPI_Group_incl(orig_group, new_num_procs, &ranks[2], &new_group); hypre_MPI_Comm_create(comm, new_group, &new_comm); hypre_MPI_Group_free(&new_group); hypre_MPI_Group_free(&orig_group); hypre_TFree(ranks); *new_comm_ptr = new_comm; return 0; } void hypre_merge_lists (HYPRE_Int *list1, HYPRE_Int* list2, hypre_int *np1, hypre_MPI_Datatype *dptr) { HYPRE_Int i, len1, len2, indx1, indx2; if (list1[0] == 0 || (list2[0] == 0 && list1[0] == 0)) { return; } else { list2[0] = 1; len1 = list1[1]; len2 = list2[1]; list2[1] = len1+len2; if ((hypre_int)(list2[1]) > *np1+2) printf("segfault in MPI User function merge_list\n"); indx1 = len1+1; indx2 = len2+1; for (i=len1+len2+1; i > 1; i--) { if (indx2 > 1 && indx1 > 1 && list1[indx1] > list2[indx2]) { list2[i] = list1[indx1]; indx1--; } else if (indx2 > 1) { list2[i] = list2[indx2]; indx2--; } else if (indx1 > 1) { list2[i] = list1[indx1]; indx1--; } } } }
18,580
30.871355
101
c
AMG
AMG-master/parcsr_ls/headers.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "_hypre_parcsr_ls.h"
1,017
36.703704
81
h
AMG
AMG-master/parcsr_ls/par_amg.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_ParAMG_DATA_HEADER #define hypre_ParAMG_DATA_HEADER #define CUMNUMIT /*#include "par_csr_block_matrix.h"*/ /*-------------------------------------------------------------------------- * hypre_ParAMGData *--------------------------------------------------------------------------*/ typedef struct { /* setup params */ HYPRE_Int max_levels; HYPRE_Real strong_threshold; HYPRE_Real max_row_sum; HYPRE_Real trunc_factor; HYPRE_Real agg_trunc_factor; HYPRE_Real agg_P12_trunc_factor; HYPRE_Real jacobi_trunc_threshold; HYPRE_Real S_commpkg_switch; HYPRE_Int measure_type; HYPRE_Int setup_type; HYPRE_Int coarsen_type; HYPRE_Int P_max_elmts; HYPRE_Int interp_type; HYPRE_Int sep_weight; HYPRE_Int agg_interp_type; HYPRE_Int agg_P_max_elmts; HYPRE_Int agg_P12_max_elmts; HYPRE_Int restr_par; HYPRE_Int agg_num_levels; HYPRE_Int num_paths; HYPRE_Int post_interp_type; HYPRE_Int max_coarse_size; HYPRE_Int min_coarse_size; HYPRE_Int seq_threshold; HYPRE_Int redundant; HYPRE_Int participate; /* solve params */ HYPRE_Int max_iter; HYPRE_Int min_iter; HYPRE_Int cycle_type; HYPRE_Int *num_grid_sweeps; HYPRE_Int *grid_relax_type; HYPRE_Int **grid_relax_points; HYPRE_Int relax_order; HYPRE_Int user_coarse_relax_type; HYPRE_Int user_relax_type; HYPRE_Int user_num_sweeps; HYPRE_Real user_relax_weight; HYPRE_Real outer_wt; HYPRE_Real *relax_weight; HYPRE_Real *omega; HYPRE_Real tol; /* problem data */ hypre_ParCSRMatrix *A; HYPRE_Int num_variables; HYPRE_Int num_functions; HYPRE_Int nodal; HYPRE_Int nodal_levels; HYPRE_Int nodal_diag; HYPRE_Int num_points; HYPRE_Int *dof_func; HYPRE_Int *dof_point; HYPRE_Int *point_dof_map; /* data generated in the setup phase */ hypre_ParCSRMatrix **A_array; hypre_ParVector **F_array; hypre_ParVector **U_array; hypre_ParCSRMatrix **P_array; hypre_ParCSRMatrix **R_array; HYPRE_Int **CF_marker_array; HYPRE_Int **dof_func_array; HYPRE_Int **dof_point_array; HYPRE_Int **point_dof_map_array; HYPRE_Int num_levels; HYPRE_Real **l1_norms; HYPRE_Int block_mode; HYPRE_Real *max_eig_est; HYPRE_Real *min_eig_est; HYPRE_Int cheby_eig_est; HYPRE_Int cheby_order; HYPRE_Int cheby_variant; HYPRE_Int cheby_scale; HYPRE_Real cheby_fraction; HYPRE_Real **cheby_ds; HYPRE_Real **cheby_coefs; /* data needed for non-Galerkin option */ HYPRE_Int nongalerk_num_tol; HYPRE_Real *nongalerk_tol; HYPRE_Real nongalerkin_tol; HYPRE_Real *nongal_tol_array; /* data generated in the solve phase */ hypre_ParVector *Vtemp; hypre_Vector *Vtemp_local; HYPRE_Real *Vtemp_local_data; HYPRE_Real cycle_op_count; hypre_ParVector *Rtemp; hypre_ParVector *Ptemp; hypre_ParVector *Ztemp; /* log info */ HYPRE_Int logging; HYPRE_Int num_iterations; #ifdef CUMNUMIT HYPRE_Int cum_num_iterations; #endif HYPRE_Real cum_nnz_A_P; HYPRE_Real rel_resid_norm; hypre_ParVector *residual; /* available if logging>1 */ /* output params */ HYPRE_Int print_level; char log_file_name[256]; HYPRE_Int debug_flag; /* enable redundant coarse grid solve */ HYPRE_Solver coarse_solver; hypre_ParCSRMatrix *A_coarse; hypre_ParVector *f_coarse; hypre_ParVector *u_coarse; MPI_Comm new_comm; /* store matrix, vector and communication info for Gaussian elimination */ HYPRE_Real *A_mat; HYPRE_Real *b_vec; HYPRE_Int *comm_info; /* information for multiplication with Lambda - additive AMG */ HYPRE_Int additive; HYPRE_Int mult_additive; HYPRE_Int simple; HYPRE_Int add_last_lvl; HYPRE_Int add_P_max_elmts; HYPRE_Real add_trunc_factor; HYPRE_Int add_rlx_type; HYPRE_Real add_rlx_wt; hypre_ParCSRMatrix *Lambda; hypre_ParCSRMatrix *Atilde; hypre_ParVector *Rtilde; hypre_ParVector *Xtilde; HYPRE_Real *D_inv; /* Use 2 mat-mat-muls instead of triple product*/ HYPRE_Int rap2; HYPRE_Int keepTranspose; } hypre_ParAMGData; /*-------------------------------------------------------------------------- * Accessor functions for the hypre_AMGData structure *--------------------------------------------------------------------------*/ /* setup params */ #define hypre_ParAMGDataRestriction(amg_data) ((amg_data)->restr_par) #define hypre_ParAMGDataMaxLevels(amg_data) ((amg_data)->max_levels) #define hypre_ParAMGDataStrongThreshold(amg_data) \ ((amg_data)->strong_threshold) #define hypre_ParAMGDataMaxRowSum(amg_data) ((amg_data)->max_row_sum) #define hypre_ParAMGDataTruncFactor(amg_data) ((amg_data)->trunc_factor) #define hypre_ParAMGDataAggTruncFactor(amg_data) ((amg_data)->agg_trunc_factor) #define hypre_ParAMGDataAggP12TruncFactor(amg_data) ((amg_data)->agg_P12_trunc_factor) #define hypre_ParAMGDataJacobiTruncThreshold(amg_data) ((amg_data)->jacobi_trunc_threshold) #define hypre_ParAMGDataSCommPkgSwitch(amg_data) ((amg_data)->S_commpkg_switch) #define hypre_ParAMGDataInterpType(amg_data) ((amg_data)->interp_type) #define hypre_ParAMGDataSepWeight(amg_data) ((amg_data)->sep_weight) #define hypre_ParAMGDataAggInterpType(amg_data) ((amg_data)->agg_interp_type) #define hypre_ParAMGDataCoarsenType(amg_data) ((amg_data)->coarsen_type) #define hypre_ParAMGDataMeasureType(amg_data) ((amg_data)->measure_type) #define hypre_ParAMGDataSetupType(amg_data) ((amg_data)->setup_type) #define hypre_ParAMGDataPMaxElmts(amg_data) ((amg_data)->P_max_elmts) #define hypre_ParAMGDataAggPMaxElmts(amg_data) ((amg_data)->agg_P_max_elmts) #define hypre_ParAMGDataAggP12MaxElmts(amg_data) ((amg_data)->agg_P12_max_elmts) #define hypre_ParAMGDataNumPaths(amg_data) ((amg_data)->num_paths) #define hypre_ParAMGDataAggNumLevels(amg_data) ((amg_data)->agg_num_levels) #define hypre_ParAMGDataPostInterpType(amg_data) ((amg_data)->post_interp_type) #define hypre_ParAMGDataL1Norms(amg_data) ((amg_data)->l1_norms) #define hypre_ParAMGDataMaxCoarseSize(amg_data) ((amg_data)->max_coarse_size) #define hypre_ParAMGDataMinCoarseSize(amg_data) ((amg_data)->min_coarse_size) #define hypre_ParAMGDataSeqThreshold(amg_data) ((amg_data)->seq_threshold) /* solve params */ #define hypre_ParAMGDataMinIter(amg_data) ((amg_data)->min_iter) #define hypre_ParAMGDataMaxIter(amg_data) ((amg_data)->max_iter) #define hypre_ParAMGDataCycleType(amg_data) ((amg_data)->cycle_type) #define hypre_ParAMGDataTol(amg_data) ((amg_data)->tol) #define hypre_ParAMGDataNumGridSweeps(amg_data) ((amg_data)->num_grid_sweeps) #define hypre_ParAMGDataUserCoarseRelaxType(amg_data) ((amg_data)->user_coarse_relax_type) #define hypre_ParAMGDataUserRelaxType(amg_data) ((amg_data)->user_relax_type) #define hypre_ParAMGDataUserRelaxWeight(amg_data) ((amg_data)->user_relax_weight) #define hypre_ParAMGDataUserNumSweeps(amg_data) ((amg_data)->user_num_sweeps) #define hypre_ParAMGDataGridRelaxType(amg_data) ((amg_data)->grid_relax_type) #define hypre_ParAMGDataGridRelaxPoints(amg_data) \ ((amg_data)->grid_relax_points) #define hypre_ParAMGDataRelaxOrder(amg_data) ((amg_data)->relax_order) #define hypre_ParAMGDataRelaxWeight(amg_data) ((amg_data)->relax_weight) #define hypre_ParAMGDataOmega(amg_data) ((amg_data)->omega) #define hypre_ParAMGDataOuterWt(amg_data) ((amg_data)->outer_wt) /* problem data parameters */ #define hypre_ParAMGDataNumVariables(amg_data) ((amg_data)->num_variables) #define hypre_ParAMGDataNumFunctions(amg_data) ((amg_data)->num_functions) #define hypre_ParAMGDataNodal(amg_data) ((amg_data)->nodal) #define hypre_ParAMGDataNodalLevels(amg_data) ((amg_data)->nodal_levels) #define hypre_ParAMGDataNodalDiag(amg_data) ((amg_data)->nodal_diag) #define hypre_ParAMGDataNumPoints(amg_data) ((amg_data)->num_points) #define hypre_ParAMGDataDofFunc(amg_data) ((amg_data)->dof_func) #define hypre_ParAMGDataDofPoint(amg_data) ((amg_data)->dof_point) #define hypre_ParAMGDataPointDofMap(amg_data) ((amg_data)->point_dof_map) /* data generated by the setup phase */ #define hypre_ParAMGDataCFMarkerArray(amg_data) ((amg_data)-> CF_marker_array) #define hypre_ParAMGDataAArray(amg_data) ((amg_data)->A_array) #define hypre_ParAMGDataFArray(amg_data) ((amg_data)->F_array) #define hypre_ParAMGDataUArray(amg_data) ((amg_data)->U_array) #define hypre_ParAMGDataPArray(amg_data) ((amg_data)->P_array) #define hypre_ParAMGDataRArray(amg_data) ((amg_data)->R_array) #define hypre_ParAMGDataDofFuncArray(amg_data) ((amg_data)->dof_func_array) #define hypre_ParAMGDataDofPointArray(amg_data) ((amg_data)->dof_point_array) #define hypre_ParAMGDataPointDofMapArray(amg_data) \ ((amg_data)->point_dof_map_array) #define hypre_ParAMGDataNumLevels(amg_data) ((amg_data)->num_levels) #define hypre_ParAMGDataMaxEigEst(amg_data) ((amg_data)->max_eig_est) #define hypre_ParAMGDataMinEigEst(amg_data) ((amg_data)->min_eig_est) #define hypre_ParAMGDataChebyEigEst(amg_data) ((amg_data)->cheby_eig_est) #define hypre_ParAMGDataChebyVariant(amg_data) ((amg_data)->cheby_variant) #define hypre_ParAMGDataChebyScale(amg_data) ((amg_data)->cheby_scale) #define hypre_ParAMGDataChebyOrder(amg_data) ((amg_data)->cheby_order) #define hypre_ParAMGDataChebyFraction(amg_data) ((amg_data)->cheby_fraction) #define hypre_ParAMGDataChebyDS(amg_data) ((amg_data)->cheby_ds) #define hypre_ParAMGDataChebyCoefs(amg_data) ((amg_data)->cheby_coefs) #define hypre_ParAMGDataBlockMode(amg_data) ((amg_data)->block_mode) /* data generated in the solve phase */ #define hypre_ParAMGDataVtemp(amg_data) ((amg_data)->Vtemp) #define hypre_ParAMGDataVtempLocal(amg_data) ((amg_data)->Vtemp_local) #define hypre_ParAMGDataVtemplocalData(amg_data) ((amg_data)->Vtemp_local_data) #define hypre_ParAMGDataCycleOpCount(amg_data) ((amg_data)->cycle_op_count) #define hypre_ParAMGDataRtemp(amg_data) ((amg_data)->Rtemp) #define hypre_ParAMGDataPtemp(amg_data) ((amg_data)->Ptemp) #define hypre_ParAMGDataZtemp(amg_data) ((amg_data)->Ztemp) /* fields used by GSMG */ #define hypre_ParAMGDataGSMG(amg_data) ((amg_data)->gsmg) #define hypre_ParAMGDataNumSamples(amg_data) ((amg_data)->num_samples) /* log info data */ #define hypre_ParAMGDataLogging(amg_data) ((amg_data)->logging) #define hypre_ParAMGDataNumIterations(amg_data) ((amg_data)->num_iterations) #ifdef CUMNUMIT #define hypre_ParAMGDataCumNumIterations(amg_data) ((amg_data)->cum_num_iterations) #endif #define hypre_ParAMGDataRelativeResidualNorm(amg_data) ((amg_data)->rel_resid_norm) #define hypre_ParAMGDataResidual(amg_data) ((amg_data)->residual) /* output parameters */ #define hypre_ParAMGDataPrintLevel(amg_data) ((amg_data)->print_level) #define hypre_ParAMGDataLogFileName(amg_data) ((amg_data)->log_file_name) #define hypre_ParAMGDataDebugFlag(amg_data) ((amg_data)->debug_flag) #define hypre_ParAMGDataCumNnzAP(amg_data) ((amg_data)->cum_nnz_AP) #define hypre_ParAMGDataCoarseSolver(amg_data) ((amg_data)->coarse_solver) #define hypre_ParAMGDataACoarse(amg_data) ((amg_data)->A_coarse) #define hypre_ParAMGDataFCoarse(amg_data) ((amg_data)->f_coarse) #define hypre_ParAMGDataUCoarse(amg_data) ((amg_data)->u_coarse) #define hypre_ParAMGDataNewComm(amg_data) ((amg_data)->new_comm) #define hypre_ParAMGDataRedundant(amg_data) ((amg_data)->redundant) #define hypre_ParAMGDataParticipate(amg_data) ((amg_data)->participate) #define hypre_ParAMGDataAMat(amg_data) ((amg_data)->A_mat) #define hypre_ParAMGDataBVec(amg_data) ((amg_data)->b_vec) #define hypre_ParAMGDataCommInfo(amg_data) ((amg_data)->comm_info) /* additive AMG parameters */ #define hypre_ParAMGDataAdditive(amg_data) ((amg_data)->additive) #define hypre_ParAMGDataMultAdditive(amg_data) ((amg_data)->mult_additive) #define hypre_ParAMGDataSimple(amg_data) ((amg_data)->simple) #define hypre_ParAMGDataAddLastLvl(amg_data) ((amg_data)->add_last_lvl) #define hypre_ParAMGDataMultAddPMaxElmts(amg_data) ((amg_data)->add_P_max_elmts) #define hypre_ParAMGDataMultAddTruncFactor(amg_data) ((amg_data)->add_trunc_factor) #define hypre_ParAMGDataAddRelaxType(amg_data) ((amg_data)->add_rlx_type) #define hypre_ParAMGDataAddRelaxWt(amg_data) ((amg_data)->add_rlx_wt) #define hypre_ParAMGDataLambda(amg_data) ((amg_data)->Lambda) #define hypre_ParAMGDataAtilde(amg_data) ((amg_data)->Atilde) #define hypre_ParAMGDataRtilde(amg_data) ((amg_data)->Rtilde) #define hypre_ParAMGDataXtilde(amg_data) ((amg_data)->Xtilde) #define hypre_ParAMGDataDinv(amg_data) ((amg_data)->D_inv) /* non-Galerkin parameters */ #define hypre_ParAMGDataNonGalerkNumTol(amg_data) ((amg_data)->nongalerk_num_tol) #define hypre_ParAMGDataNonGalerkTol(amg_data) ((amg_data)->nongalerk_tol) #define hypre_ParAMGDataNonGalerkinTol(amg_data) ((amg_data)->nongalerkin_tol) #define hypre_ParAMGDataNonGalTolArray(amg_data) ((amg_data)->nongal_tol_array) #define hypre_ParAMGDataRAP2(amg_data) ((amg_data)->rap2) #define hypre_ParAMGDataKeepTranspose(amg_data) ((amg_data)->keepTranspose) #endif
14,437
41.589971
91
h
AMG
AMG-master/parcsr_ls/par_amg_solve.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * AMG solve routine * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "par_amg.h" /*-------------------------------------------------------------------- * hypre_BoomerAMGSolve *--------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGSolve( void *amg_vdata, hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ HYPRE_Int amg_print_level; HYPRE_Int amg_logging; HYPRE_Int cycle_count; HYPRE_Int num_levels; /* HYPRE_Int num_unknowns; */ HYPRE_Real tol; hypre_ParCSRMatrix **A_array; hypre_ParVector **F_array; hypre_ParVector **U_array; /* Local variables */ HYPRE_Int j; HYPRE_Int Solve_err_flag; HYPRE_Int min_iter; HYPRE_Int max_iter; HYPRE_Int num_procs, my_id; HYPRE_Int additive; HYPRE_Int mult_additive; HYPRE_Int simple; HYPRE_Real alpha = 1.0; HYPRE_Real beta = -1.0; HYPRE_Real cycle_op_count; HYPRE_Real total_coeffs; HYPRE_Real total_variables; HYPRE_Real *num_coeffs; HYPRE_Real *num_variables; HYPRE_Real cycle_cmplxty = 0.0; HYPRE_Real operat_cmplxty; HYPRE_Real grid_cmplxty; HYPRE_Real conv_factor = 0.0; HYPRE_Real resid_nrm = 1.0; HYPRE_Real resid_nrm_init = 0.0; HYPRE_Real relative_resid; HYPRE_Real rhs_norm = 0.0; HYPRE_Real old_resid; HYPRE_Real ieee_check = 0.; hypre_ParVector *Vtemp; hypre_ParVector *Residual; /*HYPRE_ANNOTATION_BEGIN("BoomerAMG.solve");*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); amg_print_level = hypre_ParAMGDataPrintLevel(amg_data); amg_logging = hypre_ParAMGDataLogging(amg_data); if ( amg_logging > 1 ) Residual = hypre_ParAMGDataResidual(amg_data); /* num_unknowns = hypre_ParAMGDataNumUnknowns(amg_data); */ num_levels = hypre_ParAMGDataNumLevels(amg_data); A_array = hypre_ParAMGDataAArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); tol = hypre_ParAMGDataTol(amg_data); min_iter = hypre_ParAMGDataMinIter(amg_data); max_iter = hypre_ParAMGDataMaxIter(amg_data); additive = hypre_ParAMGDataAdditive(amg_data); simple = hypre_ParAMGDataSimple(amg_data); mult_additive = hypre_ParAMGDataMultAdditive(amg_data); A_array[0] = A; F_array[0] = f; U_array[0] = u; /* Vtemp = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A_array[0]), hypre_ParCSRMatrixGlobalNumRows(A_array[0]), hypre_ParCSRMatrixRowStarts(A_array[0])); hypre_ParVectorInitialize(Vtemp); hypre_ParVectorSetPartitioningOwner(Vtemp,0); hypre_ParAMGDataVtemp(amg_data) = Vtemp; */ Vtemp = hypre_ParAMGDataVtemp(amg_data); /*----------------------------------------------------------------------- * Write the solver parameters *-----------------------------------------------------------------------*/ if (my_id == 0 && amg_print_level > 1) hypre_BoomerAMGWriteSolverParams(amg_data); /*----------------------------------------------------------------------- * Initialize the solver error flag and assorted bookkeeping variables *-----------------------------------------------------------------------*/ Solve_err_flag = 0; total_coeffs = 0; total_variables = 0; cycle_count = 0; operat_cmplxty = 0; grid_cmplxty = 0; /*----------------------------------------------------------------------- * write some initial info *-----------------------------------------------------------------------*/ if (my_id == 0 && amg_print_level > 1 && tol > 0.) hypre_printf("\n\nAMG SOLUTION INFO:\n"); /*----------------------------------------------------------------------- * Compute initial fine-grid residual and print *-----------------------------------------------------------------------*/ if (amg_print_level > 1 || amg_logging > 1 || tol > 0.) { if ( amg_logging > 1 ) { hypre_ParVectorCopy(F_array[0], Residual ); if (tol > 0) hypre_ParCSRMatrixMatvec(alpha, A_array[0], U_array[0], beta, Residual ); resid_nrm = sqrt(hypre_ParVectorInnerProd( Residual, Residual )); } else { hypre_ParVectorCopy(F_array[0], Vtemp); if (tol > 0) hypre_ParCSRMatrixMatvec(alpha, A_array[0], U_array[0], beta, Vtemp); resid_nrm = sqrt(hypre_ParVectorInnerProd(Vtemp, Vtemp)); } /* Since it is does not diminish performance, attempt to return an error flag and notify users when they supply bad input. */ if (resid_nrm != 0.) ieee_check = resid_nrm/resid_nrm; /* INF -> NaN conversion */ if (ieee_check != ieee_check) { /* ...INFs or NaNs in input can make ieee_check a NaN. This test for ieee_check self-equality works on all IEEE-compliant compilers/ machines, c.f. page 8 of "Lecture Notes on the Status of IEEE 754" by W. Kahan, May 31, 1996. Currently (July 2002) this paper may be found at http://HTTP.CS.Berkeley.EDU/~wkahan/ieee754status/IEEE754.PDF */ if (amg_print_level > 0) { hypre_printf("\n\nERROR detected by Hypre ... BEGIN\n"); hypre_printf("ERROR -- hypre_BoomerAMGSolve: INFs and/or NaNs detected in input.\n"); hypre_printf("User probably placed non-numerics in supplied A, x_0, or b.\n"); hypre_printf("ERROR detected by Hypre ... END\n\n\n"); } hypre_error(HYPRE_ERROR_GENERIC); /*HYPRE_ANNOTATION_END("BoomerAMG.solve");*/ return hypre_error_flag; } resid_nrm_init = resid_nrm; rhs_norm = sqrt(hypre_ParVectorInnerProd(f, f)); if (rhs_norm) { relative_resid = resid_nrm_init / rhs_norm; } else { relative_resid = resid_nrm_init; } } else { relative_resid = 1.; } if (my_id == 0 && amg_print_level > 1) { hypre_printf(" relative\n"); hypre_printf(" residual factor residual\n"); hypre_printf(" -------- ------ --------\n"); hypre_printf(" Initial %e %e\n",resid_nrm_init, relative_resid); } /*----------------------------------------------------------------------- * Main V-cycle loop *-----------------------------------------------------------------------*/ while ((relative_resid >= tol || cycle_count < min_iter) && cycle_count < max_iter) { hypre_ParAMGDataCycleOpCount(amg_data) = 0; /* Op count only needed for one cycle */ if ((additive < 0 || additive >= num_levels) && (mult_additive < 0 || mult_additive >= num_levels) && (simple < 0 || simple >= num_levels) ) hypre_BoomerAMGCycle(amg_data, F_array, U_array); else hypre_BoomerAMGAdditiveCycle(amg_data); /*--------------------------------------------------------------- * Compute fine-grid residual and residual norm *----------------------------------------------------------------*/ if (amg_print_level > 1 || amg_logging > 1 || tol > 0.) { old_resid = resid_nrm; if ( amg_logging > 1 ) { hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A_array[0], U_array[0], beta, F_array[0], Residual ); resid_nrm = sqrt(hypre_ParVectorInnerProd( Residual, Residual )); } else { hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A_array[0], U_array[0], beta, F_array[0], Vtemp); resid_nrm = sqrt(hypre_ParVectorInnerProd(Vtemp, Vtemp)); } if (old_resid) conv_factor = resid_nrm / old_resid; else conv_factor = resid_nrm; if (rhs_norm) { relative_resid = resid_nrm / rhs_norm; } else { relative_resid = resid_nrm; } hypre_ParAMGDataRelativeResidualNorm(amg_data) = relative_resid; } ++cycle_count; hypre_ParAMGDataNumIterations(amg_data) = cycle_count; #ifdef CUMNUMIT ++hypre_ParAMGDataCumNumIterations(amg_data); #endif if (my_id == 0 && amg_print_level > 1) { hypre_printf(" Cycle %2d %e %f %e \n", cycle_count, resid_nrm, conv_factor, relative_resid); } } if (cycle_count == max_iter && tol > 0.) { Solve_err_flag = 1; hypre_error(HYPRE_ERROR_CONV); } /*----------------------------------------------------------------------- * Compute closing statistics *-----------------------------------------------------------------------*/ if (cycle_count > 0 && resid_nrm_init) conv_factor = pow((resid_nrm/resid_nrm_init),(1.0/(HYPRE_Real) cycle_count)); else conv_factor = 1.; if (amg_print_level > 1) { num_coeffs = hypre_CTAlloc(HYPRE_Real, num_levels); num_variables = hypre_CTAlloc(HYPRE_Real, num_levels); num_coeffs[0] = hypre_ParCSRMatrixDNumNonzeros(A); num_variables[0] = hypre_ParCSRMatrixGlobalNumRows(A); for (j = 1; j < num_levels; j++) { num_coeffs[j] = (HYPRE_Real) hypre_ParCSRMatrixNumNonzeros(A_array[j]); num_variables[j] = (HYPRE_Real) hypre_ParCSRMatrixGlobalNumRows(A_array[j]); } for (j=0;j<hypre_ParAMGDataNumLevels(amg_data);j++) { total_coeffs += num_coeffs[j]; total_variables += num_variables[j]; } cycle_op_count = hypre_ParAMGDataCycleOpCount(amg_data); if (num_variables[0]) grid_cmplxty = total_variables / num_variables[0]; if (num_coeffs[0]) { operat_cmplxty = total_coeffs / num_coeffs[0]; cycle_cmplxty = cycle_op_count / num_coeffs[0]; } if (my_id == 0) { if (Solve_err_flag == 1) { hypre_printf("\n\n=============================================="); hypre_printf("\n NOTE: Convergence tolerance was not achieved\n"); hypre_printf(" within the allowed %d V-cycles\n",max_iter); hypre_printf("=============================================="); } hypre_printf("\n\n Average Convergence Factor = %f",conv_factor); hypre_printf("\n\n Complexity: grid = %f\n",grid_cmplxty); hypre_printf(" operator = %f\n",operat_cmplxty); hypre_printf(" cycle = %f\n\n\n\n",cycle_cmplxty); } hypre_TFree(num_coeffs); hypre_TFree(num_variables); } /* HYPRE_ANNOTATION_END("BoomerAMG.solve"); */ return hypre_error_flag; }
12,285
33.804533
106
c
AMG
AMG-master/parcsr_ls/par_cg_relax_wt.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * ParAMG cycling routine * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "par_amg.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGCycle *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCGRelaxWt( void *amg_vdata, HYPRE_Int level, HYPRE_Int num_cg_sweeps, HYPRE_Real *rlx_wt_ptr) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; MPI_Comm comm; /* Data Structure variables */ /* hypre_ParCSRMatrix **A_array = hypre_ParAMGDataAArray(amg_data); */ /* hypre_ParCSRMatrix **R_array = hypre_ParAMGDataRArray(amg_data); */ hypre_ParCSRMatrix *A = hypre_ParAMGDataAArray(amg_data)[level]; /* hypre_ParVector **F_array = hypre_ParAMGDataFArray(amg_data); */ /* hypre_ParVector **U_array = hypre_ParAMGDataUArray(amg_data); */ hypre_ParVector *Utemp; hypre_ParVector *Vtemp; hypre_ParVector *Ptemp; hypre_ParVector *Rtemp; hypre_ParVector *Ztemp; hypre_ParVector *Qtemp = NULL; HYPRE_Int *CF_marker = hypre_ParAMGDataCFMarkerArray(amg_data)[level]; HYPRE_Real *Ptemp_data; HYPRE_Real *Ztemp_data; /* HYPRE_Int **unknown_map_array; HYPRE_Int **point_map_array; HYPRE_Int **v_at_point_array; */ HYPRE_Int *grid_relax_type; /* Local variables */ HYPRE_Int Solve_err_flag; HYPRE_Int i, j, jj; HYPRE_Int num_sweeps; HYPRE_Int relax_type; HYPRE_Int local_size; HYPRE_Int old_size; HYPRE_Int my_id = 0; HYPRE_Int smooth_type; HYPRE_Int smooth_num_levels; HYPRE_Int smooth_option = 0; HYPRE_Real *l1_norms = NULL; HYPRE_Real alpha; HYPRE_Real beta; HYPRE_Real gamma = 1.0; HYPRE_Real gammaold; HYPRE_Real *tridiag; HYPRE_Real *trioffd; HYPRE_Real alphinv, row_sum = 0; HYPRE_Real max_row_sum = 0; HYPRE_Real rlx_wt = 0; HYPRE_Real rlx_wt_old = 0; HYPRE_Real lambda_max, lambda_max_old; /* HYPRE_Real lambda_min, lambda_min_old; */ #if 0 HYPRE_Real *D_mat; HYPRE_Real *S_vec; #endif HYPRE_Int num_threads; num_threads = hypre_NumThreads(); /* Acquire data and allocate storage */ tridiag = hypre_CTAlloc(HYPRE_Real, num_cg_sweeps+1); trioffd = hypre_CTAlloc(HYPRE_Real, num_cg_sweeps+1); for (i=0; i < num_cg_sweeps+1; i++) { tridiag[i] = 0; trioffd[i] = 0; } Vtemp = hypre_ParAMGDataVtemp(amg_data); Rtemp = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(Rtemp); hypre_ParVectorSetPartitioningOwner(Rtemp,0); Ptemp = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(Ptemp); hypre_ParVectorSetPartitioningOwner(Ptemp,0); Ztemp = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(Ztemp); hypre_ParVectorSetPartitioningOwner(Ztemp,0); if (hypre_ParAMGDataL1Norms(amg_data) != NULL) l1_norms = hypre_ParAMGDataL1Norms(amg_data)[level]; if (num_threads > 1) { Qtemp = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(Qtemp); hypre_ParVectorSetPartitioningOwner(Qtemp,0); } grid_relax_type = hypre_ParAMGDataGridRelaxType(amg_data); /* Initialize */ Solve_err_flag = 0; comm = hypre_ParCSRMatrixComm(A); hypre_MPI_Comm_rank(comm,&my_id); /*--------------------------------------------------------------------- * Main loop of cycling *--------------------------------------------------------------------*/ relax_type = grid_relax_type[1]; num_sweeps = 1; local_size = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); old_size = hypre_VectorSize(hypre_ParVectorLocalVector(Vtemp)); hypre_VectorSize(hypre_ParVectorLocalVector(Vtemp)) = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); Ptemp_data = hypre_VectorData(hypre_ParVectorLocalVector(Ptemp)); Ztemp_data = hypre_VectorData(hypre_ParVectorLocalVector(Ztemp)); /* if (level == 0) hypre_ParVectorCopy(hypre_ParAMGDataFArray(amg_data)[0],Rtemp); else { hypre_ParVectorCopy(F_array[level-1],Vtemp); alpha = -1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, A_array[level-1], U_array[level-1], beta, Vtemp); alpha = 1.0; beta = 0.0; hypre_ParCSRMatrixMatvecT(alpha,R_array[level-1],Vtemp, beta,F_array[level]); hypre_ParVectorCopy(F_array[level],Rtemp); } */ hypre_ParVectorSetRandomValues(Rtemp,5128); /*------------------------------------------------------------------ * Do the relaxation num_sweeps times *-----------------------------------------------------------------*/ for (jj = 0; jj < num_cg_sweeps; jj++) { hypre_ParVectorSetConstantValues(Ztemp, 0.0); for (j = 0; j < num_sweeps; j++) { Solve_err_flag = hypre_BoomerAMGRelax(A, Rtemp, CF_marker, relax_type, 0, 1.0, 1.0, l1_norms, Ztemp, Vtemp, Qtemp); if (Solve_err_flag != 0) { hypre_ParVectorDestroy(Ptemp); hypre_TFree(tridiag); hypre_TFree(trioffd); return(Solve_err_flag); } } gammaold = gamma; gamma = hypre_ParVectorInnerProd(Rtemp,Ztemp); if (jj == 0) { hypre_ParVectorCopy(Ztemp,Ptemp); beta = 1.0; } else { beta = gamma/gammaold; for (i=0; i < local_size; i++) Ptemp_data[i] = Ztemp_data[i] + beta*Ptemp_data[i]; } hypre_ParCSRMatrixMatvec(1.0,A,Ptemp,0.0,Vtemp); alpha = gamma /hypre_ParVectorInnerProd(Ptemp,Vtemp); alphinv = 1.0/alpha; tridiag[jj+1] = alphinv; tridiag[jj] *= beta; tridiag[jj] += alphinv; trioffd[jj] *= sqrt(beta); trioffd[jj+1] = -alphinv; row_sum = fabs(tridiag[jj]) + fabs(trioffd[jj]); if (row_sum > max_row_sum) max_row_sum = row_sum; if (jj > 0) { row_sum = fabs(tridiag[jj-1]) + fabs(trioffd[jj-1]) + fabs(trioffd[jj]); if (row_sum > max_row_sum) max_row_sum = row_sum; /* lambda_min_old = lambda_min; */ lambda_max_old = lambda_max; rlx_wt_old = rlx_wt; hypre_Bisection(jj+1, tridiag, trioffd, lambda_max_old, max_row_sum, 1.e-3, jj+1, &lambda_max); rlx_wt = 1.0/lambda_max; /* hypre_Bisection(jj+1, tridiag, trioffd, 0.0, lambda_min_old, 1.e-3, 1, &lambda_min); rlx_wt = 2.0/(lambda_min+lambda_max); */ if (fabs(rlx_wt-rlx_wt_old) < 1.e-3 ) { /* if (my_id == 0) hypre_printf (" cg sweeps : %d\n", (jj+1)); */ break; } } else { /* lambda_min = tridiag[0]; */ lambda_max = tridiag[0]; } hypre_ParVectorAxpy(-alpha,Vtemp,Rtemp); } /*if (my_id == 0) hypre_printf (" lambda-min: %f lambda-max: %f\n", lambda_min, lambda_max); rlx_wt = fabs(tridiag[0])+fabs(trioffd[1]); for (i=1; i < num_cg_sweeps-1; i++) { row_sum = fabs(tridiag[i]) + fabs(trioffd[i]) + fabs(trioffd[i+1]); if (row_sum > rlx_wt) rlx_wt = row_sum; } row_sum = fabs(tridiag[num_cg_sweeps-1]) + fabs(trioffd[num_cg_sweeps-1]); if (row_sum > rlx_wt) rlx_wt = row_sum; hypre_Bisection(num_cg_sweeps, tridiag, trioffd, 0.0, rlx_wt, 1.e-3, 1, &lambda_min); hypre_Bisection(num_cg_sweeps, tridiag, trioffd, 0.0, rlx_wt, 1.e-3, num_cg_sweeps, &lambda_max); */ hypre_VectorSize(hypre_ParVectorLocalVector(Vtemp)) = old_size; hypre_ParVectorDestroy(Ztemp); hypre_ParVectorDestroy(Ptemp); hypre_ParVectorDestroy(Rtemp); if (num_threads > 1) hypre_ParVectorDestroy(Qtemp); hypre_TFree(tridiag); hypre_TFree(trioffd); if (smooth_option > 6 && smooth_option < 10) { hypre_ParVectorDestroy(Utemp); } *rlx_wt_ptr = rlx_wt; return(Solve_err_flag); } /*-------------------------------------------------------------------------- * hypre_Bisection *--------------------------------------------------------------------------*/ HYPRE_Int hypre_Bisection(HYPRE_Int n, HYPRE_Real *diag, HYPRE_Real *offd, HYPRE_Real y, HYPRE_Real z, HYPRE_Real tol, HYPRE_Int k, HYPRE_Real *ev_ptr) { HYPRE_Real x; HYPRE_Real eigen_value; HYPRE_Int ierr = 0; HYPRE_Int sign_change = 0; HYPRE_Int i; HYPRE_Real p0, p1, p2; while (fabs(y-z) > tol*(fabs(y) + fabs(z))) { x = (y+z)/2; sign_change = 0; p0 = 1; p1 = diag[0] - x; if (p0*p1 <= 0) sign_change++; for (i=1; i < n; i++) { p2 = (diag[i] - x)*p1 - offd[i]*offd[i]*p0; p0 = p1; p1 = p2; if (p0*p1 <= 0) sign_change++; } if (sign_change >= k) z = x; else y = x; } eigen_value = (y+z)/2; *ev_ptr = eigen_value; return ierr; }
11,180
30.144847
81
c
AMG
AMG-master/parcsr_ls/par_coordinates.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * GenerateCoordinates *--------------------------------------------------------------------------*/ float * GenerateCoordinates( MPI_Comm comm, HYPRE_Int nx, HYPRE_Int ny, HYPRE_Int nz, HYPRE_Int P, HYPRE_Int Q, HYPRE_Int R, HYPRE_Int p, HYPRE_Int q, HYPRE_Int r, HYPRE_Int coorddim) { HYPRE_Int ix, iy, iz; HYPRE_Int cnt; HYPRE_Int nx_local, ny_local, nz_local; HYPRE_Int local_num_rows; HYPRE_Int *nx_part; HYPRE_Int *ny_part; HYPRE_Int *nz_part; float *coord=NULL; if (coorddim<1 || coorddim>3) { return NULL; } hypre_GeneratePartitioning(nx,P,&nx_part); hypre_GeneratePartitioning(ny,Q,&ny_part); hypre_GeneratePartitioning(nz,R,&nz_part); nx_local = nx_part[p+1] - nx_part[p]; ny_local = ny_part[q+1] - ny_part[q]; nz_local = nz_part[r+1] - nz_part[r]; local_num_rows = nx_local*ny_local*nz_local; coord = hypre_CTAlloc(float, coorddim*local_num_rows); cnt = 0; for (iz = nz_part[r]; iz < nz_part[r+1]; iz++) { for (iy = ny_part[q]; iy < ny_part[q+1]; iy++) { for (ix = nx_part[p]; ix < nx_part[p+1]; ix++) { /* set coordinates BM Oct 17, 2006 */ if (coord) { if (nx>1) coord[cnt++] = ix; if (ny>1) coord[cnt++] = iy; if (nz>1) coord[cnt++] = iz; } } } } hypre_TFree(nx_part); hypre_TFree(ny_part); hypre_TFree(nz_part); return coord; }
2,564
26.880435
81
c
AMG
AMG-master/parcsr_ls/par_cycle.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * ParAMG cycling routine * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "par_amg.h" #ifdef HYPRE_USING_CALIPER #include <caliper/cali.h> #endif /*-------------------------------------------------------------------------- * hypre_BoomerAMGCycle *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCycle( void *amg_vdata, hypre_ParVector **F_array, hypre_ParVector **U_array ) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ hypre_ParCSRMatrix **A_array; hypre_ParCSRMatrix **P_array; hypre_ParCSRMatrix **R_array; hypre_ParVector *Utemp; hypre_ParVector *Vtemp; hypre_ParVector *Rtemp; hypre_ParVector *Ptemp; hypre_ParVector *Ztemp; hypre_ParVector *Aux_U; hypre_ParVector *Aux_F; HYPRE_Real *Ztemp_data; HYPRE_Real *Ptemp_data; HYPRE_Int **CF_marker_array; /* HYPRE_Int **unknown_map_array; HYPRE_Int **point_map_array; HYPRE_Int **v_at_point_array; */ HYPRE_Real cycle_op_count; HYPRE_Int cycle_type; HYPRE_Int num_levels; HYPRE_Int max_levels; HYPRE_Real *num_coeffs; HYPRE_Int *num_grid_sweeps; HYPRE_Int *grid_relax_type; HYPRE_Int **grid_relax_points; HYPRE_Int cheby_order; /* Local variables */ HYPRE_Int *lev_counter; HYPRE_Int Solve_err_flag; HYPRE_Int k; HYPRE_Int i, j, jj; HYPRE_Int level; HYPRE_Int cycle_param; HYPRE_Int coarse_grid; HYPRE_Int fine_grid; HYPRE_Int Not_Finished; HYPRE_Int num_sweep; HYPRE_Int cg_num_sweep = 1; HYPRE_Int relax_type; HYPRE_Int relax_points; HYPRE_Int relax_order; HYPRE_Int relax_local; HYPRE_Int old_version = 0; HYPRE_Real *relax_weight; HYPRE_Real *omega; HYPRE_Real alfa, beta, gammaold; HYPRE_Real gamma = 1.0; HYPRE_Int local_size; HYPRE_Int num_threads, my_id; HYPRE_Real alpha; HYPRE_Real **l1_norms = NULL; HYPRE_Real *l1_norms_level; HYPRE_Real **ds = hypre_ParAMGDataChebyDS(amg_data); HYPRE_Real **coefs = hypre_ParAMGDataChebyCoefs(amg_data); HYPRE_Int seq_cg = 0; MPI_Comm comm; #if 0 HYPRE_Real *D_mat; HYPRE_Real *S_vec; #endif #ifdef HYPRE_USING_CALIPER cali_id_t iter_attr = cali_create_attribute("hypre.par_cycle.level", CALI_TYPE_INT, CALI_ATTR_DEFAULT); #endif /* Acquire data and allocate storage */ num_threads = hypre_NumThreads(); A_array = hypre_ParAMGDataAArray(amg_data); P_array = hypre_ParAMGDataPArray(amg_data); R_array = hypre_ParAMGDataRArray(amg_data); CF_marker_array = hypre_ParAMGDataCFMarkerArray(amg_data); Vtemp = hypre_ParAMGDataVtemp(amg_data); Rtemp = hypre_ParAMGDataRtemp(amg_data); Ptemp = hypre_ParAMGDataPtemp(amg_data); Ztemp = hypre_ParAMGDataZtemp(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); max_levels = hypre_ParAMGDataMaxLevels(amg_data); cycle_type = hypre_ParAMGDataCycleType(amg_data); num_grid_sweeps = hypre_ParAMGDataNumGridSweeps(amg_data); grid_relax_type = hypre_ParAMGDataGridRelaxType(amg_data); grid_relax_points = hypre_ParAMGDataGridRelaxPoints(amg_data); relax_order = hypre_ParAMGDataRelaxOrder(amg_data); relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); omega = hypre_ParAMGDataOmega(amg_data); l1_norms = hypre_ParAMGDataL1Norms(amg_data); /*max_eig_est = hypre_ParAMGDataMaxEigEst(amg_data); min_eig_est = hypre_ParAMGDataMinEigEst(amg_data); cheby_fraction = hypre_ParAMGDataChebyFraction(amg_data);*/ cheby_order = hypre_ParAMGDataChebyOrder(amg_data); cycle_op_count = hypre_ParAMGDataCycleOpCount(amg_data); lev_counter = hypre_CTAlloc(HYPRE_Int, num_levels); if (hypre_ParAMGDataParticipate(amg_data)) seq_cg = 1; /* Initialize */ Solve_err_flag = 0; if (grid_relax_points) old_version = 1; num_coeffs = hypre_CTAlloc(HYPRE_Real, num_levels); num_coeffs[0] = hypre_ParCSRMatrixDNumNonzeros(A_array[0]); comm = hypre_ParCSRMatrixComm(A_array[0]); hypre_MPI_Comm_rank(comm,&my_id); for (j = 1; j < num_levels; j++) num_coeffs[j] = hypre_ParCSRMatrixDNumNonzeros(A_array[j]); /*--------------------------------------------------------------------- * Initialize cycling control counter * * Cycling is controlled using a level counter: lev_counter[k] * * Each time relaxation is performed on level k, the * counter is decremented by 1. If the counter is then * negative, we go to the next finer level. If non- * negative, we go to the next coarser level. The * following actions control cycling: * * a. lev_counter[0] is initialized to 1. * b. lev_counter[k] is initialized to cycle_type for k>0. * * c. During cycling, when going down to level k, lev_counter[k] * is set to the max of (lev_counter[k],cycle_type) *---------------------------------------------------------------------*/ Not_Finished = 1; lev_counter[0] = 1; for (k = 1; k < num_levels; ++k) { lev_counter[k] = cycle_type; } level = 0; cycle_param = 1; /*--------------------------------------------------------------------- * Main loop of cycling *--------------------------------------------------------------------*/ #ifdef HYPRE_USING_CALIPER cali_set_int(iter_attr, level); #endif while (Not_Finished) { if (num_levels > 1) { local_size = hypre_VectorSize(hypre_ParVectorLocalVector(F_array[level])); hypre_VectorSize(hypre_ParVectorLocalVector(Vtemp)) = local_size; cg_num_sweep = 1; num_sweep = num_grid_sweeps[cycle_param]; Aux_U = U_array[level]; Aux_F = F_array[level]; relax_type = grid_relax_type[cycle_param]; } else /* AB: 4/08: removed the max_levels > 1 check - should do this when max-levels = 1 also */ { /* If no coarsening occurred, apply a simple smoother once */ Aux_U = U_array[level]; Aux_F = F_array[level]; num_sweep = 1; /* TK: Use the user relax type (instead of 0) to allow for setting a convergent smoother (e.g. in the solution of singular problems). */ relax_type = hypre_ParAMGDataUserRelaxType(amg_data); if (relax_type == -1) relax_type = 6; } if (l1_norms != NULL) l1_norms_level = l1_norms[level]; else l1_norms_level = NULL; if (cycle_param == 3 && seq_cg) { hypre_seqAMGCycle(amg_data, level, F_array, U_array); } else { /*------------------------------------------------------------------ * Do the relaxation num_sweep times *-----------------------------------------------------------------*/ for (jj = 0; jj < cg_num_sweep; jj++) { for (j = 0; j < num_sweep; j++) { if (num_levels == 1 && max_levels > 1) { relax_points = 0; relax_local = 0; } else { if (old_version) relax_points = grid_relax_points[cycle_param][j]; relax_local = relax_order; } /*----------------------------------------------- * VERY sloppy approximation to cycle complexity *-----------------------------------------------*/ if (old_version && level < num_levels -1) { switch (relax_points) { case 1: cycle_op_count += num_coeffs[level+1]; break; case -1: cycle_op_count += (num_coeffs[level]-num_coeffs[level+1]); break; } } else { cycle_op_count += num_coeffs[level]; } /*----------------------------------------------- Choose Smoother -----------------------------------------------*/ if (relax_type == 9 || relax_type == 99) { /* Gaussian elimination */ hypre_GaussElimSolve(amg_data, level, relax_type); } else if (relax_type == 18) { /* L1 - Jacobi*/ if (relax_order == 1 && cycle_param < 3) { /* need to do CF - so can't use the AMS one */ HYPRE_Int i; HYPRE_Int loc_relax_points[2]; if (cycle_type < 2) { loc_relax_points[0] = 1; loc_relax_points[1] = -1; } else { loc_relax_points[0] = -1; loc_relax_points[1] = 1; } for (i=0; i < 2; i++) hypre_ParCSRRelax_L1_Jacobi(A_array[level], Aux_F, CF_marker_array[level], loc_relax_points[i], relax_weight[level], l1_norms[level], Aux_U, Vtemp); } else /* not CF - so use through AMS */ { if (num_threads == 1) hypre_ParCSRRelax(A_array[level], Aux_F, 1, 1, l1_norms_level, relax_weight[level], omega[level],0,0,0,0, Aux_U, Vtemp, Ztemp); else hypre_ParCSRRelaxThreads(A_array[level], Aux_F, 1, 1, l1_norms_level, relax_weight[level], omega[level], Aux_U, Vtemp, Ztemp); } } else if (relax_type == 16) { /* scaled Chebyshev */ HYPRE_Int scale = hypre_ParAMGDataChebyScale(amg_data); HYPRE_Int variant = hypre_ParAMGDataChebyVariant(amg_data); hypre_ParCSRRelax_Cheby_Solve(A_array[level], Aux_F, ds[level], coefs[level], cheby_order, scale, variant, Aux_U, Vtemp, Ztemp ); } else if (relax_type ==17) { hypre_BoomerAMGRelax_FCFJacobi(A_array[level], Aux_F, CF_marker_array[level], relax_weight[level], Aux_U, Vtemp); } else if (old_version) { Solve_err_flag = hypre_BoomerAMGRelax(A_array[level], Aux_F, CF_marker_array[level], relax_type, relax_points, relax_weight[level], omega[level], l1_norms_level, Aux_U, Vtemp, Ztemp); } else { /* smoother than can have CF ordering */ Solve_err_flag = hypre_BoomerAMGRelaxIF(A_array[level], Aux_F, CF_marker_array[level], relax_type, relax_local, cycle_param, relax_weight[level], omega[level], l1_norms_level, Aux_U, Vtemp, Ztemp); } if (Solve_err_flag != 0) return(Solve_err_flag); } } } /*------------------------------------------------------------------ * Decrement the control counter and determine which grid to visit next *-----------------------------------------------------------------*/ --lev_counter[level]; if (lev_counter[level] >= 0 && level != num_levels-1) { /*--------------------------------------------------------------- * Visit coarser level next. * Compute residual using hypre_ParCSRMatrixMatvec. * Perform restriction using hypre_ParCSRMatrixMatvecT. * Reset counters and cycling parameters for coarse level *--------------------------------------------------------------*/ fine_grid = level; coarse_grid = level + 1; hypre_ParVectorSetConstantValues(U_array[coarse_grid], 0.0); alpha = -1.0; beta = 1.0; // JSP: avoid unnecessary copy using out-of-place version of SpMV hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A_array[fine_grid], U_array[fine_grid], beta, F_array[fine_grid], Vtemp); alpha = 1.0; beta = 0.0; hypre_ParCSRMatrixMatvecT(alpha,R_array[fine_grid],Vtemp, beta,F_array[coarse_grid]); ++level; lev_counter[level] = hypre_max(lev_counter[level],cycle_type); cycle_param = 1; if (level == num_levels-1) cycle_param = 3; #ifdef HYPRE_USING_CALIPER cali_set_int(iter_attr, level); /* set the level for caliper here */ #endif } else if (level != 0) { /*--------------------------------------------------------------- * Visit finer level next. * Interpolate and add correction using hypre_ParCSRMatrixMatvec. * Reset counters and cycling parameters for finer level. *--------------------------------------------------------------*/ fine_grid = level - 1; coarse_grid = level; alpha = 1.0; beta = 1.0; hypre_ParCSRMatrixMatvec(alpha, P_array[fine_grid], U_array[coarse_grid], beta, U_array[fine_grid]); --level; cycle_param = 2; #ifdef HYPRE_USING_CALIPER cali_set_int(iter_attr, level); /* set the level for caliper here */ #endif } else { Not_Finished = 0; } } #ifdef HYPRE_USING_CALIPER cali_end(iter_attr); /* unset "iter" */ #endif hypre_ParAMGDataCycleOpCount(amg_data) = cycle_op_count; hypre_TFree(lev_counter); hypre_TFree(num_coeffs); return(Solve_err_flag); }
17,740
35.730849
101
c
AMG
AMG-master/parcsr_ls/par_difconv.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_GenerateDifConv *--------------------------------------------------------------------------*/ HYPRE_ParCSRMatrix GenerateDifConv( MPI_Comm comm, HYPRE_Int nx, HYPRE_Int ny, HYPRE_Int nz, HYPRE_Int P, HYPRE_Int Q, HYPRE_Int R, HYPRE_Int p, HYPRE_Int q, HYPRE_Int r, HYPRE_Real *value ) { hypre_ParCSRMatrix *A; hypre_CSRMatrix *diag; hypre_CSRMatrix *offd; HYPRE_Int *diag_i; HYPRE_Int *diag_j; HYPRE_Real *diag_data; HYPRE_Int *offd_i; HYPRE_Int *offd_j; HYPRE_Real *offd_data; HYPRE_Int *global_part; HYPRE_Int ix, iy, iz; HYPRE_Int cnt, o_cnt; HYPRE_Int local_num_rows; HYPRE_Int *col_map_offd; HYPRE_Int row_index; HYPRE_Int i,j; HYPRE_Int nx_local, ny_local, nz_local; HYPRE_Int nx_size, ny_size, nz_size; HYPRE_Int num_cols_offd; HYPRE_Int grid_size; HYPRE_Int *nx_part; HYPRE_Int *ny_part; HYPRE_Int *nz_part; HYPRE_Int num_procs, my_id; HYPRE_Int P_busy, Q_busy, R_busy; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); grid_size = nx*ny*nz; hypre_GeneratePartitioning(nx,P,&nx_part); hypre_GeneratePartitioning(ny,Q,&ny_part); hypre_GeneratePartitioning(nz,R,&nz_part); global_part = hypre_CTAlloc(HYPRE_Int,P*Q*R+1); global_part[0] = 0; cnt = 1; for (iz = 0; iz < R; iz++) { nz_size = nz_part[iz+1]-nz_part[iz]; for (iy = 0; iy < Q; iy++) { ny_size = ny_part[iy+1]-ny_part[iy]; for (ix = 0; ix < P; ix++) { nx_size = nx_part[ix+1] - nx_part[ix]; global_part[cnt] = global_part[cnt-1]; global_part[cnt++] += nx_size*ny_size*nz_size; } } } nx_local = nx_part[p+1] - nx_part[p]; ny_local = ny_part[q+1] - ny_part[q]; nz_local = nz_part[r+1] - nz_part[r]; my_id = r*(P*Q) + q*P + p; num_procs = P*Q*R; local_num_rows = nx_local*ny_local*nz_local; diag_i = hypre_CTAlloc(HYPRE_Int, local_num_rows+1); offd_i = hypre_CTAlloc(HYPRE_Int, local_num_rows+1); P_busy = hypre_min(nx,P); Q_busy = hypre_min(ny,Q); R_busy = hypre_min(nz,R); num_cols_offd = 0; if (p) num_cols_offd += ny_local*nz_local; if (p < P_busy-1) num_cols_offd += ny_local*nz_local; if (q) num_cols_offd += nx_local*nz_local; if (q < Q_busy-1) num_cols_offd += nx_local*nz_local; if (r) num_cols_offd += nx_local*ny_local; if (r < R_busy-1) num_cols_offd += nx_local*ny_local; if (!local_num_rows) num_cols_offd = 0; col_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); cnt = 1; o_cnt = 1; diag_i[0] = 0; offd_i[0] = 0; for (iz = nz_part[r]; iz < nz_part[r+1]; iz++) { for (iy = ny_part[q]; iy < ny_part[q+1]; iy++) { for (ix = nx_part[p]; ix < nx_part[p+1]; ix++) { diag_i[cnt] = diag_i[cnt-1]; offd_i[o_cnt] = offd_i[o_cnt-1]; diag_i[cnt]++; if (iz > nz_part[r]) diag_i[cnt]++; else { if (iz) { offd_i[o_cnt]++; } } if (iy > ny_part[q]) diag_i[cnt]++; else { if (iy) { offd_i[o_cnt]++; } } if (ix > nx_part[p]) diag_i[cnt]++; else { if (ix) { offd_i[o_cnt]++; } } if (ix+1 < nx_part[p+1]) diag_i[cnt]++; else { if (ix+1 < nx) { offd_i[o_cnt]++; } } if (iy+1 < ny_part[q+1]) diag_i[cnt]++; else { if (iy+1 < ny) { offd_i[o_cnt]++; } } if (iz+1 < nz_part[r+1]) diag_i[cnt]++; else { if (iz+1 < nz) { offd_i[o_cnt]++; } } cnt++; o_cnt++; } } } diag_j = hypre_CTAlloc(HYPRE_Int, diag_i[local_num_rows]); diag_data = hypre_CTAlloc(HYPRE_Real, diag_i[local_num_rows]); if (num_procs > 1) { offd_j = hypre_CTAlloc(HYPRE_Int, offd_i[local_num_rows]); offd_data = hypre_CTAlloc(HYPRE_Real, offd_i[local_num_rows]); } row_index = 0; cnt = 0; o_cnt = 0; for (iz = nz_part[r]; iz < nz_part[r+1]; iz++) { for (iy = ny_part[q]; iy < ny_part[q+1]; iy++) { for (ix = nx_part[p]; ix < nx_part[p+1]; ix++) { diag_j[cnt] = row_index; diag_data[cnt++] = value[0]; if (iz > nz_part[r]) { diag_j[cnt] = row_index-nx_local*ny_local; diag_data[cnt++] = value[3]; } else { if (iz) { offd_j[o_cnt] = hypre_map(ix,iy,iz-1,p,q,r-1,P,Q,R, nx_part,ny_part,nz_part,global_part); offd_data[o_cnt++] = value[3]; } } if (iy > ny_part[q]) { diag_j[cnt] = row_index-nx_local; diag_data[cnt++] = value[2]; } else { if (iy) { offd_j[o_cnt] = hypre_map(ix,iy-1,iz,p,q-1,r,P,Q,R, nx_part,ny_part,nz_part,global_part); offd_data[o_cnt++] = value[2]; } } if (ix > nx_part[p]) { diag_j[cnt] = row_index-1; diag_data[cnt++] = value[1]; } else { if (ix) { offd_j[o_cnt] = hypre_map(ix-1,iy,iz,p-1,q,r,P,Q,R, nx_part,ny_part,nz_part,global_part); offd_data[o_cnt++] = value[1]; } } if (ix+1 < nx_part[p+1]) { diag_j[cnt] = row_index+1; diag_data[cnt++] = value[4]; } else { if (ix+1 < nx) { offd_j[o_cnt] = hypre_map(ix+1,iy,iz,p+1,q,r,P,Q,R, nx_part,ny_part,nz_part,global_part); offd_data[o_cnt++] = value[4]; } } if (iy+1 < ny_part[q+1]) { diag_j[cnt] = row_index+nx_local; diag_data[cnt++] = value[5]; } else { if (iy+1 < ny) { offd_j[o_cnt] = hypre_map(ix,iy+1,iz,p,q+1,r,P,Q,R, nx_part,ny_part,nz_part,global_part); offd_data[o_cnt++] = value[5]; } } if (iz+1 < nz_part[r+1]) { diag_j[cnt] = row_index+nx_local*ny_local; diag_data[cnt++] = value[6]; } else { if (iz+1 < nz) { offd_j[o_cnt] = hypre_map(ix,iy,iz+1,p,q,r+1,P,Q,R, nx_part,ny_part,nz_part,global_part); offd_data[o_cnt++] = value[6]; } } row_index++; } } } if (num_procs > 1) { for (i=0; i < num_cols_offd; i++) col_map_offd[i] = offd_j[i]; hypre_qsort0(col_map_offd, 0, num_cols_offd-1); for (i=0; i < num_cols_offd; i++) for (j=0; j < num_cols_offd; j++) if (offd_j[i] == col_map_offd[j]) { offd_j[i] = j; break; } } #ifdef HYPRE_NO_GLOBAL_PARTITION /* ideally we would use less storage earlier in this function, but this is fine for testing */ { HYPRE_Int tmp1, tmp2; tmp1 = global_part[my_id]; tmp2 = global_part[my_id + 1]; hypre_TFree(global_part); global_part = hypre_CTAlloc(HYPRE_Int, 2); global_part[0] = tmp1; global_part[1] = tmp2; } #endif A = hypre_ParCSRMatrixCreate(comm, grid_size, grid_size, global_part, global_part, num_cols_offd, diag_i[local_num_rows], offd_i[local_num_rows]); hypre_ParCSRMatrixColMapOffd(A) = col_map_offd; diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_data; offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrixI(offd) = offd_i; if (num_cols_offd) { hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_data; } hypre_TFree(nx_part); hypre_TFree(ny_part); hypre_TFree(nz_part); return (HYPRE_ParCSRMatrix) A; }
10,430
27.422343
81
c
AMG
AMG-master/parcsr_ls/par_indepset.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * *****************************************************************************/ #include "_hypre_parcsr_ls.h" /*==========================================================================*/ /*==========================================================================*/ /** Augments measures by some random value between 0 and 1. {\bf Input files:} _hypre_parcsr_ls.h @return Error code. @param S [IN] parent graph matrix in CSR format @param measure_array [IN/OUT] measures assigned to each node of the parent graph @see hypre_AMGIndepSet */ /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGIndepSetInit( hypre_ParCSRMatrix *S, HYPRE_Real *measure_array , HYPRE_Int seq_rand) { hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); MPI_Comm comm = hypre_ParCSRMatrixComm(S); HYPRE_Int S_num_nodes = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int i, my_id; HYPRE_Int ierr = 0; hypre_MPI_Comm_rank(comm,&my_id); i = 2747+my_id; if (seq_rand) i = 2747; hypre_SeedRand(i); if (seq_rand) { for (i = 0; i < hypre_ParCSRMatrixFirstRowIndex(S); i++) hypre_Rand(); } for (i = 0; i < S_num_nodes; i++) { measure_array[i] += hypre_Rand(); } return (ierr); } /*==========================================================================*/ /*==========================================================================*/ /** Select an independent set from a graph. This graph is actually a subgraph of some parent graph. The parent graph is described as a matrix in compressed sparse row format, where edges in the graph are represented by nonzero matrix coefficients (zero coefficients are ignored). A positive measure is given for each node in the subgraph, and this is used to pick the independent set. A measure of zero must be given for all other nodes in the parent graph. The subgraph is a collection of nodes in the parent graph. Positive entries in the `IS\_marker' array indicate nodes in the independent set. All other entries are zero. The algorithm proceeds by first setting all nodes in `graph\_array' to be in the independent set. Nodes are then removed from the independent set by simply comparing the measures of adjacent nodes. {\bf Input files:} _hypre_parcsr_ls.h @return Error code. @param S [IN] parent graph matrix in CSR format @param measure_array [IN] measures assigned to each node of the parent graph @param graph_array [IN] node numbers in the subgraph to be partitioned @param graph_array_size [IN] number of nodes in the subgraph to be partitioned @param IS_marker [IN/OUT] marker array for independent set @see hypre_InitAMGIndepSet */ /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGIndepSet( hypre_ParCSRMatrix *S, HYPRE_Real *measure_array, HYPRE_Int *graph_array, HYPRE_Int graph_array_size, HYPRE_Int *graph_array_offd, HYPRE_Int graph_array_offd_size, HYPRE_Int *IS_marker, HYPRE_Int *IS_marker_offd ) { hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = NULL; HYPRE_Int local_num_vars = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int i, j, ig, jS, jj; HYPRE_Int ierr = 0; /*------------------------------------------------------- * Initialize IS_marker by putting all nodes in * the independent set. *-------------------------------------------------------*/ if (hypre_CSRMatrixNumCols(S_offd)) { S_offd_j = hypre_CSRMatrixJ(S_offd); } for (ig = 0; ig < graph_array_size; ig++) { i = graph_array[ig]; if (measure_array[i] > 1) { IS_marker[i] = 1; } } for (ig = 0; ig < graph_array_offd_size; ig++) { i = graph_array_offd[ig]; if (measure_array[i+local_num_vars] > 1) { IS_marker_offd[i] = 1; } } /*------------------------------------------------------- * Remove nodes from the initial independent set *-------------------------------------------------------*/ for (ig = 0; ig < graph_array_size; ig++) { i = graph_array[ig]; if (measure_array[i] > 1) { for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { j = S_diag_j[jS]; if (j < 0) j = -j-1; /* only consider valid graph edges */ /* if ( (measure_array[j] > 1) && (S_diag_data[jS]) ) */ if (measure_array[j] > 1) { if (measure_array[i] > measure_array[j]) { IS_marker[j] = 0; } else if (measure_array[j] > measure_array[i]) { IS_marker[i] = 0; } } } for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { jj = S_offd_j[jS]; if (jj < 0) jj = -jj-1; j = local_num_vars+jj; /* only consider valid graph edges */ /* if ( (measure_array[j] > 1) && (S_offd_data[jS]) ) */ if (measure_array[j] > 1) { if (measure_array[i] > measure_array[j]) { IS_marker_offd[jj] = 0; } else if (measure_array[j] > measure_array[i]) { IS_marker[i] = 0; } } } } } return (ierr); }
7,220
32.742991
81
c
AMG
AMG-master/parcsr_ls/par_rap_communication.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" HYPRE_Int hypre_GetCommPkgRTFromCommPkgA( hypre_ParCSRMatrix *RT, hypre_ParCSRMatrix *A, HYPRE_Int *fine_to_coarse_offd) { MPI_Comm comm = hypre_ParCSRMatrixComm(RT); hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_recvs_A = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int *recv_procs_A = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts_A = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int *send_procs_A = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); hypre_ParCSRCommPkg *comm_pkg; HYPRE_Int num_recvs_RT; HYPRE_Int *recv_procs_RT; HYPRE_Int *recv_vec_starts_RT; HYPRE_Int num_sends_RT; HYPRE_Int *send_procs_RT; HYPRE_Int *send_map_starts_RT; HYPRE_Int *send_map_elmts_RT; HYPRE_Int *col_map_offd_RT = hypre_ParCSRMatrixColMapOffd(RT); HYPRE_Int num_cols_offd_RT = hypre_CSRMatrixNumCols( hypre_ParCSRMatrixOffd(RT)); HYPRE_Int first_col_diag = hypre_ParCSRMatrixFirstColDiag(RT); HYPRE_Int i, j; HYPRE_Int vec_len, vec_start; HYPRE_Int num_procs, my_id; HYPRE_Int ierr = 0; HYPRE_Int num_requests; HYPRE_Int offd_col, proc_num; HYPRE_Int *proc_mark; HYPRE_Int *change_array; hypre_MPI_Request *requests; hypre_MPI_Status *status; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); /*-------------------------------------------------------------------------- * determine num_recvs, recv_procs and recv_vec_starts for RT *--------------------------------------------------------------------------*/ proc_mark = hypre_CTAlloc(HYPRE_Int, num_recvs_A); for (i=0; i < num_recvs_A; i++) proc_mark[i] = 0; proc_num = 0; num_recvs_RT = 0; if (num_cols_offd_RT) { for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j<recv_vec_starts_A[i+1]; j++) { offd_col = col_map_offd_RT[proc_num]; if (offd_col == j) { proc_mark[i]++; proc_num++; if (proc_num == num_cols_offd_RT) break; } } if (proc_mark[i]) num_recvs_RT++; if (proc_num == num_cols_offd_RT) break; } } for (i=0; i < num_cols_offd_RT; i++) col_map_offd_RT[i] = fine_to_coarse_offd[col_map_offd_RT[i]]; recv_procs_RT = hypre_CTAlloc(HYPRE_Int,num_recvs_RT); recv_vec_starts_RT = hypre_CTAlloc(HYPRE_Int, num_recvs_RT+1); j = 0; recv_vec_starts_RT[0] = 0; for (i=0; i < num_recvs_A; i++) if (proc_mark[i]) { recv_procs_RT[j] = recv_procs_A[i]; recv_vec_starts_RT[j+1] = recv_vec_starts_RT[j]+proc_mark[i]; j++; } /*-------------------------------------------------------------------------- * send num_changes to recv_procs_A and receive change_array from send_procs_A *--------------------------------------------------------------------------*/ num_requests = num_recvs_A+num_sends_A; requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); status = hypre_CTAlloc(hypre_MPI_Status, num_requests); change_array = hypre_CTAlloc(HYPRE_Int, num_sends_A); j = 0; for (i=0; i < num_sends_A; i++) hypre_MPI_Irecv(&change_array[i],1,HYPRE_MPI_INT,send_procs_A[i],0,comm, &requests[j++]); for (i=0; i < num_recvs_A; i++) hypre_MPI_Isend(&proc_mark[i],1,HYPRE_MPI_INT,recv_procs_A[i],0,comm, &requests[j++]); hypre_MPI_Waitall(num_requests,requests,status); hypre_TFree(proc_mark); /*-------------------------------------------------------------------------- * if change_array[i] is 0 , omit send_procs_A[i] in send_procs_RT *--------------------------------------------------------------------------*/ num_sends_RT = 0; for (i=0; i < num_sends_A; i++) if (change_array[i]) { num_sends_RT++; } send_procs_RT = hypre_CTAlloc(HYPRE_Int, num_sends_RT); send_map_starts_RT = hypre_CTAlloc(HYPRE_Int, num_sends_RT+1); j = 0; send_map_starts_RT[0] = 0; for (i=0; i < num_sends_A; i++) if (change_array[i]) { send_procs_RT[j] = send_procs_A[i]; send_map_starts_RT[j+1] = send_map_starts_RT[j]+change_array[i]; j++; } /*-------------------------------------------------------------------------- * generate send_map_elmts *--------------------------------------------------------------------------*/ send_map_elmts_RT = hypre_CTAlloc(HYPRE_Int,send_map_starts_RT[num_sends_RT]); j = 0; for (i=0; i < num_sends_RT; i++) { vec_start = send_map_starts_RT[i]; vec_len = send_map_starts_RT[i+1]-vec_start; hypre_MPI_Irecv(&send_map_elmts_RT[vec_start],vec_len,HYPRE_MPI_INT, send_procs_RT[i],0,comm,&requests[j++]); } for (i=0; i < num_recvs_RT; i++) { vec_start = recv_vec_starts_RT[i]; vec_len = recv_vec_starts_RT[i+1] - vec_start; hypre_MPI_Isend(&col_map_offd_RT[vec_start],vec_len,HYPRE_MPI_INT, recv_procs_RT[i],0,comm,&requests[j++]); } hypre_MPI_Waitall(j,requests,status); for (i=0; i < send_map_starts_RT[num_sends_RT]; i++) send_map_elmts_RT[i] -= first_col_diag; comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg) = num_sends_RT; hypre_ParCSRCommPkgNumRecvs(comm_pkg) = num_recvs_RT; hypre_ParCSRCommPkgSendProcs(comm_pkg) = send_procs_RT; hypre_ParCSRCommPkgRecvProcs(comm_pkg) = recv_procs_RT; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) = recv_vec_starts_RT; hypre_ParCSRCommPkgSendMapStarts(comm_pkg) = send_map_starts_RT; hypre_ParCSRCommPkgSendMapElmts(comm_pkg) = send_map_elmts_RT; hypre_TFree(status); hypre_TFree(requests); hypre_ParCSRMatrixCommPkg(RT) = comm_pkg; hypre_TFree(change_array); return ierr; } HYPRE_Int hypre_GenerateSendMapAndCommPkg(MPI_Comm comm, HYPRE_Int num_sends, HYPRE_Int num_recvs, HYPRE_Int *recv_procs, HYPRE_Int *send_procs, HYPRE_Int *recv_vec_starts, hypre_ParCSRMatrix *A) { HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int i, j; HYPRE_Int num_requests = num_sends+num_recvs; hypre_MPI_Request *requests; hypre_MPI_Status *status; HYPRE_Int vec_len, vec_start; hypre_ParCSRCommPkg *comm_pkg; HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int first_col_diag = hypre_ParCSRMatrixFirstColDiag(A); /*-------------------------------------------------------------------------- * generate send_map_starts and send_map_elmts *--------------------------------------------------------------------------*/ requests = hypre_CTAlloc(hypre_MPI_Request,num_requests); status = hypre_CTAlloc(hypre_MPI_Status,num_requests); send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1); j = 0; for (i=0; i < num_sends; i++) hypre_MPI_Irecv(&send_map_starts[i+1],1,HYPRE_MPI_INT,send_procs[i],0,comm, &requests[j++]); for (i=0; i < num_recvs; i++) { vec_len = recv_vec_starts[i+1] - recv_vec_starts[i]; hypre_MPI_Isend(&vec_len,1,HYPRE_MPI_INT, recv_procs[i],0,comm,&requests[j++]); } hypre_MPI_Waitall(j,requests,status); send_map_starts[0] = 0; for (i=0; i < num_sends; i++) send_map_starts[i+1] += send_map_starts[i]; send_map_elmts = hypre_CTAlloc(HYPRE_Int,send_map_starts[num_sends]); j = 0; for (i=0; i < num_sends; i++) { vec_start = send_map_starts[i]; vec_len = send_map_starts[i+1]-vec_start; hypre_MPI_Irecv(&send_map_elmts[vec_start],vec_len,HYPRE_MPI_INT, send_procs[i],0,comm,&requests[j++]); } for (i=0; i < num_recvs; i++) { vec_start = recv_vec_starts[i]; vec_len = recv_vec_starts[i+1] - vec_start; hypre_MPI_Isend(&col_map_offd[vec_start],vec_len,HYPRE_MPI_INT, recv_procs[i],0,comm,&requests[j++]); } hypre_MPI_Waitall(j,requests,status); for (i=0; i < send_map_starts[num_sends]; i++) send_map_elmts[i] -= first_col_diag; comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(comm_pkg) = send_procs; hypre_ParCSRCommPkgRecvProcs(comm_pkg) = recv_procs; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) = recv_vec_starts; hypre_ParCSRCommPkgSendMapStarts(comm_pkg) = send_map_starts; hypre_ParCSRCommPkgSendMapElmts(comm_pkg) = send_map_elmts; hypre_TFree(status); hypre_TFree(requests); hypre_ParCSRMatrixCommPkg(A) = comm_pkg; return 0; }
9,654
32.641115
88
c
AMG
AMG-master/parcsr_ls/par_relax_interface.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Relaxation scheme * *****************************************************************************/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGRelax *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGRelaxIF( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_type, HYPRE_Int relax_order, HYPRE_Int cycle_type, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { HYPRE_Int i, Solve_err_flag = 0; HYPRE_Int relax_points[2]; if (relax_order == 1 && cycle_type < 3) { if (cycle_type < 2) { relax_points[0] = 1; relax_points[1] = -1; } else { relax_points[0] = -1; relax_points[1] = 1; } for (i=0; i < 2; i++) Solve_err_flag = hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, relax_points[i], relax_weight, omega, l1_norms, u, Vtemp, Ztemp); } else { Solve_err_flag = hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, 0, relax_weight, omega, l1_norms, u, Vtemp, Ztemp); } return Solve_err_flag; }
3,608
36.59375
81
c
AMG
AMG-master/parcsr_ls/par_scaled_matnorm.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * computes |D^-1/2 A D^-1/2 |_sup where D diagonal matrix * *****************************************************************************/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixScaledNorm *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixScaledNorm( hypre_ParCSRMatrix *A, HYPRE_Real *scnorm) { hypre_ParCSRCommHandle *comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *diag_i = hypre_CSRMatrixI(diag); HYPRE_Int *diag_j = hypre_CSRMatrixJ(diag); HYPRE_Real *diag_data = hypre_CSRMatrixData(diag); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *offd_i = hypre_CSRMatrixI(offd); HYPRE_Int *offd_j = hypre_CSRMatrixJ(offd); HYPRE_Real *offd_data = hypre_CSRMatrixData(offd); HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(diag); hypre_ParVector *dinvsqrt; HYPRE_Real *dis_data; hypre_Vector *dis_ext; HYPRE_Real *dis_ext_data; hypre_Vector *sum; HYPRE_Real *sum_data; HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int num_sends, i, j, index, start; HYPRE_Real *d_buf_data; HYPRE_Real mat_norm, max_row_sum; dinvsqrt = hypre_ParVectorCreate(comm, global_num_rows, row_starts); hypre_ParVectorInitialize(dinvsqrt); dis_data = hypre_VectorData(hypre_ParVectorLocalVector(dinvsqrt)); hypre_ParVectorSetPartitioningOwner(dinvsqrt,0); dis_ext = hypre_SeqVectorCreate(num_cols_offd); hypre_SeqVectorInitialize(dis_ext); dis_ext_data = hypre_VectorData(dis_ext); sum = hypre_SeqVectorCreate(num_rows); hypre_SeqVectorInitialize(sum); sum_data = hypre_VectorData(sum); /* generate dinvsqrt */ for (i=0; i < num_rows; i++) { dis_data[i] = 1.0/sqrt(fabs(diag_data[diag_i[i]])); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); d_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) d_buf_data[index++] = dis_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, d_buf_data, dis_ext_data); for (i=0; i < num_rows; i++) { for (j=diag_i[i]; j < diag_i[i+1]; j++) { sum_data[i] += fabs(diag_data[j])*dis_data[i]*dis_data[diag_j[j]]; } } hypre_ParCSRCommHandleDestroy(comm_handle); for (i=0; i < num_rows; i++) { for (j=offd_i[i]; j < offd_i[i+1]; j++) { sum_data[i] += fabs(offd_data[j])*dis_data[i]*dis_ext_data[offd_j[j]]; } } max_row_sum = 0; for (i=0; i < num_rows; i++) { if (max_row_sum < sum_data[i]) max_row_sum = sum_data[i]; } hypre_MPI_Allreduce(&max_row_sum, &mat_norm, 1, HYPRE_MPI_REAL, hypre_MPI_MAX, comm); hypre_ParVectorDestroy(dinvsqrt); hypre_SeqVectorDestroy(sum); hypre_SeqVectorDestroy(dis_ext); hypre_TFree(d_buf_data); *scnorm = mat_norm; return 0; }
4,918
33.640845
88
c
AMG
AMG-master/parcsr_ls/pcg_par.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_ParKrylovCAlloc *--------------------------------------------------------------------------*/ char * hypre_ParKrylovCAlloc( HYPRE_Int count, HYPRE_Int elt_size ) { return( hypre_CAlloc( count, elt_size ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovFree *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovFree( char *ptr ) { HYPRE_Int ierr = 0; hypre_Free( ptr ); return ierr; } /*-------------------------------------------------------------------------- * hypre_ParKrylovCreateVector *--------------------------------------------------------------------------*/ void * hypre_ParKrylovCreateVector( void *vvector ) { hypre_ParVector *vector = (hypre_ParVector *) vvector; hypre_ParVector *new_vector; new_vector = hypre_ParVectorCreate( hypre_ParVectorComm(vector), hypre_ParVectorGlobalSize(vector), hypre_ParVectorPartitioning(vector) ); hypre_ParVectorSetPartitioningOwner(new_vector,0); hypre_ParVectorInitialize(new_vector); return ( (void *) new_vector ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovCreateVectorArray *--------------------------------------------------------------------------*/ void * hypre_ParKrylovCreateVectorArray(HYPRE_Int n, void *vvector ) { hypre_ParVector *vector = (hypre_ParVector *) vvector; hypre_ParVector **new_vector; HYPRE_Int i; new_vector = hypre_CTAlloc(hypre_ParVector*,n); for (i=0; i < n; i++) { new_vector[i] = hypre_ParVectorCreate( hypre_ParVectorComm(vector), hypre_ParVectorGlobalSize(vector), hypre_ParVectorPartitioning(vector) ); hypre_ParVectorSetPartitioningOwner(new_vector[i],0); hypre_ParVectorInitialize(new_vector[i]); } return ( (void *) new_vector ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovDestroyVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovDestroyVector( void *vvector ) { hypre_ParVector *vector = (hypre_ParVector *) vvector; return( hypre_ParVectorDestroy( vector ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvecCreate *--------------------------------------------------------------------------*/ void * hypre_ParKrylovMatvecCreate( void *A, void *x ) { void *matvec_data; matvec_data = NULL; return ( matvec_data ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvec *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovMatvec( void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ) { return ( hypre_ParCSRMatrixMatvec ( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvecT *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovMatvecT(void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ) { return ( hypre_ParCSRMatrixMatvecT( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvecDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovMatvecDestroy( void *matvec_data ) { return 0; } /*-------------------------------------------------------------------------- * hypre_ParKrylovInnerProd *--------------------------------------------------------------------------*/ HYPRE_Real hypre_ParKrylovInnerProd( void *x, void *y ) { return ( hypre_ParVectorInnerProd( (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovCopyVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovCopyVector( void *x, void *y ) { return ( hypre_ParVectorCopy( (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovClearVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovClearVector( void *x ) { return ( hypre_ParVectorSetConstantValues( (hypre_ParVector *) x, 0.0 ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovScaleVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovScaleVector( HYPRE_Complex alpha, void *x ) { return ( hypre_ParVectorScale( alpha, (hypre_ParVector *) x ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovAxpy( HYPRE_Complex alpha, void *x, void *y ) { return ( hypre_ParVectorAxpy( alpha, (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovCommInfo *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovCommInfo( void *A, HYPRE_Int *my_id, HYPRE_Int *num_procs) { MPI_Comm comm = hypre_ParCSRMatrixComm ( (hypre_ParCSRMatrix *) A); hypre_MPI_Comm_size(comm,num_procs); hypre_MPI_Comm_rank(comm,my_id); return 0; } /*-------------------------------------------------------------------------- * hypre_ParKrylovIdentitySetup *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovIdentitySetup( void *vdata, void *A, void *b, void *x ) { return 0; } /*-------------------------------------------------------------------------- * hypre_ParKrylovIdentity *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovIdentity( void *vdata, void *A, void *b, void *x ) { return( hypre_ParKrylovCopyVector( b, x ) ); }
8,616
31.764259
83
c
AMG
AMG-master/parcsr_mv/HYPRE_parcsr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_ParCSRMatrix interface * *****************************************************************************/ #include "_hypre_parcsr_mv.h" /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixCreate( MPI_Comm comm, HYPRE_Int global_num_rows, HYPRE_Int global_num_cols, HYPRE_Int *row_starts, HYPRE_Int *col_starts, HYPRE_Int num_cols_offd, HYPRE_Int num_nonzeros_diag, HYPRE_Int num_nonzeros_offd, HYPRE_ParCSRMatrix *matrix ) { if (!matrix) { hypre_error_in_arg(9); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_ParCSRMatrixCreate(comm, global_num_rows, global_num_cols, row_starts, col_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixDestroy( HYPRE_ParCSRMatrix matrix ) { return( hypre_ParCSRMatrixDestroy( (hypre_ParCSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixInitialize( HYPRE_ParCSRMatrix matrix ) { return ( hypre_ParCSRMatrixInitialize( (hypre_ParCSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixRead *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixRead( MPI_Comm comm, const char *file_name, HYPRE_ParCSRMatrix *matrix) { if (!matrix) { hypre_error_in_arg(3); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_ParCSRMatrixRead( comm, file_name ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixPrint *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixPrint( HYPRE_ParCSRMatrix matrix, const char *file_name ) { hypre_ParCSRMatrixPrint( (hypre_ParCSRMatrix *) matrix, file_name ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetComm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetComm( HYPRE_ParCSRMatrix matrix, MPI_Comm *comm ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } *comm = hypre_ParCSRMatrixComm((hypre_ParCSRMatrix *) matrix); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetDims *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetDims( HYPRE_ParCSRMatrix matrix, HYPRE_Int *M, HYPRE_Int *N ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } *M = hypre_ParCSRMatrixGlobalNumRows((hypre_ParCSRMatrix *) matrix); *N = hypre_ParCSRMatrixGlobalNumCols((hypre_ParCSRMatrix *) matrix); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetRowPartitioning *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetRowPartitioning( HYPRE_ParCSRMatrix matrix, HYPRE_Int **row_partitioning_ptr ) { HYPRE_Int *row_partitioning, *row_starts; HYPRE_Int num_procs, i; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_MPI_Comm_size(hypre_ParCSRMatrixComm((hypre_ParCSRMatrix *) matrix), &num_procs); row_starts = hypre_ParCSRMatrixRowStarts((hypre_ParCSRMatrix *) matrix); if (!row_starts) return -1; row_partitioning = hypre_CTAlloc(HYPRE_Int, num_procs+1); for (i=0; i < num_procs + 1; i++) row_partitioning[i] = row_starts[i]; *row_partitioning_ptr = row_partitioning; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetColPartitioning *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetColPartitioning( HYPRE_ParCSRMatrix matrix, HYPRE_Int **col_partitioning_ptr ) { HYPRE_Int *col_partitioning, *col_starts; HYPRE_Int num_procs, i; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_MPI_Comm_size(hypre_ParCSRMatrixComm((hypre_ParCSRMatrix *) matrix), &num_procs); col_starts = hypre_ParCSRMatrixColStarts((hypre_ParCSRMatrix *) matrix); if (!col_starts) return -1; col_partitioning = hypre_CTAlloc(HYPRE_Int, num_procs+1); for (i=0; i < num_procs + 1; i++) col_partitioning[i] = col_starts[i]; *col_partitioning_ptr = col_partitioning; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetLocalRange *--------------------------------------------------------------------------*/ /** Returns range of rows and columns owned by this processor. Not collective. @return integer error code @param HYPRE_ParCSRMatrix matrix [IN] the matrix to be operated on. @param HYPRE_Int *row_start [OUT] the global number of the first row stored on this processor @param HYPRE_Int *row_end [OUT] the global number of the first row stored on this processor @param HYPRE_Int *col_start [OUT] the global number of the first column stored on this processor @param HYPRE_Int *col_end [OUT] the global number of the first column stored on this processor */ HYPRE_Int HYPRE_ParCSRMatrixGetLocalRange( HYPRE_ParCSRMatrix matrix, HYPRE_Int *row_start, HYPRE_Int *row_end, HYPRE_Int *col_start, HYPRE_Int *col_end ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixGetLocalRange( (hypre_ParCSRMatrix *) matrix, row_start, row_end, col_start, col_end ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetRow *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetRow( HYPRE_ParCSRMatrix matrix, HYPRE_Int row, HYPRE_Int *size, HYPRE_Int **col_ind, HYPRE_Complex **values ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixGetRow( (hypre_ParCSRMatrix *) matrix, row, size, col_ind, values ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixRestoreRow *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixRestoreRow( HYPRE_ParCSRMatrix matrix, HYPRE_Int row, HYPRE_Int *size, HYPRE_Int **col_ind, HYPRE_Complex **values ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixRestoreRow( (hypre_ParCSRMatrix *) matrix, row, size, col_ind, values ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixToParCSRMatrix * Output argument (fifth argument): a new ParCSRmatrix. * Input arguments: MPI communicator, CSR matrix, and optional partitionings. * If you don't have partitionings, just pass a null pointer for the third * and fourth arguments and they will be computed. * Note that it is not possible to provide a null pointer if this is called * from Fortran code; so you must provide the paritionings from Fortran. *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixToParCSRMatrix( MPI_Comm comm, HYPRE_CSRMatrix A_CSR, HYPRE_Int *row_partitioning, HYPRE_Int *col_partitioning, HYPRE_ParCSRMatrix *matrix) { if (!matrix) { hypre_error_in_arg(5); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_CSRMatrixToParCSRMatrix( comm, (hypre_CSRMatrix *) A_CSR, row_partitioning, col_partitioning) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixToParCSRMatrix_WithNewPartitioning * Output argument (third argument): a new ParCSRmatrix. * Input arguments: MPI communicator, CSR matrix. * Row and column partitionings are computed for the output matrix. *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixToParCSRMatrix_WithNewPartitioning( MPI_Comm comm, HYPRE_CSRMatrix A_CSR, HYPRE_ParCSRMatrix *matrix ) { if (!matrix) { hypre_error_in_arg(3); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_CSRMatrixToParCSRMatrix( comm, (hypre_CSRMatrix *) A_CSR, NULL, NULL ) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixMatvec *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixMatvec( HYPRE_Complex alpha, HYPRE_ParCSRMatrix A, HYPRE_ParVector x, HYPRE_Complex beta, HYPRE_ParVector y ) { return ( hypre_ParCSRMatrixMatvec( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixMatvecT *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixMatvecT( HYPRE_Complex alpha, HYPRE_ParCSRMatrix A, HYPRE_ParVector x, HYPRE_Complex beta, HYPRE_ParVector y ) { return ( hypre_ParCSRMatrixMatvecT( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y) ); }
12,975
34.550685
84
c
AMG
AMG-master/parcsr_mv/HYPRE_parcsr_vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_ParVector interface * *****************************************************************************/ #include "_hypre_parcsr_mv.h" /*-------------------------------------------------------------------------- * HYPRE_ParVectorCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorCreate( MPI_Comm comm, HYPRE_Int global_size, HYPRE_Int *partitioning, HYPRE_ParVector *vector ) { if (!vector) { hypre_error_in_arg(4); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_ParVectorCreate(comm, global_size, partitioning) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParMultiVectorCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParMultiVectorCreate( MPI_Comm comm, HYPRE_Int global_size, HYPRE_Int *partitioning, HYPRE_Int number_vectors, HYPRE_ParVector *vector ) { if (!vector) { hypre_error_in_arg(5); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_ParMultiVectorCreate( comm, global_size, partitioning, number_vectors ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorDestroy( HYPRE_ParVector vector ) { return ( hypre_ParVectorDestroy( (hypre_ParVector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorInitialize( HYPRE_ParVector vector ) { return ( hypre_ParVectorInitialize( (hypre_ParVector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorRead *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorRead( MPI_Comm comm, const char *file_name, HYPRE_ParVector *vector) { if (!vector) { hypre_error_in_arg(3); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_ParVectorRead( comm, file_name ) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParVectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorPrint( HYPRE_ParVector vector, const char *file_name ) { return ( hypre_ParVectorPrint( (hypre_ParVector *) vector, file_name ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorSetConstantValues( HYPRE_ParVector vector, HYPRE_Complex value ) { return ( hypre_ParVectorSetConstantValues( (hypre_ParVector *) vector, value ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorSetRandomValues *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorSetRandomValues( HYPRE_ParVector vector, HYPRE_Int seed ) { return ( hypre_ParVectorSetRandomValues( (hypre_ParVector *) vector, seed ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorCopy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorCopy( HYPRE_ParVector x, HYPRE_ParVector y ) { return ( hypre_ParVectorCopy( (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorCloneShallow *--------------------------------------------------------------------------*/ HYPRE_ParVector HYPRE_ParVectorCloneShallow( HYPRE_ParVector x ) { return ( (HYPRE_ParVector) hypre_ParVectorCloneShallow( (hypre_ParVector *) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorScale *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorScale( HYPRE_Complex value, HYPRE_ParVector x) { return ( hypre_ParVectorScale( value, (hypre_ParVector *) x) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorAxpy( HYPRE_Complex alpha, HYPRE_ParVector x, HYPRE_ParVector y ) { return hypre_ParVectorAxpy( alpha, (hypre_ParVector *)x, (hypre_ParVector *)y ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorInnerProd( HYPRE_ParVector x, HYPRE_ParVector y, HYPRE_Real *prod) { if (!x) { hypre_error_in_arg(1); return hypre_error_flag; } if (!y) { hypre_error_in_arg(2); return hypre_error_flag; } *prod = hypre_ParVectorInnerProd( (hypre_ParVector *) x, (hypre_ParVector *) y) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_VectorToParVector *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorToParVector( MPI_Comm comm, HYPRE_Vector b, HYPRE_Int *partitioning, HYPRE_ParVector *vector) { if (!vector) { hypre_error_in_arg(4); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_VectorToParVector (comm, (hypre_Vector *) b, partitioning); return hypre_error_flag; }
7,715
32.402597
84
c
AMG
AMG-master/parcsr_mv/headers.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "HYPRE.h" #include "parcsr_mv.h"
1,030
34.551724
81
h
AMG
AMG-master/parcsr_mv/new_commpkg.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_NEW_COMMPKG #define hypre_NEW_COMMPKG typedef struct { HYPRE_Int length; HYPRE_Int storage_length; HYPRE_Int *id; HYPRE_Int *vec_starts; HYPRE_Int element_storage_length; HYPRE_Int *elements; HYPRE_Real *d_elements; /* Is this used anywhere? */ void *v_elements; } hypre_ProcListElements; #endif /* hypre_NEW_COMMPKG */
1,343
36.333333
81
h
AMG
AMG-master/parcsr_mv/par_csr_assumed_part.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*---------------------------------------------------- * Functions for the IJ assumed partition * (Some of these were formerly in new_commpkg.c) * AHB 4/06 *-----------------------------------------------------*/ #include "_hypre_parcsr_mv.h" /* This is used only in the function below */ #define CONTACT(a,b) (contact_list[(a)*3+(b)]) /*-------------------------------------------------------------------- * hypre_LocateAssummedPartition * Reconcile assumed partition with actual partition. Essentially * each processor ends of with a partition of its assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_LocateAssummedPartition(MPI_Comm comm, HYPRE_Int row_start, HYPRE_Int row_end, HYPRE_Int global_first_row, HYPRE_Int global_num_rows, hypre_IJAssumedPart *part, HYPRE_Int myid) { HYPRE_Int i; HYPRE_Int *contact_list; HYPRE_Int contact_list_length, contact_list_storage; HYPRE_Int contact_row_start[2], contact_row_end[2], contact_ranges; HYPRE_Int owner_start, owner_end; HYPRE_Int tmp_row_start, tmp_row_end, complete; /*HYPRE_Int locate_row_start[2]; */ HYPRE_Int locate_ranges; HYPRE_Int locate_row_count, rows_found; HYPRE_Int tmp_range[2]; HYPRE_Int *si, *sortme; const HYPRE_Int flag1 = 17; hypre_MPI_Request *requests; hypre_MPI_Status status0, *statuses; /*----------------------------------------------------------- * Contact ranges - * which rows do I have that others are assumed responsible for? * (at most two ranges - maybe none) *-----------------------------------------------------------*/ contact_row_start[0]=0; contact_row_end[0]=0; contact_row_start[1]=0; contact_row_end[1]=0; contact_ranges = 0; if (row_start <= row_end ) { /*must own at least one row*/ if ( part->row_end < row_start || row_end < part->row_start ) { /*no overlap - so all of my rows and only one range*/ contact_row_start[0] = row_start; contact_row_end[0] = row_end; contact_ranges++; } else /* the two regions overlap - so one or two ranges */ { /* check for contact rows on the low end of the local range */ if (row_start < part->row_start) { contact_row_start[0] = row_start; contact_row_end[0] = part->row_start - 1; contact_ranges++; } if (part->row_end < row_end) /* check the high end */ { if (contact_ranges) /* already found one range */ { contact_row_start[1] = part->row_end +1; contact_row_end[1] = row_end; } else { contact_row_start[0] = part->row_end +1; contact_row_end[0] = row_end; } contact_ranges++; } } } /*----------------------------------------------------------- * Contact: find out who is assumed responsible for these * ranges of contact rows and contact them * *-----------------------------------------------------------*/ contact_list_length = 0; contact_list_storage = 5; contact_list = hypre_TAlloc(HYPRE_Int, contact_list_storage*3); /*each contact needs 3 ints */ for (i=0; i<contact_ranges; i++) { /*get start and end row owners */ hypre_GetAssumedPartitionProcFromRow(comm, contact_row_start[i], global_first_row, global_num_rows, &owner_start); hypre_GetAssumedPartitionProcFromRow(comm, contact_row_end[i], global_first_row, global_num_rows, &owner_end); if (owner_start == owner_end) /* same processor owns the whole range */ { if (contact_list_length == contact_list_storage) { /*allocate more space*/ contact_list_storage += 5; contact_list = hypre_TReAlloc(contact_list, HYPRE_Int, (contact_list_storage*3)); } CONTACT(contact_list_length, 0) = owner_start; /*proc #*/ CONTACT(contact_list_length, 1) = contact_row_start[i]; /* start row */ CONTACT(contact_list_length, 2) = contact_row_end[i]; /*end row */ contact_list_length++; } else { complete = 0; while (!complete) { hypre_GetAssumedPartitionRowRange(comm, owner_start, global_first_row, global_num_rows, &tmp_row_start, &tmp_row_end); if (tmp_row_end >= contact_row_end[i]) { tmp_row_end = contact_row_end[i]; complete = 1; } if (tmp_row_start < contact_row_start[i]) { tmp_row_start = contact_row_start[i]; } if (contact_list_length == contact_list_storage) { /*allocate more space*/ contact_list_storage += 5; contact_list = hypre_TReAlloc(contact_list, HYPRE_Int, (contact_list_storage*3)); } CONTACT(contact_list_length, 0) = owner_start; /*proc #*/ CONTACT(contact_list_length, 1) = tmp_row_start; /* start row */ CONTACT(contact_list_length, 2) = tmp_row_end; /*end row */ contact_list_length++; owner_start++; /*processors are seqential */ } } } requests = hypre_CTAlloc(hypre_MPI_Request, contact_list_length); statuses = hypre_CTAlloc(hypre_MPI_Status, contact_list_length); /*send out messages */ for (i=0; i< contact_list_length; i++) { hypre_MPI_Isend(&CONTACT(i,1) ,2, HYPRE_MPI_INT, CONTACT(i,0), flag1 , comm, &requests[i]); /*hypre_MPI_COMM_WORLD, &requests[i]);*/ } /*----------------------------------------------------------- * Locate ranges - * which rows in my assumed range do I not own * (at most two ranges - maybe none) * locate_row_count = total number of rows I must locate *-----------------------------------------------------------*/ locate_row_count = 0; /*locate_row_start[0]=0; locate_row_start[1]=0;*/ locate_ranges = 0; if (part->row_end < row_start || row_end < part->row_start ) /*no overlap - so all of my assumed rows */ { /*locate_row_start[0] = part->row_start;*/ locate_ranges++; locate_row_count += part->row_end - part->row_start + 1; } else /* the two regions overlap */ { if (part->row_start < row_start) {/* check for locate rows on the low end of the local range */ /*locate_row_start[0] = part->row_start;*/ locate_ranges++; locate_row_count += (row_start-1) - part->row_start + 1; } if (row_end < part->row_end) /* check the high end */ { /*if (locate_ranges)*/ /* already have one range */ /*{ locate_row_start[1] = row_end +1; } else { locate_row_start[0] = row_end +1; }*/ locate_ranges++; locate_row_count += part->row_end - (row_end + 1) + 1; } } /*----------------------------------------------------------- * Receive messages from other procs telling us where * all our locate rows actually reside *-----------------------------------------------------------*/ /* we will keep a partition of our assumed partition - list ourselves first. We will sort later with an additional index. In practice, this should only contain a few processors */ /*which part do I own?*/ tmp_row_start = hypre_max(part->row_start, row_start); tmp_row_end = hypre_min(row_end, part->row_end); if (tmp_row_start <= tmp_row_end) { part->proc_list[0] = myid; part->row_start_list[0] = tmp_row_start; part->row_end_list[0] = tmp_row_end; part->length++; } /* now look for messages that tell us which processor has our locate rows */ /* these will be blocking receives as we know how many to expect and they should be waiting (and we don't want to continue on without them) */ rows_found = 0; while (rows_found != locate_row_count) { hypre_MPI_Recv( tmp_range, 2 , HYPRE_MPI_INT, hypre_MPI_ANY_SOURCE, flag1 , comm, &status0); /*flag1 , hypre_MPI_COMM_WORLD, &status0);*/ if (part->length==part->storage_length) { part->storage_length+=10; part->proc_list = hypre_TReAlloc(part->proc_list, HYPRE_Int, part->storage_length); part->row_start_list = hypre_TReAlloc(part->row_start_list, HYPRE_Int, part->storage_length); part->row_end_list = hypre_TReAlloc(part->row_end_list, HYPRE_Int, part->storage_length); } part->row_start_list[part->length] = tmp_range[0]; part->row_end_list[part->length] = tmp_range[1]; part->proc_list[part->length] = status0.hypre_MPI_SOURCE; rows_found += tmp_range[1]- tmp_range[0] + 1; part->length++; } /*In case the partition of the assumed partition is longish, we would like to know the sorted order */ si= hypre_CTAlloc(HYPRE_Int, part->length); sortme = hypre_CTAlloc(HYPRE_Int, part->length); for (i=0; i<part->length; i++) { si[i] = i; sortme[i] = part->row_start_list[i]; } hypre_qsort2i( sortme, si, 0, (part->length)-1); part->sort_index = si; /*free the requests */ hypre_MPI_Waitall(contact_list_length, requests, statuses); hypre_TFree(statuses); hypre_TFree(requests); hypre_TFree(sortme); hypre_TFree(contact_list); return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_ParCSRMatrixCreateAssumedPartition - * Each proc gets it own range. Then * each needs to reconcile its actual range with its assumed * range - the result is essentila a partition of its assumed range - * this is the assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixCreateAssumedPartition( hypre_ParCSRMatrix *matrix) { HYPRE_Int global_num_cols; HYPRE_Int myid; HYPRE_Int row_start=0, row_end=0, col_start = 0, col_end = 0; MPI_Comm comm; hypre_IJAssumedPart *apart; global_num_cols = hypre_ParCSRMatrixGlobalNumCols(matrix); comm = hypre_ParCSRMatrixComm(matrix); /* find out my actualy range of rows and columns */ hypre_ParCSRMatrixGetLocalRange( matrix, &row_start, &row_end , &col_start, &col_end ); hypre_MPI_Comm_rank(comm, &myid ); /* allocate space */ apart = hypre_CTAlloc(hypre_IJAssumedPart, 1); /* get my assumed partitioning - we want partitioning of the vector that the matrix multiplies - so we use the col start and end */ hypre_GetAssumedPartitionRowRange( comm, myid, 0, global_num_cols, &(apart->row_start), &(apart->row_end)); /*allocate some space for the partition of the assumed partition */ apart->length = 0; /*room for 10 owners of the assumed partition*/ apart->storage_length = 10; /*need to be >=1 */ apart->proc_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_start_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_end_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); /* now we want to reconcile our actual partition with the assumed partition */ hypre_LocateAssummedPartition(comm, col_start, col_end, 0, global_num_cols, apart, myid); /* this partition will be saved in the matrix data structure until the matrix is destroyed */ hypre_ParCSRMatrixAssumedPartition(matrix) = apart; return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_AssumedPartitionDestroy *--------------------------------------------------------------------*/ HYPRE_Int hypre_AssumedPartitionDestroy(hypre_IJAssumedPart *apart ) { if(apart->storage_length > 0) { hypre_TFree(apart->proc_list); hypre_TFree(apart->row_start_list); hypre_TFree(apart->row_end_list); hypre_TFree(apart->sort_index); } hypre_TFree(apart); return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_GetAssumedPartitionProcFromRow * Assumed partition for IJ case. Given a particular row j, return * the processor that is assumed to own that row. *--------------------------------------------------------------------*/ HYPRE_Int hypre_GetAssumedPartitionProcFromRow( MPI_Comm comm, HYPRE_Int row, HYPRE_Int global_first_row, HYPRE_Int global_num_rows, HYPRE_Int *proc_id) { HYPRE_Int num_procs; HYPRE_Int size, switch_row, extra; hypre_MPI_Comm_size(comm, &num_procs ); /*hypre_MPI_Comm_size(hypre_MPI_COMM_WORLD, &num_procs );*/ /* j = floor[(row*p/N] - this overflows*/ /* *proc_id = (row*num_procs)/global_num_rows;*/ /* this looks a bit odd, but we have to be very careful that this function and the next are inverses - and rounding errors make this difficult!!!!! */ size = global_num_rows /num_procs; extra = global_num_rows - size*num_procs; switch_row = global_first_row + (size + 1)*extra; if (row >= switch_row) { *proc_id = extra + (row - switch_row)/size; } else { *proc_id = (row - global_first_row)/(size+1); } return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_GetAssumedPartitionRowRange * Assumed partition for IJ case. Given a particular processor id, return * the assumed range of rows ([row_start, row_end]) for that processor. *--------------------------------------------------------------------*/ HYPRE_Int hypre_GetAssumedPartitionRowRange( MPI_Comm comm, HYPRE_Int proc_id, HYPRE_Int global_first_row, HYPRE_Int global_num_rows, HYPRE_Int *row_start, HYPRE_Int* row_end) { HYPRE_Int num_procs; HYPRE_Int size, extra; hypre_MPI_Comm_size(comm, &num_procs ); /*hypre_MPI_Comm_size(hypre_MPI_COMM_WORLD, &num_procs );*/ /* this may look non-intuitive, but we have to be very careful that this function and the next are inverses - and avoiding overflow and rounding errors makes this difficult! */ size = global_num_rows /num_procs; extra = global_num_rows - size*num_procs; *row_start = global_first_row + size*proc_id; *row_start += hypre_min(proc_id, extra); *row_end = global_first_row + size*(proc_id+1); *row_end += hypre_min(proc_id+1, extra); *row_end = *row_end - 1; return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_ParVectorCreateAssumedPartition - * Essentially the same as for a matrix! * Each proc gets it own range. Then * each needs to reconcile its actual range with its assumed * range - the result is essentila a partition of its assumed range - * this is the assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorCreateAssumedPartition( hypre_ParVector *vector) { HYPRE_Int global_num; HYPRE_Int myid; HYPRE_Int start=0, end=0; MPI_Comm comm; hypre_IJAssumedPart *apart; global_num = hypre_ParVectorGlobalSize(vector); comm = hypre_ParVectorComm(vector); /* find out my actualy range of rows */ start = hypre_ParVectorFirstIndex(vector); end = hypre_ParVectorLastIndex(vector); hypre_MPI_Comm_rank(comm, &myid ); /* allocate space */ apart = hypre_CTAlloc(hypre_IJAssumedPart, 1); /* get my assumed partitioning - we want partitioning of the vector that the matrix multiplies - so we use the col start and end */ hypre_GetAssumedPartitionRowRange( comm, myid, 0, global_num, &(apart->row_start), &(apart->row_end)); /*allocate some space for the partition of the assumed partition */ apart->length = 0; /*room for 10 owners of the assumed partition*/ apart->storage_length = 10; /*need to be >=1 */ apart->proc_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_start_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_end_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); /* now we want to reconcile our actual partition with the assumed partition */ hypre_LocateAssummedPartition(comm, start, end, 0, global_num, apart, myid); /* this partition will be saved in the vector data structure until the vector is destroyed */ hypre_ParVectorAssumedPartition(vector) = apart; return hypre_error_flag; }
17,884
31.400362
103
c
AMG
AMG-master/parcsr_mv/par_csr_assumed_part.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_PARCSR_ASSUMED_PART #define hypre_PARCSR_ASSUMED_PART typedef struct { HYPRE_Int length; HYPRE_Int row_start; HYPRE_Int row_end; HYPRE_Int storage_length; HYPRE_Int *proc_list; HYPRE_Int *row_start_list; HYPRE_Int *row_end_list; HYPRE_Int *sort_index; } hypre_IJAssumedPart; #endif /* hypre_PARCSR_ASSUMED_PART */
1,422
36.447368
81
h
AMG
AMG-master/parcsr_mv/par_csr_communication.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef HYPRE_PAR_CSR_COMMUNICATION_HEADER #define HYPRE_PAR_CSR_COMMUNICATION_HEADER /*-------------------------------------------------------------------------- * hypre_ParCSRCommPkg: * Structure containing information for doing communications *--------------------------------------------------------------------------*/ #define HYPRE_USING_PERSISTENT_COMM // JSP: can be defined by configure #ifdef HYPRE_USING_PERSISTENT_COMM typedef enum CommPkgJobType { HYPRE_COMM_PKG_JOB_COMPLEX = 0, HYPRE_COMM_PKG_JOB_COMPLEX_TRANSPOSE, HYPRE_COMM_PKG_JOB_INT, HYPRE_COMM_PKG_JOB_INT_TRANSPOSE, NUM_OF_COMM_PKG_JOB_TYPE, } CommPkgJobType; typedef struct { void *send_data; void *recv_data; HYPRE_Int num_requests; hypre_MPI_Request *requests; HYPRE_Int own_send_data, own_recv_data; } hypre_ParCSRPersistentCommHandle; #endif typedef struct { MPI_Comm comm; HYPRE_Int num_sends; HYPRE_Int *send_procs; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int num_recvs; HYPRE_Int *recv_procs; HYPRE_Int *recv_vec_starts; /* remote communication information */ hypre_MPI_Datatype *send_mpi_types; hypre_MPI_Datatype *recv_mpi_types; #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandle *persistent_comm_handles[NUM_OF_COMM_PKG_JOB_TYPE]; #endif } hypre_ParCSRCommPkg; /*-------------------------------------------------------------------------- * hypre_ParCSRCommHandle: *--------------------------------------------------------------------------*/ typedef struct { hypre_ParCSRCommPkg *comm_pkg; void *send_data; void *recv_data; HYPRE_Int num_requests; hypre_MPI_Request *requests; } hypre_ParCSRCommHandle; /*-------------------------------------------------------------------------- * Accessor macros: hypre_ParCSRCommPkg *--------------------------------------------------------------------------*/ #define hypre_ParCSRCommPkgComm(comm_pkg) (comm_pkg -> comm) #define hypre_ParCSRCommPkgNumSends(comm_pkg) (comm_pkg -> num_sends) #define hypre_ParCSRCommPkgSendProcs(comm_pkg) (comm_pkg -> send_procs) #define hypre_ParCSRCommPkgSendProc(comm_pkg, i) (comm_pkg -> send_procs[i]) #define hypre_ParCSRCommPkgSendMapStarts(comm_pkg) (comm_pkg -> send_map_starts) #define hypre_ParCSRCommPkgSendMapStart(comm_pkg,i)(comm_pkg -> send_map_starts[i]) #define hypre_ParCSRCommPkgSendMapElmts(comm_pkg) (comm_pkg -> send_map_elmts) #define hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i) (comm_pkg -> send_map_elmts[i]) #define hypre_ParCSRCommPkgNumRecvs(comm_pkg) (comm_pkg -> num_recvs) #define hypre_ParCSRCommPkgRecvProcs(comm_pkg) (comm_pkg -> recv_procs) #define hypre_ParCSRCommPkgRecvProc(comm_pkg, i) (comm_pkg -> recv_procs[i]) #define hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) (comm_pkg -> recv_vec_starts) #define hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i)(comm_pkg -> recv_vec_starts[i]) #define hypre_ParCSRCommPkgSendMPITypes(comm_pkg) (comm_pkg -> send_mpi_types) #define hypre_ParCSRCommPkgSendMPIType(comm_pkg,i) (comm_pkg -> send_mpi_types[i]) #define hypre_ParCSRCommPkgRecvMPITypes(comm_pkg) (comm_pkg -> recv_mpi_types) #define hypre_ParCSRCommPkgRecvMPIType(comm_pkg,i) (comm_pkg -> recv_mpi_types[i]) /*-------------------------------------------------------------------------- * Accessor macros: hypre_ParCSRCommHandle *--------------------------------------------------------------------------*/ #define hypre_ParCSRCommHandleCommPkg(comm_handle) (comm_handle -> comm_pkg) #define hypre_ParCSRCommHandleSendData(comm_handle) (comm_handle -> send_data) #define hypre_ParCSRCommHandleRecvData(comm_handle) (comm_handle -> recv_data) #define hypre_ParCSRCommHandleNumRequests(comm_handle) (comm_handle -> num_requests) #define hypre_ParCSRCommHandleRequests(comm_handle) (comm_handle -> requests) #define hypre_ParCSRCommHandleRequest(comm_handle, i) (comm_handle -> requests[i]) #endif /* HYPRE_PAR_CSR_COMMUNICATION_HEADER */
5,177
39.453125
87
h
AMG
AMG-master/parcsr_mv/par_csr_matrix.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for Parallel CSR Matrix data structures * * Note: this matrix currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_PAR_CSR_MATRIX_HEADER #define hypre_PAR_CSR_MATRIX_HEADER /*-------------------------------------------------------------------------- * Parallel CSR Matrix *--------------------------------------------------------------------------*/ #ifndef HYPRE_PAR_CSR_MATRIX_STRUCT #define HYPRE_PAR_CSR_MATRIX_STRUCT #endif typedef struct hypre_ParCSRMatrix_struct { MPI_Comm comm; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int first_row_index; HYPRE_Int first_col_diag; /* need to know entire local range in case row_starts and col_starts are null (i.e., bgl) AHB 6/05*/ HYPRE_Int last_row_index; HYPRE_Int last_col_diag; hypre_CSRMatrix *diag; hypre_CSRMatrix *offd; hypre_CSRMatrix *diagT, *offdT; /* JSP: transposed matrices are created lazily and optional */ HYPRE_Int *col_map_offd; /* maps columns of offd to global columns */ HYPRE_Int *row_starts; /* array of length num_procs+1, row_starts[i] contains the global number of the first row on proc i, first_row_index = row_starts[my_id], row_starts[num_procs] = global_num_rows */ HYPRE_Int *col_starts; /* array of length num_procs+1, col_starts[i] contains the global number of the first column of diag on proc i, first_col_diag = col_starts[my_id], col_starts[num_procs] = global_num_cols */ hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommPkg *comm_pkgT; /* Does the ParCSRMatrix create/destroy `diag', `offd', `col_map_offd'? */ HYPRE_Int owns_data; /* Does the ParCSRMatrix create/destroy `row_starts', `col_starts'? */ HYPRE_Int owns_row_starts; HYPRE_Int owns_col_starts; HYPRE_Int num_nonzeros; HYPRE_Real d_num_nonzeros; /* Buffers used by GetRow to hold row currently being accessed. AJC, 4/99 */ HYPRE_Int *rowindices; HYPRE_Complex *rowvalues; HYPRE_Int getrowactive; hypre_IJAssumedPart *assumed_partition; /* only populated if no_global_partition option is used (compile-time option)*/ } hypre_ParCSRMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the Parallel CSR Matrix structure *--------------------------------------------------------------------------*/ #define hypre_ParCSRMatrixComm(matrix) ((matrix) -> comm) #define hypre_ParCSRMatrixGlobalNumRows(matrix) ((matrix) -> global_num_rows) #define hypre_ParCSRMatrixGlobalNumCols(matrix) ((matrix) -> global_num_cols) #define hypre_ParCSRMatrixFirstRowIndex(matrix) ((matrix) -> first_row_index) #define hypre_ParCSRMatrixFirstColDiag(matrix) ((matrix) -> first_col_diag) #define hypre_ParCSRMatrixLastRowIndex(matrix) ((matrix) -> last_row_index) #define hypre_ParCSRMatrixLastColDiag(matrix) ((matrix) -> last_col_diag) #define hypre_ParCSRMatrixDiag(matrix) ((matrix) -> diag) #define hypre_ParCSRMatrixOffd(matrix) ((matrix) -> offd) #define hypre_ParCSRMatrixDiagT(matrix) ((matrix) -> diagT) #define hypre_ParCSRMatrixOffdT(matrix) ((matrix) -> offdT) #define hypre_ParCSRMatrixColMapOffd(matrix) ((matrix) -> col_map_offd) #define hypre_ParCSRMatrixRowStarts(matrix) ((matrix) -> row_starts) #define hypre_ParCSRMatrixColStarts(matrix) ((matrix) -> col_starts) #define hypre_ParCSRMatrixCommPkg(matrix) ((matrix) -> comm_pkg) #define hypre_ParCSRMatrixCommPkgT(matrix) ((matrix) -> comm_pkgT) #define hypre_ParCSRMatrixOwnsData(matrix) ((matrix) -> owns_data) #define hypre_ParCSRMatrixOwnsRowStarts(matrix) ((matrix) -> owns_row_starts) #define hypre_ParCSRMatrixOwnsColStarts(matrix) ((matrix) -> owns_col_starts) #define hypre_ParCSRMatrixNumRows(matrix) \ hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(matrix)) #define hypre_ParCSRMatrixNumCols(matrix) \ hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(matrix)) #define hypre_ParCSRMatrixNumNonzeros(matrix) ((matrix) -> num_nonzeros) #define hypre_ParCSRMatrixDNumNonzeros(matrix) ((matrix) -> d_num_nonzeros) #define hypre_ParCSRMatrixRowindices(matrix) ((matrix) -> rowindices) #define hypre_ParCSRMatrixRowvalues(matrix) ((matrix) -> rowvalues) #define hypre_ParCSRMatrixGetrowactive(matrix) ((matrix) -> getrowactive) #define hypre_ParCSRMatrixAssumedPartition(matrix) ((matrix) -> assumed_partition) /*-------------------------------------------------------------------------- * Parallel CSR Boolean Matrix *--------------------------------------------------------------------------*/ typedef struct { MPI_Comm comm; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int first_row_index; HYPRE_Int first_col_diag; HYPRE_Int last_row_index; HYPRE_Int last_col_diag; hypre_CSRBooleanMatrix *diag; hypre_CSRBooleanMatrix *offd; HYPRE_Int *col_map_offd; HYPRE_Int *row_starts; HYPRE_Int *col_starts; hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommPkg *comm_pkgT; HYPRE_Int owns_data; HYPRE_Int owns_row_starts; HYPRE_Int owns_col_starts; HYPRE_Int num_nonzeros; HYPRE_Int *rowindices; HYPRE_Int getrowactive; } hypre_ParCSRBooleanMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the Parallel CSR Boolean Matrix structure *--------------------------------------------------------------------------*/ #define hypre_ParCSRBooleanMatrix_Get_Comm(matrix) ((matrix)->comm) #define hypre_ParCSRBooleanMatrix_Get_GlobalNRows(matrix) ((matrix)->global_num_rows) #define hypre_ParCSRBooleanMatrix_Get_GlobalNCols(matrix) ((matrix)->global_num_cols) #define hypre_ParCSRBooleanMatrix_Get_StartRow(matrix) ((matrix)->first_row_index) #define hypre_ParCSRBooleanMatrix_Get_FirstRowIndex(matrix) ((matrix)->first_row_index) #define hypre_ParCSRBooleanMatrix_Get_FirstColDiag(matrix) ((matrix)->first_col_diag) #define hypre_ParCSRBooleanMatrix_Get_LastRowIndex(matrix) ((matrix)->last_row_index) #define hypre_ParCSRBooleanMatrix_Get_LastColDiag(matrix) ((matrix)->last_col_diag) #define hypre_ParCSRBooleanMatrix_Get_Diag(matrix) ((matrix)->diag) #define hypre_ParCSRBooleanMatrix_Get_Offd(matrix) ((matrix)->offd) #define hypre_ParCSRBooleanMatrix_Get_ColMapOffd(matrix) ((matrix)->col_map_offd) #define hypre_ParCSRBooleanMatrix_Get_RowStarts(matrix) ((matrix)->row_starts) #define hypre_ParCSRBooleanMatrix_Get_ColStarts(matrix) ((matrix)->col_starts) #define hypre_ParCSRBooleanMatrix_Get_CommPkg(matrix) ((matrix)->comm_pkg) #define hypre_ParCSRBooleanMatrix_Get_CommPkgT(matrix) ((matrix)->comm_pkgT) #define hypre_ParCSRBooleanMatrix_Get_OwnsData(matrix) ((matrix)->owns_data) #define hypre_ParCSRBooleanMatrix_Get_OwnsRowStarts(matrix) ((matrix)->owns_row_starts) #define hypre_ParCSRBooleanMatrix_Get_OwnsColStarts(matrix) ((matrix)->owns_col_starts) #define hypre_ParCSRBooleanMatrix_Get_NRows(matrix) ((matrix->diag->num_rows)) #define hypre_ParCSRBooleanMatrix_Get_NCols(matrix) ((matrix->diag->num_cols)) #define hypre_ParCSRBooleanMatrix_Get_NNZ(matrix) ((matrix)->num_nonzeros) #define hypre_ParCSRBooleanMatrix_Get_Rowindices(matrix) ((matrix)->rowindices) #define hypre_ParCSRBooleanMatrix_Get_Getrowactive(matrix) ((matrix)->getrowactive) #endif
9,164
49.357143
87
h
AMG
AMG-master/parcsr_mv/par_csr_matvec.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "_hypre_parcsr_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvec *--------------------------------------------------------------------------*/ // y = alpha*A*x + beta*b HYPRE_Int hypre_ParCSRMatrixMatvecOutOfPlace( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *b, hypre_ParVector *y ) { hypre_ParCSRCommHandle **comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *b_local = hypre_ParVectorLocalVector(b); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A); hypre_Vector *x_tmp; HYPRE_Int x_size = hypre_ParVectorGlobalSize(x); HYPRE_Int b_size = hypre_ParVectorGlobalSize(b); HYPRE_Int y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x_local); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, i, j, jv, index, start; HYPRE_Int vecstride = hypre_VectorVectorStride( x_local ); HYPRE_Int idxstride = hypre_VectorIndexStride( x_local ); HYPRE_Complex *x_tmp_data, **x_buf_data; HYPRE_Complex *x_local_data = hypre_VectorData(x_local); /*--------------------------------------------------------------------- * Check for size compatibility. ParMatvec returns ierr = 11 if * length of X doesn't equal the number of columns of A, * ierr = 12 if the length of Y doesn't equal the number of rows * of A, and ierr = 13 if both are true. * * Because temporary vectors are often used in ParMatvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( idxstride>0 ); if (num_cols != x_size) ierr = 11; if (num_rows != y_size || num_rows != b_size) ierr = 12; if (num_cols != x_size && (num_rows != y_size || num_rows != b_size)) ierr = 13; hypre_assert( hypre_VectorNumVectors(b_local)==num_vectors ); hypre_assert( hypre_VectorNumVectors(y_local)==num_vectors ); if ( num_vectors==1 ) x_tmp = hypre_SeqVectorCreate( num_cols_offd ); else { hypre_assert( num_vectors>1 ); x_tmp = hypre_SeqMultiVectorCreate( num_cols_offd, num_vectors ); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif HYPRE_Int use_persistent_comm = 0; #ifdef HYPRE_USING_PERSISTENT_COMM use_persistent_comm = num_vectors == 1; // JSP TODO: we can use persistent communication for multi-vectors, // but then we need different communication handles for different // num_vectors. hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if ( use_persistent_comm ) { #ifdef HYPRE_USING_PERSISTENT_COMM persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(1, comm_pkg); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); hypre_assert(num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); hypre_VectorData(x_tmp) = (HYPRE_Complex *)persistent_comm_handle->recv_data; hypre_SeqVectorSetDataOwner(x_tmp, 0); #endif } else { comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*,num_vectors); } hypre_SeqVectorInitialize(x_tmp); x_tmp_data = hypre_VectorData(x_tmp); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (!use_persistent_comm) { x_buf_data = hypre_CTAlloc( HYPRE_Complex*, num_vectors ); for ( jv=0; jv<num_vectors; ++jv ) x_buf_data[jv] = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); } if ( num_vectors==1 ) { HYPRE_Int begin = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = begin; i < end; i++) { #ifdef HYPRE_USING_PERSISTENT_COMM ((HYPRE_Complex *)persistent_comm_handle->send_data)[i - begin] #else x_buf_data[0][i - begin] #endif = x_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i)]; } } else for ( jv=0; jv<num_vectors; ++jv ) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) x_buf_data[jv][index++] = x_local_data[ jv*vecstride + idxstride*hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j) ]; } } hypre_assert( idxstride==1 ); /* ... The assert is because the following loop only works for 'column' storage of a multivector. This needs to be fixed to work more generally, at least for 'row' storage. This in turn, means either change CommPkg so num_sends is no.zones*no.vectors (not no.zones) or, less dangerously, put a stride in the logic of CommHandleCreate (stride either from a new arg or a new variable inside CommPkg). Or put the num_vector iteration inside CommHandleCreate (perhaps a new multivector variant of it). */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { comm_handle[jv] = hypre_ParCSRCommHandleCreate ( 1, comm_pkg, x_buf_data[jv], &(x_tmp_data[jv*num_cols_offd]) ); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif hypre_CSRMatrixMatvecOutOfPlace( alpha, diag, x_local, beta, b_local, y_local, 0); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { hypre_ParCSRCommHandleDestroy(comm_handle[jv]); comm_handle[jv] = NULL; } hypre_TFree(comm_handle); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif if (num_cols_offd) hypre_CSRMatrixMatvec( alpha, offd, x_tmp, 1.0, y_local); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif hypre_SeqVectorDestroy(x_tmp); x_tmp = NULL; if (!use_persistent_comm) { for ( jv=0; jv<num_vectors; ++jv ) hypre_TFree(x_buf_data[jv]); hypre_TFree(x_buf_data); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif return ierr; } HYPRE_Int hypre_ParCSRMatrixMatvec( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y ) { return hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y); } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvecT * * Performs y <- alpha * A^T * x + beta * y * *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixMatvecT( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y ) { hypre_ParCSRCommHandle **comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); hypre_Vector *y_tmp; HYPRE_Int vecstride = hypre_VectorVectorStride( y_local ); HYPRE_Int idxstride = hypre_VectorIndexStride( y_local ); HYPRE_Complex *y_tmp_data, **y_buf_data; HYPRE_Complex *y_local_data = hypre_VectorData(y_local); HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int x_size = hypre_ParVectorGlobalSize(x); HYPRE_Int y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(y_local); HYPRE_Int i, j, jv, index, start, num_sends; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_rows != x_size) ierr = 1; if (num_cols != y_size) ierr = 2; if (num_rows != x_size && num_cols != y_size) ierr = 3; /*----------------------------------------------------------------------- *-----------------------------------------------------------------------*/ if ( num_vectors==1 ) { y_tmp = hypre_SeqVectorCreate(num_cols_offd); } else { y_tmp = hypre_SeqMultiVectorCreate(num_cols_offd,num_vectors); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif HYPRE_Int use_persistent_comm = 0; #ifdef HYPRE_USING_PERSISTENT_COMM use_persistent_comm = num_vectors == 1; // JSP TODO: we can use persistent communication for multi-vectors, // but then we need different communication handles for different // num_vectors. hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM // JSP TODO: we should be also able to use persistent communication for multiple vectors persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(2, comm_pkg); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); hypre_assert(num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); hypre_VectorData(y_tmp) = (HYPRE_Complex *)persistent_comm_handle->send_data; hypre_SeqVectorSetDataOwner(y_tmp, 0); #endif } else { comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*,num_vectors); } hypre_SeqVectorInitialize(y_tmp); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (!use_persistent_comm) { y_buf_data = hypre_CTAlloc( HYPRE_Complex*, num_vectors ); for ( jv=0; jv<num_vectors; ++jv ) y_buf_data[jv] = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); } y_tmp_data = hypre_VectorData(y_tmp); y_local_data = hypre_VectorData(y_local); hypre_assert( idxstride==1 ); /* only 'column' storage of multivectors * implemented so far */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif if (num_cols_offd) { if (A->offdT) { // offdT is optional. Used only if it's present. hypre_CSRMatrixMatvec(alpha, A->offdT, x_local, 0.0, y_tmp); } else { hypre_CSRMatrixMatvecT(alpha, offd, x_local, 0.0, y_tmp); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { /* this is where we assume multivectors are 'column' storage */ comm_handle[jv] = hypre_ParCSRCommHandleCreate ( 2, comm_pkg, &(y_tmp_data[jv*num_cols_offd]), y_buf_data[jv] ); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif if (A->diagT) { // diagT is optional. Used only if it's present. hypre_CSRMatrixMatvec(alpha, A->diagT, x_local, beta, y_local); } else { hypre_CSRMatrixMatvecT(alpha, diag, x_local, beta, y_local); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { hypre_ParCSRCommHandleDestroy(comm_handle[jv]); comm_handle[jv] = NULL; } hypre_TFree(comm_handle); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif if ( num_vectors==1 ) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) y_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)] #ifdef HYPRE_USING_PERSISTENT_COMM += ((HYPRE_Complex *)persistent_comm_handle->recv_data)[index++]; #else += y_buf_data[0][index++]; #endif } } else for ( jv=0; jv<num_vectors; ++jv ) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) y_local_data[ jv*vecstride + idxstride*hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j) ] += y_buf_data[jv][index++]; } } hypre_SeqVectorDestroy(y_tmp); y_tmp = NULL; if (!use_persistent_comm) { for ( jv=0; jv<num_vectors; ++jv ) hypre_TFree(y_buf_data[jv]); hypre_TFree(y_buf_data); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvec_FF *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixMatvec_FF( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y, HYPRE_Int *CF_marker, HYPRE_Int fpt ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommHandle *comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A); hypre_Vector *x_tmp; HYPRE_Int x_size = hypre_ParVectorGlobalSize(x); HYPRE_Int y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, i, j, index, start, num_procs; HYPRE_Int *int_buf_data = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Complex *x_tmp_data = NULL; HYPRE_Complex *x_buf_data = NULL; HYPRE_Complex *x_local_data = hypre_VectorData(x_local); /*--------------------------------------------------------------------- * Check for size compatibility. ParMatvec returns ierr = 11 if * length of X doesn't equal the number of columns of A, * ierr = 12 if the length of Y doesn't equal the number of rows * of A, and ierr = 13 if both are true. * * Because temporary vectors are often used in ParMatvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm,&num_procs); if (num_cols != x_size) ierr = 11; if (num_rows != y_size) ierr = 12; if (num_cols != x_size && num_rows != y_size) ierr = 13; if (num_procs > 1) { if (num_cols_offd) { x_tmp = hypre_SeqVectorCreate( num_cols_offd ); hypre_SeqVectorInitialize(x_tmp); x_tmp_data = hypre_VectorData(x_tmp); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_sends) x_buf_data = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) x_buf_data[index++] = x_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate ( 1, comm_pkg, x_buf_data, x_tmp_data ); } hypre_CSRMatrixMatvec_FF( alpha, diag, x_local, beta, y_local, CF_marker, CF_marker, fpt); if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; if (num_sends) int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); if (num_cols_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg,int_buf_data,CF_marker_offd ); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; if (num_cols_offd) hypre_CSRMatrixMatvec_FF( alpha, offd, x_tmp, 1.0, y_local, CF_marker, CF_marker_offd, fpt); hypre_SeqVectorDestroy(x_tmp); x_tmp = NULL; hypre_TFree(x_buf_data); hypre_TFree(int_buf_data); hypre_TFree(CF_marker_offd); } return ierr; }
22,782
34.992101
94
c
AMG
AMG-master/parcsr_mv/par_vector.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for Parallel Vector data structure * *****************************************************************************/ #ifndef hypre_PAR_VECTOR_HEADER #define hypre_PAR_VECTOR_HEADER /*-------------------------------------------------------------------------- * hypre_ParVector *--------------------------------------------------------------------------*/ #ifndef HYPRE_PAR_VECTOR_STRUCT #define HYPRE_PAR_VECTOR_STRUCT #endif typedef struct hypre_ParVector_struct { MPI_Comm comm; HYPRE_Int global_size; HYPRE_Int first_index; HYPRE_Int last_index; HYPRE_Int *partitioning; HYPRE_Int actual_local_size; /* stores actual length of data in local vector to allow memory manipulations for temporary vectors*/ hypre_Vector *local_vector; /* Does the Vector create/destroy `data'? */ HYPRE_Int owns_data; HYPRE_Int owns_partitioning; hypre_IJAssumedPart *assumed_partition; /* only populated if no_global_partition option is used (compile-time option) AND this partition needed (for setting off-proc elements, for example)*/ } hypre_ParVector; /*-------------------------------------------------------------------------- * Accessor functions for the Vector structure *--------------------------------------------------------------------------*/ #define hypre_ParVectorComm(vector) ((vector) -> comm) #define hypre_ParVectorGlobalSize(vector) ((vector) -> global_size) #define hypre_ParVectorFirstIndex(vector) ((vector) -> first_index) #define hypre_ParVectorLastIndex(vector) ((vector) -> last_index) #define hypre_ParVectorPartitioning(vector) ((vector) -> partitioning) #define hypre_ParVectorActualLocalSize(vector) ((vector) -> actual_local_size) #define hypre_ParVectorLocalVector(vector) ((vector) -> local_vector) #define hypre_ParVectorOwnsData(vector) ((vector) -> owns_data) #define hypre_ParVectorOwnsPartitioning(vector) ((vector) -> owns_partitioning) #define hypre_ParVectorNumVectors(vector)\ (hypre_VectorNumVectors( hypre_ParVectorLocalVector(vector) )) #define hypre_ParVectorAssumedPartition(vector) ((vector) -> assumed_partition) #endif
3,376
39.202381
94
h
AMG
AMG-master/seq_mv/HYPRE_csr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_CSRMatrix interface * *****************************************************************************/ #include "seq_mv.h" /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixCreate *--------------------------------------------------------------------------*/ HYPRE_CSRMatrix HYPRE_CSRMatrixCreate( HYPRE_Int num_rows, HYPRE_Int num_cols, HYPRE_Int *row_sizes ) { hypre_CSRMatrix *matrix; HYPRE_Int *matrix_i; HYPRE_Int i; matrix_i = hypre_CTAlloc(HYPRE_Int, num_rows + 1); matrix_i[0] = 0; for (i = 0; i < num_rows; i++) { matrix_i[i+1] = matrix_i[i] + row_sizes[i]; } matrix = hypre_CSRMatrixCreate(num_rows, num_cols, matrix_i[num_rows]); hypre_CSRMatrixI(matrix) = matrix_i; return ( (HYPRE_CSRMatrix) matrix ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixDestroy( HYPRE_CSRMatrix matrix ) { return( hypre_CSRMatrixDestroy( (hypre_CSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixInitialize( HYPRE_CSRMatrix matrix ) { return ( hypre_CSRMatrixInitialize( (hypre_CSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixRead *--------------------------------------------------------------------------*/ HYPRE_CSRMatrix HYPRE_CSRMatrixRead( char *file_name ) { return ( (HYPRE_CSRMatrix) hypre_CSRMatrixRead( file_name ) ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixPrint *--------------------------------------------------------------------------*/ void HYPRE_CSRMatrixPrint( HYPRE_CSRMatrix matrix, char *file_name ) { hypre_CSRMatrixPrint( (hypre_CSRMatrix *) matrix, file_name ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixGetNumRows *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixGetNumRows( HYPRE_CSRMatrix matrix, HYPRE_Int *num_rows ) { hypre_CSRMatrix *csr_matrix = (hypre_CSRMatrix *) matrix; *num_rows = hypre_CSRMatrixNumRows( csr_matrix ); return 0; }
3,645
31.553571
81
c
AMG
AMG-master/seq_mv/HYPRE_seq_mv.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for HYPRE_mv library * *****************************************************************************/ #ifndef HYPRE_SEQ_MV_HEADER #define HYPRE_SEQ_MV_HEADER #include "../utilities/HYPRE_utilities.h" #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Structures *--------------------------------------------------------------------------*/ struct hypre_CSRMatrix_struct; typedef struct hypre_CSRMatrix_struct *HYPRE_CSRMatrix; #ifndef HYPRE_VECTOR_STRUCT #define HYPRE_VECTOR_STRUCT struct hypre_Vector_struct; typedef struct hypre_Vector_struct *HYPRE_Vector; #endif /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* HYPRE_csr_matrix.c */ HYPRE_CSRMatrix HYPRE_CSRMatrixCreate( HYPRE_Int num_rows , HYPRE_Int num_cols , HYPRE_Int *row_sizes ); HYPRE_Int HYPRE_CSRMatrixDestroy( HYPRE_CSRMatrix matrix ); HYPRE_Int HYPRE_CSRMatrixInitialize( HYPRE_CSRMatrix matrix ); HYPRE_CSRMatrix HYPRE_CSRMatrixRead( char *file_name ); void HYPRE_CSRMatrixPrint( HYPRE_CSRMatrix matrix , char *file_name ); HYPRE_Int HYPRE_CSRMatrixGetNumRows( HYPRE_CSRMatrix matrix , HYPRE_Int *num_rows ); /* HYPRE_vector.c */ HYPRE_Vector HYPRE_VectorCreate( HYPRE_Int size ); HYPRE_Int HYPRE_VectorDestroy( HYPRE_Vector vector ); HYPRE_Int HYPRE_VectorInitialize( HYPRE_Vector vector ); HYPRE_Int HYPRE_VectorPrint( HYPRE_Vector vector , char *file_name ); HYPRE_Vector HYPRE_VectorRead( char *file_name ); typedef enum HYPRE_TimerID { // timers for solver phase HYPRE_TIMER_ID_MATVEC = 0, HYPRE_TIMER_ID_BLAS1, HYPRE_TIMER_ID_RELAX, HYPRE_TIMER_ID_GS_ELIM_SOLVE, // timers for solve MPI HYPRE_TIMER_ID_PACK_UNPACK, // copying data to/from send/recv buf HYPRE_TIMER_ID_HALO_EXCHANGE, // halo exchange in matvec and relax HYPRE_TIMER_ID_ALL_REDUCE, // timers for setup phase // coarsening HYPRE_TIMER_ID_CREATES, HYPRE_TIMER_ID_CREATE_2NDS, HYPRE_TIMER_ID_PMIS, // interpolation HYPRE_TIMER_ID_EXTENDED_I_INTERP, HYPRE_TIMER_ID_PARTIAL_INTERP, HYPRE_TIMER_ID_MULTIPASS_INTERP, HYPRE_TIMER_ID_INTERP_TRUNC, HYPRE_TIMER_ID_MATMUL, // matrix-matrix multiplication HYPRE_TIMER_ID_COARSE_PARAMS, // rap HYPRE_TIMER_ID_RAP, // timers for setup MPI HYPRE_TIMER_ID_RENUMBER_COLIDX, HYPRE_TIMER_ID_EXCHANGE_INTERP_DATA, // setup etc HYPRE_TIMER_ID_GS_ELIM_SETUP, // temporaries HYPRE_TIMER_ID_BEXT_A, HYPRE_TIMER_ID_BEXT_S, HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP, HYPRE_TIMER_ID_MERGE, HYPRE_TIMER_ID_COUNT } HYPRE_TimerID; extern HYPRE_Real hypre_profile_times[HYPRE_TIMER_ID_COUNT]; #ifdef __cplusplus } #endif #endif
3,825
30.619835
104
h
AMG
AMG-master/seq_mv/HYPRE_vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_Vector interface * *****************************************************************************/ #include "seq_mv.h" /*-------------------------------------------------------------------------- * HYPRE_VectorCreate *--------------------------------------------------------------------------*/ HYPRE_Vector HYPRE_VectorCreate( HYPRE_Int size ) { return ( (HYPRE_Vector) hypre_SeqVectorCreate(size) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorDestroy( HYPRE_Vector vector ) { return ( hypre_SeqVectorDestroy( (hypre_Vector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorInitialize( HYPRE_Vector vector ) { return ( hypre_SeqVectorInitialize( (hypre_Vector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorPrint( HYPRE_Vector vector, char *file_name ) { return ( hypre_SeqVectorPrint( (hypre_Vector *) vector, file_name ) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorRead *--------------------------------------------------------------------------*/ HYPRE_Vector HYPRE_VectorRead( char *file_name ) { return ( (HYPRE_Vector) hypre_SeqVectorRead( file_name ) ); }
2,727
33.1
81
c
AMG
AMG-master/seq_mv/csr_matop.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Matrix operation functions for hypre_CSRMatrix class. * *****************************************************************************/ #include <assert.h> #include "seq_mv.h" #include "csr_matrix.h" /*-------------------------------------------------------------------------- * hypre_CSRMatrixAdd: * adds two CSR Matrices A and B and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixAdd( hypre_CSRMatrix *A, hypre_CSRMatrix *B ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int ia, ib, ic, jcol, num_nonzeros; HYPRE_Int pos; HYPRE_Int *marker; if (nrows_A != nrows_B || ncols_A != ncols_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } marker = hypre_CTAlloc(HYPRE_Int, ncols_A); C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1); for (ia = 0; ia < ncols_A; ia++) marker[ia] = -1; num_nonzeros = 0; C_i[0] = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; marker[jcol] = ic; num_nonzeros++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] != ic) { marker[jcol] = ic; num_nonzeros++; } } C_i[ic+1] = num_nonzeros; } C = hypre_CSRMatrixCreate(nrows_A, ncols_A, num_nonzeros); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize(C); C_j = hypre_CSRMatrixJ(C); C_data = hypre_CSRMatrixData(C); for (ia = 0; ia < ncols_A; ia++) marker[ia] = -1; pos = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; C_j[pos] = jcol; C_data[pos] = A_data[ia]; marker[jcol] = pos; pos++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] < C_i[ic]) { C_j[pos] = jcol; C_data[pos] = B_data[ib]; marker[jcol] = pos; pos++; } else { C_data[marker[jcol]] += B_data[ib]; } } } hypre_TFree(marker); return C; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMultiply * multiplies two CSR Matrices A and B and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixMultiply( hypre_CSRMatrix *A, hypre_CSRMatrix *B) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int ia, ib, ic, ja, jb, num_nonzeros=0; HYPRE_Int row_start, counter; HYPRE_Complex a_entry, b_entry; HYPRE_Int allsquare = 0; HYPRE_Int max_num_threads; HYPRE_Int *jj_count; if (ncols_A != nrows_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } if (nrows_A == ncols_B) allsquare = 1; C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1); max_num_threads = hypre_NumThreads(); jj_count = hypre_CTAlloc(HYPRE_Int, max_num_threads); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(ia, ib, ic, ja, jb, num_nonzeros, row_start, counter, a_entry, b_entry) #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne, ii, jj; HYPRE_Int size, rest, num_threads; HYPRE_Int i1; ii = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); size = nrows_A/num_threads; rest = nrows_A - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } B_marker = hypre_CTAlloc(HYPRE_Int, ncols_B); for (ib = 0; ib < ncols_B; ib++) B_marker[ib] = -1; num_nonzeros = 0; for (ic = ns; ic < ne; ic++) { C_i[ic] = num_nonzeros; if (allsquare) { B_marker[ic] = ic; num_nonzeros++; } for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { ja = A_j[ia]; for (ib = B_i[ja]; ib < B_i[ja+1]; ib++) { jb = B_j[ib]; if (B_marker[jb] != ic) { B_marker[jb] = ic; num_nonzeros++; } } } } jj_count[ii] = num_nonzeros; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { jj = jj_count[0]; for (i1 = 1; i1 < ii; i1++) jj += jj_count[i1]; for (i1 = ns; i1 < ne; i1++) C_i[i1] += jj; } else { C_i[nrows_A] = 0; for (i1 = 0; i1 < num_threads; i1++) C_i[nrows_A] += jj_count[i1]; C = hypre_CSRMatrixCreate(nrows_A, ncols_B, C_i[nrows_A]); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize(C); C_j = hypre_CSRMatrixJ(C); C_data = hypre_CSRMatrixData(C); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (ib = 0; ib < ncols_B; ib++) B_marker[ib] = -1; counter = C_i[ns]; for (ic = ns; ic < ne; ic++) { row_start = C_i[ic]; if (allsquare) { B_marker[ic] = counter; C_data[counter] = 0; C_j[counter] = ic; counter++; } for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { ja = A_j[ia]; a_entry = A_data[ia]; for (ib = B_i[ja]; ib < B_i[ja+1]; ib++) { jb = B_j[ib]; b_entry = B_data[ib]; if (B_marker[jb] < row_start) { B_marker[jb] = counter; C_j[B_marker[jb]] = jb; C_data[B_marker[jb]] = a_entry*b_entry; counter++; } else C_data[B_marker[jb]] += a_entry*b_entry; } } } hypre_TFree(B_marker); } /*end parallel region */ hypre_TFree(jj_count); return C; } hypre_CSRMatrix * hypre_CSRMatrixDeleteZeros( hypre_CSRMatrix *A, HYPRE_Real tol) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); hypre_CSRMatrix *B; HYPRE_Complex *B_data; HYPRE_Int *B_i; HYPRE_Int *B_j; HYPRE_Int zeros; HYPRE_Int i, j; HYPRE_Int pos_A, pos_B; zeros = 0; for (i=0; i < num_nonzeros; i++) if (hypre_cabs(A_data[i]) <= tol) zeros++; if (zeros) { B = hypre_CSRMatrixCreate(nrows_A,ncols_A,num_nonzeros-zeros); hypre_CSRMatrixInitialize(B); B_i = hypre_CSRMatrixI(B); B_j = hypre_CSRMatrixJ(B); B_data = hypre_CSRMatrixData(B); B_i[0] = 0; pos_A = 0; pos_B = 0; for (i=0; i < nrows_A; i++) { for (j = A_i[i]; j < A_i[i+1]; j++) { if (hypre_cabs(A_data[j]) <= tol) { pos_A++; } else { B_data[pos_B] = A_data[pos_A]; B_j[pos_B] = A_j[pos_A]; pos_B++; pos_A++; } } B_i[i+1] = pos_B; } return B; } else return NULL; } /****************************************************************************** * * Finds transpose of a hypre_CSRMatrix * *****************************************************************************/ /** * idx = idx2*dim1 + idx1 * -> ret = idx1*dim2 + idx2 * = (idx%dim1)*dim2 + idx/dim1 */ static inline HYPRE_Int transpose_idx(HYPRE_Int idx, HYPRE_Int dim1, HYPRE_Int dim2) { return idx%dim1*dim2 + idx/dim1; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixTranspose *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixTranspose(hypre_CSRMatrix *A, hypre_CSRMatrix **AT, HYPRE_Int data) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int num_colsA = hypre_CSRMatrixNumCols(A); HYPRE_Int num_nonzerosA = hypre_CSRMatrixNumNonzeros(A); HYPRE_Complex *AT_data; /*HYPRE_Int *AT_i;*/ HYPRE_Int *AT_j; HYPRE_Int num_rowsAT; HYPRE_Int num_colsAT; HYPRE_Int num_nonzerosAT; HYPRE_Int max_col; HYPRE_Int i, j; /*-------------------------------------------------------------- * First, ascertain that num_cols and num_nonzeros has been set. * If not, set them. *--------------------------------------------------------------*/ if (! num_nonzerosA) { num_nonzerosA = A_i[num_rowsA]; } if (num_rowsA && num_nonzerosA && ! num_colsA) { max_col = -1; for (i = 0; i < num_rowsA; ++i) { for (j = A_i[i]; j < A_i[i+1]; j++) { if (A_j[j] > max_col) max_col = A_j[j]; } } num_colsA = max_col+1; } num_rowsAT = num_colsA; num_colsAT = num_rowsA; num_nonzerosAT = num_nonzerosA; *AT = hypre_CSRMatrixCreate(num_rowsAT, num_colsAT, num_nonzerosAT); if (0 == num_colsA) { // JSP: parallel counting sorting breaks down // when A has no columns hypre_CSRMatrixInitialize(*AT); return 0; } AT_j = hypre_CTAlloc(HYPRE_Int, num_nonzerosAT); hypre_CSRMatrixJ(*AT) = AT_j; if (data) { AT_data = hypre_CTAlloc(HYPRE_Complex, num_nonzerosAT); hypre_CSRMatrixData(*AT) = AT_data; } /*----------------------------------------------------------------- * Parallel count sort *-----------------------------------------------------------------*/ HYPRE_Int *bucket = hypre_TAlloc( HYPRE_Int, (num_colsA + 1)*hypre_NumThreads()); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int iBegin = hypre_CSRMatrixGetLoadBalancedPartitionBegin(A); HYPRE_Int iEnd = hypre_CSRMatrixGetLoadBalancedPartitionEnd(A); hypre_assert(iBegin <= iEnd); hypre_assert(iBegin >= 0 && iBegin <= num_rowsA); hypre_assert(iEnd >= 0 && iEnd <= num_rowsA); HYPRE_Int i, j; memset(bucket + my_thread_num*num_colsA, 0, sizeof(HYPRE_Int)*num_colsA); /*----------------------------------------------------------------- * Count the number of entries that will go into each bucket * bucket is used as HYPRE_Int[num_threads][num_colsA] 2D array *-----------------------------------------------------------------*/ for (j = A_i[iBegin]; j < A_i[iEnd]; ++j) { HYPRE_Int idx = A_j[j]; bucket[my_thread_num*num_colsA + idx]++; } /*----------------------------------------------------------------- * Parallel prefix sum of bucket with length num_colsA * num_threads * accessed as if it is transposed as HYPRE_Int[num_colsA][num_threads] *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = my_thread_num*num_colsA + 1; i < (my_thread_num + 1)*num_colsA; ++i) { HYPRE_Int transpose_i = transpose_idx(i, num_threads, num_colsA); HYPRE_Int transpose_i_minus_1 = transpose_idx(i - 1, num_threads, num_colsA); bucket[transpose_i] += bucket[transpose_i_minus_1]; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #pragma omp master #endif { for (i = 1; i < num_threads; ++i) { HYPRE_Int j0 = num_colsA*i - 1, j1 = num_colsA*(i + 1) - 1; HYPRE_Int transpose_j0 = transpose_idx(j0, num_threads, num_colsA); HYPRE_Int transpose_j1 = transpose_idx(j1, num_threads, num_colsA); bucket[transpose_j1] += bucket[transpose_j0]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { HYPRE_Int transpose_i0 = transpose_idx(num_colsA*my_thread_num - 1, num_threads, num_colsA); HYPRE_Int offset = bucket[transpose_i0]; for (i = my_thread_num*num_colsA; i < (my_thread_num + 1)*num_colsA - 1; ++i) { HYPRE_Int transpose_i = transpose_idx(i, num_threads, num_colsA); bucket[transpose_i] += offset; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /*---------------------------------------------------------------- * Load the data and column numbers of AT *----------------------------------------------------------------*/ if (data) { for (i = iEnd - 1; i >= iBegin; --i) { for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) { HYPRE_Int idx = A_j[j]; --bucket[my_thread_num*num_colsA + idx]; HYPRE_Int offset = bucket[my_thread_num*num_colsA + idx]; AT_data[offset] = A_data[j]; AT_j[offset] = i; } } } else { for (i = iEnd - 1; i >= iBegin; --i) { for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) { HYPRE_Int idx = A_j[j]; --bucket[my_thread_num*num_colsA + idx]; HYPRE_Int offset = bucket[my_thread_num*num_colsA + idx]; AT_j[offset] = i; } } } } /*end parallel region */ hypre_CSRMatrixI(*AT) = bucket; // JSP: bucket is hypre_NumThreads() times longer than // the size needed for AT_i, but this should be OK. // If the memory size is a concern, we can allocate // a new memory for AT_i and copy from bucket. hypre_CSRMatrixI(*AT)[num_colsA] = num_nonzerosA; return(0); } /*-------------------------------------------------------------------------- * hypre_CSRMatrixReorder: * Reorders the column and data arrays of a square CSR matrix, such that the * first entry in each row is the diagonal one. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixReorder(hypre_CSRMatrix *A) { HYPRE_Int i, j, tempi, row_size; HYPRE_Complex tempd; HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int num_colsA = hypre_CSRMatrixNumCols(A); /* the matrix should be square */ if (num_rowsA != num_colsA) return -1; for (i = 0; i < num_rowsA; i++) { row_size = A_i[i+1]-A_i[i]; for (j = 0; j < row_size; j++) { if (A_j[j] == i) { if (j != 0) { tempi = A_j[0]; A_j[0] = A_j[j]; A_j[j] = tempi; tempd = A_data[0]; A_data[0] = A_data[j]; A_data[j] = tempd; } break; } /* diagonal element is missing */ if (j == row_size-1) return -2; } A_j += row_size; A_data += row_size; } return 0; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSumElts: * Returns the sum of all matrix elements. *--------------------------------------------------------------------------*/ HYPRE_Complex hypre_CSRMatrixSumElts( hypre_CSRMatrix *A ) { HYPRE_Complex sum = 0; HYPRE_Complex *data = hypre_CSRMatrixData( A ); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int i; for ( i=0; i<num_nonzeros; ++i ) sum += data[i]; return sum; }
18,537
27.652241
100
c
AMG
AMG-master/seq_mv/csr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "seq_mv.h" #ifdef HYPRE_PROFILE HYPRE_Real hypre_profile_times[HYPRE_TIMER_ID_COUNT] = { 0 }; #endif /*-------------------------------------------------------------------------- * hypre_CSRMatrixCreate *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixCreate( HYPRE_Int num_rows, HYPRE_Int num_cols, HYPRE_Int num_nonzeros ) { hypre_CSRMatrix *matrix; matrix = hypre_CTAlloc(hypre_CSRMatrix, 1); hypre_CSRMatrixData(matrix) = NULL; hypre_CSRMatrixI(matrix) = NULL; hypre_CSRMatrixJ(matrix) = NULL; hypre_CSRMatrixRownnz(matrix) = NULL; hypre_CSRMatrixNumRows(matrix) = num_rows; hypre_CSRMatrixNumCols(matrix) = num_cols; hypre_CSRMatrixNumNonzeros(matrix) = num_nonzeros; /* set defaults */ hypre_CSRMatrixOwnsData(matrix) = 1; hypre_CSRMatrixNumRownnz(matrix) = num_rows; return matrix; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixDestroy( hypre_CSRMatrix *matrix ) { HYPRE_Int ierr=0; if (matrix) { hypre_TFree(hypre_CSRMatrixI(matrix)); hypre_CSRMatrixI(matrix) = NULL; if (hypre_CSRMatrixRownnz(matrix)) hypre_TFree(hypre_CSRMatrixRownnz(matrix)); if ( hypre_CSRMatrixOwnsData(matrix) ) { hypre_TFree(hypre_CSRMatrixData(matrix)); hypre_TFree(hypre_CSRMatrixJ(matrix)); hypre_CSRMatrixData(matrix) = NULL; hypre_CSRMatrixJ(matrix) = NULL; } hypre_TFree(matrix); matrix = NULL; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixInitialize( hypre_CSRMatrix *matrix ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows(matrix); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(matrix); /* HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(matrix); */ HYPRE_Int ierr=0; if ( ! hypre_CSRMatrixData(matrix) && num_nonzeros ) hypre_CSRMatrixData(matrix) = hypre_CTAlloc(HYPRE_Complex, num_nonzeros); if ( ! hypre_CSRMatrixI(matrix) ) hypre_CSRMatrixI(matrix) = hypre_CTAlloc(HYPRE_Int, num_rows + 1); /* if ( ! hypre_CSRMatrixRownnz(matrix) ) hypre_CSRMatrixRownnz(matrix) = hypre_CTAlloc(HYPRE_Int, num_rownnz);*/ if ( ! hypre_CSRMatrixJ(matrix) && num_nonzeros ) hypre_CSRMatrixJ(matrix) = hypre_CTAlloc(HYPRE_Int, num_nonzeros); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixSetDataOwner( hypre_CSRMatrix *matrix, HYPRE_Int owns_data ) { HYPRE_Int ierr=0; hypre_CSRMatrixOwnsData(matrix) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSetRownnz * * function to set the substructure rownnz and num_rowsnnz inside the CSRMatrix * it needs the A_i substructure of CSRMatrix to find the nonzero rows. * It runs after the create CSR and when A_i is known..It does not check for * the existence of A_i or of the CSR matrix. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixSetRownnz( hypre_CSRMatrix *matrix ) { HYPRE_Int ierr=0; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(matrix); HYPRE_Int *A_i = hypre_CSRMatrixI(matrix); HYPRE_Int *Arownnz; HYPRE_Int i, adiag; HYPRE_Int irownnz=0; for (i=0; i < num_rows; i++) { adiag = (A_i[i+1] - A_i[i]); if(adiag > 0) irownnz++; } hypre_CSRMatrixNumRownnz(matrix) = irownnz; if ((irownnz == 0) || (irownnz == num_rows)) { hypre_CSRMatrixRownnz(matrix) = NULL; } else { Arownnz = hypre_CTAlloc(HYPRE_Int, irownnz); irownnz = 0; for (i=0; i < num_rows; i++) { adiag = A_i[i+1]-A_i[i]; if(adiag > 0) Arownnz[irownnz++] = i; } hypre_CSRMatrixRownnz(matrix) = Arownnz; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixRead *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixRead( char *file_name ) { hypre_CSRMatrix *matrix; FILE *fp; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int num_nonzeros; HYPRE_Int max_col = 0; HYPRE_Int file_base = 1; HYPRE_Int j; /*---------------------------------------------------------- * Read in the data *----------------------------------------------------------*/ fp = fopen(file_name, "r"); hypre_fscanf(fp, "%d", &num_rows); matrix_i = hypre_CTAlloc(HYPRE_Int, num_rows + 1); for (j = 0; j < num_rows+1; j++) { hypre_fscanf(fp, "%d", &matrix_i[j]); matrix_i[j] -= file_base; } num_nonzeros = matrix_i[num_rows]; matrix = hypre_CSRMatrixCreate(num_rows, num_rows, matrix_i[num_rows]); hypre_CSRMatrixI(matrix) = matrix_i; hypre_CSRMatrixInitialize(matrix); matrix_j = hypre_CSRMatrixJ(matrix); for (j = 0; j < num_nonzeros; j++) { hypre_fscanf(fp, "%d", &matrix_j[j]); matrix_j[j] -= file_base; if (matrix_j[j] > max_col) { max_col = matrix_j[j]; } } matrix_data = hypre_CSRMatrixData(matrix); for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fscanf(fp, "%le", &matrix_data[j]); } fclose(fp); hypre_CSRMatrixNumNonzeros(matrix) = num_nonzeros; hypre_CSRMatrixNumCols(matrix) = ++max_col; return matrix; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixPrint( hypre_CSRMatrix *matrix, char *file_name ) { FILE *fp; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int file_base = 1; HYPRE_Int j; HYPRE_Int ierr = 0; /*---------------------------------------------------------- * Print the matrix data *----------------------------------------------------------*/ matrix_data = hypre_CSRMatrixData(matrix); matrix_i = hypre_CSRMatrixI(matrix); matrix_j = hypre_CSRMatrixJ(matrix); num_rows = hypre_CSRMatrixNumRows(matrix); fp = fopen(file_name, "w"); hypre_fprintf(fp, "%d\n", num_rows); for (j = 0; j <= num_rows; j++) { hypre_fprintf(fp, "%d\n", matrix_i[j] + file_base); } for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fprintf(fp, "%d\n", matrix_j[j] + file_base); } if (matrix_data) { for (j = 0; j < matrix_i[num_rows]; j++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(matrix_data[j]), hypre_cimag(matrix_data[j])); #else hypre_fprintf(fp, "%.14e\n", matrix_data[j]); #endif } } else { hypre_fprintf(fp, "Warning: No matrix data!\n"); } fclose(fp); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixPrintHB: print a CSRMatrix in Harwell-Boeing format *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixPrintHB( hypre_CSRMatrix *matrix_input, char *file_name ) { FILE *fp; hypre_CSRMatrix *matrix; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int file_base = 1; HYPRE_Int j, totcrd, ptrcrd, indcrd, valcrd, rhscrd; HYPRE_Int ierr = 0; /*---------------------------------------------------------- * Print the matrix data *----------------------------------------------------------*/ /* First transpose the input matrix, since HB is in CSC format */ hypre_CSRMatrixTranspose(matrix_input, &matrix, 1); matrix_data = hypre_CSRMatrixData(matrix); matrix_i = hypre_CSRMatrixI(matrix); matrix_j = hypre_CSRMatrixJ(matrix); num_rows = hypre_CSRMatrixNumRows(matrix); fp = fopen(file_name, "w"); hypre_fprintf(fp, "%-70s Key \n", "Title"); ptrcrd = num_rows; indcrd = matrix_i[num_rows]; valcrd = matrix_i[num_rows]; rhscrd = 0; totcrd = ptrcrd + indcrd + valcrd + rhscrd; hypre_fprintf (fp, "%14d%14d%14d%14d%14d\n", totcrd, ptrcrd, indcrd, valcrd, rhscrd); hypre_fprintf (fp, "%-14s%14i%14i%14i%14i\n", "RUA", num_rows, num_rows, valcrd, 0); hypre_fprintf (fp, "%-16s%-16s%-16s%26s\n", "(1I8)", "(1I8)", "(1E16.8)", ""); for (j = 0; j <= num_rows; j++) { hypre_fprintf(fp, "%8d\n", matrix_i[j] + file_base); } for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fprintf(fp, "%8d\n", matrix_j[j] + file_base); } if (matrix_data) { for (j = 0; j < matrix_i[num_rows]; j++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%16.8e , %16.8e\n", hypre_creal(matrix_data[j]), hypre_cimag(matrix_data[j])); #else hypre_fprintf(fp, "%16.8e\n", matrix_data[j]); #endif } } else { hypre_fprintf(fp, "Warning: No matrix data!\n"); } fclose(fp); hypre_CSRMatrixDestroy(matrix); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixCopy: * copys A to B, * if copy_data = 0 only the structure of A is copied to B. * the routine does not check if the dimensions of A and B match !!! *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixCopy( hypre_CSRMatrix *A, hypre_CSRMatrix *B, HYPRE_Int copy_data ) { HYPRE_Int ierr=0; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Complex *A_data; HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Complex *B_data; HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int i, j; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i=0; i <= num_rows; i++) { B_i[i] = A_i[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_nonzeros; ++j) { B_j[j] = A_j[j]; } if (copy_data) { A_data = hypre_CSRMatrixData(A); B_data = hypre_CSRMatrixData(B); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (j=0; j < num_nonzeros; j++) { B_data[j] = A_data[j]; } } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixClone * Creates and returns a new copy of the argument, A. * Data is not copied, only structural information is reproduced. * Copying is a deep copy in that no pointers are copied; new arrays are * created where necessary. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixClone( hypre_CSRMatrix * A ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows( A ); HYPRE_Int num_cols = hypre_CSRMatrixNumCols( A ); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros( A ); hypre_CSRMatrix * B = hypre_CSRMatrixCreate( num_rows, num_cols, num_nonzeros ); HYPRE_Int * A_i; HYPRE_Int * A_j; HYPRE_Int * B_i; HYPRE_Int * B_j; HYPRE_Int i, j; hypre_CSRMatrixInitialize( B ); A_i = hypre_CSRMatrixI(A); A_j = hypre_CSRMatrixJ(A); B_i = hypre_CSRMatrixI(B); B_j = hypre_CSRMatrixJ(B); for ( i=0; i<num_rows+1; ++i ) B_i[i] = A_i[i]; for ( j=0; j<num_nonzeros; ++j ) B_j[j] = A_j[j]; hypre_CSRMatrixNumRownnz(B) = hypre_CSRMatrixNumRownnz(A); if ( hypre_CSRMatrixRownnz(A) ) hypre_CSRMatrixSetRownnz( B ); return B; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixUnion * Creates and returns a matrix whose elements are the union of those of A and B. * Data is not computed, only structural information is created. * A and B must have the same numbers of rows. * Nothing is done about Rownnz. * * If col_map_offd_A and col_map_offd_B are zero, A and B are expected to have * the same column indexing. Otherwise, col_map_offd_A, col_map_offd_B should * be the arrays of that name from two ParCSRMatrices of which A and B are the * offd blocks. * * The algorithm can be expected to have reasonable efficiency only for very * sparse matrices (many rows, few nonzeros per row). * The nonzeros of a computed row are NOT necessarily in any particular order. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixUnion( hypre_CSRMatrix * A, hypre_CSRMatrix * B, HYPRE_Int * col_map_offd_A, HYPRE_Int * col_map_offd_B, HYPRE_Int ** col_map_offd_C ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows( A ); HYPRE_Int num_cols_A = hypre_CSRMatrixNumCols( A ); HYPRE_Int num_cols_B = hypre_CSRMatrixNumCols( B ); HYPRE_Int num_cols; HYPRE_Int num_nonzeros; HYPRE_Int * A_i = hypre_CSRMatrixI(A); HYPRE_Int * A_j = hypre_CSRMatrixJ(A); HYPRE_Int * B_i = hypre_CSRMatrixI(B); HYPRE_Int * B_j = hypre_CSRMatrixJ(B); HYPRE_Int * C_i; HYPRE_Int * C_j; HYPRE_Int * jC = NULL; HYPRE_Int i, jA, jB, jBg; HYPRE_Int ma, mb, mc, ma_min, ma_max, match; hypre_CSRMatrix * C; hypre_assert( num_rows == hypre_CSRMatrixNumRows(B) ); if ( col_map_offd_B ) hypre_assert( col_map_offd_A ); if ( col_map_offd_A ) hypre_assert( col_map_offd_B ); /* ==== First, go through the columns of A and B to count the columns of C. */ if ( col_map_offd_A==0 ) { /* The matrices are diagonal blocks. Normally num_cols_A==num_cols_B, col_starts is the same, etc. */ num_cols = hypre_max( num_cols_A, num_cols_B ); } else { /* The matrices are offdiagonal blocks. */ jC = hypre_CTAlloc( HYPRE_Int, num_cols_B ); num_cols = num_cols_A; /* initialization; we'll compute the actual value */ for ( jB=0; jB<num_cols_B; ++jB ) { match = 0; jBg = col_map_offd_B[jB]; for ( ma=0; ma<num_cols_A; ++ma ) { if ( col_map_offd_A[ma]==jBg ) match = 1; } if ( match==0 ) { jC[jB] = num_cols; ++num_cols; } } } /* ==== If we're working on a ParCSRMatrix's offd block, make and load col_map_offd_C */ if ( col_map_offd_A ) { *col_map_offd_C = hypre_CTAlloc( HYPRE_Int, num_cols ); for ( jA=0; jA<num_cols_A; ++jA ) (*col_map_offd_C)[jA] = col_map_offd_A[jA]; for ( jB=0; jB<num_cols_B; ++jB ) { match = 0; jBg = col_map_offd_B[jB]; for ( ma=0; ma<num_cols_A; ++ma ) { if ( col_map_offd_A[ma]==jBg ) match = 1; } if ( match==0 ) (*col_map_offd_C)[ jC[jB] ] = jBg; } } /* ==== The first run through A and B is to count the number of nonzero elements, without HYPRE_Complex-counting duplicates. Then we can create C. */ num_nonzeros = hypre_CSRMatrixNumNonzeros(A); for ( i=0; i<num_rows; ++i ) { ma_min = A_i[i]; ma_max = A_i[i+1]; for ( mb=B_i[i]; mb<B_i[i+1]; ++mb ) { jB = B_j[mb]; if ( col_map_offd_B ) jB = col_map_offd_B[jB]; match = 0; for ( ma=ma_min; ma<ma_max; ++ma ) { jA = A_j[ma]; if ( col_map_offd_A ) jA = col_map_offd_A[jA]; if ( jB == jA ) { match = 1; if( ma==ma_min ) ++ma_min; break; } } if ( match==0 ) ++num_nonzeros; } } C = hypre_CSRMatrixCreate( num_rows, num_cols, num_nonzeros ); hypre_CSRMatrixInitialize( C ); /* ==== The second run through A and B is to pick out the column numbers for each row, and put them in C. */ C_i = hypre_CSRMatrixI(C); C_i[0] = 0; C_j = hypre_CSRMatrixJ(C); mc = 0; for ( i=0; i<num_rows; ++i ) { ma_min = A_i[i]; ma_max = A_i[i+1]; for ( ma=ma_min; ma<ma_max; ++ma ) { C_j[mc] = A_j[ma]; ++mc; } for ( mb=B_i[i]; mb<B_i[i+1]; ++mb ) { jB = B_j[mb]; if ( col_map_offd_B ) jB = col_map_offd_B[jB]; match = 0; for ( ma=ma_min; ma<ma_max; ++ma ) { jA = A_j[ma]; if ( col_map_offd_A ) jA = col_map_offd_A[jA]; if ( jB == jA ) { match = 1; if( ma==ma_min ) ++ma_min; break; } } if ( match==0 ) { if ( col_map_offd_A ) C_j[mc] = jC[ B_j[mb] ]; else C_j[mc] = B_j[mb]; /* ... I don't know whether column indices are required to be in any particular order. If so, we'll need to sort. */ ++mc; } } C_i[i+1] = mc; } hypre_assert( mc == num_nonzeros ); if (jC) hypre_TFree( jC ); return C; } static HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBoundary(hypre_CSRMatrix *A, HYPRE_Int idx) { HYPRE_Int num_nonzerosA = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int nonzeros_per_thread = (num_nonzerosA + num_threads - 1)/num_threads; if (idx <= 0) { return 0; } else if (idx >= num_threads) { return num_rowsA; } else { return (HYPRE_Int)(hypre_LowerBound(A_i, A_i + num_rowsA, nonzeros_per_thread*idx) - A_i); } } HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBegin(hypre_CSRMatrix *A) { return hypre_CSRMatrixGetLoadBalancedPartitionBoundary(A, hypre_GetThreadNum()); } HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionEnd(hypre_CSRMatrix *A) { return hypre_CSRMatrixGetLoadBalancedPartitionBoundary(A, hypre_GetThreadNum() + 1); }
20,095
28.727811
99
c
AMG
AMG-master/seq_mv/csr_matrix.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for CSR Matrix data structures * * Note: this matrix currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_CSR_MATRIX_HEADER #define hypre_CSR_MATRIX_HEADER /*-------------------------------------------------------------------------- * CSR Matrix *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Int *i; HYPRE_Int *j; HYPRE_Int num_rows; HYPRE_Int num_cols; HYPRE_Int num_nonzeros; /* Does the CSRMatrix create/destroy `data', `i', `j'? */ HYPRE_Int owns_data; HYPRE_Complex *data; /* for compressing rows in matrix multiplication */ HYPRE_Int *rownnz; HYPRE_Int num_rownnz; } hypre_CSRMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the CSR Matrix structure *--------------------------------------------------------------------------*/ #define hypre_CSRMatrixData(matrix) ((matrix) -> data) #define hypre_CSRMatrixI(matrix) ((matrix) -> i) #define hypre_CSRMatrixJ(matrix) ((matrix) -> j) #define hypre_CSRMatrixNumRows(matrix) ((matrix) -> num_rows) #define hypre_CSRMatrixNumCols(matrix) ((matrix) -> num_cols) #define hypre_CSRMatrixNumNonzeros(matrix) ((matrix) -> num_nonzeros) #define hypre_CSRMatrixRownnz(matrix) ((matrix) -> rownnz) #define hypre_CSRMatrixNumRownnz(matrix) ((matrix) -> num_rownnz) #define hypre_CSRMatrixOwnsData(matrix) ((matrix) -> owns_data) HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBegin( hypre_CSRMatrix *A ); HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionEnd( hypre_CSRMatrix *A ); /*-------------------------------------------------------------------------- * CSR Boolean Matrix *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Int *i; HYPRE_Int *j; HYPRE_Int num_rows; HYPRE_Int num_cols; HYPRE_Int num_nonzeros; HYPRE_Int owns_data; } hypre_CSRBooleanMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the CSR Boolean Matrix structure *--------------------------------------------------------------------------*/ #define hypre_CSRBooleanMatrix_Get_I(matrix) ((matrix)->i) #define hypre_CSRBooleanMatrix_Get_J(matrix) ((matrix)->j) #define hypre_CSRBooleanMatrix_Get_NRows(matrix) ((matrix)->num_rows) #define hypre_CSRBooleanMatrix_Get_NCols(matrix) ((matrix)->num_cols) #define hypre_CSRBooleanMatrix_Get_NNZ(matrix) ((matrix)->num_nonzeros) #define hypre_CSRBooleanMatrix_Get_OwnsData(matrix) ((matrix)->owns_data) #endif
3,814
38.329897
81
h
AMG
AMG-master/seq_mv/csr_matvec.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "seq_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvec *--------------------------------------------------------------------------*/ /* y[offset:end] = alpha*A[offset:end,:]*x + beta*b[offset:end] */ HYPRE_Int hypre_CSRMatrixMatvecOutOfPlace( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *b, hypre_Vector *y, HYPRE_Int offset ) { #ifdef HYPRE_PROFILE HYPRE_Real time_begin = hypre_MPI_Wtime(); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A) + offset; HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A) - offset; HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); /*HYPRE_Int num_nnz = hypre_CSRMatrixNumNonzeros(A);*/ HYPRE_Int *A_rownnz = hypre_CSRMatrixRownnz(A); HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *b_data = hypre_VectorData(b) + offset; HYPRE_Complex *y_data = hypre_VectorData(y) + offset; HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int b_size = hypre_VectorSize(b) - offset; HYPRE_Int y_size = hypre_VectorSize(y) - offset; HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); /*HYPRE_Int idxstride_b = hypre_VectorIndexStride(b); HYPRE_Int vecstride_b = hypre_VectorVectorStride(b);*/ HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); HYPRE_Complex temp, tempx; HYPRE_Int i, j, jj; HYPRE_Int m; HYPRE_Real xpar=0.7; HYPRE_Int ierr = 0; hypre_Vector *x_tmp = NULL; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); hypre_assert( num_vectors == hypre_VectorNumVectors(b) ); if (num_cols != x_size) ierr = 1; if (num_rows != y_size || num_rows != b_size) ierr = 2; if (num_cols != x_size && (num_rows != y_size || num_rows != b_size)) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = beta*b_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif return ierr; } if (x == y) { x_tmp = hypre_SeqVectorCloneDeep(x); x_data = hypre_VectorData(x_tmp); } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; /* use rownnz pointer to do the A*x multiplication when num_rownnz is smaller than num_rows */ if (num_rownnz < xpar*(num_rows) || num_vectors > 1) { /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = b_data[i]*temp; } } else { for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = b_data[i]; } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ if (num_rownnz < xpar*(num_rows)) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,jj,m,tempx) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rownnz; i++) { m = A_rownnz[i]; /* * for (jj = A_i[m]; jj < A_i[m+1]; jj++) * { * j = A_j[jj]; * y_data[m] += A_data[jj] * x_data[j]; * } */ if ( num_vectors==1 ) { tempx = 0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[A_j[jj]]; y_data[m] += tempx; } else for ( j=0; j<num_vectors; ++j ) { tempx = 0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; y_data[ j*vecstride_y + m*idxstride_y] += tempx; } } } else // num_vectors > 1 { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,jj,tempx) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { for (j = 0; j < num_vectors; ++j) { tempx = 0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; } y_data[ j*vecstride_y + i*idxstride_y ] += tempx; } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= alpha; } } else { // JSP: this is currently the only path optimized #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,jj,tempx) #endif { HYPRE_Int iBegin = hypre_CSRMatrixGetLoadBalancedPartitionBegin(A); HYPRE_Int iEnd = hypre_CSRMatrixGetLoadBalancedPartitionEnd(A); hypre_assert(iBegin <= iEnd); hypre_assert(iBegin >= 0 && iBegin <= num_rows); hypre_assert(iEnd >= 0 && iEnd <= num_rows); if (0 == temp) { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x else if (-1 == alpha) { for (i = iBegin; i < iEnd; i++) { tempx = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x else { for (i = iBegin; i < iEnd; i++) { tempx = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*A*x } // temp == 0 else if (-1 == temp) // beta == -alpha { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x - y else if (-1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x + y else { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*(A*x - y) } // temp == -1 else if (1 == temp) { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x + y else if (-1 == alpha) { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x - y else { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*(A*x + y) } else { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]*temp; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x + temp*y else if (-1 == alpha) { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]*temp; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x - temp*y else { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]*temp; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*(A*x + temp*y) } // temp != 0 && temp != -1 && temp != 1 } // omp parallel } if (x == y) hypre_SeqVectorDestroy(x_tmp); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif return ierr; } HYPRE_Int hypre_CSRMatrixMatvec( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y ) { return hypre_CSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y, 0); } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvecT * * This version is using a different (more efficient) threading scheme * Performs y <- alpha * A^T * x + beta * y * * From Van Henson's modification of hypre_CSRMatrixMatvec. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvecT( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); HYPRE_Complex temp; HYPRE_Complex *y_data_expand; HYPRE_Int my_thread_num = 0, offset = 0; HYPRE_Int i, j, jv, jj; HYPRE_Int num_threads; HYPRE_Int ierr = 0; hypre_Vector *x_tmp = NULL; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); if (num_rows != x_size) ierr = 1; if (num_cols != y_size) ierr = 2; if (num_rows != x_size && num_cols != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= beta; return ierr; } if (x == y) { x_tmp = hypre_SeqVectorCloneDeep(x); x_data = hypre_VectorData(x_tmp); } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A^T*x *-----------------------------------------------------------------*/ num_threads = hypre_NumThreads(); if (num_threads > 1) { y_data_expand = hypre_CTAlloc(HYPRE_Complex, num_threads*y_size); if ( num_vectors==1 ) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,jj,j,my_thread_num,offset) #endif { my_thread_num = hypre_GetThreadNum(); offset = y_size*my_thread_num; #ifdef HYPRE_USING_OPENMP #pragma omp for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data_expand[offset + j] += A_data[jj] * x_data[i]; } } /* implied barrier (for threads)*/ #ifdef HYPRE_USING_OPENMP #pragma omp for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < y_size; i++) { for (j = 0; j < num_threads; j++) { y_data[i] += y_data_expand[j*y_size + i]; } } } /* end parallel threaded region */ } else { /* multiple vector case is not threaded */ for (i = 0; i < num_rows; i++) { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x]; } } } } hypre_TFree(y_data_expand); } else { for (i = 0; i < num_rows; i++) { if ( num_vectors==1 ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[j] += A_data[jj] * x_data[i]; } } else { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x ]; } } } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= alpha; } if (x == y) hypre_SeqVectorDestroy(x_tmp); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvec_FF *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvec_FF( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y, HYPRE_Int *CF_marker_x, HYPRE_Int *CF_marker_y, HYPRE_Int fpt ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Complex temp; HYPRE_Int i, jj; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_cols != x_size) ierr = 1; if (num_rows != y_size) ierr = 2; if (num_cols != x_size && num_rows != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,jj) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { if (CF_marker_x[i] == fpt) { temp = y_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) if (CF_marker_y[A_j[jj]] == fpt) temp += A_data[jj] * x_data[A_j[jj]]; y_data[i] = temp; } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= alpha; } return ierr; }
24,315
30.335052
95
c
AMG
AMG-master/seq_mv/genpart.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "seq_mv.h" /*-------------------------------------------------------------------------- * hypre_GeneratePartitioning: * generates load balanced partitioning of a 1-d array *--------------------------------------------------------------------------*/ /* for multivectors, length should be the (global) length of a single vector. Thus each of the vectors of the multivector will get the same data distribution. */ HYPRE_Int hypre_GeneratePartitioning(HYPRE_Int length, HYPRE_Int num_procs, HYPRE_Int **part_ptr) { HYPRE_Int ierr = 0; HYPRE_Int *part; HYPRE_Int size, rest; HYPRE_Int i; part = hypre_CTAlloc(HYPRE_Int, num_procs+1); size = length / num_procs; rest = length - size*num_procs; part[0] = 0; for (i=0; i < num_procs; i++) { part[i+1] = part[i]+size; if (i < rest) part[i+1]++; } *part_ptr = part; return ierr; } /* This function differs from the above in that it only returns the portion of the partition belonging to the individual process - to do this it requires the processor id as well AHB 6/05*/ HYPRE_Int hypre_GenerateLocalPartitioning(HYPRE_Int length, HYPRE_Int num_procs, HYPRE_Int myid, HYPRE_Int **part_ptr) { HYPRE_Int ierr = 0; HYPRE_Int *part; HYPRE_Int size, rest; part = hypre_CTAlloc(HYPRE_Int, 2); size = length /num_procs; rest = length - size*num_procs; /* first row I own */ part[0] = size*myid; part[0] += hypre_min(myid, rest); /* last row I own */ part[1] = size*(myid+1); part[1] += hypre_min(myid+1, rest); part[1] = part[1] - 1; /* add 1 to last row since this is for "starts" vector */ part[1] = part[1] + 1; *part_ptr = part; return ierr; }
2,649
28.775281
108
c
AMG
AMG-master/seq_mv/headers.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "seq_mv.h"
1,007
36.333333
81
h
AMG
AMG-master/seq_mv/vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang ([email protected]) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "seq_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_SeqVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCreate( HYPRE_Int size ) { hypre_Vector *vector; vector = hypre_CTAlloc(hypre_Vector, 1); hypre_VectorData(vector) = NULL; hypre_VectorSize(vector) = size; hypre_VectorNumVectors(vector) = 1; hypre_VectorMultiVecStorageMethod(vector) = 0; /* set defaults */ hypre_VectorOwnsData(vector) = 1; return vector; } /*-------------------------------------------------------------------------- * hypre_SeqMultiVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqMultiVectorCreate( HYPRE_Int size, HYPRE_Int num_vectors ) { hypre_Vector *vector = hypre_SeqVectorCreate(size); hypre_VectorNumVectors(vector) = num_vectors; return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorDestroy( hypre_Vector *vector ) { HYPRE_Int ierr=0; if (vector) { if ( hypre_VectorOwnsData(vector) ) { hypre_TFree(hypre_VectorData(vector)); } hypre_TFree(vector); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorInitialize( hypre_Vector *vector ) { HYPRE_Int size = hypre_VectorSize(vector); HYPRE_Int ierr = 0; HYPRE_Int num_vectors = hypre_VectorNumVectors(vector); HYPRE_Int multivec_storage_method = hypre_VectorMultiVecStorageMethod(vector); if ( ! hypre_VectorData(vector) ) hypre_VectorData(vector) = hypre_CTAlloc(HYPRE_Complex, num_vectors*size); if ( multivec_storage_method == 0 ) { hypre_VectorVectorStride(vector) = size; hypre_VectorIndexStride(vector) = 1; } else if ( multivec_storage_method == 1 ) { hypre_VectorVectorStride(vector) = 1; hypre_VectorIndexStride(vector) = num_vectors; } else ++ierr; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetDataOwner( hypre_Vector *vector, HYPRE_Int owns_data ) { HYPRE_Int ierr=0; hypre_VectorOwnsData(vector) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * ReadVector *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorRead( char *file_name ) { hypre_Vector *vector; FILE *fp; HYPRE_Complex *data; HYPRE_Int size; HYPRE_Int j; /*---------------------------------------------------------- * Read in the data *----------------------------------------------------------*/ fp = fopen(file_name, "r"); hypre_fscanf(fp, "%d", &size); vector = hypre_SeqVectorCreate(size); hypre_SeqVectorInitialize(vector); data = hypre_VectorData(vector); for (j = 0; j < size; j++) { hypre_fscanf(fp, "%le", &data[j]); } fclose(fp); /* multivector code not written yet >>> */ hypre_assert( hypre_VectorNumVectors(vector) == 1 ); return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorPrint( hypre_Vector *vector, char *file_name ) { FILE *fp; HYPRE_Complex *data; HYPRE_Int size, num_vectors, vecstride, idxstride; HYPRE_Int i, j; HYPRE_Complex value; HYPRE_Int ierr = 0; num_vectors = hypre_VectorNumVectors(vector); vecstride = hypre_VectorVectorStride(vector); idxstride = hypre_VectorIndexStride(vector); /*---------------------------------------------------------- * Print in the data *----------------------------------------------------------*/ data = hypre_VectorData(vector); size = hypre_VectorSize(vector); fp = fopen(file_name, "w"); if ( hypre_VectorNumVectors(vector) == 1 ) { hypre_fprintf(fp, "%d\n", size); } else { hypre_fprintf(fp, "%d vectors of size %d\n", num_vectors, size ); } if ( num_vectors>1 ) { for ( j=0; j<num_vectors; ++j ) { hypre_fprintf(fp, "vector %d\n", j ); for (i = 0; i < size; i++) { value = data[ j*vecstride + i*idxstride ]; #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(value), hypre_cimag(value)); #else hypre_fprintf(fp, "%.14e\n", value); #endif } } } else { for (i = 0; i < size; i++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(data[i]), hypre_cimag(data[i])); #else hypre_fprintf(fp, "%.14e\n", data[i]); #endif } } fclose(fp); return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetConstantValues( hypre_Vector *v, HYPRE_Complex value ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *vector_data = hypre_VectorData(v); HYPRE_Int size = hypre_VectorSize(v); HYPRE_Int i; HYPRE_Int ierr = 0; size *=hypre_VectorNumVectors(v); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) vector_data[i] = value; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetRandomValues * * returns vector of values randomly distributed between -1.0 and +1.0 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetRandomValues( hypre_Vector *v, HYPRE_Int seed ) { HYPRE_Complex *vector_data = hypre_VectorData(v); HYPRE_Int size = hypre_VectorSize(v); HYPRE_Int i; HYPRE_Int ierr = 0; hypre_SeedRand(seed); size *=hypre_VectorNumVectors(v); /* RDF: threading this loop may cause problems because of hypre_Rand() */ for (i = 0; i < size; i++) vector_data[i] = 2.0 * hypre_Rand() - 1.0; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCopy * copies data from x to y * if size of x is larger than y only the first size_y elements of x are * copied to y *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorCopy( hypre_Vector *x, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int size_y = hypre_VectorSize(y); HYPRE_Int i; HYPRE_Int ierr = 0; if (size > size_y) size = size_y; size *=hypre_VectorNumVectors(x); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) y_data[i] = x_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneDeep * Returns a complete copy of x - a deep copy, with its own copy of the data. *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCloneDeep( hypre_Vector *x ) { HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); hypre_Vector * y = hypre_SeqMultiVectorCreate( size, num_vectors ); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_SeqVectorInitialize(y); hypre_SeqVectorCopy( x, y ); return y; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneShallow * Returns a complete copy of x - a shallow copy, pointing the data of x *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCloneShallow( hypre_Vector *x ) { HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); hypre_Vector * y = hypre_SeqMultiVectorCreate( size, num_vectors ); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_VectorData(y) = hypre_VectorData(x); hypre_SeqVectorSetDataOwner( y, 0 ); hypre_SeqVectorInitialize(y); return y; } /*-------------------------------------------------------------------------- * hypre_SeqVectorScale *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorScale( HYPRE_Complex alpha, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(y); HYPRE_Int i; HYPRE_Int ierr = 0; size *=hypre_VectorNumVectors(y); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) y_data[i] *= alpha; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorAxpy( HYPRE_Complex alpha, hypre_Vector *x, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int i; HYPRE_Int ierr = 0; size *=hypre_VectorNumVectors(x); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) y_data[i] += alpha * x_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Real hypre_SeqVectorInnerProd( hypre_Vector *x, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int i; HYPRE_Real result = 0.0; size *=hypre_VectorNumVectors(x); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) reduction(+:result) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) result += hypre_conj(y_data[i]) * x_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return result; } /*-------------------------------------------------------------------------- * hypre_VectorSumElts: * Returns the sum of all vector elements. *--------------------------------------------------------------------------*/ HYPRE_Complex hypre_VectorSumElts( hypre_Vector *vector ) { HYPRE_Complex sum = 0; HYPRE_Complex *data = hypre_VectorData( vector ); HYPRE_Int size = hypre_VectorSize( vector ); HYPRE_Int i; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) reduction(+:sum) HYPRE_SMP_SCHEDULE #endif for ( i=0; i<size; ++i ) sum += data[i]; return sum; }
14,362
26.88932
82
c