Example #1
0
TYPED_TEST(Bell_Math_Vector2, ConstMethodCompileTime) {
	using T = TypeParam;
	using V = Vector2<T>;

	constexpr V a = { T{1}, 0};
	constexpr V b = { T{10}, T{13} };
	constexpr V c = { T{-5}, T{ 8} };

	static_assert( V::zero ().isZero(), "");
	static_assert(!V::unitX().isZero(), "");
	static_assert(!V::unitY().isZero(), "");

	static_assert(!V::zero ().equals(a), "");
	static_assert( V::unitX().equals(a), "");
	static_assert(!V::unitY().equals(a), "");

	static_assert(b.dot(c) == 54, "");
	static_assert(c.dot(b) == 54, "");

	static_assert(b.cross(c) ==  145, "");
	static_assert(c.cross(b) == -145, "");

	static_assert(b.lengthSq() == 269, "");
	static_assert(c.lengthSq() ==  89, "");

	static_assert(b.distanceSq(c) == 250, "");
	static_assert(c.distanceSq(b) == 250, "");
}
BOOST_FIXTURE_TEST_CASE(ViscosityValue, TestFixture<SetupSimple>)
{
    const Opm::BlackoilPropsAdFromDeck::Cells cells(5, 0);

    typedef Opm::BlackoilPropsAdFromDeck::V V;
    typedef Opm::BlackoilPropsAdFromDeck::ADB ADB;

    V Vpw;
    Vpw.resize(cells.size());
    Vpw[0] =  1*Opm::unit::barsa;
    Vpw[1] =  2*Opm::unit::barsa;
    Vpw[2] =  4*Opm::unit::barsa;
    Vpw[3] =  8*Opm::unit::barsa;
    Vpw[4] = 16*Opm::unit::barsa;

    // standard temperature
    V T = V::Constant(cells.size(), 273.15+20);

    BOOST_REQUIRE_EQUAL(Vpw.size(), cells.size());

    const V VmuWat = boprops_ad.muWat(ADB::constant(Vpw), ADB::constant(T), cells).value();

    BOOST_REQUIRE_EQUAL(Vpw.size(), cells.size());

    // Zero pressure dependence in water viscosity
    for (V::Index i = 0, n = VmuWat.size(); i < n; ++i) {
        BOOST_CHECK_EQUAL(VmuWat[i], VmuWat[0]);
    }
}
Example #3
0
void init () {
	char *buf;

	buf = (char *) MemAlloc (2048);
	if (! CapInit (buf)) {
		outerr("cannot read termcap\n",0);
		exit (1);
	}
	if (! v.VInit ()) {
		outerr("cannot initialize terminal\n",0);
		exit (1);
	}
	if (COLS < 80) {
		outerr("must be 80 columns on terminal\n",0);
		exit (1);
	}
	KeyInit (keymap, VFlush);
	v.VOpen();
	MemFree ((mem *) buf);

	/* H is the number of lines at file window */

	H = LINES/2-1;

}
Example #4
0
int main() {
  {
    using V = std::variant<int, ConstexprTestTypes::NoCtors>;
    constexpr V v;
    static_assert(v.index() == 0, "");
  }
  {
    using V = std::variant<int, long>;
    constexpr V v(std::in_place_index<1>);
    static_assert(v.index() == 1, "");
  }
  {
    using V = std::variant<int, std::string>;
    V v("abc");
    assert(v.index() == 1);
    v = 42;
    assert(v.index() == 0);
  }
#ifndef TEST_HAS_NO_EXCEPTIONS
  {
    using V = std::variant<int, MakeEmptyT>;
    V v;
    assert(v.index() == 0);
    makeEmpty(v);
    assert(v.index() == std::variant_npos);
  }
#endif
}
Example #5
0
TYPED_TEST(Bell_Math_Vector2_F, ConstMethod) {
	using T = TypeParam;
	using V = Vector2<T>;

	constexpr V a = { T{ 4}, T{3} };
	constexpr V b = { T{12}, T{5} };

	EXPECT_EQ( 5, a.length());
	EXPECT_EQ(13, b.length());

	EXPECT_EQ(         0,   V::unitX() .angle());
	EXPECT_EQ( pi<T>()/2,   V::unitY() .angle());
	EXPECT_EQ(-pi<T>()  , (-V::unitX()).angle());
	EXPECT_EQ(-pi<T>()/2, (-V::unitY()).angle());

	EXPECT_EQ(sqrt(T{68}), a.distance(b));
	EXPECT_EQ(sqrt(T{68}), b.distance(a));

	EXPECT_EQ(V(static_cast<T>( 4./ 5), static_cast<T>(3./ 5)), a.normalized());
	EXPECT_EQ(V(static_cast<T>(12./13), static_cast<T>(5./13)), b.normalized());
	
	EXPECT_NEAR( V::unitX().x, V::unitX().rotated(        0).x, 1e-6);
	EXPECT_NEAR( V::unitX().y, V::unitX().rotated(        0).y, 1e-6);
	EXPECT_NEAR( V::unitY().x, V::unitX().rotated(pi<T>()/2).x, 1e-6);
	EXPECT_NEAR( V::unitY().y, V::unitX().rotated(pi<T>()/2).y, 1e-6);
	EXPECT_NEAR(-V::unitX().x, V::unitX().rotated(pi<T>()  ).x, 1e-6);
	EXPECT_NEAR(-V::unitX().y, V::unitX().rotated(pi<T>()  ).y, 1e-6);
}
Example #6
0
    ~SmartPointerListElement()
    {
        value.reset();

        prev = nullptr;
        next = nullptr;
    }
 J u()
 {
   for (int x = 0; x < e.s(); ++x)
     if (e[x])
       return J(e[x], this);
   return v();
 }
