repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/abstractMain.h
/** AbstractMain holds common functionality for main classes -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 24, 2011 * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_ABSTRACT_MAIN_H_ #define DES_ABSTRACT_MAIN_H_ #include <iostream> #include <string> #include <vector> #include <map> #include <utility> #include <cstdio> #include "Galois/Statistic.h" #include "Galois/Graph/Graph.h" #include "Galois/Graph/LCGraph.h" #include "Galois/Galois.h" #include "Galois/Runtime/Sampling.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include "comDefs.h" #include "BaseSimObject.h" #include "Event.h" #include "SimInit.h" #include "SimGate.h" #include "Input.h" #include "Output.h" namespace des { namespace cll = llvm::cl; static const char* name = "Discrete Event Simulation"; static const char* desc = "Perform logic circuit simulation using Discrete Event Simulation"; static const char* url = "discrete_event_simulation"; static cll::opt<std::string> netlistFile(cll::Positional, cll::desc("<input file>"), cll::Required); /** * The Class AbstractMain holds common functionality for {@link des_unord::DESunorderedSerial} and {@link des_unord::DESunordered}. */ // TODO: graph type can also be exposed to sub-classes as a template parameter template <typename SimInit_tp> class AbstractMain { public: typedef Galois::Graph::FirstGraph<typename SimInit_tp::BaseSimObj_ty*, void, true> Graph; typedef typename Graph::GraphNode GNode; protected: static const unsigned CHUNK_SIZE = 8; static const unsigned DEFAULT_EPI = 32; /** * Gets the version. * * @return the version */ virtual std::string getVersion() const = 0; /** * Run loop. * * @throws Exception the exception */ virtual void runLoop(const SimInit_tp& simInit, Graph& graph) = 0; virtual void initRemaining (const SimInit_tp& simInit, Graph& graph) = 0; public: /** * Run the simulation * @param argc * @param argv */ void run(int argc, char* argv[]) { Galois::StatManager sm; LonestarStart(argc, argv, name, desc, url); SimInit_tp simInit(netlistFile); Graph graph; simInit.initialize (graph); // Graph graph; // graph.copyFromGraph (in_graph); printf("circuit graph: %d nodes, %zd edges\n", graph.size(), simInit.getNumEdges()); printf("Number of initial events = %zd\n", simInit.getInitEvents().size()); initRemaining (simInit, graph); Galois::StatTimer t; t.start (); Galois::Runtime::beginSampling (); runLoop(simInit, graph); Galois::Runtime::endSampling (); t.stop (); if (!skipVerify) { simInit.verify (); } } }; } // namespace des #endif // DES_ABSTRACT_MAIN_H_
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/BaseSimObject.h
/** Base SimObject-*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_BASE_SIM_OBJECT_H #define DES_BASE_SIM_OBJECT_H #include "Galois/Graph/Graph.h" #include <iostream> #include <sstream> namespace des { template <typename Event_tp> class BaseSimObject { protected: size_t id; size_t eventIDcntr; public: typedef Event_tp Event_ty; BaseSimObject (size_t id): id (id), eventIDcntr (0) {} virtual ~BaseSimObject () {} size_t getID () const { return id; } virtual std::string str () const { std::ostringstream ss; ss << "SimObject-" << id; return ss.str (); } virtual BaseSimObject* clone () const = 0; Event_ty makeEvent ( BaseSimObject* recvObj, const typename Event_ty::Action_ty& action, const typename Event_ty::Type& type, const des::SimTime& sendTime, des::SimTime delay=des::MIN_DELAY) { if (delay < des::MIN_DELAY) { delay = des::MIN_DELAY; } des::SimTime recvTime = sendTime + delay; assert (recvTime > sendTime); assert (recvTime < 2*des::INFINITY_SIM_TIME); return Event_ty ((eventIDcntr++), this, recvObj, action, type, sendTime, recvTime); } Event_ty makeZeroEvent () { return Event_ty ((eventIDcntr++), this, this, typename Event_ty::Action_ty (), Event_ty::NULL_EVENT, 0, 0); } protected: struct SendWrapper { virtual void send (BaseSimObject* dstObj, const Event_ty& event) = 0; virtual ~SendWrapper () {} }; struct BaseOutDegIter: public std::iterator<std::forward_iterator_tag, BaseSimObject*> { typedef std::iterator<std::forward_iterator_tag, BaseSimObject*> Super_ty; BaseOutDegIter () {}; virtual typename Super_ty::reference operator * () = 0; virtual typename Super_ty::pointer operator -> () = 0; virtual BaseOutDegIter& operator ++ () = 0; // since BaseOutDegIter is virtual, can't return copy of BaseOutDegIter here virtual void operator ++ (int) = 0; virtual bool is_equal (const BaseOutDegIter& that) const = 0; friend bool operator == (const BaseOutDegIter& left, const BaseOutDegIter& right) { return left.is_equal (right); } friend bool operator != (const BaseOutDegIter& left, const BaseOutDegIter& right) { return !left.is_equal (right); } }; template <typename G> struct OutDegIterator: public BaseOutDegIter { typedef BaseOutDegIter Base; typedef typename G::edge_iterator GI; G& graph; GI edgeIter; OutDegIterator (G& _graph, GI _edgeIter): BaseOutDegIter (), graph (_graph), edgeIter (_edgeIter) {} virtual typename Base::reference operator * () { return graph.getData (graph.getEdgeDst (edgeIter), Galois::MethodFlag::NONE); } virtual typename Base::pointer operator-> () { return &(operator * ()); } virtual OutDegIterator<G>& operator ++ () { ++edgeIter; return *this; } virtual void operator ++ (int) { operator ++ (); } virtual bool is_equal (const BaseOutDegIter& t) const { assert (dynamic_cast<const OutDegIterator<G>*> (&t) != NULL); const OutDegIterator<G>& that = static_cast<const OutDegIterator<G>&> (t); assert (&that != NULL); assert (&(this->graph) == &(that.graph)); return (this->edgeIter == that.edgeIter); } }; template <typename G> OutDegIterator<G> make_begin (G& graph, typename G::GraphNode& node) const { assert (graph.getData (node, Galois::MethodFlag::NONE) == this); return OutDegIterator<G> (graph, graph.edge_begin (node, Galois::MethodFlag::NONE)); } template <typename G> OutDegIterator<G> make_end (G& graph, typename G::GraphNode& node) const { assert (graph.getData (node, Galois::MethodFlag::NONE) == this); return OutDegIterator<G> (graph, graph.edge_end (node, Galois::MethodFlag::NONE)); } virtual void execEventIntern (const Event_ty& event, SendWrapper& sendWrap, BaseOutDegIter& b, BaseOutDegIter& e) = 0; virtual size_t getInputIndex (const Event_ty& event) const = 0; }; } // end namespace #endif // DES_BASE_SIM_OBJECT_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESordered.cpp
/** main function for DESordered -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "DESordered.h" int main (int argc, char* argv[]) { des_ord::DESordered s; s.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESorderedSerial.h
/** DES serial ordered version -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_ORDERED_SERIAL_H #define DES_ORDERED_SERIAL_H #include <deque> #include <functional> #include <queue> #include <set> #include <cassert> #include "Galois/Runtime/ll/CompilerSpecific.h" #include "abstractMain.h" #include "SimInit.h" #include "TypeHelper.h" namespace des_ord { class DESorderedSerial: public des::AbstractMain<TypeHelper::SimInit_ty>, public TypeHelper { typedef std::priority_queue<Event_ty, std::vector<Event_ty>, des::EventRecvTimeLocalTieBrkCmp<Event_ty>::RevCmp> MinHeap; typedef std::set<Event_ty, des::EventRecvTimeLocalTieBrkCmp<Event_ty> > OrdSet; std::vector<GNode> nodes; protected: virtual std::string getVersion () const { return "Ordered serial"; } virtual void initRemaining (const SimInit_ty& simInit, Graph& graph) { nodes.clear (); nodes.resize (graph.size ()); for (Graph::iterator n = graph.begin () , endn = graph.end (); n != endn; ++n) { BaseSimObj_ty* so = graph.getData (*n, Galois::MethodFlag::NONE); nodes[so->getID ()] = *n; } } GALOIS_ATTRIBUTE_PROF_NOINLINE static Event_ty removeMin (MinHeap& pq) { Event_ty ret = pq.top (); pq.pop (); return ret; } GALOIS_ATTRIBUTE_PROF_NOINLINE static Event_ty removeMin (OrdSet& pq) { Event_ty ret = *pq.begin (); pq.erase (pq.begin ()); return ret; } GALOIS_ATTRIBUTE_PROF_NOINLINE static void add (MinHeap& pq, const Event_ty& event) { pq.push (event); } GALOIS_ATTRIBUTE_PROF_NOINLINE static void add (OrdSet& pq, const Event_ty& event) { pq.insert (event); } virtual void runLoop (const SimInit_ty& simInit, Graph& graph) { // MinHeap pq; OrdSet pq; for (std::vector<Event_ty>::const_iterator i = simInit.getInitEvents ().begin () , endi = simInit.getInitEvents ().end (); i != endi; ++i) { add (pq, *i); } std::vector<Event_ty> newEvents; size_t numEvents = 0;; while (!pq.empty ()) { ++numEvents; newEvents.clear (); Event_ty event = removeMin (pq); SimObj_ty* recvObj = static_cast<SimObj_ty*> (event.getRecvObj ()); GNode recvNode = nodes[recvObj->getID ()]; recvObj->execEvent (event, graph, recvNode, newEvents); for (std::vector<Event_ty>::const_iterator a = newEvents.begin () , enda = newEvents.end (); a != enda; ++a) { add (pq, *a); } } std::cout << "Number of events processed = " << numEvents << std::endl; } }; } // namespace des_ord #endif // DES_ORDERED_SERIAL_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESorderedSerial.cpp
/** main function for DESorderedSerial -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "DESorderedSerial.h" int main (int argc, char* argv[]) { des_ord::DESorderedSerial s; s.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESorderedHand.cpp
/** main function for DESorderedHand -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "DESorderedHand.h" int main (int argc, char* argv[]) { des_ord::DESorderedHand s; s.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESorderedHand.h
/** DES ordered version -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_ORDERED_EXP_H #define DES_ORDERED_EXP_H #include "Galois/Accumulator.h" #include "Galois/Timer.h" #include "Galois/Runtime/PerThreadWorkList.h" #include "Galois/Runtime/ll/PaddedLock.h" #include "Galois/Runtime/ll/CompilerSpecific.h" #include <deque> #include <functional> #include <queue> #include <set> #include <cassert> #include "abstractMain.h" #include "SimInit.h" #include "TypeHelper.h" namespace des_ord { typedef Galois::GAccumulator<size_t> Accumulator_ty; typedef des::EventRecvTimeLocalTieBrkCmp<TypeHelper::Event_ty> Cmp_ty; typedef Galois::Runtime::PerThreadVector<TypeHelper::Event_ty> AddList_ty; struct SimObjInfo: public TypeHelper { typedef Galois::Runtime::LL::SimpleLock<true> Lock_ty; typedef des::AbstractMain<SimInit_ty>::GNode GNode; typedef std::set<Event_ty, Cmp_ty , Galois::Runtime::MM::FSBGaloisAllocator<Event_ty> > PQ; Lock_ty mutex; PQ pendingEvents; GNode node; size_t numInputs; size_t numOutputs; std::vector<des::SimTime> inputTimes; SimObjInfo () {} SimObjInfo (const GNode& node, SimObj_ty* sobj): node (node) { SimGate_ty* sg = static_cast<SimGate_ty*> (sobj); assert (sg != NULL); numInputs = sg->getImpl ().getNumInputs (); numOutputs = sg->getImpl ().getNumOutputs (); inputTimes.resize (numInputs, des::SimTime ()); } void recv (const Event_ty& event) { SimGate_ty* dstGate = static_cast<SimGate_ty*> (event.getRecvObj ()); assert (dstGate != NULL); const std::string& outNet = event.getAction ().getNetName (); size_t dstIn = dstGate->getImpl ().getInputIndex (outNet); // get the input index of the net to which my output is connected assert (dstIn < inputTimes.size ()); inputTimes[dstIn] = event.getRecvTime (); mutex.lock (); pendingEvents.insert (event); mutex.unlock (); } bool hasPending () const { mutex.lock (); bool ret = !pendingEvents.empty (); mutex.unlock (); return ret; } bool hasReady () const { mutex.lock (); bool ret = false; if (!pendingEvents.empty ()) { ret = isReady (*pendingEvents.begin ()); } mutex.unlock (); return ret; } Event_ty getMin () const { mutex.lock (); Event_ty ret = *pendingEvents.begin (); mutex.unlock (); return ret; } bool isMin (const Event_ty& event) const { mutex.lock (); bool ret = !pendingEvents.empty () && (*pendingEvents.begin () == event); mutex.unlock (); return ret; } Event_ty removeMin () { mutex.lock (); assert (!pendingEvents.empty ()); Event_ty event = *pendingEvents.begin (); pendingEvents.erase (pendingEvents.begin ()); mutex.unlock (); return event; } void remove (const Event_ty& event) { mutex.lock (); assert (pendingEvents.find (event) != pendingEvents.end ()); pendingEvents.erase (event); mutex.unlock (); } bool isReady (const Event_ty& event) const { // not ready if event has a timestamp greater than the latest event received // on any input. // an input with INFINITY_SIM_TIME is dead and will not receive more non-null events // in the future bool notReady = false; for (std::vector<des::SimTime>::const_iterator i = inputTimes.begin () , endi = inputTimes.end (); i != endi; ++i) { if ((*i < des::INFINITY_SIM_TIME) && (event.getRecvTime () > *i)) { notReady = true; break; } } return !notReady; } }; std::vector<SimObjInfo>::iterator getGlobalMin (std::vector<SimObjInfo>& sobjInfoVec) { std::vector<SimObjInfo>::iterator minPos = sobjInfoVec.end (); for (std::vector<SimObjInfo>::iterator i = sobjInfoVec.begin () , endi = sobjInfoVec.end (); i != endi; ++i) { if (i->hasPending ()) { if (minPos == sobjInfoVec.end ()) { minPos = i; } else if (Cmp_ty::compare (i->getMin (), minPos->getMin ()) < 0) { minPos = i; } } } return minPos; } class DESorderedHand: public des::AbstractMain<TypeHelper::SimInit_ty>, public TypeHelper { typedef Galois::Runtime::PerThreadVector<Event_ty> WL_ty; struct FindReady { WL_ty& readyEvents; Accumulator_ty& findIter; FindReady ( WL_ty& readyEvents, Accumulator_ty& findIter) : readyEvents (readyEvents), findIter (findIter) {} GALOIS_ATTRIBUTE_PROF_NOINLINE void operator () (SimObjInfo& sinfo) { findIter += 1; if (sinfo.hasReady ()) { readyEvents.get ().push_back (sinfo.removeMin ()); } } }; struct ProcessEvents { Graph& graph; std::vector<SimObjInfo>& sobjInfoVec; AddList_ty& newEvents; Accumulator_ty& nevents; ProcessEvents ( Graph& graph, std::vector<SimObjInfo>& sobjInfoVec, AddList_ty& newEvents, Accumulator_ty& nevents) : graph (graph), sobjInfoVec (sobjInfoVec), newEvents (newEvents), nevents (nevents) {} GALOIS_ATTRIBUTE_PROF_NOINLINE void operator () (const Event_ty& event) { nevents += 1; newEvents.get ().clear (); SimObj_ty* recvObj = static_cast<SimObj_ty*> (event.getRecvObj ()); GNode recvNode = sobjInfoVec[recvObj->getID ()].node; recvObj->execEvent (event, graph, recvNode, newEvents.get ()); for (AddList_ty::local_iterator a = newEvents.get ().begin () , enda = newEvents.get ().end (); a != enda; ++a) { sobjInfoVec[a->getRecvObj ()->getID ()].recv (*a); } } }; std::vector<SimObjInfo> sobjInfoVec; protected: virtual std::string getVersion () const { return "Handwritten Ordered ODG based"; } virtual void initRemaining (const SimInit_ty& simInit, Graph& graph) { sobjInfoVec.clear (); sobjInfoVec.resize (graph.size ()); for (Graph::iterator n = graph.begin () , endn = graph.end (); n != endn; ++n) { SimObj_ty* so = static_cast<SimObj_ty*> (graph.getData (*n, Galois::MethodFlag::NONE)); sobjInfoVec[so->getID ()] = SimObjInfo (*n, so); } } virtual void runLoop (const SimInit_ty& simInit, Graph& graph) { for (std::vector<Event_ty>::const_iterator i = simInit.getInitEvents ().begin () , endi = simInit.getInitEvents ().end (); i != endi; ++i) { SimObj_ty* recvObj = static_cast<SimObj_ty*> (i->getRecvObj ()); sobjInfoVec[recvObj->getID ()].recv (*i); } WL_ty readyEvents; AddList_ty newEvents; Accumulator_ty findIter; Accumulator_ty nevents; size_t round = 0; size_t gmin_calls = 0; Galois::TimeAccumulator t_find; Galois::TimeAccumulator t_gmin; Galois::TimeAccumulator t_simulate; while (true) { ++round; readyEvents.clear_all (); assert (readyEvents.empty_all ()); t_find.start (); Galois::do_all ( // Galois::Runtime::do_all_coupled ( sobjInfoVec.begin (), sobjInfoVec.end (), FindReady (readyEvents, findIter), Galois::loopname("find_ready_events")); t_find.stop (); // std::cout << "Number of ready events found: " << readyEvents.size_all () << std::endl; if (readyEvents.empty_all ()) { t_gmin.start (); ++gmin_calls; std::vector<SimObjInfo>::iterator minPos = getGlobalMin (sobjInfoVec); if (minPos == sobjInfoVec.end ()) { break; } else { readyEvents.get ().push_back (minPos->removeMin ()); } t_gmin.stop (); } t_simulate.start (); Galois::do_all ( // Galois::Runtime::do_all_coupled ( readyEvents.begin_all (), readyEvents.end_all (), ProcessEvents (graph, sobjInfoVec, newEvents, nevents), Galois::loopname("process_ready_events")); t_simulate.stop (); } std::cout << "Number of rounds = " << round << std::endl; std::cout << "Number of iterations spent in finding ready events = " << findIter.reduce () << std::endl; std::cout << "Number of events processed = " << nevents.reduce () << std::endl; std::cout << "Average parallelism: " << double (nevents.reduce ())/ double (round) << std::endl; std::cout << "Number of times global min computed = " << gmin_calls << std::endl; std::cout << "Time spent in finding ready events = " << t_find.get () << std::endl; std::cout << "Time spent in computing global min = " << t_gmin.get () << std::endl; std::cout << "Time spent in simulating events = " << t_simulate.get () << std::endl; } }; class DESorderedHandNB: public des::AbstractMain<TypeHelper::SimInit_ty>, public TypeHelper { struct OpFuncEagerAdd { Graph& graph; std::vector<SimObjInfo>& sobjInfoVec; AddList_ty& newEvents; Accumulator_ty& niter; Accumulator_ty& nevents; OpFuncEagerAdd ( Graph& graph, std::vector<SimObjInfo>& sobjInfoVec, AddList_ty& newEvents, Accumulator_ty& niter, Accumulator_ty& nevents) : graph (graph), sobjInfoVec (sobjInfoVec), newEvents (newEvents), niter (niter), nevents (nevents) {} template <typename C> void operator () (const Event_ty& event, C& lwl) { niter += 1; SimObj_ty* recvObj = static_cast<SimObj_ty*> (event.getRecvObj ()); SimObjInfo& recvInfo = sobjInfoVec[recvObj->getID ()]; graph.getData (recvInfo.node, Galois::MethodFlag::CHECK_CONFLICT); if (recvInfo.isReady (event) && recvInfo.isMin (event)) { nevents += 1; newEvents.get ().clear (); GNode& recvNode = sobjInfoVec[recvObj->getID ()].node; recvObj->execEvent (event, graph, recvNode, newEvents.get ()); for (AddList_ty::local_iterator a = newEvents.get ().begin () , enda = newEvents.get ().end (); a != enda; ++a) { SimObjInfo& sinfo = sobjInfoVec[a->getRecvObj ()->getID ()]; sinfo.recv (*a); // if (sinfo.getMin () == *a) { // lwl.push (*a); // } lwl.push (sinfo.getMin ()); } assert (recvInfo.isReady (event)); recvInfo.remove (event); if (recvInfo.hasReady ()) { lwl.push (recvInfo.getMin ()); } } } }; std::vector<SimObjInfo> sobjInfoVec; protected: virtual std::string getVersion () const { return "Handwritten Ordered ODG, no barrier"; } virtual void initRemaining (const SimInit_ty& simInit, Graph& graph) { sobjInfoVec.clear (); sobjInfoVec.resize (graph.size ()); for (Graph::iterator n = graph.begin () , endn = graph.end (); n != endn; ++n) { SimObj_ty* so = static_cast<SimObj_ty*> (graph.getData (*n, Galois::MethodFlag::NONE)); sobjInfoVec[so->getID ()] = SimObjInfo (*n, so); } } virtual void runLoop (const SimInit_ty& simInit, Graph& graph) { std::vector<Event_ty> initWL; for (std::vector<Event_ty>::const_iterator i = simInit.getInitEvents ().begin () , endi = simInit.getInitEvents ().end (); i != endi; ++i) { SimObj_ty* recvObj = static_cast<SimObj_ty*> (i->getRecvObj ()); SimObjInfo& sinfo = sobjInfoVec[recvObj->getID ()]; sinfo.recv (*i); if (sinfo.isMin (*i)) { // for eager add initWL.push_back (*i); } // std::cout << "initial event: " << i->detailedString () << std::endl // << "is_ready: " << sinfo.isReady (*i) << ", is_min: " << (sinfo.getMin () == *i) << std::endl; } AddList_ty newEvents; Accumulator_ty niter; Accumulator_ty nevents; size_t round = 0; while (true) { ++round; typedef Galois::WorkList::dChunkedFIFO<16> WL_ty; Galois::for_each(initWL.begin (), initWL.end (), OpFuncEagerAdd (graph, sobjInfoVec, newEvents, niter, nevents), Galois::wl<WL_ty>()); initWL.clear (); std::vector<SimObjInfo>::iterator minPos = getGlobalMin (sobjInfoVec); if (minPos == sobjInfoVec.end ()) { break; } else { initWL.push_back (minPos->getMin ()); } } std::cout << "Number of rounds = " << round << std::endl; std::cout << "Number of iterations or attempts = " << niter.reduce () << std::endl; std::cout << "Number of events processed= " << nevents.reduce () << std::endl; } }; } // namespace des_ord #endif // DES_ORDERED_EXP_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESordered.h
/** DES ordered version -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_ORDERED_H #define DES_ORDERED_H #include "Galois/Accumulator.h" #include "Galois/Timer.h" #include "Galois/Atomic.h" #include "Galois/Galois.h" #include "Galois/Runtime/PerThreadWorkList.h" #include "Galois/Runtime/ll/PaddedLock.h" #include "Galois/Runtime/ll/CompilerSpecific.h" #include "abstractMain.h" #include "SimInit.h" #include "TypeHelper.h" #include <deque> #include <functional> #include <queue> #include <cassert> namespace des_ord { typedef Galois::GAccumulator<size_t> Accumulator_ty; typedef des::EventRecvTimeLocalTieBrkCmp<TypeHelper::Event_ty> Cmp_ty; typedef Galois::Runtime::PerThreadVector<TypeHelper::Event_ty> AddList_ty; struct SimObjInfo; typedef std::vector<SimObjInfo> VecSobjInfo; struct SimObjInfo: public TypeHelper { typedef des::AbstractMain<SimInit_ty>::GNode GNode; GNode node; size_t numInputs; size_t numOutputs; std::vector<Event_ty> lastInputEvents; mutable volatile des::SimTime clock; SimObjInfo () {} SimObjInfo (GNode node, SimObj_ty* sobj): node (node) { SimGate_ty* sg = static_cast<SimGate_ty*> (sobj); assert (sg != NULL); numInputs = sg->getImpl ().getNumInputs (); numOutputs = sg->getImpl ().getNumOutputs (); lastInputEvents.resize (numInputs, sobj->makeZeroEvent ()); clock = 0; } void recv (const Event_ty& event) { SimGate_ty* dstGate = static_cast<SimGate_ty*> (event.getRecvObj ()); assert (dstGate != NULL); const std::string& outNet = event.getAction ().getNetName (); size_t dstIn = dstGate->getImpl ().getInputIndex (outNet); // get the input index of the net to which my output is connected assert (dstIn < lastInputEvents.size ()); lastInputEvents[dstIn] = event; } bool isReady (const Event_ty& event) const { // not ready if event has a timestamp greater than the latest event received // on any input. // an input with INFINITY_SIM_TIME is dead and will not receive more non-null events // in the future bool notReady = false; if (event.getRecvTime () < clock) { return true; } else { des::SimTime new_clk = 2 * des::INFINITY_SIM_TIME; for (std::vector<Event_ty>::const_iterator e = lastInputEvents.begin () , ende = lastInputEvents.end (); e != ende; ++e) { if ((e->getRecvTime () < des::INFINITY_SIM_TIME) && (Cmp_ty::compare (event, *e) > 0)) { notReady = true; // break; } if (e->getRecvTime () < des::INFINITY_SIM_TIME) { new_clk = std::min (new_clk, e->getRecvTime ()); } } this->clock = new_clk; } return !notReady; } }; class DESordered: public des::AbstractMain<TypeHelper::SimInit_ty>, public TypeHelper { struct NhoodVisitor { typedef int tt_has_fixed_neighborhood; Graph& graph; VecSobjInfo& sobjInfoVec; NhoodVisitor (Graph& graph, VecSobjInfo& sobjInfoVec) : graph (graph), sobjInfoVec (sobjInfoVec) {} template <typename C> void operator () (const Event_ty& event, C&) const { SimObjInfo& recvInfo = sobjInfoVec[event.getRecvObj ()->getID ()]; graph.getData (recvInfo.node, Galois::MethodFlag::CHECK_CONFLICT); } }; struct ReadyTest { VecSobjInfo& sobjInfoVec; ReadyTest (VecSobjInfo& sobjInfoVec): sobjInfoVec (sobjInfoVec) {} bool operator () (const Event_ty& event) const { SimObjInfo& sinfo = sobjInfoVec[event.getRecvObj ()->getID ()]; return sinfo.isReady (event); } }; struct OpFunc { Graph& graph; std::vector<SimObjInfo>& sobjInfoVec; AddList_ty& newEvents; Accumulator_ty& nevents; OpFunc ( Graph& graph, std::vector<SimObjInfo>& sobjInfoVec, AddList_ty& newEvents, Accumulator_ty& nevents) : graph (graph), sobjInfoVec (sobjInfoVec), newEvents (newEvents), nevents (nevents) {} template <typename C> void operator () (const Event_ty& event, C& lwl) { // std::cout << ">>> Processing: " << event.detailedString () << std::endl; // TODO: needs a PQ with remove operation to work correctly assert (ReadyTest (sobjInfoVec) (event)); SimObj_ty* recvObj = static_cast<SimObj_ty*> (event.getRecvObj ()); SimObjInfo& recvInfo = sobjInfoVec[recvObj->getID ()]; nevents += 1; newEvents.get ().clear (); recvObj->execEvent (event, graph, recvInfo.node, newEvents.get ()); for (AddList_ty::local_iterator a = newEvents.get ().begin () , enda = newEvents.get ().end (); a != enda; ++a) { SimObjInfo& sinfo = sobjInfoVec[a->getRecvObj()->getID ()]; sinfo.recv (*a); lwl.push (*a); // std::cout << "### Adding: " << a->detailedString () << std::endl; } } }; std::vector<SimObjInfo> sobjInfoVec; protected: virtual std::string getVersion () const { return "Handwritten Ordered ODG, no barrier"; } virtual void initRemaining (const SimInit_ty& simInit, Graph& graph) { sobjInfoVec.clear (); sobjInfoVec.resize (graph.size ()); for (Graph::iterator n = graph.begin () , endn = graph.end (); n != endn; ++n) { SimObj_ty* so = static_cast<SimObj_ty*> (graph.getData (*n, Galois::MethodFlag::NONE)); sobjInfoVec[so->getID ()] = SimObjInfo (*n, so); } } virtual void runLoop (const SimInit_ty& simInit, Graph& graph) { for (std::vector<Event_ty>::const_iterator e = simInit.getInitEvents ().begin () , ende = simInit.getInitEvents ().end (); e != ende; ++e) { SimObjInfo& sinfo = sobjInfoVec[e->getRecvObj ()->getID ()]; sinfo.recv (*e); } AddList_ty newEvents; Accumulator_ty nevents; Galois::for_each_ordered ( simInit.getInitEvents ().begin (), simInit.getInitEvents ().end (), Cmp_ty (), NhoodVisitor (graph, sobjInfoVec), OpFunc (graph, sobjInfoVec, newEvents, nevents), ReadyTest (sobjInfoVec)); std::cout << "Number of events processed= " << nevents.reduce () << std::endl; } }; } #endif // DES_ORDERED_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESorderedHandNB.cpp
/** main function for DESorderedHand -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "DESorderedHand.h" int main (int argc, char* argv[]) { des_ord::DESorderedHandNB s; s.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESorderedHandSet.cpp
/** main function for DESorderedHandSet -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "DESorderedHandSet.h" int main (int argc, char* argv[]) { des_ord::DESorderedHandSet s; s.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/SimObject.h
/** SimObject for Ordered algorithm -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef ORDERED_SIM_OBJECT_H #define ORDERED_SIM_OBJECT_H #include <sstream> #include <iostream> #include <vector> #include "comDefs.h" #include "BaseSimObject.h" #include "Event.h" namespace des_ord { template <typename Event_tp> class SimObject: public des::BaseSimObject<Event_tp> { typedef des::BaseSimObject<Event_tp> Base; typedef Event_tp Event_ty; template <typename Cont> struct SendAddList: public Base::SendWrapper { Cont& container; SendAddList (Cont& _container): Base::SendWrapper (), container (_container) {} virtual void send (Base* dstObj, const Event_ty& event) { container.push_back (event); } }; public: SimObject (size_t id, unsigned numOutputs, unsigned numInputs) : Base (id) {} template <typename G, typename C> void execEvent ( const Event_ty& event, G& graph, typename G::GraphNode& mynode, C& newEvents) { assert (event.getRecvObj () == this); typename Base::template OutDegIterator<G> beg = this->make_begin (graph, mynode); typename Base::template OutDegIterator<G> end = this->make_end (graph, mynode); SendAddList<C> addListWrap (newEvents); this->execEventIntern (event, addListWrap, beg, end); } }; } // end namespace des_ord #endif // ORDERED_SIM_OBJECT_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/DESorderedHandSet.h
/** DES ordered version -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_ORDERED_HAND_SET_H #define DES_ORDERED_HAND_SET_H #include "Galois/Accumulator.h" #include "Galois/Timer.h" #include "Galois/Atomic.h" #include "Galois/Runtime/PerThreadWorkList.h" #include "Galois/Runtime/ll/PaddedLock.h" #include "Galois/Runtime/ll/CompilerSpecific.h" #include <deque> #include <functional> #include <queue> #include <cassert> #include "abstractMain.h" #include "SimInit.h" #include "TypeHelper.h" namespace des_ord { typedef Galois::GAccumulator<size_t> Accumulator_ty; typedef des::EventRecvTimeLocalTieBrkCmp<TypeHelper::Event_ty> Cmp_ty; typedef Galois::Runtime::PerThreadVector<TypeHelper::Event_ty> AddList_ty; typedef Galois::GAtomicPadded<bool> AtomicBool_ty; static const bool DEBUG = false; struct SimObjInfo: public TypeHelper { struct MarkedEvent { Event_ty event; // mutable AtomicBool_ty flag; mutable bool flag; explicit MarkedEvent (const Event_ty& _event) : event (_event), flag (false) {} bool isMarked () const { return flag; } bool mark () const { // return flag.cas (false, true); if (flag == false) { flag = true; return true; } else { return false; } } void unmark () { flag = false; } operator const Event_ty& () const { return event; } }; typedef Galois::Runtime::LL::PaddedLock<true> Lock_ty; typedef des::AbstractMain<SimInit_ty>::GNode GNode; typedef std::set<MarkedEvent, Cmp_ty , Galois::Runtime::MM::FSBGaloisAllocator<MarkedEvent> > PQ; // typedef std::priority_queue<MarkedEvent, std::vector<MarkedEvent>, Cmp_ty::RevCmp> PQ; Lock_ty mutex; PQ pendingEvents; GNode node; size_t numInputs; size_t numOutputs; std::vector<Event_ty> lastInputEvents; volatile mutable des::SimTime clock; SimObjInfo () {} SimObjInfo (GNode node, SimObj_ty* sobj): node (node) { SimGate_ty* sg = static_cast<SimGate_ty*> (sobj); assert (sg != NULL); numInputs = sg->getImpl ().getNumInputs (); numOutputs = sg->getImpl ().getNumOutputs (); lastInputEvents.resize (numInputs, sobj->makeZeroEvent ()); clock = 0; } void recv (const Event_ty& event) { SimGate_ty* dstGate = static_cast<SimGate_ty*> (event.getRecvObj ()); assert (dstGate != NULL); const std::string& outNet = event.getAction ().getNetName (); size_t dstIn = dstGate->getImpl ().getInputIndex (outNet); // get the input index of the net to which my output is connected assert (dstIn < lastInputEvents.size ()); assert (Cmp_ty::compare (event, lastInputEvents[dstIn]) >= 0); // event >= last[dstIn] lastInputEvents[dstIn] = event; mutex.lock (); pendingEvents.insert (MarkedEvent(event)); mutex.unlock (); } bool isReady (const Event_ty& event) const { // not ready if event has a timestamp greater than the latest event received // on any input. // an input with INFINITY_SIM_TIME is dead and will not receive more non-null events // in the future bool notReady = false; if (event.getRecvTime () < clock) { return true; } else { des::SimTime new_clk = 2 * des::INFINITY_SIM_TIME; for (std::vector<Event_ty>::const_iterator e = lastInputEvents.begin () , ende = lastInputEvents.end (); e != ende; ++e) { if ((e->getRecvTime () < des::INFINITY_SIM_TIME) && (Cmp_ty::compare (event, *e) > 0)) { notReady = true; // break; } if (e->getRecvTime () < des::INFINITY_SIM_TIME) { new_clk = std::min (new_clk, e->getRecvTime ()); } } this->clock = new_clk; } return !notReady; } bool hasPending () const { mutex.lock (); bool ret = !pendingEvents.empty (); mutex.unlock (); return ret; } MarkedEvent getMin () const { mutex.lock (); MarkedEvent ret = *pendingEvents.begin (); mutex.unlock (); return ret; } bool isMin (const Event_ty& event) const { mutex.lock (); bool ret = false; if (!pendingEvents.empty ()) { ret = (event == *pendingEvents.begin ()); } mutex.unlock (); return ret; } Event_ty removeMin () { mutex.lock (); assert (!pendingEvents.empty ()); Event_ty event = *pendingEvents.begin (); pendingEvents.erase (pendingEvents.begin ()); mutex.unlock (); return event; } bool isSrc (const Event_ty& event) const { return isReady(event) && (event.getRecvTime() < des::INFINITY_SIM_TIME ? isMin (event) : true); } bool canAddMin () const { mutex.lock (); bool ret = !pendingEvents.empty () && !(pendingEvents.begin ()->isMarked ()) && isReady (*pendingEvents.begin ()) && pendingEvents.begin ()->mark (); mutex.unlock (); return ret; } }; std::vector<SimObjInfo>::iterator getGlobalMin (std::vector<SimObjInfo>& sobjInfoVec) { std::vector<SimObjInfo>::iterator minPos = sobjInfoVec.end (); for (std::vector<SimObjInfo>::iterator i = sobjInfoVec.begin () , endi = sobjInfoVec.end (); i != endi; ++i) { if (i->hasPending ()) { if (minPos == endi) { minPos = i; } else if (Cmp_ty::compare (i->getMin (), minPos->getMin ()) < 0) { minPos = i; } } } return minPos; } class DESorderedHandSet: public des::AbstractMain<TypeHelper::SimInit_ty>, public TypeHelper { static const unsigned EPI = 32; struct OpFuncSet { Graph& graph; std::vector<SimObjInfo>& sobjInfoVec; AddList_ty& newEvents; Accumulator_ty& nevents; OpFuncSet ( Graph& graph, std::vector<SimObjInfo>& sobjInfoVec, AddList_ty& newEvents, Accumulator_ty& nevents) : graph (graph), sobjInfoVec (sobjInfoVec), newEvents (newEvents), nevents (nevents) {} template <typename C> void operator () (Event_ty event, C& lwl) { // std::cout << ">>> Processing: " << event.detailedString () << std::endl; unsigned epi = 0; while (epi < EPI) { ++epi; SimObj_ty* recvObj = static_cast<SimObj_ty*> (event.getRecvObj ()); SimObjInfo& srcInfo = sobjInfoVec[recvObj->getID ()]; if (DEBUG && !srcInfo.isSrc (event)) { abort (); } nevents += 1; newEvents.get ().clear (); recvObj->execEvent (event, graph, srcInfo.node, newEvents.get ()); for (AddList_ty::local_iterator a = newEvents.get ().begin () , enda = newEvents.get ().end (); a != enda; ++a) { SimObjInfo& sinfo = sobjInfoVec[a->getRecvObj ()->getID ()]; sinfo.recv (*a); if (sinfo.canAddMin ()) { assert (sinfo.getMin ().isMarked ()); lwl.push (sinfo.getMin ()); // std::cout << "### Adding: " << static_cast<const Event_ty&> (sinfo.getMin ()).detailedString () << std::endl; } } if (DEBUG && !srcInfo.isSrc (event)) { abort (); } srcInfo.removeMin (); if (srcInfo.canAddMin ()) { assert (srcInfo.isSrc (srcInfo.getMin ())); assert (srcInfo.getMin ().isMarked ()); event = srcInfo.getMin (); assert (srcInfo.isSrc (event)); if (epi == EPI) { lwl.push (event); } // lwl.push (srcInfo.getMin ()); // std::cout << "%%% Adding: " << static_cast<const Event_ty&> (srcInfo.getMin ()).detailedString () << std::endl; } else { break; } } // end while SimObjInfo& srcInfo = sobjInfoVec[event.getRecvObj ()->getID ()]; if (srcInfo.canAddMin ()) { assert (srcInfo.getMin ().isMarked ()); lwl.push (srcInfo.getMin ()); } } }; std::vector<SimObjInfo> sobjInfoVec; protected: virtual std::string getVersion () const { return "Handwritten Ordered ODG, no barrier"; } virtual void initRemaining (const SimInit_ty& simInit, Graph& graph) { sobjInfoVec.clear (); sobjInfoVec.resize (graph.size ()); for (Graph::iterator n = graph.begin () , endn = graph.end (); n != endn; ++n) { SimObj_ty* so = static_cast<SimObj_ty*> (graph.getData (*n, Galois::MethodFlag::NONE)); sobjInfoVec[so->getID ()] = SimObjInfo (*n, so); } } virtual void runLoop (const SimInit_ty& simInit, Graph& graph) { std::vector<Event_ty> initWL; for (std::vector<Event_ty>::const_iterator i = simInit.getInitEvents ().begin () , endi = simInit.getInitEvents ().end (); i != endi; ++i) { SimObj_ty* recvObj = static_cast<SimObj_ty*> (i->getRecvObj ()); SimObjInfo& sinfo = sobjInfoVec[recvObj->getID ()]; sinfo.recv (*i); } for (std::vector<Event_ty>::const_iterator i = simInit.getInitEvents ().begin (), endi = simInit.getInitEvents ().end (); i != endi; ++i) { BaseSimObj_ty* recvObj = i->getRecvObj (); SimObjInfo& sinfo = sobjInfoVec[recvObj->getID ()]; if (sinfo.canAddMin ()) { initWL.push_back (sinfo.getMin ()); // std::cout << "Initial source found: " << Event_ty (sinfo.getMin ()).detailedString () << std::endl; } } std::cout << "Number of initial sources: " << initWL.size () << std::endl; AddList_ty newEvents; Accumulator_ty nevents; size_t round = 0; while (true) { ++round; typedef Galois::WorkList::dChunkedFIFO<CHUNK_SIZE> WL_ty; Galois::for_each(initWL.begin (), initWL.end (), OpFuncSet (graph, sobjInfoVec, newEvents, nevents), Galois::wl<WL_ty>()); initWL.clear (); std::vector<SimObjInfo>::iterator p = getGlobalMin (sobjInfoVec); if (p == sobjInfoVec.end ()) { break; } else { initWL.push_back (p->getMin ()); } } std::cout << "Number of rounds = " << round << std::endl; std::cout << "Number of events processed= " << nevents.reduce () << std::endl; } }; } // namespace des_ord #endif // DES_ORDERED_HAND_SET_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/ordered/TypeHelper.h
/** DES ordered type helper -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_ORD_TYPE_HELPER_H #define DES_ORD_TYPE_HELPER_H #include "abstractMain.h" #include "SimInit.h" namespace des_ord { struct TypeHelper { typedef des::Event<des::LogicUpdate> Event_ty; typedef Event_ty::BaseSimObj_ty BaseSimObj_ty; typedef des_ord::SimObject<Event_ty> SimObj_ty; typedef des::SimGate<SimObj_ty> SimGate_ty; typedef des::Input<SimObj_ty> Input_ty; typedef des::Output<SimObj_ty> Output_ty; typedef des::SimInit<SimGate_ty, Input_ty, Output_ty> SimInit_ty; }; } #endif // DES_ORD_TYPE_HELPER_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/betweennesscentrality/CMakeLists.txt
app(betweennesscentrality-outer BetweennessCentralityOuter.cpp) include_directories(../bfs) app(betweennesscentrality-inner BetweennessCentralityInner.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/betweennesscentrality/BetweennessCentralityOuter.cpp
/** Betweenness centrality application -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Dimitrios Prountzos <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Statistic.h" #include "Galois/UserContext.h" #include "Galois/Graph/LCGraph.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include <boost/iterator/filter_iterator.hpp> #include <algorithm> #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <vector> #include <deque> #include <cstdlib> static const char* name = "Betweenness Centrality"; static const char* desc = "Computes the betweenness centrality of all nodes in a graph"; static const char* url = "betweenness_centrality"; static llvm::cl::opt<std::string> filename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::Required); static llvm::cl::opt<int> iterLimit("limit", llvm::cl::desc("Limit number of iterations to value (0 is all nodes)"), llvm::cl::init(0)); static llvm::cl::opt<unsigned int> startNode("startNode", llvm::cl::desc("Node to start search from"), llvm::cl::init(0)); static llvm::cl::opt<bool> forceVerify("forceVerify", llvm::cl::desc("Abort if not verified, only makes sense for torus graphs")); static llvm::cl::opt<bool> printAll("printAll", llvm::cl::desc("Print betweenness values for all nodes")); typedef Galois::Graph::LC_CSR_Graph<void, void>::with_no_lockable<true>::type ::with_numa_alloc<true>::type Graph; typedef Graph::GraphNode GNode; Graph* G; int NumNodes; Galois::Runtime::PerThreadStorage<double*> CB; Galois::Runtime::PerThreadStorage<double*> perThreadSigma; Galois::Runtime::PerThreadStorage<int*> perThreadD; Galois::Runtime::PerThreadStorage<double*> perThreadDelta; Galois::Runtime::PerThreadStorage<Galois::gdeque<GNode>*> perThreadSucc; template<typename T> struct PerIt { typedef typename Galois::PerIterAllocTy::rebind<T>::other Ty; }; struct process { typedef int tt_does_not_need_aborts; //typedef int tt_needs_per_iter_alloc; typedef int tt_does_not_need_push; void operator()(GNode& _req, Galois::UserContext<GNode>& lwl) { Galois::gdeque<GNode> SQ; double* sigma = *perThreadSigma.getLocal(); int* d = *perThreadD.getLocal(); double* delta = *perThreadDelta.getLocal(); Galois::gdeque<GNode>* succ = *perThreadSucc.getLocal(); #if 0 std::deque<double, PerIt<double>::Ty> sigma(NumNodes, 0.0, lwl.getPerIterAlloc()); std::deque<int, PerIt<int>::Ty> d(NumNodes, 0, lwl.getPerIterAlloc()); std::deque<double, PerIt<double>::Ty> delta(NumNodes, 0.0, lwl.getPerIterAlloc()); std::deque<GNdeque, PerIt<GNdeque>::Ty> succ(NumNodes, GNdeque(lwl.getPerIterAlloc()), lwl.getPerIterAlloc()); #endif unsigned int QAt = 0; int req = _req; sigma[req] = 1; d[req] = 1; SQ.push_back(_req); for (auto qq = SQ.begin(), eq = SQ.end(); qq != eq; ++qq) { GNode _v = *qq; int v = _v; for (Graph::edge_iterator ii = G->edge_begin(_v, Galois::MethodFlag::NONE), ee = G->edge_end(_v, Galois::MethodFlag::NONE); ii != ee; ++ii) { GNode _w = G->getEdgeDst(ii); int w = _w; if (!d[w]) { SQ.push_back(_w); d[w] = d[v] + 1; } if (d[w] == d[v] + 1) { sigma[w] = sigma[w] + sigma[v]; succ[v].push_back(w); } } } while (SQ.size() > 1) { int w = SQ.back(); SQ.pop_back(); double sigma_w = sigma[w]; double delta_w = delta[w]; auto& slist = succ[w]; for (auto ii = slist.begin(), ee = slist.end(); ii != ee; ++ii) { //std::cerr << "Processing node " << w << std::endl; GNode v = *ii; delta_w += (sigma_w/sigma[v])*(1.0 + delta[v]); } delta[w] = delta_w; } double* Vec = *CB.getLocal(); for (unsigned int i = 0; i < NumNodes; ++i) { Vec[i] += delta[i]; delta[i] = 0; sigma[i] = 0; d[i] = 0; succ[i].clear(); } } }; // Verification for reference torus graph inputs. // All nodes should have the same betweenness value. void verify() { double sampleBC = 0.0; bool firstTime = true; for (int i=0; i<NumNodes; ++i) { double bc = (*CB.getRemote(0))[i]; for (unsigned int j = 1; j < Galois::getActiveThreads(); ++j) bc += (*CB.getRemote(j))[i]; if (firstTime) { sampleBC = bc; std::cerr << "BC: " << sampleBC << std::endl; firstTime = false; } else { if (!((bc - sampleBC) <= 0.0001)) { std::cerr << "If torus graph, verification failed " << (bc - sampleBC) << "\n"; if (forceVerify) abort(); assert ((bc - sampleBC) <= 0.0001); return; } } } } void printBCcertificate() { std::stringstream foutname; foutname << "outer_certificate_" << numThreads; std::ofstream outf(foutname.str().c_str()); std::cerr << "Writing certificate..." << std::endl; for (int i=0; i<NumNodes; ++i) { double bc = (*CB.getRemote(0))[i]; for (unsigned int j = 1; j < Galois::getActiveThreads(); ++j) bc += (*CB.getRemote(j))[i]; outf << i << ": " << std::setiosflags(std::ios::fixed) << std::setprecision(9) << bc << std::endl; } outf.close(); } struct HasOut: public std::unary_function<GNode,bool> { Graph* graph; HasOut(Graph* g): graph(g) { } bool operator()(const GNode& n) const { return graph->edge_begin(n) != graph->edge_end(n); } }; struct InitializeLocal { template<typename T> void initArray(T** addr) { T* a = new T[NumNodes](); *addr = a; } void operator()(unsigned, unsigned) { initArray(CB.getLocal()); initArray(perThreadSigma.getLocal()); initArray(perThreadD.getLocal()); initArray(perThreadDelta.getLocal()); initArray(perThreadSucc.getLocal()); } }; struct DeleteLocal { template<typename T> void deleteArray(T** addr) { delete [] *addr; } void operator()(unsigned, unsigned) { deleteArray(CB.getLocal()); deleteArray(perThreadSigma.getLocal()); deleteArray(perThreadD.getLocal()); deleteArray(perThreadDelta.getLocal()); deleteArray(perThreadSucc.getLocal()); } }; int main(int argc, char** argv) { Galois::StatManager M; LonestarStart(argc, argv, name, desc, url); Graph g; G = &g; Galois::Graph::readGraph(*G, filename); NumNodes = G->size(); Galois::on_each(InitializeLocal()); Galois::reportPageAlloc("MeminfoPre"); Galois::preAlloc(numThreads * NumNodes / 1650); Galois::reportPageAlloc("MeminfoMid"); boost::filter_iterator<HasOut,Graph::iterator> begin = boost::make_filter_iterator(HasOut(G), g.begin(), g.end()), end = boost::make_filter_iterator(HasOut(G), g.end(), g.end()); boost::filter_iterator<HasOut,Graph::iterator> begin2 = iterLimit ? Galois::safe_advance(begin, end, (int)iterLimit) : end; size_t iterations = std::distance(begin, begin2); std::vector<GNode> v(begin, begin2); std::cout << "NumNodes: " << NumNodes << " Start Node: " << startNode << " Iterations: " << iterations << "\n"; typedef Galois::WorkList::StableIterator< std::vector<GNode>::iterator, true> WLL; Galois::StatTimer T; T.start(); Galois::for_each(v.begin(), v.end(), process(), Galois::wl<WLL>()); T.stop(); if (!skipVerify) { for (int i=0; i<10; ++i) { double bc = (*CB.getRemote(0))[i]; for (unsigned int j = 1; j < Galois::getActiveThreads(); ++j) bc += (*CB.getRemote(j))[i]; std::cout << i << ": " << std::setiosflags(std::ios::fixed) << std::setprecision(6) << bc << "\n"; } } if (printAll) printBCcertificate(); Galois::reportPageAlloc("MeminfoPost"); if (forceVerify || !skipVerify) { verify(); } // XXX(ddn): Could use unique_ptr but not supported on all our platforms :( Galois::on_each(DeleteLocal()); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/betweennesscentrality/BetweennessCentralityInner.cpp
/** Betweenness Centrality -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Betweenness centrality. Implementation based on Ligra * * @author Andrew Lenharth <[email protected]> */ #include "Galois/config.h" #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Timer.h" #include "Galois/Statistic.h" #include "Galois/Graph/LCGraph.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include "Galois/Graph/GraphNodeBag.h" #include "HybridBFS.h" #include GALOIS_CXX11_STD_HEADER(atomic) #include <string> #include <deque> #include <iostream> #include <iomanip> static const char* name = "Betweenness Centrality"; static const char* desc = 0; static const char* url = 0; enum Algo { async, leveled }; namespace cll = llvm::cl; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input graph>"), cll::Required); static cll::opt<std::string> transposeGraphName("graphTranspose", cll::desc("Transpose of input graph")); static cll::opt<bool> symmetricGraph("symmetricGraph", cll::desc("Input graph is symmetric")); static cll::opt<unsigned int> startNode("startNode", cll::desc("Node to start search from"), cll::init(0)); static cll::opt<Algo> algo("algo", cll::desc("Choose an algorithm:"), cll::values( clEnumValN(Algo::async, "async", "Async Algorithm"), clEnumValN(Algo::leveled, "leveled", "Leveled Algorithm"), clEnumValEnd), cll::init(Algo::async)); template<typename Algo> void initialize(Algo& algo, typename Algo::Graph& graph, typename Algo::Graph::GraphNode& source) { algo.readGraph(graph); std::cout << "Read " << graph.size() << " nodes\n"; if (startNode >= graph.size()) { std::cerr << "failed to set source: " << startNode << "\n"; assert(0); abort(); } typename Algo::Graph::iterator it = graph.begin(); std::advance(it, startNode); source = *it; } template<typename Graph> void readInOutGraph(Graph& graph) { using namespace Galois::Graph; if (symmetricGraph) { Galois::Graph::readGraph(graph, filename); } else if (transposeGraphName.size()) { Galois::Graph::readGraph(graph, filename, transposeGraphName); } else { GALOIS_DIE("Graph type not supported"); } } static const int ChunkSize = 128; static const int bfsChunkSize = 32+64; struct AsyncAlgo { struct SNode { float numPaths; float dependencies; int dist; SNode() :numPaths(-std::numeric_limits<float>::max()), dependencies(-std::numeric_limits<float>::max()), dist(std::numeric_limits<int>::max()) { } }; typedef Galois::Graph::LC_CSR_Graph<SNode,void> ::with_no_lockable<true>::type ::with_numa_alloc<true>::type InnerGraph; typedef Galois::Graph::LC_InOut_Graph<InnerGraph> Graph; //typedef Galois::Graph::LC_CSR_Graph<SNode, void> Graph; typedef Graph::GraphNode GNode; std::string name() const { return "async"; } void readGraph(Graph& graph) { readInOutGraph(graph); } struct Initialize { Graph& g; Initialize(Graph& g): g(g) { } void operator()(Graph::GraphNode n) { SNode& data = g.getData(n, Galois::MethodFlag::NONE); data.numPaths = -std::numeric_limits<float>::max(); data.dependencies = -std::numeric_limits<float>::max(); data.dist = std::numeric_limits<int>::max(); } }; struct BFS { typedef int tt_does_not_need_aborts; typedef std::pair<GNode, int> WorkItem; struct Indexer: public std::unary_function<WorkItem,int> { int operator()(const WorkItem& val) const { return val.second; } }; typedef Galois::WorkList::OrderedByIntegerMetric<Indexer,Galois::WorkList::dChunkedFIFO<bfsChunkSize> > OBIM; Graph& g; BFS(Graph& g) :g(g) {} void operator()(WorkItem& item, Galois::UserContext<WorkItem>& ctx) const { GNode n = item.first; int newDist = item.second; if (newDist > g.getData(n).dist + 1) return; for (Graph::edge_iterator ii = g.edge_begin(n, Galois::MethodFlag::NONE), ei = g.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = g.getEdgeDst(ii); SNode& ddata = g.getData(dst, Galois::MethodFlag::NONE); int oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= newDist) break; if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { ctx.push(WorkItem(dst, newDist + 1)); break; } } } } }; struct CountPaths { typedef int tt_does_not_need_aborts; struct Indexer: public std::unary_function<GNode,int> { static Graph* g; int operator()(const GNode& val) const { // //use out edges as that signifies how many people will wait on this node // auto ii = g->edge_begin(val, Galois::MethodFlag::NONE); // auto ee = g->edge_end(val, Galois::MethodFlag::NONE); // bool big = Galois::safe_advance(ii, ee, 10) != ee; // return 2 * g->getData(val, Galois::MethodFlag::NONE).dist + (big ? 0 : 1); return g->getData(val, Galois::MethodFlag::NONE).dist; } }; typedef Galois::WorkList::OrderedByIntegerMetric<Indexer,Galois::WorkList::dChunkedFIFO<ChunkSize> > OBIM; Graph& g; CountPaths(Graph& g) :g(g) { Indexer::g = &g; } void operator()(GNode& n, Galois::UserContext<GNode>& ctx) const { SNode& sdata = g.getData(n, Galois::MethodFlag::NONE); while (sdata.numPaths == -std::numeric_limits<float>::max()) { unsigned long np = 0; bool allready = true; for (Graph::in_edge_iterator ii = g.in_edge_begin(n, Galois::MethodFlag::NONE), ee = g.in_edge_end(n, Galois::MethodFlag::NONE); ii != ee; ++ii) { GNode dst = g.getInEdgeDst(ii); SNode& ddata = g.getData(dst, Galois::MethodFlag::NONE); if (ddata.dist + 1 == sdata.dist) { if (ddata.numPaths != -std::numeric_limits<float>::max()) { np += ddata.numPaths; } else { allready = false; // ctx.push(n); // return; } } } if (allready) sdata.numPaths = np; } } }; struct ComputeDep { typedef int tt_does_not_need_aborts; struct Indexer: public std::unary_function<GNode,int> { static Graph* g; int operator()(const GNode& val) const { // //use in edges as that signifies how many people will wait on this node // auto ii = g->in_edge_begin(val, Galois::MethodFlag::NONE); // auto ee = g->in_edge_end(val, Galois::MethodFlag::NONE); // bool big = Galois::safe_advance(ii, ee, 10) != ee; // return std::numeric_limits<int>::max() - 2 * g->getData(val, Galois::MethodFlag::NONE).dist + (big ? 0 : 1); return std::numeric_limits<int>::max() - g->getData(val, Galois::MethodFlag::NONE).dist; } }; typedef Galois::WorkList::OrderedByIntegerMetric<Indexer,Galois::WorkList::dChunkedFIFO<ChunkSize> > OBIM; Graph& g; ComputeDep(Graph& g) :g(g) { Indexer::g = &g; } void operator()(GNode& n, Galois::UserContext<GNode>& ctx) const { SNode& sdata = g.getData(n, Galois::MethodFlag::NONE); while (sdata.dependencies == -std::numeric_limits<float>::max()) { float newDep = 0.0; bool allready = true; for (Graph::edge_iterator ii = g.edge_begin(n, Galois::MethodFlag::NONE), ei = g.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = g.getEdgeDst(ii); SNode& ddata = g.getData(dst, Galois::MethodFlag::NONE); if (ddata.dist == sdata.dist + 1) { if (ddata.dependencies != -std::numeric_limits<float>::max()) { newDep += ((float)sdata.numPaths / (float)ddata.numPaths) * (1 + ddata.dependencies); } else { allready = false; // ctx.push(n); // return; } } } if (allready) sdata.dependencies = newDep; } } }; void operator()(Graph& graph, GNode source) { Galois::StatTimer Tinit("InitTime"), Tlevel("LevelTime"), Tbfs("BFSTime"), Tcount("CountTime"), Tdep("DepTime"); Tinit.start(); Galois::do_all_local(graph, Initialize(graph), Galois::loopname("INIT")); Tinit.stop(); std::cout << "INIT DONE " << Tinit.get() << "\n"; Tbfs.start(); graph.getData(source).dist = 0; //Galois::for_each(BFS::WorkItem(source, 1), BFS(graph), Galois::loopname("BFS"), Galois::wl<BFS::OBIM>()); HybridBFS<SNode, int> H; H(graph,source); Tbfs.stop(); std::cout << "BFS DONE " << Tbfs.get() << "\n"; Tcount.start(); graph.getData(source).numPaths = 1; Galois::for_each_local(graph, CountPaths(graph), Galois::loopname("COUNT"), Galois::wl<CountPaths::OBIM>()); Tcount.stop(); std::cout << "COUNT DONE " << Tcount.get() << "\n"; Tdep.start(); graph.getData(source).dependencies = 0.0; Galois::for_each(graph.begin(), graph.end(), ComputeDep(graph), Galois::loopname("DEP"), Galois::wl<ComputeDep::OBIM>()); Tdep.stop(); std::cout << "DEP DONE " << Tdep.get() << "\n"; } }; AsyncAlgo::Graph* AsyncAlgo::CountPaths::Indexer::g; AsyncAlgo::Graph* AsyncAlgo::ComputeDep::Indexer::g; struct LeveledAlgo { struct SNode { std::atomic<unsigned long> numPaths; float dependencies; std::atomic<int> dist; SNode() :numPaths(~0UL), dependencies(-std::numeric_limits<float>::max()), dist(std::numeric_limits<int>::max()) { } }; typedef Galois::Graph::LC_CSR_Graph<SNode,void> ::with_no_lockable<true>::type ::with_numa_alloc<true>::type InnerGraph; typedef Galois::Graph::LC_InOut_Graph<InnerGraph> Graph; //typedef Galois::Graph::LC_CSR_Graph<SNode, void> Graph; typedef Graph::GraphNode GNode; typedef Galois::InsertBag<GNode> Bag; std::string name() const { return "Leveled"; } void readGraph(Graph& graph) { readInOutGraph(graph); } struct Initialize { Graph& g; Initialize(Graph& g): g(g) { } void operator()(Graph::GraphNode n) { SNode& data = g.getData(n, Galois::MethodFlag::NONE); data.numPaths = 0; data.dependencies = 0.0; //std::numeric_limits<float>::lowest(); data.dist = std::numeric_limits<int>::max(); } }; //push based template<bool doCount = true> struct BFS { typedef int tt_does_not_need_aborts; Graph& g; Bag& b; BFS(Graph& g, Bag& b) :g(g), b(b) {} void operator()(GNode& n) const { auto& sdata = g.getData(n, Galois::MethodFlag::NONE); for (Graph::edge_iterator ii = g.edge_begin(n, Galois::MethodFlag::NONE), ei = g.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = g.getEdgeDst(ii); SNode& ddata = g.getData(dst, Galois::MethodFlag::NONE); if (ddata.dist.load(std::memory_order_relaxed) == std::numeric_limits<int>::max()) { if (std::numeric_limits<int>::max() == ddata.dist.exchange(sdata.dist + 1)) b.push_back(dst); if (doCount) ddata.numPaths = ddata.numPaths + sdata.numPaths; } else if (ddata.dist == sdata.dist + 1) { if (doCount) ddata.numPaths = ddata.numPaths + sdata.numPaths; } } // for (Graph::in_edge_iterator ii = g.in_edge_begin(n, Galois::MethodFlag::NONE), // ee = g.in_edge_end(n, Galois::MethodFlag::NONE); ii != ee; ++ii) { // GNode dst = g.getInEdgeDst(ii); // SNode& ddata = g.getData(dst, Galois::MethodFlag::NONE); // if (ddata.dist + 1 == sdata.dist) // sdata.numPaths += ddata.numPaths; // } } }; //pull based struct Counter { typedef int tt_does_not_need_aborts; Graph& g; Counter(Graph& g) :g(g) {} void operator()(GNode& n) const { auto& sdata = g.getData(n, Galois::MethodFlag::NONE); unsigned long np = 0; for (Graph::in_edge_iterator ii = g.in_edge_begin(n, Galois::MethodFlag::NONE), ee = g.in_edge_end(n, Galois::MethodFlag::NONE); ii != ee; ++ii) { GNode dst = g.getInEdgeDst(ii); SNode& ddata = g.getData(dst, Galois::MethodFlag::NONE); if (ddata.dist + 1 == sdata.dist) np += ddata.numPaths; } sdata.numPaths = sdata.numPaths + np; } }; //pull based struct ComputeDep { Graph& g; ComputeDep(Graph& g) :g(g) {} void operator()(GNode& n) const { SNode& sdata = g.getData(n, Galois::MethodFlag::NONE); for (Graph::edge_iterator ii = g.edge_begin(n, Galois::MethodFlag::NONE), ei = g.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = g.getEdgeDst(ii); SNode& ddata = g.getData(dst, Galois::MethodFlag::NONE); if (ddata.dist == sdata.dist + 1) sdata.dependencies += ((float)sdata.numPaths / (float)ddata.numPaths) * (1 + ddata.dependencies); } } }; void operator()(Graph& graph, GNode source) { Galois::StatTimer Tinit("InitTime"), Tlevel("LevelTime"), Tbfs("BFSTime"), Tcount("CountTime"), Tdep("DepTime"); Tinit.start(); Galois::do_all_local(graph, Initialize(graph), Galois::loopname("INIT")); Tinit.stop(); std::cout << "INIT DONE " << Tinit.get() << "\n"; Tbfs.start(); std::deque<Bag*> levels; levels.push_back(new Bag()); levels[0]->push_back(source); graph.getData(source).dist = 0; graph.getData(source).numPaths = 1; while (!levels.back()->empty()) { Bag* b = levels.back(); levels.push_back(new Bag()); Galois::do_all_local(*b, BFS<>(graph, *levels.back()), Galois::loopname("BFS"), Galois::do_all_steal(true)); //Galois::do_all_local(*levels.back(), Counter(graph), "COUNTER", true); } delete levels.back(); levels.pop_back(); Tbfs.stop(); std::cout << "BFS DONE " << Tbfs.get() << " with " << levels.size() << " levels\n"; Tdep.start(); for (int i = levels.size() - 1; i > 0; --i) Galois::do_all_local(*levels[i-1], ComputeDep(graph), Galois::loopname("DEPS"), Galois::do_all_steal(true)); Tdep.stop(); std::cout << "DEP DONE " << Tdep.get() << "\n"; while (!levels.empty()) { delete levels.back(); levels.pop_back(); } } }; template<typename Algo> void run() { typedef typename Algo::Graph Graph; typedef typename Graph::GraphNode GNode; Algo algo; Graph graph; GNode source; initialize(algo, graph, source); Galois::reportPageAlloc("MeminfoPre"); Galois::preAlloc(numThreads + (3*graph.size() * sizeof(typename Graph::node_data_type)) / Galois::Runtime::MM::pageSize); Galois::reportPageAlloc("MeminfoMid"); Galois::StatTimer T; std::cout << "Running " << algo.name() << " version\n"; T.start(); algo(graph, source); T.stop(); Galois::reportPageAlloc("MeminfoPost"); if (!skipVerify) { int count = 0; for (typename Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei && count < 20; ++ii, ++count) { std::cout << count << ": " << std::setiosflags(std::ios::fixed) << std::setprecision(6) << graph.getData(*ii).dependencies << " " << graph.getData(*ii).numPaths << " " << graph.getData(*ii).dist << "\n"; } count = 0; // for (typename Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii, ++count) // std::cout << ((count % 128 == 0) ? "\n" : " ") << graph.getData(*ii).numPaths; std::cout << "\n"; } } int main(int argc, char **argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); Galois::StatTimer T("TotalTime"); T.start(); switch (algo) { case Algo::async: run<AsyncAlgo>(); break; case Algo::leveled: run<LeveledAlgo>(); break; } T.stop(); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/bfs/CMakeLists.txt
if(USE_EXP) include_directories(../../exp/apps/bfs .) endif() app(bfs bfs.cpp) if(NOT CMAKE_CXX_COMPILER_ID MATCHES "XL") app(diameter Diameter.cpp) endif()
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/bfs/HybridBFS.h
#ifndef APPS_BFS_HYBRIDBFS_H #define APPS_BFS_HYBRIDBFS_H #include "Galois/Galois.h" #include "Galois/Graph/LCGraph.h" template<typename NodeData,typename Dist> struct HybridBFS { typedef typename Galois::Graph::LC_CSR_Graph<NodeData,void> ::template with_no_lockable<true>::type ::template with_numa_alloc<true>::type InnerGraph; typedef typename Galois::Graph::LC_InOut_Graph<InnerGraph> Graph; typedef typename Graph::GraphNode GNode; typedef std::pair<GNode,Dist> WorkItem; typedef Galois::InsertBag<GNode> NodeBag; typedef Galois::InsertBag<WorkItem> WorkItemBag; Galois::GAccumulator<size_t> count; NodeBag bags[2]; struct ForwardProcess { typedef int tt_does_not_need_aborts; Graph& graph; HybridBFS* self; NodeBag* nextBag; Dist newDist; ForwardProcess(Graph& g, HybridBFS* s, NodeBag* n = 0, int d = 0): graph(g), self(s), nextBag(n), newDist(d) { } void operator()(const GNode& n, Galois::UserContext<GNode>&) { for (typename Graph::edge_iterator ii = graph.edge_begin(n, Galois::MethodFlag::NONE), ei = graph.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { processBS(ii, newDist, *nextBag); } } void operator()(const typename Graph::edge_iterator& ii, Galois::UserContext<typename Graph::edge_iterator>&) { processBS(ii, newDist, *nextBag); } void operator()(const WorkItem& item, Galois::UserContext<WorkItem>& ctx) { GNode n = item.first; for (typename Graph::edge_iterator ii = graph.edge_begin(n, Galois::MethodFlag::NONE), ei = graph.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { processAsync(ii, item.second, ctx); } } void processBS(const typename Graph::edge_iterator& ii, Dist nextDist, NodeBag& next) { GNode dst = graph.getEdgeDst(ii); NodeData& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= nextDist) return; if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, nextDist)) { next.push(dst); self->count += 1 + std::distance(graph.edge_begin(dst, Galois::MethodFlag::NONE), graph.edge_end(dst, Galois::MethodFlag::NONE)); break; } } } void processAsync(const typename Graph::edge_iterator& ii, Dist nextDist, Galois::UserContext<WorkItem>& next) { GNode dst = graph.getEdgeDst(ii); NodeData& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= nextDist) return; if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, nextDist)) { next.push(WorkItem(dst, nextDist + 1)); break; } } } }; struct BackwardProcess { typedef int tt_does_not_need_aborts; typedef int tt_does_not_need_push; Graph& graph; HybridBFS* self; NodeBag* nextBag; Dist newDist; BackwardProcess(Graph& g, HybridBFS* s, NodeBag* n, int d): graph(g), self(s), nextBag(n), newDist(d) { } void operator()(const GNode& n, Galois::UserContext<GNode>&) { (*this)(n); } void operator()(const GNode& n) { NodeData& sdata = graph.getData(n, Galois::MethodFlag::NONE); if (sdata.dist <= newDist) return; for (typename Graph::in_edge_iterator ii = graph.in_edge_begin(n, Galois::MethodFlag::NONE), ei = graph.in_edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getInEdgeDst(ii); NodeData& ddata = graph.getData(dst, Galois::MethodFlag::NONE); if (ddata.dist + 1 == newDist) { sdata.dist = newDist; nextBag->push(n); self->count += 1 + std::distance(graph.edge_begin(n, Galois::MethodFlag::NONE), graph.edge_end(n, Galois::MethodFlag::NONE)); break; } } } }; struct PopulateAsync { typedef int tt_does_not_need_aborts; typedef int tt_does_not_need_push; WorkItemBag& bag; Dist newDist; PopulateAsync(WorkItemBag& b, Dist d): bag(b), newDist(d) { } void operator()(const GNode& n, Galois::UserContext<GNode>&) { (*this)(n); } void operator()(const GNode& n) { bag.push(WorkItem(n, newDist)); } }; void operator()(Graph& graph, const GNode& source) { using namespace Galois::WorkList; typedef dChunkedLIFO<256> WL; typedef BulkSynchronous<dChunkedLIFO<256> > BSWL; int next = 0; Dist newDist = 1; int numForward = 0; int numBackward = 0; graph.getData(source).dist = 0; if (std::distance(graph.edge_begin(source), graph.edge_end(source)) + 1 > (long) graph.sizeEdges() / 20) { Galois::do_all_local(graph, BackwardProcess(graph, this, &bags[next], newDist)); numBackward += 1; } else { Galois::for_each(graph.out_edges(source, Galois::MethodFlag::NONE).begin(), graph.out_edges(source, Galois::MethodFlag::NONE).end(), ForwardProcess(graph, this, &bags[next], newDist)); numForward += 1; } while (!bags[next].empty()) { size_t nextSize = count.reduce(); count.reset(); int cur = next; next = (cur + 1) & 1; newDist++; if (nextSize > graph.sizeEdges() / 20) { //std::cout << "Dense " << nextSize << "\n"; Galois::do_all_local(graph, BackwardProcess(graph, this, &bags[next], newDist)); numBackward += 1; } else if (numForward < 10 && numBackward == 0) { //std::cout << "Sparse " << nextSize << "\n"; Galois::for_each_local(bags[cur], ForwardProcess(graph, this, &bags[next], newDist), Galois::wl<WL>()); numForward += 1; } else { //std::cout << "Async " << nextSize << "\n"; WorkItemBag asyncBag; Galois::for_each_local(bags[cur], PopulateAsync(asyncBag, newDist), Galois::wl<WL>()); Galois::for_each_local(asyncBag, ForwardProcess(graph, this), Galois::wl<BSWL>()); break; } bags[cur].clear(); } } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/bfs/bfs.cpp
/** Breadth-first search -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Breadth-first search. * * @author Andrew Lenharth <[email protected]> * @author Donald Nguyen <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Bag.h" #include "Galois/Statistic.h" #include "Galois/Timer.h" #include "Galois/Graph/LCGraph.h" #include "Galois/Graph/TypeTraits.h" #include "Galois/ParallelSTL/ParallelSTL.h" #ifdef GALOIS_USE_EXP #include "Galois/Runtime/ParallelWorkInline.h" #endif #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include <string> #include <deque> #include <sstream> #include <limits> #include <iostream> #include "HybridBFS.h" #ifdef GALOIS_USE_EXP #include "LigraAlgo.h" #include "GraphLabAlgo.h" #endif #include "BFS.h" static const char* name = "Breadth-first Search"; static const char* desc = "Computes the shortest path from a source node to all nodes in a directed " "graph using a modified Bellman-Ford algorithm"; static const char* url = "breadth_first_search"; //****** Command Line Options ****** enum Algo { async, barrier, barrierWithCas, barrierWithInline, deterministic, deterministicDisjoint, graphlab, highCentrality, hybrid, ligra, ligraChi, serial }; enum DetAlgo { none, base, disjoint }; namespace cll = llvm::cl; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input graph>"), cll::Required); static cll::opt<std::string> transposeGraphName("graphTranspose", cll::desc("Transpose of input graph")); static cll::opt<bool> symmetricGraph("symmetricGraph", cll::desc("Input graph is symmetric")); static cll::opt<bool> useDetBase("detBase", cll::desc("Deterministic")); static cll::opt<bool> useDetDisjoint("detDisjoint", cll::desc("Deterministic with disjoint optimization")); static cll::opt<unsigned int> startNode("startNode", cll::desc("Node to start search from"), cll::init(0)); static cll::opt<unsigned int> reportNode("reportNode", cll::desc("Node to report distance to"), cll::init(1)); cll::opt<unsigned int> memoryLimit("memoryLimit", cll::desc("Memory limit for out-of-core algorithms (in MB)"), cll::init(~0U)); static cll::opt<Algo> algo("algo", cll::desc("Choose an algorithm:"), cll::values( clEnumValN(Algo::async, "async", "Asynchronous"), clEnumValN(Algo::barrier, "barrier", "Parallel optimized with barrier (default)"), clEnumValN(Algo::barrierWithCas, "barrierWithCas", "Use compare-and-swap to update nodes"), clEnumValN(Algo::deterministic, "detBase", "Deterministic"), clEnumValN(Algo::deterministicDisjoint, "detDisjoint", "Deterministic with disjoint optimization"), clEnumValN(Algo::highCentrality, "highCentrality", "Optimization for graphs with many shortest paths"), clEnumValN(Algo::hybrid, "hybrid", "Hybrid of barrier and high centrality algorithms"), clEnumValN(Algo::serial, "serial", "Serial"), #ifdef GALOIS_USE_EXP clEnumValN(Algo::barrierWithInline, "barrierWithInline", "Optimized with inlined workset"), clEnumValN(Algo::graphlab, "graphlab", "Use GraphLab programming model"), clEnumValN(Algo::ligraChi, "ligraChi", "Use Ligra and GraphChi programming model"), clEnumValN(Algo::ligra, "ligra", "Use Ligra programming model"), #endif clEnumValEnd), cll::init(Algo::barrier)); template<typename Graph, typename Enable = void> struct not_consistent { not_consistent(Graph& g) { } bool operator()(typename Graph::GraphNode n) const { return false; } }; template<typename Graph> struct not_consistent<Graph, typename std::enable_if<!Galois::Graph::is_segmented<Graph>::value>::type> { Graph& g; not_consistent(Graph& g): g(g) { } bool operator()(typename Graph::GraphNode n) const { Dist dist = g.getData(n).dist; if (dist == DIST_INFINITY) return false; for (typename Graph::edge_iterator ii = g.edge_begin(n), ee = g.edge_end(n); ii != ee; ++ii) { Dist ddist = g.getData(g.getEdgeDst(ii)).dist; if (ddist > dist + 1) { return true; } } return false; } }; template<typename Graph> struct not_visited { Graph& g; not_visited(Graph& g): g(g) { } bool operator()(typename Graph::GraphNode n) const { return g.getData(n).dist >= DIST_INFINITY; } }; template<typename Graph> struct max_dist { Graph& g; Galois::GReduceMax<Dist>& m; max_dist(Graph& g, Galois::GReduceMax<Dist>& m): g(g), m(m) { } void operator()(typename Graph::GraphNode n) const { Dist d = g.getData(n).dist; if (d == DIST_INFINITY) return; m.update(d); } }; template<typename Graph> bool verify(Graph& graph, typename Graph::GraphNode source) { if (graph.getData(source).dist != 0) { std::cerr << "source has non-zero dist value\n"; return false; } namespace pstl = Galois::ParallelSTL; size_t notVisited = pstl::count_if(graph.begin(), graph.end(), not_visited<Graph>(graph)); if (notVisited) { std::cerr << notVisited << " unvisited nodes; this is an error if the graph is strongly connected\n"; } bool consistent = pstl::find_if(graph.begin(), graph.end(), not_consistent<Graph>(graph)) == graph.end(); if (!consistent) { std::cerr << "node found with incorrect distance\n"; return false; } Galois::GReduceMax<Dist> m; Galois::do_all(graph.begin(), graph.end(), max_dist<Graph>(graph, m)); std::cout << "max dist: " << m.reduce() << "\n"; return true; } template<typename Graph> struct Initialize { Graph& g; Initialize(Graph& g): g(g) { } void operator()(typename Graph::GraphNode n) { g.getData(n).dist = DIST_INFINITY; } }; template<typename Algo> void initialize(Algo& algo, typename Algo::Graph& graph, typename Algo::Graph::GraphNode& source, typename Algo::Graph::GraphNode& report) { algo.readGraph(graph); std::cout << "Read " << graph.size() << " nodes\n"; if (startNode >= graph.size() || reportNode >= graph.size()) { std::cerr << "failed to set report: " << reportNode << "or failed to set source: " << startNode << "\n"; assert(0); abort(); } typename Algo::Graph::iterator it = graph.begin(); std::advance(it, startNode); source = *it; it = graph.begin(); std::advance(it, reportNode); report = *it; } template<typename Graph> void readInOutGraph(Graph& graph) { using namespace Galois::Graph; if (symmetricGraph) { Galois::Graph::readGraph(graph, filename); } else if (transposeGraphName.size()) { Galois::Graph::readGraph(graph, filename, transposeGraphName); } else { GALOIS_DIE("Graph type not supported"); } } //! Serial BFS using optimized flags based off asynchronous algo struct SerialAlgo { typedef Galois::Graph::LC_CSR_Graph<SNode,void> ::with_no_lockable<true>::type Graph; typedef Graph::GraphNode GNode; std::string name() const { return "Serial"; } void readGraph(Graph& graph) { Galois::Graph::readGraph(graph, filename); } void operator()(Graph& graph, const GNode source) const { std::deque<GNode> wl; graph.getData(source).dist = 0; wl.push_back(source); while (!wl.empty()) { GNode n = wl.front(); wl.pop_front(); SNode& data = graph.getData(n, Galois::MethodFlag::NONE); Dist newDist = data.dist + 1; for (Graph::edge_iterator ii = graph.edge_begin(n, Galois::MethodFlag::NONE), ei = graph.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); SNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); if (newDist < ddata.dist) { ddata.dist = newDist; wl.push_back(dst); } } } } }; //! Galois BFS using optimized flags struct AsyncAlgo { typedef Galois::Graph::LC_CSR_Graph<SNode,void> ::with_no_lockable<true>::type ::with_numa_alloc<true>::type Graph; typedef Graph::GraphNode GNode; std::string name() const { return "Asynchronous"; } void readGraph(Graph& graph) { Galois::Graph::readGraph(graph, filename); } typedef std::pair<GNode, Dist> WorkItem; struct Indexer: public std::unary_function<WorkItem,Dist> { Dist operator()(const WorkItem& val) const { return val.second; } }; struct Process { typedef int tt_does_not_need_aborts; Graph& graph; Process(Graph& g): graph(g) { } void operator()(WorkItem& item, Galois::UserContext<WorkItem>& ctx) const { GNode n = item.first; Dist newDist = item.second; for (Graph::edge_iterator ii = graph.edge_begin(n, Galois::MethodFlag::NONE), ei = graph.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); SNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= newDist) break; if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { ctx.push(WorkItem(dst, newDist + 1)); break; } } } } }; void operator()(Graph& graph, const GNode& source) const { using namespace Galois::WorkList; typedef dChunkedFIFO<64> dChunk; //typedef ChunkedFIFO<64> Chunk; typedef OrderedByIntegerMetric<Indexer,dChunk> OBIM; graph.getData(source).dist = 0; Galois::for_each(WorkItem(source, 1), Process(graph), Galois::wl<OBIM>()); } }; /** * Alternate between processing outgoing edges or incoming edges. Best for * graphs that have many redundant shortest paths. * * S. Beamer, K. Asanovic and D. Patterson. Direction-optimizing breadth-first * search. In Supercomputing. 2012. */ struct HighCentralityAlgo { typedef Galois::Graph::LC_CSR_Graph<SNode,void> ::with_no_lockable<true>::type ::with_numa_alloc<true>::type InnerGraph; typedef Galois::Graph::LC_InOut_Graph<InnerGraph> Graph; typedef Graph::GraphNode GNode; std::string name() const { return "High Centrality"; } void readGraph(Graph& graph) { readInOutGraph(graph); } struct CountingBag { Galois::InsertBag<GNode> wl; Galois::GAccumulator<size_t> count; void clear() { wl.clear(); count.reset(); } bool empty() { return wl.empty(); } size_t size() { return count.reduce(); } }; CountingBag bags[2]; struct ForwardProcess { typedef int tt_does_not_need_aborts; typedef int tt_does_not_need_push; Graph& graph; CountingBag* next; Dist newDist; ForwardProcess(Graph& g, CountingBag* n, int d): graph(g), next(n), newDist(d) { } void operator()(const GNode& n, Galois::UserContext<GNode>&) { (*this)(n); } void operator()(const Graph::edge_iterator& it, Galois::UserContext<Graph::edge_iterator>&) { (*this)(it); } void operator()(const Graph::edge_iterator& ii) { GNode dst = graph.getEdgeDst(ii); SNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= newDist) return; if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { next->wl.push(dst); next->count += 1 + std::distance(graph.edge_begin(dst, Galois::MethodFlag::NONE), graph.edge_end(dst, Galois::MethodFlag::NONE)); break; } } } void operator()(const GNode& n) { for (Graph::edge_iterator ii = graph.edge_begin(n, Galois::MethodFlag::NONE), ei = graph.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { (*this)(ii); } } }; struct BackwardProcess { typedef int tt_does_not_need_aborts; typedef int tt_does_not_need_push; Graph& graph; CountingBag* next; Dist newDist; BackwardProcess(Graph& g, CountingBag* n, int d): graph(g), next(n), newDist(d) { } void operator()(const GNode& n, Galois::UserContext<GNode>&) { (*this)(n); } void operator()(const GNode& n) { SNode& sdata = graph.getData(n, Galois::MethodFlag::NONE); if (sdata.dist <= newDist) return; for (Graph::in_edge_iterator ii = graph.in_edge_begin(n, Galois::MethodFlag::NONE), ei = graph.in_edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getInEdgeDst(ii); SNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); if (ddata.dist + 1 == newDist) { sdata.dist = newDist; next->wl.push(n); next->count += 1 + std::distance(graph.edge_begin(n, Galois::MethodFlag::NONE), graph.edge_end(n, Galois::MethodFlag::NONE)); break; } } } }; void operator()(Graph& graph, const GNode& source) { using namespace Galois::WorkList; typedef dChunkedLIFO<256> WL; int next = 0; Dist newDist = 1; graph.getData(source).dist = 0; Galois::for_each(graph.out_edges(source, Galois::MethodFlag::NONE).begin(), graph.out_edges(source, Galois::MethodFlag::NONE).end(), ForwardProcess(graph, &bags[next], newDist)); while (!bags[next].empty()) { size_t nextSize = bags[next].size(); int cur = next; next = (cur + 1) & 1; newDist++; std::cout << nextSize << " " << (nextSize > graph.sizeEdges() / 20) << "\n"; if (nextSize > graph.sizeEdges() / 20) Galois::do_all_local(graph, BackwardProcess(graph, &bags[next], newDist)); else Galois::for_each_local(bags[cur].wl, ForwardProcess(graph, &bags[next], newDist), Galois::wl<WL>()); bags[cur].clear(); } } }; //! BFS using optimized flags and barrier scheduling template<typename WL, bool useCas> struct BarrierAlgo { typedef Galois::Graph::LC_CSR_Graph<SNode,void> ::template with_numa_alloc<true>::type ::template with_no_lockable<true>::type Graph; typedef Graph::GraphNode GNode; typedef std::pair<GNode,Dist> WorkItem; std::string name() const { return "Barrier"; } void readGraph(Graph& graph) { Galois::Graph::readGraph(graph, filename); } struct Process { typedef int tt_does_not_need_aborts; Graph& graph; Process(Graph& g): graph(g) { } void operator()(const WorkItem& item, Galois::UserContext<WorkItem>& ctx) const { GNode n = item.first; Dist newDist = item.second; for (Graph::edge_iterator ii = graph.edge_begin(n, Galois::MethodFlag::NONE), ei = graph.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); SNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= newDist) break; if (!useCas || __sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { if (!useCas) ddata.dist = newDist; ctx.push(WorkItem(dst, newDist + 1)); break; } } } } }; void operator()(Graph& graph, const GNode& source) const { graph.getData(source).dist = 0; Galois::for_each(WorkItem(source, 1), Process(graph), Galois::wl<WL>()); } }; struct HybridAlgo: public HybridBFS<SNode,Dist> { std::string name() const { return "Hybrid"; } void readGraph(Graph& graph) { readInOutGraph(graph); } }; template<DetAlgo Version> struct DeterministicAlgo { typedef Galois::Graph::LC_CSR_Graph<SNode,void> ::template with_numa_alloc<true>::type Graph; typedef Graph::GraphNode GNode; std::string name() const { return "Deterministic"; } void readGraph(Graph& graph) { Galois::Graph::readGraph(graph, filename); } typedef std::pair<GNode,int> WorkItem; struct Process { typedef int tt_needs_per_iter_alloc; // For LocalState static_assert(Galois::needs_per_iter_alloc<Process>::value, "Oops"); Graph& graph; Process(Graph& g): graph(g) { } struct LocalState { typedef typename Galois::PerIterAllocTy::rebind<GNode>::other Alloc; typedef std::deque<GNode,Alloc> Pending; Pending pending; LocalState(Process& self, Galois::PerIterAllocTy& alloc): pending(alloc) { } }; typedef LocalState GaloisDeterministicLocalState; static_assert(Galois::has_deterministic_local_state<Process>::value, "Oops"); uintptr_t galoisDeterministicId(const WorkItem& item) const { return item.first; } static_assert(Galois::has_deterministic_id<Process>::value, "Oops"); void build(const WorkItem& item, typename LocalState::Pending* pending) const { GNode n = item.first; Dist newDist = item.second; for (Graph::edge_iterator ii = graph.edge_begin(n, Galois::MethodFlag::NONE), ei = graph.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); SNode& ddata = graph.getData(dst, Galois::MethodFlag::ALL); Dist oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= newDist) break; pending->push_back(dst); break; } } } void modify(const WorkItem& item, Galois::UserContext<WorkItem>& ctx, typename LocalState::Pending* ppending) const { Dist newDist = item.second; bool useCas = false; for (typename LocalState::Pending::iterator ii = ppending->begin(), ei = ppending->end(); ii != ei; ++ii) { GNode dst = *ii; SNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist oldDist; while (true) { oldDist = ddata.dist; if (oldDist <= newDist) break; if (!useCas || __sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { if (!useCas) ddata.dist = newDist; ctx.push(WorkItem(dst, newDist + 1)); break; } } } } void operator()(const WorkItem& item, Galois::UserContext<WorkItem>& ctx) const { typename LocalState::Pending* ppending; if (Version == DetAlgo::disjoint) { bool used; LocalState* localState = (LocalState*) ctx.getLocalState(used); ppending = &localState->pending; if (used) { modify(item, ctx, ppending); return; } } if (Version == DetAlgo::disjoint) { build(item, ppending); } else { typename LocalState::Pending pending(ctx.getPerIterAlloc()); build(item, &pending); graph.getData(item.first, Galois::MethodFlag::WRITE); // Failsafe point modify(item, ctx, &pending); } } }; void operator()(Graph& graph, const GNode& source) const { #ifdef GALOIS_USE_EXP typedef Galois::WorkList::BulkSynchronousInline<> WL; #else typedef Galois::WorkList::BulkSynchronous<Galois::WorkList::dChunkedLIFO<256> > WL; #endif graph.getData(source).dist = 0; switch (Version) { case DetAlgo::none: Galois::for_each(WorkItem(source, 1), Process(graph),Galois::wl<WL>()); break; case DetAlgo::base: Galois::for_each_det(WorkItem(source, 1), Process(graph)); break; case DetAlgo::disjoint: Galois::for_each_det(WorkItem(source, 1), Process(graph)); break; default: std::cerr << "Unknown algorithm " << int(Version) << "\n"; abort(); } } }; template<typename Algo> void run() { typedef typename Algo::Graph Graph; typedef typename Graph::GraphNode GNode; Algo algo; Graph graph; GNode source, report; initialize(algo, graph, source, report); //Galois::preAlloc(numThreads + (3*graph.size() * sizeof(typename Graph::node_data_type)) / Galois::Runtime::MM::pageSize); Galois::preAlloc(8*(numThreads + (graph.size() * sizeof(typename Graph::node_data_type)) / Galois::Runtime::MM::pageSize)); Galois::reportPageAlloc("MeminfoPre"); Galois::StatTimer T; std::cout << "Running " << algo.name() << " version\n"; T.start(); Galois::do_all_local(graph, Initialize<typename Algo::Graph>(graph)); algo(graph, source); T.stop(); Galois::reportPageAlloc("MeminfoPost"); std::cout << "Node " << reportNode << " has distance " << graph.getData(report).dist << "\n"; if (!skipVerify) { if (verify(graph, source)) { std::cout << "Verification successful.\n"; } else { std::cerr << "Verification failed.\n"; assert(0 && "Verification failed"); abort(); } } } int main(int argc, char **argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); using namespace Galois::WorkList; typedef BulkSynchronous<dChunkedLIFO<256> > BSWL; #ifdef GALOIS_USE_EXP typedef BulkSynchronousInline<> BSInline; #else typedef BSWL BSInline; #endif if (useDetDisjoint) algo = Algo::deterministicDisjoint; else if (useDetBase) algo = Algo::deterministic; Galois::StatTimer T("TotalTime"); T.start(); switch (algo) { case Algo::serial: run<SerialAlgo>(); break; case Algo::async: run<AsyncAlgo>(); break; case Algo::barrier: run<BarrierAlgo<BSWL,false> >(); break; case Algo::barrierWithCas: run<BarrierAlgo<BSWL,true> >(); break; case Algo::barrierWithInline: run<BarrierAlgo<BSInline,false> >(); break; case Algo::highCentrality: run<HighCentralityAlgo>(); break; case Algo::hybrid: run<HybridAlgo>(); break; #ifdef GALOIS_USE_EXP case Algo::graphlab: run<GraphLabBFS>(); break; case Algo::ligraChi: run<LigraBFS<true> >(); break; case Algo::ligra: run<LigraBFS<false> >(); break; #endif case Algo::deterministic: run<DeterministicAlgo<DetAlgo::base> >(); break; case Algo::deterministicDisjoint: run<DeterministicAlgo<DetAlgo::disjoint> >(); break; default: std::cerr << "Unknown algorithm\n"; abort(); } T.stop(); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/bfs/Diameter.cpp
/** Computing/Estimating diameter of a graph -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Algorithms for estimating the diameter (longest shortest path) of a graph. * * @author Donald Nguyen <[email protected]> */ #include "Galois/config.h" #include "Galois/Accumulator.h" #include "Galois/Bag.h" #include "Galois/Galois.h" #include "Galois/Statistic.h" #include "Galois/Timer.h" #include "Galois/Graph/LCGraph.h" #include "Galois/ParallelSTL/ParallelSTL.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include GALOIS_CXX11_STD_HEADER(random) #include <deque> #include <string> #include <limits> #include <iostream> #include "HybridBFS.h" #ifdef GALOIS_USE_EXP #include "LigraAlgo.h" #include "GraphLabAlgo.h" #endif #include "BFS.h" static const char* name = "Diameter Estimation"; static const char* desc = "Estimates the diameter of a graph"; static const char* url = 0; //****** Command Line Options ****** enum Algo { graphlab, ligra, ligraChi, pickK, simple }; namespace cll = llvm::cl; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input graph>"), cll::Required); static cll::opt<std::string> transposeGraphName("graphTranspose", cll::desc("Transpose of input graph")); static cll::opt<bool> symmetricGraph("symmetricGraph", cll::desc("Input graph is symmetric")); static cll::opt<unsigned int> startNode("startNode", cll::desc("Node to start search from"), cll::init(0)); static cll::opt<unsigned int> numCandidates("numCandidates", cll::desc("Number of candidates to use for pickK algorithm"), cll::init(5)); cll::opt<unsigned int> memoryLimit("memoryLimit", cll::desc("Memory limit for out-of-core algorithms (in MB)"), cll::init(~0U)); static cll::opt<Algo> algo("algo", cll::desc("Choose an algorithm:"), cll::values( clEnumValN(Algo::simple, "simple", "Simple pseudo-peripheral algorithm (default)"), clEnumValN(Algo::pickK, "pickK", "Pick K candidates"), #ifdef USE_EXP clEnumValN(Algo::ligra, "ligra", "Use Ligra programming model"), clEnumValN(Algo::ligraChi, "ligraChi", "Use Ligra and GraphChi programming model"), clEnumValN(Algo::graphlab, "graphlab", "Use GraphLab programming model"), #endif clEnumValEnd), cll::init(Algo::simple)); template<typename Graph> struct min_degree { typedef typename Graph::GraphNode GNode; Graph& graph; min_degree(Graph& g): graph(g) { } Galois::optional<GNode> operator()(const Galois::optional<GNode>& a, const Galois::optional<GNode>& b) const { if (!a) return b; if (!b) return a; if (std::distance(graph.edge_begin(*a), graph.edge_end(*a)) < std::distance(graph.edge_begin(*b), graph.edge_end(*b))) return a; else return b; } }; template<typename Graph> struct order_by_degree { typedef typename Graph::GraphNode GNode; Graph& graph; order_by_degree(Graph& g): graph(g) { } bool operator()(const GNode& a, const GNode& b) const { return std::distance(graph.edge_begin(a), graph.edge_end(a)) < std::distance(graph.edge_begin(b), graph.edge_end(b)); } }; //! Collect nodes with dist == d template<typename Graph> struct collect_nodes_with_dist { typedef typename Graph::GraphNode GNode; Graph& graph; Galois::InsertBag<GNode>& bag; Dist dist; collect_nodes_with_dist(Graph& g, Galois::InsertBag<GNode>& b, Dist d): graph(g), bag(b), dist(d) { } void operator()(const GNode& n) { if (graph.getData(n).dist == dist) bag.push(n); } }; template<typename Graph> struct has_dist { typedef typename Graph::GraphNode GNode; Graph& graph; Dist dist; has_dist(Graph& g, Dist d): graph(g), dist(d) { } Galois::optional<GNode> operator()(const GNode& a) const { if (graph.getData(a).dist == dist) return Galois::optional<GNode>(a); return Galois::optional<GNode>(); } }; template<typename Graph> struct CountLevels { Graph& graph; std::deque<size_t> counts; CountLevels(Graph& g): graph(g) { } void operator()(typename Graph::GraphNode n) { Dist d = graph.getData(n).dist; if (d == DIST_INFINITY) return; if (counts.size() <= d) counts.resize(d + 1); ++counts[d]; } // Reduce function template<typename G> void operator()(CountLevels<G>& a, CountLevels<G>& b) { if (a.counts.size() < b.counts.size()) a.counts.resize(b.counts.size()); std::transform(b.counts.begin(), b.counts.end(), a.counts.begin(), a.counts.begin(), std::plus<size_t>()); } std::deque<size_t> count() { return Galois::Runtime::do_all_impl(Galois::Runtime::makeLocalRange(graph), *this, *this).counts; } }; template<typename Algo> void resetGraph(typename Algo::Graph& g) { Galois::do_all_local(g, typename Algo::Initialize(g)); } template<typename Graph> void readInOutGraph(Graph& graph) { using namespace Galois::Graph; if (symmetricGraph) { Galois::Graph::readGraph(graph, filename); } else if (transposeGraphName.size()) { Galois::Graph::readGraph(graph, filename, transposeGraphName); } else { GALOIS_DIE("Graph type not supported"); } } /** * The eccentricity of vertex v, ecc(v), is the greatest distance from v to any vertex. * A peripheral vertex v is one whose distance from some other vertex u is the * diameter of the graph: \exists u : dist(v, u) = D. A pseudo-peripheral vertex is a * vertex v that satisfies: \forall u : dist(v, u) = ecc(v) ==> ecc(v) = ecc(u). * * Simple pseudo-peripheral algorithm: * 1. Choose v * 2. Among the vertices dist(v, u) = ecc(v), select u with minimal degree * 3. If ecc(u) > ecc(v) then * v = u and go to step 2 * otherwise * u is a pseudo-peripheral vertex */ struct SimpleAlgo { typedef HybridBFS<SNode,Dist> BFS; typedef BFS::Graph Graph; typedef Graph::GraphNode GNode; typedef std::pair<size_t,GNode> Result; void readGraph(Graph& graph) { readInOutGraph(graph); } struct Initialize { Graph& graph; Initialize(Graph& g): graph(g) { } void operator()(GNode n) { graph.getData(n).dist = DIST_INFINITY; } }; Result search(Graph& graph, GNode start) { BFS bfs; bfs(graph, start); CountLevels<Graph> cl(graph); std::deque<size_t> counts = cl.count(); size_t ecc = counts.size() - 1; //size_t maxWidth = *std::max_element(counts.begin(), counts.end()); GNode candidate = *Galois::ParallelSTL::map_reduce(graph.begin(), graph.end(), has_dist<Graph>(graph, ecc), Galois::optional<GNode>(), min_degree<Graph>(graph)); resetGraph<SimpleAlgo>(graph); return Result(ecc, candidate); } size_t operator()(Graph& graph, GNode source) { Result v = search(graph, source); while (true) { Result u = search(graph, v.second); std::cout << "ecc(v) = " << v.first << " ecc(u) = " << u.first << "\n"; bool better = u.first > v.first; if (!better) break; v = u; } return v.first; } }; /** * A more complicated pseudo-peripheral algorithm. Designed for finding pairs * of nodes with small maximum width between them, which is useful for matrix * reordering. Include it here for completeness. * * Let the width of vertex v be the maximum number of nodes with the same * distance from v. * * Unlike the simple one, instead of picking a minimal degree candidate u, * select among some number of candidates U. Here, we select the top n * lowest degree nodes who do not share neighborhoods. * * If there exists a vertex u such that ecc(u) > ecc(v) proceed as in the * simple algorithm. * * Otherwise, select the u that has least maximum width. */ struct PickKAlgo { struct LNode: public SNode { bool done; }; typedef HybridBFS<LNode,Dist> BFS; typedef BFS::Graph Graph; typedef Graph::GraphNode GNode; void readGraph(Graph& graph) { readInOutGraph(graph); } struct Initialize { Graph& graph; Initialize(Graph& g): graph(g) { } void operator()(GNode n) { graph.getData(n).dist = DIST_INFINITY; graph.getData(n).done = false; } }; std::deque<GNode> select(Graph& graph, unsigned topn, size_t dist) { Galois::InsertBag<GNode> bag; Galois::do_all_local(graph, collect_nodes_with_dist<Graph>(graph, bag, dist)); // Incrementally sort nodes until we find least N who are not neighbors // of each other std::deque<GNode> nodes; std::deque<GNode> result; std::copy(bag.begin(), bag.end(), std::back_inserter(nodes)); size_t cur = 0; size_t size = nodes.size(); size_t delta = topn * 5; for (std::deque<GNode>::iterator ii = nodes.begin(), ei = nodes.end(); ii != ei; ) { std::deque<GNode>::iterator mi = ii; if (cur + delta < size) { std::advance(mi, delta); cur += delta; } else { mi = ei; cur = size; } std::partial_sort(ii, mi, ei, order_by_degree<Graph>(graph)); for (std::deque<GNode>::iterator jj = ii; jj != mi; ++jj) { GNode n = *jj; // Ignore marked neighbors if (graph.getData(n).done) continue; result.push_back(n); if (result.size() == topn) { return result; } // Mark neighbors for (Graph::edge_iterator nn = graph.edge_begin(n), en = graph.edge_end(n); nn != en; ++nn) graph.getData(graph.getEdgeDst(nn)).done = true; } ii = mi; } return result; } struct Result { GNode source; std::deque<GNode> candidates; size_t maxWidth; size_t ecc; }; Result search(Graph& graph, const GNode& start, size_t limit, bool computeCandidates) { BFS bfs; Result res; bfs(graph, start); CountLevels<Graph> cl(graph); std::deque<size_t> counts = cl.count(); res.source = start; res.ecc = counts.size() - 1; res.maxWidth = *std::max_element(counts.begin(), counts.end()); if (limit == static_cast<size_t>(-1) || res.maxWidth < limit) { if (computeCandidates) res.candidates = select(graph, numCandidates, res.ecc); } resetGraph<PickKAlgo>(graph); return res; } size_t operator()(Graph& graph, GNode source) { Galois::optional<size_t> terminal; Result v = search(graph, source, ~0, true); while (true) { std::cout << "(ecc(v), max_width) =" << " (" << v.ecc << ", " << v.maxWidth << ")" << " (ecc(u), max_width(u)) ="; size_t last = ~0; for (auto ii = v.candidates.begin(), ei = v.candidates.end(); ii != ei; ++ii) { Result u = search(graph, *ii, last, false); std::cout << " (" << u.ecc << ", " << u.maxWidth << ")"; if (u.maxWidth >= last) { continue; } else if (u.ecc > v.ecc) { v = u; terminal = Galois::optional<size_t>(); break; } else if (u.maxWidth < last) { last = u.maxWidth; terminal = Galois::optional<size_t>(u.ecc); } } std::cout << "\n"; if (terminal) break; v = search(graph, v.source, ~0, true); } return *terminal; } }; template<typename Algo> void initialize(Algo& algo, typename Algo::Graph& graph, typename Algo::Graph::GraphNode& source) { algo.readGraph(graph); std::cout << "Read " << graph.size() << " nodes\n"; if (startNode >= graph.size()) { std::cerr << "failed to set source: " << startNode << "\n"; assert(0); abort(); } typename Algo::Graph::iterator it = graph.begin(); std::advance(it, startNode); source = *it; } template<typename Algo> void run() { typedef typename Algo::Graph Graph; typedef typename Graph::GraphNode GNode; Algo algo; Graph graph; GNode source; initialize(algo, graph, source); //Galois::preAlloc((numThreads + (graph.size() * sizeof(SNode) * 2) / Galois::Runtime::MM::pageSize)*8); Galois::reportPageAlloc("MeminfoPre"); Galois::StatTimer T; T.start(); resetGraph<Algo>(graph); size_t diameter = algo(graph, source); T.stop(); Galois::reportPageAlloc("MeminfoPost"); std::cout << "Estimated diameter: " << diameter << "\n"; } int main(int argc, char **argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); Galois::StatTimer T("TotalTime"); T.start(); switch (algo) { case Algo::simple: run<SimpleAlgo>(); break; case Algo::pickK: run<PickKAlgo>(); break; #ifdef GALOIS_USE_EXP case Algo::ligra: run<LigraDiameter<false> >(); break; case Algo::ligraChi: run<LigraDiameter<true> >(); break; case Algo::graphlab: run<GraphLabDiameter<true> >(); break; #endif default: std::cerr << "Unknown algorithm\n"; abort(); } T.stop(); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/bfs/BFS.h
#ifndef APPS_BFS_BFS_H #define APPS_BFS_BFS_H #include "llvm/Support/CommandLine.h" typedef unsigned int Dist; static const Dist DIST_INFINITY = std::numeric_limits<Dist>::max() - 1; //! Standard data type on nodes struct SNode { Dist dist; }; template<typename Graph> void readInOutGraph(Graph& graph); extern llvm::cl::opt<unsigned int> memoryLimit; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/dummy.f90
!*************************************************** ! File: Minimal95.F95 ! Language: Fortran 95 ! Description: This program does nothing !*************************************************** PROGRAM Minimal95 print *, "Hello" END PROGRAM Minimal95
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/CMakeLists.txt
file(GLOB Sources util/*.cpp libMat/*.cpp libElm/libGeom/*.cpp libElm/libQuad/*.cpp libElm/libShape/*.cpp libElm/libShapesEvaluated/*.cpp libElm/libElement/*.cpp libElm/*.cpp libElOp/*.cpp libAVI/*.cpp libMeshInit/femap/*.cpp libMeshInit/dgmechanics/*.cpp libMeshInit/*.cpp dummy.f90 ) find_package(Fortran) if(Fortran_FOUND) enable_language(Fortran OPTIONAL) endif() find_package(LAPACK) find_package(ZLIB) # TODO(ddn): CMake Boost module on BG/Q cannot be called multiple times. Skip # avi althogether for now. if(CMAKE_SYSTEM_NAME MATCHES "BlueGeneQ") set(Boost_FOUND off) else() # Needs a slightly higher version than other Galois apps find_package(Boost 1.50.0 COMPONENTS system iostreams filesystem) endif() if(CMAKE_Fortran_COMPILER_WORKS AND LAPACK_FOUND AND ZLIB_FOUND AND Boost_FOUND) include_directories(${ZLIB_INCLUDE_DIRS}) add_library(AVI ${Sources}) target_link_libraries(AVI ${ZLIB_LIBRARIES}) target_link_libraries(AVI ${Boost_LIBRARIES}) set(AVI_FOUND TRUE) endif() app(AVIorderedSerial main/AVIorderedSerial.cpp REQUIRES AVI_FOUND EXTLIBS AVI ${LAPACK_LIBRARIES}) app(AVIodgOrdered main/AVIodgOrdered.cpp REQUIRES AVI_FOUND EXTLIBS AVI ${LAPACK_LIBRARIES}) app(AVIodgExplicit main/AVIodgExplicit.cpp REQUIRES AVI_FOUND EXTLIBS AVI ${LAPACK_LIBRARIES}) app(AVIodgExplicitNoLock main/AVIodgExplicitNoLock.cpp REQUIRES AVI_FOUND EXTLIBS AVI ${LAPACK_LIBRARIES}) # the files may be removed from the release without causing error in cmake if(0) app(AVIodgReadonly exp/AVIodgReadonly.cpp REQUIRES AVI_FOUND USE_EXP EXTLIBS AVI ${LAPACK_LIBRARIES}) app(AVIodgImplicit exp/AVIodgImplicit.cpp REQUIRES AVI_FOUND USE_EXP EXTLIBS AVI ${LAPACK_LIBRARIES}) app(AVIodgAutoPriLock exp/AVIodgAutoPriLock.cpp REQUIRES AVI_FOUND USE_EXP EXTLIBS AVI ${LAPACK_LIBRARIES}) app(AVIodgAutoShare exp/AVIodgAutoShare.cpp REQUIRES AVI_FOUND USE_EXP EXTLIBS AVI ${LAPACK_LIBRARIES}) app(AVIodgNB exp/AVIodgNB.cpp REQUIRES AVI_FOUND USE_EXP EXTLIBS AVI ${LAPACK_LIBRARIES}) endif() include_directories(util) include_directories(main) include_directories(libElm) include_directories(libElm/libQuad) include_directories(libElm/libGeom) include_directories(libElm/libShapesEvaluated) include_directories(libElm/libShape) include_directories(libElm/libElement) include_directories(libAVI) include_directories(libMeshInit) include_directories(libMeshInit/dgmechanics) include_directories(libMeshInit/femap) include_directories(libMat) include_directories(libElOp)
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/util/util.h
/** Some debug utilities etc. -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef UTIL_H #define UTIL_H #include <iostream> #include <vector> template <typename T> std::ostream& operator << (std::ostream& out, const std::vector<T>& v) { out << "{ "; for (typename std::vector<T>::const_iterator i = v.begin(); i != v.end(); ++i) { out << *i << ", "; } out << "}"; return out; } template <typename I> void printIter (std::ostream& out, I begin, I end) { out << "{ "; for (I i = begin; i != end; ++i) { out << *i << ", "; } out << "}" << std::endl; } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/util/AuxDefs.h
/* * AuxDefs.h: Common definitions * DG++ * * Created by Adrian Lew on 9/4/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _AUXDEFS_H_ #define _AUXDEFS_H_ #include <cstddef> #include <cmath> #include <cstdlib> #include <vector> //! Nodal indices, starting at 0. : amber typedef size_t GlobalNodalIndex; //! Degree of freedom indices, starting at 0. typedef size_t GlobalDofIndex; //! Element indices, starting at 0. typedef size_t GlobalElementIndex; //! commonly used vector and vector<vector> typedef std::vector<double> VecDouble; typedef std::vector< std::vector<double> > MatDouble; typedef std::vector< std::vector < std::vector < std::vector <double> > > > FourDVecDouble; typedef std::vector<bool> VecBool; typedef std::vector< std::vector< bool> > MatBool; //! constants const double TOLERANCE = 1e-20; struct DoubleComparator { static inline int compare (double left, double right) { double tdiff = left - right; if (fabs (tdiff) < TOLERANCE) { return 0; } else if (tdiff > 0.0) { return 1; } else if (tdiff < 0.0) { return -1; } else { abort (); // shouldn't reach here return 0; } } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/dgmechanics/TriLinearCoordConn.h
/** TriLinearCoordConn represents a mesh of linear triangles -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef _TRI_LINEAR_COORD_CONN_H_ #define _TRI_LINEAR_COORD_CONN_H_ #include "CoordConn.h" /** * important constants for linear triangle */ struct TriLinearTraits { enum { SPD = 2, NODES_PER_ELEM = 3, TOPO = 2, NUM_EDGES = 3, NFIELDS = SPD, }; }; class TriLinearCoordConn : public AbstractCoordConn <TriLinearTraits::SPD, TriLinearTraits::NODES_PER_ELEM, TriLinearTraits::TOPO> { protected: /** * * Return a 2d element with linear shape functions and linear triangle as the geometry * * @param elemIndex */ virtual Element* makeElem (const size_t elemIndex) const { std::vector<GlobalNodalIndex> conn; genElemConnectivity (elemIndex, conn); Triangle<TriLinearTraits::SPD>* triGeom = new Triangle<TriLinearTraits::SPD> (coordinates, conn); return new P12D<TriLinearTraits::NFIELDS>::Bulk (*triGeom); } public: /** * divides each triangle in the mesh in to 4 triangles * The main idea is to join the mid points of the three segments (called edges here) */ virtual void subdivide () { // Check for consistency of connectivity and coordinates arrays: std::vector<edgestruct> faces; size_t iElements = getNumElements(); // 3 nodes per element. size_t iNodes = getNumNodes(); // Assume 2D triangles. for (size_t e = 0; e < iElements; e++) { // std::vector<GlobalNodalIndex> conn; GlobalNodalIndex node0; GlobalNodalIndex node1; node0 = connectivity[e * 3 + 0]; node1 = connectivity[e * 3 + 1]; faces.push_back (edgestruct (e, 0, node0, node1)); node0 = connectivity[e * 3 + 1]; node1 = connectivity[e * 3 + 2]; faces.push_back (edgestruct (e, 1, node0, node1)); node0 = connectivity[e * 3 + 2]; node1 = connectivity[e * 3 + 0]; faces.push_back (edgestruct (e, 2, node0, node1)); } std::sort (faces.begin (), faces.end ()); std::vector<size_t> NodeInfo (faces.size () * 2, 0); size_t middlenodenum = iNodes; // Create middle nodes for (std::vector<edgestruct>::iterator it = faces.begin (); it != faces.end (); it++) { // for 1-based node numbering // double xm = (coordinates[2 * (it->conn[0] - 1)] + coordinates[2 * (it->conn[1] - 1)]) / 2.; // double ym = (coordinates[2 * (it->conn[0] - 1) + 1] + coordinates[2 * (it->conn[1] - 1) + 1]) / 2.; // // for 0-based node numbering, we don't need to subtract 1 from conn field of facestruct double xm = (coordinates[2 * it->node0] + coordinates[2 * it->node1]) / 2.; double ym = (coordinates[2 * it->node0 + 1] + coordinates[2 * it->node1 + 1]) / 2.; coordinates.push_back (xm); coordinates.push_back (ym); NodeInfo[it->elemId * 6 + it->edgeId * 2 + 0] = it->edgeId; // for 0-based node numbering, don't add 1 // NodeInfo[it->elemId * 6 + it->edgeId * 2 + 1] = middlenodenum + 1; NodeInfo[it->elemId * 6 + it->edgeId * 2 + 1] = middlenodenum; if (it + 1 != faces.end ()) { if (it->node0 == (it + 1)->node0 && it->node1 == (it + 1)->node1) { it++; NodeInfo[it->elemId * 6 + it->edgeId * 2 + 0] = it->edgeId; // for 0-based node numbering, don't add 1 // NodeInfo[it->elemId * 6 + it->edgeId * 2 + 1] = middlenodenum + 1; NodeInfo[it->elemId * 6 + it->edgeId * 2 + 1] = middlenodenum; } } ++middlenodenum; } // Create connectivity std::vector<GlobalNodalIndex> copyconn (connectivity); connectivity.resize (iElements * 3 * 4); for (size_t e = 0; e < iElements; e++) { // triangle 1 connectivity[e * 4 * 3 + 0 * 3 + 0] = copyconn[e * 3]; connectivity[e * 4 * 3 + 0 * 3 + 1] = NodeInfo[e * 6 + 0 * 2 + 1]; connectivity[e * 4 * 3 + 0 * 3 + 2] = NodeInfo[e * 6 + 2 * 2 + 1]; // triangle 2 connectivity[e * 4 * 3 + 1 * 3 + 0] = copyconn[e * 3 + 1]; connectivity[e * 4 * 3 + 1 * 3 + 1] = NodeInfo[e * 6 + 1 * 2 + 1]; connectivity[e * 4 * 3 + 1 * 3 + 2] = NodeInfo[e * 6 + 0 * 2 + 1]; // triangle 3 connectivity[e * 4 * 3 + 2 * 3 + 0] = copyconn[e * 3 + 2]; connectivity[e * 4 * 3 + 2 * 3 + 1] = NodeInfo[e * 6 + 2 * 2 + 1]; connectivity[e * 4 * 3 + 2 * 3 + 2] = NodeInfo[e * 6 + 1 * 2 + 1]; // triangle 4 connectivity[e * 4 * 3 + 3 * 3 + 0] = NodeInfo[e * 6 + 0 * 2 + 1]; connectivity[e * 4 * 3 + 3 * 3 + 1] = NodeInfo[e * 6 + 1 * 2 + 1]; connectivity[e * 4 * 3 + 3 * 3 + 2] = NodeInfo[e * 6 + 2 * 2 + 1]; } // nodes = int(coordinates.size() / 2); // elements = int(connectivity.size() / 3); } }; #endif // _TRI_LINEAR_COORD_CONN_H_
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/dgmechanics/MeshInit.h
/** MeshInit combines reading and initializtion of mesh -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef MESHINIT_H_ #define MESHINIT_H_ #include <vector> #include <string> #include <algorithm> #include <exception> #include <cassert> #include <cmath> #include <cstdio> #include <boost/noncopyable.hpp> #include "AuxDefs.h" #include "StandardAVI.h" #include "Element.h" #include "Femap.h" #include "Material.h" #include "CoordConn.h" #include "TriLinearCoordConn.h" #include "TetLinearCoordConn.h" class MeshInit : private boost::noncopyable { public: typedef StandardAVI::BCFunc BCFunc; typedef StandardAVI::BCImposedType BCImposedType; private: static const double RHO; static const double MU; static const double LAMBDA; static const int PID; static const double DELTA; static const double T_INIT; // length of filenames static const size_t MAX_FNAME; private: double simEndTime; bool wave; //! to be freed LocalToGlobalMap* l2gMap; CoordConn* cc; SimpleMaterial* ile; //! vectors to keep track of all the memory std::vector<ElementGeometry*> geomVec; std::vector<Element*> elemVec; std::vector<Residue*> massResidueVec; std::vector<DResidue*> operationsVec; std::vector<AVI*> aviVec; std::vector<size_t> fieldsUsed; double writeInc; int writeInterval; std::vector<size_t> aviWriteInterval; FILE* syncFileWriter; private: void stretchInternal (VecDouble& dispOrVel, bool isVel) const ; void getBCs (const Element& e, std::vector< std::vector<BCImposedType> >& itypeMat, std::vector<BCFunc>& bcfuncVec) const; static bool computeDiffAVI (std::vector<AVI*> listA, std::vector<AVI*> listB, bool printDiff); template <typename T> static void destroyVecOfPtr (std::vector<T*>& vec) { for (typename std::vector<T*>::iterator i = vec.begin (), ei = vec.end (); i != ei; ++i) { delete *i; *i = NULL; } } void destroy () { destroyVecOfPtr (geomVec); destroyVecOfPtr (elemVec); destroyVecOfPtr (massResidueVec); destroyVecOfPtr (operationsVec); destroyVecOfPtr (aviVec); delete l2gMap; delete cc; delete ile; } public: /** * * @param simEndTime * @param wave */ MeshInit (double simEndTime, bool wave): simEndTime (simEndTime), wave(wave) { //TODO: writeInc should depend on simEndTime and // number of intervals intended if (wave) { this->writeInc = 0.005; // XXX: from testPAVI2D } else { this->writeInc = 0.1; } writeInterval = 0; syncFileWriter = NULL; } virtual ~MeshInit () { destroy (); } /** * * main function to call after creating an instance. This * initializes all the data structures by reading this file * * @param fileName * @param ndiv: number of times the mesh (read in from the file) should be subdivided */ void initializeMesh (const std::string& fileName, int ndiv); virtual size_t getSpatialDim () const = 0; virtual size_t getNodesPerElem () const = 0; bool isWave () const { return wave; } double getSimEndTime () const { return simEndTime; } //! Number of elements in the mesh int getNumElements () const { return cc->getNumElements (); } //! number of nodes (vertices) in the mesh int getNumNodes () const { return cc->getNumNodes (); } //! number of nodes times the dimensionality unsigned int getTotalNumDof () const { return l2gMap->getTotalNumDof (); } const std::vector<AVI*>& getAVIVec () const { return aviVec; } //! mapping function from local per element vectors (for target functions) to global vectors //! this tells what indices in the global vector each element contributes to const LocalToGlobalMap& getLocalToGlobalMap () const { return *l2gMap; } /** * setup initial conditions * to be called before starting the simulation loop * * @param disp: global dispalcements vector */ void setupDisplacements (VecDouble& disp) const { stretchInternal (disp, false); } /** * setup initial conditions * to be called before starting the simulation loop * * @param vel: global velocities vector */ void setupVelocities (VecDouble& vel) const { stretchInternal (vel, true); } /** * Write the values in global vectors corresponding to this avi element * to a file at regular intervals * * @param avi * @param Qval * @param Vbval * @param Tval */ void writeSync (const AVI& avi, const VecDouble& Qval, const VecDouble& Vbval, const VecDouble& Tval) ; /** * Compare state of avi vector against other object * Use for verification between different versions * * @param that */ bool cmpState (const MeshInit& that) const { return computeDiffAVI (this->aviVec, that.aviVec, false); } /** * Compare state of avi vector against other object * Use for verification between different versions * and also print out the differences * * @param that */ void printDiff (const MeshInit& that) const { computeDiffAVI (this->aviVec, that.aviVec, true); } void writeMeshCenters (const char* outFileName="mesh-centers.csv") const; void writeMesh (const char* polyFileName="mesh-poly.csv", const char* coordFileName="mesh-coord.csv") const; protected: //! functions to compute boundary condtions //! @param coord virtual BCFunc getBCFunc (const double* coord) const = 0; //! returns the correct derived type of CoordConn virtual CoordConn* makeCoordConn () const = 0; //! parametric node numbering of an element (triangle or tetrahedron) virtual const double* getParam () const = 0; //! internal function used by @see setupDisplacements //! @param coord //! @param f virtual double initDisp (const double* coord, int f) const = 0; //! internal function used by @see setupVelocities //! @param coord //! @param f virtual double initVel (const double* coord, int f) const = 0; //! number of fields often the same as dimensionality virtual size_t numFields () const = 0; }; class TriMeshInit: public MeshInit { private: static double topBC (int f, int a, double t) { if (f == 0) { return (0.1 * cos (t)); } else { return (0.0); } } static double botBC (int f, int a, double t) { return (0.0); } public: static const double PARAM[]; TriMeshInit (double simEndTime, bool wave=false): MeshInit(simEndTime, wave) { } virtual size_t getSpatialDim () const { return TriLinearTraits::SPD; } virtual size_t getNodesPerElem () const { return TriLinearTraits::NODES_PER_ELEM; } protected: virtual CoordConn* makeCoordConn () const { return new TriLinearCoordConn(); } virtual const double* getParam () const { return PARAM; } virtual size_t numFields () const { return TriLinearTraits::NFIELDS;} virtual BCFunc getBCFunc (const double* coord) const { if (coord[0] == 0.0) { return botBC; } else if (coord[0] == 10.0) { return topBC; } else { return NULL; } } virtual double initDisp (const double* coord, int f) const { double stretch; if (f == 0) { // XXX: some weird code??? stretch = coord[0] * 0.2 - 1.0; stretch = coord[0] * 0.01 - 0.05; } else { stretch = coord[1] * 0.2 - 1.0; stretch = coord[1] * 0.01 - 0.05; } return stretch; } virtual double initVel (const double* coord, int f) const { if (coord[0] == 0.0) { return 0.1; } else { return 0.0; } } }; class TetMeshInit: public MeshInit { private: static double topBC (int f, int a, double t) { if (f == 2) { return (0.1 * sin (t)); } else { return (0.0); } } static double botBC (int f, int a, double t) { return (0.0); } public: static const double PARAM[]; TetMeshInit (double simEndTime, bool wave=false): MeshInit(simEndTime, wave) { } virtual size_t getSpatialDim () const { return TetLinearTraits::SPD; } virtual size_t getNodesPerElem () const { return TetLinearTraits::NODES_PER_ELEM; } protected: virtual CoordConn* makeCoordConn () const { return new TetLinearCoordConn(); } virtual const double* getParam () const { return PARAM; } virtual size_t numFields () const { return TetLinearTraits::NFIELDS;} virtual BCFunc getBCFunc (const double* coord) const { if (fabs (coord[0]) < 0.01) { return botBC; } else if (fabs (coord[0] - 5.0) < 0.01) { return topBC; } else { return NULL; } } virtual double initDisp (const double* coord, int f) const { double stretch = coord[f] * 0.10 - 0.25; return stretch; } virtual double initVel (const double* coord, int f) const { return 0.0; } }; #endif /* MESHINIT_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/dgmechanics/MeshInit.cpp
#include "MeshInit.h" const double TriMeshInit::PARAM[] = {1, 0, 0, 1, 0, 0 }; const double TetMeshInit::PARAM[] = { 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 }; const double MeshInit::RHO = 1.0; const double MeshInit::MU = 0.5; const double MeshInit::LAMBDA = 0.0; const int MeshInit::PID = 0; const double MeshInit::DELTA = 0.1; const double MeshInit::T_INIT = 0.0; const size_t MeshInit::MAX_FNAME = 1024; /** * * @param fileName * @param ndiv * number of times to subdivide the initial mesh */ void MeshInit::initializeMesh (const std::string& fileName, int ndiv) { FemapInput input (fileName.c_str ()); this->cc = makeCoordConn (); cc->initFromFileData (input); for (int i = 0; i < ndiv; ++i) { cc->subdivide (); } fieldsUsed.resize (numFields ()); // fileds numbered from 0..N-1 for (size_t i = 0; i < fieldsUsed.size (); ++i) { fieldsUsed[i] = i; } geomVec.clear (); elemVec.clear (); for (size_t i = 0; i < cc->getNumElements (); ++i) { Element* elem = cc->makeElem (i); elemVec.push_back(elem); geomVec.push_back (const_cast<ElementGeometry*> (&(elem->getGeometry ()))); } this->l2gMap = new StandardP1nDMap (elemVec); this->ile = new NeoHookean (LAMBDA, MU, RHO); massResidueVec.clear (); operationsVec.clear (); for (std::vector<Element*>::const_iterator i = elemVec.begin (); i != elemVec.end (); ++i) { Residue* m = new DiagonalMassForSW (*(*i), *ile, fieldsUsed); massResidueVec.push_back (m); DResidue* sw = new StressWork (*(*i), *ile, fieldsUsed); operationsVec.push_back (sw); } size_t totalDof = l2gMap->getTotalNumDof (); VecDouble massVec (totalDof, 0.0); VecDouble dofArray (totalDof, 0.0); Residue::assemble (massResidueVec, *l2gMap, dofArray, massVec); aviVec.clear (); for (size_t i = 0; i < elemVec.size (); ++i) { const Element* e = elemVec[i]; std::vector<BCFunc> bcfuncVec(getNodesPerElem ()); std::vector< std::vector<StandardAVI::BCImposedType> > itypeMat( getSpatialDim (), std::vector<StandardAVI::BCImposedType> (getNodesPerElem (), StandardAVI::ZERO)); getBCs (*e, itypeMat, bcfuncVec); // TODO: AVI init broken here AVI* avi = new StandardAVI (*l2gMap, *operationsVec[i], massVec, i, itypeMat, bcfuncVec, DELTA, T_INIT); this->aviVec.push_back (avi); assert (operationsVec[i]->getFields ().size () == fieldsUsed.size()); } this->aviWriteInterval = std::vector<size_t> (getNumElements(), 0); } void MeshInit::getBCs (const Element& e, std::vector< std::vector<BCImposedType> >& itypeMat, std::vector<BCFunc>& bcfuncVec) const { const double* param = getParam (); double* coord = new double[this->getSpatialDim ()]; for (size_t a = 0; a < getNodesPerElem (); ++a) { e.getGeometry ().map (param + this->getSpatialDim () * a, coord); BCFunc bc = getBCFunc (coord); BCImposedType itypeVal = StandardAVI::ZERO; if (bc == NULL) { itypeVal = StandardAVI::ZERO; } else { itypeVal = StandardAVI::ONE; } bcfuncVec[a] = bc; // XXX: sometimes BCFunc is NULL for (size_t i = 0; i < this->getSpatialDim (); ++i) { itypeMat[i][a] = itypeVal; } } delete[] coord; } /** * * @param avi * @param Qval * displacement * @param Vbval * velocity * @param Tval * time */ void MeshInit::writeSync (const AVI& avi, const VecDouble& Qval, const VecDouble& Vbval, const VecDouble& Tval) { // end time of the write interval for element 'avi' double interEnd = (this->aviWriteInterval[avi.getGlobalIndex ()] * this->writeInc); // when the first time update time of 'a' goes past the current write // interval // we dump some state into a file if (avi.getNextTimeStamp () > interEnd) { ++this->aviWriteInterval[avi.getGlobalIndex ()]; // if 'a' is the first to enter a new write interval // then open a new file // and also close the old file if (avi.getNextTimeStamp () > (this->writeInterval * this->writeInc)) { if (syncFileWriter != NULL) { // will be true after the first interval fclose (syncFileWriter); syncFileWriter = NULL; // being defensive ... printf ("myid = %d, done with syncfiles for interval = %d, simulation time for interval = %g\n", PID, (this->writeInterval - 1), (this->writeInterval * this->writeInc)); // TODO: measure // syncfile writing // time per interval } char syncFileName[MAX_FNAME]; sprintf(syncFileName, "sync.%d_%d.dat", this->writeInterval, PID); this->syncFileWriter = fopen (syncFileName, "w"); if (syncFileWriter == NULL) { std::cerr << "Failed to open log file for writing: " << syncFileName << std::endl; abort (); } // increment to define the end limit for the new interval. ++this->writeInterval; } assert (this->syncFileWriter != NULL); const std::vector<GlobalNodalIndex>& conn = avi.getGeometry ().getConnectivity (); for (size_t aa = 0; aa < conn.size (); ++aa) { GlobalNodalIndex nodeNum = conn[aa]; fprintf (syncFileWriter, "%zd %zd ", avi.getGlobalIndex (), nodeNum); int idx = -1; for (size_t f = 0; f < avi.getGeometry ().getEmbeddingDimension (); ++f) { idx = l2gMap->map (f, aa, avi.getGlobalIndex ()); // XXX: commented out and printing vector values instead // double pos = Qval[idx] + Vbval[idx] * (aviWriteInterval[avi.getGlobalIndex ()] * this->writeInc - Tval[idx]); // fprintf (syncFileWriter, "%12.10f ", pos); fprintf (syncFileWriter, "%12.10f ", Qval[idx]); fprintf (syncFileWriter, "%12.10f ", Vbval[idx]); } fprintf (syncFileWriter, "%12.10f \n", Tval[idx]); } } } void MeshInit::stretchInternal (VecDouble& dispOrVel, bool isVel) const { // int localsize = this->getSpatialDim () * this->getNodesPerElem () * this->elemVec.size (); double* coord = new double[this->getSpatialDim ()]; double stretch; const double* param = getParam (); for (size_t e = 0, i = 0; e < this->elemVec.size (); ++e) { for (size_t f = 0; f < this->numFields (); ++f) { for (size_t a = 0; a < this->getNodesPerElem (); ++a, ++i) { elemVec[e]->getGeometry ().map (param + this->numFields () * a, coord); if (isVel) { stretch = this->initVel (coord, f); } else { stretch = this->initDisp (coord, f); } size_t index = l2gMap->map (f, a, e); dispOrVel[index] = stretch; } } } delete[] coord; } // makes a copy of the arguments to sort them etc. bool MeshInit::computeDiffAVI (std::vector<AVI*> listA, std::vector<AVI*> listB, bool printDiff) { bool result = false; const char* nameA = "this->aviList"; const char* nameB = "that.aviList"; if (listA.size () != listB.size ()) { result = false; if (printDiff) { fprintf (stderr, "Comparing lists of different sizes, %s.size() = %zd, %s.size() = %zd\n", nameA, listA.size (), nameB, listB.size ()); } } else { // sort in increasing order of next update time AVIComparator aviCmp; std::sort (listA.begin (), listA.end (), aviCmp); std::sort (listB.begin (), listB.end (), aviCmp); result = true; for (size_t i = 0; i < listA.size (); ++i) { const AVI& aviA = *listA[i]; const AVI& aviB = *listB[i]; double diff = fabs (aviA.getTimeStamp () - aviB.getTimeStamp ()); if (diff > TOLERANCE) { result = false; if (printDiff) { fprintf (stderr, "(%s[%zd] = (id=%zd,time:%g)) != (%s[%zd]= (id=%zd,time=%g)) diff=%g\n", nameA, i, aviA.getGlobalIndex (), aviA.getTimeStamp (), nameB, i, aviB.getGlobalIndex (), aviB.getTimeStamp (), diff); } else { break; // no use continuing on if not printing } } } // end for } return result; } void MeshInit::writeMeshCenters (const char* outFileName) const { if (getSpatialDim () != 2) { std::cerr << "Mesh plotting implemented for 2D elements only" << std::endl; abort (); } FILE* plotFile = fopen (outFileName, "w"); if (plotFile == NULL) { abort (); } std::vector<double> center (getSpatialDim(), 0); fprintf (plotFile , "center_x, center_y, timestamp\n"); for (std::vector<AVI*>::const_iterator i = getAVIVec ().begin (), ei = getAVIVec ().end (); i != ei ; ++i) { const AVI& avi = **i; std::fill (center.begin (), center.end (), 0.0); avi.getElement ().getGeometry ().computeCenter (center); fprintf (plotFile, "%g, %g, %g\n", center[0], center[1], avi.getNextTimeStamp ()); } fclose (plotFile); } void MeshInit::writeMesh (const char* polyFileName, const char* coordFileName) const { FILE* polyFile = fopen (polyFileName, "w"); if (polyFile == NULL) { abort (); } for (size_t i = 0; i < cc->getNodesPerElem (); ++i) { fprintf (polyFile, "node%zd, ", i); } fprintf (polyFile , "timestamp\n"); for (std::vector<AVI*>::const_iterator i = getAVIVec ().begin (), ei = getAVIVec ().end (); i != ei ; ++i) { const AVI& avi = **i; const std::vector<GlobalNodalIndex>& conn = avi.getElement ().getGeometry ().getConnectivity (); for (size_t j = 0; j < conn.size (); ++j) { fprintf (polyFile, "%zd, ", conn[j]); } fprintf (polyFile, "%g\n", avi.getNextTimeStamp ()); } fclose (polyFile); FILE* coordFile = fopen (coordFileName, "w"); if (coordFile == NULL) { abort (); } for (size_t i = 0; i < cc->getNodesPerElem (); ++i) { fprintf (coordFile, "dim%zd", i); if (i < cc->getNodesPerElem () - 1) { fprintf (coordFile, ", "); } else { fprintf (coordFile, "\n"); } } const std::vector<double>& coord = cc->getCoordinates (); for (size_t i = 0; i < coord.size (); i += cc->getSpatialDim ()) { for (size_t j = i; j < i + cc->getSpatialDim (); ++j) { if (j != i) { // not first iter fprintf (coordFile, ", "); } fprintf (coordFile, "%g", coord[j]); } fprintf (coordFile, "\n"); } fclose (coordFile); }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/dgmechanics/CoordConn.h
/** CoordConn Represents the connectivity and coordinates of mesh -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 16, 2011 * @author M. Amber Hassaan <[email protected]> */ #ifndef COORDCONN_H_ #define COORDCONN_H_ #include "AuxDefs.h" #include "Element.h" #include "P12DElement.h" #include "P13DElement.h" #include "ElementGeometry.h" #include "Triangle.h" #include "Tetrahedron.h" #include "Femap.h" #include <cassert> #include <algorithm> #include <sstream> #include <iostream> #include <vector> #include <stdexcept> /** * This class maintains connectivity and coordinates of the mesh read from a file. * Connectivity is the ids of the nodes of each element, where nodes are numbered from * 0..numNodes-1 * Coordinates is the 2D or 3D coordinates of each node in the mesh * The elements themselves have ids 0..numElements-1 */ class CoordConn { public: CoordConn () {} virtual ~CoordConn () {} /** * Connectivity of all elements in a single vector. Let NPE = nodes per element, then connectivity of * element i is in the range [NPE*i, NPE*(i+1)) * * @return ref to vector */ virtual const std::vector<GlobalNodalIndex>& getConnectivity () const = 0; /** * Coordinates of all nodes in the mesh in a single vector. Let SPD = number of spatial dimensions * e.g. 2D or 3D, the coordinates for node i are in the range [i*SPD, (i+1)*SPD) * * @return ref to vector */ virtual const std::vector<double>& getCoordinates () const = 0; virtual size_t getSpatialDim () const = 0; virtual size_t getNodesPerElem () const = 0; /** * specific to file input format */ virtual size_t getTopology () const = 0; /** * subdivide each element into smaller elements */ virtual void subdivide () = 0; virtual void initFromFileData (const FemapInput& neu) = 0; virtual size_t getNumNodes () const = 0; virtual size_t getNumElements () const = 0; /** * helper for MeshInit * The derived class decides the kind of element and element geometry to * instantiate for each element addressed by elemIndex * * @param elemIndex * @return Element* */ virtual Element* makeElem (const size_t elemIndex) const = 0; protected: /** * populates vector elemConn with * the connectivity of element indexed by elemIndex * @see CoordConn::getConnectivity() * * @param elemIndex * @param elemConn * */ virtual void genElemConnectivity (size_t elemIndex, std::vector<GlobalNodalIndex>& elemConn) const = 0; }; /** * * Common functionality and data structures */ template <size_t SPD, size_t NODES_PER_ELEM, size_t TOPO> class AbstractCoordConn: public CoordConn { protected: std::vector<GlobalNodalIndex> connectivity; std::vector<double> coordinates; public: AbstractCoordConn (): CoordConn() { } AbstractCoordConn (const AbstractCoordConn& that): CoordConn(that), connectivity (that.connectivity), coordinates (that.coordinates) { } AbstractCoordConn& operator = (const AbstractCoordConn& that) { CoordConn::operator = (that); if (this != &that) { connectivity = that.connectivity; coordinates = that.coordinates; } return (*this); } virtual inline size_t getSpatialDim () const { return SPD; } virtual inline size_t getNodesPerElem () const { return NODES_PER_ELEM; } virtual inline size_t getTopology () const { return TOPO; } virtual const std::vector<GlobalNodalIndex>& getConnectivity () const { return connectivity; } virtual const std::vector<double>& getCoordinates () const { return coordinates; } virtual size_t getNumNodes () const { return getCoordinates ().size () / getSpatialDim (); } virtual size_t getNumElements () const { return getConnectivity ().size () / getNodesPerElem (); } virtual void initFromFileData (const FemapInput& neu) { size_t nodes = neu.getNumNodes (); size_t elements = neu.getNumElements (getTopology ()); coordinates.clear (); coordinates.resize (nodes * getSpatialDim ()); connectivity.clear (); connectivity.resize (elements * getNodesPerElem ()); transferNodes (neu); transferElements (neu); } protected: virtual void genElemConnectivity (size_t elemIndex, std::vector<GlobalNodalIndex>& conn) const { const size_t npe = getNodesPerElem (); conn.clear(); for (size_t i = 0; i < npe; ++i) { conn.push_back (connectivity[elemIndex * npe + i]); } } private: void transferNodes (const FemapInput& neu) { size_t n, d; for (n = 0; n < neu.getNumNodes (); n++) { const femapNode& nd = neu.getNode (n); for (d = 0; d < getSpatialDim (); d++) { coordinates[getSpatialDim () * n + d] = nd.x[d]; } } } void transferElements (const FemapInput& neu) { size_t i, j; for (i = 0; i < neu.getNumElements (); i++) { const femapElement& e = neu.getElement (i); if (e.topology == getTopology ()) { for (j = 0; j < getNodesPerElem (); ++j) { // changed following to make node ids start from 0. // connectivity[nodesPerElem * iv + j] = neu.getNodeId(e.node[j]) + 1; connectivity[getNodesPerElem () * i + j] = neu.getNodeId (e.node[j]); } } else { std::cerr << "Warning: topology " << e.topology << " of element " << neu.getElementId (e.id) << " is not supported for conversion to ADLIB. Skipping. " << std::endl; abort (); } } return; } }; /** * represents an edge between two mesh nodes */ struct edgestruct { size_t elemId; size_t edgeId; GlobalNodalIndex node0; GlobalNodalIndex node1; edgestruct(size_t ielem, size_t iedge, GlobalNodalIndex _node0, GlobalNodalIndex _node1) : elemId(ielem), edgeId(iedge) { // sort the args in the increasing order // can't sort fields due to const if (_node1 < _node0) { std::swap (_node0, _node1); } // sort of node id's of an edge in a consistent manner is necessary // in order to sort a list of edgestruct objects node0 = _node0; node1 = _node1; assert (node0 <= node1); } /** * ordering based on node ids * * @param that */ bool operator < (const edgestruct &that) const { // compare the nodes of the two edges int result = compare (that); return result < 0; } /** * comparison function that compares * two objects based on the node ids in the edge * Therefore it's necessary to store the node ids within an edge * in sorted order to allow lexicographic comparison * * @param that */ inline int compare (const edgestruct& that) const { int result = this->node0 - that.node0; if (result == 0) { result = this->node1 - that.node1; } return result; } }; #endif /* COORDCONN_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/dgmechanics/TetLinearCoordConn.h
/** TetLinearCoordConn represents a mesh containing linear tetrahedra -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef _TET_LINEAR_COORD_CONN_H_ #define _TET_LINEAR_COORD_CONN_H_ /** * important constants for linear tetrahedron */ struct TetLinearTraits { enum { SPD = 3, NODES_PER_ELEM = 4, TOPO = 6, NUM_EDGES = 6, NFIELDS = SPD, }; }; class TetLinearCoordConn : public AbstractCoordConn <TetLinearTraits::SPD, TetLinearTraits::NODES_PER_ELEM, TetLinearTraits::TOPO> { public: static const size_t NUM_EDGES = TetLinearTraits::NUM_EDGES; protected: /** * Return an instance of 3D with linear shape functions * and linear tetrahedron as geometry */ virtual Element* makeElem (const size_t elemIndex) const { std::vector<GlobalNodalIndex> conn; genElemConnectivity (elemIndex, conn); Tetrahedron* tetGeom = new Tetrahedron (coordinates, conn); return new P13D<TetLinearTraits::NFIELDS>::Bulk (*tetGeom); } private: /** * * @param neighbors: the output vector * for each element p, populate an indexed list L of pairs (q,j), where i is index of each pair, * such that * p shares it's i with q's edge j. * There should be a corresponding entry (p,i) in q's list at index j. * */ void getEdgeNeighborList (std::vector<std::vector<std::vector<size_t> > > &neighbors) const { size_t iElements = getNumElements (); neighbors.clear(); neighbors.resize(iElements); std::vector<edgestruct> edges; size_t V1[] = { 0, 1, 0, 2, 0, 1 }; size_t V2[] = { 1, 2, 2, 3, 3, 3 }; // the 4 nodes of a tet are numbered 0..3 // edges are 0-1, 0-2, 0-3, 1-2, 1-3, 2-3 // the nodes corresponding to edges are picked up in an involved manner using two arrays V1 and V2 // the edges must be sorted in a consistent manner, due to which the nodes in an edge must be // sorted. // Creating a list of all possible edges. for (size_t e = 0; e < iElements; e++) { neighbors[e].resize(NUM_EDGES); const size_t econn[] = { connectivity[e * 4 + 0], connectivity[e * 4 + 1], connectivity[e * 4 + 2], connectivity[e * 4 + 3] }; for (size_t edgenum = 0; edgenum < NUM_EDGES; edgenum++) { GlobalNodalIndex node0; GlobalNodalIndex node1; node0 = econn[V1[edgenum]]; node1 = econn[V2[edgenum]]; edgestruct myedge(e, edgenum, node0, node1); edges.push_back(myedge); } } std::sort(edges.begin(), edges.end()); // Edges that have exactly the same connectivity should appear consecutively. // If there is no repetition, the edgeId is free. std::vector<edgestruct>::iterator it1 = edges.begin(); while (it1 != edges.end()) { std::vector<edgestruct> repedges; repedges.clear(); repedges.push_back(*it1); std::vector<edgestruct>::iterator it2 = it1 + 1; while (true && it2 != edges.end()) { // check for same connectivity if ((it2->node0 == it1->node0) && (it2->node1 == it1->node1)) { repedges.push_back(*it2); it2++; } else { break; } } if (repedges.size() > 1) { // Shared edgeId. for (size_t p = 0; p < repedges.size(); p++) { for (size_t q = 0; q < repedges.size(); q++) { if (p != q) { neighbors[repedges[p].elemId][repedges[p].edgeId]. push_back(repedges[q].elemId); neighbors[repedges[p].elemId][repedges[p].edgeId]. push_back(repedges[q].edgeId); } } } } it1 = it2; } // done. } public: /** * Purpose : Subdivide a tetrahedron in 8 smaller ones. * Algorithm to subdivide a test: * Parent tet: ABCD. * Since a consistent numbering of edges is crucial, the following convention * is adopted : 1 - AB, 2-BC, 3-CA, 4-CD, 5-AD, 6-BD. * Midpoints of edges AB,BC,CA,CD,AD,BD are M1, M2, M3, M4, M5, M6 resply. * Tet1: A-M1-M3-M5, * Tet2: M1-B-M2-M6, * Tet3: M3-M2-C-M4, * Tet4: M5-M6-M4-D, * Tet5: M1-M4-M5-M6, * Tet6: M1-M4-M6-M2, * Tet7: M1-M4-M2-M3, * Tet8: M1-M4-M3-M5. */ virtual void subdivide () { size_t sd = getSpatialDim(); size_t eNodes = getNodesPerElem(); // Number of nodes per element. size_t iElements = getNumElements(); // Number of elements. size_t iNodes = getNumNodes(); std::vector<std::vector<std::vector<size_t> > > neighbors; getEdgeNeighborList(neighbors); // Connectivity for mid-points of each edgeId for each element. // size_t midconn[iElements][NUM_EDGES]; std::vector<std::vector<size_t> > midconn (iElements); for (size_t i = 0; i < midconn.size (); ++i) { midconn[i].resize (NUM_EDGES); } size_t count = iNodes; for (size_t e = 0; e < iElements; e++) { for (size_t f = 0; f < NUM_EDGES; f++) { // Number of elements sharing edgeId 'f' of element 'e'. size_t nNeighbors = neighbors[e][f].size() / 2; if (nNeighbors == 0) { // Free edgeId. // for 0-based node numbering we increment 'count' afterwards // count++; midconn[e][f] = count; ++count; } else { // Shared edgeId // Find the least element neighbor number. size_t minElem = e; for (size_t p = 0; p < nNeighbors; p++) { if (minElem > neighbors[e][f][2 * p]) { minElem = neighbors[e][f][2 * p]; } } if (e == minElem) { // Allot only once for a shared edgeId. // for 0-based node numbering we increment 'count' afterwards // count++; midconn[e][f] = count; for (size_t p = 0; p < nNeighbors; p++) { size_t nelem = neighbors[e][f][2 * p]; size_t nedge = neighbors[e][f][2 * p + 1]; midconn[nelem][nedge] = count; } // increment 'count' now ++count; } } } } // Creating new coordinates and connectivity arrays: // Each tet is subdivided into 8. std::vector<double> newCoord(count * sd); std::vector<size_t> newConn; for (size_t i = 0; i < coordinates.size(); i++) { newCoord[i] = coordinates[i]; } // Coordinates for midside nodes: size_t V1[] = { 0, 1, 0, 2, 0, 1 }; size_t V2[] = { 1, 2, 2, 3, 3, 3 }; for (size_t e = 0; e < iElements; e++) for (size_t f = 0; f < NUM_EDGES; f++) { // for 0-based node numbering, we don't need to subtract 1 from node ids in connectivity // size_t v1 = connectivity[e * eNodes + V1[f]] - 1; // size_t v2 = connectivity[e * eNodes + V2[f]] - 1; // for (size_t k = 0; k < sd; k++) // newCoord[(midconn[e][f] - 1) * sd + k] = 0.5 * (coordinates[v1 * sd + k] + coordinates[v2 * sd + k]); size_t v1 = connectivity[e * eNodes + V1[f]]; size_t v2 = connectivity[e * eNodes + V2[f]]; for (size_t k = 0; k < sd; k++) { newCoord[midconn[e][f] * sd + k] = 0.5 * (coordinates[v1 * sd + k] + coordinates[v2 * sd + k]); } } for (size_t e = 0; e < iElements; e++) { // tet 1-8 // four at conrners size_t t1conn[] = { connectivity[e * eNodes + 0], midconn[e][0], midconn[e][2], midconn[e][4] }; size_t t2conn[] = { midconn[e][0], connectivity[e * eNodes + 1], midconn[e][1], midconn[e][5] }; size_t t3conn[] = { midconn[e][2], midconn[e][1], connectivity[e * eNodes + 2], midconn[e][3] }; size_t t4conn[] = { midconn[e][4], midconn[e][5], midconn[e][3], connectivity[e * eNodes + 3] }; // four in the middle size_t t5conn[] = { midconn[e][0], midconn[e][3], midconn[e][4], midconn[e][5] }; size_t t6conn[] = { midconn[e][0], midconn[e][3], midconn[e][5], midconn[e][1] }; size_t t7conn[] = { midconn[e][0], midconn[e][3], midconn[e][1], midconn[e][2] }; size_t t8conn[] = { midconn[e][0], midconn[e][3], midconn[e][2], midconn[e][4] }; newConn.insert (newConn.end (), &t1conn[0], &t1conn[eNodes]); newConn.insert (newConn.end (), &t2conn[0], &t2conn[eNodes]); newConn.insert (newConn.end (), &t3conn[0], &t3conn[eNodes]); newConn.insert (newConn.end (), &t4conn[0], &t4conn[eNodes]); newConn.insert (newConn.end (), &t5conn[0], &t5conn[eNodes]); newConn.insert (newConn.end (), &t6conn[0], &t6conn[eNodes]); newConn.insert (newConn.end (), &t7conn[0], &t7conn[eNodes]); newConn.insert (newConn.end (), &t8conn[0], &t8conn[eNodes]); } coordinates.clear(); connectivity.clear(); coordinates.assign(newCoord.begin(), newCoord.end()); connectivity.assign(newConn.begin(), newConn.end()); // nodes = size_t(coordinates.size() / 3); // elements = size_t(connectivity.size() / 4); } }; #endif // _TET_LINEAR_COORD_CONN_H_
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/femap/FemapData.h
/** * FemapData.h: Contains data structures that store data from Femap Neutral file format * DG++ * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ struct femapMaterial { size_t id; size_t type; size_t subtype; std::string title; int bval[10]; int ival[25]; double mval[200]; }; struct femapProperty { size_t id; size_t matId; size_t type; std::string title; int flag[4]; int num_val; std::vector<double> value; }; struct femapNode { size_t id; //! coordinates double x[3]; int permBc[6]; }; struct femapElement { size_t id; size_t propId; size_t type; size_t topology; size_t geomId; int formulation; // int is a guess--documentation doesn't give type std::vector<size_t> node; }; struct constraint { size_t id; bool dof[6]; int ex_geom; }; struct femapConstraintSet { size_t id; std::string title; std::vector<constraint> nodalConstraint; }; struct load { size_t id; size_t type; int dof_face[3]; double value[3]; bool is_expanded; }; struct femapLoadSet { size_t id; std::string title; double defTemp; bool tempOn; bool gravOn; bool omegaOn; double grav[6]; double origin[3]; double omega[3]; std::vector<load> loads; }; struct groupRule { size_t type; size_t startID; size_t stopID; size_t incID; size_t include; }; struct groupList { size_t type; std::vector<size_t> entityID; }; struct femapGroup { size_t id; short int need_eval; std::string title; int layer[2]; int layer_method; std::vector<groupRule> rules; std::vector<groupList> lists; };
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/femap/Femap.h
/** * Femap.h: Classes for parsing and writing Femap Neutral file format * DG++ * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _FEMAP_H #define _FEMAP_H #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> // #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> #include "FemapData.h" class Femap { public: size_t getNumMaterials() const { return _materials.size(); } size_t getNumProperties() const { return _properties.size(); } size_t getNumNodes() const { return _nodes.size(); } size_t getNumElements() const { return _elements.size(); } //! no. of elements with topology indicator t //! @param t size_t getNumElements(size_t t) const ; size_t getNumConstraintSets() const { return _constraintSets.size(); } size_t getNumLoadSets() const { return _loadSets.size(); } size_t getNumGroups() const { return _groups.size(); } const std::vector<femapMaterial>& getMaterials() const { return _materials; } const std::vector<femapProperty>& getProperties() const { return _properties; } const std::vector<femapNode>& getNodes() const { return _nodes; } const std::vector<femapElement>& getElements() const { return _elements; } const std::vector<femapConstraintSet>& getConstraintSets() const { return _constraintSets; } const std::vector<femapLoadSet>& getLoadSets() const { return _loadSets; } const std::vector<femapGroup>& getGroups() const { return _groups; } //! get elements with topology indicator t //! @param t //! @param vout: output vector void getElements(size_t t, std::vector<femapElement>& vout) const ; // gets elements with topology t const femapMaterial& getMaterial(size_t i) const { return _materials[i]; } const femapProperty& getProperty(size_t i) const { return _properties[i]; } const femapNode& getNode(size_t i) const { return _nodes[i]; } const femapElement& getElement(size_t i) const { return _elements[i]; } const femapConstraintSet& getConstraintSet(size_t i) const { return _constraintSets[i]; } const femapLoadSet& getLoadSet(size_t i) const { return _loadSets[i]; } const femapGroup& getGroup(size_t i) const { return _groups[i]; } int getMaterialId(size_t i) const { return _materialIdMap.at (i); } int getPropertyId(size_t i) const { return _propertyIdMap.at (i); } int getNodeId(size_t i) const { return _nodeIdMap.at (i); } int getElementId(size_t i) const { return _elementIdMap.at (i); } int getConstraintSetId(size_t i) const { return _constraintSetIdMap.at (i); } int getLoadSetId(size_t i) const { return _loadSetIdMap.at (i); } int getGroupId(size_t i) const { return _groupIdMap.at (i); } protected: std::vector<femapMaterial> _materials; std::vector<femapProperty> _properties; std::vector<femapNode> _nodes; std::vector<femapElement> _elements; std::vector<femapGroup> _groups; std::vector<femapConstraintSet> _constraintSets; std::vector<femapLoadSet> _loadSets; std::map<size_t,size_t> _materialIdMap; std::map<size_t,size_t> _propertyIdMap; std::map<size_t,size_t> _nodeIdMap; std::map<size_t,size_t> _elementIdMap; std::map<size_t,size_t> _groupIdMap; std::map<size_t,size_t> _constraintSetIdMap; std::map<size_t,size_t> _loadSetIdMap; private: }; class FemapInput : public Femap { public: FemapInput(const char* fileName); private: boost::iostreams::filtering_istream _ifs; // std::ifstream _ifs; void _readHeader(); void _readProperty(); void _readNodes(); void _readElements(); void _readGroups(); void _readConstraints(); void _readLoads(); void _readMaterial(); // MO 1/9/01 begin //void nextLine(int=1); void nextLine(int); void nextLine(); // MO 1/9/01 end }; class FemapOutput : public Femap { public: FemapOutput(const char* fileName) : _ofs(fileName) {} private: std::ofstream _ofs; }; #endif //_FEMAP_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMeshInit/femap/Femap.cpp
#include "Femap.h" // // FemapInput::FemapInput(const char* fileName) // Constructor. Opens input file and checks to make sure it worked. // Searches for "-1" indicator, identifies following record, // and calls appropriate function to deal with the record. // FemapInput::FemapInput(const char* fileName) : _ifs() { std::ifstream gzfile (fileName, std::ios_base::in | std::ios_base::binary); _ifs.push (boost::iostreams::gzip_decompressor ()); _ifs.push (gzfile); if (_ifs) { std::cout << std::endl << "Femap Neutral file " << fileName << " is open for input." << std::endl << std::endl; } else { std::cerr << "Cannot open Femap Neutral file " << fileName << ". Quitting\n"; exit(1); } std::string s; int id; for ( _ifs >> s; ( _ifs >> id ) && ( s == "-1" ) ; _ifs >> s ) { nextLine(); switch ( id ) { case 100: _readHeader(); break; //case 402: _readProperty(); break; case 403: _readNodes(); break; case 404: _readElements(); break; //case 408: _readGroups(); break; //case 506: _readConstraints(); break; case 507: _readLoads(); break; //case 601: _readMaterial(); break; case 999: break; default: //std::cout << "Skipping Data Block " << id << ". Not supported.\n"; do { getline( _ifs, s ); s.assign(s,0,5); } while ( s != " -1" ); } } std::cout << "\nDone reading Neutral File input. Closing file " << fileName << ".\n\n"; return; } // // FemapInput::_readHeader() // Called for Data Block ID 100. // Reads Neutral File Header and prints to stdout // void FemapInput::_readHeader() { std::string s; _ifs >> s; if (s=="<NULL>") s=""; std::cout << "Database Title: " << s <<std::endl; _ifs >> s; std::cout << "Created with version: " << s <<std::endl; _ifs >> s; if (s!="-1") { std::cerr << "Too many records in Data Block 100.\n"; while (s!="-1") _ifs >> s; } return; } // // FemapInput::_readProperty() // void FemapInput::_readProperty() { std::string s, sdumm; std::cout << "Reading Properties.\n"; femapProperty p; // read prop id, etc. getline( _ifs, s ); do{ sscanf(s.c_str(), "%zd,%*d,%zd,%zd,%*d,%*d", &(p.id), &(p.matId), &(p.type)); // read & print title _ifs >> p.title; if (p.title=="<NULL>") p.title=""; std::cout << "Id: " << p.id << " Title: " << p.title << std::endl; nextLine(); // read flag[0,3] getline( _ifs, s ); sscanf(s.c_str(), "%d,%d,%d,%d", p.flag, p.flag+1, p.flag+2, p.flag+3); // skip laminate data int i; _ifs >> i; nextLine(); nextLine(i/8); if (i%8) nextLine(); // get # of prop values & size value std::vector accordingly _ifs >> p.num_val; p.value.resize(p.num_val); // get values nextLine(); for (i=0; i<p.num_val; i++) { char dumm; _ifs >> p.value[i]; _ifs >> dumm; } // read num_outline int num_outline; _ifs >> num_outline; nextLine(); // skip outline point definitions nextLine(num_outline); _properties.push_back(p); _propertyIdMap[p.id] = _properties.size() - 1; // Look for more properties getline( _ifs, s ); } while ( sdumm.assign(s,0,5) != " -1" ); return; } // // FemapInput::_readNodes() // void FemapInput::_readNodes() { std::string s; std::cout << "Reading Nodes.\n"; femapNode n; getline( _ifs, s ); while ( sscanf(s.c_str(), "%zd,%*d,%*d,%*d,%*d,%d,%d,%d,%d,%d,%d,%lg,%lg,%lg,%*d,", &(n.id), &(n.permBc[0]), &(n.permBc[1]), &(n.permBc[2]), &(n.permBc[3]), &(n.permBc[4]), &(n.permBc[5]), &(n.x[0]), &(n.x[1]), &(n.x[2]) ) == 10 ) { _nodes.push_back(n); _nodeIdMap[n.id] = _nodes.size() - 1; getline( _ifs, s ); } std::cout << "Read " << _nodes.size() << " nodes.\n" << std::flush; return; } // // FemapInput::_readElements() // void FemapInput::_readElements() { std::string s; std::cout << "Reading Elements.\n"; int nd[20]; getline( _ifs, s ); int id, propId, type, topology, geomId, formulation; while ( sscanf(s.c_str(), "%d,%*d,%d,%d,%d,%*d,%*d,%*d,%d,%d,%*d,%*d,", &(id), &(propId), &(type), &(topology), &(geomId), &(formulation) ) == 6 ) { femapElement e; e.id = id; e.propId = propId; e.type = type; e.topology = topology; e.geomId = geomId; e.formulation = formulation; getline( _ifs, s ); sscanf(s.c_str(), "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,", &(nd[0]),&(nd[1]),&(nd[2]),&(nd[3]),&(nd[4]), &(nd[5]),&(nd[6]),&(nd[7]),&(nd[8]),&(nd[9]) ); getline( _ifs, s ); sscanf(s.c_str(), "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,", &(nd[10]),&(nd[11]),&(nd[12]),&(nd[13]),&(nd[14]), &(nd[15]),&(nd[16]),&(nd[17]),&(nd[18]),&(nd[19]) ); for (int i = 0; i < 20; i++ ) if ( nd[i] != 0 ) e.node.push_back( nd[i] ); nextLine(3); getline( _ifs, s ); int flg[4]; sscanf(s.c_str(), "%*d,%*d,%*d,%*d,%*d,%*d,%*d,%*d,%*d,%*d,%*d,%*d,%d,%d,%d,%d,", &(flg[0]), &(flg[1]), &(flg[2]), &(flg[3]) ); if ( flg[0]!=0 || flg[1]!=0 || flg[2]!=0 || flg[3]!=0 ) { std::cerr << "Unexpected node lists attatched to element " << e.id << ". Quitting.\n"; exit(-1); } _elements.push_back(e); _elementIdMap[e.id] = _elements.size() - 1; getline( _ifs, s ); } std::cout << "Read " << _elements.size() << " elements.\n"; return; } // // FemapInput::_readConstraints() // void FemapInput::_readConstraints() { std::cout << "Reading Constraints.\n"; std::string s; femapConstraintSet cs; _ifs >> cs.id; if ( static_cast<long> (cs.id) != -1 ) { _ifs >> cs.title; const size_t NDOF = 6; int dofread[NDOF]; constraint c; getline( _ifs, s ); while ( sscanf(s.c_str(), "%zd,%*d,%*d,%d,%d,%d,%d,%d,%d,%d", &(c.id), &(dofread[0]), &(dofread[1]), &(dofread[2]), &(dofread[3]), &(dofread[4]), &(dofread[5]), &(c.ex_geom) ) == 8 && static_cast<long> (c.id) != -1 ) { for (size_t i = 0; i < NDOF; ++i) { c.dof[i] = !(dofread[i] == 0); // 0 -> false, non-zero -> true } cs.nodalConstraint.push_back(c); } _constraintSets.push_back(cs); } // skip other types of constraints (geom., etc.) do { getline( _ifs, s ); s.assign(s,0,5); } while ( s != " -1" ); return; } // // FemapInput::_readLoads() // void FemapInput::_readLoads() { std::cout << "Reading Loads.\n"; std::string s; femapLoadSet ls; //_ifs >> ls.id; getline( _ifs, s ); sscanf( s.c_str(), "%zd,", &(ls.id) ); if ( static_cast<long> (ls.id) != -1 ) { getline( _ifs, ls.title ); std::cout << ls.title << std::endl << std::flush; getline( _ifs, s ); int tempOn_int, gravOn_int, omegaOn_int; sscanf(s.c_str(), "%*d,%lg,%d,%d,%d,", &(ls.defTemp),&(tempOn_int),&(gravOn_int),&(omegaOn_int) ); ls.tempOn = !(tempOn_int == 0); // 0-> false, non-zero -> true ls.gravOn = !(gravOn_int == 0); // 0-> false, non-zero -> true ls.omegaOn = !(omegaOn_int == 0); // 0-> false, non-zero -> true getline( _ifs, s ); sscanf(s.c_str(), "%lg,%lg,%lg,", &(ls.grav[0]), &(ls.grav[1]), &(ls.grav[2]) ); getline( _ifs, s ); sscanf(s.c_str(), "%lg,%lg,%lg,", &(ls.grav[3]), &(ls.grav[4]), &(ls.grav[5]) ); getline( _ifs, s ); sscanf(s.c_str(), "%lg,%lg,%lg,", &(ls.origin[0]), &(ls.origin[1]), &(ls.origin[2]) ); getline( _ifs, s ); sscanf(s.c_str(), "%lg,%lg,%lg,", &(ls.omega[0]), &(ls.omega[1]), &(ls.omega[2]) ); nextLine(14); // skip some junk we won't use int id, type, exp; getline( _ifs, s ); sscanf( s.c_str(), "%d,%d,%*d,%*d,%*d,%*d,%d,", &id, &type, &exp ); while ( id != -1 ) { load l; l.id = id; l.type = type; l.is_expanded = exp; getline( _ifs, s ); sscanf(s.c_str(), "%d,%d,%d", &(l.dof_face[0]), &(l.dof_face[1]), &(l.dof_face[2]) ); getline( _ifs, s ); sscanf(s.c_str(), "%lg,%lg,%lg,%*g,%*g,", &(l.value[0]), &(l.value[1]), &(l.value[2]) ); nextLine(4); ls.loads.push_back(l); getline( _ifs, s ); sscanf( s.c_str(), "%d,%d,%*d,%*d,%*d,%*d,%d,", &id, &type, &exp ); } _loadSets.push_back(ls); } // skip geometry-based and non-structural loads do { getline( _ifs, s ); s.assign(s,0,5); } while ( s != " -1" ); return; } // // FemapInput::_readMaterial() // void FemapInput::_readMaterial() { std::string s, sdumm; //temporary string int i; std::cout << "Reading Materials.\n"; femapMaterial m; int functioncount; // read mat id, etc. getline( _ifs, s ); do{ sscanf( s.c_str(), "%zd,%*d,%*d,%zd,%zd,%*d,%d", &(m.id), &(m.type), &(m.subtype), &functioncount); // read & print title _ifs >> m.title; if (m.title=="<NULL>") m.title=""; std::cout << "Id: " << m.id << " Title: " << m.title << std::endl; nextLine(2); // get bval[0,9] getline( _ifs, s ); sscanf(s.c_str(), "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", &(m.bval[0]), &(m.bval[1]), &(m.bval[2]), &(m.bval[3]), &(m.bval[4]), &(m.bval[5]), &(m.bval[6]), &(m.bval[7]), &(m.bval[8]), &(m.bval[9])); nextLine(); // get ival[0,24]; 2 rows of 10 and 1 row of 5. for (i=0; i<2; i++) { getline( _ifs, s ); sscanf(s.c_str(), "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", &(m.ival[10*i+0]), &(m.ival[10*i+1]), &(m.ival[10*i+2]), &(m.ival[10*i+3]), &(m.ival[10*i+4]), &(m.ival[10*i+5]), &(m.ival[10*i+6]), &(m.ival[10*i+7]), &(m.ival[10*i+8]), &(m.ival[10*i+9])); } getline( _ifs, s ); sscanf(s.c_str(), "%d,%d,%d,%d,%d", &(m.ival[10*i+0]),&(m.ival[10*i+1]), &(m.ival[10*i+2]),&(m.ival[10*i+3]),&(m.ival[10*i+4])); nextLine(); // get mval[0,199]; 20 rows of 10. for (i=0; i<20; i++) { getline( _ifs, s ); sscanf(s.c_str(), "%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg,%lg", &(m.mval[10*i+0]), &(m.mval[10*i+1]), &(m.mval[10*i+2]), &(m.mval[10*i+3]), &(m.mval[10*i+4]), &(m.mval[10*i+5]), &(m.mval[10*i+6]), &(m.mval[10*i+7]), &(m.mval[10*i+8]), &(m.mval[10*i+9])); } // skip function data nextLine(14+functioncount); _materials.push_back(m); _materialIdMap[m.id] = _materials.size() - 1; // Look for more materials getline( _ifs, s ); } while ( sdumm.assign(s,0,5) != " -1" ); return; } // // FemapInput::_readGroups() // void FemapInput::_readGroups () { std::string s; std::cout << "Reading Groups." << std::endl << std::flush; int id, need_eval; getline (_ifs, s); sscanf (s.c_str (), "%d,%d,%*d,", &id, &need_eval); while (id != -1) { femapGroup g; g.id = id; g.need_eval = need_eval; getline (_ifs, g.title); std::cout << g.title << std::endl << std::flush; getline (_ifs, s); sscanf (s.c_str (), "%d,%d,%d,", &(g.layer[0]), &(g.layer[1]), &(g.layer_method)); nextLine (20); // skip clipping info // read group rules size_t max; getline (_ifs, s); sscanf (s.c_str (), "%zd,", &max); getline (_ifs, s); groupRule r; sscanf (s.c_str (), "%zd,", &(r.type)); while (static_cast<long> (r.type) != -1) { if (r.type < max) { getline (_ifs, s); sscanf (s.c_str (), "%zd,%zd,%zd,%zd,", &(r.startID), &(r.stopID), &(r.incID), &(r.include)); while (static_cast<long> (r.startID) != -1) { g.rules.push_back (r); getline (_ifs, s); sscanf (s.c_str (), "%zd,%zd,%zd,%zd,", &(r.startID), &(r.stopID), &(r.incID), &(r.include)); } } else nextLine (); getline (_ifs, s); sscanf (s.c_str (), "%zd,", &(r.type)); } // read group lists getline (_ifs, s); sscanf (s.c_str (), "%zd,", &max); groupList l; getline (_ifs, s); sscanf (s.c_str (), "%zd,", &(l.type)); while (static_cast<long> (l.type) != -1) { if (l.type < max) { getline (_ifs, s); sscanf (s.c_str (), "%d,", &id); while (id != -1) { l.entityID.push_back (id); getline (_ifs, s); sscanf (s.c_str (), "%d,", &id); } g.lists.push_back (l); } else { nextLine (); } getline (_ifs, s); sscanf (s.c_str (), "%zd,", &(l.type)); } _groups.push_back (g); _groupIdMap[g.id] = _groups.size () - 1; getline (_ifs, s); sscanf (s.c_str (), "%d,%d,%*d,", &id, &need_eval); } // do { getline( _ifs, s ); s.assign(s,0,5); } // while ( s != " -1" ); return; } // MO 1/9/01 begin /* inline void FemapInput::nextLine(int n=1) { std::string s; for (int i = 0; i < n; i++) getline( _ifs, s ); return; } */ inline void FemapInput::nextLine(int n) { std::string s; for (int i = 0; i < n; i++) { getline( _ifs, s ); } return; } inline void FemapInput::nextLine() { std::string s; getline( _ifs, s ); return; } // MO 1/9/01 end size_t Femap::getNumElements(size_t t) const { size_t n = 0; for (std::vector<femapElement>::const_iterator e = _elements.begin(); e != _elements.end(); e++ ) { if ( e->topology == t ) { n++; } } return n; } void Femap::getElements (size_t t, std::vector<femapElement>& vout) const { for (std::vector<femapElement>::const_iterator e = _elements.begin(); e != _elements.end(); e++ ) { if ( e->topology == t ) { vout.push_back(*e); } } }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIodgOrdered.cpp
/* * Created on: Jun 21, 2011 * Author: amber */ #include "AVIodgOrdered.h" int main (int argc, char* argv[]) { AVIodgOrdered um; um.run(argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIodgExplicit.h
/** AVI unordered algorithm with abstract locks -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef AVI_ODG_EXPLICIT_H #define AVI_ODG_EXPLICIT_H #include "Galois/Atomic.h" #include "Galois/Accumulator.h" #include "Galois/Galois.h" #include "Galois/Graph/Graph.h" #include "Galois/Graph/LCGraph.h" #include "Galois/Runtime/PerThreadStorage.h" #include "Galois/WorkList/WorkList.h" #include <string> #include <sstream> #include <limits> #include <iostream> #include <fstream> #include <set> #include <utility> #include <cassert> #include "AuxDefs.h" #include "AVI.h" #include "Element.h" #include "AVIabstractMain.h" /** * * Unordered AVI algorithm uses two key data structures * * 1) Element Adjacency Graph * 2) in degree vector * * This graph has a node for each mesh element and * keeps track of node-adjacency between AVI elements. Two elements * are adjacent if they share a node in the mesh between them. * We create a graph by connecting adjacent elements with an edge. * Conceptually the edge is directed from the avi element with smaller * time stamp to the greater one. But in implementation this direction information * is not kept in the graph but in an array 'inDegVec', which has an entry corresponding * to each AVI element. * An avi element with 0 in edges has the minimum time stamp among its neighbors * and is therefore eligible for an update * It is assumed that AVI elements have unique integer id's 0..numElements-1, and * the id is used to index into inDegVec * */ //#define USE_LC_GRAPH class AVIodgExplicit: public AVIabstractMain { protected: static const bool DEBUG = false; #ifdef USE_LC_GRAPH typedef Galois::Graph::LC_CSR_Graph<AVI*, void> Graph; typedef Graph::GraphNode GNode; #else typedef Galois::Graph::FirstGraph<AVI*, void, false> Graph; typedef Graph::GraphNode GNode; #endif Graph graph; virtual const std::string getVersion () const { return "ODG explicit, abstract locks on ODG nodes"; } /** * Generate element adjacency graph, where nodes are elements * in the mesh, and there is an edge between the nodes if their * corresponding elements share a vertex in the mesh * * @param meshInit * @param g */ void genElemAdjGraph (const MeshInit& meshInit, const GlobalVec& g) { #ifdef USE_LC_GRAPH typedef Galois::Graph::FirstGraph<AVI*, void, false> MGraph; typedef MGraph::GraphNode MNode; MGraph mgraph; #else Graph& mgraph = graph; typedef GNode MNode; #endif std::vector<MNode> aviAdjNodes; const std::vector<AVI*>& aviList = meshInit.getAVIVec (); for (std::vector<AVI*>::const_iterator i = aviList.begin (), e = aviList.end (); i != e; ++i) { AVI* avi = *i; MNode gn = mgraph.createNode (avi); mgraph.addNode (gn); aviAdjNodes.push_back (gn); } // map where // key is node id // value is a list of avi elements that share this node std::vector< std::vector<MNode> > nodeSharers(meshInit.getNumNodes ()); // for (int i = 0; i < nodeSharers.size (); ++i) { // nodeSharers[i] = new ArrayList<GNode<AVIAdjNode>> (); // } for (std::vector<MNode>::const_iterator i = aviAdjNodes.begin (), ei = aviAdjNodes.end (); i != ei; ++i) { MNode aviAdjN = *i; AVI* avi = mgraph.getData (aviAdjN, Galois::MethodFlag::NONE); const std::vector<GlobalNodalIndex>& conn = avi->getGeometry ().getConnectivity (); for (std::vector<GlobalNodalIndex>::const_iterator j = conn.begin (), ej = conn.end (); j != ej; ++j) { GlobalNodalIndex n = *j; nodeSharers[n].push_back (aviAdjN); } } int numEdges = 0; for (std::vector< std::vector<MNode> >::const_iterator it = nodeSharers.begin (), ei = nodeSharers.end (); it != ei; ++it) { const std::vector<MNode>& adjElms = *it; // adjElms is the list of elements who share the node with id == current index pos in the array // and therefore form a clique among themselves for (size_t i = 0; i < adjElms.size (); ++i) { // populate the upper triangle of the adj matrix for (size_t j = i + 1; j < adjElms.size (); ++j) { // if (!adjElms[i].hasNeighbor (adjElms[j])) { if (mgraph.findEdge(adjElms[i], adjElms[j]) == mgraph.edge_end(adjElms[i])) { ++numEdges; } mgraph.addEdge (adjElms[i], adjElms[j]); } } } #ifdef USE_LC_GRAPH graph.copyFromGraph (mgraph); #endif printf ("Graph created with %u nodes and %d edges\n", graph.size (), numEdges); } virtual void initRemaining (const MeshInit& meshInit, const GlobalVec& g) { Galois::StatTimer t_graph ("Time spent in creating the graph: "); t_graph.start (); genElemAdjGraph (meshInit, g); t_graph.stop (); } //! Functor for loop body struct Process { Graph& graph; std::vector<int>& inDegVec; MeshInit& meshInit; GlobalVec& g; Galois::Runtime::PerThreadStorage<LocalVec>& perIterLocalVec; bool createSyncFiles; IterCounter& iter; Process ( Graph& graph, std::vector<int>& inDegVec, MeshInit& meshInit, GlobalVec& g, Galois::Runtime::PerThreadStorage<LocalVec>& perIterLocalVec, bool createSyncFiles, IterCounter& iter): graph (graph), inDegVec (inDegVec), meshInit (meshInit), g (g), perIterLocalVec (perIterLocalVec), createSyncFiles (createSyncFiles), iter (iter) {} /** * Loop body * * The loop body uses one-shot optimization, where we grab abstract locks on the node * and its neighbors before performing the udpates. This removes the need for saving * and performing undo operations. * * * @param src is active elemtn * @param lwl is the worklist handle */ template <typename ContextTy> void operator () (GNode& src, ContextTy& lwl) { // one-shot optimization: acquire abstract locks on active node and // neighbors (all its neighbors, in this case) before performing any modifications AVI* srcAVI = graph.getData (src, Galois::MethodFlag::CHECK_CONFLICT); for (Graph::edge_iterator e = graph.edge_begin (src, Galois::MethodFlag::CHECK_CONFLICT) , ende = graph.edge_end (src, Galois::MethodFlag::CHECK_CONFLICT); e != ende; ++e) { } // past the fail-safe point now int inDeg = inDegVec[srcAVI->getGlobalIndex ()]; // assert inDeg == 0 : String.format ("active node %s with inDeg = %d\n", srcAVI, inDeg); // // TODO: DEBUG // std::cout << "Processing element: " << srcAVI->toString() << std::endl; assert (inDeg == 0); LocalVec& l = *perIterLocalVec.getLocal(); AVIabstractMain::simulate(srcAVI, meshInit, g, l, createSyncFiles); // update the inEdges count and determine // which neighbor is at local minimum and needs to be added to the worklist for (Graph::edge_iterator e = graph.edge_begin (src, Galois::MethodFlag::NONE) , ende = graph.edge_end (src, Galois::MethodFlag::NONE); e != ende; ++e) { const GNode& dst = graph.getEdgeDst (e); AVI* dstAVI = graph.getData (dst, Galois::MethodFlag::NONE); if (AVIComparator::compare (srcAVI, dstAVI) > 0) { // if srcAVI has a higher time stamp that dstAVI ++inDegVec[srcAVI->getGlobalIndex ()]; int din = (--inDegVec[dstAVI->getGlobalIndex ()] ); if (din == 0) { // dstAVI has become minimum among its neighbors if (dstAVI->getNextTimeStamp () < meshInit.getSimEndTime ()) { lwl.push (dst); } } } } // end for if (inDegVec[srcAVI->getGlobalIndex ()] == 0) { // srcAVI is still the minimum among its neighbors if (srcAVI->getNextTimeStamp () < meshInit.getSimEndTime ()) { lwl.push (src); } } iter += 1; // if (iter.get () == 5000) { // meshInit.writeMesh (); // meshInit.plotMeshCenters (); // } } }; template <typename T> void initWorkList (std::vector<GNode>& initWL, std::vector<T>& inDegVec) { Galois::StatTimer t_wl ("Time to populate the worklist"); t_wl.start (); for (Graph::iterator i = graph.begin (), e = graph.end (); i != e; ++i) { const GNode& src = *i; AVI* srcAVI = graph.getData (src, Galois::MethodFlag::NONE); // calculate the in degree of src by comparing it against its neighbors for (Graph::edge_iterator e = graph.edge_begin (src, Galois::MethodFlag::NONE), ende = graph.edge_end (src, Galois::MethodFlag::NONE); e != ende; ++e) { GNode dst = graph.getEdgeDst (e); AVI* dstAVI = graph.getData (dst, Galois::MethodFlag::NONE); if (AVIComparator::compare (srcAVI, dstAVI) > 0) { ++inDegVec[srcAVI->getGlobalIndex ()]; } } // if src is less than all its neighbors then add to initWL if (inDegVec[srcAVI->getGlobalIndex ()] == 0) { initWL.push_back (src); } } t_wl.stop (); printf ("Initial worklist contains %zd elements\n", initWL.size ()); } public: virtual void runLoop (MeshInit& meshInit, GlobalVec& g, bool createSyncFiles) { ///////////////////////////////////////////////////////////////// // populate an initial worklist ///////////////////////////////////////////////////////////////// std::vector<int> inDegVec(meshInit.getNumElements (), 0); std::vector<GNode> initWL; initWorkList (initWL, inDegVec); // // TODO: DEBUG // std::cout << "Initial Worklist = " << std::endl; // for (size_t i = 0; i < initWL.size (); ++i) { // std::cout << graph.getData (initWL[i], Galois::MethodFlag::NONE)->toString () << ", "; // } // std::cout << std::endl; ///////////////////////////////////////////////////////////////// // perform the simulation ///////////////////////////////////////////////////////////////// // uncomment to plot the mesh meshInit.writeMesh (); // meshInit.plotMeshCenters (); writeAdjacencyGraph (meshInit, graph); // temporary matrices size_t nrows = meshInit.getSpatialDim (); size_t ncols = meshInit.getNodesPerElem(); Galois::Runtime::PerThreadStorage<LocalVec> perIterLocalVec; for (unsigned int i = 0; i < perIterLocalVec.size(); ++i) *perIterLocalVec.getRemote(i) = LocalVec(nrows, ncols); IterCounter iter; Process p(graph, inDegVec, meshInit, g, perIterLocalVec, createSyncFiles, iter); Galois::for_each(initWL.begin (), initWL.end (), p, Galois::wl<AVIWorkList>()); printf ("iterations = %zd\n", iter.reduce ()); } static void writeAdjacencyGraph (const MeshInit& meshInit, Graph& graph, const char* nodesFileName="mesh-nodes.csv", const char* edgesFileName="mesh-edges.csv") { if (meshInit.getSpatialDim () != 2) { std::cerr << "implemented for 2D elements only" << std::endl; abort (); } FILE* nodesFile = fopen (nodesFileName, "w"); if (nodesFile == NULL) { abort (); } fprintf (nodesFile, "nodeId, inDeg, outDeg, centerX, centerY, timeStamp\n"); // a set of edges computed by picking outgoing edges for each node std::vector<std::pair<GNode, GNode> > outEdges; std::vector<double> center (meshInit.getSpatialDim(), 0.0); for (Graph::iterator i = graph.begin (), e = graph.end (); i != e; ++i) { const GNode& src = *i; AVI* srcAVI = graph.getData (src, Galois::MethodFlag::NONE); size_t inDeg = 0; // calculate the in degree of src by comparing it against its neighbors for (Graph::edge_iterator e = graph.edge_begin (src, Galois::MethodFlag::NONE) , ende = graph.edge_end (src, Galois::MethodFlag::NONE); e != ende; ++e) { GNode dst = graph.getEdgeDst (e); AVI* dstAVI = graph.getData (dst, Galois::MethodFlag::NONE); if (AVIComparator::compare (srcAVI, dstAVI) > 0) { ++inDeg; } else { // is an out-going edge outEdges.push_back (std::make_pair(src, dst)); } } // size_t outDeg = graph.neighborsSize(src, Galois::MethodFlag::NONE) - inDeg; size_t outDeg = std::distance (graph.edge_begin (src, Galois::MethodFlag::NONE), graph.edge_end (src, Galois::MethodFlag::NONE)); std::fill (center.begin (), center.end (), 0.0); srcAVI->getElement ().getGeometry ().computeCenter (center); fprintf (nodesFile, "%zd, %zd, %zd, %g, %g, %g\n", srcAVI->getGlobalIndex(), inDeg, outDeg, center[0], center[1], srcAVI->getNextTimeStamp()); } fclose (nodesFile); FILE* edgesFile = fopen (edgesFileName, "w"); if (edgesFile == NULL) { abort (); } fprintf (edgesFile, "srcId, dstId\n"); for (std::vector<std::pair<GNode, GNode> >::const_iterator i = outEdges.begin(), ei = outEdges.end(); i != ei; ++i) { size_t srcId = graph.getData (i->first, Galois::MethodFlag::NONE)->getGlobalIndex (); size_t dstId = graph.getData (i->second, Galois::MethodFlag::NONE)->getGlobalIndex (); fprintf (edgesFile, "%zd, %zd\n", srcId, dstId); } fclose (edgesFile); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIodgExplicitNoLock.h
/** AVI unordered algorithm with no abstract locks -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef AVI_UNORDERED_NO_LOCK_H_ #define AVI_UNORDERED_NO_LOCK_H_ #include "Galois/Graph/Graph.h" #include "Galois/Graph/FileGraph.h" #include "Galois/Galois.h" #include "Galois/Atomic.h" #include "Galois/Runtime/PerThreadStorage.h" #include <string> #include <sstream> #include <limits> #include <iostream> #include <fstream> #include <set> #include <cassert> #include "AuxDefs.h" #include "AVI.h" #include "Element.h" #include "AVIabstractMain.h" #include "AVIodgExplicit.h" /** * AVI unordered algorithm that uses atomic integers * and no abstract locks */ class AVIodgExplicitNoLock: public AVIodgExplicit { typedef Galois::GAtomicPadded<int> AtomicInteger; protected: virtual const std::string getVersion () const { return "ODG explicit, no abstract locks"; } /** * Functor for loop body */ struct Process { Graph& graph; std::vector<AtomicInteger>& inDegVec; MeshInit& meshInit; GlobalVec& g; Galois::Runtime::PerThreadStorage<LocalVec>& perIterLocalVec; bool createSyncFiles; IterCounter& iter; Process ( Graph& graph, std::vector<AtomicInteger>& inDegVec, MeshInit& meshInit, GlobalVec& g, Galois::Runtime::PerThreadStorage<LocalVec>& perIterLocalVec, bool createSyncFiles, IterCounter& iter): graph (graph), inDegVec (inDegVec), meshInit (meshInit), g (g), perIterLocalVec (perIterLocalVec), createSyncFiles (createSyncFiles), iter (iter) {} /** * Loop body * * The key condition is that a node and its neighbor cannot be active at the same time, * and it must be impossible for two of them to be processed in parallel * Therefore a node can add its newly active neighbors to the workset as the last step only when * it has finished performing all other updates. *(As per current semantics of for_each, adds to worklist * happen on commit. If this is not the case, then each thread should * accumulate adds in a temp vec and add to the worklist all together in the * end) * For the same reason, active node src must update its own in degree before updating the * indegree of any of the neighbors. Imagine the alternative, where active node updates its in * degree and that of it's neighbor in the same loop. For example A is current active node and * has a neighbor B. A > B, therefore A increments its own in degree and decrements that of B to * 1. Another active node C is neighbor of B but not of A, and C decreases in degree of B to 0 * and adds B to the workset while A is not finished yet. This violates our key condition * mentioned above * * @param gn is active elemtn * @param lwl is the worklist handle * @param avi is the avi object */ template <typename C> GALOIS_ATTRIBUTE_PROF_NOINLINE void addToWL (C& lwl, const GNode& gn, AVI* avi) { assert (graph.getData (gn, Galois::MethodFlag::NONE) == avi); if (avi->getNextTimeStamp () < meshInit.getSimEndTime ()) { lwl.push (gn); } } template <typename C> GALOIS_ATTRIBUTE_PROF_NOINLINE void updateODG (const GNode& src, AVI* srcAVI, C& lwl) { unsigned addAmt = 0; for (Graph::edge_iterator e = graph.edge_begin (src, Galois::MethodFlag::NONE) , ende = graph.edge_end (src, Galois::MethodFlag::NONE); e != ende; ++e) { GNode dst = graph.getEdgeDst (e); AVI* dstAVI = graph.getData (dst, Galois::MethodFlag::NONE); if (AVIComparator::compare (srcAVI, dstAVI) > 0) { ++addAmt; } } // may be the active node is still at the local minimum // and no updates to neighbors are necessary if (addAmt == 0) { addToWL (lwl, src, srcAVI); } else { inDegVec[srcAVI->getGlobalIndex ()] += addAmt; for (Graph::edge_iterator e = graph.edge_begin (src, Galois::MethodFlag::NONE) , ende = graph.edge_end (src, Galois::MethodFlag::NONE); e != ende; ++e) { GNode dst = graph.getEdgeDst (e); AVI* dstAVI = graph.getData (dst, Galois::MethodFlag::NONE); if (AVIComparator::compare (srcAVI, dstAVI) > 0) { int din = --inDegVec[dstAVI->getGlobalIndex ()]; assert (din >= 0); if (din == 0) { addToWL (lwl, dst, dstAVI); // // TODO: DEBUG // std::cout << "Adding: " << dstAVI->toString () << std::endl; } } } // end for } // end else } template <typename ContextTy> void operator () (const GNode& src, ContextTy& lwl) { AVI* srcAVI = graph.getData (src, Galois::MethodFlag::NONE); int inDeg = (int)inDegVec[srcAVI->getGlobalIndex ()]; // assert inDeg == 0 : String.format ("active node %s with inDeg = %d\n", srcAVI, inDeg); // // TODO: DEBUG // std::cout << "Processing element: " << srcAVI->toString() << std::endl; assert (inDeg == 0); LocalVec& l = *perIterLocalVec.getLocal(); AVIabstractMain::simulate(srcAVI, meshInit, g, l, createSyncFiles); // update the inEdges count and determine // which neighbor is at local minimum and needs to be added to the worklist updateODG (src, srcAVI, lwl); // for debugging, remove later iter += 1; } }; public: /** * For the in degree vector, we use a vector of atomic integers * This along with other changes in the loop body allow us to * no use abstract locks. @see Process */ virtual void runLoop (MeshInit& meshInit, GlobalVec& g, bool createSyncFiles) { ///////////////////////////////////////////////////////////////// // populate an initial worklist ///////////////////////////////////////////////////////////////// std::vector<AtomicInteger> inDegVec(meshInit.getNumElements (), AtomicInteger (0)); std::vector<GNode> initWL; initWorkList (initWL, inDegVec); // // TODO: DEBUG // std::cout << "Initial Worklist = " << std::endl; // for (size_t i = 0; i < initWL.size (); ++i) { // std::cout << graph.getData (initWL[i], Galois::MethodFlag::NONE)->toString () << ", "; // } // std::cout << std::endl; ///////////////////////////////////////////////////////////////// // perform the simulation ///////////////////////////////////////////////////////////////// // temporary matrices size_t nrows = meshInit.getSpatialDim (); size_t ncols = meshInit.getNodesPerElem(); Galois::Runtime::PerThreadStorage<LocalVec> perIterLocalVec; for (unsigned int i = 0; i < perIterLocalVec.size(); ++i) *perIterLocalVec.getRemote(i) = LocalVec(nrows, ncols); IterCounter iter; Process p (graph, inDegVec, meshInit, g, perIterLocalVec, createSyncFiles, iter); Galois::for_each(initWL.begin (), initWL.end (), p, Galois::wl<AVIWorkList>()); printf ("iterations = %zd\n", iter.reduce ()); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIodgExplicitNoLock.cpp
/* * AVIodgExplicitNoLock.cpp * * Created on: Jun 21, 2011 * Author: amber */ #include "AVIodgExplicitNoLock.h" int main (int argc, char* argv[]) { AVIodgExplicitNoLock um; um.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/GlobalVec.h
/** Global vectors for functions being computed over the mesh -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 20, 2011 * @author M. Amber Hassaan <[email protected]> */ #ifndef GLOBALVEC_H_ #define GLOBALVEC_H_ #include "AuxDefs.h" #include <vector> #include <cstdio> #include <cmath> struct GlobalVec { //! Global vectors computed for each mesh node //! Q is displacement //! V is velocity, V_b is half step value //! T is time VecDouble vecQ; VecDouble vecV; VecDouble vecV_b; VecDouble vecT; VecDouble vecLUpdate; //! @param totalNDOF is total number of Mesh nodes times the dimensionality GlobalVec (unsigned int totalNDOF) { vecQ = VecDouble (totalNDOF, 0.0); vecV = VecDouble (vecQ); vecV_b = VecDouble (vecQ); vecT = VecDouble (vecQ); vecLUpdate = VecDouble (vecQ); } private: static bool computeDiff (const VecDouble& vecA, const char* nameA, const VecDouble& vecB, const char* nameB, bool printDiff) { bool result = false; if (vecA.size () != vecB.size ()) { if (printDiff) { fprintf (stderr, "Arrays of different length %s.size () = %zd, %s.size () = %zd\n", nameA, vecA.size (), nameB, vecB.size ()); } result = false; } else { result = true; // start optimistically :) for (size_t i = 0; i < vecA.size (); ++i) { double diff = fabs (vecA[i] - vecB[i]); if ( diff > TOLERANCE) { result = false; if (printDiff) { fprintf (stderr, "(%s[%zd] = %g) != (%s[%zd] = %g), diff=%g\n", nameA, i, vecA[i], nameB, i, vecB[i], diff); } else { break; // no use continuing on if not printing diff; } } } } return result; } bool computeDiffInternal (const GlobalVec& that, bool printDiff) const { return true && computeDiff (this->vecQ, "this->vecQ", that.vecQ, "that.vecQ", printDiff) && computeDiff (this->vecV, "this->vecV", that.vecV, "that.vecV", printDiff) && computeDiff (this->vecV_b, "this->vecV_b", that.vecV_b, "that.vecV_b", printDiff) && computeDiff (this->vecT, "this->vecT", that.vecT, "that.vecT", printDiff) && computeDiff (this->vecLUpdate, "this->vecLUpdate", that.vecLUpdate, "that.vecLUpdate", printDiff); } public: /** * compare the values of global vectors element by element * * @param that */ bool cmpState (const GlobalVec& that) const { return computeDiffInternal (that, false); } /** compare the values of global vector element by element * and print the differences * * @param that */ void printDiff (const GlobalVec& that) const { computeDiffInternal (that, true); } }; #endif /* GLOBALVEC_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIodgOrdered.h
/** AVI a version without explicit ODG using deterministic infrastructure -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef AVI_ODG_ORDERED_H #define AVI_ODG_ORDERED_H #include "Galois/Galois.h" #include "Galois/Runtime/PerThreadStorage.h" #include "Galois/WorkList/WorkList.h" #include <boost/iterator/transform_iterator.hpp> #include <string> #include <sstream> #include <limits> #include <iostream> #include <fstream> #include <set> #include <utility> #include <cassert> #include "AuxDefs.h" #include "AVI.h" #include "Element.h" #include "AVIabstractMain.h" enum ExecType { useAddRem, useTwoPhase, }; static cll::opt<ExecType> execType ( cll::desc ("Ordered Executor Type:"), cll::values ( clEnumVal(useAddRem, "Use Add-Remove executor"), clEnumVal(useTwoPhase, "Use Two-Phase executor"), clEnumValEnd), cll::init (useAddRem)); class AVIodgOrdered: public AVIabstractMain { protected: typedef Galois::Graph::FirstGraph<void*,void,true> Graph; typedef Graph::GraphNode Lockable; typedef std::vector<Lockable> Locks; Graph graph; Locks locks; virtual const std::string getVersion() const { return "Parallel version, ODG automatically managed"; } virtual void initRemaining(const MeshInit& meshInit, const GlobalVec& g) { assert(locks.empty()); locks.reserve(meshInit.getNumNodes()); for (int i = 0; i < meshInit.getNumNodes(); ++i) { locks.push_back(graph.createNode(nullptr)); } } struct Update { AVI* avi; double ts; Update(AVI* a, double t): avi(a), ts(t) { } Update updatedCopy () const { return Update (avi, avi->getNextTimeStamp ()); } friend std::ostream& operator << (std::ostream& out, const Update& up) { return (out << "(id:" << up.avi->getGlobalIndex() << ", ts:" << up.ts << ")"); } }; struct Comparator { bool operator() (const Update& a, const Update& b) const { int c = DoubleComparator::compare (a.ts, b.ts); if (c == 0) { c = a.avi->getGlobalIndex () - b.avi->getGlobalIndex (); } return (c < 0); } }; struct MakeUpdate: public std::unary_function<AVI*,Update> { Update operator()(AVI* avi) const { return Update(avi, avi->getNextTimeStamp ()); } }; struct NhoodVisit { Graph& graph; Locks& locks; NhoodVisit(Graph& g, Locks& l): graph(g), locks(l) { } template <typename C> void operator()(const Update& item, C&) { typedef std::vector<GlobalNodalIndex> V; const V& conn = item.avi->getGeometry().getConnectivity(); for (V::const_iterator ii = conn.begin(), ei = conn.end(); ii != ei; ++ii) { graph.getData(locks[*ii]); } } }; struct NhoodVisitAddRem: public NhoodVisit { typedef int tt_has_fixed_neighborhood; NhoodVisitAddRem (Graph& g, Locks& l): NhoodVisit (g, l) {} }; struct Process { MeshInit& meshInit; GlobalVec& g; Galois::Runtime::PerThreadStorage<LocalVec>& perIterLocalVec; bool createSyncFiles; IterCounter& niter; Process( MeshInit& meshInit, GlobalVec& g, Galois::Runtime::PerThreadStorage<LocalVec>& perIterLocalVec, bool createSyncFiles, IterCounter& niter): meshInit(meshInit), g(g), perIterLocalVec(perIterLocalVec), createSyncFiles(createSyncFiles), niter(niter) { } void operator()(const Update& item, Galois::UserContext<Update>& ctx) { // for debugging, remove later niter += 1; LocalVec& l = *perIterLocalVec.getLocal(); AVIabstractMain::simulate(item.avi, meshInit, g, l, createSyncFiles); if (item.avi->getNextTimeStamp() < meshInit.getSimEndTime()) { ctx.push(item.updatedCopy ()); } } }; public: virtual void runLoop(MeshInit& meshInit, GlobalVec& g, bool createSyncFiles) { const size_t nrows = meshInit.getSpatialDim(); const size_t ncols = meshInit.getNodesPerElem(); Galois::Runtime::PerThreadStorage<LocalVec> perIterLocalVec; for (unsigned int i = 0; i < perIterLocalVec.size(); ++i) *perIterLocalVec.getRemote(i) = LocalVec(nrows, ncols); IterCounter niter; NhoodVisit nhVisitor(graph, locks); NhoodVisitAddRem nhVisitorAddRem (graph, locks); Process p(meshInit, g, perIterLocalVec, createSyncFiles, niter); const std::vector<AVI*>& elems = meshInit.getAVIVec(); switch (execType) { case useAddRem: Galois::for_each_ordered ( boost::make_transform_iterator(elems.begin(), MakeUpdate()), boost::make_transform_iterator(elems.end(), MakeUpdate()), Comparator(), nhVisitorAddRem, p); break; case useTwoPhase: Galois::for_each_ordered ( boost::make_transform_iterator(elems.begin(), MakeUpdate()), boost::make_transform_iterator(elems.end(), MakeUpdate()), Comparator(), nhVisitor, p); break; default: GALOIS_ERROR(true, "Unknown executor type"); break; } printf("iterations = %lu\n", niter.reduce()); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/LocalVec.h
/** Per AVI element local vectors -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 20, 2011 * @author M. Amber Hassaan <[email protected]> */ #ifndef LOCALVEC_H_ #define LOCALVEC_H_ #include "AuxDefs.h" #include "StandardAVI.h" #include <vector> struct LocalVec { typedef StandardAVI::BCImposedType BCImposedType; //! initial state as read from GlobalVec using gather MatDouble q; MatDouble v; MatDouble vb; MatDouble ti; //! updated state computed using initial state MatDouble qnew; MatDouble vnew; MatDouble vbnew; MatDouble vbinit; MatDouble tnew; //! some temporaries so that we don't need to allocate memory in every iteration MatDouble forcefield; MatDouble funcval; MatDouble deltaV; /** * * @param nrows * @param ncols */ LocalVec (size_t nrows=0, size_t ncols=0) { q = MatDouble (nrows, VecDouble (ncols, 0.0)); v = MatDouble (q); vb = MatDouble (q); ti = MatDouble (q); qnew = MatDouble (q); vnew = MatDouble (q); vbnew = MatDouble (q); vbinit = MatDouble (q); tnew = MatDouble (q); forcefield = MatDouble (q); funcval = MatDouble (q); deltaV = MatDouble (q); } }; #endif /* LOCALVEC_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIodgExplicit.cpp
/* * AVIodgExplicit.cpp * * Created on: Jun 21, 2011 * Author: amber */ #include "AVIodgExplicit.h" int main (int argc, char* argv[]) { AVIodgExplicit um; um.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIorderedSerial.cpp
/* * AVIorderedSerial.cpp * * Created on: Jun 21, 2011 * Author: amber */ #include "AVIabstractMain.h" int main (int argc, char* argv[]) { AVIorderedSerial serial; serial.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/main/AVIabstractMain.h
/** Common code for different AVI algorithms -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef AVI_ABSTRACT_MAIN_H_ #define AVI_ABSTRACT_MAIN_H_ #include <vector> #include <string> #include <exception> #include <iostream> #include <sstream> #include <vector> #include <string> #include <queue> #include <cassert> #include <cstdlib> #include <cstdio> #include "AVI.h" #include "MeshInit.h" #include "GlobalVec.h" #include "LocalVec.h" #include "Galois/Accumulator.h" #include "Galois/Galois.h" #include "Galois/Graph/Graph.h" #include "Galois/Statistic.h" #include "Galois/Runtime/Sampling.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" namespace cll = llvm::cl; static cll::opt<std::string> fileNameOpt("f", cll::desc("<input mesh file>"), cll::Required); static cll::opt<int> spDimOpt("d", cll::desc("spatial dimensionality of the problem i.e. 2 for 2D, 3 for 3D"), cll::init(2)); static cll::opt<int> ndivOpt("n", cll::desc("number of times the mesh should be subdivided"), cll::init(0)); static cll::opt<double> simEndTimeOpt("e", cll::desc("simulation end time"), cll::init(1.0)); static const char* name = "Asynchronous Variational Integrators"; static const char* desc = "Performs elasto-dynamic simulation of a mesh with minimal number of simulation updates"; static const char* url = "asynchronous_variational_integrators"; /** * Common functionality for different versions and algorithms */ class AVIabstractMain { private: // TODO: add support for verifying from a file struct InputConfig { std::string fileName; int spDim; int ndiv; double simEndTime; std::string verifile; std::string wltype; InputConfig (const std::string& fileName, int spDim, int ndiv, double simEndTime, const std::string& verifile, std::string w) :fileName (fileName), spDim (spDim), ndiv (ndiv), simEndTime (simEndTime), verifile (verifile), wltype(w) { } }; private: static const std::string getUsage (); static InputConfig readCmdLine (); static MeshInit* initMesh (const InputConfig& input); static void initGlobalVec (const MeshInit& meshInit, GlobalVec& g); protected: static const int CHUNK_SIZE = 32; typedef Galois::WorkList::dChunkedFIFO<CHUNK_SIZE> AVIWorkList; typedef Galois::GAccumulator<size_t> IterCounter; std::string wltype; /** version name */ virtual const std::string getVersion () const = 0; /** * To be implemented by derived classes for some type specific initialization * e.g. unordered needs element adjacency graph * while ordered needs a lock per node of the original mesh. * @param meshInit * @param g */ virtual void initRemaining (const MeshInit& meshInit, const GlobalVec& g) = 0; public: /** * * @param meshInit * @param g * @param createSyncFiles */ virtual void runLoop (MeshInit& meshInit, GlobalVec& g, bool createSyncFiles) = 0; /** * The main method to call * @param argc * @param argv */ void run (int argc, char* argv[]); void verify (const InputConfig& input, const MeshInit& meshInit, const GlobalVec& g) const; /** * Code common to loop body of different versions * Performs the updates to avi parameter * * @param avi * @param meshInit * @param g * @param l * @param createSyncFiles */ inline static void simulate (AVI* avi, MeshInit& meshInit, GlobalVec& g, LocalVec& l, bool createSyncFiles); virtual ~AVIabstractMain() { } }; /** * Serial ordered AVI algorithm */ class AVIorderedSerial: public AVIabstractMain { protected: virtual const std::string getVersion () const { return std::string ("Serial"); } virtual void initRemaining (const MeshInit& meshInit, const GlobalVec& g) { // Nothing to do, so far } public: virtual void runLoop (MeshInit& meshInit, GlobalVec& g, bool createSyncFiles); }; AVIabstractMain::InputConfig AVIabstractMain::readCmdLine () { const char* fileName = fileNameOpt.c_str(); int spDim = spDimOpt; int ndiv = ndivOpt; double simEndTime = simEndTimeOpt; std::string wltype; return InputConfig (fileName, spDim, ndiv, simEndTime, "", wltype); } MeshInit* AVIabstractMain::initMesh (const AVIabstractMain::InputConfig& input) { MeshInit* meshInit = NULL; if (input.spDim == 2) { meshInit = new TriMeshInit (input.simEndTime); } else if (input.spDim == 3) { meshInit = new TetMeshInit (input.simEndTime); } else { std::cerr << "ERROR: Wrong spatical dimensionality, run with -help" << std::endl; std::cerr << spDimOpt.HelpStr << std::endl; std::abort (); } // read in the mesh from file and setup the mesh, bc etc meshInit->initializeMesh (input.fileName, input.ndiv); return meshInit; } void AVIabstractMain::initGlobalVec (const MeshInit& meshInit, GlobalVec& g) { if (meshInit.isWave ()) { meshInit.setupVelocities (g.vecV); meshInit.setupVelocities (g.vecV_b); } else { meshInit.setupDisplacements (g.vecQ); } } void AVIabstractMain::run (int argc, char* argv[]) { Galois::StatManager sm; LonestarStart(argc, argv, name, desc, url); // print messages e.g. version, input etc. InputConfig input = readCmdLine (); wltype = input.wltype; MeshInit* meshInit = initMesh (input); GlobalVec g(meshInit->getTotalNumDof ()); const std::vector<AVI*>& aviList = meshInit->getAVIVec (); for (size_t i = 0; i < aviList.size (); ++i) { assert (aviList[i]->getOperation ().getFields ().size () == meshInit->getSpatialDim()); } initGlobalVec (*meshInit, g); // derived classes may have some data to initialze before running the loop initRemaining (*meshInit, g); printf ("PAVI %s version\n", getVersion ().c_str ()); printf ("input mesh: %d elements, %d nodes\n", meshInit->getNumElements (), meshInit->getNumNodes ()); Galois::StatTimer t; t.start (); Galois::Runtime::beginSampling (); // don't write to files when measuring time runLoop (*meshInit, g, false); Galois::Runtime::endSampling (); t.stop (); if (!skipVerify) { verify (input, *meshInit, g); } delete meshInit; } void AVIabstractMain::verify (const InputConfig& input, const MeshInit& meshInit, const GlobalVec& g) const { if (input.verifile == ("")) { AVIorderedSerial* serial = new AVIorderedSerial (); MeshInit* serialMesh = initMesh (input); GlobalVec sg(serialMesh->getTotalNumDof ()); initGlobalVec (*serialMesh, sg); // do write to sync files when verifying serial->runLoop (*serialMesh, sg, true); // compare the global vectors for equality (within some tolerance) bool gvecCmp = g.cmpState (sg); // compare the final state of avi elements in the mesh bool aviCmp = meshInit.cmpState (*serialMesh); if (!gvecCmp || !aviCmp) { g.printDiff (sg); meshInit.printDiff (*serialMesh); std::cerr << "BAD: results don't match against Serial" << std::endl; abort (); } std::cout << ">>> OK: result verified against serial" << std::endl; delete serialMesh; delete serial; } else { std::cerr << "TODO: cmp against file data needs implementation" << std::endl; abort (); } } void AVIabstractMain::simulate (AVI* avi, MeshInit& meshInit, GlobalVec& g, LocalVec& l, bool createSyncFiles) { if (createSyncFiles) { meshInit.writeSync (*avi, g.vecQ, g.vecV_b, g.vecT); } const LocalToGlobalMap& l2gMap = meshInit.getLocalToGlobalMap(); avi->gather (l2gMap, g.vecQ, g.vecV, g.vecV_b, g.vecT, l.q, l.v, l.vb, l.ti); avi->computeLocalTvec (l.tnew); if (avi->getTimeStamp () == 0.0) { avi->vbInit (l.q, l.v, l.vb, l.ti, l.tnew, l.qnew, l.vbinit, l.forcefield, l.funcval, l.deltaV); avi->update (l.q, l.v, l.vbinit, l.ti, l.tnew, l.qnew, l.vnew, l.vbnew, l.forcefield, l.funcval, l.deltaV); } else { avi->update (l.q, l.v, l.vb, l.ti, l.tnew, l.qnew, l.vnew, l.vbnew, l.forcefield, l.funcval, l.deltaV); } avi->incTimeStamp (); avi->assemble (l2gMap, l.qnew, l.vnew, l.vbnew, l.tnew, g.vecQ, g.vecV, g.vecV_b, g.vecT, g.vecLUpdate); } void AVIorderedSerial::runLoop (MeshInit& meshInit, GlobalVec& g, bool createSyncFiles) { typedef std::priority_queue<AVI*, std::vector<AVI*>, AVIReverseComparator> PQ; // typedef std::set<AVI*, AVIComparator> PQ; // temporary matrices int nrows = meshInit.getSpatialDim (); int ncols = meshInit.getNodesPerElem (); LocalVec l(nrows, ncols); const std::vector<AVI*>& aviList = meshInit.getAVIVec (); for (size_t i = 0; i < aviList.size (); ++i) { assert (aviList[i]->getOperation ().getFields ().size () == meshInit.getSpatialDim()); } PQ pq; for (std::vector<AVI*>::const_iterator i = aviList.begin (), e = aviList.end (); i != e; ++i) { pq.push (*i); // pq.insert (*i); } int iter = 0; while (!pq.empty ()) { AVI* avi = pq.top (); pq.pop (); // AVI* avi = *pq.begin (); pq.erase (pq.begin ()); assert (avi != NULL); AVIabstractMain::simulate (avi, meshInit, g, l, createSyncFiles); if (avi->getNextTimeStamp () < meshInit.getSimEndTime ()) { pq.push (avi); // pq.insert (avi); } ++iter; } // printf ("iterations = %d, time taken (in ms) = %d, average time per iter = %g\n", iter, time, ((double)time)/iter); printf ("iterations = %d\n", iter); } #endif // AVI_ABSTRACT_MAIN_H_
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/ElementalOperation.cpp
/* * ElementalOperation.cpp * DG++ * * Created by Adrian Lew on 10/25/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cmath> #include <vector> #include <algorithm> #include "util.h" #include "ElementalOperation.h" bool DResidue::consistencyTest(const DResidue & DRes, const std::vector<size_t> & DofPerField, const MatDouble &argval) { size_t NFields = DRes.getFields().size(); MatDouble largval(argval); MatDouble funcval; MatDouble funcvalplus; MatDouble funcvalminus; FourDVecDouble dfuncval; FourDVecDouble dfuncvalnum; const double EPS = 1.e-6; dfuncvalnum.resize(NFields); for (size_t f = 0; f < NFields; f++) { dfuncvalnum[f].resize(DofPerField[f]); for (size_t a = 0; a < DofPerField[f]; a++) { dfuncvalnum[f][a].resize(NFields); for (size_t g = 0; g < NFields; g++) { dfuncvalnum[f][a][g].resize(DofPerField[g]); } } } double maxval = 0; for (size_t f = 0; f < NFields; f++) { for (size_t a = 0; a < DofPerField[f]; a++) { if (maxval > fabs(argval[f][a])) { maxval = fabs(argval[f][a]); } } } maxval += 1; for (size_t f = 0; f < NFields; f++) { for (size_t a = 0; a < DofPerField[f]; a++) { double ival = largval[f][a]; largval[f][a] = ival + EPS * maxval; DRes.getVal(largval, funcvalplus); largval[f][a] = ival - EPS * maxval; DRes.getVal(largval, funcvalminus); largval[f][a] = ival; for (size_t g = 0; g < NFields; g++) { for (size_t b = 0; b < DofPerField[g]; b++) { dfuncvalnum[g][b][f][a] = (funcvalplus[g][b] - funcvalminus[g][b]) / (2 * EPS * maxval); } } } } DRes.getDVal(largval, funcval, dfuncval); double error = 0; double norm = 0; for (size_t f = 0; f < dfuncval.size(); f++) { for (size_t a = 0; a < dfuncval[f].size(); a++) { for (size_t g = 0; g < dfuncval[f][a].size(); g++) { for (size_t b = 0; b < dfuncval[f][a][g].size(); b++) { error += pow(dfuncval[f][a][g][b] - dfuncvalnum[f][a][g][b], 2); norm += pow(dfuncval[f][a][g][b], 2); } } } } error = sqrt(error); norm = sqrt(norm); if (error / norm > EPS * 100) { std::cerr << "DResidue::ConsistencyTest. DResidue not consistent\n"; std::cerr << "norm: " << norm << " error: " << error << "\n"; return false; } return true; } enum AssembleMode { RESIDUE, DRESIDUE, }; template<typename T> static bool _Assemble(std::vector<T *> &DResArray, const LocalToGlobalMap & L2G , const VecDouble & Dofs, VecDouble& ResVec, MatDouble& DResMat, const AssembleMode& mode) { // VecZeroEntries(*ResVec); std::fill (ResVec.begin(), ResVec.end (), 0.0 ); if (mode == DRESIDUE) { // MatZeroEntries(DResMat); for (MatDouble::iterator i = DResMat.begin (); i != DResMat.end (); ++i) { std::fill (i->begin(), i->end (), 0.0); } } MatDouble argval; MatDouble funcval; FourDVecDouble dfuncval; // double * GDofs; // VecGetArray(Dofs, &GDofs); const VecDouble& GDofs = Dofs; for (size_t e = 0; e < DResArray.size(); e++) { const std::vector<size_t> & DPF = DResArray[e]->getFields(); size_t localsize = 0; if (argval.size() < DPF.size()) { argval.resize(DPF.size()); } for (size_t f = 0; f < DPF.size(); f++) { if (argval[f].size() < DResArray[e]->getFieldDof(f)) { argval[f].resize(DResArray[e]->getFieldDof(f)); } localsize += DResArray[e]->getFieldDof(f); for (size_t a = 0; a < DResArray[e]->getFieldDof(f); a++) { argval[f][a] = GDofs[L2G.map(f, a, e)]; } } if (mode == DRESIDUE) { // I am using a dynamic_cast to prevent writing two versions of essentially the // same code, one for residue and another for dresidue. However, I think that there is // a flaw in the abstraction, since I cannot apparently do it with polymorphism here. DResidue * dr = dynamic_cast<DResidue *> (DResArray[e]); if (dr) { if (!dr->getDVal(argval, funcval, dfuncval)) { std::cerr << "ElementalOperation.cpp::Assemble Error in residual computation\n"; return false; } } else { std::cerr << "ElementalOperation.cpp::Assemble Error. Attempted to compute" " derivatives of a non-dresidue type\n"; return false; } } else if (!DResArray[e]->getVal(argval, funcval)) { std::cerr << "ElementalOperation.cpp::Assemble Error in residual computation\n"; return false; } #ifdef DEBUG std::cout << "Assemble:: element " << e << std::endl; for (size_t f = 0; f < DPF.size (); ++f) { printIter (std::cout, funcval[f].begin(), funcval[f].end()); } #endif double * resvals = new double[localsize]; size_t * indices = new size_t[localsize]; double * dresvals; if (mode == DRESIDUE) { dresvals = new double[localsize * localsize]; } for (size_t f = 0, i = 0, j = 0; f < DPF.size(); f++) { for (size_t a = 0; a < DResArray[e]->getFieldDof(f); a++, i++) { resvals[i] = funcval[f][a]; indices[i] = L2G.map(f, a, e); if (mode == DRESIDUE) for (size_t g = 0; g < DPF.size(); g++) for (size_t b = 0; b < DResArray[e]->getFieldDof(g); b++, j++) dresvals[j] = dfuncval[f][a][g][b]; } } // signature (Vec, size_of_indices, size_t indices[], double[] vals, Mode) // VecSetValues(*ResVec, localsize, indices, resvals, ADD_VALUES); for (size_t i = 0; i < localsize; ++i) { ResVec[indices[i]] += resvals[i]; } if (mode == DRESIDUE) { // signature (Mat, nrows_of_indices, size_t row_indices[], ncols_of_indices, size_t col_indices[], // double vals[], Mode) // algo // for i in 0..nrows { // for j in 0..ncols { // Mat[row_indices[i]][col_indices[j] += or = vals[ncols * i + j]; // MatSetValues(*DResMat, localsize, indices, localsize, indices, dresvals, ADD_VALUES); for (size_t i = 0; i < localsize; ++i) { for (size_t j = 0; j < localsize; ++j) { DResMat[ indices[i] ][ indices[j] ] += dresvals [localsize * i + j]; } } } delete[] resvals; delete[] indices; if (mode == DRESIDUE) { delete[] dresvals; } } // VecRestoreArray(Dofs, &GDofs); return true; } bool Residue::assemble(std::vector<Residue *> &ResArray, const LocalToGlobalMap & L2G, const VecDouble & Dofs, VecDouble& ResVec) { MatDouble d; return _Assemble<Residue> (ResArray, L2G, Dofs, ResVec, d, RESIDUE); } bool DResidue::assemble(std::vector<DResidue *> &DResArray, const LocalToGlobalMap & L2G, const VecDouble & Dofs, VecDouble& ResVec, MatDouble& DResMat) { return _Assemble<DResidue> (DResArray, L2G, Dofs, ResVec, DResMat, DRESIDUE); }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/ElementalOperation.h
/** * ElementalOperation.h * DG++ * * Created by Adrian Lew on 10/25/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ELEMENTALOPERATION #define ELEMENTALOPERATION #include <vector> #include <iostream> #include <cstdlib> #include "AuxDefs.h" #include "Element.h" #include "Material.h" /** \brief Computes a residue on an element A Residue object computes the values of a vector function of some or all the fields in the element, with the distinguishing feature that there is one component of the function per degree of freedom of the participating fields. A Residue object contains two concepts:\n 1) A procedure to compute the value of the function\n 2) A pointer to the element over which to compute it\n Each residue acts then as a container of a pointer to an element object, and an operation to perform on that object. In this way the same element can be used for several operation in a single computation (The alternative of adding more layers of inheritance to the element classes makes the last possibility very clumsy). Additionally, operation that need higher-levels of specialization, such as special classes of elements, can perform type-checking in their own implementation. The class residue is in fact very similar to a general container, in the sense that the object it points to does not need to be an element but can be any object that permits the computation of the function and can use the (field, dof) notation to label the inputs and outputs. The precise fields to be utilized in the computation of the operation may vary from element type to element type, hence these will generally be specified. More precisely, a residual is a function \f[ F^f_a(u^0_0,u^0_1, \ldots, u^0_{n_0-1}, u^0_1, \ldots, u^{K}_{n_{K-1}-1}), \f] where \f$u^f_a\f$ is the a-th degree of freedom of the f-th participating field in the function. A total of K of the element fields participate as arguments in the function. The f-th participating field has a total of \f$n_f\f$ degrees of freedom. The coefficient of the force "f" runs from 0 to K-1, and "a" ia the degree of freedom index that ranges from 0 to \f$n_f\f$. We need to specify specify which field in the element will represent the f-th participating field in the function F. For instance, the field number 2 in the element can be used as the first argument of F, i.e., as participating field number 0. \todo This class does not accept the input of additional parameters that may be needed for the evaluation of T that may not be solved for. \todo The assembly procedure should probably be changed */ class Residue { public: Residue() {} virtual ~Residue() {} Residue(const Residue &NewEl) {} virtual Residue * clone() const = 0; //! Returns the fields used for the computation of the residue\n //! //! getFields()[i] returns the field number beginning from zero.\n //! The variable \f$u^f_a\f$ is then computed with field getFields()[f] //! in the element. virtual const std::vector<size_t> & getFields() const = 0; //! Returns the number of degrees of freedom per field used //! for the computation of the residue\n //! //! getFieldDof(fieldnum) returns the number of deegrees of freedom //! in the participating fieldo number "fieldnumber". The argument //! fieldnumber begins from zero.\n //! The number of different values of "a" in \f$u^{f}_a\f$ is //! then computed with field getFieldDof(f) virtual size_t getFieldDof(size_t fieldnumber) const = 0; //! Returns the value of the residue given the values of the fields. //! //! @param argval vector of vector<double> containing the values of the degrees of //! freedom for each field.\n //! argval[f][a] contains the value of degree of freedom "a" for participating //! field "f". //! //! @param funcval It returns a vector< vector<double> > with the values of each //! component of the residual function. We have that \f$F^f_a\f$=funcval[f][a]. //! The vector funcval is resized and zeroed in getVal. //! //! //! The function returns true if successful, false otherwise. virtual bool getVal(const MatDouble &argval, MatDouble& funcval ) const = 0; virtual const Element& getElement () const = 0; virtual const SimpleMaterial& getMaterial () const = 0; //! \brief assemble Residual Vector //! //! Assembles the contributions from an Array of residual objects ResArray //! into ResVec. The contribution from each ResArray, ResArray[e], is mapped //! into ResVec with a LocalToGlobalMap. //! //! //! @param ResArray Array of residue objects //! @param L2G LocalToGlobalMap //! @param Dofs PetscVector with values of degrees of freedom //! @param ResVec Pointer to a PetscVector where to assemble the residues. //! ResVec is zeroed in assemble //! //! This is precisely what's done:\n //! 1) assemble input gathered as \n //! argval[f][a] = Dofs[L2G(f,a)]\n //! 2) Computation of the local residue funcval as //! ResArray[i]->getVal(argval, funcval)\n //! 3) assemble output gathered as\n //! ResVec[L2G(f,a)] += funcval[f][a]\n //! //! Behavior:\n //! Successful assembly returns true, unsuccessful false //! //! \warning: The residue object that computes the contributions of element //! "e" is required to have position "e" in ResArray as well, so that //! the LocalToGlobalMap object is used consistently //! //! \todo A defect of this implementation is that all fields in the element enter as //! arguments for Residue and its derivative. It would be good to have the flexibility to extract //! a subset of the degrees of freedom of the element as the argument to Residue and its //! derivative. In this way it is possible to act with different elemental operation on //! different degrees of freedom naturally, i.e., without having to artificially return a Residue //! that has presumed contributions from all degrees of freedom. static bool assemble(std::vector<Residue *> &ResArray, const LocalToGlobalMap & L2G, const VecDouble & Dofs, VecDouble& ResVec); }; /** * Base class for common functionality */ class BaseResidue: public Residue { protected: const Element& element; const SimpleMaterial& material; const std::vector<size_t>& fieldsUsed; BaseResidue (const Element& element, const SimpleMaterial& material, const std::vector<size_t>& fieldsUsed) : element (element), material (material), fieldsUsed (fieldsUsed) { } BaseResidue (const BaseResidue& that) : element (that.element), material (that.material) , fieldsUsed (that.fieldsUsed) { } public: virtual const Element& getElement () const { return element; } virtual const std::vector<size_t>& getFields () const { return fieldsUsed; } virtual const SimpleMaterial& getMaterial () const { return material; } virtual size_t getFieldDof (size_t fieldNum) const { return element.getDof (fieldsUsed[fieldNum]); } }; /** \brief Computes a residue and its derivative on an element See Residue class for an explanation. This class just adds a function getDVal that contains a vector to return the derivative */ class DResidue: public BaseResidue { public: DResidue (const Element& element, const SimpleMaterial& material, const std::vector<size_t>& fieldsUsed) : BaseResidue(element, material, fieldsUsed) {} DResidue(const DResidue &NewEl): BaseResidue(NewEl) {} virtual DResidue * clone() const = 0; //! Returns the value of the residue and its derivative given the values of the fields. //! //! @param argval vector of vector<double> containing the values of the degrees of //! freedom for each field.\n //! argval[f][a] contains the value of degree of freedom "a" for participating //! field "f". //! //! @param funcval It returns a vector< vector<double> > with the values of each //! component of the residual function. We have that \f$F^f_a\f$=funcval[f][a]. //! The vector funcval is resized and zeroed in getVal. //! //! @param dfuncval It returns a vector< vector< vector< vector<double> > > > //! with the values of each //! component of the derivative of the residual function. //! We have that \f$\frac{\partial F^f_a}{\partial u^g_b}\f$=dfuncval[f][a][g][b]. //! The vector dfuncval is resized and zeroed in getVal. //! //! The function returns true if successful, false otherwise. virtual bool getDVal(const MatDouble& argval, MatDouble& funcval, FourDVecDouble& dfuncval) const = 0; //! Consistency test for DResidues. static bool consistencyTest(const DResidue & DRes, const std::vector<size_t> & DofPerField, const MatDouble &argval); //! \brief assemble Residual Vector and it Derivative //! //! Assembles the contributions from an Array of dresidual objects DResArray //! into DResVec. The contribution from each DResArray, DResArray[e], is //! mapped into DResVec with a LocalToGlobalMap. //! //! @param DResArray Array of dresidue objects //! @param L2G LocalToGlobalMap //! @param Dofs PetscVector with values of degrees of freedom //! @param ResVec Pointer to a PetscVector where to assemble the dresidues. //! ResVec is zeroed in assemble //! @param DResMat Pointer to a PetscVector where to assemble the dresidues. //! DResMat is zeroed in assemble //! //! This is precisely what's done:\n //! 1) assemble input gathered as \n //! argval[f][a] = Dofs[L2G(f,a)]\n //! 2) Computation of the local residue funcval and its derivative dfucnval as //! DResArray[i]->getVal(argval, funcval, dfuncval)\n //! 3) assemble output gathered as\n //! ResVec[L2G(f,a)] += funcval[f][a]\n //! DResMat[L2G(f,a)][L2G(g,b)] += dfuncval[f][a][g][b] //! //! Behavior:\n //! Successful assembly returns true, unsuccessful false //! //! \warning: The residue object that computes the contributions of element //! "e" is required to have position "e" in DResArray as well, so that //! the LocalToGlobalMap object is used consistently //! //! \todo This structure has to be revised. In the implementation of both //! assemble functions I had to use a dynamic_cast to prevent writing two //! versions of essentially the same code, one for residue and another for // DResidue. This should have been possible through polymorphism. //! There must be a flaw in the abstraction. static bool assemble(std::vector<DResidue *> &DResArray, const LocalToGlobalMap & L2G, const VecDouble & Dofs, VecDouble& ResVec, MatDouble& DResMat); }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/DiagonalMassForSW.cpp
// Sriramajayam #include "DiagonalMassForSW.h" #include "Material.h" bool DiagonalMassForSW::getVal(const MatDouble &argval, MatDouble& funcval) const { size_t Dim = fieldsUsed.size(); // Assume that all fields use the same quadrature rules size_t nquad = element.getIntegrationWeights(fieldsUsed[0]).size(); std::vector<size_t> nDof(Dim, 0); // Number of dofs in each field MatDouble IntWeights(Dim); // Integration weights for each field MatDouble Shape(Dim); // Shape functions for each field. for (size_t f = 0; f < Dim; f++) { nDof[f] = element.getDof(fieldsUsed[f]); IntWeights[f] = element.getIntegrationWeights(fieldsUsed[f]); Shape[f] = element.getShapes(fieldsUsed[f]); } // Resize funcval if required. if (funcval.size() < fieldsUsed.size()) { funcval.resize(fieldsUsed.size()); } for (size_t f = 0; f < fieldsUsed.size(); f++) { if (funcval[f].size() < nDof[f]) { funcval[f].resize(nDof[f], 0.); } else { for (size_t a = 0; a < nDof[f]; a++) { funcval[f][a] = 0.; } } } for (size_t q = 0; q < nquad; q++) { VecDouble F(SimpleMaterial::MAT_SIZE, 0.); // F = I in the reference config. std::copy(SimpleMaterial::I_MAT, SimpleMaterial::I_MAT + SimpleMaterial::MAT_SIZE, F.begin ()); // F[0] = 1.; // F[4] = 1.; // F[8] = 1.; double Ref_rho = 0.; if (!material.getLocalMaterialDensity(&F, Ref_rho)) { std::cerr << "\nDiagonalMassForSW::GetVal()- Could not compute local density.\n"; return false; } for (size_t f = 0; f < fieldsUsed.size(); f++) { for (size_t a = 0; a < nDof[f]; a++) { funcval[f][a] += IntWeights[f][q] * Ref_rho * Shape[f][nDof[f] * q + a]; } } } return true; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/StressWork.h
/** * StressWork.h * DG++ * * Created by Adrian Lew on 10/25/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef STRESSWORK #define STRESSWORK #include <vector> #include <algorithm> #include <cassert> #include "Galois/Runtime/PerThreadStorage.h" #include "ElementalOperation.h" #include "AuxDefs.h" /** \brief Computes the virtual work of the stress tensor, and its derivative The virtual work of the stress tensor \f${\bf P}\f$ is defined as \f[ \int_{E} P_{iJ} v_{i,J}\ d\Omega, \f] where \f${\bf v}\f$ is a virtual displacement field. This operation works for two and three-dimensional problems. In two-dimensional problems plane strain is assumed, i.e., the displacements and virtual displacements have the form \f$(v_1(x_1,x_2), v_2(x_1,x_2), 0)\f$. StressWork works only on SolidElements, since it needs a SimpleMaterial to compute the stress tensor. StressWork computes the residue \f[ R[f][a] = \int_{E} P_{fJ} N_{a,J}\ d\Omega, \f] where \f$N_{a,f}\f$ is the derivative of shape function associated to degree of freedom \f$a\f$ in direction \f$f\f$. The derivative of this residue is \f[ DR[f][a][g][b] = \int_{E} A_{fJgL} N_{a,J} N_{b,L}\ d\Omega, \f] where \f$A\f$ are the elastic moduli \f$\partial{\bf P}/\partial {\bf F}\f$. */ class StressWork: public DResidue { protected: enum GetValMode { VAL, DVAL, }; //! \warning argval should contain displacements, not deformation mapping bool getDValIntern(const MatDouble &argval, MatDouble& funcval, FourDVecDouble& dfuncval, const GetValMode& mode) const; private: /** * Contains the temporary vectors used by @see getDValIntern * Instead of creating and destroying new vectors on every call, * which happens at least once per iteration, we reuse vectors * from this struct. There's one instance per thread of this struct */ struct StressWorkTmpVec { static const size_t MAT_SIZE = SimpleMaterial::MAT_SIZE; std::vector<size_t> nDof; std::vector<size_t> nDiv; MatDouble DShape; MatDouble IntWeights; VecDouble A; VecDouble F; VecDouble P; StressWorkTmpVec () : A (MAT_SIZE * MAT_SIZE, 0.0), F (MAT_SIZE, 0.0), P (MAT_SIZE, 0.0) {} void adjustSizes (size_t Dim) { if (nDof.size () != Dim) { nDof.resize (Dim); } if (nDiv.size () != Dim) { nDiv.resize (Dim); } if (DShape.size () != Dim) { DShape.resize (Dim); } if (IntWeights.size () != Dim) { IntWeights.resize (Dim); } if (A.size () != MAT_SIZE * MAT_SIZE) { A.resize (MAT_SIZE * MAT_SIZE, 0.0); } if (F.size () != MAT_SIZE) { F.resize (MAT_SIZE, 0.0); } if (P.size () != MAT_SIZE) { P.resize (MAT_SIZE, 0.0); } } }; /** * Per thread storage for temporary vectors used in @see getDValIntern */ typedef Galois::Runtime::PerThreadStorage<StressWorkTmpVec> PerCPUtmpVecTy; static PerCPUtmpVecTy perCPUtmpVec; public: //! Construct a StressWork object with fields "field1, field2 and field3" as //! the three dimensional displacement fields. //! @param IElm pointer to the element over which the value will be computed. //! The Input object is non-const, since these can be modified during the //! operation. The object pointed to is not destroyed when the operation is. //! @param SM SimpleMaterial object used to compute the stress and moduli. It is //! only referenced, not copied. //! @param fieldsUsed vector containing ids of fields being computed starting with 0 //! Cartesian component of the displacement field. If not provided, it is //! assumed that it is a plane strain case. StressWork(const Element& IElm, const SimpleMaterial &SM, const std::vector<size_t>& fieldsUsed) : DResidue (IElm, SM, fieldsUsed) { assert (fieldsUsed.size() > 0 && fieldsUsed.size () <= 3); } virtual ~StressWork() {} StressWork(const StressWork & SW) : DResidue (SW) {} virtual StressWork * clone() const { return new StressWork(*this); } VecDouble getIntegrationWeights(size_t fieldnumber) const { return BaseResidue::element.getIntegrationWeights(fieldnumber); } //! \warning argval should contain displacements, not deformation mapping bool getDVal(const MatDouble &argval, MatDouble& funcval, FourDVecDouble& dfuncval) const { return getDValIntern (argval, funcval, dfuncval, DVAL); } //! \warning argval should contain displacements, not deformation mapping bool getVal(const MatDouble &argval, MatDouble& funcval) const { FourDVecDouble d; return getDValIntern(argval, funcval, d, VAL); } private: static void copyVecDouble (const VecDouble& vin, VecDouble& vout) { if (vout.size () != vin.size ()) { vout.resize (vin.size ()); } std::copy (vin.begin (), vin.end (), vout.begin ()); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/StressWork.cpp
/* * StressWork.cpp * DG++ * * Created by Adrian Lew on 10/25/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include "StressWork.h" StressWork::PerCPUtmpVecTy StressWork::perCPUtmpVec; bool StressWork::getDValIntern (const MatDouble &argval, MatDouble& funcval, FourDVecDouble& dfuncval , const GetValMode& mode) const { const size_t Dim = fieldsUsed.size(); // XXX: (amber) replaced 3 with NDM, 9 with MAT_SIZE and so on ... const size_t MAT_SIZE = SimpleMaterial::MAT_SIZE; const size_t NDM = SimpleMaterial::NDM; // We should have the same quadrature points in all fields used size_t nquad = element.getIntegrationWeights(fieldsUsed[0]).size(); StressWorkTmpVec& tmpVec = *StressWork::perCPUtmpVec.getLocal (); tmpVec.adjustSizes (Dim); std::vector<size_t>& nDof = tmpVec.nDof; std::vector<size_t>& nDiv = tmpVec.nDiv; MatDouble& DShape = tmpVec.DShape; MatDouble& IntWeights = tmpVec.IntWeights; VecDouble& A = tmpVec.A; VecDouble& F = tmpVec.F; VecDouble& P = tmpVec.P; for (size_t f = 0; f < Dim; ++f) { nDof[f] = element.getDof(fieldsUsed[f]); nDiv[f] = element.getNumDerivatives(fieldsUsed[f]); // DShape[f] = element.getDShapes(fieldsUsed[f]); // do copy instead of assignment to pervent calls to allocator StressWork::copyVecDouble (element.getDShapes (fieldsUsed[f]), DShape[f]); // IntWeights[f] = element.getIntegrationWeights(fieldsUsed[f]); // do copy instead of assignment to pervent calls to allocator StressWork::copyVecDouble (element.getIntegrationWeights (fieldsUsed[f]), IntWeights[f]); } if (funcval.size() < Dim) { funcval.resize(Dim); } for (size_t f = 0; f < Dim; f++) { if (funcval[f].size() < nDof[f]) { funcval[f].resize(nDof[f], 0.); } else { std::fill(funcval[f].begin(), funcval[f].end(), 0.0); // for (size_t a = 0; a < nDof[f]; ++a) { // funcval[f][a] = 0.; // } } } if (mode == DVAL) { if (dfuncval.size() < Dim) { dfuncval.resize(Dim); } for (size_t f = 0; f < Dim; ++f) { if (dfuncval[f].size() < nDof[f]) { dfuncval[f].resize(nDof[f]); } for (size_t a = 0; a < nDof[f]; ++a) { if (dfuncval[f][a].size() < Dim) { dfuncval[f][a].resize(Dim); } for (size_t g = 0; g < Dim; ++g) { if (dfuncval[f][a][g].size() < nDof[g]) { dfuncval[f][a][g].resize(nDof[g], 0.); } else { for (size_t b = 0; b < nDof[g]; ++b) { dfuncval[f][a][g][b] = 0.; } } } // end for } } } for (size_t q = 0; q < nquad; ++q) { // Compute gradients // F[0] = F[4] = F[8] = 1.; // F[1] = F[2] = F[3] = F[5] = F[6] = F[7] = 0.; std::copy (SimpleMaterial::I_MAT, SimpleMaterial::I_MAT + MAT_SIZE, F.begin ()); for (size_t f = 0; f < Dim; ++f) { for (size_t a = 0; a < nDof[f]; ++a) { for (size_t J = 0; J < nDiv[f]; ++J) { // double t = argval[f][a] * DShape[f][q * nDof[f] * nDiv[f] + a * nDiv[f] + J]; double t = DShape[f][q * nDof[f] * nDiv[f] + a * nDiv[f] + J] * argval[f][a]; F[f * NDM + J] += t; } } } if (!material.getConstitutiveResponse(F, P, A, SimpleMaterial::SKIP_TANGENTS)) { std::cerr << "StressWork.cpp: Error in the constitutive response\n"; return false; } for (size_t f = 0; f < Dim; ++f) { for (size_t a = 0; a < nDof[f]; ++a) { for (size_t J = 0; J < nDiv[f]; ++J) { funcval[f][a] += IntWeights[f][q] * P[f * NDM + J] * DShape[f][q * nDof[f] * nDiv[f] + a * nDiv[f] + J]; } } } if (mode == DVAL) { for (size_t f = 0; f < Dim; ++f) { for (size_t a = 0; a < nDof[f]; ++a) { for (size_t g = 0; g < Dim; ++g) { for (size_t b = 0; b < nDof[g]; ++b) { for (register size_t J = 0; J < nDiv[f]; ++J) { for (register size_t L = 0; L < nDiv[g]; ++L) { dfuncval[f][a][g][b] += IntWeights[f][q] * A[f * NDM * MAT_SIZE + J * MAT_SIZE + g * NDM + L] * DShape[f][q * nDof[f] * nDiv[f] + a * nDiv[f] + J] * DShape[g][q * nDof[g] * nDiv[g] + b * nDiv[g] + L]; } } } } } } } } return true; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/DiagonalMassForSW.h
/** * DiagonalMassForSW.h * DG++ * * Created by Adrian Lew on 10/24/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Sriramajayam #ifndef DIAGONALMASSMATRIXFORSW #define DIAGONALMASSMATRIXFORSW #include "AuxDefs.h" #include "ElementalOperation.h" //! \brief Class to compute a diagonal mass matrix for StressWork. /** This class computes a diagonalized form of the (exact) mass matrix * \f$ M[f][a][b] = \int_E \rho_0 N_a^f N_b^f. \f$ * * Since a diagonal mass matrix is often desired, the entries in each * row of the exact mass-matrix are lumped together on the diagonal * entry \f$ M[f][a][a] \f$. * * A mass-vector is assembled (instead of a matrix) with each entry * compued as \f$ M[f][a] = \int_E \rho_0 N_a^f \f$ * where \f$a\f$ runs over all degrees of freedom for * field \f$ f \f$. * * Keeping this in mind, this class inherits the class Residue to * assemble the mass vector. It has pointers to the element for which * the mass matrix is to be computed and the material provided over * the element. It assumes that there are a minimum of two fields over * the element with an optional third. It implements the member * function getVal of Residue to compute the elemental contribution to * the mass-vector. * */ class DiagonalMassForSW: public BaseResidue { public: //! Constructor //! \param IElm Pointer to element over which mass is to be compued. //! \param SM SimpleMaterial over the element. //! \param fieldsUsed vector containing ids of fields being computed starting with 0 inline DiagonalMassForSW (const Element& IElm, const SimpleMaterial &SM, const std::vector<size_t>& fieldsUsed) : BaseResidue (IElm, SM, fieldsUsed) { assert (fieldsUsed.size() > 0 && fieldsUsed.size () <= 3); } //! Destructor virtual ~DiagonalMassForSW() { } //! Copy constructor //! \param DMM DiagonalMassForSW object to be copied. inline DiagonalMassForSW(const DiagonalMassForSW & DMM) : BaseResidue (DMM) { } //! Cloning mechanism virtual DiagonalMassForSW * clone() const { return new DiagonalMassForSW(*this); } //! Computes the elemental contribution to the mass-vector. //! \param argval See Residue. It is a dummy argument since integrations are done over the reference. //! \param funcval See Residue. bool getVal(const MatDouble &argval, MatDouble& funcval) const; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/test/testDiagonalMassForSW.cpp
// Sriramajayam #include "P12DElement.h" #include "DiagonalMassForSW.h" int main() { // Create a P12D element. double coord[] = {0.,0., sqrt(2),sqrt(3), sqrt(3),sqrt(2)}; std::vector<double> coordinates; coordinates.assign(coord, coord+6); Segment<2>::SetGlobalCoordinatesArray(coordinates); Triangle<2>::SetGlobalCoordinatesArray(coordinates); Element * Elm = new P12D<2>::Bulk(1,2,3); // Create simple material. IsotropicLinearElastic ILE(1.0, 1.0, 1.0); // lambda, mu and ref_rho. // Create Residue object to compute diagonal mass vector. DiagonalMassForSW MassVec(Elm, ILE, 0, 1); // Test class DiagonalMassForSW std::cout<<"\nNumber of fields: "<<MassVec.getFields().size() <<" should be 2."; std::cout<<"\nLocal fields: "<<MassVec.getFields()[0]<<","<<MassVec.getFields()[1] <<" should be 0,1."; std::cout<<"\nNumber of dofs per field: "<<MassVec.getFieldDof(0)<<","<<MassVec.getFieldDof(1) <<" should be 3,3."; std::cout<<"\nMaterial given over element: "<<MassVec.GetSimpleMaterial().getMaterialName() <<" should be IsotropicLinearElastic."; std::cout<<"\nDensity of material in reference config.: "<<MassVec.GetSimpleMaterial().getDensityInReference() <<" should be 1."; // Testing calculation of mass vector: std::vector< std::vector<double> > argval(2); argval[0].resize(3,0.); argval[1].resize(3,0.); std::vector< std::vector<double> > funcval; if(!MassVec.getVal(argval, &funcval)) { std::cerr<<"\nCould not compute mass vector. Test failed.\n"; exit(1); } for(unsigned int f=0; f<MassVec.getFields().size(); f++) { std::cout<<"\nMass vector for field "<<f<<": ("; for(int a=0; a<MassVec.getFieldDof(f); a++) std::cout<<funcval[f][a]<<","; std::cout<<")\n"; } // Exact vector is computed as the volume of a tetrahedron- each entry is (1/3)*rho_0*area of triangle*ht(=1). double Area = 0.; for(unsigned int q=0; q<Elm->getIntegrationWeights(0).size(); q++) Area += Elm->getIntegrationWeights(0)[q]; double mv = (1./3.)*MassVec.GetSimpleMaterial().getDensityInReference()*Area*1.0; std::cout<<"\nBoth mass vectors should read: (" <<mv<<","<<mv<<","<<mv<<")\n"; std::cout<<"\nTesting Copy constructor: "; { DiagonalMassForSW MassVecCopy(MassVec); std::cout<<"\nNumber of fields: "<<MassVecCopy.getFields().size() <<" should be 2."; std::cout<<"\nLocal fields: "<<MassVecCopy.getFields()[0]<<","<<MassVecCopy.getFields()[1] <<" should be 0,1."; std::cout<<"\nNumber of dofs per field: "<<MassVecCopy.getFieldDof(0)<<","<<MassVecCopy.getFieldDof(1) <<" should be 3,3."; std::cout<<"\nMaterial given over element: "<<MassVecCopy.GetSimpleMaterial().getMaterialName() <<" should be IsotropicLinearElastic."; std::cout<<"\nDensity of material in reference config.: "<<MassVecCopy.GetSimpleMaterial().getDensityInReference() <<" should be 1."; } std::cout<<"\n\nTesting Cloning: "; { DiagonalMassForSW * MassVecClone = MassVec.clone(); std::cout<<"\nNumber of fields: "<<MassVecClone->getFields().size() <<" should be 2."; std::cout<<"\nLocal fields: "<<MassVecClone->getFields()[0]<<","<<MassVecClone->getFields()[1] <<" should be 0,1."; std::cout<<"\nNumber of dofs per field: "<<MassVecClone->getFieldDof(0)<<","<<MassVecClone->getFieldDof(1) <<" should be 3,3."; std::cout<<"\nMaterial given over element: "<<MassVecClone->GetSimpleMaterial().getMaterialName() <<" should be IsotropicLinearElastic."; std::cout<<"\nDensity of material in reference config.: "<<MassVecClone->GetSimpleMaterial().getDensityInReference() <<" should be 1."; delete MassVecClone; } std::cout<<"\n\nTesing finished.\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/test/testStressWork.cpp
/* * testStressWork.cpp * DG++ * * Created by Adrian Lew on 10/25/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Triangle.h" #include "ElementalOperation.h" #include "StressWork.h" #include "P12DElement.h" int main() { double Vertices[] = {1,0,0,1,0,0,1,1}; std::vector<double> Vertices0(Vertices, Vertices+8); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); P12D<2>::Bulk TestElement(1,2,3); NeoHookean NH(1,1); StressWork MyResidue(&TestElement, NH, 0,1); std::vector< std::vector<double> > argval(2); argval[0].resize(3); argval[1].resize(3); argval[0][0] = 0.1; argval[0][1] = 0.; argval[0][2] = -0.1; argval[1][0] = 0.; argval[1][1] = 0.1; argval[1][2] = -0.1; argval[0][0] = 0.; argval[0][1] = 0.; argval[0][2] = -0.; argval[1][0] = 0.; argval[1][1] = 0.; argval[1][2] = -0.; std::vector<unsigned int> DofPerField(2); DofPerField[0] = TestElement.getDof( MyResidue.getFields()[0] ); DofPerField[1] = TestElement.getDof( MyResidue.getFields()[1] ); if(MyResidue.consistencyTest(MyResidue, DofPerField, argval)) std::cout << "DResidue::Consistency test successful\n"; else std::cout << "DResidue::Consistency test not successful\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/test/testAssemble.cpp
/* * testAssemble.cpp * DG++ * * Created by Adrian Lew on 10/27/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Triangle.h" #include "ElementalOperation.h" #include "StressWork.h" #include "P12DElement.h" #include "petscvec.h" #include "petscmat.h" static char help[] = "test"; int main(int argc, char **argv) { PetscInitialize(&argc,&argv,(char*) 0,help); double Vertices[] = {1,0,0,1,0,0,1,1,0,2}; std::vector<double> Vertices0(Vertices, Vertices+10); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); std::vector< Element * > LocalElements; std::vector< DResidue * > LocalOperations(3); double conn[] = {1,2,3,1,4,2,2,4,5}; int dim = 10; sleep(1); NeoHookean NH(1,1); for(int e=0; e<3; e++) { LocalElements.push_back(new P12D<2>::Bulk(conn[3*e],conn[3*e+1],conn[3*e+2])); LocalOperations[e] = new StressWork(LocalElements[e], NH, 0,1); } StandardP12DMap L2G(LocalElements); Vec Dofs, resVec; Mat dresMat; VecCreate(PETSC_COMM_WORLD, &Dofs); VecSetSizes(Dofs,PETSC_DECIDE,dim); VecSetFromOptions(Dofs); VecDuplicate(Dofs,&resVec); MatCreateSeqDense(PETSC_COMM_SELF,dim,dim,PETSC_NULL,&dresMat); MatSetOption(dresMat,MAT_SYMMETRIC); double dofvalues[] = {0.1,0.,0.,0.1,0.,0.,0.1,0.2,-0.1,0.2}; int indices[] = {0,1,2,3,4,5,6,7,8,9}; VecSetValues(Dofs,dim,indices,dofvalues,INSERT_VALUES); VecAssemblyBegin(Dofs); VecAssemblyEnd(Dofs); DResidue::assemble(LocalOperations, L2G, Dofs, &resVec, &dresMat); VecAssemblyBegin(resVec); VecAssemblyEnd(resVec); MatAssemblyBegin(dresMat,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(dresMat,MAT_FINAL_ASSEMBLY); VecView(resVec,PETSC_VIEWER_STDOUT_SELF); MatView(dresMat,PETSC_VIEWER_STDOUT_SELF); std::cout << "\n\nConsistency Test\n"; Vec resVecPlus; Vec resVecMinus; VecDuplicate(Dofs,&resVecPlus); VecDuplicate(Dofs,&resVecMinus); Mat dresMatNum; MatDuplicate(dresMat, MAT_DO_NOT_COPY_VALUES, &dresMatNum); double EPS = 1.e-6; for(int i=0; i<dim; i++) { double v[1]; int ix[1]={i}; VecGetValues(Dofs, 1, ix, v); double ival = v[0]; double newval = ival + EPS; VecSetValue(Dofs, i, newval, INSERT_VALUES); VecAssemblyBegin(Dofs); VecAssemblyEnd(Dofs); DResidue::assemble(LocalOperations, L2G, Dofs, &resVecPlus, 0); newval = ival - EPS; VecSetValue(Dofs, i, newval, INSERT_VALUES); VecAssemblyBegin(Dofs); VecAssemblyEnd(Dofs); DResidue::assemble(LocalOperations, L2G, Dofs, &resVecMinus, 0); newval = ival; VecSetValue(Dofs, i, newval, INSERT_VALUES); VecAssemblyBegin(Dofs); VecAssemblyEnd(Dofs); VecAssemblyBegin(resVecPlus); VecAssemblyEnd(resVecPlus); VecAssemblyBegin(resVecMinus); VecAssemblyEnd(resVecMinus); double *Plus, *Minus; VecGetArray(resVecPlus, &Plus); VecGetArray(resVecMinus, &Minus); for(int j=0; j<dim; j++) { double deriv = (Plus[j]-Minus[j])/(2*EPS); MatSetValue(dresMatNum,i,j, deriv, INSERT_VALUES); } VecRestoreArray(resVecPlus, &Plus); VecRestoreArray(resVecMinus, &Minus); } MatAssemblyBegin(dresMatNum,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(dresMatNum,MAT_FINAL_ASSEMBLY); // Compare matrices double error = 0; double norm = 0; double *dresMatA; MatGetArray(dresMat,&dresMatA); double *dresMatNumA; MatGetArray(dresMatNum,&dresMatNumA); for(int i=0; i<dim*dim; i++) { error += pow(dresMatA[i]-dresMatNumA[i] ,2); norm += pow(dresMatA[i] ,2); } MatRestoreArray(dresMat,&dresMatA); MatRestoreArray(dresMatNum,&dresMatNumA); error = sqrt(error); norm = sqrt(norm); if(error/norm<EPS*100) std::cout << "Consistency test successful - norm = " << norm << " error = " << error << "\n"; else std::cout << "Consistency test failed - norm = " << norm << " error = " << error << "\n"; VecDestroy(resVecPlus); VecDestroy(resVecMinus); MatDestroy(dresMatNum); VecDestroy(Dofs); VecDestroy(resVec); MatDestroy(dresMat); }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElOp/test/testAssemble-modelOutput
0.154738 -0.299013 -0.393311 -0.0738921 -0.1821 -0.1821 0.437839 0.366179 -0.017166 0.188826 1.7526200541774453e+00 -5.4367685082125014e-02 -5.9310201907772753e-02 6.8684748269348916e-01 -1.2476775373517976e+00 -4.1322314049586772e-01 -4.4563231491787492e-01 -2.1925665711549644e-01 0.0000000000000000e+00 0.0000000000000000e+00 -5.4367685082125014e-02 1.5980445359033753e+00 7.1324227564380849e-01 0.0000000000000000e+00 -3.3445439685592970e-01 -4.9999999999999989e-01 -3.2442019370575381e-01 -1.0980445359033753e+00 0.0000000000000000e+00 0.0000000000000000e+00 -5.9310201907772739e-02 7.1324227564380849e-01 3.3167846176174178e+00 7.2607463366897407e-01 -4.9999999999999989e-01 -3.3445439685592970e-01 -2.3179806351820593e+00 -7.6763391024997962e-01 -4.3949378052758548e-01 -3.3722860220687306e-01 6.8684748269348916e-01 0.0000000000000000e+00 7.2607463366897396e-01 3.6189670977545658e+00 -4.1322314049586772e-01 -1.2476775373517976e+00 -7.4396662724380636e-01 -1.0726074633668974e+00 -2.5573234862278899e-01 -1.2986820970358712e+00 -1.2476775373517976e+00 -3.3445439685592970e-01 -4.9999999999999989e-01 -4.1322314049586772e-01 1.7476775373517976e+00 7.4767753735179743e-01 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 -4.1322314049586772e-01 -4.9999999999999989e-01 -3.3445439685592970e-01 -1.2476775373517976e+00 7.4767753735179743e-01 1.7476775373517976e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 -4.4563231491787497e-01 -3.2442019370575381e-01 -2.3179806351820593e+00 -7.4396662724380636e-01 0.0000000000000000e+00 0.0000000000000000e+00 2.8301697915195905e+00 6.6460137732303115e-01 -6.6556841419655927e-02 4.0378544362652902e-01 -2.1925665711549644e-01 -1.0980445359033753e+00 -7.6763391024997962e-01 -1.0726074633668974e+00 0.0000000000000000e+00 0.0000000000000000e+00 6.6460137732303115e-01 2.1040951578506166e+00 3.2228919004244494e-01 6.6556841419655927e-02 0.0000000000000000e+00 0.0000000000000000e+00 -4.3949378052758548e-01 -2.5573234862278899e-01 0.0000000000000000e+00 0.0000000000000000e+00 -6.6556841419655927e-02 3.2228919004244494e-01 5.0605062194724137e-01 -6.6556841419655927e-02 0.0000000000000000e+00 0.0000000000000000e+00 -3.3722860220687306e-01 -1.2986820970358712e+00 0.0000000000000000e+00 0.0000000000000000e+00 4.0378544362652902e-01 6.6556841419655927e-02 -6.6556841419655927e-02 1.2321252556162152e+00 Consistency Test Consistency test successful - norm = 9.30356 error = 4.36321e-10
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat/NeoHookean.cpp
/* * NeoHookean.cpp * DG++ * * Created by Adrian Lew on 10/24/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Material.h" // calling default constructor Galois::Runtime::PerThreadStorage<NeoHookean::NeoHookenTmpVec> NeoHookean::perCPUtmpVec; static double matlib_determinant(const double *A) { double det; det = A[0] * (A[4] * A[8] - A[5] * A[7]) - A[1] * (A[3] * A[8] - A[5] * A[6]) + A[2] * (A[3] * A[7] - A[4] * A[6]); return det; } static double matlib_inverse(const double *A, double *Ainv) { double det, detinv; det = matlib_determinant(A); if (fabs(det) < SimpleMaterial::DET_MIN) { return 0.e0; } detinv = 1. / det; Ainv[0] = detinv * (A[4] * A[8] - A[5] * A[7]); Ainv[1] = detinv * (-A[1] * A[8] + A[2] * A[7]); Ainv[2] = detinv * (A[1] * A[5] - A[2] * A[4]); Ainv[3] = detinv * (-A[3] * A[8] + A[5] * A[6]); Ainv[4] = detinv * (A[0] * A[8] - A[2] * A[6]); Ainv[5] = detinv * (-A[0] * A[5] + A[2] * A[3]); Ainv[6] = detinv * (A[3] * A[7] - A[4] * A[6]); Ainv[7] = detinv * (-A[0] * A[7] + A[1] * A[6]); Ainv[8] = detinv * (A[0] * A[4] - A[1] * A[3]); return det; } static void matlib_mults(const double *A, const double *B, double *C) { C[0] = A[0] * B[0] + A[1] * B[1] + A[2] * B[2]; C[1] = A[3] * B[0] + A[4] * B[1] + A[5] * B[2]; C[2] = A[6] * B[0] + A[7] * B[1] + A[8] * B[2]; C[3] = A[0] * B[3] + A[1] * B[4] + A[2] * B[5]; C[4] = A[3] * B[3] + A[4] * B[4] + A[5] * B[5]; C[5] = A[6] * B[3] + A[7] * B[4] + A[8] * B[5]; C[6] = A[0] * B[6] + A[1] * B[7] + A[2] * B[8]; C[7] = A[3] * B[6] + A[4] * B[7] + A[5] * B[8]; C[8] = A[6] * B[6] + A[7] * B[7] + A[8] * B[8]; } bool NeoHookean::getConstitutiveResponse(const std::vector<double>& strain, std::vector<double>& stress, std::vector<double>& tangents , const ConstRespMode& mode) const { // XXX: (amber) replaced unknown 3's with NDM, 9 & 81 with MAT_SIZE & MAT_SIZE ^ 2 size_t i; size_t j; size_t k; size_t l; size_t m; size_t n; size_t ij; size_t jj; size_t kl; size_t jk; size_t il; size_t ik; size_t im; size_t jl; size_t kj; size_t kn; size_t mj; size_t nl; size_t ijkl; size_t indx; double coef; double defVol; double detC; double p; // double trace; NeoHookenTmpVec& tmpVec = *perCPUtmpVec.getLocal (); double* F = tmpVec.F; // double* Finv = tmpVec.Finv; double* C = tmpVec.C; double* Cinv = tmpVec.Cinv; double* S = tmpVec.S; double* M = tmpVec.M; // double detF; size_t J; std::copy (I_MAT, I_MAT + MAT_SIZE, F); /*Fill in the deformation gradient*/ for (i = 0; i < NDF; i++) { for (J = 0; J < NDM; J++) { F[i * NDM + J] = strain[i * NDM + J]; } } /* compute right Cauchy-Green tensor C */ matlib_mults(F, F, C); /* compute PK2 stresses and derivatives wrt C*/ detC = matlib_inverse(C, Cinv); // detF = matlib_inverse(F, Finv); if (detC < DET_MIN) { std::cerr << "NeoHookean::GetConstitutiveResponse: close to negative jacobian\n"; return false; } defVol = 0.5 * log(detC); p = Lambda * defVol; // trace = C[0] + C[4] + C[8]; coef = p - Mu; for (j = 0, ij = 0, jj = 0; j < NDF; j++, jj += NDF + 1) { for (i = 0; i < NDM; i++, ij++) { S[ij] = coef * Cinv[ij]; } S[jj] += Mu; } if (mode == COMPUTE_TANGENTS) { coef = Mu - p; for (l = 0, kl = 0, ijkl = 0; l < NDM; l++) { for (k = 0, jk = 0; k < NDM; k++, kl++) { for (j = 0, ij = 0, jl = l * NDM; j < NDM; j++, jk++, jl++) { for (i = 0, ik = k * NDM, il = l * NDM; i < NDM; i++, ij++, ik++, il++, ijkl++) { M[ijkl] = Lambda * Cinv[ij] * Cinv[kl] + coef * (Cinv[ik] * Cinv[jl] + Cinv[il] * Cinv[jk]); } } } } } if (stress.size() != MAT_SIZE) { stress.resize(MAT_SIZE); } /* PK2 -> PK1 */ for (j = 0, ij = 0; j < NDM; j++) { for (i = 0; i < NDM; i++, ij++) { stress[ij] = 0.e0; for (k = 0, ik = i, kj = j * NDM; k < NDM; k++, ik += NDM, kj++) { stress[ij] += F[ik] * S[kj]; } } } if (mode == COMPUTE_TANGENTS) { if (tangents.size() != MAT_SIZE * MAT_SIZE) { tangents.resize(MAT_SIZE * MAT_SIZE); } /* apply partial push-forward and add geometrical term */ for (l = 0, ijkl = 0; l < NDM; l++) { for (k = 0; k < NDF; k++) { for (j = 0, jl = l * NDF; j < NDM; j++, jl++) { for (i = 0; i < NDF; i++, ijkl++) { tangents[ijkl] = 0.e0; /* push-forward */ for (n = 0, kn = k, nl = l * NDF; n < NDM; n++, kn += NDM, nl++) { indx = nl * MAT_SIZE; for (m = 0, im = i, mj = j * NDM; m < NDM; m++, im += NDM, mj++) { tangents[ijkl] += F[im] * M[mj + indx] * F[kn]; } } /* geometrical term */ if (i == k) { tangents[ijkl] += S[jl]; } } } } } } return true; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat/Material.h
/** * Material.h * DG++ * * Created by Adrian Lew on 10/24/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef MATERIAL_H #define MATERIAL_H #include "Galois/Runtime/PerThreadStorage.h" #include <vector> #include <string> #include <iostream> #include <algorithm> #include <cmath> #include <cassert> /** \brief Base class for all materials. \warning This is a quick fix. Will be revised later. */ class Material { }; /** \brief Material whose thermodynamic state depends only on the local strain. Simple materials are those for which the stress depends only on the strain. Assumes a homogeneous density in the reference configuration. Convention:\n Any 3x3 second-order tensor \f${\bf A}\f$ is represented by a 2x2 matrix with components ordered in an array \f$A\f$ as \f$A_{iJ}\f$=A[i*3+J].\n Any 3x3x3x3 fourth-order tensor \f$\mathbb{C}\f$ is represented by a 3x3x3x3 matrix with components ordered in an array \f$C\f$ as \f$\mathbb{C}_{iJkL}\f$=C[i*27+J*9+k*3+l].\n */ class SimpleMaterial: public Material { public: // (amber) some constants collected here //! Some constants collected together here static const double EPS; static const double PERT; static const double DET_MIN; static const size_t MAT_SIZE = 9; static const size_t NDF; static const size_t NDM; static const double I_MAT[MAT_SIZE]; //! for use with getConstitutiveResponse //! optional to compute the tangents or skip //! the computation enum ConstRespMode { COMPUTE_TANGENTS, SKIP_TANGENTS, }; //! \param rhoInput Density in reference configuration. If not provided, assumed to be zero. inline SimpleMaterial(double rhoInput = 0) : RefRho(rhoInput) { } virtual ~SimpleMaterial() { } //! Copy constructor //! \param SM SimpleMaterial object to be copied. inline SimpleMaterial(const SimpleMaterial &SM) : RefRho(SM.RefRho) { } virtual SimpleMaterial * clone() const = 0; /** \brief Returns the constitutive response of the material Given the local strain, it returns the local stress, and if requested, the constitutive tangents.\n\n More precisely:\n The strain is assumed to be a 3x3 second-order tensor \f$F_{iJ}\f$. \n The stress is assumed to be a 3x3 second-order tensor \f$P_{iJ}(\bf{F})\f$. \n The constitutive tangents are a 3x3x3x3 fourth-order tensor \f[ A_{iJkL} = \frac{\partial P_{iJ}}{\partial F_{kL}} \f] @param strain strain tensor, input @param stress array where the stress tensor is returned @param tangents array where the constitutive tangents are returned. If not provided, not computed. @param mode tells whether to compute tangents vector or skip it @see ConstRespMode If cannot compute the constitutive relation for some reason, for example a negative determinant in the strain, it returns false. If successful, returns true. */ virtual bool getConstitutiveResponse(const std::vector<double>& strain, std::vector<double>& stress, std::vector<double>& tangents , const ConstRespMode& mode) const = 0; //! Returns the (uniform) density of the reference configuration. double getDensityInReference() const { return RefRho; } /** Returns the local density that is a function of only the strain. The density is computed as \f[ \rho = \frac{\rho_0}{\text{det}(\nabla F)}, \f] where \f$F\f$ is the deformation gradient (as described above). <br> Returns true if the computation went well and false otherwise. \param strain Deformation gradient. \param LocDensity Computed local density. */ bool getLocalMaterialDensity(const std::vector<double> * strain, double &LocDensity) const { assert((*strain).size () == MAT_SIZE); // Compute determinant of strain. double J = (*strain)[0] * ((*strain)[4] * (*strain)[8] - (*strain)[5] * (*strain)[7]) - (*strain)[1] * ((*strain)[3] * (*strain)[8] - (*strain)[5] * (*strain)[6]) + (*strain)[2] * ((*strain)[3] * (*strain)[7] - (*strain)[4] * (*strain)[6]); if (fabs(J) < 1.e-10) return false; else { LocDensity = RefRho / J; return true; } } //! returns a string with the name of the material virtual const std::string getMaterialName() const = 0; //! Consistency test\n //! Checks that the tangets are in fact the derivatives of the stress with respect to the //! strain. static bool consistencyTest(const SimpleMaterial &Smat); //! @return speed of sound virtual double getSoundSpeed(void) const = 0; private: double RefRho; }; /** \brief NeoHookean constitutive behavior */ class NeoHookean: public SimpleMaterial { /** * Holds temporary vectors used by getConstitutiveResponse * Instead of allocating new arrays on the stack, we reuse * the same memory in the hope of better cache efficiency * There is on instance of this struct per thread */ struct NeoHookenTmpVec { static const size_t MAT_SIZE = SimpleMaterial::MAT_SIZE; double F[MAT_SIZE]; double Finv[MAT_SIZE]; double C[MAT_SIZE]; double Cinv[MAT_SIZE]; double S[MAT_SIZE]; double M[MAT_SIZE * MAT_SIZE]; }; /** * Per thread storage for NeoHookenTmpVec */ static Galois::Runtime::PerThreadStorage<NeoHookenTmpVec> perCPUtmpVec; public: NeoHookean(double LambdaInput, double MuInput, double rhoInput = 0) : SimpleMaterial(rhoInput), Lambda(LambdaInput), Mu(MuInput) { } virtual ~NeoHookean() { } NeoHookean(const NeoHookean &NewMat) : SimpleMaterial(NewMat), Lambda(NewMat.Lambda), Mu(NewMat.Mu) { } virtual NeoHookean * clone() const { return new NeoHookean(*this); } bool getConstitutiveResponse(const std::vector<double>& strain, std::vector<double>& stress, std::vector<double>& tangents , const ConstRespMode& mode) const; const std::string getMaterialName() const { return "NeoHookean"; } double getSoundSpeed(void) const { return sqrt((Lambda + 2.0 * Mu) / getDensityInReference()); } private: // Lame constants double Lambda; double Mu; }; /** \brief Linear Elastic constitutive behavior This is an abstract class that provides the constitutive response of a linear elastic material. However, it does not store the moduli, leaving that task for derived classes. In this way, we have the flexibility to handle cases in which the material has different types of anisotropy or under stress. */ class LinearElasticBase: public SimpleMaterial { public: LinearElasticBase(double irho = 0) : SimpleMaterial(irho) { } virtual ~LinearElasticBase() { } LinearElasticBase(const LinearElasticBase &NewMat) : SimpleMaterial(NewMat) { } virtual LinearElasticBase * clone() const = 0; bool getConstitutiveResponse(const std::vector<double>& strain, std::vector<double>& stress, std::vector<double>& tangents , const ConstRespMode& mode) const; const std::string getMaterialName() const { return "LinearElasticBase"; } protected: virtual double getModuli(int i1, int i2, int i3, int i4) const = 0; }; /** \brief Isotropic, unstressed Linear Elastic constitutive behavior */ class IsotropicLinearElastic: public LinearElasticBase { public: static const int DELTA_MAT[][3]; IsotropicLinearElastic(double iLambda, double imu, double irho = 0) : LinearElasticBase(irho), lambda(iLambda), mu(imu) { } virtual ~IsotropicLinearElastic() { } IsotropicLinearElastic(const IsotropicLinearElastic &NewMat) : LinearElasticBase(NewMat), lambda(NewMat.lambda), mu(NewMat.mu) { } virtual IsotropicLinearElastic * clone() const { return new IsotropicLinearElastic(*this); } const std::string getMaterialName() const { return "IsotropicLinearElastic"; } double getSoundSpeed(void) const { return sqrt((lambda + 2.0 * mu) / getDensityInReference()); } protected: double getModuli(int i1, int i2, int i3, int i4) const { return lambda * DELTA_MAT[i1][i2] * DELTA_MAT[i3][i4] + mu * (DELTA_MAT[i1][i3] * DELTA_MAT[i2][i4] + DELTA_MAT[i1][i4] * DELTA_MAT[i2][i3]); } private: double lambda; double mu; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat/Material.cpp
/* * NeoHookean.cpp * DG++ * * Created by Adrian Lew on 10/24/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Material.h" #include <vector> #include <cstdlib> #include <cmath> #include <iostream> const double SimpleMaterial::I_MAT[] = { 1., 0., 0., 0., 1., 0., 0., 0., 1. }; const int IsotropicLinearElastic::DELTA_MAT[][3] = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; const double SimpleMaterial::EPS = 1.e-6; const double SimpleMaterial::PERT = 1.e-1; const double SimpleMaterial::DET_MIN = 1.e-10; const size_t SimpleMaterial::NDF = 3; const size_t SimpleMaterial::NDM = 3; bool SimpleMaterial::consistencyTest(const SimpleMaterial &SMat) { std::vector<double> strain(MAT_SIZE); std::vector<double> stress(MAT_SIZE); std::vector<double> tangents(MAT_SIZE * MAT_SIZE); std::vector<double> stressplus(MAT_SIZE); std::vector<double> stressminus(MAT_SIZE); std::vector<double> tangentsnum(MAT_SIZE * MAT_SIZE); srand(time(0)); strain[0] = 1 + double(rand()) / double(RAND_MAX) * PERT; strain[1] = double(rand()) / double(RAND_MAX) * PERT; strain[2] = double(rand()) / double(RAND_MAX) * PERT; strain[3] = double(rand()) / double(RAND_MAX) * PERT; strain[4] = 1 + double(rand()) / double(RAND_MAX) * PERT; strain[5] = double(rand()) / double(RAND_MAX) * PERT; strain[6] = double(rand()) / double(RAND_MAX) * PERT; strain[7] = double(rand()) / double(RAND_MAX) * PERT; strain[8] = 1 + double(rand()) / double(RAND_MAX) * PERT; for (unsigned int i = 0; i < MAT_SIZE; i++) { std::vector<double> t; double Forig = strain[i]; strain[i] = Forig + EPS; SMat.getConstitutiveResponse(strain, stressplus, t, SKIP_TANGENTS); strain[i] = Forig - EPS; SMat.getConstitutiveResponse(strain, stressminus, t, SKIP_TANGENTS); for (unsigned j = 0; j < MAT_SIZE; j++) { tangentsnum[j * MAT_SIZE + i] = (stressplus[j] - stressminus[j]) / (2 * EPS); } strain[i] = Forig; } SMat.getConstitutiveResponse(strain, stress, tangents, COMPUTE_TANGENTS); double error = 0; double norm = 0; for (size_t i = 0; i < MAT_SIZE * MAT_SIZE; i++) { error += pow(tangents[i] - tangentsnum[i], 2); norm += pow(tangents[i], 2); } error = sqrt(error); norm = sqrt(norm); if (error / norm > EPS * 100) { std::cerr << "SimpleMaterial::ConsistencyTest. Material not consistent\n"; return false; } return true; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat/LinearElasticMaterial.cpp
/* * LinearElasticMaterial.cpp * DG++ * * Created by Adrian Lew on 11/19/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Material.h" #include <cmath> #include <iostream> // XXX: (amber) replaced 3,9. 27, 81 with NDM, MAT_SIZE bool LinearElasticBase::getConstitutiveResponse(const std::vector<double>& strain, std::vector<double>& stress, std::vector<double> & tangents, const ConstRespMode& mode) const { // Compute stress if (stress.size () != MAT_SIZE) { stress.resize(MAT_SIZE); } for (size_t i = 0; i < NDM; i++) { for (size_t J = 0; J < NDM; J++) { stress[i * NDM + J] = 0; for (size_t k = 0; k < NDM; k++) { for (size_t L = 0; L < NDM; L++) { stress[i * NDM + J] += getModuli(i, J, k, L) * (strain[k * NDM + L] - I_MAT[k * NDM + L]); } } } } // Compute tangents, if needed if (mode == COMPUTE_TANGENTS) { if (tangents.size () != MAT_SIZE * MAT_SIZE) { tangents.resize(MAT_SIZE * MAT_SIZE); } for (size_t i = 0; i < NDM; i++) for (size_t J = 0; J < NDM; J++) for (size_t k = 0; k < NDM; k++) for (size_t L = 0; L < NDM; L++) tangents[i * MAT_SIZE * NDM + J * MAT_SIZE + k * NDM + L] = getModuli(i, J, k, L); } return true; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat/test/testLinearElastic.cpp
/* * testLinearElastic.cpp * DG++ * * Created by Adrian Lew on 11/21/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Material.h" #include <vector> #include <iostream> int main() { IsotropicLinearElastic ILE(1., 2.); if(ILE.consistencyTest(ILE)) std::cout << "Successful\n"; else std::cout << "Failed\n"; return 1; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libMat/test/testNeoHookean.cpp
/* * testNeoHookean.cpp * DG++ * * Created by Adrian Lew on 10/24/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Material.h" #include <vector> #include <iostream> int main() { NeoHookean NH(1., 2.); if(NH.consistencyTest(NH)) std::cout << "Successful\n"; else std::cout << "Failed\n"; return 1; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/QuadratureP3.h
/** * QuadratureP3.h * DG++ * * Created by Adrian Lew on 10/21/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef QUADRATUREP3 #define QUADRATUREP3 #include "Quadrature.h" /*! * \brief Class for 4 point quadrature rules for tetrahedrons. * * 4-point Gauss quadrature coordinates in the tetrahedron with * 0(1,0,0), 1(0,1,0), 2(0,0,0), 3(0,0,1) as vertices. * Barycentric coordinates are used for the Gauss points. * Barycentric coordinates are specified with respect to vertices 1,2 and 4 * in that order.Coordinate of vertex 3 is not independent. * * Quadrature for Faces: * Faces are ordered as - * Face 1: 2-1-0, * Face 2: 2-0-3, * Face 3: 2-3-1, * Face 4: 0-1-3. */ class Tet_4Point: public SpecificQuadratures { public: //! Bulk quadrature static const Quadrature* const Bulk; //! Face (2-1-0) quadrature static const Quadrature* const FaceOne; //! Face (2-0-3) quadrature static const Quadrature* const FaceTwo; //! Face (2-3-1) quadrature static const Quadrature* const FaceThree; //! Face (0-1-3) quadrature static const Quadrature* const FaceFour; private: static const double BulkCoordinates[]; static const double BulkWeights[]; static const double FaceMapCoordinates[]; static const double FaceOneShapeCoordinates[]; static const double FaceOneWeights[]; static const double FaceTwoShapeCoordinates[]; static const double FaceTwoWeights[]; static const double FaceThreeShapeCoordinates[]; static const double FaceThreeWeights[]; static const double FaceFourShapeCoordinates[]; static const double FaceFourWeights[]; }; //! \brief 11 point quadrature rule for tetrahedron //! Degree of precision 4, number of points 11. class Tet_11Point: public SpecificQuadratures { public: //! Bulk quadrature static const Quadrature* const Bulk; //! \todo Include face quadrature rules if needed. private: static const double BulkCoordinates[]; static const double BulkWeights[]; }; //! \brief 15 point quadrature rule for tetrahedron //! Degree of precision 5, number of points 15. class Tet_15Point: public SpecificQuadratures { public: //! Bulk quadrature static const Quadrature* const Bulk; //! \todo Include face quadrature rules if needed. private: static const double BulkCoordinates[]; static const double BulkWeights[]; }; #endif // Sriramajayam
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/QuadratureP3.cpp
#include "QuadratureP3.h" const double Tet_4Point::BulkCoordinates[] = {0.58541020e0, 0.13819660e0, 0.13819660e0, 0.13819660e0, 0.58541020e0, 0.13819660e0, 0.13819660e0, 0.13819660e0, 0.58541020e0, 0.13819660e0, 0.13819660e0, 0.13819660e0}; const double Tet_4Point::BulkWeights [] = {1./24., 1./24., 1./24., 1./24.}; const double Tet_4Point::FaceMapCoordinates[] = {2./3., 1./6., 1./6., 2./3., 1./6., 1./6.}; // Face 1 : 2-1-0. const double Tet_4Point::FaceOneShapeCoordinates[] = { 1./6., 1./6., 0., 1./6., 2./3., 0., 2./3., 1./6., 0.}; const double Tet_4Point::FaceOneWeights [] = { 1./6., 1./6., 1./6.}; // Face 2 : 2-0-3. const double Tet_4Point::FaceTwoShapeCoordinates[] = { 1./6., 0., 1./6., 2./3., 0., 1./6., 1./6., 0., 2./3.}; const double Tet_4Point::FaceTwoWeights [] = { 1./6., 1./6., 1./6.}; // Face 3: 2-3-1. const double Tet_4Point::FaceThreeShapeCoordinates[] = { 0., 1./6., 1./6., 0., 1./6., 2./3., 0., 2./3., 1./6.}; const double Tet_4Point::FaceThreeWeights [] = { 1./6., 1./6., 1./6.}; // Face 4: 0-1-3. const double Tet_4Point::FaceFourShapeCoordinates [] = { 2./3., 1./6., 1./6., 1./6., 2./3., 1./6., 1./6., 1./6., 2./3.}; const double Tet_4Point::FaceFourWeights [] = { 1./6., 1./6., 1./6.}; const Quadrature* const Tet_4Point::Bulk = new Quadrature(Tet_4Point::BulkCoordinates, Tet_4Point::BulkWeights, 3, 4); const Quadrature* const Tet_4Point::FaceOne = new Quadrature(Tet_4Point::FaceMapCoordinates, Tet_4Point::FaceOneShapeCoordinates, Tet_4Point::FaceOneWeights, 2, 3, 3); const Quadrature* const Tet_4Point::FaceTwo = new Quadrature(Tet_4Point::FaceMapCoordinates, Tet_4Point::FaceTwoShapeCoordinates, Tet_4Point::FaceTwoWeights, 2, 3, 3); const Quadrature* const Tet_4Point::FaceThree = new Quadrature(Tet_4Point::FaceMapCoordinates, Tet_4Point::FaceThreeShapeCoordinates, Tet_4Point::FaceThreeWeights, 2, 3, 3); const Quadrature* const Tet_4Point::FaceFour = new Quadrature(Tet_4Point::FaceMapCoordinates, Tet_4Point::FaceFourShapeCoordinates, Tet_4Point::FaceFourWeights, 2, 3, 3); const double Tet_11Point::BulkCoordinates[] = {1./4., 1./4., 1./4., 11./14., 1./14., 1./14., 1./14., 11./14., 1./14., 1./14., 1./14., 11./14., 1./14., 1./14., 1./14., 0.3994035761667992, 0.3994035761667992, 0.1005964238332008, 0.3994035761667992, 0.1005964238332008, 0.3994035761667992, 0.3994035761667992, 0.1005964238332008, 0.1005964238332008, 0.1005964238332008, 0.3994035761667992, 0.3994035761667992, 0.1005964238332008, 0.3994035761667992, 0.1005964238332008, 0.1005964238332008, 0.1005964238332008, 0.3994035761667992}; const double Tet_11Point::BulkWeights[] = {-74./5625., 343./45000., 343./45000., 343./45000., 343./45000., 56./2250., 56./2250., 56./2250., 56./2250., 56./2250., 56./2250.}; const Quadrature* const Tet_11Point::Bulk = new Quadrature(Tet_11Point::BulkCoordinates, Tet_11Point::BulkWeights, 3, 11); const double Tet_15Point::BulkCoordinates[] = {1./4., 1./4., 1./4., 0., 1./3., 1./3., 1./3., 0., 1./3., 1./3., 1./3., 0., 1./3., 1./3., 1./3., 72./99., 1./11., 1./11., 1./11., 72./99., 1./11., 1./11., 1./11., 72./99., 1./11., 1./11., 1./11., 0.066550153573664, 0.066550153573664, 0.433449846426336, 0.066550153573664, 0.433449846426336, 0.066550153573664, 0.066550153573664, 0.433449846426336, 0.433449846426336, 0.433449846426336, 0.066550153573664, 0.066550153573664, 0.433449846426336, 0.433449846426336, 0.066550153573664, 0.433449846426336, 0.066550153573664, 0.433449846426336}; const double Tet_15Point::BulkWeights[] = {0.030283678097089, 0.006026785714286, 0.006026785714286, 0.006026785714286, 0.006026785714286, 0.011645249086029, 0.011645249086029, 0.011645249086029, 0.011645249086029, 0.010949141561386, 0.010949141561386, 0.010949141561386, 0.010949141561386, 0.010949141561386, 0.010949141561386}; const Quadrature* const Tet_15Point::Bulk = new Quadrature(Tet_15Point::BulkCoordinates, Tet_15Point::BulkWeights, 3, 15); // Sriramajayam
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/BasisFunctions.cpp
/* * BasisFunctions.h * DG++ * * Created by Adrian Lew on 10/21/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "BasisFunctions.h" #include "BasisFunctionsProvided.h" std::vector<double> EmptyBasisFunctions::ZeroSizeVector; const std::vector<double> BasisFunctionsProvidedExternalQuad::ZeroSizeVector;
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/BasisFunctions.h
/** * BasisFunctions.h * DG++ * * Created by Adrian Lew on 10/21/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BASISFUNCTIONS #define BASISFUNCTIONS #include "Shape.h" #include "Quadrature.h" #include "ElementGeometry.h" /** \brief BasisFunctions: Evaluation of basis functions and derivatives at the quadrature points. Abstract class. A BasisFunctions object consists of:\n 1) A set of quadrature points with quadrature weights\n 2) A set of basis functions and their derivatives evaluated at these points\n \todo So far the number of spatial dimensions, needed to transverse the getDShapes and getQuadraturePointArrays is not provided, but should be obtained from the ElementGeometry where these basis functions are in. One way in which this may be computed is using the fact that getQuadraturePointCoordinates().size()/getIntegrationWeights().size() = getDShapes().size()/getShapes().size() = spatial dimensions */ class BasisFunctions { public: inline BasisFunctions() {} inline virtual ~BasisFunctions(){} inline BasisFunctions(const BasisFunctions &) {} virtual BasisFunctions * clone() const = 0; //! Shape functions at quadrature points //! getShapes()[q*getBasisDimension()+a] //! gives the value of shape function a at quadrature point q //! //! getShapes returns an empty vector if no shape functions are available virtual const std::vector<double> & getShapes() const = 0; //! Derivatives of shape functions at quadrature points //! getDShapes()[q*getBasisDimension()*getNumberOfDerivativesPerFunction()+ //! +a*getNumberOfDerivativesPerFunction()+i] gives the //! derivative in the i-th direction of degree of freedom a at quadrature point q //! //! getDShapes returns an empty vector if no derivatives are //! available virtual const std::vector<double> & getDShapes() const = 0; //! @return vector of integration weights virtual const std::vector<double> & getIntegrationWeights() const = 0; //!< Integration weights //! Coordinates of quadrature points in the real configuration //! getQuadraturePointCoordinates() //! q*ElementGeometry::getEmbeddingDimension()+i] //! returns the i-th coordinate in real space of quadrature point q virtual const std::vector<double> & getQuadraturePointCoordinates() const = 0; //! returns the number of shape functions provided virtual size_t getBasisDimension() const = 0; //! returns the number of directional derivative for each shape function virtual size_t getNumberOfDerivativesPerFunction() const = 0; //! returns the number of number of coordinates for each Gauss point virtual size_t getSpatialDimensions() const = 0; }; /** \brief dummy set with no basis functions. This class contains only static data and has the mission of providing a BasisFunctions object that has no basis functions in it. This becomes useful, for example, as a cheap way of providing Element with a BasisFunction object that can be returned but that occupies no memory. Since Element has to be able to have a BasisFunction object per field, by utilizing this object there is no need to construct an odd order for the fields in order to save memory. */ class EmptyBasisFunctions: public BasisFunctions { public: inline EmptyBasisFunctions() {} inline virtual ~EmptyBasisFunctions(){} inline EmptyBasisFunctions(const EmptyBasisFunctions &) {} virtual EmptyBasisFunctions * clone() const { return new EmptyBasisFunctions(*this); } const std::vector<double> & getShapes() const { return ZeroSizeVector; } const std::vector<double> & getDShapes() const { return ZeroSizeVector; } const std::vector<double> & getIntegrationWeights() const { return ZeroSizeVector; } const std::vector<double> & getQuadraturePointCoordinates() const { return ZeroSizeVector; } size_t getBasisDimension() const { return 0; } size_t getNumberOfDerivativesPerFunction() const { return 0; } size_t getSpatialDimensions() const { return 0; } private: static std::vector<double> ZeroSizeVector; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/ShapesEvaluatedP13D.cpp
/* * ShapesEvaluatedP13D.cpp * DG++ * * Created by Ramsharan Rangarajan. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ShapesEvaluatedP13D.h" // Implementation of class ShapesEvaluatedP13D : const size_t ShapesP13D::bctMap[] = {0,1,3,2}; const Shape * const ShapesP13D::P13D = new Linear<3>(ShapesP13D::bctMap); const Shape * const ShapesP13D::P12D = new Linear<2>;
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/ShapesEvaluated.cpp
/* * ShapesEvaluatedImpl.cpp * DG++ * * Created by Adrian Lew on 9/7/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Quadrature.h" #include "Linear.h" #include "ShapesEvaluated.h" #include "util.h" // #include "petscblaslapack.h" #include <iostream> extern "C" void dgesv_(int *, int *, double *, int *, int *, double *, int *, int *); const Shape * const ShapesP12D::P12D = new Linear<2> ; const Shape * const ShapesP12D::P11D = new Linear<1> ; const Shape * const ShapesP11D::P11D = new Linear<1> ; void ShapesEvaluated::createObject(const ElementGeometry& EG) { const Shape& TShape = accessShape(); const Quadrature& TQuadrature = accessQuadrature(); int Na = TShape.getNumFunctions(); int Nq = TQuadrature.getNumQuadraturePoints(); int Nd = EG.getEmbeddingDimension(); int Np = EG.getParametricDimension(); LocalShapes.resize(Nq * Na); if (Np == Nd) LocalDShapes.resize(Nq * Na * Nd); LocalWeights.resize(Nq); LocalCoordinates.resize(Nq * Nd); double *DY = new double[Nd * Np]; double *Y = new double[Nd]; for (int q = 0; q < Nq; q++) { EG.map(TQuadrature.getQuadraturePoint(q), Y); for (int i = 0; i < Nd; i++) LocalCoordinates[q * Nd + i] = Y[i]; for (int a = 0; a < Na; a++) LocalShapes[q * Na + a] = TShape.getVal(a, TQuadrature.getQuadraturePointShape(q)); double Jac; EG.dMap(TQuadrature.getQuadraturePoint(q), DY, Jac); LocalWeights[q] = (TQuadrature.getQuadratureWeights(q)) * Jac; // Compute derivatives of shape functions only when the element map goes // between spaces of the same dimension if (Np == Nd) { double *DYInv = new double[Np * Np]; double *DYT = new double[Np * Np]; // Lapack { // Transpose DY to Fortran mode for (int k = 0; k < Nd; k++) for (int M = 0; M < Np; M++) { DYT[k * Nd + M] = DY[M * Np + k]; //Right hand-side DYInv[k * Nd + M] = k == M ? 1 : 0; } int *IPIV = new int[Np]; int INFO; // DYInv contains the transpose of the inverse dgesv_(&Np, &Np, DYT, &Np, IPIV, DYInv, &Np, &INFO); #ifdef DEBUG_TEST const double* ptCoord = TQuadrature.getQuadraturePoint(q); const double* shapeCoord = TQuadrature.getQuadraturePointShape(q); printIter (std::cerr << "ptCoord = ", ptCoord, ptCoord + Np); printIter (std::cerr << "shapeCoord ", shapeCoord, shapeCoord + Np); printIter (std::cerr << "Y = ", Y, Y + Np); printIter (std::cerr << "DY = ", DY, DY + Np * Np); printIter (std::cerr << "DYInv = ", DYInv, DYInv + Np * Np); std::cerr << "----------------------" << std::endl; #endif if (INFO != 0) { std::cerr << "ShapesEvaluated::CreateObject: Lapack could not invert matrix\n"; abort (); } #ifdef DEBUG_TEST // Output only useful during testing for(int r=0; r<Nd*Np; r++) std::cout << DYInv[r] << " "; std::cout << "\n"; #endif delete[] DYT; delete[] IPIV; } for (int a = 0; a < Na; a++) for (int i = 0; i < Nd; i++) { LocalDShapes[q * Na * Nd + a * Nd + i] = 0; for (int M = 0; M < Np; M++) LocalDShapes[q * Na * Nd + a * Nd + i] += TShape.getDVal(a, TQuadrature.getQuadraturePointShape(q), M) * DYInv[M * Np + i]; } delete[] DYInv; } else { std::cerr << "did not enter lapack block" << std::endl; } } #ifdef DEBUG_TEST printIter (std::cerr << "LocalDShapes = ", LocalDShapes.begin(), LocalDShapes.end()); #endif delete[] DY; delete[] Y; } ShapesEvaluated::ShapesEvaluated(const ShapesEvaluated & SE) : BasisFunctions(SE), LocalShapes(SE.LocalShapes), LocalDShapes(SE.LocalDShapes), LocalWeights(SE.LocalWeights), LocalCoordinates(SE.LocalCoordinates) { }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/ShapesEvaluatedP13D.h
/** * ShapesEvaluatedP13D.h * DG++ * * Created by Ramsharan Rangarajan. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SHAPESEVALUATEDP13D #define SHAPESEVALUATEDP13D #include "ShapesEvaluated.h" #include "Quadrature.h" #include "Linear.h" /** \brief Shape functions for P13D elements: Linear functions on tetrahedra. It containes two types of traces 1) ShapesP13D::Faces are linear functions on triangles and their dofs are those associated with the nodes of the triangular face. 2) ShapesP13D::FaceOne, ShapesP13D::FaceTwo, ShapesP13D::FaceThree and ShapesP13D::FaceFour are the full set of linear shape functions in the elements evaluated at quadrature points in each one of the faces. Instead of having 3 dofs per field per face, there are 3 dofs per field per face. Some of these values are trivially zero, i.e., those of the shape function associated to the node opposite to the face where the quadrature point is. As was the done in ShapesP12D, these are provided since ocassionally it may be necessary to have the same number of dofs as the bulk fields. In the most general case of arbitrary bases, there is generally no shape function that is zero on the face, and hence bulk and trace fields have the same number of dofs. */ class ShapesP13D: public SpecificShapesEvaluated { protected: static const size_t bctMap[]; public: static const Shape * const P13D; static const Shape * const P12D; typedef ShapesEvaluated__<P13D, Tet_1::Bulk> Bulk; typedef ShapesEvaluated__<P12D, Triangle_1::Bulk> Faces; typedef ShapesEvaluated__<P13D, Tet_1::FaceOne> FaceOne; // 2-1-0 typedef ShapesEvaluated__<P13D, Tet_1::FaceTwo> FaceTwo; // 2-0-3 typedef ShapesEvaluated__<P13D, Tet_1::FaceThree> FaceThree;// 2-3-1 typedef ShapesEvaluated__<P13D, Tet_1::FaceFour> FaceFour; // 0-1-3 }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/BasisFunctionsProvided.h
/** * BasisFunctionsProvided.h * DG++ * * Created by Adrian Lew on 10/21/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BASISFUNCTIONSPROVIDED #define BASISFUNCTIONSPROVIDED #include "Shape.h" #include "Quadrature.h" #include "ElementGeometry.h" #include "BasisFunctions.h" #include <iostream> /** \brief BasisFunctionsProvidedExternalQuad: set of basis functions and derivatives at the quadrature points provided directly at construction. The quadrature points are referenced externally, they are not kept as a copy inside the object. */ class BasisFunctionsProvidedExternalQuad: public BasisFunctions { public: //! Constructor //! //! In the following,\n //! NQuad = QuadratureWeights.size(), the total number of quadrature points\n //! NShapes = ShapesInput.size()/QuadratureWeights.size(), total number of shape //! functions provided\n //! spd = QuadratureCoords().size/QuadratureWeights.size(), number of spatial dimensions //! //! @param ShapesInput: Values of each shape function at each quadrature point.\n //! ShapesInput[ q*NShapes + a] = value of shape function "a" at quadrature point "q" //! @param DShapesInput: Values of each shape function derivative at each quadrature point.\n //! DShapesInput[ q*NShapes*spd + a*spd + i] = value of shape function "a" derivative in the i-th //! direction at quadrature point "q" //! @param QuadratureWeights: QuadratureWeights[q] contains the value of the quadrature weight at quad point "q" //! @param QuadratureCoords: QuadratureCoords[q*spd+i] contains the i-th coordinate of the position of quadrature //! point "q" //! //! If not derivatives of shape functions are available, just provide and empty vector as //! DShapesInput inline BasisFunctionsProvidedExternalQuad (const std::vector<double> &ShapesInput, const std::vector<double> &DShapesInput, const std::vector<double> &QuadratureWeights, const std::vector<double> &QuadratureCoords) : LocalShapes (ShapesInput), LocalDShapes (DShapesInput), LocalWeights (QuadratureWeights), LocalCoordinates (QuadratureCoords) { // Check that the dimensions are correct if (LocalShapes.size () % LocalWeights.size () != 0 || LocalCoordinates.size () % LocalWeights.size () != 0 || LocalDShapes.size () % LocalWeights.size () != 0 || LocalDShapes.size () % LocalShapes.size () != 0) { std::cerr << "BasisFunctionsProvidedExternalQuad::Constructor. Error\n" " Inconsistent length of some of the vectors provided\n"; exit (1); } NumberOfShapes = LocalShapes.size () / LocalWeights.size (); } //! Constructor //! //! In the following no shape functions are provided. An empty vector will be\n //! place in its place. \n //! NQuad = QuadratureWeights.size(), the total number of quadrature points\n //! spd = QuadratureCoords().size/QuadratureWeights.size(), number of spatial dimensions //! NDerivatives = LocalDShapes.size()/(NumberOfShapes*LocalWeights.size()) //! //! @param NShapes Number of shape functions for which derivatives are offered //! @param DShapesInput: Values of each shape function derivative at each quadrature point.\n //! DShapesInput[ q*NShapes*spd + a*spd + i] = value of shape function "a" derivative in the i-th //! direction at quadrature point "q" //! @param QuadratureWeights: QuadratureWeights[q] contains the value of the quadrature weight at quad point "q" //! @param QuadratureCoords: QuadratureCoords[q*spd+i] contains the i-th coordinate of the position of quadrature //! point "q" inline BasisFunctionsProvidedExternalQuad (size_t NShapes, const std::vector<double> &DShapesInput, const std::vector<double> &QuadratureWeights, const std::vector<double> &QuadratureCoords) : LocalShapes (ZeroSizeVector), LocalDShapes (DShapesInput), NumberOfShapes (NShapes), LocalWeights (QuadratureWeights), LocalCoordinates (QuadratureCoords) { // Check that the dimensions are correct if (LocalCoordinates.size () % LocalWeights.size () != 0 || LocalDShapes.size () % (LocalWeights.size () * NShapes) != 0 || LocalDShapes.size () % NShapes != 0) { std::cerr << "BasisFunctionsProvidedExternalQuad::Constructor. Error\n" " Inconsistent length of some of the vectors provided\n"; exit (1); } } inline virtual ~BasisFunctionsProvidedExternalQuad () { } inline BasisFunctionsProvidedExternalQuad (const BasisFunctionsProvidedExternalQuad &NewBas) : LocalShapes (NewBas.LocalShapes), LocalDShapes (NewBas.LocalDShapes), NumberOfShapes (NewBas.NumberOfShapes) , LocalWeights (NewBas.LocalWeights), LocalCoordinates (NewBas.LocalCoordinates) { } virtual BasisFunctionsProvidedExternalQuad * clone () const { return new BasisFunctionsProvidedExternalQuad (*this); } //! Shape functions at quadrature points //! getShapes()[q*Shape::getNumFunctions()+a] //! gives the value of shape function a at quadrature point q inline const std::vector<double> & getShapes () const { return LocalShapes; } //! Derivatives of shape functions at quadrature points //! getDShapes()[q*Shape::getNumFunctions()*ElementGeometry::getEmbeddingDimensions()+a*ElementGeometry::getEmbeddingDimensions()+i] //! gives the //! derivative in the i-th direction of degree of freedom a at quadrature point q inline const std::vector<double> & getDShapes () const { return LocalDShapes; } //!< Integration weights inline const std::vector<double> & getIntegrationWeights () const { return LocalWeights; } //! Coordinates of quadrature points in the real configuration //! getQuadraturePointCoordinates() //! [q*ElementGeometry::getEmbeddingDimension()+i] //! returns the i-th coordinate in real space of quadrature point q inline const std::vector<double> & getQuadraturePointCoordinates () const { return LocalCoordinates; } //! returns the number of shape functions provided inline size_t getBasisDimension () const { return NumberOfShapes; } //! returns the number of directional derivative for each shape function inline size_t getNumberOfDerivativesPerFunction () const { return LocalDShapes.size () / (NumberOfShapes * LocalWeights.size ()); } //! returns the number of number of coordinates for each Gauss point inline size_t getSpatialDimensions () const { return LocalCoordinates.size () / LocalWeights.size (); } private: const std::vector<double>& LocalShapes; const std::vector<double>& LocalDShapes; size_t NumberOfShapes; protected: const std::vector<double>& LocalWeights; const std::vector<double>& LocalCoordinates; static const std::vector<double> ZeroSizeVector; }; /** \brief BasisFunctionsProvided: set of basis functions and derivatives at the quadrature points provided directly at construction. The quadrature points are provided and stored inside the object */ class BasisFunctionsProvided: public BasisFunctionsProvidedExternalQuad { public: //! Constructor //! //! In the following,\n //! NQuad = QuadratureWeights.size(), the total number of quadrature points\n //! NShapes = ShapesInput.size()/QuadratureWeights.size(), total number of shape //! functions provided\n //! spd = QuadratureCoords().size/QuadratureWeights.size(), number of spatial dimensions //! //! @param ShapesInput: Values of each shape function at each quadrature point.\n //! ShapesInput[ q*NShapes + a] = value of shape function "a" at quadrature point "q" //! @param DShapesInput: Values of each shape function derivative at each quadrature point.\n //! DShapesInput[ q*NShapes*spd + a*spd + i] = value of shape function "a" derivative in the i-th //! direction at quadrature point "q" //! @param QuadratureWeights: QuadratureWeights[q] contains the value of the quadrature weight at quad point "q" //! @param QuadratureCoords: QuadratureCoords[q*spd+i] contains the i-th coordinate of the position of quadrature //! point "q" inline BasisFunctionsProvided (const std::vector<double> &ShapesInput, const std::vector<double> &DShapesInput, const std::vector<double> &QuadratureWeights, const std::vector<double> &QuadratureCoords) : BasisFunctionsProvidedExternalQuad (ShapesInput, DShapesInput, QuadratureWeights, QuadratureCoords) { } inline virtual ~BasisFunctionsProvided () { } inline BasisFunctionsProvided (const BasisFunctionsProvided &NewBas) : BasisFunctionsProvidedExternalQuad (NewBas) { } virtual BasisFunctionsProvided * clone () const { return new BasisFunctionsProvided (*this); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/ShapesEvaluated.h
/** * ShapesEvaluated.h * DG++ * * Created by Adrian Lew on 9/7/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SHAPESEVALUATED #define SHAPESEVALUATED #include <string> #include "Shape.h" #include "Quadrature.h" #include "ElementGeometry.h" #include "BasisFunctions.h" #include "Linear.h" /** ShapesEvaluated: Evaluation of the shape functions and derivatives at the quadrature points. Abstract class. ShapesEvaluated is the class that takes the element geometry, a quadrature rule and shape functions on the reference element, and computes the values of the shape functions and their derivatives at the quadrature points. As opposed to Shapes, there will be one or more ShapesEvaluated objects per element in the mesh. Each different interpolation needed in an element will have a different ShapesEvaluated object. This class provides all functionality for the templated derived classes ShapesEvaluated__. Only two abstract functions are left to be defined by derived classes, accessShape and accessQuadrature. Objects in this class should only be constructed by derived classes. ShapesEvaluated evaluates ElementGeometry::(D)map at the quadrature point (map)Coordinates using Quadrature::getQuadraturePoint(). ShapesEvaluated evaluates Shape functions at the quadrature point (Shape)Coordinates using Quadrature::getQuadraturePointShape(). \warning: The type of coordinates used to evaluate functions in Shape and ElementGeometry::(D)map (barycentric, Cartesian, etc.) should be consistent with those provided in Quadrature::getQuadraturePoint. In other words, if the Quadrature object returns Cartesian coordinates, the Shape and ElementGeometry objects should evaluate functions taking Cartesian coordinates as arguments. \todo It would be nice to provide an interface of iterators to navigate the vectors, so that it is not necessary to remember in which order the data is stored in the vector. In the interest of simiplicity, this is for the moment skipped. \todo It would useful to have the option of not computing the derivatives of the shape functions if not needed. Right now, it is not possible. \todo Make coordinate types so that it is not necessary to check whether one is using the right convention between the three related classes. \todo The computation of derivatives of shape functions with respect to the coordinates of the embedding space can only be performed if the ElementGeometry::map has domain and ranges of the same dimension. Otherwise, the derivatives should be computed with respect to some system of coordinates on the manifold. This will likely need to be revisited in the case of shells. \todo Need to fix the Lapack interface... it is too particular to Mac here, and even not the best way to do it in Mac... */ class ShapesEvaluated: public BasisFunctions { protected: ShapesEvaluated() {} inline virtual ~ShapesEvaluated(){} ShapesEvaluated(const ShapesEvaluated &SEI); public: // Accessors/Mutators: inline const std::vector<double> & getShapes() const { return LocalShapes; } inline const std::vector<double> & getDShapes() const { return LocalDShapes; } inline const std::vector<double> & getIntegrationWeights() const { return LocalWeights;} inline const std::vector<double> & getQuadraturePointCoordinates() const { return LocalCoordinates; } //! returns the number of shape functions provided inline size_t getBasisDimension() const { return accessShape().getNumFunctions(); } //! returns the number of directional derivative for each shape function inline size_t getNumberOfDerivativesPerFunction() const { return LocalDShapes.size()/LocalShapes.size(); } //! returns the number of number of coordinates for each Gauss point inline size_t getSpatialDimensions() const { return LocalCoordinates.size()/LocalWeights.size(); } protected: //! Returns the specific Shape objects in derived classes. virtual const Shape& accessShape() const = 0; //! Quadrature type //! Returns the specific Quadrature objects in derived classes. virtual const Quadrature& accessQuadrature() const = 0; //! Since it is not possible to have a virtual constructor, //! one is emulated below only accessible from derived classes //! The virtual aspect are the calls to accessShape and accessQuadrature. void createObject(const ElementGeometry& eg); private: std::vector<double> LocalShapes; std::vector<double> LocalDShapes; std::vector<double> LocalWeights; std::vector<double> LocalCoordinates; }; /** \brief ShapesEvaluated__: This class is the one that brings the flexibility for building shape functions of different types evaluated at different quadrature points. The class takes the Shape and Quadrature types as template arguments. An object is constructed by providing an ElementGeometry object. ShapesEvaluated_ and ShapesEvaluated__ could have been made into a single templated class. By splitting them the templated part of the class is very small. \todo Should I perhaps have the constructors of the class to be protected, making the classes using ShapesEvaluated__ friends? Since the ElementGeometry is not stored or referenced from within the class, it would prevent unwanted mistakes. \warning When a ShapesEvaluated__ object is constructed on a geometry where the parametric and embedding dimensions are different, the constructor is not warning that it does not compute the derivatives for the shape functions. These objects, however, still provide the values of the Shape functions themselves. \todo In the future, as remarked in ShapesEvaluated as well, we need to separate the need to provide the Shape function values from the one of providing the derivatives as well, perhaps through multiple inheritance. */ template <const Shape * const& ShapeObj, const Quadrature * const& QuadObj> class ShapesEvaluated__:public ShapesEvaluated { public: inline ShapesEvaluated__(const ElementGeometry& EG): ShapesEvaluated() { createObject(EG); } virtual ShapesEvaluated__* clone() const { return new ShapesEvaluated__(*this); } ShapesEvaluated__(const ShapesEvaluated__ & SE): ShapesEvaluated (SE) { } const Shape& accessShape() const { return *ShapeObj;} const Quadrature& accessQuadrature() const { return *QuadObj;} }; // Build specific ShapesEvaluated //! Specific ShapesEvaluated types class SpecificShapesEvaluated {}; //! Shape functions for P12D elements: Linear functions on Triangles\n //! It contains two types of traces\n //! 1) ShapesP12D::Faces are linear functions on Segments, and their degrees of freedom //! are those associated to the nodes of the Segment. //! //! 2) ShapesP12D::FaceOne, ShapesP12D::FaceTwo, ShapesP12D::FaceThree are the full set //! of linear shape functions in the element evaluated at quadrature points in each one //! of the faces. Instead of having then 2 degrees of freedom per field per face, there are //! here 3 degrees of freedom per field per face. Of course, some of these values are //! trivially zero, i.e., those of the shape functions associated to the node opposite //! to the face where the quadrature point is. These are provided since ocassionally //! it may be necessary to have the boundary fields have the same //! number of degrees of freedom as the bulk fields. In the most general case of //! arbitrary bases, there is generally no shape functions that is //! identically zero on the face, and hence bulk and trace fields have the same number of //! degrees of freedom. With these shape functions, for example, it is possible to compute //! the normal derivative of each basis function at the boundary. class ShapesP12D: public SpecificShapesEvaluated { public: //! Shape functions on reference triangle static const Shape * const P12D; //! Shape functions on reference segment static const Shape * const P11D; //! Bulk shape functions typedef ShapesEvaluated__<P12D,Triangle_1::Bulk> Bulk; //! Shape functions for FaceOne, FaceTwo and FaceThree typedef ShapesEvaluated__<P11D,Line_1::Bulk> Faces; //! Full shape functions for FaceOne typedef ShapesEvaluated__<P12D,Triangle_1::FaceOne> FaceOne; //! Full shape functions for FaceTwo typedef ShapesEvaluated__<P12D,Triangle_1::FaceTwo> FaceTwo; //! Full shape functions for FaceThree typedef ShapesEvaluated__<P12D,Triangle_1::FaceThree> FaceThree; }; //! Shape functions for P11D elements: Linear functions on segments class ShapesP11D: public SpecificShapesEvaluated { public: //! Shape functions on reference segment static const Shape * const P11D; //! Bulk shape functions typedef ShapesEvaluated__<P11D,Line_1::Bulk> Bulk; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/test/testLinearSE-model_output
Parametric triangle Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Twice Parametric triangle Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 0.5 0 0 0.5 -0.5 -0.5 0.5 0 0 0.5 -0.5 -0.5 0.5 0 0 0.5 -0.5 -0.5 Integration weights 0.666667 0.666667 0.666667 Quadrature point coordinates 1.33333 0.333333 0.333333 1.33333 0.333333 0.333333 Reordered nodes of twice parametric triangle Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values -0.5 -0.5 0.5 0 0 0.5 -0.5 -0.5 0.5 0 0 0.5 -0.5 -0.5 0.5 0 0 0.5 Integration weights 0.666667 0.666667 0.666667 Quadrature point coordinates 0.333333 0.333333 1.33333 0.333333 0.333333 1.33333 Equilateral triangle with area sqrt(3) Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values -0.5 -0.288675 0.5 -0.288675 0 0.57735 -0.5 -0.288675 0.5 -0.288675 0 0.57735 -0.5 -0.288675 0.5 -0.288675 0 0.57735 Integration weights 0.57735 0.57735 0.57735 Quadrature point coordinates 0.5 0.288675 1.5 0.288675 1 1.1547 Irregular triangle with area sqrt(3) Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values -0.5 0.144338 0.5 -0.721688 5.55112e-17 0.57735 -0.5 0.144338 0.5 -0.721688 5.55112e-17 0.57735 -0.5 0.144338 0.5 -0.721688 5.55112e-17 0.57735 Integration weights 0.57735 0.57735 0.57735 Quadrature point coordinates 0.75 0.288675 1.75 0.288675 2 1.1547
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/test/testQuadraticSE.cpp
// Sriramajayam // Purpose : To check ShapesEvaluatedP13D #include "Triangle.h" #include "ShapesEvaluatedP22D.h" #include <iostream> static void PrintData(ShapesP22D::Bulk PShapes); int main() { double TempVertices0[] = {0,0, 1,0, 0,1}; std::vector<double> Vertices0(TempVertices0,TempVertices0+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); Triangle<2> T1(1,2,3); ShapesP22D::Bulk P1Shapes(&T1); std::cout << "Parametric triangle\n"; PrintData(P1Shapes); std::cout << "\nTwice Parametric triangle\n"; double TempVertices1[] = {0,0, 2,0, 0,2}; std::vector<double> Vertices1(TempVertices1,TempVertices1+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices1); Triangle<2> T2(1,2,3); ShapesP22D::Bulk P2Shapes(&T2); PrintData(P2Shapes); } static void PrintData(ShapesP22D::Bulk PShapes) { std::cout << "Function values\n"; for(unsigned int a=0; a<PShapes.getShapes().size(); a++) std::cout << PShapes.getShapes()[a] << " "; std::cout << "\n"; std::cout << "Function derivative values\n"; for(unsigned int a=0; a<PShapes.getDShapes().size(); a++) std::cout << PShapes.getDShapes()[a] << " "; std::cout << "\n"; std::cout << "Integration weights\n"; for(unsigned int a=0; a<PShapes.getIntegrationWeights().size(); a++) std::cout << PShapes.getIntegrationWeights()[a] << " "; std::cout << "\n"; std::cout << "Quadrature point coordinates\n"; for(unsigned int a=0; a<PShapes.getQuadraturePointCoordinates().size(); a++) std::cout << PShapes.getQuadraturePointCoordinates()[a] << " "; std::cout << "\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/test/testLinearSE.cpp
/* * testLinearSE.cpp * DG++ * * Created by Adrian Lew on 9/9/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Triangle.h" #include "ShapesEvaluated.h" #include <iostream> static void PrintData(ShapesP12D::Bulk P10Shapes); int main() { double V0[] = {1,0,0,1,0,0}; std::vector<double> Vertices0(V0, V0+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); Triangle<2> P10(1,2,3); ShapesP12D::Bulk P10Shapes(&P10); std::cout << "Parametric triangle\n"; PrintData(P10Shapes); std::cout << "\nTwice Parametric triangle\n"; double V1[] = {2,0,0,2,0,0}; std::vector<double> Vertices1(V1, V1+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices1); Triangle<2> P11(1,2,3); ShapesP12D::Bulk P11Shapes(&P11); PrintData(P11Shapes); std::cout << "\nReordered nodes of twice parametric triangle\n"; double V2[] = {0,0,2,0,0,2}; std::vector<double> Vertices2(V2, V2+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices2); Triangle<2> P12(1,2,3); ShapesP12D::Bulk P12Shapes(&P12); PrintData(P12Shapes); std::cout << "\n Equilateral triangle with area sqrt(3)\n"; double V3[] = {0,0,2,0,1,sqrt(3)}; std::vector<double> Vertices3(V3, V3+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices3); Triangle<2> P13(1,2,3); ShapesP12D::Bulk P13Shapes(&P13); PrintData(P13Shapes); std::cout << "\n Irregular triangle with area sqrt(3)\n"; double V4[] = {0,0,2,0,2.5,sqrt(3)}; std::vector<double> Vertices4(V4, V4+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices4); Triangle<2> P14(1,2,3); ShapesP12D::Bulk P14Shapes(&P14); PrintData(P14Shapes); } static void PrintData(ShapesP12D::Bulk P10Shapes) { std::cout << "Function values\n"; for(unsigned int a=0; a<P10Shapes.getShapes().size(); a++) std::cout << P10Shapes.getShapes()[a] << " "; std::cout << "\n"; std::cout << "Function derivative values\n"; for(unsigned int a=0; a<P10Shapes.getDShapes().size(); a++) std::cout << P10Shapes.getDShapes()[a] << " "; std::cout << "\n"; std::cout << "Integration weights\n"; for(unsigned int a=0; a<P10Shapes.getIntegrationWeights().size(); a++) std::cout << P10Shapes.getIntegrationWeights()[a] << " "; std::cout << "\n"; std::cout << "Quadrature point coordinates\n"; for(unsigned int a=0; a<P10Shapes.getQuadraturePointCoordinates().size(); a++) std::cout << P10Shapes.getQuadraturePointCoordinates()[a] << " "; std::cout << "\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/test/testBasisFunctionsProvided.cpp
/* * testLinearSE.cpp * DG++ * * Created by Adrian Lew on 9/9/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Triangle.h" #include "ShapesEvaluated.h" #include "BasisFunctionsProvided.h" #include <iostream> static void PrintData(const BasisFunctions & P10Shapes); int main() { double V0[] = {1,0,0,1,0,0}; std::vector<double> Vertices0(V0, V0+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); Triangle<2> P10(1,2,3); ShapesP12D::Bulk * P10Shapes = new ShapesP12D::Bulk(&P10); BasisFunctionsProvided BFS(P10Shapes->getShapes(), P10Shapes->getDShapes(), P10Shapes->getIntegrationWeights(), P10Shapes->getQuadraturePointCoordinates()); BasisFunctionsProvidedExternalQuad BFSExternalQuad(P10Shapes->getShapes(), P10Shapes->getDShapes(), P10Shapes->getIntegrationWeights(), P10Shapes->getQuadraturePointCoordinates()); BasisFunctionsProvidedExternalQuad BFSExternalQuadNoShapes(2, P10Shapes->getDShapes(), P10Shapes->getIntegrationWeights(), P10Shapes->getQuadraturePointCoordinates()); std::cout << "\nPrint data before deleting original shapes\n"; std::cout << "\n\nTest BasisFunctionProvided\n"; PrintData(BFS); std::cout << "\n\nTest BasisFunctionProvidedExternalQuad\n"; PrintData(BFSExternalQuad); std::cout << "\n\nTest BasisFunctionProvidedExternalQuadNoShapes\n"; PrintData(BFSExternalQuadNoShapes); std::cout << "\n\nTest Copy constructors\n"; BasisFunctionsProvided BFSCopy(BFS); BasisFunctionsProvidedExternalQuad BFSExternalQuadCopy(BFSExternalQuad); std::cout << "\n\nTest BasisFunctionProvided\n"; PrintData(BFSCopy); std::cout << "\n\nTest BasisFunctionProvidedExternalQuad\n"; PrintData(BFSExternalQuadCopy); std::cout << "\n\nTest cloning\n"; BasisFunctions * BFSClone = BFS.clone(); BasisFunctions * BFSExternalQuadClone = BFSExternalQuad.clone(); std::cout << "\n\nTest BasisFunctionProvided\n"; PrintData(*BFSClone); std::cout << "\n\nTest BasisFunctionProvidedExternalQuad\n"; PrintData(*BFSExternalQuadClone); delete BFSClone; delete BFSExternalQuadClone; delete P10Shapes; std::cout << "\nPrint data after deleted original shapes \n"; PrintData(BFS); } static void PrintData(const BasisFunctions & P10Shapes) { std::cout << "Function values\n"; for(unsigned int a=0; a<P10Shapes.getShapes().size(); a++) std::cout << P10Shapes.getShapes()[a] << " "; std::cout << "\n"; std::cout << "Function derivative values\n"; for(unsigned int a=0; a<P10Shapes.getDShapes().size(); a++) std::cout << P10Shapes.getDShapes()[a] << " "; std::cout << "\n"; std::cout << "Integration weights\n"; for(unsigned int a=0; a<P10Shapes.getIntegrationWeights().size(); a++) std::cout << P10Shapes.getIntegrationWeights()[a] << " "; std::cout << "\n"; std::cout << "Quadrature point coordinates\n"; for(unsigned int a=0; a<P10Shapes.getQuadraturePointCoordinates().size(); a++) std::cout << P10Shapes.getQuadraturePointCoordinates()[a] << " "; std::cout << "\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/test/testBasisFunctionsProvided-model_output
Print data before deleting original shapes Test BasisFunctionProvided Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Test BasisFunctionProvidedExternalQuad Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Test BasisFunctionProvidedExternalQuadNoShapes Function values Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Test Copy constructors Test BasisFunctionProvided Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.166667 0.166667 0.166667 Test BasisFunctionProvidedExternalQuad Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Test cloning Test BasisFunctionProvided Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.166667 0.166667 0.166667 Test BasisFunctionProvidedExternalQuad Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Print data after deleted original shapes Function values 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Function derivative values 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weights 0.166667 0.166667 0.166667 Quadrature point coordinates 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShapesEvaluated/test/testLinear3DSE.cpp
// Sriramajayam // Purpose : To check ShapesEvaluatedP13D #include "Tetrahedron.h" #include "ShapesEvaluatedP13D.h" #include <iostream> static void PrintData(ShapesP13D::Bulk PShapes); int main() { double TempVertices0[] = {1,0,0, 0,1,0, 0,0,0, 0,0,1}; std::vector<double> Vertices0(TempVertices0,TempVertices0+12); Tetrahedron::SetGlobalCoordinatesArray(Vertices0); Tetrahedron P1(1,2,3,4); ShapesP13D::Bulk P1Shapes(P1); std::cout << "Parametric tet\n"; PrintData(P1Shapes); std::cout << "\nTwice Parametric tet\n"; double TempVertices1[] = {2,0,0, 0,2,0, 0,0,0, 0,0,2}; std::vector<double> Vertices1(TempVertices1,TempVertices1+12); Tetrahedron::SetGlobalCoordinatesArray(Vertices1); Tetrahedron P2(1,2,3,4); ShapesP13D::Bulk P2Shapes(P2); PrintData(P2Shapes); } static void PrintData(ShapesP13D::Bulk PShapes) { std::cout << "Function values\n"; for(unsigned int a=0; a<PShapes.getShapes().size(); a++) std::cout << PShapes.getShapes()[a] << " "; std::cout << "\n"; std::cout << "Function derivative values\n"; for(unsigned int a=0; a<PShapes.getDShapes().size(); a++) std::cout << PShapes.getDShapes()[a] << " "; std::cout << "\n"; std::cout << "Integration weights\n"; for(unsigned int a=0; a<PShapes.getIntegrationWeights().size(); a++) std::cout << PShapes.getIntegrationWeights()[a] << " "; std::cout << "\n"; std::cout << "Quadrature point coordinates\n"; for(unsigned int a=0; a<PShapes.getQuadraturePointCoordinates().size(); a++) std::cout << PShapes.getQuadraturePointCoordinates()[a] << " "; std::cout << "\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/Tetrahedron.cpp
#include "Tetrahedron.h" const double Tetrahedron::ParamCoord[] = {1,0,0, // Parametric coordinates of the tet. 0,1,0, 0,0,0, 0,0,1}; const size_t Tetrahedron::FaceNodes[] = {2,1,0, // face 0 2,0,3, // face 1 2,3,1, // face 2 0,1,3}; // face 3
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/ElementGeometry.h
/** * ElementGeometry.h: Geometry of an element. e.g. a triangle or tetrahedron * DG++ * * Created by Adrian Lew on 9/4/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ELEMENTGEOMETRY #define ELEMENTGEOMETRY #include "AuxDefs.h" #include <string> #include <vector> #include <iostream> #include <cmath> /** \brief ElementGeometry: Defines the geometry of the polytope over which the interpolation takes place ElementGeometry consists of:\n 1) A set of vertices that define a convex hull, the domain of the polytope\n 2) A map from a parametric, reference polytope to the real polytope. This map is one-to-one, and may have domain and range in Euclidean spaces of different dimensions. In this way it is possible to map the parametric configuration of a planar triangle into three-dimensional real space as needed for plates and shells.\n 3) A name for the polytope, for identification purposes whenever needed.\n The idea of the class is to avoid having copies of the vertices coordinates in the object, only the connectivity. */ class ElementGeometry { public: inline ElementGeometry(){} inline virtual ~ElementGeometry(){} inline ElementGeometry(const ElementGeometry &){} virtual ElementGeometry * clone() const = 0; //! @return number of vertices virtual size_t getNumVertices() const = 0; //!@return ref to Vertices of the polytope. virtual const std::vector <GlobalNodalIndex>& getConnectivity() const = 0; //! @return Name of type of polytope. virtual const std::string getPolytopeName() const = 0; //! @return spatial dimension e.g. 2 for 2D virtual size_t getSpatialDimension () const = 0; //! Number of dimensions in parametric configuration virtual size_t getParametricDimension() const = 0; //! Number of dimensions in the real configuration virtual size_t getEmbeddingDimension() const = 0; //! map from parametric to real configuration //! @param X parametric coordinates //! @param Y returned real coordinates virtual void map(const double * X, double *Y) const = 0; //! Derivative of map from parametric to real configuration //! @param X parametric coordinates. //! @param Jac returns absolute value of the Jacobian of the map. //! @param DY returns derivative of the map. //! Here DY[a*getEmbeddingDimension()+i] //! contains the derivative in the a-th direction //! of the i-th coordinate. virtual void dMap(const double * X, double *DY, double &Jac) const = 0; //! Consistency test for map and its derivative //! @param X parametric coordinates at which to test //! @param Pert size of the perturbation with which to compute numerical //! derivatives (X->X+Pert) virtual bool consistencyTest(const double * X, const double Pert) const = 0; //! Number of faces the polytope has virtual size_t getNumFaces() const = 0; //! Creates and returns a new ElementGeometry object corresponding //! to face "e" in the polytope. The object has to be destroyed //! with delete by the recipient. //! //! @param e face number, starting from 0 //! //! Returns a null pointer if "e" is out of range virtual ElementGeometry * getFaceGeometry(size_t e) const = 0; //! Computes the Inner radius of the ElementGeometry object //! //! This is defined as the radius of the largest sphere that can be fit inside the polytope. virtual double getInRadius() const = 0; //! Computes the Outer radius of the ElementGeometry object //! //! This is defined as the radius of the smallest sphere that contains the object. virtual double getOutRadius() const = 0; //! Compute external normal for a face //! //! @param e: face number for which the normal is desired //! @param vNormal: output of the three Cartesian components of the normal vector virtual void computeNormal (size_t e, std::vector<double>& vNormal) const = 0; /** * Returns the value of dimension 'i' of local node 'a' of the eleement * * @param a local index of the node in [0..numNodes) * @param i local index of dimension (x or y or z) in [0..Dim) */ virtual double getCoordinate (size_t a, size_t i) const = 0; /** * Computes the center of the element (the way center is defined may be * different for different elements) * * @param center output vector containing the coordinates of the center */ virtual void computeCenter (std::vector<double>& center) const = 0; }; /** * Base class with common functionality */ template <size_t SPD> class AbstractGeom : public ElementGeometry { private: const std::vector<double>& globalCoordVec; std::vector<GlobalNodalIndex> connectivity; protected: static const size_t SP_DIM = SPD; /** * @return ref to the vector that contains global coordinates for all mesh nodes */ const std::vector<double>& getGlobalCoordVec () const { return globalCoordVec; } public: /** * @param globalCoordVec is a reference to the vector containing coordinates of all nodes * Coordinates of node i in N dimensional space are in locations [N*i, N*(i+1)) * @param connectivity is a vector containing ids of nodes of this element in the mesh */ AbstractGeom (const std::vector<double>& globalCoordVec, const std::vector<GlobalNodalIndex>& connectivity) :ElementGeometry (), globalCoordVec(globalCoordVec), connectivity (connectivity) { } AbstractGeom (const AbstractGeom<SPD>& that) : ElementGeometry (that), globalCoordVec (that.globalCoordVec), connectivity (that.connectivity) { } virtual size_t getSpatialDimension () const { return SP_DIM; } virtual const std::vector<GlobalNodalIndex>& getConnectivity () const { return connectivity; } virtual bool consistencyTest (const double* X, const double Pert) const { double *DYNum = new double[getParametricDimension() * getEmbeddingDimension()]; double *DY = new double[getParametricDimension() * getEmbeddingDimension()]; double *Xpert = new double[getParametricDimension()]; double *Yplus = new double[getEmbeddingDimension()]; double *Yminus = new double[getEmbeddingDimension()]; double Jac; if (Pert <= 0) std::cerr << "ElementGeometry::ConsistencyTest - Pert cannot be less or equal than zero\n"; for (size_t a = 0; a < getParametricDimension(); a++) Xpert[a] = X[a]; dMap(X, DY, Jac); for (size_t a = 0; a < getParametricDimension(); a++) { Xpert[a] = X[a] + Pert; map(Xpert, Yplus); Xpert[a] = X[a] - Pert; map(Xpert, Yminus); Xpert[a] = X[a]; for (size_t i = 0; i < getEmbeddingDimension(); i++) DYNum[a * getEmbeddingDimension() + i] = (Yplus[i] - Yminus[i]) / (2 * Pert); } double error = 0; double normX = 0; double normDYNum = 0; double normDY = 0; for (size_t a = 0; a < getParametricDimension(); a++) { normX += X[a] * X[a]; for (size_t i = 0; i < getEmbeddingDimension(); i++) { error += pow(DY[a * getEmbeddingDimension() + i] - DYNum[a * getEmbeddingDimension() + i], 2.); normDY += pow(DY[a * getEmbeddingDimension() + i], 2.); normDYNum += pow(DYNum[a * getEmbeddingDimension() + i], 2.); } } error = sqrt(error); normX = sqrt(normX); normDY = sqrt(normDY); normDYNum = sqrt(normDYNum); delete[] Yplus; delete[] Yminus; delete[] Xpert; delete[] DYNum; delete[] DY; if (error * (normX + Pert) < (normDY < normDYNum ? normDYNum : normDY) * Pert * 10) return true; else return false; } /** * @param a node id * @param i dimension id * @return value of dimension 'i' of coordinates of node 'a' */ virtual double getCoordinate (size_t a, size_t i) const { // 0-based numbering of nodes in the mesh size_t index = getConnectivity ()[a] * getSpatialDimension() + i; return globalCoordVec[index]; } virtual void computeCenter (std::vector<double>& center) const { std::cerr << "computeCenter not implemented" << std::endl; abort (); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/Tetrahedron.h
/** * Tetrahedron.h * DG++ * * Created by Adrian Lew on 9/4/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TETRAHEDRON_H #define TETRAHEDRON_H #include "Galois/Runtime/ll/gio.h" #include <algorithm> #include <cassert> #include "ElementGeometry.h" #include "Triangle.h" /** \brief Geometry of 3D tetrahedra. A tetrahedron is: 1) A set of indices that describe the connectivity of the tetrahedran, properly oriented. 2) An affine map from a three-dimensional tetrahedron (parametric configuration) with volume 1/6 to the convex hull of 4 vertices. The parametric configuration of the tetrahedron is 0(1,0,0), 1(0,1,0), 2(0,0,0), 3(0,0,1). The parametric coordinates are the ones associated with vertices 0,1 and 3. The faces (for the purpose of quadrature points) are ordered as: 1) Face 1: 2-1-0, 2) Face 2: 2-0-3, 3) Face 3: 2-3-1, 4) Face 4: 0-1-3. The convention used in numbering these faces is that the resulting normal is always outward. */ #define TET_SPD 3 class Tetrahedron: public AbstractGeom<TET_SPD> { public: static const double ParamCoord[]; static const size_t FaceNodes[]; public: Tetrahedron (const std::vector<double>& globalCoordVec, const std::vector<GlobalNodalIndex>& connectivity) :AbstractGeom<TET_SPD> (globalCoordVec, connectivity) { assert (connectivity.size () == 4); } Tetrahedron(const Tetrahedron & that) : AbstractGeom<TET_SPD>(that) { } virtual Tetrahedron* clone() const { return new Tetrahedron(*this); } //! Returns the number of vertices. inline size_t getNumVertices() const { return 4; } //! Returns the name of the geometry. It clarifies the meaning of the connectivity array. inline const std::string getPolytopeName() const { return "TETRAHEDRON"; } //! Returns the number of dimensions in the parametric configuartion. inline size_t getParametricDimension() const { return 3; } //! Returns the number of dimensions in the real configuration. inline size_t getEmbeddingDimension() const { return 3; } //! Number of faces the polytope has. inline size_t getNumFaces() const { return 4; } //! map from parametric to real configuration. //! \param X parametric coordinates. //! \param Y returned real coordinates. void map(const double *X, double *Y) const { const size_t sd = AbstractGeom<TET_SPD>::getSpatialDimension (); for(size_t i=0; i<sd; i++) Y[i] = X[0]*AbstractGeom<TET_SPD>::getCoordinate(0,i) + X[1]*AbstractGeom<TET_SPD>::getCoordinate(1,i) + X[2]*AbstractGeom<TET_SPD>::getCoordinate(3,i) + (1.0-X[0]-X[1]-X[2])*AbstractGeom<TET_SPD>::getCoordinate(2,i); } //! Derivative of the map from the parametric to the real configuration. //! \param X parametric cooridnates //! \param Jac returns Jacobian of the map. //! \param DY returnd derivative of the map. //! Here DY[a*getEmbeddingDimension()+i] contains the derivative of the a-th direction of the i-th coordinate. void dMap(const double *X, double *DY, double &Jac) const { const size_t sd = AbstractGeom<TET_SPD>::getSpatialDimension (); // spatial_dimension. for(size_t i=0; i<sd; i++) // Loop over x,y,z { DY[i] = AbstractGeom<TET_SPD>::getCoordinate(0,i)-AbstractGeom<TET_SPD>::getCoordinate(2,i); DY[sd*1+i] = AbstractGeom<TET_SPD>::getCoordinate(1,i)-AbstractGeom<TET_SPD>::getCoordinate(2,i); DY[sd*2+i] = AbstractGeom<TET_SPD>::getCoordinate(3,i)-AbstractGeom<TET_SPD>::getCoordinate(2,i); } Jac = 0.; for(size_t i=0; i<sd; i++) { size_t i1 = (i+1)%sd; size_t i2 = (i+2)%sd; Jac += DY[i]*(DY[1*sd+i1]*DY[2*sd+i2] - DY[2*sd+i1]*DY[1*sd+i2]); } Jac = fabs(Jac); } //! Creates a new ElementGeometry object corresponding to face 'e' in the polytope. The object ghas to be //! deleted by the recepient. //! \param e facenumber , starting from 0. //! Prompts an error if an invalid face is requested. Triangle<3> * getFaceGeometry(size_t e) const { if(e<=3) { std::vector<GlobalNodalIndex> conn(FaceNodes + 3*e, FaceNodes + 3*e + 2); return new Triangle<TET_SPD> (AbstractGeom<TET_SPD>::getGlobalCoordVec (), conn); // return new Triangle<3>(AbstractGeom<TET_SPD>::getConnectivity()[FaceNodes[3*e+0]], // AbstractGeom<TET_SPD>::getConnectivity()[FaceNodes[3*e+1]], // AbstractGeom<TET_SPD>::getConnectivity()[FaceNodes[3*e+2]]); } GALOIS_DIE("Tetrahedron::getFaceGeometry() : Request for invalid face."); return NULL; } //! get the inradius double getInRadius(void) const { double a[3],b[3],c[3],o,t[3],d[3],t1[3],t2[3], t3[3]; for(size_t i=0;i<3;i++) { o = AbstractGeom<TET_SPD>::getCoordinate(0,i); a[i]=AbstractGeom<TET_SPD>::getCoordinate(1,i) - o; b[i]=AbstractGeom<TET_SPD>::getCoordinate(2,i) - o; c[i]=AbstractGeom<TET_SPD>::getCoordinate(3,i) - o; } cross(b,c,t); cross(c,a,d); d[0]+=t[0]; d[1]+=t[1]; d[2]+=t[2]; cross(a,b,t); d[0]+=t[0]; d[1]+=t[1]; d[2]+=t[2]; cross(b,c,t); cross(b,c,t1); cross(c,a,t2); cross(a,b,t3); double rv = (dot(a,t)/(mag(t1)+mag(t2)+mag(t3)+ mag(d))); return(rv); } //! get the outradius -- radius of the circumscribed sphere double getOutRadius(void) const { double x[4],y[4],z[4],r2[4],ones[4]; double M11, M12, M13, M14, M15; double **a; a = new double*[4]; for(size_t i = 0; i < 4; i++) { x[i] = AbstractGeom<TET_SPD>::getCoordinate(i,0); y[i] = AbstractGeom<TET_SPD>::getCoordinate(i,1); z[i] = AbstractGeom<TET_SPD>::getCoordinate(i,2); r2[i] = x[i]*x[i] + y[i]*y[i] + z[i]*z[i]; ones[i] = 1.0; } a[0] = x; a[1] = y; a[2] = z; a[3] = ones; M11 = determinant(a,4); a[0] = r2; M12 = determinant(a,4); a[1] = x; M13 = determinant(a,4); a[2] = y; M14 = determinant(a,4); a[3] = z; M15 = determinant(a,4); double x0,y0,z0; x0 = 0.5 * M12/M11; y0 = -0.5 * M13/M11; z0 = 0.5 * M14/M11; delete[] a; return(sqrt(x0*x0 + y0*y0 + z0*z0 - M15/M11)); } //! Compute external normal for a face //! //! @param e: face number for which the normal is desired //! @param vNormal: output of the three Cartesian components of the normal vector virtual void computeNormal (size_t e, std::vector<double>& vNormal) const { const size_t sd = AbstractGeom<TET_SPD>::SP_DIM; size_t n0, n1, n2; // Local node numbers of face 'e' n0 = FaceNodes[3*e]; n1 = FaceNodes[3*e+1]; n2 = FaceNodes[3*e+2]; // Finding the coordinates of each node of face 'e': double p0[sd], p1[sd], p2[sd]; map(&ParamCoord[3*n0], p0); map(&ParamCoord[3*n1], p1); map(&ParamCoord[3*n2], p2); double L01[sd]; double L02[sd]; for(size_t k=0; k<sd; k++) { L01[k] = p1[k]-p0[k]; L02[k] = p2[k]-p0[k]; } if(vNormal.size() < sd) vNormal.resize(sd); double vnorm2=0.; for(size_t k=0; k<sd; k++) { size_t n1 = (k+1)%sd; size_t n2 = (k+2)%sd; vNormal[k] = L01[n1]*L02[n2] - L01[n2]*L02[n1]; vnorm2 += vNormal[k]*vNormal[k]; } for(size_t k=0; k<sd; k++) vNormal[k] /= sqrt(vnorm2); } protected: //! a vector array //! @return magnitued of the vector static double mag(const double *a) { double rv = sqrt(dot(a,a)); return(rv); } //! @param a vector size 3 //! @param b vector size 3 //! @return dot product of vectors a and b static double dot(const double *a,const double *b) { return(a[0]*b[0] + a[1]*b[1] + a[2]*b[2]); } //! @param a first input vector size 3 //! @param b second input vector size 3 //! @param rv output vector containing cross product of a and b (size 3) static void cross(const double *a,const double *b, double *rv) { rv[0] = a[1]*b[2] - a[2]*b[1]; rv[1] = a[2]*b[0] - a[0]*b[2]; rv[2] = a[0]*b[1] - a[1]*b[0]; } //! @param a square matrix //! @param n number of rows and cols in matrix //! @return determinant of the matrix static double determinant(double **a,size_t n) { size_t i,j,j1,j2; double det = 0; double **m = NULL; if (n < 1) { /* Error */ } else if (n == 1) { /* Shouldn't get used */ det = a[0][0]; } else if (n == 2) { det = a[0][0] * a[1][1] - a[1][0] * a[0][1]; } else { det = 0; for (j1=0;j1<n;j1++) { m = new double*[n-1]; for (i=0;i<n-1;i++) { m[i] = new double[n-1]; } for (i=1;i<n;i++) { j2 = 0; for (j=0;j<n;j++) { if (j == j1) { continue; } m[i-1][j2] = a[i][j]; j2++; } } det += pow(-1.0,1.0+j1+1.0) * a[0][j1] * determinant(m,n-1); for (i=0;i<n-1;i++) { delete[] m[i]; } delete[] m; } } return(det); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/Segment.h
/** * Segment.h: a line segment * DG++ * * Created by Adrian Lew on 10/7/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SEGMENT #define SEGMENT #include "AuxDefs.h" #include "ElementGeometry.h" #include <cmath> #include <iostream> #include <cassert> /** \brief Segment: Geometry of straight segments A Segment is:\n 1) A set of indices that describe the connectivity of the segment, properly oriented. The coordinates are not stored in the element but wherever the application decides\n 2) An affine map from a one-dimensional segment (parametric configuration) with length 1 to the convex hull of the two vertices. Segments embedded in two- and three-dimensional space are hence easily handled. \n The parametric configuration is the segment (0,1).\n The parametric coordinate used is the distance to 0. \warning Neither map nor dMap check for bounds of their array arguments */ template<size_t SPD> class Segment:public AbstractGeom<SPD> { public: Segment (const std::vector<double> globalCoordVec, const std::vector<GlobalNodalIndex>& connectivity) :AbstractGeom<SPD> (globalCoordVec, connectivity) { assert (connectivity.size () == 2); } inline virtual ~Segment(){} Segment(const Segment<SPD> & that) : AbstractGeom<SPD> (that) { } virtual Segment<SPD>* clone() const { return new Segment<SPD>(*this); } inline size_t getNumVertices() const { return 2; } inline const std::string getPolytopeName() const { return "SEGMENT"; } inline size_t getParametricDimension() const { return 1; } inline size_t getEmbeddingDimension() const { return SPD; } //! @param X first parametric coordinate //! @param Y Output the result of the map void map(const double * X, double *Y) const; //! @param X first parametric coordinate //! @param DY Output the derivative of the map //! @param Jac Output the jacobian of the map void dMap(const double * X, double *DY, double &Jac) const; inline size_t getNumFaces() const { return 2; } //! \warning not implemented ElementGeometry * getFaceGeometry(size_t e) const { std::cerr << "Segment<SPD>::getFaceGeometry. " "Not implemented!\n\n"; return 0; } double getInRadius(void) const{ double l; l = 0.0; for(size_t i=0; i<SPD; i++) { l += (AbstractGeom<SPD>::getCoordinate(1,i) - AbstractGeom<SPD>::getCoordinate(0,i))* (AbstractGeom<SPD>::getCoordinate(1,i) - AbstractGeom<SPD>::getCoordinate(0,i)) ; } return(0.5*sqrt(l)); } double getOutRadius(void) const{ return(getInRadius()); } virtual void computeNormal (size_t e, std::vector<double>& vNormal) const { std::cerr << "Segment::computeNormal not implemented yet" << std::endl; abort (); } }; // Class implementation template<size_t SPD> void Segment<SPD>::map(const double * X, double *Y) const { for(size_t i=0; i<SPD; i++) Y[i] = X[0]*AbstractGeom<SPD>::getCoordinate(0,i) + (1-X[0])*AbstractGeom<SPD>::getCoordinate(1,i); return; } template<size_t SPD> void Segment<SPD>::dMap(const double * X, double *DY, double &Jac) const { for(size_t i=0; i<SPD; i++) DY[i] = AbstractGeom<SPD>::getCoordinate(0,i) - AbstractGeom<SPD>::getCoordinate(1,i); double g11=0; for(size_t i=0; i<SPD; i++) g11 += DY[i]*DY[i]; Jac=sqrt(g11); return; } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/Triangle.h
/** * Triangle.h * DG++ * * Created by Adrian Lew on 9/4/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef TRIANGLE #define TRIANGLE #include "AuxDefs.h" #include "ElementGeometry.h" #include "Segment.h" #include <algorithm> #include <cmath> #include <cassert> /** \brief Triangle: Geometry of planar triangles A Triangle is:\n 1) A set of indices that describe the connectivity of the triangle, properly oriented. The coordinates are not stored in the element but wherever the application decides\n 2) An affine map from a two-dimensional triangle (parametric configuration) with area 1/2 to the convex hull of the three vertices. Triangles embedded in three-dimensional space are hence easily handled. \n The parametric configuration is the triangle (0,0),(1,0),(0,1).\n The two parametric coordinates used are the ones aligned with the two axes in 2D. For a triangle with connectivity (1,2,3) the faces are ordered as (1,2),(2,3),(3,1). Rationale for a templated class: prevent having multiple copies of the dimension of SPD in each one of the multiple elements in a mesh. A static variable for it would have only allowed to use one type of triangles in a program. \warning Neither map nor dMap check for bounds of their array arguments */ template<size_t SPD> class Triangle: public AbstractGeom<SPD> { public: //! Connectivity in Triangle<SPD> GlobalCoordinatesArray Triangle (const std::vector<double>& globalCoordVec, const std::vector<GlobalNodalIndex>& connectivity) :AbstractGeom<SPD> (globalCoordVec, connectivity) { assert (connectivity.size () == 3); } inline virtual ~Triangle(){} Triangle(const Triangle<SPD> & that) : AbstractGeom<SPD>(that) { } virtual Triangle<SPD>* clone() const { return new Triangle<SPD>(*this); } inline size_t getNumVertices() const { return 3; } inline const std::string getPolytopeName() const { return "TRIANGLE"; } inline size_t getParametricDimension() const { return 2; } inline size_t getEmbeddingDimension() const { return SPD; } void map(const double * X, double *Y) const; void dMap(const double * X, double *DY, double &Jac) const; inline size_t getNumFaces() const { return 3; } virtual double getInRadius(void) const; virtual double getOutRadius(void) const; virtual Segment<SPD> * getFaceGeometry(size_t e) const; virtual void computeNormal (size_t e, std::vector<double>& vNormal) const; virtual void computeCenter (std::vector<double>& center) const; private: static size_t SegmentNodes[]; static double ParamCoord[]; static double midpoint (double x1, double x2) { return (x1 + x2) / 2; } }; // Class implementation template <size_t SPD> size_t Triangle<SPD>::SegmentNodes[] = {0,1,1,2,2,0}; template <size_t SPD> double Triangle<SPD>::ParamCoord[] = {1,0,0,1,0,0}; template<size_t SPD> void Triangle<SPD>::map(const double * X, double *Y) const { for(size_t i=0; i<SPD; i++) Y[i] = X[0]*AbstractGeom<SPD>::getCoordinate(0,i) + X[1]*AbstractGeom<SPD>::getCoordinate(1,i) + (1-X[0]-X[1])*AbstractGeom<SPD>::getCoordinate(2,i); return; } template<size_t SPD> void Triangle<SPD>::dMap(const double * X, double *DY, double &Jac) const { for(size_t i=0; i<SPD; i++) { DY[ i] = AbstractGeom<SPD>::getCoordinate(0,i) - AbstractGeom<SPD>::getCoordinate(2,i); DY[SPD+i] = AbstractGeom<SPD>::getCoordinate(1,i) - AbstractGeom<SPD>::getCoordinate(2,i); } double g11=0; double g22=0; double g12=0; for(size_t i=0; i<SPD; i++) { g11 += DY[i]*DY[i]; g22 += DY[SPD+i]*DY[SPD+i]; g12 += DY[SPD+i]*DY[i]; } Jac=sqrt(g11*g22-g12*g12); return; } template<size_t SPD> Segment<SPD> * Triangle<SPD>::getFaceGeometry(size_t e) const { std::vector<GlobalNodalIndex> conn(2); switch(e) { case 0: conn[0] = AbstractGeom<SPD>::getConnectivity ()[0]; conn[1] = AbstractGeom<SPD>::getConnectivity ()[1]; break; case 1: conn[0] = AbstractGeom<SPD>::getConnectivity ()[1]; conn[1] = AbstractGeom<SPD>::getConnectivity ()[2]; break; case 2: conn[0] = AbstractGeom<SPD>::getConnectivity ()[2]; conn[1] = AbstractGeom<SPD>::getConnectivity ()[0]; break; default: return 0; } return new Segment<SPD> (AbstractGeom<SPD>::getGlobalCoordVec (), conn); } template<size_t SPD> double Triangle<SPD>:: getInRadius(void) const { double a,b,c,s; a = b = c = s = 0.0; for(size_t i=0; i<SPD; i++) { a += (AbstractGeom<SPD>::getCoordinate(1,i) - AbstractGeom<SPD>::getCoordinate(0,i))* (AbstractGeom<SPD>::getCoordinate(1,i) - AbstractGeom<SPD>::getCoordinate(0,i)) ; b += (AbstractGeom<SPD>::getCoordinate(2,i) - AbstractGeom<SPD>::getCoordinate(1,i))* (AbstractGeom<SPD>::getCoordinate(2,i) - AbstractGeom<SPD>::getCoordinate(1,i)) ; c += (AbstractGeom<SPD>::getCoordinate(0,i) - AbstractGeom<SPD>::getCoordinate(2,i))* (AbstractGeom<SPD>::getCoordinate(0,i) - AbstractGeom<SPD>::getCoordinate(2,i)) ; } a = sqrt(a); b = sqrt(b); c = sqrt(c); s = (a + b + c)/2.0; return(2.0*sqrt(s*(s-a)*(s-b)*(s-c))/(a+b+c)); } template<size_t SPD> double Triangle<SPD>:: getOutRadius(void) const { double a,b,c; a = b = c = 0.0; for(size_t i=0; i<SPD; i++) { a += (AbstractGeom<SPD>::getCoordinate(1,i) - AbstractGeom<SPD>::getCoordinate(0,i))* (AbstractGeom<SPD>::getCoordinate(1,i) - AbstractGeom<SPD>::getCoordinate(0,i)) ; b += (AbstractGeom<SPD>::getCoordinate(2,i) - AbstractGeom<SPD>::getCoordinate(1,i))* (AbstractGeom<SPD>::getCoordinate(2,i) - AbstractGeom<SPD>::getCoordinate(1,i)) ; c += (AbstractGeom<SPD>::getCoordinate(0,i) - AbstractGeom<SPD>::getCoordinate(2,i))* (AbstractGeom<SPD>::getCoordinate(0,i) - AbstractGeom<SPD>::getCoordinate(2,i)) ; } a = sqrt(a); b = sqrt(b); c = sqrt(c); return(a*b*c/sqrt((a+b+c)*(b+c-a)*(c+a-b)*(a+b-c))); } template <size_t SPD> void Triangle<SPD>::computeNormal(size_t e, std::vector<double> &VNormal) const { double NodalCoord[4]; size_t n[2]; double v[2]; n[0] = SegmentNodes[e*2]; n[1] = SegmentNodes[e*2+1]; Triangle<SPD>::map(&Triangle<SPD>::ParamCoord[2*n[0]], NodalCoord ); Triangle<SPD>::map(&Triangle<SPD>::ParamCoord[2*n[1]], NodalCoord+2); v[0] = NodalCoord[2]-NodalCoord[0]; v[1] = NodalCoord[3]-NodalCoord[1]; double norm = sqrt(v[0]*v[0]+v[1]*v[1]); if(norm<=0) { std::cerr << "The normal cannot be computed. Two vertices of a polytope seem to coincide\n"; } VNormal.push_back( v[1]/norm); VNormal.push_back(-v[0]/norm); } /** * computes the center of the in-circle of a triangle * by computing the point of intersection of bisectors of the * sides, which are perpendicular to the sides */ template <size_t SPD> void Triangle<SPD>::computeCenter (std::vector<double>& center) const { double x1 = AbstractGeom<SPD>::getCoordinate (0, 0); // node 0, x coord double y1 = AbstractGeom<SPD>::getCoordinate (0, 1); // node 0, y coord double x2 = AbstractGeom<SPD>::getCoordinate (1, 0); // node 0, y coord double y2 = AbstractGeom<SPD>::getCoordinate (1, 1); // node 0, y coord double x3 = AbstractGeom<SPD>::getCoordinate (2, 0); // node 0, y coord double y3 = AbstractGeom<SPD>::getCoordinate (2, 1); // node 0, y coord // check if the slope of some side will come out to inf // and swap with third side if (fabs(x2 - x1) < TOLERANCE) { // almost zero std::swap (x2, x3); std::swap (y2, y3); } if (fabs(x3 - x2) < TOLERANCE) { std::swap (x1, x2); std::swap (y1, y2); } // mid points of the sides double xb1 = midpoint(x1, x2); double yb1 = midpoint(y1, y2); double xb2 = midpoint(x2, x3); double yb2 = midpoint(y2, y3); double xb3 = midpoint(x3, x1); double yb3 = midpoint(y3, y1); // slopes of all sides double m1 = (y2 - y1) / (x2 - x1); double m2 = (y3 - y2) / (x3 - x2); double m3 = (y3 - y1) / (x3 - x1); // solve simultaneous equations for first 2 bisectors double cy = (xb2 - xb1 + m2 * yb2 - m1 * yb1) / (m2 - m1); double cx = (m2 * xb1 - m1 * xb2 + m2 * m1 * yb1 - m2 * m1 * yb2) / (m2 - m1); // check against the third bisector if (fabs(x3-x1) > 0) { // checks if m3 == inf assert(fabs((cx + m3 * cy) - (xb3 + m3 * yb3)) < 1e-9); } // output the computed values center[0] = cx; center[1] = cy; } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/test/testTetrahedron.cpp
// Sriramajayam // Purpose : To check class Tetrahedron. #include <iostream> #include <cstdlib> #include "Tetrahedron.h" int main() { double coord[] = {2,0,0, 0,2,0, 0,0,0, 0,0,2}; std::vector<double> dummycoordinates(coord, coord+12); int c[] = {0, 1, 2, 3}; std::vector<GlobalNodalIndex> conn(c, c+4); Tetrahedron MyTet(dummycoordinates, conn); std::cout << "\nNumber of vertices: " << MyTet.getNumVertices(); std::cout << "\nParametricDimension: " << MyTet.getParametricDimension(); std::cout << "\nEmbeddingDimension: " << MyTet.getEmbeddingDimension(); std::cout<<"\n"; const double X[3] = {0.25, 0.25, 0.25}; // Barycentric coordinates. if(MyTet.consistencyTest(X,1.e-6)) std::cout << "Consistency test successful" << "\n"; else std::cout << "Consistency test failed" << "\n"; double DY[9], Jac; MyTet.dMap(X, DY, Jac); std::cout<<"\n Jacobian: "<<Jac; // Faces std::cout<<"\n Testing Face 1: \n"; ElementGeometry *face = MyTet.getFaceGeometry(1); std::cout << "\nNumber of vertices: " << face->getNumVertices(); std::cout << "\nParametricDimension: " << face->getParametricDimension(); std::cout << "\nEmbeddingDimension: " << face->getEmbeddingDimension(); std::cout << "\nConnectivity: " << face->getConnectivity()[0] << " " << face->getConnectivity()[1] << " "<<face->getConnectivity()[2] <<" should be 3 1 4\n"; std::cout << "\nIn Radius: " << MyTet.getInRadius() << "\nshould be 0.42264973\n"; std::cout << "\nOut Radius: " << MyTet.getOutRadius() << "\nshould be 1.7320508075688772\n"; std::cout << "\n"; delete face; // Test virtual mechanism and copy and clone constructors ElementGeometry *MyElmGeo = &MyTet; std::cout << "Testing virtual mechanism: "; std::cout << "\nPolytope name: " << MyElmGeo->getPolytopeName() << " should be Tetrahedron\n"; const std::vector<GlobalNodalIndex> &Conn = MyElmGeo->getConnectivity(); std::cout << "\nConnectivity: " << Conn[0] << " " << Conn[1] << " " << Conn[2] <<" "<<Conn[3]<< " should be 1 2 3 4\n"; ElementGeometry *MyElmGeoCloned = MyTet.clone(); std::cout << "Testing cloning mechanism: "; std::cout << "\nPolytope name: " << MyElmGeoCloned->getPolytopeName() << " should be Tetrahedron\n"; const std::vector<GlobalNodalIndex> &Conn2 = MyElmGeoCloned->getConnectivity(); std::cout << "\nConnectivity: " << Conn2[0] << " " << Conn2[1] << " " << Conn2[2] <<" "<<Conn2[3]<< " should be 1 2 3 4\n"; return 1; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/test/testTriangle.cpp
/* * testTriangle.cpp * DG++ * * Created by Adrian Lew on 9/7/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <cstdlib> #include <ctime> #include "Triangle.h" int main() { std::vector<double> dummycoordinates(6); // Fill-in the dummy global array dummycoordinates[0] = 0; dummycoordinates[1] = 0; dummycoordinates[2] = 0.5; dummycoordinates[3] = 0.3; dummycoordinates[4] = 0.2; dummycoordinates[5] = 1.5; GlobalNodalIndex c[] = {0, 1, 2}; std::vector<GlobalNodalIndex> conn(c, c+3); Triangle<2> MyTriangle(dummycoordinates, conn); std::cout << "Number of vertices: " << MyTriangle.getNumVertices() << " should be 3\n"; std::cout << "ParametricDimension: " << MyTriangle.getParametricDimension() << " should be 2\n"; std::cout << "EmbeddingDimension: " << MyTriangle.getEmbeddingDimension() << " should be 2\n"; srand(time(NULL)); double X[2]; X[0] = double(rand())/double(RAND_MAX); X[1] = double(rand())/double(RAND_MAX); //It may be outside the triangle if(MyTriangle.consistencyTest(X,1.e-6)) std::cout << "Consistency test successful" << "\n"; else std::cout << "Consistency test failed" << "\n"; std::cout << "\nIn Radius: " << MyTriangle.getInRadius() << "\nshould be 0.207002\n"; std::cout << "\nOut Radius: " << MyTriangle.getOutRadius() << "\nshould be 0.790904\n"; std::cout << "\n"; // Faces ElementGeometry *face = MyTriangle.getFaceGeometry(2); std::cout << "Number of vertices: " << face->getNumVertices() << " should be 2\n"; std::cout << "ParametricDimension: " << face->getParametricDimension() << " should be 1\n"; std::cout << "EmbeddingDimension: " << face->getEmbeddingDimension() << " should be 2\n"; std::cout << "Connectivity: " << face->getConnectivity()[0] << " " << face->getConnectivity()[1] << " should be 1 2\n"; delete face; // Test virtual mechanism and copy and clone constructors ElementGeometry *MyElmGeo = &MyTriangle; std::cout << "Testing virtual mechanism: "; std::cout << "Polytope name: " << MyElmGeo->getPolytopeName() << " should be TRIANGLE\n"; const std::vector<GlobalNodalIndex> &Conn = MyElmGeo->getConnectivity(); std::cout << "Connectivity: " << Conn[0] << " " << Conn[1] << " " << Conn[2] << " should be 1 2 3\n"; ElementGeometry *MyElmGeoCloned = MyTriangle.clone(); std::cout << "Testing cloning mechanism: "; std::cout << "Polytope name: " << MyElmGeoCloned->getPolytopeName() << " should be TRIANGLE\n"; const std::vector<GlobalNodalIndex> &Conn2 = MyElmGeoCloned->getConnectivity(); std::cout << "Connectivity: " << Conn2[0] << " " << Conn2[1] << " " << Conn2[2] << " should be 1 2 3\n"; std::cout << "Test triangle in 3D\n"; std::vector<double> dummycoordinates3(9); // Fill-in the dummy global array dummycoordinates3[0] = 0; dummycoordinates3[1] = 0; dummycoordinates3[2] = 0; dummycoordinates3[3] = 0.5; dummycoordinates3[4] = 0.3; dummycoordinates3[5] = 1; dummycoordinates3[6] = 0.2; dummycoordinates3[7] = 1.5; dummycoordinates3[8] = 2; Triangle<3> MyTriangle3(dummycoordinates3, conn); std::cout << "Number of vertices: " << MyTriangle3.getNumVertices() << " should be 3\n"; std::cout << "ParametricDimension: " << MyTriangle3.getParametricDimension() << " should be 2\n"; std::cout << "EmbeddingDimension: " << MyTriangle3.getEmbeddingDimension() << " should be 3\n"; srand(time(NULL)); X[0] = double(rand())/double(RAND_MAX); X[1] = double(rand())/double(RAND_MAX); //It may be outside the triangle if(MyTriangle3.consistencyTest(X,1.e-6)) std::cout << "Consistency test successful" << "\n"; else std::cout << "Consistency test failed" << "\n"; std::cout << "\nIn Radius: " << MyTriangle3.getInRadius() << "\nshould be 0.26404\n"; std::cout << "\nOut Radius: " << MyTriangle3.getOutRadius() << "\nshould be 1.66368\n"; std::cout << "\n"; return 1; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libGeom/test/testSegment.cpp
/* * testSegment.cpp * DG++ * * Created by Adrian Lew on 10/8/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <cstdlib> #include <ctime> #include "Segment.h" int main() { std::vector<double> dummycoordinates(4); // Fill-in the dummy global array dummycoordinates[0] = 0; dummycoordinates[1] = 0; dummycoordinates[2] = 0.5; dummycoordinates[3] = 0.3; std::vector<GlobalNodalIndex> conn(2); conn[0] = 0; conn[1] = 1; Segment<2> MySegment(dummycoordinates, conn); std::cout << "Number of vertices: " << MySegment.getNumVertices() << " should be 2\n"; std::cout << "ParametricDimension: " << MySegment.getParametricDimension() << " should be 1\n"; std::cout << "EmbeddingDimension: " << MySegment.getEmbeddingDimension() << " should be 2\n"; srand(time(NULL)); double X[2]; X[0] = double(rand())/double(RAND_MAX); //It may be outside the segment if(MySegment.consistencyTest(X,1.e-6)) std::cout << "Consistency test successful" << "\n"; else std::cout << "Consistency test failed" << "\n"; // Test virtual mechanism and copy and clone constructors ElementGeometry *MyElmGeo = &MySegment; std::cout << "Testing virtual mechanism: "; std::cout << "Polytope name: " << MyElmGeo->getPolytopeName() << " should be SEGMENT\n"; const std::vector<GlobalNodalIndex> &Conn = MyElmGeo->getConnectivity(); std::cout << "Connectivity: " << Conn[0] << " " << Conn[1] << " should be 1 2\n"; ElementGeometry *MyElmGeoCloned = MySegment.clone(); std::cout << "Testing cloning mechanism: "; std::cout << "Polytope name: " << MyElmGeoCloned->getPolytopeName() << " should be SEGMENT\n"; const std::vector<GlobalNodalIndex> &Conn2 = MyElmGeoCloned->getConnectivity(); std::cout << "Connectivity: " << Conn2[0] << " " << Conn2[1] << " should be 1 2\n"; std::cout << "Test Segment in 3D\n"; std::vector<double> dummycoordinates3(6); // Fill-in the dummy global array dummycoordinates3[0] = 0; dummycoordinates3[1] = 0; dummycoordinates3[2] = 0; dummycoordinates3[3] = 0.5; dummycoordinates3[4] = 0.3; dummycoordinates3[5] = 1; Segment<3> MySegment3(dummycoordinates3, conn); std::cout << "Number of vertices: " << MySegment3.getNumVertices() << " should be 2\n"; std::cout << "ParametricDimension: " << MySegment3.getParametricDimension() << " should be 1\n"; std::cout << "EmbeddingDimension: " << MySegment3.getEmbeddingDimension() << " should be 3\n"; srand(time(NULL)); X[0] = double(rand())/double(RAND_MAX); // It may be outside the segment if(MySegment3.consistencyTest(X,1.e-6)) std::cout << "Consistency test successful" << "\n"; else std::cout << "Consistency test failed" << "\n"; return 1; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/Element.h
/** * Element.h: Basic Element over which fields are defined. * It contains an element geometry, shape functions etc. * * DG++ * * Created by Adrian Lew on 9/2/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ELEMENT #define ELEMENT #include <vector> #include "AuxDefs.h" #include "ElementGeometry.h" #include "BasisFunctions.h" // TODO: add P1nDBoundaryTrace and P1nDMap /** \brief Element: abstract base class for any element An Element is a convex polytope with possibly-multiple discrete functional spaces, one for each field, with support on it. An element has:\n 1) A geometry. The connectivity of vertices that define the convex hull.\n 2) A group of scalar functional spaces. Each functional space is defined by a set of basis functions with support on the element. Each functional space has an associated number of degrees of freedom to it: the components of any function in the space in the chosen basis.\n A field is a scalar-valued function defined over the element.\n Each field may have a different underlying functional space.\n Each field may have a different quadrature rule. Different quadrature rules will also be handled with different elements, or through inheritance. The consistency of the quadrature rule when different fields are integrated together is in principle not checked by the element hierarchy. \n Clearly, isoparametric elements will not necessarily be convex, but Element class can still be used. As a convention, fields are numbered starting from 0. \todo It would be nice to have vectors and tensors as fields, where for each component one assigns a single set of shape functions and quadrature points. The current abstraction is flexible in the sense that it does not enforce vector or tensor fields to have the same quadrature and shapes. \todo Need to explain what the expected order of the vectors getShapes() and getDShapes() is. \todo Need to explain that either getShapes or getDShapes may return an empty vector, signaling that those values are not available. */ class Element { public: inline Element(){} inline virtual ~Element(){} inline Element(const Element &){} virtual Element * clone() const = 0; // Accessors/Mutators: //! Number of different fields virtual size_t getNumFields() const = 0; //! Number of degrees of freedom of one of the fields. virtual size_t getDof(size_t field) const = 0; //! Number of derivatives per shape function for one of the fields virtual size_t getNumDerivatives(size_t field) const = 0; //! Shape functions at quadrature points of one of the fields virtual const std::vector <double> &getShapes(size_t field) const = 0; //! Shape function derivatives at quadrature points of one of the fields virtual const std::vector <double> &getDShapes(size_t field) const = 0; //! Integration weights of a given field virtual const std::vector <double> &getIntegrationWeights(size_t field) const = 0; //! Integration point coordinates of a given field virtual const std::vector <double> &getIntegrationPtCoords(size_t field) const = 0; //! Value of shape function "shapenumber" of field "field" //! at quadrature point "quad" virtual double getShape(size_t field, size_t quad, size_t shapenumber) const = 0; //! Value of derivative of shape function "shapenumber" of field "field" //! at quadrature point "quad" in direction "dir" virtual double getDShape(size_t field, size_t quad, size_t shapenumber, size_t dir) const = 0; //! Access to Element Geometry virtual const ElementGeometry & getGeometry() const = 0; }; /** \brief Element_: Abstract implementation of an Element class Element_ constructs a finite element type. The ElementGeometry is specified in derived classes. The idea is to use this class to derive different finite element types. Element_ is defined by:\n 1) Access to a (ElementGeometry &)EG that defines the geometry of the element through a map a reference domain \f$\hat{\Omega}\f$ to the real element shape (or an approximation, such as in isoparametric elements)\n 2) An array (BasisFunctions *) LocalShapes all constructed over EG. 3) A virtual function to be defined by derived classses getFieldShapes. The value of LocalShapes[getFieldShapes(FieldNumber)] returns the shape functions of field FieldNumber. This map is needed since the same BasisFunctions object can be used for several fields. */ class Element_: public Element { private: void copy (const Element_& that) { for (size_t i = 0; i < that.LocalShapes.size (); i++) { LocalShapes.push_back ((that.LocalShapes[i])->clone ()); } } void destroy () { for (size_t i = 0; i < LocalShapes.size (); i++) { delete LocalShapes[i]; LocalShapes[i] = NULL; } } public: inline Element_ () : Element() { } inline virtual ~Element_ () { destroy (); } Element_ (const Element_ &OldElement_) : Element (OldElement_) { copy (OldElement_); } Element_& operator = (const Element_& that) { if (this != &that) { destroy (); copy (that); } return (*this); } virtual Element_ * clone () const = 0; inline size_t getDof (size_t field) const { return LocalShapes[getFieldShapes (field)]->getBasisDimension (); } inline size_t getNumDerivatives (size_t field) const { return LocalShapes[getFieldShapes (field)]-> getNumberOfDerivativesPerFunction (); } inline const std::vector<double> &getShapes (size_t field) const { return LocalShapes[getFieldShapes (field)]->getShapes (); } inline const std::vector<double> &getDShapes (size_t field) const { return LocalShapes[getFieldShapes (field)]->getDShapes (); } inline const std::vector<double> &getIntegrationWeights (size_t field) const { return LocalShapes[getFieldShapes (field)]->getIntegrationWeights (); } inline const std::vector<double> &getIntegrationPtCoords (size_t field) const { return LocalShapes[getFieldShapes (field)]->getQuadraturePointCoordinates (); } inline double getShape (size_t field, size_t quad, size_t shapenumber) const { return getShapes (field)[quad * getDof (field) + shapenumber]; } inline double getDShape (size_t field, size_t quad, size_t shapenumber, size_t dir) const { return getDShapes (field)[quad * getDof (field) * getNumDerivatives (field) + shapenumber * getNumDerivatives (field) + dir]; } protected: //! addBasisFunctions adds a BasisFunctions pointer at the end of LocalShapes //! The i-th added BasisFunctions pointer is referenced when getFieldShapes //! returns the integer i-1 inline void addBasisFunctions (const BasisFunctions &BasisFunctionsPointer) { LocalShapes.push_back (BasisFunctionsPointer.clone ()); // XXX: amber: clone has no effect (see ShapesEvaluated__ copy constructor) and it seems // that clone is not needed // LocalShapes.push_back( (const_cast<BasisFunctions*> (&BasisFunctionsPointer)) ); } //! getFieldShapes returns the position in LocalShapes in which //! the shape functions for field Field are. virtual size_t getFieldShapes (size_t Field) const = 0; //! returns the length of LocalShapes inline size_t getNumShapes () const { return LocalShapes.size (); } private: std::vector<BasisFunctions *> LocalShapes; }; /** \brief SpecificElementFamily: classes that contain all Element types that form a family. For example, bulk and boundary interpolation. */ class SpecificElementFamily { }; /** \brief LocalToGlobalMap class: map the local degrees of freedom of each Element to the global ones. The Local to Global map is strongly dependent on how the program that utilizes the Element objects is organized. The objective of this class is then to define the interface that the derived objects should have. There will generally not be a single LocalToGlobalMap object per Element, but rather only one LocalToGlobalMap for all of them. Hence, the interface requires a way to specify which element is being mapped. Convention:\n Fields and Dofs start to be numbered at 0 */ class LocalToGlobalMap { public: inline LocalToGlobalMap () { } inline virtual ~LocalToGlobalMap () { } inline LocalToGlobalMap (const LocalToGlobalMap &) { } virtual LocalToGlobalMap * clone () const = 0; // //! @param ElementMapped: GlobalElementIndex of the Element to be mapped. // //! This sets // //! the default Element object whose field degrees of freedom are // //! mapped. // // XXX: commented out (amber) // // virtual void set (const GlobalElementIndex &ElementMapped) = 0; // //! @param field field number in the element, 0\f$ \le \f$ field \f$\le\f$ Nfields-1\n // //! @param dof number of degree of freedom in that field, // //! \f$ 0 \le \f$ dof \f$\le\f$ Ndofs-1 \n // //! map returns the GlobalDofIndex associated to degree of freedom "dof" of field "field" // //! in the default Element object. The latter is // //! set with the function set(const Element &). // // XXX: commented out (amber) // // virtual const GlobalDofIndex map (size_t field, size_t dof) const = 0; //! @param field field number in the element, 0\f$ \le \f$ field \f$\le\f$ Nfields-1\n //! @param dof number of degree of freedom in that field, \f$ 0 \le \f$ dof \f$\le\f$ Ndofs-1 \n //! @param ElementMapped: GlobalElementIndex of the Element whose degrees //! of freedom are being mapped\n //! map returns the GlobalDofIndex associated to degree of freedom "dof" //! of field "field" //! in element MappedElement. virtual GlobalDofIndex map (size_t field, size_t dof, const GlobalElementIndex & ElementMapped) const = 0; //! Total number of elements that can be mapped. Usually, total number of //! elements in the mesh. virtual size_t getNumElements () const = 0; //! Number of fields in an element mapped virtual size_t getNumFields (const GlobalElementIndex & ElementMapped) const = 0; //! Number of dofs in an element mapped in a given field virtual size_t getNumDof (const GlobalElementIndex & ElementMapped, size_t field) const = 0; //! Total number of dof in the entire map virtual size_t getTotalNumDof () const = 0; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/P13DElement.h
/** * P13DElement.h: A 3D element with linear shape functions * * DG++ * * Created by Ramsharan Rangarajan * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef P13DELEMENT #define P13DELEMENT #include "P1nDElement.h" #include "P12DElement.h" #include "ShapesEvaluatedP13D.h" #include "Tetrahedron.h" #include "ElementGeometry.h" #include <iostream> #include <vector> #include <cassert> //! \brief three-dimensional linear tetrahedra with NF different fields. template<size_t NF> class P13DElement: public P1nDElement<NF> { public: //! \param _elemGeom A reference to element geometry P13DElement (const Tetrahedron& _elemGeom): P1nDElement<NF> (_elemGeom) { ShapesP13D::Bulk modelShape (_elemGeom); Element_::addBasisFunctions (modelShape); } //! Copy constructor P13DElement (const P13DElement<NF>& that): P1nDElement<NF> (that) { } //! Cloning mechanism virtual P13DElement<NF>* clone () const { return new P13DElement<NF> (*this); } }; // Class P13DTrace: /** \brief Traces of P13DElement. These trace elements are templated according to the number of linear fields and the Tetrahedron face P13DTrace<NF>::FaceLabel on which the trace is computed. Traces of P13DElements are somewhat special, since for each side one of the bulk basis functions is identically zero, effectively leaving three dofs per face. To reduce the amount of memory allocated per element is then convenient to consider trace elements with only 3 dofs per field per face, i.e., use the ShapesP13D::Faces ShapesEvaluated objects. However, ocassionally, it may be necessary to have the boundary elements have the same nummber of dofs as the bulk elements, as it is generally the case for arbitrary bases. Hence during their construction, it is possible to specify what type of shape functions to use. This is accomplished by specifying the type ShapeType. \warning As opposed to P13DElement(s), there is no local copy of the geometry of the element here, but only a reference to it. Hence, the destruction of the base geometry before the destruction of the element will render the implementation inconsistent. \todo As was commented in P12DTrace, TetGeom may have to be a pointer and not a reference, since this is a reference to a copy of the original geometry. */ template<size_t NF> class P13DTrace: public P1nDTrace<NF> { public: //! \param BaseElement Element whose trace is desired. //! \param FaceName Face on which to take the trace. //! \param Type ShapeType of the face, i.e., with three or four dofs. P13DTrace (const P13DElement<NF> &BaseElement, const typename P1nDTrace<NF>::FaceLabel& FaceName, const typename P1nDTrace<NF>::ShapeType& Type); virtual ~P13DTrace () { } //! Copy constructor P13DTrace (const P13DTrace<NF> &OldElement_) : P1nDTrace<NF> (OldElement_) { } //! Cloning mechanism virtual P13DTrace<NF>* clone () const { return new P13DTrace<NF> (*this); } private: //! checks if arguments are consistend with 3D element //! @param flabel //! @param shType void checkArgs (const typename P1nDTrace<NF>::FaceLabel& flabel, const typename P1nDTrace<NF>::ShapeType& shType) { assert (shType != P1nDTrace<NF>::TwoDofs); } }; // Implementation of class P13DTrace: template<size_t NF> P13DTrace<NF>::P13DTrace (const P13DElement<NF> &BaseElement, const typename P1nDTrace<NF>::FaceLabel& FaceName, const typename P1nDTrace<NF>::ShapeType& Type) : P1nDTrace<NF> (BaseElement) { checkArgs (FaceName, Type); const ElementGeometry& tetGeom = Element::getGeometry (); assert (dynamic_cast<const Tetrahedron*> (&tetGeom) != NULL); ElementGeometry* faceGeom = tetGeom.getFaceGeometry(FaceName); assert (dynamic_cast<Triangle<3>* > (faceGeom) != NULL); if (Type == P1nDTrace<NF>::ThreeDofs) { ShapesP13D::Faces ModelShape (*faceGeom); Element_::addBasisFunctions (ModelShape); } else { //Type == FourDofs switch (FaceName) { case P1nDTrace<NF>::FaceOne: { ShapesP13D::FaceOne ModelShape(*faceGeom); Element_::addBasisFunctions(ModelShape); break; } case P1nDTrace<NF>::FaceTwo: { ShapesP13D::FaceTwo ModelShape(*faceGeom); Element_::addBasisFunctions(ModelShape); break; } case P1nDTrace<NF>::FaceThree: { ShapesP13D::FaceThree ModelShape(*faceGeom); Element_::addBasisFunctions(ModelShape); break; } case P1nDTrace<NF>::FaceFour: { ShapesP13D::FaceFour ModelShape(*faceGeom); Element_::addBasisFunctions(ModelShape); break; } } } delete faceGeom; faceGeom = NULL; } // Class for ElementBoundaryTraces: /** \brief Group of traces for P13DElement. It contains P13DTrace elements. It is possible to specify which faces to build traces for. getTrace(i) returns the i-th face for which traces are built. The order of these faces is always increasing in number. It does not make a copy o keep reference of the BaseElement. */ template<size_t NF> class P13DElementBoundaryTraces: public P1nDBoundaryTraces<NF> { public: //! \param BaseElement Element for which to build traces. //! \param faceLabels is a vector telling which faces to build //! \param Type type of trace element to use. P13DElementBoundaryTraces (const P13DElement<NF> &BaseElement, const std::vector<typename P1nDTrace<NF>::FaceLabel>& faceLabels, typename P13DTrace<NF>::ShapeType Type): P1nDBoundaryTraces<NF> (BaseElement, faceLabels, Type) { } virtual ~P13DElementBoundaryTraces () { } //! Copy constructor P13DElementBoundaryTraces (const P13DElementBoundaryTraces<NF> &OldElem) : P1nDBoundaryTraces<NF> (OldElem) { } //! Cloning mechanism P13DElementBoundaryTraces<NF> * clone () const { return new P13DElementBoundaryTraces<NF> (*this); } //! map dofs between dofs of field in a trace and those in the original element. //! \param FaceIndex starting from 0. //! \param field field number to map, starting from 0. //! \param dof degree of freedom number on the trace of field "field" //! The function returns the degree of freedom number in the original element. size_t dofMap (size_t FaceIndex, size_t field, size_t dof) const; }; // Implementation of class P13DElementBoundaryTraces template<size_t NF> size_t P13DElementBoundaryTraces<NF>::dofMap (size_t FaceIndex, size_t field, size_t dof) const { size_t val; if (ElementBoundaryTraces::getTrace (FaceIndex).getDof (field) == 4) { val = dof; } else { // Three dofs per face. const size_t* FaceNodes = Tetrahedron::FaceNodes; size_t facenum = ElementBoundaryTraces::getTraceFaceIds ()[FaceIndex]; val = FaceNodes[3 * facenum + dof]; } return val; } //! \brief Family of elements over tetrahedra with NF linearly interpolated fields. template<size_t NF> class P13D: public SpecificElementFamily { public: //! Linear over the element. typedef P13DElement<NF> Bulk; //! Linear over triangles. typedef P13DTrace<NF> Face; //! Traces on the boundary of P13DElement<NF> typedef P13DElementBoundaryTraces<NF> Traces; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/P1nDElement.h
/** * P1nDElement.h: Common base class for 2D/3D elements with linear shape functions * * DG++ * * Created by Adrian Lew on 9/2/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef P1NDELEMENT_H_ #define P1NDELEMENT_H_ #include <vector> #include <cassert> #include "AuxDefs.h" #include "Element.h" #include "ElementBoundaryTrace.h" #include "ElementGeometry.h" template <size_t NF> class P1nDElement: public Element_ { private: const ElementGeometry& elemGeom; public: //! constructor //! @param _elemGeom element geometry P1nDElement (const ElementGeometry& _elemGeom) : Element_(), elemGeom(_elemGeom) { } //! copy constructor //! @param that P1nDElement (const P1nDElement& that) : Element_(that), elemGeom (that.elemGeom) { } //! @see Element::getNumFields virtual size_t getNumFields () const { return NF; } //! @see Element::getGeometry virtual const ElementGeometry& getGeometry () const { return elemGeom; } protected: //! @see Element_::getFieldShapes size_t getFieldShapes (size_t field) const { return 0; } }; /** * Common base class for 2D/3D linear traces */ template <size_t NF> class P1nDTrace: public P1nDElement<NF> { public: //! Range of FaceIndices available to enumerate faces\n //! When providing a FaceLabel as an argument there is automatic //! control of its range enum FaceLabel { FaceOne=0, FaceTwo=1, FaceThree=2, FaceFour=3 }; //! TwoDofs indicates Segment<2> boundary elements, with two dofs per field \n //! ThreeDofs indicates Triangle<2> boundary elements, with three dofs per field. The //! shape functions in P12DElement are just evaluated at quadrature points on each face\n //! FourDofs is a Tetrahedron enum ShapeType { TwoDofs, ThreeDofs, FourDofs }; P1nDTrace (const P1nDElement<NF>& baseElem): P1nDElement<NF>(baseElem) { } P1nDTrace (const P1nDTrace<NF>& that): P1nDElement<NF> (that) { } }; /** * Common base class for boundary traces * @see ElementBoundaryTraces */ template <size_t NF> class P1nDBoundaryTraces: public ElementBoundaryTraces_ { private: MatDouble normals; public: typedef typename P1nDTrace<NF>::FaceLabel FaceLabel; typedef typename P1nDTrace<NF>::ShapeType ShapeType; P1nDBoundaryTraces (const P1nDElement<NF>& baseElem, const std::vector<FaceLabel>& faceLabels, const ShapeType& shapeType) : ElementBoundaryTraces_ () { assert (faceLabels.size() == baseElem.getGeometry().getNumFaces ()); for (size_t i = 0; i < faceLabels.size (); ++i) { const P1nDTrace<NF>* fTrace = makeTrace (baseElem, faceLabels[i], shapeType); addFace (fTrace, i); } normals.resize (getNumTraceFaces ()); for (size_t i = 0; i < getNumTraceFaces (); ++i) { baseElem.getGeometry ().computeNormal (getTraceFaceIds ()[i], normals[i]); } } P1nDBoundaryTraces (const P1nDBoundaryTraces<NF>& that) : ElementBoundaryTraces_ (that), normals (that.normals) { } const std::vector<double> & getNormal (size_t FaceIndex) const { return normals[FaceIndex]; } protected: virtual const P1nDTrace<NF>* makeTrace (const P1nDElement<NF>& baseElem, const FaceLabel& flabel, const ShapeType& shType) const = 0; }; /** \brief StandardP1nDMap class: standard local to global map for 2D/3D elements with linear shape functions StandardP1nDMap assumes that\n 1) The GlobalNodalIndex of a node is an size_t\n 2) All degrees of freedom are associated with nodes, and their values for each node ordered consecutively according to the field number. Consequently, the GlobalDofIndex of the degrees of freedom of node N with NField fields are given by (N-1)*NF + field-1, where \f$ 1 \le \f$ fields \f$ \le \f$ NF */ class StandardP1nDMap: public LocalToGlobalMap { private: const std::vector<Element*>& elementArray; public: StandardP1nDMap (const std::vector<Element*>& _elementArray) : LocalToGlobalMap (), elementArray (_elementArray) { } StandardP1nDMap (const StandardP1nDMap& that) : LocalToGlobalMap (that), elementArray (that.elementArray) { } virtual StandardP1nDMap* clone () const { return new StandardP1nDMap (*this); } inline GlobalDofIndex map (size_t field, size_t dof, const GlobalElementIndex& ElementMapped) const { const Element* elem = elementArray[ElementMapped]; // we subtract 1 from node ids in 1-based node numbering // return elem->getNumFields () * (elem-> getGeometry ().getConnectivity ()[dof] - 1) + field; // no need to subtract 1 with 0-based node numbering return elem->getNumFields () * (elem-> getGeometry ().getConnectivity ()[dof]) + field; } inline size_t getNumElements () const { return elementArray.size (); } inline size_t getNumFields (const GlobalElementIndex & ElementMapped) const { return elementArray[ElementMapped]->getNumFields (); } inline size_t getNumDof (const GlobalElementIndex & ElementMapped, size_t field) const { return elementArray[ElementMapped]->getDof (field); } size_t getTotalNumDof () const { GlobalNodalIndex MaxNodeNumber = 0; for (size_t e = 0; e < elementArray.size (); e++) { const std::vector<GlobalNodalIndex>& conn = elementArray[e]->getGeometry ().getConnectivity (); for (size_t a = 0; a < conn.size (); ++a) { if (conn[a] > MaxNodeNumber) { MaxNodeNumber = conn[a]; } } } // return maxNode * elementArray.get (0).numFields (); // add 1 here since nodes are number 0 .. numNodes-1 in 0-based node numbering return static_cast<size_t> (MaxNodeNumber + 1) * elementArray[0]->getNumFields (); } protected: //! Access to ElementArray for derived classes const std::vector<Element *> & getElementArray () const { return elementArray; } }; #endif /* P1NDELEMENT_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/P12DElement.h
/** * P12DElement.h: 2D Element with linear shape functions * * DG++ * * Created by Adrian Lew on 9/22/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef P12DELEMENT #define P12DELEMENT #include "Element.h" #include "P1nDElement.h" #include "ElementGeometry.h" #include "Triangle.h" #include "ElementBoundaryTrace.h" #include "ShapesEvaluated.h" #include <iostream> #include <vector> #include <cassert> /** \brief Two-dimensional linear triangles with NF different fields */ template<size_t NF> class P12DElement: public P1nDElement<NF> { public: P12DElement (const Triangle<2>& _elemGeom) : P1nDElement<NF> (_elemGeom) { ShapesP12D::Bulk modelShape (_elemGeom); Element_::addBasisFunctions (modelShape); } P12DElement (const P12DElement<NF> &that) : P1nDElement<NF> (that) { } virtual P12DElement<NF>* clone () const { return new P12DElement<NF> (*this); } }; /** \brief P12DTrace: traces of P12DElements These trace elements are templated according to the number of Linear fields and the Triangle face P12DTrace<NF>::FaceLabel on which the trace is computed. Traces of P12D elements are somewhat special, since for each side one of the bulk basis functions is identically zero, effectively leaving only two degrees of freedom per face. To reduce the amount of memory allocated per element is then convenient to consider Trace elements with only two degrees of freedom per field per face, i.e., use the ShapesP12D::Faces ShapesEvaluated objects. However, ocassionally it may be necessary to have the boundary elements have the same number of degrees of freedom as the bulk elements, as it is generally the case for arbitrary bases. Hence, during the construction of these elements it is possible to decide which type of shape functions to use. This is accomplished by specifying the type ShapeType. */ template<size_t NF> class P12DTrace: public P1nDTrace<NF> { public: //! @param BaseElement Element whose trace is desired //! @param FaceName Face on which to take the trace //! @param Type ShapeType of face, i.e., with two or three dof P12DTrace (const P12DElement<NF> & BaseElement, const typename P1nDTrace<NF>::FaceLabel& FaceName, const typename P1nDTrace<NF>::ShapeType& Type); virtual ~P12DTrace () { } P12DTrace (const P12DTrace<NF> &that) : P1nDTrace<NF> (that) { } virtual P12DTrace<NF> * clone () const { return new P12DTrace<NF> (*this); } private: //! check if the faceLabel and shapeType are consistent with //! 2D element trace //! @param faceLabel //! @param shapeType void checkArgs (const typename P1nDTrace<NF>::FaceLabel& faceLabel, const typename P1nDTrace<NF>::ShapeType& shapeType) { // Triangle has only 3 faces assert (faceLabel != P1nDTrace<NF>::FaceFour); // valid ShapeTypes are TwoDofs and ThreeDofs assert (shapeType == P1nDTrace<NF>::TwoDofs || shapeType == P1nDTrace<NF>::ThreeDofs); } }; template<size_t NF> P12DTrace<NF>::P12DTrace (const P12DElement<NF> & BaseElement, const typename P1nDTrace<NF>::FaceLabel& FaceName, const typename P1nDTrace<NF>::ShapeType& Type) : P1nDTrace<NF> (BaseElement) { checkArgs (FaceName, Type); const ElementGeometry& TriGeom = Element::getGeometry (); assert (dynamic_cast<const Triangle<2>* > (&TriGeom) != NULL); ElementGeometry* faceGeom = TriGeom.getFaceGeometry(FaceName); assert (dynamic_cast<Segment<2>* > (faceGeom) != NULL); if (Type == P1nDTrace<NF>::TwoDofs) { ShapesP12D::Faces modelShape (*faceGeom); Element_::addBasisFunctions (modelShape); } else { // Type==ThreeDofs switch (FaceName) { case P1nDTrace<NF>::FaceOne: { ShapesP12D::FaceOne ModelShape (*faceGeom); Element_::addBasisFunctions (ModelShape); break; } case P1nDTrace<NF>::FaceTwo: { ShapesP12D::FaceTwo ModelShape (*faceGeom); Element_::addBasisFunctions (ModelShape); break; } case P1nDTrace<NF>::FaceThree: { ShapesP12D::FaceThree ModelShape (*faceGeom); Element_::addBasisFunctions (ModelShape); break; } } } delete faceGeom; faceGeom = NULL; } /** \brief P12DElementBoundaryTraces: group of traces of P12DElements. It contains P12DTrace Elements. It is possible to specify which faces to build traces for. getTrace(i) returns the i-th face for which traces were built. The order of these faces is always increasing in face number. Example: if only faces one and three have traces, then getTrace(0) returns face one's trace, and getTrace(1) face three's trace. It does not make a copy or keep a reference of the BaseElement. */ template<size_t NF> class P12DElementBoundaryTraces: public P1nDBoundaryTraces<NF> { public: //! @param BaseElement Element for which traces are to be build //! @param flabels a vector of face labels (size is 3 for triangles) //! @param shType type of trace element to use. See P12DTrace<NF> P12DElementBoundaryTraces (const P12DElement<NF> &BaseElement, const std::vector<typename P1nDTrace<NF>::FaceLabel>& flabels, const typename P1nDTrace<NF>::ShapeType& shType): P1nDBoundaryTraces<NF> (BaseElement, flabels, shType) { } virtual ~P12DElementBoundaryTraces () { } P12DElementBoundaryTraces (const P12DElementBoundaryTraces<NF> & OldElem) : P1nDBoundaryTraces<NF> (OldElem) { } P12DElementBoundaryTraces<NF> * clone () const { return new P12DElementBoundaryTraces<NF> (*this); } size_t dofMap (size_t FaceIndex, size_t field, size_t dof) const; }; // Class Implementation template<size_t NF> size_t P12DElementBoundaryTraces<NF>::dofMap ( size_t FaceIndex, size_t field, size_t dof) const { size_t val; if (ElementBoundaryTraces::getTrace (FaceIndex).getDof (field) == 3) { val = dof; } else { // getTrace(FaceIndex).getDof(field)=2 switch (ElementBoundaryTraces::getTraceFaceIds ()[FaceIndex]) { case 0: val = dof; break; case 1: val = dof + 1; break; case 2: val = (dof == 0 ? 2 : 0); break; default: std::cerr << "P12DElementBoundaryTraces.DofMap Error\n"; exit (1); } } return val; } /** \brief P12D<NF> family of elements over triangles with NF linearly interpolated fields. */ template<size_t NF> class P12D: public SpecificElementFamily { public: //! Linear element over a triangle typedef P12DElement<NF> Bulk; //! Linear elements over segments typedef P12DTrace<NF> Face; //! Traces on the boundary for P12DElement<NF> typedef P12DElementBoundaryTraces<NF> Traces; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/ElementBoundaryTrace.h
/** * ElementBoundaryTraces.h * DG++ * * Created by Adrian Lew on 10/12/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ELEMENTBOUNDARYTRACES #define ELEMENTBOUNDARYTRACES #include <vector> #include "AuxDefs.h" #include "Element.h" /** \brief ElementBoundaryTraces: values of the trace of some or all the fields in an Element over some or all faces of the polytope. An ElementBoundaryTraces object contains\n 1) The outward normal to the faces for which values are desired.\n 2) The trace at these faces of some or all of the fields in the element. These traces are provided as Element objects, one for each face. The number of faces or fields in each face depends on the particular ElementBoundaryTraces object build. The exact number of fields whose trace is computed for each face will be determined by the Element object in each face. ElementBoundaryTraces objects are designed to work jointly with Element objects, so for example, it has no access to the ElementGeometry. The outward normal to the faces are included here because these are often used in integrands over faces. Each polytope has a convention to label ALL of its faces. By convention, these labels are consecutive integers starting at 0 to the total number of faces in the polytope minus one. */ class ElementBoundaryTraces { public: ElementBoundaryTraces() {} virtual ~ElementBoundaryTraces() {} ElementBoundaryTraces(const ElementBoundaryTraces &) {} virtual ElementBoundaryTraces * clone() const = 0; //! Number of faces for which traces are provided virtual size_t getNumTraceFaces() const = 0; //! Returns the face number in the polytope whose traces are provided. //! Each polytope has a convention to label ALL of its faces. Traces are //! provided for a subset of these faces. A total number of getNumTraceFaces() //! faces have their traces in this object. getTraceFaceIds()[FaceIndex], //! with FaceIndex between //! 0 and getNumTraceFaces()-1, provides the face number in the polytope //! face element accesses with getTrace(FaceIndex). //! //! The value returned starts at 0 for the first face and so on. virtual const std::vector<size_t> & getTraceFaceIds() const = 0; //! Returns the Trace number where the trace for face FaceIndex is stored. //! If no trace is provided for that face returns a -1. //! //! It is always true that FaceNumberToTrace[ getTraceFaceIds()[i] ] = i; //! for 0<= i <= getNumTraceFaces()-1 virtual size_t getTraceNumberOfFace(size_t FaceIndex) const = 0; //! Returns a constant reference to the Element that contains //! the traces of the face getTraceFacesNumbers()[FaceIndex]. \n //! FaceIndex ranges from 0 //! to the getNumTraceFaces()-1. virtual const Element & getTrace(size_t FaceIndex) const = 0; //! Returns getTrace(FaceIndex). Done for simplicity of the interface. //! FaceIndex ranges from 0 //! to the getNumTraceFaces()-1. inline const Element & operator[](size_t FaceIndex) { return getTrace(FaceIndex); } //! Returns the outward normal to face getTraceFaceIds(FaceIndex) //! FaceIndex ranges from 0 //! to the getNumTraceFaces()-1. virtual const std::vector<double> & getNormal(size_t FaceIndex) const = 0; //! map between the degrees of freedom of field in a trace //! and those in the original element //! //! @param FaceIndex starting from 0 //! @param field field number to map, starting from 0 //! @param dof degree of freedom number on the trace of field "field" //! //! The function returns the degree of freedom number in the original //! element virtual size_t dofMap(size_t FaceIndex, size_t field, size_t dof) const = 0; }; /** \brief ElementBoundaryTraces_: implementation of ElementBoundaryTraces An ElementBoundaryTraces_ allows derived classes to add Element_ objects, one per face whose trace is desired. The class is abstract since the getNormal function is yet to be defined by the specific derived ElementBoundaryTraces classes. The faces added with addFace are copied into the object, not referenced. */ class ElementBoundaryTraces_: public ElementBoundaryTraces { private: void copy (const ElementBoundaryTraces_& that) { FaceNumbers = that.FaceNumbers; for (size_t i = 0; i < that.FaceElements.size (); i++) { FaceElements.push_back (that.FaceElements[i]->clone ()); } } void destroy () { for (size_t i = 0; i < FaceElements.size (); i++) { delete FaceElements[i]; FaceElements[i] = NULL; } } public: ElementBoundaryTraces_ () { } virtual ~ElementBoundaryTraces_ () { destroy(); } ElementBoundaryTraces_ (const ElementBoundaryTraces_ & that) : ElementBoundaryTraces (that) { copy (that); } ElementBoundaryTraces_& operator = (const ElementBoundaryTraces_& that) { if (this != &that) { destroy (); copy (that); } return (*this); } virtual ElementBoundaryTraces_ * clone () const = 0; size_t getNumTraceFaces () const { return FaceElements.size (); } const std::vector<size_t> & getTraceFaceIds () const { return FaceNumbers; } inline size_t getTraceNumberOfFace (size_t FaceIndex) const { for (size_t i = 0; i < FaceNumbers.size (); i++) { if (FaceNumbers[i] == FaceIndex) { return i; } } return -1; } virtual const Element & getTrace (size_t FaceIndex) const { return *FaceElements[FaceIndex]; } protected: void addFace (const Element_ * NewFace, const size_t FaceNumber) { FaceElements.push_back (NewFace->clone ()); FaceNumbers.push_back (FaceNumber); } private: std::vector<const Element *> FaceElements; std::vector<size_t> FaceNumbers; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP12DElement-modelOutput
Number of fields: 2 should be 2 Number of dof field(0): 3 should be 3 Number of dof field(1): 3 should be 3 Shape function values at quad points field(0): 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Shape function values at quad points field(1): 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Shape function derivatives values at quad points field(0): 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Shape function derivatives values at quad points field(1): 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weight values at quad points field(0): 0.166667 0.166667 0.166667 Integration weight values at quad points field(1): 0.166667 0.166667 0.166667 Quad points coordinates for field(0): 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Quad points coordinates for field(1): 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Test Copy Constructor Number of fields: 2 should be 2 Number of dof field(0): 3 should be 3 Number of dof field(1): 3 should be 3 Shape function values at quad points field(0): 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Shape function values at quad points field(1): 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Shape function derivatives values at quad points field(0): 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Shape function derivatives values at quad points field(1): 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weight values at quad points field(0): 0.166667 0.166667 0.166667 Integration weight values at quad points field(1): 0.166667 0.166667 0.166667 Quad points coordinates for field(0): 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Quad points coordinates for field(1): 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Cloned element before destruction. Test cloning mechanism Number of fields: 2 should be 2 Number of dof field(0): 3 should be 3 Number of dof field(1): 3 should be 3 Shape function values at quad points field(0): 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Shape function values at quad points field(1): 0.666667 0.166667 0.166667 0.166667 0.666667 0.166667 0.166667 0.166667 0.666667 Shape function derivatives values at quad points field(0): 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Shape function derivatives values at quad points field(1): 1 0 0 1 -1 -1 1 0 0 1 -1 -1 1 0 0 1 -1 -1 Integration weight values at quad points field(0): 0.166667 0.166667 0.166667 Integration weight values at quad points field(1): 0.166667 0.166667 0.166667 Quad points coordinates for field(0): 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667 Quad points coordinates for field(1): 0.666667 0.166667 0.166667 0.666667 0.166667 0.166667
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP12DElementBoundaryTraces-modelOutput
Number of traces: 2 should be 2 Face number : 0 Normal components 0.707107 0.707107 Face number : 2 Normal components 0 -1 Face number : 0 Shape functions values for the first field 0.788675 0.211325 0.211325 0.788675 Integration point coordinates 0.788675 0.211325 0.211325 0.788675 Face number : 2 Shape functions values for the first field 0.788675 0.211325 0.211325 0.788675 Integration point coordinates 0.211325 0 0.788675 0 Test copy constructor Number of traces: 2 should be 2 Face number : 0 Normal components 0.707107 0.707107 Face number : 2 Normal components 0 -1 Face number : 0 Shape functions values for the first field 0.788675 0.211325 0.211325 0.788675 Integration point coordinates 0.788675 0.211325 0.211325 0.788675 Face number : 2 Shape functions values for the first field 0.788675 0.211325 0.211325 0.788675 Integration point coordinates 0.211325 0 0.788675 0 Test Cloning Number of traces: 2 should be 2 Face number : 0 Normal components 0.707107 0.707107 Face number : 2 Normal components 0 -1 Face number : 0 Shape functions values for the first field 0.788675 0.211325 0.211325 0.788675 Integration point coordinates 0.788675 0.211325 0.211325 0.788675 Face number : 2 Shape functions values for the first field 0.788675 0.211325 0.211325 0.788675 Integration point coordinates 0.211325 0 0.788675 0 Test ThreeDofs traces Number of traces: 2 should be 2 Face number : 0 Normal components 0.707107 0.707107 Face number : 2 Normal components 0 -1 Face number : 0 Shape functions values for the first field 0.788675 0.211325 0 0.211325 0.788675 0 Integration point coordinates 0.788675 0.211325 0.211325 0.788675 Face number : 2 Shape functions values for the first field 0.211325 0 0.788675 0.788675 0 0.211325 Integration point coordinates 0.211325 0 0.788675 0
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP12DElementBoundaryTraces.cpp
/* * testP12DElementBoundaryTraces.cpp * DG++ * * Created by Adrian Lew on 10/12/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "P12DElement.h" #include <iostream> int main() { double Vertices[] = {1,0,0,1,0,0}; std::vector<double> Vertices0(Vertices, Vertices+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); Segment<2>::SetGlobalCoordinatesArray(Vertices0); ElementBoundaryTraces * TestElementBoundaryClone; sleep(2); P12DElement<2> TestElement(1,2,3); { P12DElementBoundaryTraces<2> TestElementBoundary(TestElement, true, false, true, P12DTrace<2>::TwoDofs); std::cout << "Number of traces: " << TestElementBoundary.getNumTraceFaces() << " should be 2\n"; for(unsigned int a=0; a<TestElementBoundary.getNumTraceFaces(); a++) { int facenumber = TestElementBoundary.getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Normal components\n"; for(unsigned int q=0;q<TestElementBoundary.getNormal(a).size();q++) std::cout << TestElementBoundary.getNormal(a)[q] << " "; std::cout << "\n"; } for(unsigned int a=0; a<TestElementBoundary.getNumTraceFaces(); a++) { int facenumber = TestElementBoundary.getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Shape functions values for the first field\n"; const Element & face = TestElementBoundary[a]; for(unsigned int q=0;q<face.getShapes(0).size();q++) std::cout << face.getShapes(0)[q] << " "; std::cout << "\n"; std::cout << "Integration point coordinates\n"; for(unsigned int q=0;q<face.getIntegrationPtCoords(0).size();q++) std::cout << face.getIntegrationPtCoords(0)[q] << " "; std::cout << "\n"; } std::cout << "\nTest copy constructor\n"; P12DElementBoundaryTraces<2> TestElementBoundaryCopy(TestElementBoundary); std::cout << "Number of traces: " << TestElementBoundaryCopy.getNumTraceFaces() << " should be 2\n"; for(unsigned int a=0; a<TestElementBoundaryCopy.getNumTraceFaces(); a++) { int facenumber = TestElementBoundaryCopy.getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Normal components\n"; for(unsigned int q=0;q<TestElementBoundaryCopy.getNormal(a).size();q++) std::cout << TestElementBoundaryCopy.getNormal(a)[q] << " "; std::cout << "\n"; } for(unsigned int a=0; a<TestElementBoundaryCopy.getNumTraceFaces(); a++) { int facenumber = TestElementBoundaryCopy.getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Shape functions values for the first field\n"; const Element & face = TestElementBoundaryCopy[a]; for(unsigned int q=0;q<face.getShapes(0).size();q++) std::cout << face.getShapes(0)[q] << " "; std::cout << "\n"; std::cout << "Integration point coordinates\n"; for(unsigned int q=0;q<face.getIntegrationPtCoords(0).size();q++) std::cout << face.getIntegrationPtCoords(0)[q] << " "; std::cout << "\n"; } std::cout << "\nTest Cloning\n"; TestElementBoundaryClone = TestElementBoundary.Clone(); } std::cout << "Number of traces: " << TestElementBoundaryClone->getNumTraceFaces() << " should be 2\n"; for(unsigned int a=0; a<TestElementBoundaryClone->getNumTraceFaces(); a++) { int facenumber = TestElementBoundaryClone->getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Normal components\n"; for(unsigned int q=0;q<TestElementBoundaryClone->getNormal(a).size();q++) std::cout << TestElementBoundaryClone->getNormal(a)[q] << " "; std::cout << "\n"; } for(unsigned int a=0; a<TestElementBoundaryClone->getNumTraceFaces(); a++) { int facenumber = TestElementBoundaryClone->getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Shape functions values for the first field\n"; const Element & face = (*TestElementBoundaryClone)[a]; for(unsigned int q=0;q<face.getShapes(0).size();q++) std::cout << face.getShapes(0)[q] << " "; std::cout << "\n"; std::cout << "Integration point coordinates\n"; for(unsigned int q=0;q<face.getIntegrationPtCoords(0).size();q++) std::cout << face.getIntegrationPtCoords(0)[q] << " "; std::cout << "\n"; } delete TestElementBoundaryClone; { std::cout << "\n Test ThreeDofs traces\n"; P12DElementBoundaryTraces<2> TestElementBoundary(TestElement, true, false, true, P12DTrace<2>::ThreeDofs); std::cout << "Number of traces: " << TestElementBoundary.getNumTraceFaces() << " should be 2\n"; for(unsigned int a=0; a<TestElementBoundary.getNumTraceFaces(); a++) { int facenumber = TestElementBoundary.getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Normal components\n"; for(unsigned int q=0;q<TestElementBoundary.getNormal(a).size();q++) std::cout << TestElementBoundary.getNormal(a)[q] << " "; std::cout << "\n"; } for(unsigned int a=0; a<TestElementBoundary.getNumTraceFaces(); a++) { int facenumber = TestElementBoundary.getTraceFaceIds()[a]; std::cout << "Face number : " << facenumber << std::endl; std::cout << "Shape functions values for the first field\n"; const Element & face = TestElementBoundary[a]; for(unsigned int q=0;q<face.getShapes(0).size();q++) std::cout << face.getShapes(0)[q] << " "; std::cout << "\n"; std::cout << "Integration point coordinates\n"; for(unsigned int q=0;q<face.getIntegrationPtCoords(0).size();q++) std::cout << face.getIntegrationPtCoords(0)[q] << " "; std::cout << "\n"; } } }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP12DTrace.cpp
/* * testP12DElement.cpp * DG++ * * Created by Adrian Lew on 10/12/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "P12DElement.h" #include <iostream> int main() { double Vertices[] = {1,0,0,1,0,0}; std::vector<double> Vertices0(Vertices, Vertices+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); Segment<2>::SetGlobalCoordinatesArray(Vertices0); sleep(2); P12DElement<2> TestElement(1,2,3); P12DTrace<2> TestTraceOne(TestElement,P12DTrace<2>::FaceOne,P12DTrace<2>::TwoDofs); P12DTrace<2> TestTraceTwo(TestElement,P12DTrace<2>::FaceTwo,P12DTrace<2>::TwoDofs); P12DTrace<2> TestTraceThree(TestElement,P12DTrace<2>::FaceThree,P12DTrace<2>::TwoDofs); P12DTrace<2> * Faces[] = { &TestTraceOne, &TestTraceTwo, &TestTraceThree}; for(int i=0; i<3; i++) { std::cout << "\nTesting Face: "<< i+1 << "\n"; std::cout << "Number of fields: " << Faces[i]->getFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << Faces[i]->getDof(0) << " should be 2\n"; std::cout << "Number of dof field(1): " << Faces[i]->getDof(1) << " should be 2\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<Faces[i]->getShapes(a).size();q++) std::cout << Faces[i]->getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<Faces[i]->getIntegrationWeights(a).size();q++) std::cout << Faces[i]->getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<Faces[i]->getIntegrationPtCoords(a).size();q++) std::cout << Faces[i]->getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } std::cout << "No shape function derivatives tested\n"; } P12DTrace<2> *VirtualTraceOne; { P12DTrace<2> CopyTraceOne(TestTraceOne); std::cout << "\nTest Copy Constructor for Face 1\n"; std::cout << "Number of fields: " << CopyTraceOne.getFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << CopyTraceOne.getDof(0) << " should be 2\n"; std::cout << "Number of dof field(1): " << CopyTraceOne.getDof(1) << " should be 2\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyTraceOne.getShapes(a).size();q++) std::cout << CopyTraceOne.getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyTraceOne.getIntegrationWeights(a).size();q++) std::cout << CopyTraceOne.getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<CopyTraceOne.getIntegrationPtCoords(a).size();q++) std::cout << CopyTraceOne.getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } std::cout << "No shape function derivatives tested\n"; VirtualTraceOne = CopyTraceOne.clone(); std::cout << "\nCloned element before destruction. Test cloning mechanism\n"; } std::cout << "Number of fields: " << VirtualTraceOne->getFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << VirtualTraceOne->getDof(0) << " should be 2\n"; std::cout << "Number of dof field(1): " << VirtualTraceOne->getDof(1) << " should be 2\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualTraceOne->getShapes(a).size();q++) std::cout << VirtualTraceOne->getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualTraceOne->getIntegrationWeights(a).size();q++) std::cout << VirtualTraceOne->getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualTraceOne->getIntegrationPtCoords(a).size();q++) std::cout << VirtualTraceOne->getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } std::cout << "No shape function derivatives tested\n\n"; delete VirtualTraceOne; std::cout << "Test different ShapeType\n"; P12DTrace<2> TestTraceOneType(TestElement,P12DTrace<2>::FaceOne,P12DTrace<2>::ThreeDofs); P12DTrace<2> TestTraceTwoType(TestElement,P12DTrace<2>::FaceTwo,P12DTrace<2>::ThreeDofs); P12DTrace<2> TestTraceThreeType(TestElement,P12DTrace<2>::FaceThree,P12DTrace<2>::ThreeDofs); Faces[0] = &TestTraceOneType; Faces[1] = &TestTraceTwoType; Faces[2] = &TestTraceThreeType; for(int i=0; i<3; i++) { std::cout << "\nTesting Face: "<< i+1 << "\n"; std::cout << "Number of fields: " << Faces[i]->getFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << Faces[i]->getDof(0) << " should be 3\n"; std::cout << "Number of dof field(1): " << Faces[i]->getDof(1) << " should be 3\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<Faces[i]->getShapes(a).size();q++) std::cout << Faces[i]->getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<Faces[i]->getIntegrationWeights(a).size();q++) std::cout << Faces[i]->getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<Faces[i]->getIntegrationPtCoords(a).size();q++) std::cout << Faces[i]->getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } std::cout << "No shape function derivatives tested\n"; } }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP13DElementBoundaryTraces.cpp
/* Sriramajayam */ // testP13DElementBoundaryTraces.cpp. #include "P13DElement.h" #include <iostream> int main() { double V0[] = {1,0,0, 0,1,0, 0,0,0, 0,0,1}; std::vector<double> Vertices(V0, V0+12); Tetrahedron::SetGlobalCoordinatesArray(Vertices); Triangle<3>::SetGlobalCoordinatesArray(Vertices); Segment<3>::SetGlobalCoordinatesArray(Vertices); P13DElement<2> Elm(1,2,3,4); P13DElementBoundaryTraces<2> EBT(Elm, true, false, true, true, P13DTrace<2>::ThreeDofs); std::cout<<"\n Number of Traces: "<<EBT.getNumTraceFaces()<<" should be 3. \n"; for(unsigned int a=0; a<3; a++) // Change to test different/all traces. { int facenumber = EBT.getTraceFaceIds()[a]; std::cout<<" \n FaceNumber :"<<facenumber<<"\n"; std::cout<<"\n Normal to face: "; for(unsigned int q=0; q<EBT.getNormal(a).size(); q++) std::cout<< EBT.getNormal(a)[q]<<", "; std::cout<<"\n"; } for(unsigned int a=0; a<1; a++) { int facenumber = EBT.getTraceFaceIds()[a]; std::cout<<"\nFace Number :"<<facenumber<<"\n"; const Element &face = EBT[a]; // Integration weights: std::cout<<"\n Integration weights: \n"; for(unsigned int q=0; q<face.getIntegrationWeights(0).size(); q++) std::cout<<face.getIntegrationWeights(0)[q]<<", "; // Integration points: std::cout<<"\n Integration point coordinates: \n"; for(unsigned int q=0; q<face.getIntegrationPtCoords(0).size(); q++) std::cout<<face.getIntegrationPtCoords(0)[q]<<", "; // Shape functions: std::cout<<"\n Shape Functions at quadrature points: \n"; for(unsigned int q=0; q<face.getShapes(0).size(); q++) std::cout<<face.getShapes(0)[q]<<", "; std::cout<<"\n"; } }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP13DElement.cpp
// Sriramajayam // Purpose: To check P13DElement. #include "P13DElement.h" #include <iostream> #include <vector> int main() { double Vertices[] = {1,0,0, 0,1,0, 0,0,0, 0,0,1}; std::vector<double> Vertices0(Vertices, Vertices+12); Tetrahedron::SetGlobalCoordinatesArray(Vertices0); P13DElement<2> TestElement(1,2,3,4); Element * VirtualElement; sleep(2); std::cout << "Number of fields: " << TestElement.getFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << TestElement.getDof(0) << " should be 4\n"; std::cout << "Number of dof field(1): " << TestElement.getDof(1) << " should be 4\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getShapes(a).size();q++) std::cout << TestElement.getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Shape function derivatives values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getDShapes(a).size();q++) std::cout << TestElement.getDShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getIntegrationWeights(a).size();q++) std::cout << TestElement.getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getIntegrationPtCoords(a).size();q++) std::cout << TestElement.getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } // testing CopyConstructor : // { P13DElement<2> CopyElement(TestElement); std::cout << "Test Copy Constructor\n"; std::cout<<"Number of fields: " << CopyElement.getFields() << " should be 2\n"; std::cout<<"Number of dof field(0): " <<CopyElement.getDof(0)<< " should be 4\n"; std::cout<<"Number of dof field(1): " <<CopyElement.getDof(1)<< " should be 4\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getShapes(a).size();q++) std::cout << CopyElement.getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Shape function derivatives values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getDShapes(a).size();q++) std::cout << CopyElement.getDShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getIntegrationWeights(a).size();q++) std::cout << CopyElement.getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points cooridnates for field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getIntegrationPtCoords(a).size();q++) std::cout << CopyElement.getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } // Cloning mechanism : // VirtualElement = CopyElement.clone(); std::cout << "Cloned element before destruction. Test cloning mechanism\n"; } std::cout <<"Number of fields: " << VirtualElement->getNumFields() << " should be 2\n"; std::cout <<"Number of dof field(0): "<<VirtualElement->getDof(0)<<" should be 4\n"; std::cout <<"Number of dof field(1): "<<VirtualElement->getDof(1)<<" should be 4\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getShapes(a).size();q++) std::cout << VirtualElement->getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Shape function derivatives values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getDShapes(a).size();q++) std::cout << VirtualElement->getDShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getIntegrationWeights(a).size();q++) std::cout << VirtualElement->getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points cooridnates for field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getIntegrationPtCoords(a).size();q++) std::cout << VirtualElement->getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } delete VirtualElement; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP13DTrace.cpp
/* Sriramajayam */ // testP13DTrace.cpp #include "P13DElement.h" #include <iostream> int main() { double V0[] = {1,0,0, 0,1,0, 0,0,0, 0,0,1}; std::vector<double> Vertices(V0, V0+12); Tetrahedron::SetGlobalCoordinatesArray(Vertices); Triangle<3>::SetGlobalCoordinatesArray(Vertices); Segment<3>::SetGlobalCoordinatesArray(Vertices); P13DElement<2> Elm(1,2,3,4); P13DTrace<2> Trace1(Elm, P13DTrace<2>::FaceOne, P13DTrace<2>::ThreeDofs); P13DTrace<2> Trace2(Elm, P13DTrace<2>::FaceTwo, P13DTrace<2>::ThreeDofs); P13DTrace<2> Trace3(Elm, P13DTrace<2>::FaceThree, P13DTrace<2>::ThreeDofs); P13DTrace<2> Trace4(Elm, P13DTrace<2>::FaceFour, P13DTrace<2>::ThreeDofs); P13DTrace<2> * Faces[] = { &Trace1, &Trace2, &Trace3, &Trace4}; for(int i=1; i<2; i++) // Change to test different/all traces. { std::cout<<"\n Testing Face: "<<i<<".\n"; std::cout<<"\n Number of Fields: "<<Faces[i]->GetFields()<<" should be 2\n"; std::cout<<"\nNumber of dof field(0): "<<Faces[i]->getDof(0)<<" should be 3\n"; std::cout<<"\nNumber of dof field(1): "<<Faces[i]->getDof(1)<<" should be 3\n"; // Printing Shape functions at quadrature points. for(int f=0; f<2; f++) { std::cout <<"\n Shape Function values at quad point for field "<< f<< ":\n"; for(unsigned int q=0; q<Faces[i]->getShapes(f).size(); q++) std::cout << Faces[i]->getShapes(f)[q] <<" "; std::cout << "\n"; } // Printing integration weights at quad points: for(int f=0; f<2; f++) { std::cout <<"\n Integration weights at quad point for field "<< f<< ":\n"; for(unsigned int q=0; q<Faces[i]->getIntegrationWeights(f).size(); q++) std::cout << Faces[i]->getIntegrationWeights(f)[q] <<" "; std::cout << "\n"; } // Printing integration quad points: for(int f=0; f<2; f++) { std::cout <<"\n Quad point coordinates for field "<< f<< ":\n"; for(unsigned int q=0; q<Faces[i]->getIntegrationPtCoords(f).size(); q++) std::cout << Faces[i]->getIntegrationPtCoords(f)[q] <<" "; std::cout << "\n"; } std::cout<<"\n Shape function derivatives not tested. \n"; } std::cout<< "\n Test Successful. \n\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP12DElement.cpp
/* * testP12DElement.cpp * DG++ * * Created by Adrian Lew on 9/22/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "P12DElement.h" #include <iostream> int main() { double Vertices[] = {1,0,0,1,0,0}; std::vector<double> Vertices0(Vertices, Vertices+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); P12DElement<2> TestElement(1,2,3); Element * VirtualElement; sleep(2); std::cout << "Number of fields: " << TestElement.GetFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << TestElement.getDof(0) << " should be 3\n"; std::cout << "Number of dof field(1): " << TestElement.getDof(1) << " should be 3\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getShapes(a).size();q++) std::cout << TestElement.getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Shape function derivatives values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getDShapes(a).size();q++) std::cout << TestElement.getDShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getIntegrationWeights(a).size();q++) std::cout << TestElement.getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<TestElement.getIntegrationPtCoords(a).size();q++) std::cout << TestElement.getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } { P12DElement<2> CopyElement(TestElement); std::cout << "Test Copy Constructor\n"; std::cout << "Number of fields: " << CopyElement.GetFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << CopyElement.getDof(0) << " should be 3\n"; std::cout << "Number of dof field(1): " << CopyElement.getDof(1) << " should be 3\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getShapes(a).size();q++) std::cout << CopyElement.getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Shape function derivatives values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getDShapes(a).size();q++) std::cout << CopyElement.getDShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getIntegrationWeights(a).size();q++) std::cout << CopyElement.getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<CopyElement.getIntegrationPtCoords(a).size();q++) std::cout << CopyElement.getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } VirtualElement = CopyElement.clone(); std::cout << "Cloned element before destruction. Test cloning mechanism\n"; } std::cout << "Number of fields: " << VirtualElement->getNumFields() << " should be 2\n"; std::cout << "Number of dof field(0): " << VirtualElement->getDof(0) << " should be 3\n"; std::cout << "Number of dof field(1): " << VirtualElement->getDof(1) << " should be 3\n"; for(int a=0; a<2; a++) { std::cout << "Shape function values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getShapes(a).size();q++) std::cout << VirtualElement->getShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Shape function derivatives values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getDShapes(a).size();q++) std::cout << VirtualElement->getDShapes(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Integration weight values at quad points field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getIntegrationWeights(a).size();q++) std::cout << VirtualElement->getIntegrationWeights(a)[q] << " "; std::cout << "\n"; } for(int a=0; a<2; a++) { std::cout << "Quad points coordinates for field("<< a<< "):\n"; for(unsigned int q=0;q<VirtualElement->getIntegrationPtCoords(a).size();q++) std::cout << VirtualElement->getIntegrationPtCoords(a)[q] << " "; std::cout << "\n"; } delete VirtualElement; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libElement/test/testP12DTrace-modelOutput
Testing Face: 1 Number of fields: 2 should be 2 Number of dof field(0): 2 should be 2 Number of dof field(1): 2 should be 2 Shape function values at quad points field(0): 0.788675 0.211325 0.211325 0.788675 Shape function values at quad points field(1): 0.788675 0.211325 0.211325 0.788675 Integration weight values at quad points field(0): 0.707107 0.707107 Integration weight values at quad points field(1): 0.707107 0.707107 Quad points coordinates for field(0): 0.788675 0.211325 0.211325 0.788675 Quad points coordinates for field(1): 0.788675 0.211325 0.211325 0.788675 No shape function derivatives tested Testing Face: 2 Number of fields: 2 should be 2 Number of dof field(0): 2 should be 2 Number of dof field(1): 2 should be 2 Shape function values at quad points field(0): 0.788675 0.211325 0.211325 0.788675 Shape function values at quad points field(1): 0.788675 0.211325 0.211325 0.788675 Integration weight values at quad points field(0): 0.5 0.5 Integration weight values at quad points field(1): 0.5 0.5 Quad points coordinates for field(0): 0 0.788675 0 0.211325 Quad points coordinates for field(1): 0 0.788675 0 0.211325 No shape function derivatives tested Testing Face: 3 Number of fields: 2 should be 2 Number of dof field(0): 2 should be 2 Number of dof field(1): 2 should be 2 Shape function values at quad points field(0): 0.788675 0.211325 0.211325 0.788675 Shape function values at quad points field(1): 0.788675 0.211325 0.211325 0.788675 Integration weight values at quad points field(0): 0.5 0.5 Integration weight values at quad points field(1): 0.5 0.5 Quad points coordinates for field(0): 0.211325 0 0.788675 0 Quad points coordinates for field(1): 0.211325 0 0.788675 0 No shape function derivatives tested Test Copy Constructor for Face 1 Number of fields: 2 should be 2 Number of dof field(0): 2 should be 2 Number of dof field(1): 2 should be 2 Shape function values at quad points field(0): 0.788675 0.211325 0.211325 0.788675 Shape function values at quad points field(1): 0.788675 0.211325 0.211325 0.788675 Integration weight values at quad points field(0): 0.707107 0.707107 Integration weight values at quad points field(1): 0.707107 0.707107 Quad points coordinates for field(0): 0.788675 0.211325 0.211325 0.788675 Quad points coordinates for field(1): 0.788675 0.211325 0.211325 0.788675 No shape function derivatives tested Cloned element before destruction. Test cloning mechanism Number of fields: 2 should be 2 Number of dof field(0): 2 should be 2 Number of dof field(1): 2 should be 2 Shape function values at quad points field(0): 0.788675 0.211325 0.211325 0.788675 Shape function values at quad points field(1): 0.788675 0.211325 0.211325 0.788675 Integration weight values at quad points field(0): 0.707107 0.707107 Integration weight values at quad points field(1): 0.707107 0.707107 Quad points coordinates for field(0): 0.788675 0.211325 0.211325 0.788675 Quad points coordinates for field(1): 0.788675 0.211325 0.211325 0.788675 No shape function derivatives tested Test different ShapeType Testing Face: 1 Number of fields: 2 should be 2 Number of dof field(0): 3 should be 3 Number of dof field(1): 3 should be 3 Shape function values at quad points field(0): 0.788675 0.211325 0 0.211325 0.788675 0 Shape function values at quad points field(1): 0.788675 0.211325 0 0.211325 0.788675 0 Integration weight values at quad points field(0): 0.707107 0.707107 Integration weight values at quad points field(1): 0.707107 0.707107 Quad points coordinates for field(0): 0.788675 0.211325 0.211325 0.788675 Quad points coordinates for field(1): 0.788675 0.211325 0.211325 0.788675 No shape function derivatives tested Testing Face: 2 Number of fields: 2 should be 2 Number of dof field(0): 3 should be 3 Number of dof field(1): 3 should be 3 Shape function values at quad points field(0): 0 0.788675 0.211325 0 0.211325 0.788675 Shape function values at quad points field(1): 0 0.788675 0.211325 0 0.211325 0.788675 Integration weight values at quad points field(0): 0.5 0.5 Integration weight values at quad points field(1): 0.5 0.5 Quad points coordinates for field(0): 0 0.788675 0 0.211325 Quad points coordinates for field(1): 0 0.788675 0 0.211325 No shape function derivatives tested Testing Face: 3 Number of fields: 2 should be 2 Number of dof field(0): 3 should be 3 Number of dof field(1): 3 should be 3 Shape function values at quad points field(0): 0.211325 0 0.788675 0.788675 0 0.211325 Shape function values at quad points field(1): 0.211325 0 0.788675 0.788675 0 0.211325 Integration weight values at quad points field(0): 0.5 0.5 Integration weight values at quad points field(1): 0.5 0.5 Quad points coordinates for field(0): 0.211325 0 0.788675 0 Quad points coordinates for field(1): 0.211325 0 0.788675 0 No shape function derivatives tested
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libQuad/Quadrature.h
/** * Quadrature.h * DG++ * * Created by Adrian Lew on 9/4/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef QUADRATURE #define QUADRATURE #include <algorithm> /** \brief base class for any quadrature rule A quadrature rule provides and approximation of the integral over a domain \f$\Omega\f$, and it has:\n 1) A number of quadrature point coordinates in \f$\Omega\f$. (map) 2) Weights at each quadrature point 3) A second set of coordinates for the same quadrature points. (Shape) The number of coordinates in (1) of each quadrature point should be unisolvent, i.e., each coordinate can be varied independently. The reason for this choice is that otherwise we need a way to convey the constraint between coordinates when functions of these coordinates and their derivatives are considered. For example, the mapping from the parametric configuration to the real space in finite elements. In addition to the unisolvent set of coordinates above, the class also allows for an alternative set of coordinates for each gauss point. These do not need to be unisolvent, and can be used to localize the quadrature points when embedded in a higher dimensional space. For example, if \f$\Omega\f$ is a triangle in 3D, then the second set of coordinates provide the coordinates of these points in 3D. A specific example is the following: consider a triangle in 2D, and the integration over a segment on its boundary. The quadrature object for a segment should have only one (map) coordinate in (1) to be unisolvent. This coordinate is one of the barycentric coordinates of the quadrature point over the segment. However, if we have a function over the triangle and would like to restrict its values to the segment, we need the coordinates of the quadrature points in the triangle. This is the case when integrating a shape function in the triangle over the segment. This second set of coordinates is given in (3). Based on this example we shall call the coordinates in (1) map coordinates, and the coordinates in (3) Shape coordinates. Although the coordinates in (3) are not a natural inclusion in a quadrature rule, they provide the simplest implementation for the scenario just described. A number of specific Quadrature objects are defined in Quadrature.cpp, and declared here. */ class Quadrature { public: //! @param NQ number of quadrature points //! @param NC number of coordinates for each point //! @param xqdat vector with coordinates of the quadrature points //! xqdat[a*NC+i] gives the i-th coordinate of quadrature point a //! @param wqdat vector with quadrature point weights //! wq[a] is the weight of quadrature point a //! This constructor sets the two sets of coordinates for the quadrature points to //! be the same. Quadrature(const double * const xqdat, const double * const wqdat, const size_t NC, const size_t NQ); //! @param NQ number of quadrature points //! @param NCmap number of map coordinates for each point //! @param NCshape number of shape coordinates for each point //! @param xqdatmap vector with coordinates of the quadrature points //! xqdatmap[a*NC+i] gives the i-th coordinate of quadrature point a //! @param xqdatshape vector with coordinates of the quadrature points //! xqdatshape[a*NC+i] gives the i-th coordinate of quadrature point a //! @param wqdat vector with quadrature point weights //! wq[a] is the weight of quadrature point a Quadrature(const double * const xqdatmap, const double * const xqdatshape, const double * const wqdat, const size_t NCmap, const size_t NCshape, const size_t NQ); inline virtual ~Quadrature() { if(xqmap!=xqshape) { delete[] xqshape; xqshape = NULL; } delete[] xqmap; xqmap = NULL; delete[] wq; wq = NULL; } Quadrature(const Quadrature &); Quadrature * clone() const; // Accessors/Mutators inline size_t getNumQuadraturePoints() const { return numQuadraturePoints; } //! Returns the number of map coordinates inline size_t getNumCoordinates() const { return numMapCoordinates; } //! Returns the number of shape coordinates inline size_t getNumShapeCoordinates() const { return numShapeCoordinates; } //! Return map coordinates of quadrature point q inline const double * getQuadraturePoint(size_t q) const { return xqmap+q*numMapCoordinates; } //! Return shape coordinates of quadrature point q inline const double * getQuadraturePointShape(size_t q) const { return xqshape+q*numShapeCoordinates; } //! Returns weight of quadrature point q inline double getQuadratureWeights(size_t q) const { return wq[q]; } private: double * xqmap; double * xqshape; double * wq; size_t numMapCoordinates; size_t numShapeCoordinates; size_t numQuadraturePoints; }; /** \brief SpecificQuadratures: class used just to qualify all specific quadrature objects used to build the quadrature rules. */ class SpecificQuadratures {}; /** \brief 3-point Gauss quadrature coordinates in the triangle (0,0), (1,0), (0,1), and its traces. Barycentric coordinates used for the Gauss points. */ class Triangle_1: public SpecificQuadratures { public: //! Bulk quadrature static const Quadrature * const Bulk; //! Face (1,2) quadrature static const Quadrature * const FaceOne; //! Face (2,3) quadrature static const Quadrature * const FaceTwo; //! Face (3,1) quadrature static const Quadrature * const FaceThree; private: static const double BulkCoordinates[]; static const double BulkWeights[]; static const double FaceMapCoordinates[]; static const double FaceOneShapeCoordinates[]; static const double FaceOneWeights[]; static const double FaceTwoShapeCoordinates[]; static const double FaceTwoWeights[]; static const double FaceThreeShapeCoordinates[]; static const double FaceThreeWeights[]; }; /** \brief 2-point Gauss quadrature coordinates in the segment (0,1). Barycentric coordinates used for the Gauss points. */ class Line_1: public SpecificQuadratures { public: //! Bulk quadrature static const Quadrature * const Bulk; private: static const double BulkCoordinates[]; static const double BulkWeights[]; }; /*! * \brief Class for 4 point quadrature rules for tetrahedra. * * 4-point Gauss quadrature coordinates in the tetrahedron with * 0(1,0,0), 1(0,1,0), 2(0,0,0), 3(0,0,1) as vertices. * Barycentric coordinates are used for the Gauss points. * Barycentric coordinates are specified with respect to vertices 1,2 and 4 * in that order. Coordinate of vertex 3 is not independent. * * Quadrature for Faces: * Faces are ordered as - * Face 1: 2-1-0, * Face 2: 2-0-3, * Face 3: 2-3-1, * Face 4: 0-1-3. * * \todo Need to include a test for this quadrature */ class Tet_1: public SpecificQuadratures { public: //! Bulk quadrature static const Quadrature * const Bulk; //! Face (2-1-0) quadrature static const Quadrature * const FaceOne; //! Face (2-0-3) quadrature static const Quadrature * const FaceTwo; //! Face (2-3-1) quadrature static const Quadrature * const FaceThree; //! Face (0-1-3) quadrature static const Quadrature * const FaceFour; private: static const double BulkCoordinates[]; static const double BulkWeights[]; static const double FaceMapCoordinates[]; static const double FaceOneShapeCoordinates[]; static const double FaceOneWeights[]; static const double FaceTwoShapeCoordinates[]; static const double FaceTwoWeights[]; static const double FaceThreeShapeCoordinates[]; static const double FaceThreeWeights[]; static const double FaceFourShapeCoordinates[]; static const double FaceFourWeights[]; }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libQuad/Quadrature.cpp
/* * Quadrature.cpp * DG++ * * Created by Adrian Lew on 9/4/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include "Quadrature.h" #include <cmath> Quadrature::Quadrature (const double * const xqdat, const double * const wqdat, const size_t NC, const size_t NQ) : numMapCoordinates (NC), numShapeCoordinates (NC), numQuadraturePoints (NQ) { #if 0 if (NQ < 0 || NC < 0) { std::cerr << "Quadrature::Quadrature: Negative number of quadrature points or coordinates\n"; exit (1); // Bad..., to be improved in the future with exceptions } #endif xqshape = xqmap = new double[NQ * NC]; wq = new double[NQ]; for (size_t q = 0; q < NQ; q++) { for (size_t i = 0; i < NC; i++) { xqmap[q * NC + i] = xqdat[q * NC + i]; } wq[q] = wqdat[q]; } } Quadrature::Quadrature (const double * const xqdatmap, const double * const xqdatshape, const double * const wqdat, const size_t NCmap, const size_t NCshape, const size_t NQ) : numMapCoordinates (NCmap), numShapeCoordinates (NCshape), numQuadraturePoints (NQ) { #if 0 if (NQ < 0 || NCmap < 0 || NCshape < 0) { std::cerr << "Quadrature::Quadrature: Negative number of quadrature points or coordinates\n"; exit (1); // Bad..., to be improved in the future with exceptions } #endif xqmap = new double[NQ * NCmap]; xqshape = new double[NQ * NCshape]; wq = new double[NQ]; for (size_t q = 0; q < NQ; q++) { for (size_t i = 0; i < NCmap; i++) { xqmap[q * NCmap + i] = xqdatmap[q * NCmap + i]; } for (size_t i = 0; i < NCshape; i++) { xqshape[q * NCshape + i] = xqdatshape[q * NCshape + i]; } wq[q] = wqdat[q]; } } Quadrature::Quadrature (const Quadrature &SQ) : numMapCoordinates (SQ.numMapCoordinates),numShapeCoordinates (SQ.numShapeCoordinates), numQuadraturePoints (SQ.numQuadraturePoints) { xqmap = new double[numMapCoordinates * numQuadraturePoints]; if (SQ.xqmap != SQ.xqshape) xqshape = new double[numShapeCoordinates * numQuadraturePoints]; else xqshape = xqmap; wq = new double[numQuadraturePoints]; for (size_t q = 0; q < numQuadraturePoints; q++) { for (size_t i = 0; i < numMapCoordinates; i++) xqmap[q * numMapCoordinates + i] = SQ.xqmap[q * numMapCoordinates + i]; if (xqmap != xqshape) for (size_t i = 0; i < numShapeCoordinates; i++) xqshape[q * numShapeCoordinates + i] = SQ.xqshape[q * numShapeCoordinates + i]; wq[q] = SQ.wq[q]; } } Quadrature * Quadrature::clone () const { return new Quadrature (*this); } // Build specific quadratures // 3-point quadrature on Triangle (0,0), (1,0), (0,1) const double Triangle_1::BulkCoordinates[] = {0.6666666666666667e0,0.1666666666666667e0, 0.1666666666666667e0,0.6666666666666667e0, 0.1666666666666667e0,0.1666666666666667e0}; const double Triangle_1::BulkWeights [] = {1./6.,1./6.,1./6.}; const double Triangle_1::FaceMapCoordinates[] = {0.5 + 0.577350269/2., 0.5 - 0.577350269/2.}; // First barycentric coordinate in reference segment (0,1) const double Triangle_1::FaceOneShapeCoordinates[] = {0.5 + 0.577350269/2., 0.5 - 0.577350269/2., 0.5 - 0.577350269/2., 0.5 + 0.577350269/2.}; // Coordinates in the reference triangle const double Triangle_1::FaceOneWeights [] = {1./2.,1./2.}; const double Triangle_1::FaceTwoShapeCoordinates[] = {0., 0.5 + 0.577350269/2., 0., 0.5 - 0.577350269/2.}; // Coordinates in the reference triangle const double Triangle_1::FaceTwoWeights [] = {1./2.,1./2.}; const double Triangle_1::FaceThreeShapeCoordinates[] = {0.5 - 0.577350269/2., 0., 0.5 + 0.577350269/2., 0.}; // Coordinates in the reference triangle const double Triangle_1::FaceThreeWeights [] = {1./2.,1./2.}; const Quadrature * const Triangle_1::Bulk = new Quadrature(Triangle_1::BulkCoordinates, Triangle_1::BulkWeights, 2, 3); const Quadrature * const Triangle_1::FaceOne = new Quadrature(Triangle_1::FaceMapCoordinates, Triangle_1::FaceOneShapeCoordinates, Triangle_1::FaceOneWeights, 1, 2, 2); const Quadrature * const Triangle_1::FaceTwo = new Quadrature(Triangle_1::FaceMapCoordinates, Triangle_1::FaceTwoShapeCoordinates, Triangle_1::FaceTwoWeights, 1, 2, 2); const Quadrature * const Triangle_1::FaceThree = new Quadrature(Triangle_1::FaceMapCoordinates, Triangle_1::FaceThreeShapeCoordinates, Triangle_1::FaceThreeWeights, 1, 2, 2); // 2-point Gauss quadrature in a Segment (0,1) const double Line_1::BulkCoordinates[] = {0.5 + 0.577350269/2., 0.5 - 0.577350269/2.}; const double Line_1::BulkWeights [] = {1./2.,1./2.}; const Quadrature * const Line_1::Bulk = new Quadrature(Line_1::BulkCoordinates, Line_1::BulkWeights, 1, 2); // 4-point Gauss quadrature in a Tet (1,0,0), (0,1,0), (0,0,0), (0,0,1) const double Tet_1::BulkCoordinates[] = {0.58541020e0, 0.13819660e0, 0.13819660e0, 0.13819660e0, 0.58541020e0, 0.13819660e0, 0.13819660e0, 0.13819660e0, 0.58541020e0, 0.13819660e0, 0.13819660e0, 0.13819660e0}; const double Tet_1::BulkWeights [] = {1./24., 1./24., 1./24., 1./24.}; const double Tet_1::FaceMapCoordinates[] = {2./3., 1./6., 1./6., 2./3., 1./6., 1./6.}; // Face 1 : 2-1-0. const double Tet_1::FaceOneShapeCoordinates[] = { 1./6., 1./6., 0., 1./6., 2./3., 0., 2./3., 1./6., 0.}; const double Tet_1::FaceOneWeights [] = { 1./6., 1./6., 1./6.}; // Face 2 : 2-0-3. const double Tet_1::FaceTwoShapeCoordinates[] = { 1./6., 0., 1./6., 2./3., 0., 1./6., 1./6., 0., 2./3.}; const double Tet_1::FaceTwoWeights [] = { 1./6., 1./6., 1./6.}; // Face 3: 2-3-1. const double Tet_1::FaceThreeShapeCoordinates[] = { 0., 1./6., 1./6., 0., 1./6., 2./3., 0., 2./3., 1./6.}; const double Tet_1::FaceThreeWeights [] = { 1./6., 1./6., 1./6.}; // Face 4: 0-1-3. const double Tet_1::FaceFourShapeCoordinates [] = { 2./3., 1./6., 1./6., 1./6., 2./3., 1./6., 1./6., 1./6., 2./3.}; const double Tet_1::FaceFourWeights [] = { 1./6., 1./6., 1./6.}; const Quadrature * const Tet_1::Bulk = new Quadrature(Tet_1::BulkCoordinates, Tet_1::BulkWeights, 3, 4); const Quadrature * const Tet_1::FaceOne = new Quadrature(Tet_1::FaceMapCoordinates, Tet_1::FaceOneShapeCoordinates, Tet_1::FaceOneWeights, 2, 3, 3); const Quadrature * const Tet_1::FaceTwo = new Quadrature(Tet_1::FaceMapCoordinates, Tet_1::FaceTwoShapeCoordinates, Tet_1::FaceTwoWeights, 2, 3, 3); const Quadrature * const Tet_1::FaceThree = new Quadrature(Tet_1::FaceMapCoordinates, Tet_1::FaceThreeShapeCoordinates, Tet_1::FaceThreeWeights, 2, 3, 3); const Quadrature * const Tet_1::FaceFour = new Quadrature(Tet_1::FaceMapCoordinates, Tet_1::FaceFourShapeCoordinates, Tet_1::FaceFourWeights, 2, 3, 3);
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libQuad
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libQuad/test/testSimpleQuadrature.cpp
/* * testSimpleQuadrature.cpp * DG++ * * Created by Adrian Lew on 9/7/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Quadrature.h" #include <iostream> int main() { std::cout << Triangle_1::Bulk->getNumQuadraturePoints() << " should be " << 3 << "\n"; std::cout << Triangle_1::Bulk->getNumShapeCoordinates() << " should be " << 2 << "\n\n"; std::cout << Triangle_1::Bulk->getNumCoordinates() << " should be " << 2 << "\n\n"; for(int q=0; q<Triangle_1::Bulk->getNumQuadraturePoints(); q++) { for(int i=0; i<Triangle_1::Bulk->getNumCoordinates(); i++) std::cout << Triangle_1::Bulk->getQuadraturePoint(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.666667 0.166667 \n" "0.166667 0.666667 \n" "0.166667 0.166667 \n\n"; for(int q=0; q<Triangle_1::Bulk->getNumQuadraturePoints(); q++) { for(int i=0; i<Triangle_1::Bulk->getNumShapeCoordinates(); i++) std::cout << Triangle_1::Bulk->getQuadraturePointShape(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.666667 0.166667 \n" "0.166667 0.666667 \n" "0.166667 0.166667 \n\n"; for(int q=0; q<Triangle_1::Bulk->getNumQuadraturePoints(); q++) std::cout << Triangle_1::Bulk->getQuadratureWeights(q) << " "; std::cout << "\n"; std::cout << "should read \n" "0.166667 0.166667 0.166667\n\n"; std::cout << "\n Copy Constructor\n"; Quadrature GaussCopy(*Triangle_1::Bulk); std::cout << GaussCopy.getNumQuadraturePoints() << " should be " << 3 << "\n"; std::cout << GaussCopy.getNumShapeCoordinates() << " should be " << 2 << "\n\n"; std::cout << GaussCopy.getNumCoordinates() << " should be " << 2 << "\n\n"; for(int q=0; q<GaussCopy.getNumQuadraturePoints(); q++) { for(int i=0; i<GaussCopy.getNumCoordinates(); i++) std::cout << GaussCopy.getQuadraturePoint(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.666667 0.166667 \n" "0.166667 0.666667 \n" "0.166667 0.166667 \n\n"; for(int q=0; q<GaussCopy.getNumQuadraturePoints(); q++) { for(int i=0; i<GaussCopy.getNumShapeCoordinates(); i++) std::cout << GaussCopy.getQuadraturePointShape(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.666667 0.166667 \n" "0.166667 0.666667 \n" "0.166667 0.166667 \n\n"; for(int q=0; q<GaussCopy.getNumQuadraturePoints(); q++) std::cout << GaussCopy.getQuadratureWeights(q) << " "; std::cout << "\n"; std::cout << "should read \n " "0.166667 0.166667 0.166667\n\n"; std::cout << "\n Cloning and virtual mechanisms\n"; Quadrature *GaussClone = Triangle_1::Bulk->clone(); std::cout << GaussClone->getNumQuadraturePoints() << " should be " << 3 << "\n"; std::cout << GaussClone->getNumCoordinates() << " should be " << 2 << "\n\n"; for(int q=0; q<GaussClone->getNumQuadraturePoints(); q++) { for(int i=0; i<GaussClone->getNumCoordinates(); i++) std::cout << GaussClone->getQuadraturePoint(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.666667 0.166667 \n" "0.166667 0.666667 \n" "0.166667 0.166667 \n\n"; for(int q=0; q<GaussClone->getNumQuadraturePoints(); q++) std::cout << GaussClone->getQuadratureWeights(q) << " "; std::cout << "\n"; std::cout << "should read \n " "0.166667 0.166667 0.166667\n\n"; std::cout << Triangle_1::FaceOne->getNumQuadraturePoints() << " should be " << 2 << "\n"; std::cout << Triangle_1::FaceOne->getNumCoordinates() << " should be " << 1 << "\n\n"; std::cout << Triangle_1::FaceOne->getNumShapeCoordinates() << " should be " << 2 << "\n\n"; for(int q=0; q<Triangle_1::FaceOne->getNumQuadraturePoints(); q++) { for(int i=0; i<Triangle_1::FaceOne->getNumCoordinates(); i++) std::cout << Triangle_1::FaceOne->getQuadraturePoint(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.788675\n" "0.211325\n\n"; for(int q=0; q<Triangle_1::FaceOne->getNumQuadraturePoints(); q++) { for(int i=0; i<Triangle_1::FaceOne->getNumShapeCoordinates(); i++) std::cout << Triangle_1::FaceOne->getQuadraturePointShape(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.788675 0.211325\n" "0.211325 0.788675\n\n"; for(int q=0; q<Triangle_1::FaceOne->getNumQuadraturePoints(); q++) std::cout << Triangle_1::FaceOne->getQuadratureWeights(q) << " "; std::cout << "\n"; std::cout << "should read \n" "0.5 0.5\n\n"; std::cout << "Test copy constructor once more\n\n"; Quadrature NewTriangleFace(*Triangle_1::FaceOne); std::cout << NewTriangleFace.getNumQuadraturePoints() << " should be " << 2 << "\n"; std::cout << NewTriangleFace.getNumCoordinates() << " should be " << 1 << "\n\n"; std::cout << NewTriangleFace.getNumShapeCoordinates() << " should be " << 2 << "\n\n"; for(int q=0; q<NewTriangleFace.getNumQuadraturePoints(); q++) { for(int i=0; i<NewTriangleFace.getNumCoordinates(); i++) std::cout << NewTriangleFace.getQuadraturePoint(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.788675\n" "0.211325\n\n"; for(int q=0; q<NewTriangleFace.getNumQuadraturePoints(); q++) { for(int i=0; i<NewTriangleFace.getNumShapeCoordinates(); i++) std::cout << NewTriangleFace.getQuadraturePointShape(q)[i] << " "; std::cout << "\n"; } std::cout << "should read \n" "0.788675 0.211325\n" "0.211325 0.788675\n\n"; for(int q=0; q<NewTriangleFace.getNumQuadraturePoints(); q++) std::cout << NewTriangleFace.getQuadratureWeights(q) << " "; std::cout << "\n"; std::cout << "should read \n" "0.5 0.5\n\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm
rapidsai_public_repos/code-share/maxflow/galois/apps/avi/libElm/libShape/Shape.cpp
/* * Shape.cpp * DG++ * * Created by Adrian Lew on 9/7/06. * * Copyright (c) 2006 Adrian Lew * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Shape.h" #include <cmath> #include <iostream> bool Shape::consistencyTest (const double * X, const double Pert) const { double *DValNum = new double[getNumFunctions () * getNumVariables ()]; double *DValAnal = new double[getNumFunctions () * getNumVariables ()]; double *Xpert = new double[getNumVariables ()]; double *Valplus = new double[getNumFunctions ()]; double *Valminus = new double[getNumFunctions ()]; if (Pert <= 0) std::cerr << "Shape::ConsistencyTest - Pert cannot be less or equal than zero\n"; for (size_t i = 0; i < getNumVariables (); i++) { Xpert[i] = X[i]; for (size_t a = 0; a < getNumFunctions (); a++) DValAnal[a * getNumVariables () + i] = getDVal (a, X, i); } for (size_t i = 0; i < getNumVariables (); i++) { Xpert[i] = X[i] + Pert; for (size_t a = 0; a < getNumFunctions (); a++) Valplus[a] = getVal (a, Xpert); Xpert[i] = X[i] - Pert; for (size_t a = 0; a < getNumFunctions (); a++) Valminus[a] = getVal (a, Xpert); Xpert[i] = X[i]; for (size_t a = 0; a < getNumFunctions (); a++) DValNum[a * getNumVariables () + i] = (Valplus[a] - Valminus[a]) / (2 * Pert); } double error = 0; double normX = 0; double normDValNum = 0; double normDValAnal = 0; for (size_t i = 0; i < getNumVariables (); i++) { normX += X[i] * X[i]; for (size_t a = 0; a < getNumFunctions (); a++) { error += pow (DValAnal[a * getNumVariables () + i] - DValNum[a * getNumVariables () + i], 2.); normDValAnal += pow (DValAnal[a * getNumVariables () + i], 2.); normDValNum += pow (DValNum[a * getNumVariables () + i], 2.); } } error = sqrt (error); normX = sqrt (normX); normDValAnal = sqrt (normDValAnal); normDValNum = sqrt (normDValNum); delete[] Valplus; delete[] Valminus; delete[] Xpert; delete[] DValNum; delete[] DValAnal; if (error * (normX + Pert) < (normDValAnal < normDValNum ? normDValNum : normDValAnal) * Pert * 10) { return true; } else { return false; } }
0