Example #8
0
/* cmd, com */
void quitdeco(void) {
	VMove (LINES-1, 0);
	VClearLine ();
	VSync ();
	v.VClose ();
	exit (0);
}
int kruskal() {
	int a, b, sum = 0;
	sort(v.begin(), v.end());
	for (int i = 0; i <= N; i++)
		mf[i] = i; // inicializar conjuntos conexos

	for (int i = 0; i < (int)v.SZ; i++) {
		a = set(v[i].Y.X), b = set(v[i].Y.Y);
		if (a != b) { // si conjuntos son diferentes
			mf[b] = a;  // unificar los conjuntos
			sum += v[i].X; // agregar coste de arista
			K[v[i].Y.X].PB(MP(v[i].X, v[i].Y.Y));
			K[v[i].Y.Y].PB(MP(v[i].X, v[i].Y.X));
		}
	}
	return sum;
}
 S(const V<int>& arr) : arr(arr) {
     auto& a = this->arr; 
     N = a.size();
     reverse(a.begin(), a.end());
     a.push_back(0);
     reverse(a.begin(), a.end());
     
     t.resize(N+1, V<V<int>>(N+1, V<int>(N+1, -1)));        
 }
Example #11
0
void test_default_ctor_basic() {
  {
    std::variant<int> v;
    assert(v.index() == 0);
    assert(std::get<0>(v) == 0);
  }
  {
    std::variant<int, long> v;
    assert(v.index() == 0);
    assert(std::get<0>(v) == 0);
  }
  {
    using V = std::variant<int, long>;
    constexpr V v;
    static_assert(v.index() == 0, "");
    static_assert(std::get<0>(v) == 0, "");
  }
  {
    using V = std::variant<int, long>;
    constexpr V v;
    static_assert(v.index() == 0, "");
    static_assert(std::get<0>(v) == 0, "");
  }
}
Example #12
0
int main(){
	int T,a,b,r;
	for(scanf("%d",&T);T--;){
		scanf("%d%d%d",&a,&b,&r);r--;
		V x(n*n);
		V e(n*n);
		z.resize(n*n);

		x[0]=x[1]=x[2]=1;
		e[0]=1,e[3]=1;

		for(;r;r>>=1){
			if(r&1)e=Me(e,x);
			x=Mx(x);
		}
		printf("%lld\n",(e[0]*b+e[1]*a)%m);
	}
}
Example #13
0
main(){
	int t=1,T,r;
	for(;~scanf("%d",&r);){
		int f=1-r%2;
		V x(n*n);
		V e(n*n);
		z.resize(n*n);

		x[0]=1,x[1]=3,x[2]=1,x[3]=1;
		e[0]=1,e[3]=1; //unit

		for(;r;r>>=1){
			if(r&1)e=Me(e,x);
			x=Mx(x);
		}
		printf("%d\n",(int)(2*e[0]-f)%1000);
	}
}
Example #14
0
int main(){
	int T;
	long long t,t0;
	//for(scanf("%d",&T);T--;){
		cin>>t;
		V x(n*n);
		V e(n*n);
		z.resize(n*n);

		x[0]=x[3]=3;
		x[1]=x[2]=1;
		e[0]=e[3]=1;
		for(;t;t>>=1){
			if(t&1)e=Me(e,x);
			x=Mx(x);
		}
		cout<<e[0]<<endl;
	//}
}
Example #15
0
int main() {
    F x;
    foo( &x );
    _PASS;
}
Example #16
0
File: utils.cpp Project: VcDevel/Vc
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

}}}*/

#include "unittest.h"

using namespace Vc;

// reversed{{{1
TEST_TYPES(V, reversed, (ALL_VECTORS, SIMD_ARRAYS(2), SIMD_ARRAYS(3), SIMD_ARRAYS(15)))
{
    const V x = V::IndexesFromZero() + 1;
    const V reference = V::generate([](int i) { return V::Size - i; });
    COMPARE(x.reversed(), reference);
}

// testCall{{{1
template<typename T, typename Mem> struct Foo
{
    Foo() : i(0) {}
    void reset() { i = 0; }
    void operator()(T v) { d[i++] = v; }
    Mem d;
    int i;
};

TEST_TYPES(V, testCall, (ALL_VECTORS))
int main()
{
	long T = 0; // test cases

	cin >> T;

	for (long i = 1; i <= T; ++i)
	{
		cout << "Case " << i << endl;

		v.clear();

		long R; // number of roads
		cin >> N >> R;

		for (int j = 1; j <= N; ++j)
		{
			K[j].clear();
			vis[j] = false;
		}
		
		int a, b;
		long l;

		for (long j = 0; j < R; ++j)
		{
			cin >> a >> b >> l;
			v.PB(MP(l, MP(a, b)));
		}

		kruskal();

		/*
		for (int j = 1; j <= N; ++j)
		{
			for (int k = 0; k < K[j].size(); ++k)
			{
				cout << j << ", " << K[j][k].Y << " --> " << K[j][k].X << endl;
			}
		}
		*/

		int Q; // number of queries
		cin >> Q;

		for (int j = 0; j < Q; ++j)
		{
			cin >> a >> b;

			long maxDist = -1;
			func(a, b, maxDist);

			cout << maxDist << endl;

			for (int k = 1; k <= N; ++k) vis[k] = false;
		}

		cout << endl;
	}

	return 0;
}
Example #18
0
 */


#include "prio_queue.hpp"
#include <queue>

#define CATCH_CONFIG_MAIN
#include <catch.hpp>

using A = rollbear::prio_q_internal::heap_heap_addressing<8>;
using V = rollbear::prio_q_internal::skip_vector<int, 4>;
using rollbear::prio_queue;

TEST_CASE("a default constructed vector is empty", "[vector]")
{
  V v;
  REQUIRE(v.size() == 0);
  REQUIRE(v.empty());
}

TEST_CASE("a has size 2 after one push_key", "[vector]")
{
  V v;
  auto i = v.push_back(1);
  REQUIRE(!v.empty());
  REQUIRE(v.size() == 2);
  REQUIRE(i == 1);
}

TEST_CASE("a vector of size 2 becomes empty on pop", "[vector]")
{
Example #19
0
    /// @brief Computes injected and produced volumes of all phases,
    ///        and injected and produced polymer mass - in the compressible case.
    /// Note 1: assumes that only the first phase is injected.
    /// Note 2: assumes that transport has been done with an
    ///         implicit method, i.e. that the current state
    ///         gives the mobilities used for the preceding timestep.
    /// @param[in]  props     fluid and rock properties.
    /// @param[in]  polyprops polymer properties
    /// @param[in]  state     state variables (pressure, fluxes etc.)
    /// @param[in]  transport_src  if < 0: total reservoir volume outflow,
    ///                       if > 0: first phase *surface volume* inflow.
    /// @param[in]  inj_c     injected concentration by cell
    /// @param[in]  dt        timestep used
    /// @param[out] injected  must point to a valid array with P elements,
    ///                       where P = s.size()/transport_src.size().
    /// @param[out] produced  must also point to a valid array with P elements.
    /// @param[out] polyinj   injected mass of polymer
    /// @param[out] polyprod  produced mass of polymer
    void computeInjectedProduced(const BlackoilPropsAdInterface& props,
                                 const Opm::PolymerPropsAd& polymer_props,
                                 const PolymerBlackoilState& state,
                                 const std::vector<double>& transport_src,
                                 const std::vector<double>& inj_c,
                                 const double dt,
                                 double* injected,
                                 double* produced,
                                 double& polyinj,
                                 double& polyprod)
    {
        const int num_cells = transport_src.size();
        if (props.numCells() != num_cells) {
            OPM_THROW(std::runtime_error, "Size of transport_src vector does not match number of cells in props.");
        }
        const int np = props.numPhases();
        if (int(state.saturation().size()) != num_cells*np) {
            OPM_THROW(std::runtime_error, "Sizes of state vectors do not match number of cells.");
        }
		std::vector<int> cells(num_cells);
		const V p = Eigen::Map<const V>(&state.pressure()[0], num_cells, 1);
        const DataBlock s = Eigen::Map<const DataBlock>(&state.saturation()[0], num_cells, np);
		const V sw = s.col(0);
		const V so = s.col(1);
		const V c = Eigen::Map<const V>(&state.concentration()[0], num_cells, 1);
		const V cmax = Eigen::Map<const V>(&state.maxconcentration()[0], num_cells, 1);
		const V trans_src = Eigen::Map<const V>(&transport_src[0], num_cells, 1);
		V src = V::Constant(num_cells, -1.0); // negative is injec, positive is producer.
		for (int cell = 0; cell < num_cells; ++cell) {
			cells[cell] = cell;
			if(transport_src[cell] > 0.0) {
				src[cell] = 1.0;
			}
		}
        //Add PhasePresence make muOil() happy.
        std::vector<PhasePresence> phaseCondition(num_cells);
        for (int c = 0; c < num_cells; ++c) {
            phaseCondition[c] = PhasePresence();
            phaseCondition[c].setFreeWater();
            phaseCondition[c].setFreeOil();
        }
		const Selector<double> src_selector(src);
		const V one = V::Constant(num_cells, 1.0);
		const V zero = V::Zero(num_cells);
		const std::vector<V> kr = props.relperm(sw, so, zero, cells);
		const V muw = props.muWat(p, cells);
		const V muo = props.muOil(p, zero, phaseCondition, cells);
        const V krw_eff = polymer_props.effectiveRelPerm(c, cmax, kr[0]);
		const V inv_muw_eff = polymer_props.effectiveInvWaterVisc(c, muw.data());
		std::vector<V> mob(np);
		mob[0] = krw_eff * inv_muw_eff;
		mob[1] = kr[1] / muo;
		
		const V watmob_c = src_selector.select(mob[0], one);
		const V oilmob_c = src_selector.select(mob[1], zero);
		const V flux = trans_src * dt;
	    const V totmob_c = watmob_c + oilmob_c;
		const V wat_src = flux * (watmob_c / totmob_c);
		const V oil_src = flux * (oilmob_c / totmob_c);
		const V mc = polymer_props.polymerWaterVelocityRatio(c);
		
        polyinj = 0.0;
        polyprod = 0.0;
		std::fill(injected, injected + np , 0.0);
		std::fill(produced, produced + np , 0.0);
		for (int cell = 0; cell < num_cells; ++cell) {
			if (wat_src[cell] < 0) {
				injected[0] += wat_src[cell];
				polyinj += injected[0] * inj_c[cell];
			} else {
				produced[0] += wat_src[cell];
				produced[1] += oil_src[cell];
				polyprod += produced[0] * mc[cell];
			}
		}
    }
Example #20
0
main (int argc, char **argv, char **envp) {
	register c;

	if (argc > 2) {
		outerr("Usage: deco [dirname]\n",0);
		exit (1);
	}
	outerr("Demos Commander, Copyright (C) 1989-1994 Serge Vakulenko\n",0);
	palette = dflt_palette;
	EnvInit (envp);
	uid = getuid ();
	gid = getgid ();
# ifdef GROUPS
	gidnum = getgroups (sizeof(gidlist)/sizeof(gidlist[0]), (unsigned int *)gidlist);
# endif
	ppid = getppid ();
	user = username (uid);
	group = groupname (gid);
	tty = ttyname (0);
	machine = getmachine ();
#if 0
	sigign();
#else
	signal(SIGTERM, SIG_IGN);
	signal(SIGQUIT, SIG_IGN);
	signal(SIGINT, SIG_IGN);
# ifdef SIGTSTP
	signal(SIGTSTP, SIG_IGN);
# endif
#endif
	init ();
//	inithome ();
	VClear ();
/* init class dir */
	if (argc > 1)
//		chdir (argv [1]);
		left = new dir(argv [1]);
	else
		left = new dir;
	right = new dir;
	left->d.basecol = 0;
	right->d.basecol = 40;
/*-----------*/
	initfile.read();
	if (uid == 0)
		palette.dimfg = 6;
	v.VSetPalette (palette.fg, palette.bg, palette.revfg, palette.revbg,
		palette.boldfg, palette.boldbg, palette.boldrevfg, palette.boldrevbg,
		palette.dimfg, palette.dimbg, palette.dimrevfg, palette.dimrevbg);
	setdir (left, ".");
	setdir (right, ".");
	left->chdir(left->d.cwd);
	cur = left;
	draw.draw(cur, left, right);
	for (;;) {
		if (! cmdreg)
			draw.drawcursor(cur);
//		cmd.drawcmd(cur, &left, &right);
		VSync ();
		c = KeyGet ();
		if (! cmdreg)
			draw.undrawcursor(cur);
		switch (c) {
		case '+':               /* select */
		case '-':               /* unselect */
			if (! cpos && ! cmdreg && ! cur->d.status) {
				if (c == '+')
					tagall ();
				else
					untagall ();
				draw.draw(cur, left, right);
				continue;
			}
		default:
//			if (c>=' ' && c<='~' || c>=0300 && c<=0376) {
//				if (cpos || c!=' ')
//					cmd.inscmd(c);
//				continue;
//			}
			VBeep ();
			continue;
//		case cntrl ('V'):       /* quote next char */
//			cmd.inscmd(quote ());
//			continue;
//		case cntrl ('J'):       /* insert file name */
//			if (! cmdreg && ! cur->status)
//				cmd.namecmd(cur);
//			continue;
//		case cntrl ('G'):
//			cmd.delcmd();
//			continue;
//		case meta ('b'):        /* backspace */
//			if (cpos) {
//				cmd.leftcmd();
//				cmd.delcmd();
//			}
//			continue;
		case cntrl ('O'):       /* set/unset command mode */
		case cntrl ('P'):       /* set/unset command mode */
			switchcmdreg ();
			if (! cmdreg)
				visualwin = 1;
			draw.draw(cur, left, right);
			continue;
		case cntrl ('M'):         /* return */
//			if (command [0]) {
//				cmd.exec(cur, &left, &right, 1, 1);
//				draw.draw(cur, &left, &right);
//				continue;
//			}
			if (cmdreg) {
				cmdreg = 0;
				if (! visualwin) {
					visualwin = 1;
					setdir (cur==left ? right : left, NULL);
					setdir (cur, NULL);
				}
				draw.draw(cur, left, right);
				continue;
			}
			execute ();
			continue;
		case cntrl (']'):       /* redraw screen */
			VRedraw ();
			continue;
//		case cntrl ('B'):        /* history */
//			if (! visualwin)
//				VClearBox (1, 0, LINES-2, 80);
//			cmd.histmenu(cur, &left, &right);
//			draw.draw(cur, &left, &right);
//			continue;
		case meta ('A'):        /* f1 */
			genhelp ();
			draw.draw(cur, left, right);
			continue;
		case meta ('B'):          /* f2 */
			udm.menu();
			draw.draw(cur, left, right);
			continue;
		case meta ('I'):        /* f9 */
			mymenu.runmenu (cur==left ? 'l' : 'r');
			draw.draw(cur, left, right);
			continue;
		case meta ('J'):        /* f0 */
		case cntrl ('C'):       /* quit */
			quit ();
			continue;
		case cntrl ('U'):       /* swap panels */
			swappanels ();
			draw.draw(cur, left, right);
			continue;
		case cntrl ('F'):       /* full screen */
			fullscreen ();
			draw.draw(cur, left, right);
			continue;
		case cntrl ('^'):       /* cd / */
			directory (0, 'r');
			if (! cur->d.status)
				draw.drawdir(cur, 1, left, right);
			continue;
		case cntrl ('\\'):      /* cd $HOME */
			directory (0, 'o');
			if (! cur->d.status)
				draw.drawdir(cur, 1, left, right);
			continue;
//		case cntrl ('Y'):       /* clear line */
//			command [cpos = 0] = 0;
//			continue;
//		case cntrl ('X'):       /* next history */
//			cmd.nextcmd();
//			continue;
//		case cntrl ('E'):       /* prev history */
//			cmd.prevcmd();
//			continue;
//		case cntrl ('S'):       /* char left */
//		case cntrl ('A'):       /* char left */
//			cmd.leftcmd();
//			continue;
//		case cntrl ('D'):       /* char right */
//			cmd.rightcmd();
//			continue;
		case cntrl ('I'):       /* tab */
			if (cmdreg) {}
//				if (command [cpos])
//					cmd.endcmd();
//				else
//					cmd.homecmd();
			else {
				switchpanels ();
				if (fullwin) {
					draw.drawbanners();
					draw.drawdir(cur, 0, left, right);
					break;
				}
			}
			continue;
		case cntrl ('W'):       /* double width */
			if (! cmdreg) {
				setdwid ();
				draw.draw(cur, left, right);
			}
			continue;
//		case meta ('G'):        /* f7 */
//			makedir ();
//			draw.draw(cur, &left, &right);
//			continue;
		case meta ('h'):        /* home */
		case meta ('e'):        /* end */
		case meta ('u'):        /* up */
		case meta ('d'):        /* down */
		case meta ('l'):        /* left */
		case meta ('r'):        /* right */
		case meta ('n'):        /* next page */
		case meta ('p'):        /* prev page */
		case cntrl ('K'):       /* find file */
		case cntrl ('R'):       /* reread catalog */
		case cntrl ('T'):       /* tag file */
		case meta ('C'):        /* f3 */
		case meta ('D'):        /* f4 */
		case meta ('E'):        /* f5 */
		case meta ('F'):        /* f6 */
		case meta ('H'):        /* f8 */
		case cntrl ('L'):       /* status */
			if (cmdreg || cur->d.status) {}
//				docmdreg (c);
			else
				doscrreg (c);
			continue;
		}
	}
}
Example #21
0
 void rebind( V const & v) { _v.rebind(v);}
Example #22
0
void
foo ()
{
  v.m2 (0);
}
Example #23
0
}}}*/

#include "unittest.h"
#include "../common/simdarray.h"

using namespace Vc;

template <typename T, size_t N> constexpr size_t captureN(const SimdArray<T, N> &)
{
    return N;
}

TEST_TYPES(V, createArray, (SIMD_ARRAY_LIST))
{
    typedef typename V::VectorEntryType VT;
    V array;

    COMPARE(array.size(), captureN(V()));
    VERIFY(sizeof(array) >= array.size() * sizeof(VT));
    VERIFY(sizeof(array) <= 2 * array.size() * sizeof(VT));
}

template <typename T, typename U> constexpr T bound(T x, U max)
{
    return x > max ? max : x;
}

TEST_TYPES(V, checkArrayAlignment, (SIMD_ARRAY_LIST))
{
    using T = typename V::value_type;
    using M = typename V::mask_type;
Example #24
0
int main()
try
{
    typedef Opm::AutoDiffBlock<double> ADB;
    typedef ADB::V V;
    typedef Eigen::SparseMatrix<double> S;

    Opm::time::StopWatch clock;
    clock.start();
    const Opm::GridManager gm(3,3);//(50, 50, 10);
    const UnstructuredGrid& grid = *gm.c_grid();
    using namespace Opm::unit;
    using namespace Opm::prefix;
    // const Opm::IncompPropertiesBasic props(2, Opm::SaturationPropsBasic::Linear,
    //                                        { 1000.0, 800.0 },
    //                                        { 1.0*centi*Poise, 5.0*centi*Poise },
    //                                        0.2, 100*milli*darcy,
    //                                        grid.dimensions, grid.number_of_cells);
    // const Opm::IncompPropertiesBasic props(2, Opm::SaturationPropsBasic::Linear,
    //                                        { 1000.0, 1000.0 },
    //                                        { 1.0, 1.0 },
    //                                        1.0, 1.0,
    //                                        grid.dimensions, grid.number_of_cells);
    const Opm::IncompPropertiesBasic props(2, Opm::SaturationPropsBasic::Linear,
                                           { 1000.0, 1000.0 },
                                           { 1.0, 30.0 },
                                           1.0, 1.0,
                                           grid.dimensions, grid.number_of_cells);
    V htrans(grid.cell_facepos[grid.number_of_cells]);
    tpfa_htrans_compute(const_cast<UnstructuredGrid*>(&grid), props.permeability(), htrans.data());
    V trans_all(grid.number_of_faces);
    // tpfa_trans_compute(const_cast<UnstructuredGrid*>(&grid), htrans.data(), trans_all.data());
    const int nc = grid.number_of_cells;
    std::vector<int> allcells(nc);
    for (int i = 0; i < nc; ++i) {
        allcells[i] = i;
    }
    std::cerr << "Opm core " << clock.secsSinceLast() << std::endl;

    // Define neighbourhood-derived operator matrices.
    const Opm::HelperOps ops(grid);
    const int num_internal = ops.internal_faces.size();
    std::cerr << "Topology matrices " << clock.secsSinceLast() << std::endl;

    typedef Opm::AutoDiffBlock<double> ADB;
    typedef ADB::V V;

    // q
    V q(nc);
    q.setZero();
    q[0] = 1.0;
    q[nc-1] = -1.0;

    // s0 - this is explicit now
    typedef Eigen::Array<double, Eigen::Dynamic, 2, Eigen::RowMajor> TwoCol;
    TwoCol s0(nc, 2);
    s0.leftCols<1>().setZero();
    s0.rightCols<1>().setOnes();

    // totmob - explicit as well
    TwoCol kr(nc, 2);
    props.relperm(nc, s0.data(), allcells.data(), kr.data(), 0);
    const V krw = kr.leftCols<1>();
    const V kro = kr.rightCols<1>();
    const double* mu = props.viscosity();
    const V totmob = krw/mu[0] + kro/mu[1];

    // Moved down here because we need total mobility.
    tpfa_eff_trans_compute(const_cast<UnstructuredGrid*>(&grid), totmob.data(),
                           htrans.data(), trans_all.data());
    // Still explicit, and no upwinding!
    V mobtransf(num_internal);
    for (int fi = 0; fi < num_internal; ++fi) {
        mobtransf[fi] = trans_all[ops.internal_faces[fi]];
    }
    std::cerr << "Property arrays " << clock.secsSinceLast() << std::endl;

    // Initial pressure.
    V p0(nc,1);
    p0.fill(200*Opm::unit::barsa);

    // First actual AD usage: defining pressure variable.
    const std::vector<int> bpat = { nc };
    // Could actually write { nc } instead of bpat below,
    // but we prefer a named variable since we will repeat it.
    const ADB p = ADB::variable(0, p0, bpat);
    const ADB ngradp = ops.ngrad*p;
    // We want flux = totmob*trans*(p_i - p_j) for the ij-face.
    const ADB flux = mobtransf*ngradp;
    const ADB residual = ops.div*flux - q;
    std::cerr << "Construct AD residual " << clock.secsSinceLast() << std::endl;

    // It's the residual we want to be zero. We know it's linear in p,
    // so we just need a single linear solve. Since we have formulated
    // ourselves with a residual and jacobian we do this with a single
    // Newton step (hopefully easy to extend later):
    //   p = p0 - J(p0) \ R(p0)
    // Where R(p0) and J(p0) are contained in residual.value() and
    // residual.derived()[0].

#if HAVE_SUITESPARSE_UMFPACK_H
    typedef Eigen::UmfPackLU<S> LinSolver;
#else
    typedef Eigen::BiCGSTAB<S>  LinSolver;
#endif  // HAVE_SUITESPARSE_UMFPACK_H

    LinSolver solver;
    S pmatr;
    residual.derivative()[0].toSparse(pmatr);
    pmatr.coeffRef(0,0) *= 2.0;
    pmatr.makeCompressed();
    solver.compute(pmatr);
    if (solver.info() != Eigen::Success) {
        std::cerr << "Pressure/flow Jacobian decomposition error\n";
        return EXIT_FAILURE;
    }
    // const Eigen::VectorXd dp = solver.solve(residual.value().matrix());
    ADB::V residual_v = residual.value();
    const V dp = solver.solve(residual_v.matrix()).array();
    if (solver.info() != Eigen::Success) {
        std::cerr << "Pressure/flow solve failure\n";
        return EXIT_FAILURE;
    }
    const V p1 = p0 - dp;
    std::cerr << "Solve " << clock.secsSinceLast() << std::endl;
    // std::cout << p1 << std::endl;

    // ------ Transport solve ------

    // Now we'll try to do a transport step as well.
    // Residual formula is
    //   R_w = s_w - s_w^0 + dt/pv * (div v_w)
    // where
    //   v_w = f_w v
    // and f_w is (for now) based on averaged mobilities, not upwind.

    double res_norm = 1e100;
    const V sw0 = s0.leftCols<1>();
    // V sw1 = sw0;
    V sw1 = 0.5*V::Ones(nc,1);
    const V ndp = (ops.ngrad * p1.matrix()).array();
    const V dflux = mobtransf * ndp;
    const Opm::UpwindSelector<double> upwind(grid, ops, dflux);
    const V pv = Eigen::Map<const V>(props.porosity(), nc, 1)
        * Eigen::Map<const V>(grid.cell_volumes, nc, 1);
    const double dt = 0.0005;
    const V dtpv = dt/pv;
    const V qneg = q.min(V::Zero(nc,1));
    const V qpos = q.max(V::Zero(nc,1));

    std::cout.setf(std::ios::scientific);
    std::cout.precision(16);

    int it = 0;
    do {
        const ADB sw = ADB::variable(0, sw1, bpat);
        const std::vector<ADB> pmobc = phaseMobility<ADB>(props, allcells, sw.value());
        const std::vector<ADB> pmobf = upwind.select(pmobc);
        const ADB fw_cell = fluxFunc(pmobc);
        const ADB fw_face = fluxFunc(pmobf);
        const ADB flux1 = fw_face * dflux;
        const ADB qtr_ad = qpos + fw_cell*qneg;
        const ADB transport_residual = sw - sw0 + dtpv*(ops.div*flux1 - qtr_ad);
        res_norm = transport_residual.value().matrix().norm();
        std::cout << "res_norm[" << it << "] = "
                  << res_norm << std::endl;

        S smatr;
        transport_residual.derivative()[0].toSparse(smatr);
        smatr.makeCompressed();
        solver.compute(smatr);
        if (solver.info() != Eigen::Success) {
            std::cerr << "Transport Jacobian decomposition error\n";
            return EXIT_FAILURE;
        }
        ADB::V transport_residual_v = transport_residual.value();
        const V ds = solver.solve(transport_residual_v.matrix()).array();
        if (solver.info() != Eigen::Success) {
            std::cerr << "Transport solve failure\n";
            return EXIT_FAILURE;
        }
        sw1 = sw.value() - ds;
        std::cerr << "Solve for s[" << it << "]: "
                  << clock.secsSinceLast() << '\n';
        sw1 = sw1.min(V::Ones(nc,1)).max(V::Zero(nc,1));

        it += 1;
    } while (res_norm > 1e-7);

    std::cout << "Saturation solution:\n"
              << "function s1 = solution\n"
              << "s1 = [\n" << sw1 << "\n];\n";
}
catch (const std::exception &e) {
    std::cerr << "Program threw an exception: " << e.what() << "\n";
    throw;
}
Example #25
0
void h() {
  using namespace U; // Using directive
  using V::f; // Using declaration
  f(); // Calls V::f();
  U::f(); // Must fully qualify to call
}