Exemple #1
0
func Test_nurbs02(tst *testing.T) {

	//verbose()
	chk.PrintTitle("nurbs02. square with initial stress. run")

	// fem
	analysis := NewFEM("data/nurbs02.sim", "", true, false, false, false, chk.Verbose, 0)

	// run simulation
	err := analysis.Run()
	if err != nil {
		tst.Errorf("Run failed\n%v", err)
		return
	}

	// domain
	dom := analysis.Domains[0]

	e := dom.Elems[0].(*ElemU)
	io.PfYel("fex = %v\n", e.fex)
	io.PfYel("fey = %v\n", e.fey)
	la.PrintMat("K", e.K, "%10.2f", false)

	// solution
	var sol ana.CteStressPstrain
	sol.Init(fun.Prms{
		&fun.Prm{N: "qnH0", V: -20},
		&fun.Prm{N: "qnV0", V: -20},
		&fun.Prm{N: "qnH", V: -50},
		&fun.Prm{N: "qnV", V: -100},
	})

	// check displacements
	t := dom.Sol.T
	tolu := 1e-16
	for _, n := range dom.Nodes {
		eqx := n.GetEq("ux")
		eqy := n.GetEq("uy")
		u := []float64{dom.Sol.Y[eqx], dom.Sol.Y[eqy]}
		io.Pfyel("u = %v\n", u)
		sol.CheckDispl(tst, t, u, n.Vert.C, tolu)
	}

	// check stresses
	tols := 1e-13
	for idx, ip := range e.IpsElem {
		x := e.Cell.Shp.IpRealCoords(e.X, ip)
		σ := e.States[idx].Sig
		io.Pforan("σ = %v\n", σ)
		sol.CheckStress(tst, t, σ, x, tols)
	}
}
Exemple #2
0
func main() {

	mpi.Start(false)
	defer func() {
		mpi.Stop(false)
	}()

	if mpi.Rank() == 0 {
		io.PfYel("\nTest MPI 03\n")
	}
	if mpi.Size() != 3 {
		chk.Panic("this test needs 3 processors")
	}
	x := []int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
	n := len(x)
	id, sz := mpi.Rank(), mpi.Size()
	start, endp1 := (id*n)/sz, ((id+1)*n)/sz
	for i := start; i < endp1; i++ {
		x[i] = i
	}

	//io.Pforan("x = %v\n", x)

	// IntAllReduceMax
	w := make([]int, n)
	mpi.IntAllReduceMax(x, w)
	var tst testing.T
	chk.Ints(&tst, fmt.Sprintf("IntAllReduceMax: x @ proc # %d", id), x, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

	//io.Pfred("x = %v\n", x)
}
Exemple #3
0
// CheckFront0 returns front0 and number of failed/success
func CheckFront0(opt *Optimiser, verbose bool) (nfailed int, front0 []*Solution) {
	front0 = make([]*Solution, 0)
	var nsuccess int
	for _, sol := range opt.Solutions {
		var failed bool
		for _, oor := range sol.Oor {
			if oor > 0 {
				failed = true
				break
			}
		}
		if failed {
			nfailed++
		} else {
			nsuccess++
			if sol.FrontId == 0 {
				front0 = append(front0, sol)
			}
		}
	}
	if verbose {
		if nfailed > 0 {
			io.PfRed("N failed = %d out of %d\n", nfailed, opt.Nsol)
		} else {
			io.PfGreen("N success = %d out of %d\n", nsuccess, opt.Nsol)
		}
		io.PfYel("N front 0 = %d\n", len(front0))
	}
	return
}
Exemple #4
0
// skip skips test based on it and/or t
func (o testKb) skip() bool {
	if o.itmin >= 0 {
		if o.it < o.itmin {
			return true // skip
		}
	}
	if o.itmax >= 0 {
		if o.it > o.itmax {
			return true // skip
		}
	}
	if o.tmin >= 0 {
		if o.t < o.tmin {
			return true // skip
		}
	}
	if o.tmax >= 0 {
		if o.t > o.tmax {
			return true // skip
		}
	}
	if o.verb {
		io.PfYel("\nit=%2d t=%v\n", o.it, o.t)
	}
	return false
}
Exemple #5
0
func Test_nurbs03(tst *testing.T) {

	//verbose()
	chk.PrintTitle("nurbs03. ini stress free square")

	// fem
	analysis := NewFEM("data/nurbs03.sim", "", true, false, false, false, chk.Verbose, 0)

	// run simulation
	err := analysis.Run()
	if err != nil {
		tst.Errorf("Run failed\n%v", err)
		return
	}

	// domain
	dom := analysis.Domains[0]

	// element
	e := dom.Elems[0].(*ElemU)
	io.PfYel("fex = %v\n", e.fex)
	io.PfYel("fey = %v\n", e.fey)
	la.PrintMat("K", e.K, "%10.2f", false)

	// solution
	var sol ana.CteStressPstrain
	sol.Init(fun.Prms{
		&fun.Prm{N: "qnH", V: -50},
		&fun.Prm{N: "qnV", V: -100},
	})

	// check displacements
	t := dom.Sol.T
	tolu := 1e-16
	for _, n := range dom.Nodes {
		eqx := n.GetEq("ux")
		eqy := n.GetEq("uy")
		u := []float64{dom.Sol.Y[eqx], dom.Sol.Y[eqy]}
		io.Pfyel("u = %v\n", u)
		sol.CheckDispl(tst, t, u, n.Vert.C, tolu)
	}
}
Exemple #6
0
// PrintMemStat prints memory statistics
func PrintMemStat(msg string) {
	var mem runtime.MemStats
	runtime.ReadMemStats(&mem)
	io.PfYel("%s\n", msg)
	io.Pfyel("Alloc      = %v [KB]  %v [MB]  %v [GB]\n", mem.Alloc/KBSIZE, mem.Alloc/MBSIZE, mem.Alloc/GBSIZE)
	io.Pfyel("HeapAlloc  = %v [KB]  %v [MB]  %v [GB]\n", mem.HeapAlloc/KBSIZE, mem.HeapAlloc/MBSIZE, mem.HeapAlloc/GBSIZE)
	io.Pfyel("Sys        = %v [KB]  %v [MB]  %v [GB]\n", mem.Sys/KBSIZE, mem.Sys/MBSIZE, mem.Sys/GBSIZE)
	io.Pfyel("HeapSys    = %v [KB]  %v [MB]  %v [GB]\n", mem.HeapSys/KBSIZE, mem.HeapSys/MBSIZE, mem.HeapSys/GBSIZE)
	io.Pfyel("TotalAlloc = %v [KB]  %v [MB]  %v [GB]\n", mem.TotalAlloc/KBSIZE, mem.TotalAlloc/MBSIZE, mem.TotalAlloc/GBSIZE)
	io.Pfyel("Mallocs    = %v\n", mem.Mallocs)
	io.Pfyel("Frees      = %v\n", mem.Frees)
}
Exemple #7
0
func main() {

	// finalise analysis process and catch errors
	defer out.End()

	// input data
	simfn := "d2-simple-flux"
	flag.Parse()
	if len(flag.Args()) > 0 {
		simfn = flag.Arg(0)
	}
	if io.FnExt(simfn) == "" {
		simfn += ".sim"
	}

	// start analysis process
	out.Extrap = []string{"nwlx", "nwly"}
	out.Start(simfn, 0, 0)

	// define entities
	out.Define("top-middle", out.At{5, 3})
	out.Define("section-A", out.N{-1})
	out.Define("section-B", out.Along{{0, 0}, {10, 0}})

	// load results
	out.LoadResults(nil)

	// compute water discharge along section-A
	nwlx_TM := out.GetRes("ex_nwlx", "top-middle", -1)
	Q := out.Integrate("ex_nwlx", "section-A", "y", -1)
	io.PfYel("Q = %g m³/s [answer: 0.0003]\n", Q)

	// plot
	kt := len(out.Times) - 1
	out.Splot("")
	out.Plot("pl", "y", "section-A", plt.Fmt{L: "t=0"}, 0)
	out.Plot("pl", "y", "section-A", plt.Fmt{L: io.Sf("t=%g", out.Times[kt])}, kt)
	out.Splot("")
	out.Plot("x", "pl", "section-B", plt.Fmt{L: "t=0"}, 0)
	out.Plot("x", "pl", "section-B", plt.Fmt{L: io.Sf("t=%g", out.Times[kt])}, kt)
	out.Splot("")
	out.Plot("t", nwlx_TM, "top-middle", plt.Fmt{}, -1)
	out.Csplot.Ylbl = "$n_{\\ell}\\cdot w_{\\ell x}$"

	// show
	if true {
		out.Draw("", "", true, func(i, j, nplots int) {
			if i == 2 && j == 1 {
				plt.Plot([]float64{0, 10}, []float64{10, 9}, "'k--'")
			}
		})
	}
}
Exemple #8
0
func (o *PrincStrainsUp) dbg_plot(eid, ipid int, time float64) {
	if eid == o.DbgEid && ipid == o.DbgIpId {

		// skip if not selected time
		if o.DbgTime > -1 {
			if math.Abs(time-o.DbgTime) > 1e-7 {
				return
			}
		}

		// check Jacobian
		var cnd float64
		io.PfYel("\nchecking Jacobian: eid=%d ipid=%d\n", eid, ipid)
		cnd, err := o.nls.CheckJ(o.x, o.ChkJacTol, true, o.ChkSilent)
		if err != nil {
			io.PfRed("CheckJ failed:\n%v\n", err)
		}
		io.PfYel("after: cnd(J) = %v\n\n", cnd)
		io.Pfcyan("\nN  = %v\n", o.N)
		io.Pfcyan("Nb = %v\n", o.Nb)
		io.Pfcyan("A  = %v\n", o.A)
		io.Pfcyan("h  = %v\n", o.h)
		io.Pfcyan("Mb = %v\n", o.Mb)
		io.Pfcyan("a  = %v\n", o.a)
		io.Pfcyan("b  = %v\n", o.b)
		io.Pfcyan("c  = %v\n", o.c)
		io.Pfcyan("Lσ = %v\n", o.Lσ)
		io.Pforan("Ne = %v\n", o.Ne)
		io.Pforan("Mbe = %v\n", o.Mbe)
		io.Pforan("Fcoef = %v\n\n", o.Fcoef)

		// plot
		var plr Plotter
		plr.SetFig(false, false, 1.5, 400, "/tmp", io.Sf("fig_stress_eid%d_ipid%d", eid, ipid))
		plr.SetModel(o.Mdl)
		plr.PreCor = o.DbgPco
		plr.Plot([]string{"p,q,ys", "oct,ys"}, o.DbgRes, o.DbgSts, true, true)
	}
}
Exemple #9
0
// Stat prints statistical analysis
func (o *SimpleFltProb) Stat(idxF, hlen int, Fref float64) {
	if o.C.Ntrials < 2 || o.Nfeasible < 2 {
		return
	}
	F := make([]float64, o.Nfeasible)
	for i := 0; i < o.Nfeasible; i++ {
		o.Fcn(o.ff[0], o.gg[0], o.hh[0], o.Xbest[i])
		F[i] = o.ff[0][idxF]
	}
	fmin, fave, fmax, fdev := rnd.StatBasic(F, true)
	io.Pf("fmin = %v\n", fmin)
	io.PfYel("fave = %v (%v)\n", fave, Fref)
	io.Pf("fmax = %v\n", fmax)
	io.Pf("fdev = %v\n\n", fdev)
	io.Pf(rnd.BuildTextHist(nice_num(fmin-0.05), nice_num(fmax+0.05), 11, F, "%.2f", hlen))
}
Exemple #10
0
func main() {

	// filename
	filename, fnkey := io.ArgToFilename(0, "d2-simple-flux", ".sim", true)

	// start analysis process
	out.Extrap = []string{"nwlx", "nwly"}
	out.Start(filename, 0, 0)

	// define entities
	out.Define("top-middle", out.At{5, 3})
	out.Define("section-A", out.N{-1})
	out.Define("section-B", out.Along{{0, 0}, {10, 0}})

	// load results
	out.LoadResults(nil)

	// compute water discharge along section-A
	nwlx_TM := out.GetRes("ex_nwlx", "top-middle", -1)
	Q := out.Integrate("ex_nwlx", "section-A", "y", -1)
	io.PfYel("Q = %g m³/s [answer: 0.0003]\n", Q)

	// plot
	kt := len(out.Times) - 1
	out.Splot("")
	out.Plot("pl", "y", "section-A", plt.Fmt{L: "t=0"}, 0)
	out.Plot("pl", "y", "section-A", plt.Fmt{L: io.Sf("t=%g", out.Times[kt])}, kt)
	out.Splot("")
	out.Plot("x", "pl", "section-B", plt.Fmt{L: "t=0"}, 0)
	out.Plot("x", "pl", "section-B", plt.Fmt{L: io.Sf("t=%g", out.Times[kt])}, kt)
	out.Splot("")
	out.Plot("t", nwlx_TM, "top-middle", plt.Fmt{}, -1)
	out.Csplot.Ylbl = "$n_{\\ell}\\cdot w_{\\ell x}$"

	// save
	plt.SetForPng(1.5, 400, 200)
	out.Draw("/tmp", "seep_simple_flux_"+fnkey+".png", false, func(i, j, nplots int) {
		if i == 2 && j == 1 {
			plt.Plot([]float64{0, 10}, []float64{10, 9}, "'k--'")
		}
	})
}
Exemple #11
0
func main() {

	mpi.Start(false)
	defer func() {
		mpi.Stop(false)
	}()

	if mpi.Rank() == 0 {
		io.PfYel("\nTest MPI 04\n")
	}

	for i := 0; i < 60; i++ {
		time.Sleep(1e9)
		io.Pf("hello from %v\n", mpi.Rank())
		if mpi.Rank() == 2 && i == 3 {
			io.PfGreen("rank = 3 wants to abort (the following error is OK)\n")
			mpi.Abort()
		}
	}
}
Exemple #12
0
// do_solve solve nonlinear problem
func (o *PrincStrainsUp) do_solve(bsmp float64, eid, ipid int, time float64) (err error) {
	silent := true
	if o.DbgOn {
		silent = o.dbg_silent(eid, ipid)
		if !silent {
			io.PfYel("\n\neid=%d ipid=%d time=%g: running with bsmp=%g\n", eid, ipid, time, bsmp)
		}
	}
	err = o.nls.Solve(o.x, silent)
	if err != nil {
		if o.DbgOn {
			o.dbg_plot(eid, ipid, time)
		}
		return
	}
	if o.DbgOn && o.DbgPlot {
		o.dbg_plot(eid, ipid, time)
	}
	return
}
Exemple #13
0
func Test_nurbs01(tst *testing.T) {

	//verbose()
	chk.PrintTitle("nurbs01")

	b := get_nurbs_A()
	elems := b.Elements()
	enodes := b.Enodes()
	io.PfYel("enodes = %v\n", enodes)
	chk.Ints(tst, "elem[0]", elems[0], []int{2, 3, 1, 2})
	chk.Ints(tst, "elem[1]", elems[1], []int{3, 4, 1, 2})
	chk.Ints(tst, "elem[2]", elems[2], []int{4, 5, 1, 2})
	chk.Ints(tst, "enodes[0]", enodes[0], []int{0, 1, 2, 5, 6, 7})
	chk.Ints(tst, "enodes[1]", enodes[1], []int{1, 2, 3, 6, 7, 8})
	chk.Ints(tst, "enodes[2]", enodes[2], []int{2, 3, 4, 7, 8, 9})

	if T_NURBS_SAVE {
		do_plot_nurbs_basis(b, 0, 7)
		plt.SaveD("/tmp/gosl", "t_nurbs01.eps")
	}
}
Exemple #14
0
func Test_eigenp01(tst *testing.T) {

	//verbose()
	chk.PrintTitle("eigenp01")

	// constants
	tolP := 1e-14        // eigenprojectors
	tolS := 1e-13        // spectral decomposition
	toldP := 1e-9        // derivatives of eigenprojectors
	ver := chk.Verbose   // check P verbose
	verdP := chk.Verbose // check dPda verbose

	// run test
	nd := test_nd
	for idxA := 0; idxA < len(test_nd); idxA++ {
		//for idxA := 10; idxA < 11; idxA++ {
		//for idxA := 11; idxA < 12; idxA++ {
		//for idxA := 12; idxA < 13; idxA++ {

		// tensor and eigenvalues
		A := test_AA[idxA]
		a := M_Alloc2(nd[idxA])
		Ten2Man(a, A)
		io.PfYel("\n\ntst # %d ###################################################################################\n", idxA)
		io.Pfblue2("a = %v\n", a)
		io.Pfblue2("λ = %v\n", test_λ[idxA])

		// check eigenprojectors
		io.Pforan("\neigenprojectors\n")
		λsorted := CheckEigenprojs(a, tolP, tolS, ver)
		io.Pfyel("λsorted = %v\n", λsorted)
		λchk := utl.DblGetSorted(test_λ[idxA])
		chk.Vector(tst, "λchk", 1e-12, λsorted, λchk)

		// check derivatives of eigenprojectors
		io.Pforan("\nderivatives\n")
		CheckEigenprojsDerivs(a, toldP, verdP, EV_ZERO)

	}
}
Exemple #15
0
// main function
func main() {

	// flags
	benchmark := false
	ncpuMax := 16

	// benchmarking
	if benchmark {
		var nsol, tf int
		var et time.Duration
		X := make([]float64, ncpuMax)
		T := make([]float64, ncpuMax)
		S := make([]float64, ncpuMax) // speedup
		S[0] = 1
		for i := 0; i < ncpuMax; i++ {
			io.Pf("\n\n")
			nsol, tf, et = runone(i + 1)
			io.PfYel("elaspsedTime = %v\n", et)
			X[i] = float64(i + 1)
			T[i] = et.Seconds()
			if i > 0 {
				S[i] = T[0] / T[i] // Told / Tnew
			}
		}

		plt.SetForEps(0.75, 250)
		plt.Plot(X, S, io.Sf("'b-',marker='.', label='speedup: $N_{sol}=%d,\\,t_f=%d$', clip_on=0, zorder=100", nsol, tf))
		plt.Plot([]float64{1, 16}, []float64{1, 16}, "'k--',zorder=50")
		plt.Gll("$N_{cpu}:\\;$ number of groups", "speedup", "leg_out=1")
		plt.DoubleYscale("$T_{sys}:\\;$ system time [s]")
		plt.Plot(X, T, "'k-',color='gray', clip_on=0")
		plt.SaveD("/tmp/goga", "topology-speedup.eps")
		return
	}

	// normal run
	runone(-1)
}
Exemple #16
0
func solve_problem(problem int) (opt *goga.Optimiser) {

	io.Pf("\n\n------------------------------------- problem = %d ---------------------------------------\n", problem)

	// parameters
	opt = new(goga.Optimiser)
	opt.Default()
	opt.Ncpu = 3
	opt.Tf = 500
	opt.Verbose = false
	opt.Nsamples = 1000
	opt.GenType = "latin"
	opt.DEC = 0.1

	// options for report
	opt.HistNsta = 6
	opt.HistLen = 13
	opt.RptFmtE = "%.4e"
	opt.RptFmtL = "%.4e"
	opt.RptFmtEdev = "%.3e"
	opt.RptFmtLdev = "%.3e"

	// problem variables
	nx := 10
	opt.RptName = io.Sf("CTP%d", problem)
	opt.Nsol = 120
	opt.FltMin = make([]float64, nx)
	opt.FltMax = make([]float64, nx)
	for i := 0; i < nx; i++ {
		opt.FltMin[i] = 0
		opt.FltMax[i] = 1
	}
	nf, ng, nh := 2, 1, 0

	// extra problem variables
	var f1max float64
	var fcn goga.MinProb_t
	var extraplot func()

	// problems
	switch problem {

	// problem # 0 -- TNK
	case 0:
		ng = 2
		f1max = 1.21
		opt.RptName = "TNK"
		opt.FltMin = []float64{0, 0}
		opt.FltMax = []float64{PI, PI}
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			f[0] = x[0]
			f[1] = x[1]
			g[0] = x[0]*x[0] + x[1]*x[1] - 1.0 - 0.1*math.Cos(16.0*math.Atan2(x[0], x[1]))
			g[1] = 0.5 - math.Pow(x[0]-0.5, 2.0) - math.Pow(x[1]-0.5, 2.0)
		}
		extraplot = func() {
			np := 301
			X, Y := utl.MeshGrid2D(0, 1.3, 0, 1.3, np, np)
			Z1, Z2, Z3 := utl.DblsAlloc(np, np), utl.DblsAlloc(np, np), utl.DblsAlloc(np, np)
			for j := 0; j < np; j++ {
				for i := 0; i < np; i++ {
					g1 := 0.5 - math.Pow(X[i][j]-0.5, 2.0) - math.Pow(Y[i][j]-0.5, 2.0)
					if g1 >= 0 {
						Z1[i][j] = X[i][j]*X[i][j] + Y[i][j]*Y[i][j] - 1.0 - 0.1*math.Cos(16.0*math.Atan2(Y[i][j], X[i][j]))
					} else {
						Z1[i][j] = -1
					}
					Z2[i][j] = X[i][j]*X[i][j] + Y[i][j]*Y[i][j] - 1.0 - 0.1*math.Cos(16.0*math.Atan2(Y[i][j], X[i][j]))
					Z3[i][j] = g1
				}
			}
			plt.Contour(X, Y, Z1, "levels=[0,2],cbar=0,lwd=0.5,fsz=5,cmapidx=6")
			plt.Text(0.3, 0.95, "0.000", "size=5,rotation=10")
			plt.ContourSimple(X, Y, Z2, false, 7, "linestyles=['-'], linewidths=[0.7], colors=['k'], levels=[0]")
			plt.ContourSimple(X, Y, Z3, false, 7, "linestyles=['-'], linewidths=[1.0], colors=['k'], levels=[0]")
		}
		opt.Multi_fcnErr = func(f []float64) float64 {
			return f[0]*f[0] + f[1]*f[1] - 1.0 - 0.1*math.Cos(16.0*math.Atan2(f[0], f[1]))
		}

	// problem # 1 -- CTP1, Deb 2001, p367, fig 225
	case 1:
		ng = 2
		f1max = 1.0
		a0, b0 := 0.858, 0.541
		a1, b1 := 0.728, 0.295
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			c0 := 1.0
			for i := 1; i < len(x); i++ {
				c0 += x[i]
			}
			f[0] = x[0]
			f[1] = c0 * math.Exp(-x[0]/c0)
			if true {
				g[0] = f[1] - a0*math.Exp(-b0*f[0])
				g[1] = f[1] - a1*math.Exp(-b1*f[0])
			}
		}
		f0a := math.Log(a0) / (b0 - 1.0)
		f1a := math.Exp(-f0a)
		f0b := math.Log(a0/a1) / (b0 - b1)
		f1b := a0 * math.Exp(-b0*f0b)
		opt.Multi_fcnErr = func(f []float64) float64 {
			if f[0] < f0a {
				return f[1] - math.Exp(-f[0])
			}
			if f[0] < f0b {
				return f[1] - a0*math.Exp(-b0*f[0])
			}
			return f[1] - a1*math.Exp(-b1*f[0])
		}
		extraplot = func() {
			np := 201
			X, Y := utl.MeshGrid2D(0, 1, 0, 1, np, np)
			Z := utl.DblsAlloc(np, np)
			for j := 0; j < np; j++ {
				for i := 0; i < np; i++ {
					Z[i][j] = opt.Multi_fcnErr([]float64{X[i][j], Y[i][j]})
				}
			}
			plt.Contour(X, Y, Z, "levels=[0,0.6],cbar=0,lwd=0.5,fsz=5,cmapidx=6")
			F0 := utl.LinSpace(0, 1, 21)
			F1r := make([]float64, len(F0))
			F1s := make([]float64, len(F0))
			F1t := make([]float64, len(F0))
			for i, f0 := range F0 {
				F1r[i] = math.Exp(-f0)
				F1s[i] = a0 * math.Exp(-b0*f0)
				F1t[i] = a1 * math.Exp(-b1*f0)
			}
			plt.Plot(F0, F1r, "'k--',color='blue'")
			plt.Plot(F0, F1s, "'k--',color='green'")
			plt.Plot(F0, F1t, "'k--',color='gray'")
			plt.PlotOne(f0a, f1a, "'k|', ms=20")
			plt.PlotOne(f0b, f1b, "'k|', ms=20")
		}

	// problem # 2 -- CTP2, Deb 2001, p368/369, fig 226
	case 2:
		f1max = 1.2
		θ, a, b := -0.2*PI, 0.2, 10.0
		c, d, e := 1.0, 6.0, 1.0
		fcn = CTPgenerator(θ, a, b, c, d, e)
		extraplot = CTPplotter(θ, a, b, c, d, e, f1max)
		opt.Multi_fcnErr = CTPerror1(θ, a, b, c, d, e)

	// problem # 3 -- CTP3, Deb 2001, p368/370, fig 227
	case 3:
		f1max = 1.2
		θ, a, b := -0.2*PI, 0.1, 10.0
		c, d, e := 1.0, 0.5, 1.0
		fcn = CTPgenerator(θ, a, b, c, d, e)
		extraplot = CTPplotter(θ, a, b, c, d, e, f1max)
		opt.Multi_fcnErr = CTPerror1(θ, a, b, c, d, e)

	// problem # 4 -- CTP4, Deb 2001, p368/370, fig 228
	case 4:
		f1max = 2.0
		θ, a, b := -0.2*PI, 0.75, 10.0
		c, d, e := 1.0, 0.5, 1.0
		fcn = CTPgenerator(θ, a, b, c, d, e)
		extraplot = CTPplotter(θ, a, b, c, d, e, f1max)
		opt.Multi_fcnErr = CTPerror1(θ, a, b, c, d, e)

	// problem # 5 -- CTP5, Deb 2001, p368/371, fig 229
	case 5:
		f1max = 1.2
		θ, a, b := -0.2*PI, 0.1, 10.0
		c, d, e := 2.0, 0.5, 1.0
		fcn = CTPgenerator(θ, a, b, c, d, e)
		extraplot = CTPplotter(θ, a, b, c, d, e, f1max)
		opt.Multi_fcnErr = CTPerror1(θ, a, b, c, d, e)

	// problem # 6 -- CTP6, Deb 2001, p368/372, fig 230
	case 6:
		f1max = 5.0
		θ, a, b := 0.1*PI, 40.0, 0.5
		c, d, e := 1.0, 2.0, -2.0
		fcn = CTPgenerator(θ, a, b, c, d, e)
		extraplot = func() {
			np := 201
			X, Y := utl.MeshGrid2D(0, 1, 0, 20, np, np)
			Z := utl.DblsAlloc(np, np)
			for j := 0; j < np; j++ {
				for i := 0; i < np; i++ {
					Z[i][j] = CTPconstraint(θ, a, b, c, d, e, X[i][j], Y[i][j])
				}
			}
			plt.Contour(X, Y, Z, "levels=[-30,-15,0,15,30],cbar=0,lwd=0.5,fsz=5,cmapidx=6")
		}
		opt.Multi_fcnErr = CTPerror1(θ, a, b, c, d, e)

	// problem # 7 -- CTP7, Deb 2001, p368/373, fig 231
	case 7:
		f1max = 1.2
		θ, a, b := -0.05*PI, 40.0, 5.0
		c, d, e := 1.0, 6.0, 0.0
		fcn = CTPgenerator(θ, a, b, c, d, e)
		opt.Multi_fcnErr = func(f []float64) float64 { return f[1] - (1.0 - f[0]) }
		extraplot = func() {
			np := 201
			X, Y := utl.MeshGrid2D(0, 1, 0, f1max, np, np)
			Z1 := utl.DblsAlloc(np, np)
			Z2 := utl.DblsAlloc(np, np)
			for j := 0; j < np; j++ {
				for i := 0; i < np; i++ {
					Z1[i][j] = opt.Multi_fcnErr([]float64{X[i][j], Y[i][j]})
					Z2[i][j] = CTPconstraint(θ, a, b, c, d, e, X[i][j], Y[i][j])
				}
			}
			plt.Contour(X, Y, Z2, "levels=[0,3],cbar=0,lwd=0.5,fsz=5,cmapidx=6")
			plt.ContourSimple(X, Y, Z1, false, 7, "linestyles=['--'], linewidths=[0.7], colors=['b'], levels=[0]")
		}

	// problem # 8 -- CTP8, Deb 2001, p368/373, fig 232
	case 8:
		ng = 2
		f1max = 5.0
		θ1, a, b := 0.1*PI, 40.0, 0.5
		c, d, e := 1.0, 2.0, -2.0
		θ2, A, B := -0.05*PI, 40.0, 2.0
		C, D, E := 1.0, 6.0, 0.0
		sin1, cos1 := math.Sin(θ1), math.Cos(θ1)
		sin2, cos2 := math.Sin(θ2), math.Cos(θ2)
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			c0 := 1.0
			for i := 1; i < len(x); i++ {
				c0 += x[i]
			}
			f[0] = x[0]
			f[1] = c0 * (1.0 - f[0]/c0)
			if true {
				c1 := cos1*(f[1]-e) - sin1*f[0]
				c2 := sin1*(f[1]-e) + cos1*f[0]
				c3 := math.Sin(b * PI * math.Pow(c2, c))
				g[0] = c1 - a*math.Pow(math.Abs(c3), d)
				d1 := cos2*(f[1]-E) - sin2*f[0]
				d2 := sin2*(f[1]-E) + cos2*f[0]
				d3 := math.Sin(B * PI * math.Pow(d2, C))
				g[1] = d1 - A*math.Pow(math.Abs(d3), D)
			}
		}
		extraplot = func() {
			np := 401
			X, Y := utl.MeshGrid2D(0, 1, 0, 20, np, np)
			Z1 := utl.DblsAlloc(np, np)
			Z2 := utl.DblsAlloc(np, np)
			Z3 := utl.DblsAlloc(np, np)
			for j := 0; j < np; j++ {
				for i := 0; i < np; i++ {
					c1 := cos1*(Y[i][j]-e) - sin1*X[i][j]
					c2 := sin1*(Y[i][j]-e) + cos1*X[i][j]
					c3 := math.Sin(b * PI * math.Pow(c2, c))
					d1 := cos2*(Y[i][j]-E) - sin2*X[i][j]
					d2 := sin2*(Y[i][j]-E) + cos2*X[i][j]
					d3 := math.Sin(B * PI * math.Pow(d2, C))
					Z1[i][j] = c1 - a*math.Pow(math.Abs(c3), d)
					Z2[i][j] = d1 - A*math.Pow(math.Abs(d3), D)
					if Z1[i][j] >= 0 && Z2[i][j] >= 0 {
						Z3[i][j] = 1
					} else {
						Z3[i][j] = -1
					}
				}
			}
			plt.Contour(X, Y, Z3, "colors=['white','gray'],clabels=0,cbar=0,lwd=0.5,fsz=5")
			plt.ContourSimple(X, Y, Z1, false, 7, "linestyles=['--'], linewidths=[0.7], colors=['gray'], levels=[0]")
			plt.ContourSimple(X, Y, Z2, false, 7, "linestyles=['--'], linewidths=[0.7], colors=['gray'], levels=[0]")
		}
		opt.Multi_fcnErr = CTPerror1(θ1, a, b, c, d, e)

	default:
		chk.Panic("problem %d is not available", problem)
	}

	// initialise optimiser
	opt.Init(goga.GenTrialSolutions, nil, fcn, nf, ng, nh)

	// initial solutions
	var sols0 []*goga.Solution
	if false {
		sols0 = opt.GetSolutionsCopy()
	}

	// solve
	opt.RunMany("", "")
	goga.StatMulti(opt, true)
	io.PfYel("Tsys = %v\n", opt.SysTime)

	// check
	goga.CheckFront0(opt, true)

	// plot
	if true {
		feasibleOnly := false
		plt.SetForEps(0.8, 300)
		fmtAll := &plt.Fmt{L: "final solutions", M: ".", C: "orange", Ls: "none", Ms: 3}
		fmtFront := &plt.Fmt{L: "final Pareto front", C: "r", M: "o", Ms: 3, Ls: "none"}
		goga.PlotOvaOvaPareto(opt, sols0, 0, 1, feasibleOnly, fmtAll, fmtFront)
		extraplot()
		//plt.AxisYrange(0, f1max)
		if problem > 0 && problem < 6 {
			plt.Text(0.05, 0.05, "unfeasible", "color='gray', ha='left',va='bottom'")
			plt.Text(0.95, f1max-0.05, "feasible", "color='white', ha='right',va='top'")
		}
		if opt.RptName == "CTP6" {
			plt.Text(0.02, 0.15, "unfeasible", "rotation=-7,color='gray', ha='left',va='bottom'")
			plt.Text(0.02, 6.50, "unfeasible", "rotation=-7,color='gray', ha='left',va='bottom'")
			plt.Text(0.02, 13.0, "unfeasible", "rotation=-7,color='gray', ha='left',va='bottom'")
			plt.Text(0.50, 2.40, "feasible", "rotation=-7,color='white', ha='center',va='bottom'")
			plt.Text(0.50, 8.80, "feasible", "rotation=-7,color='white', ha='center',va='bottom'")
			plt.Text(0.50, 15.30, "feasible", "rotation=-7,color='white', ha='center',va='bottom'")
		}
		if opt.RptName == "TNK" {
			plt.Text(0.05, 0.05, "unfeasible", "color='gray', ha='left',va='bottom'")
			plt.Text(0.80, 0.85, "feasible", "color='white', ha='left',va='top'")
			plt.Equal()
			plt.AxisRange(0, 1.22, 0, 1.22)
		}
		plt.SaveD("/tmp/goga", io.Sf("%s.eps", opt.RptName))
	}
	return
}
func Test_ops03(tst *testing.T) {

	//verbose()
	chk.PrintTitle("ops03")

	nonsymTol := 1e-15

	dtol := 1e-9
	dver := chk.Verbose

	nd := test_nd
	for idxA := 0; idxA < len(test_nd)-3; idxA++ {
		//for idxA := 0; idxA < 1; idxA++ {

		// tensor and eigenvalues
		A := test_AA[idxA]
		a := M_Alloc2(nd[idxA])
		Ten2Man(a, A)
		io.PfYel("\n\ntst # %d ###################################################################################\n", idxA)
		io.Pfblue2("a = %v\n", a)

		// inverse
		Ai := Alloc2()
		ai := M_Alloc2(nd[idxA])
		detA, err := Inv(Ai, A)
		if err != nil {
			chk.Panic("%v", err)
		}
		deta_ := M_Det(a)
		deta, err := M_Inv(ai, a, MINDET)
		if err != nil {
			chk.Panic("%v", err)
		}
		Ai_ := Alloc2()
		Man2Ten(Ai_, ai)
		aia := M_Alloc2(nd[idxA])
		err = M_Dot(aia, ai, a, nonsymTol)
		if err != nil {
			chk.Panic("%v", err)
		}
		chk.Scalar(tst, "detA", 1e-14, detA, deta)
		chk.Scalar(tst, "deta", 1e-14, deta, deta_)
		chk.Matrix(tst, "Ai", 1e-14, Ai, Ai_)
		chk.Vector(tst, "ai*a", 1e-15, aia, Im[:2*nd[idxA]])
		io.Pforan("ai*a = %v\n", aia)

		// derivative of inverse
		dtol_tmp := dtol
		if idxA == 5 {
			dtol = 1e-8
		}
		var tmp float64
		ai_tmp := M_Alloc2(nd[idxA])
		daida := M_Alloc4(nd[idxA])
		M_InvDeriv(daida, ai)
		io.Pforan("ai = %v\n", ai)
		for i := 0; i < len(a); i++ {
			for j := 0; j < len(a); j++ {
				//dnum, _ := num.DerivForward(func(x float64, args ...interface{}) (res float64) {
				dnum, _ := num.DerivCentral(func(x float64, args ...interface{}) (res float64) {
					tmp, a[j] = a[j], x
					_, err := M_Inv(ai_tmp, a, MINDET)
					a[j] = tmp
					if err != nil {
						chk.Panic("daida failed:\n%v", err)
					}
					return ai_tmp[i]
				}, a[j], 1e-6)
				chk.AnaNum(tst, io.Sf("dai/da[%d][%d]", i, j), dtol, daida[i][j], dnum, dver)
			}
		}
		dtol = dtol_tmp
	}
}
func Test_ops02(tst *testing.T) {

	//verbose()
	chk.PrintTitle("ops02")

	nd := []int{2, 2, 3, 3, 3}
	AA := [][][]float64{
		{
			{1, 2, 0},
			{2, -2, 0},
			{0, 0, -2},
		},
		{
			{-100, 33, 0},
			{33, -200, 0},
			{0, 0, 150},
		},
		{
			{1, 2, 4},
			{2, -2, 3},
			{4, 3, -2},
		},
		{
			{-100, -10, 20},
			{-10, -200, 15},
			{20, 15, -300},
		},
		{
			{-100, 0, -10},
			{0, -200, 0},
			{-10, 0, 100},
		},
	}
	BB := [][][]float64{
		{
			{0.13, 1.2, 0},
			{1.2, -20, 0},
			{0, 0, -28},
		},
		{
			{-10, 3.3, 0},
			{3.3, -2, 0},
			{0, 0, 1.5},
		},
		{
			{0.1, 0.2, 0.8},
			{0.2, -1.3, 0.3},
			{0.8, 0.3, -0.2},
		},
		{
			{-10, -1, 2},
			{-1, -20, 1},
			{2, 1, -30},
		},
		{
			{-10, 3, -1},
			{3, -20, 1},
			{-1, 1, 10},
		},
	}

	nonsymTol := 1e-15

	for m := 0; m < len(nd); m++ {

		// tensors
		A := AA[m]
		B := BB[m]
		a := M_Alloc2(nd[m])
		b := M_Alloc2(nd[m])
		Ten2Man(a, A)
		Ten2Man(b, B)
		io.PfYel("\n\ntst # %d ###################################################################################\n", m)
		io.Pfblue2("a = %v\n", a)
		io.Pfblue2("b = %v\n", b)

		// dyadic
		c := M_Dy(a, b)
		c_ := M_Alloc4(nd[m])
		c__ := M_Alloc4(nd[m])
		M_DyAdd(c_, 1, a, b)
		for i := 0; i < len(a); i++ {
			for j := 0; j < len(a); j++ {
				for k := 0; k < len(a); k++ {
					c__[i][j] = a[i] * b[j]
				}
			}
		}
		chk.Matrix(tst, "a dy b", 1e-12, c, c_)
		chk.Matrix(tst, "a dy b", 1e-12, c, c__)

		// dot product
		d := M_Alloc2(nd[m])
		D := Alloc2()
		for i := 0; i < 3; i++ {
			for j := 0; j < 3; j++ {
				for k := 0; k < 3; k++ {
					D[i][j] += A[i][k] * B[k][j]
				}
			}
		}
		err := M_Dot(d, a, b, nonsymTol)
		for i := 0; i < 3; i++ {
			chk.Scalar(tst, io.Sf("a_dot_b[%d][%d]", i, i), 1e-15, D[i][i], d[i])
		}
		/*
		   for k := 0; k < 2*nd[m]; k++ {
		       I, J := M2Ti[k], M2Tj[k]
		       cf   := 1.0
		       if k > 2 {
		           cf = 1.0 / SQ2
		       }
		       io.Pforan("%v %v\n", D[I][J], d[k] * cf)
		       chk.Scalar(tst, io.Sf("a_dot_b[%d][%d]",I,J), 1e-15, D[I][J], d[k] * cf)
		   }
		*/
		if err == nil {
			chk.Panic("dot product failed: error should be non-nil, since the result is expected to be non-symmetric")
		}

		// dot product (square tensor)
		a2 := M_Alloc2(nd[m])
		M_Sq(a2, a)
		aa := M_Alloc2(nd[m])
		tol_tmp := nonsymTol
		if m == 3 || m == 4 {
			nonsymTol = 1e-12
		}
		err = M_Dot(aa, a, a, nonsymTol)
		io.Pforan("a2 = %v\n", a2)
		io.Pforan("aa = %v\n", aa)
		if err != nil {
			chk.Panic("%v", err)
		}
		chk.Vector(tst, "a2", 1e-15, a2, aa)
		nonsymTol = tol_tmp
	}
}
Exemple #19
0
func Test_isofun01(tst *testing.T) {

	//verbose()
	chk.PrintTitle("isofun01. rounded cone")

	// SMP director parameters
	//  Note:
	//   1) eps and ϵ have an effect on how close to DP/MC SMP will be
	//   2) as eps increases, SMP is closer to DP/MC
	//   3) as ϵ increases, SMP is closer to DP/MC
	//   4) eps also changes the shape of FC surface
	a, b, eps, ϵ := -1.0, 0.5, 1e-3, 1e-3
	shift := 1.0

	// radius
	r := 2.0

	// failure crit parameters and number of stress components
	φ, ncp := 30.0, 6

	// q/p coefficient
	μ := SmpCalcμ(φ, a, b, eps, ϵ)
	io.Pforan("μ = %v\n", μ)

	// isotropic functions
	var o IsoFun
	o.Init(a, b, eps, ϵ, shift, ncp, rounded_cone_ffcn, rounded_cone_gfcn, rounded_cone_hfcn)

	// plot
	if false {
		//if true {
		σcCte := 10.0
		M := Phi2M(φ, "oct")
		rmin, rmax := 0.0, 1.28*M*σcCte
		nr, nα := 31, 81
		//nr,   nα   := 31, 1001
		npolarc := true
		simplec := true
		only0 := true
		grads := false
		showpts := false
		ferr := 10.0
		PlotOct("fig_isofun01.png", σcCte, rmin, rmax, nr, nα, φ, o.Fa, o.Ga,
			npolarc, simplec, only0, grads, showpts, true, true, ferr, r, μ)
	}

	// 3D view
	if false {
		//if true {
		grads := true
		gftol := 5e-2
		o.View(10, nil, grads, gftol, func(e *vtk.IsoSurf) {
			e.Nlevels = 7
		}, r, μ)
	}

	// constants
	ver := chk.Verbose
	tol := 1e-6
	tol2 := 1e-6
	tolq := tol2

	// check gradients
	for idxA := 0; idxA < len(test_nd); idxA++ {
		//for idxA := 0; idxA < 1; idxA++ {
		//for idxA := 2; idxA < 3; idxA++ {
		//for idxA := 10; idxA < 11; idxA++ {
		//for idxA := 11; idxA < 12; idxA++ {
		//for idxA := 12; idxA < 13; idxA++ {

		// tensor
		AA := test_AA[idxA]
		A := M_Alloc2(3)
		Ten2Man(A, AA)
		io.PfYel("\n\ntst # %d ###################################################################################\n", idxA)
		io.Pfblue2("A = %v\n", A)

		// function evaluation and shifted eigenvalues
		fval, err := o.Fa(A, r, μ)
		if err != nil {
			chk.Panic("cannot compute F(A):\n%v", err)
		}
		io.Pfpink("shift = %v\n", shift)
		io.Pforan("p, q  = %v, %v\n", o.p, o.q)
		io.Pforan("f(A)  = %v\n", fval)

		// change tolerances
		tol3 := tol2
		tol2_tmp := tol2
		switch idxA {
		case 7:
			tolq = 1e-5
		case 10:
			tolq = 2508  // TODO
			tol3 = 0.772 // TODO: check why test # 10 fails with d2f/dAdA
		case 11:
			tol2 = 0.0442 // TODO: check this
			tol3 = 440    //TODO: check this
		case 12:
			tol2 = 1e-3
			tol3 = 0.082 // TODO: check this
		}

		// check gradients
		err = o.CheckDerivs(A, tol, tol2, tolq, tol3, ver, r, μ)
		if err != nil {

			// plot
			if true {
				np := 41
				pmin, pmax := -o.p*10, o.p*10
				pq_point := []float64{o.p, o.q}
				o.PlotFfcn("/tmp", io.Sf("t_isofun01_%d.png", idxA), pmin, pmax, np, pq_point, "", "'ro'", nil, nil, r, μ)
			}

			// test failed
			chk.Panic("CheckDerivs failed:%v\n", err)
		}

		// recover tolerances
		tol2 = tol2_tmp
	}
}
Exemple #20
0
func main() {

	mpi.Start(false)
	defer func() {
		mpi.Stop(false)
	}()

	if mpi.Rank() == 0 {
		io.PfYel("\nTest MPI 01\n")
	}
	if mpi.Size() != 3 {
		chk.Panic("this test needs 3 processors")
	}
	n := 11
	x := make([]float64, n)
	id, sz := mpi.Rank(), mpi.Size()
	start, endp1 := (id*n)/sz, ((id+1)*n)/sz
	for i := start; i < endp1; i++ {
		x[i] = float64(i)
	}

	// Barrier
	mpi.Barrier()

	io.Pfgrey("x @ proc # %d = %v\n", id, x)

	// SumToRoot
	r := make([]float64, n)
	mpi.SumToRoot(r, x)
	var tst testing.T
	if id == 0 {
		chk.Vector(&tst, fmt.Sprintf("SumToRoot:       r @ proc # %d", id), 1e-17, r, []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
	} else {
		chk.Vector(&tst, fmt.Sprintf("SumToRoot:       r @ proc # %d", id), 1e-17, r, make([]float64, n))
	}

	// BcastFromRoot
	r[0] = 666
	mpi.BcastFromRoot(r)
	chk.Vector(&tst, fmt.Sprintf("BcastFromRoot:   r @ proc # %d", id), 1e-17, r, []float64{666, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})

	// AllReduceSum
	setslice(x)
	w := make([]float64, n)
	mpi.AllReduceSum(x, w)
	chk.Vector(&tst, fmt.Sprintf("AllReduceSum:    w @ proc # %d", id), 1e-17, w, []float64{110, 110, 110, 1021, 1021, 1021, 2032, 2032, 2032, 3043, 3043})

	// AllReduceSumAdd
	setslice(x)
	y := []float64{-1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000, -1000}
	mpi.AllReduceSumAdd(y, x, w)
	chk.Vector(&tst, fmt.Sprintf("AllReduceSumAdd: y @ proc # %d", id), 1e-17, y, []float64{-890, -890, -890, 21, 21, 21, 1032, 1032, 1032, 2043, 2043})

	// AllReduceMin
	setslice(x)
	mpi.AllReduceMin(x, w)
	chk.Vector(&tst, fmt.Sprintf("AllReduceMin:    x @ proc # %d", id), 1e-17, x, []float64{0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3})

	// AllReduceMax
	setslice(x)
	mpi.AllReduceMax(x, w)
	chk.Vector(&tst, fmt.Sprintf("AllReduceMax:    x @ proc # %d", id), 1e-17, x, []float64{100, 100, 100, 1000, 1000, 1000, 2000, 2000, 2000, 3000, 3000})
}
Exemple #21
0
func Test_nls04(tst *testing.T) {

	//verbose()
	chk.PrintTitle("nls04. finite differences problem")

	// grid
	var g fdm.Grid2D
	g.Init(1.0, 1.0, 6, 6)

	// equations numbering
	var e fdm.Equations
	peq := utl.IntUnique(g.L, g.R, g.B, g.T)
	e.Init(g.N, peq)

	// K11 and K12
	var K11, K12 la.Triplet
	fdm.InitK11andK12(&K11, &K12, &e)

	// assembly
	F1 := make([]float64, e.N1)
	fdm.Assemble(&K11, &K12, F1, nil, &g, &e)

	// prescribed values
	U2 := make([]float64, e.N2)
	for _, eq := range g.L {
		U2[e.FR2[eq]] = 50.0
	}
	for _, eq := range g.R {
		U2[e.FR2[eq]] = 0.0
	}
	for _, eq := range g.B {
		U2[e.FR2[eq]] = 0.0
	}
	for _, eq := range g.T {
		U2[e.FR2[eq]] = 50.0
	}

	// functions
	k11 := K11.ToMatrix(nil)
	k12 := K12.ToMatrix(nil)
	ffcn := func(fU1, U1 []float64) error { // K11*U1 + K12*U2 - F1
		la.VecCopy(fU1, -1, F1)            // fU1 := (-F1)
		la.SpMatVecMulAdd(fU1, 1, k11, U1) // fU1 += K11*U1
		la.SpMatVecMulAdd(fU1, 1, k12, U2) // fU1 += K12*U2
		return nil
	}
	Jfcn := func(dfU1dU1 *la.Triplet, U1 []float64) error {
		fdm.Assemble(dfU1dU1, &K12, F1, nil, &g, &e)
		return nil
	}
	JfcnD := func(dfU1dU1 [][]float64, U1 []float64) error {
		la.MatCopy(dfU1dU1, 1, K11.ToMatrix(nil).ToDense())
		return nil
	}

	prms := map[string]float64{
		"atol":    1e-8,
		"rtol":    1e-8,
		"ftol":    1e-12,
		"lSearch": 0.0,
	}

	// init
	var nls_sps NlSolver // sparse analytical
	var nls_num NlSolver // sparse numerical
	var nls_den NlSolver // dense analytical
	nls_sps.Init(e.N1, ffcn, Jfcn, nil, false, false, prms)
	nls_num.Init(e.N1, ffcn, nil, nil, false, true, prms)
	nls_den.Init(e.N1, ffcn, nil, JfcnD, true, false, prms)
	defer nls_sps.Clean()
	defer nls_num.Clean()
	defer nls_den.Clean()

	// results
	U1sps := make([]float64, e.N1)
	U1num := make([]float64, e.N1)
	U1den := make([]float64, e.N1)
	Usps := make([]float64, e.N)
	Unum := make([]float64, e.N)
	Uden := make([]float64, e.N)

	// solution
	Uc := []float64{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, 25.0, 325.0 / 22.0, 100.0 / 11.0, 50.0 / 11.0,
		0.0, 50.0, 775.0 / 22.0, 25.0, 375.0 / 22.0, 100.0 / 11.0, 0.0, 50.0, 450.0 / 11.0, 725.0 / 22.0,
		25.0, 325.0 / 22.0, 0.0, 50.0, 500.0 / 11.0, 450.0 / 11.0, 775.0 / 22.0, 25.0, 0.0, 50.0, 50.0,
		50.0, 50.0, 50.0, 50.0,
	}

	io.PfYel("\n---- sparse -------- Analytical Jacobian -------------------\n")

	// solve
	err := nls_sps.Solve(U1sps, false)
	if err != nil {
		chk.Panic(err.Error())
	}

	// check
	fdm.JoinVecs(Usps, U1sps, U2, &e)
	chk.Vector(tst, "Usps", 1e-14, Usps, Uc)

	// plot
	if false {
		g.Contour("results", "fig_t_heat_square", nil, Usps, 11, false)
	}

	io.PfYel("\n---- dense -------- Analytical Jacobian -------------------\n")

	// solve
	err = nls_den.Solve(U1den, false)
	if err != nil {
		chk.Panic(err.Error())
	}

	// check
	fdm.JoinVecs(Uden, U1den, U2, &e)
	chk.Vector(tst, "Uden", 1e-14, Uden, Uc)

	io.PfYel("\n---- sparse -------- Numerical Jacobian -------------------\n")

	// solve
	err = nls_num.Solve(U1num, false)
	if err != nil {
		chk.Panic(err.Error())
	}

	// check
	fdm.JoinVecs(Unum, U1num, U2, &e)
	chk.Vector(tst, "Unum", 1e-14, Unum, Uc)
}
Exemple #22
0
func Test_up01a(tst *testing.T) {

	/* this tests simulates seepage flow along a column
	 * by reducing the initial hydrostatic pressure at
	 * at the bottom of the column
	 *
	 *   using mesh from col104elay.msh
	 *
	 *      Nodes / Tags                       Equations
	 *                              ux uy pl               ux uy pl
	 *     8 o----o----o 9 (-5)     53 54 55  o----o----o  50 51 52
	 *       |   14    |             .  .  .  |  58 59  |   .  .  .
	 *       |  (-1)   |             .  .  .  |         |   .  .  .
	 *    21 o    o    o 22 (-6)    60 61  .  o    o    o  56 57  .
	 *       |   26    |             .  .  .  |  62 63  |   .  .  .
	 *       |         |             .  .  .  |         |   .  .  .
	 *     6 o----o----o 7 (-4)     39 40 41  o----o----o  36 37 38
	 *       |   13    |             .  .  .  |  44 45  |   .  .  .
	 *       |  (-1)   |             .  .  .  |         |   .  .  .
	 *    19 |    o    o 20 (-6)    46 47  .  |    o    o  42 43  .
	 *       |   25    |             .  .  .  |  48 49  |   .  .  .
	 *       |         |             .  .  .  |         |   .  .  .
	 *     4 o----o----o 5 (-3)     25 26 27  o----o----o  22 23 24
	 *       |   12    |             .  .  .  |  30 31  |   .  .  .
	 *       |  (-2)   |             .  .  .  |         |   .  .  .
	 *    17 o    o    o 18 (-6)    32 33  .  o    o    o  28 29  .
	 *       |   24    |             .  .  .  |  34 35  |   .  .  .
	 *       |         |             .  .  .  |         |   .  .  .
	 *     2 o----o----o 3 (-2)      9 10 11  o----o----o   6  7  8
	 *       |   11    |             .  .  .  |  16 17  |   .  .  .
	 *       |  (-2)   |             .  .  .  |         |   .  .  .
	 *    15 o    o    o 16 (-6)    18 19     o    o    o  14 15
	 *       |   23    |             .  .  .  |  20 21  |   .  .  .
	 *       |         |             .  .  .  |         |   .  .  .
	 *     0 o----o----o 1 (-1)      0  1  2  o----o----o   3  4  5
	 *           10                              12 13
	 */

	// capture errors and flush log
	defer End()

	//verbose()
	chk.PrintTitle("up01a")

	// start simulation
	if !Start("data/up01.sim", true, chk.Verbose) {
		chk.Panic("cannot start simulation")
	}

	// domain
	distr := false
	dom := NewDomain(Global.Sim.Regions[0], distr)
	if dom == nil {
		chk.Panic("cannot allocate new domain")
	}

	// set stage
	if !dom.SetStage(0, Global.Sim.Stages[0], distr) {
		chk.Panic("cannot set stage")
	}

	// nodes and elements
	chk.IntAssert(len(dom.Nodes), 27)
	chk.IntAssert(len(dom.Elems), 4)

	if true {

		// nodes with pl
		nods_with_pl := map[int]bool{0: true, 2: true, 4: true, 6: true, 8: true, 1: true, 3: true, 5: true, 7: true, 9: true}

		// check dofs
		for _, nod := range dom.Nodes {
			if nods_with_pl[nod.Vert.Id] {
				chk.IntAssert(len(nod.Dofs), 3)
				chk.StrAssert(nod.Dofs[0].Key, "ux")
				chk.StrAssert(nod.Dofs[1].Key, "uy")
				chk.StrAssert(nod.Dofs[2].Key, "pl")
			} else {
				chk.IntAssert(len(nod.Dofs), 2)
				chk.StrAssert(nod.Dofs[0].Key, "ux")
				chk.StrAssert(nod.Dofs[1].Key, "uy")
			}
		}

		// check equations
		nids, eqs := get_nids_eqs(dom)
		chk.Ints(tst, "eqs", eqs, utl.IntRange(10*3+17*2))
		chk.Ints(tst, "nids", nids, []int{
			0, 1, 3, 2, 10, 16, 11, 15, 23,
			5, 4, 18, 12, 17, 24,
			7, 6, 20, 13, 19, 25,
			9, 8, 22, 14, 21, 26,
		})

		// check pmap
		Pmaps := [][]int{
			{2, 5, 8, 11},
			{11, 8, 24, 27},
			{27, 24, 38, 41},
			{41, 38, 52, 55},
		}
		Umaps := [][]int{
			{0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21},
			{9, 10, 6, 7, 22, 23, 25, 26, 16, 17, 28, 29, 30, 31, 32, 33, 34, 35},
			{25, 26, 22, 23, 36, 37, 39, 40, 30, 31, 42, 43, 44, 45, 46, 47, 48, 49},
			{39, 40, 36, 37, 50, 51, 53, 54, 44, 45, 56, 57, 58, 59, 60, 61, 62, 63},
		}
		for i, ele := range dom.Elems {
			e := ele.(*ElemUP)
			io.Pfpink("%2d : Pmap = %v\n", e.Id(), e.P.Pmap)
			io.Pfpink("%2d : Umap = %v\n", e.Id(), e.U.Umap)
			chk.Ints(tst, "Pmap", e.P.Pmap, Pmaps[i])
			chk.Ints(tst, "Umap", e.U.Umap, Umaps[i])
		}

		// constraints
		chk.IntAssert(len(dom.EssenBcs.Bcs), 9*2+2+3)
		var ct_ux_eqs []int // equations with ux prescribed [sorted]
		var ct_uy_eqs []int // equations with uy prescribed [sorted]
		var ct_pl_eqs []int // equations with pl prescribed [sorted]
		for _, c := range dom.EssenBcs.Bcs {
			chk.IntAssert(len(c.Eqs), 1)
			eq := c.Eqs[0]
			io.Pfgrey("key=%v eq=%v\n", c.Key, eq)
			switch c.Key {
			case "ux":
				ct_ux_eqs = append(ct_ux_eqs, eq)
			case "uy":
				ct_uy_eqs = append(ct_uy_eqs, eq)
			case "pl":
				ct_pl_eqs = append(ct_pl_eqs, eq)
			default:
				tst.Errorf("key %s is incorrect", c.Key)
			}
		}
		sort.Ints(ct_ux_eqs)
		sort.Ints(ct_uy_eqs)
		sort.Ints(ct_pl_eqs)
		chk.Ints(tst, "equations with ux prescribed", ct_ux_eqs, []int{0, 3, 6, 9, 14, 18, 22, 25, 28, 32, 36, 39, 42, 46, 50, 53, 56, 60})
		chk.Ints(tst, "equations with uy prescribed", ct_uy_eqs, []int{1, 4, 13})
		chk.Ints(tst, "equations with pl prescribed", ct_pl_eqs, []int{2, 5})

	}

	// initial values @ nodes
	io.Pforan("initial values @ nodes\n")
	for _, nod := range dom.Nodes {
		z := nod.Vert.C[1]
		for _, dof := range nod.Dofs {
			u := dom.Sol.Y[dof.Eq]
			switch dof.Key {
			case "ux":
				chk.Scalar(tst, io.Sf("nod %3d : ux(@ %4g)= %6g", nod.Vert.Id, z, u), 1e-17, u, 0)
			case "uy":
				chk.Scalar(tst, io.Sf("nod %3d : uy(@ %4g)= %6g", nod.Vert.Id, z, u), 1e-17, u, 0)
			case "pl":
				plC, _, _ := Global.HydroSt.Calc(z)
				chk.Scalar(tst, io.Sf("nod %3d : pl(@ %4g)= %6g", nod.Vert.Id, z, u), 1e-13, u, plC)
			}
		}
	}

	// intial values @ integration points
	io.Pforan("initial values @ integration points\n")
	for _, ele := range dom.Elems {
		e := ele.(*ElemUP)
		for idx, ip := range e.P.IpsElem {
			s := e.P.States[idx]
			z := e.P.Shp.IpRealCoords(e.P.X, ip)[1]
			chk.AnaNum(tst, io.Sf("sl(z=%11.8f)", z), 1e-17, s.A_sl, 1, chk.Verbose)
		}
	}

	// parameters
	ν := 0.2            // Poisson's coefficient
	K0 := ν / (1.0 - ν) // earth pressure at rest
	nf := 0.3           // porosity
	sl := 1.0           // saturation
	ρL := 1.0           // intrinsic (real) density of liquid
	ρS_top := 2.0       // intrinsic (real) density of solids in top layer
	ρS_bot := 3.0       // intrinsic (real) density of solids in bottom layer
	h := 5.0            // height of each layer
	g := 10.0           // gravity

	// densities
	nl := nf * sl         // volume fraction of luqid
	ns := 1.0 - nf        // volume fraction of solid
	ρl := nl * ρL         // partial density of liquid
	ρs_top := ns * ρS_top // partial density of solids in top layer
	ρs_bot := ns * ρS_bot // partial density of solids in bottom layer
	ρ_top := ρl + ρs_top  // density of mixture in top layer
	ρ_bot := ρl + ρs_bot  // density of mixture in bottom layer

	// absolute values of stresses
	σV_z5 := ρ_top * g * h     // total vertical stress @ elevation z = 5 m (absolute value)
	σV_z0 := σV_z5 + ρ_bot*g*h // total vertical stress @ elevation z = 0 m (absolute value)
	io.Pfyel("ρ_top       = %g\n", ρ_top)
	io.Pfyel("ρ_bot       = %g\n", ρ_bot)
	io.Pfyel("|ΔσV_top|   = %g\n", ρ_top*g*h)
	io.Pfyel("|ΔσV_bot|   = %g\n", ρ_bot*g*h)
	io.PfYel("|σV|(@ z=0) = %g\n", σV_z0)
	io.PfYel("|σV|(@ z=5) = %g\n", σV_z5)

	// stress functions
	var sig fun.Pts
	var pres fun.Pts
	sig.Init(fun.Prms{
		&fun.Prm{N: "t0", V: 0.00}, {N: "y0", V: -σV_z0},
		&fun.Prm{N: "t1", V: 5.00}, {N: "y1", V: -σV_z5},
		&fun.Prm{N: "t2", V: 10.00}, {N: "y2", V: 0.0},
	})
	pres.Init(fun.Prms{
		&fun.Prm{N: "t0", V: 0.00}, {N: "y0", V: 100},
		&fun.Prm{N: "t1", V: 10.00}, {N: "y1", V: 0},
	})

	// check stresses
	io.Pforan("initial stresses @ integration points\n")
	for _, ele := range dom.Elems {
		e := ele.(*ElemUP)
		for idx, ip := range e.U.IpsElem {
			z := e.U.Shp.IpRealCoords(e.U.X, ip)[1]
			σe := e.U.States[idx].Sig
			sv := sig.F(z, nil)
			sve := sv + pres.F(z, nil)
			she := sve * K0
			if math.Abs(σe[2]-σe[0]) > 1e-17 {
				tst.Errorf("σx is not equal to σz: %g != %g\n", σe[2], σe[0])
				return
			}
			if math.Abs(σe[3]) > 1e-17 {
				tst.Errorf("σxy is not equal to zero: %g != 0\n", σe[3])
				return
			}
			chk.AnaNum(tst, io.Sf("sx(z=%11.8f)", z), 0.0003792, σe[0], she, chk.Verbose)
			chk.AnaNum(tst, io.Sf("sy(z=%11.8f)", z), 0.001517, σe[1], sve, chk.Verbose)
		}
	}
	return
}
Exemple #23
0
// CalcDerived computes derived variables and checks consistency
func (o *Parameters) CalcDerived() {

	// check
	if o.Nova < 1 {
		chk.Panic("number of objective values (nova) must be greater than 0")
	}
	if o.Nsol < 6 {
		chk.Panic("number of solutions must greater than 6. Nsol = %d is invalid", o.Nsol)
	}
	if o.Ncpu < 2 {
		o.Ncpu = 1
		o.Pll = false
		o.DtExc = 1
	}
	if o.Ncpu > o.Nsol/2 {
		chk.Panic("number of CPU must be smaller than or equal to half the number of solutions. Ncpu=%d > Nsol/2=%d", o.Ncpu, o.Nsol/2)
	}
	if o.Tf < 1 {
		o.Tf = 1
	}
	if o.DtExc < 1 {
		o.DtExc = o.Tf / 10
	}
	if o.DtOut < 1 {
		o.DtOut = o.Tf / 5
	}

	// derived
	o.Nflt = len(o.FltMin)
	o.Nint = len(o.IntMin)
	if o.BinInt > 0 {
		o.Nint = o.BinInt
	}
	if o.Nflt == 0 && o.Nint == 0 {
		chk.Panic("either floats and ints must be set (via FltMin/Max or IntMin/Max)")
	}

	// floats
	if o.Nflt > 0 {
		chk.IntAssert(len(o.FltMax), o.Nflt)
		o.DelFlt = make([]float64, o.Nflt)
		for i := 0; i < o.Nflt; i++ {
			o.DelFlt[i] = o.FltMax[i] - o.FltMin[i]
		}
	}

	// mesh
	if o.Nflt < 2 {
		o.UseMesh = false
	}
	if o.UseMesh {
		if o.Nbry < 2 {
			o.Nbry = 2
		}
		o.NumXiXjPairs = (o.Nflt*o.Nflt - o.Nflt) / 2
		o.NumXiXjBryPts = (o.Nbry-2)*4 + 4
		o.NumExtraSols = o.NumXiXjPairs * o.NumXiXjBryPts
		io.PfYel("NumXiXjPairs=%d NumXiXjBryPts=%d NumExtraSols=%d\n", o.NumXiXjPairs, o.NumXiXjBryPts, o.NumExtraSols)
		o.Nsol += o.NumExtraSols
	}

	// generic ints
	if o.BinInt == 0 && o.Nint > 0 {
		chk.IntAssert(len(o.IntMax), o.Nint)
		o.DelInt = make([]int, o.Nint)
		for i := 0; i < o.Nint; i++ {
			o.DelInt[i] = o.IntMax[i] - o.IntMin[i]
		}
	}
	if o.Nint != o.Nflt {
		o.ClearFlt = false
	}

	// number of cuts and changes in ints
	if o.Nint > 0 {
		if o.IntNcuts > o.Nint {
			o.IntNcuts = o.Nint
		}
		if o.IntNchanges > o.Nint {
			o.IntNchanges = o.Nint
		}
	}

	// initialise random numbers generator
	rnd.Init(o.Seed)
}
Exemple #24
0
func Test_munkres01(tst *testing.T) {

	//verbose()
	chk.PrintTitle("munkres01")

	C := [][]float64{
		{1, 2, 3},
		{2, 4, 6},
		{3, 6, 9},
	}
	Ccor := [][]float64{
		{0, 1, 2},
		{0, 2, 4},
		{0, 3, 6},
	}
	Mcor := [][]Mask_t{
		{STAR, NONE, NONE},
		{NONE, NONE, NONE},
		{NONE, NONE, NONE},
	}

	var mnk Munkres
	mnk.Init(len(C), len(C[0]))
	mnk.SetCostMatrix(C)

	// 1:
	io.PfYel("1: after step 0:\n")
	io.Pf("%v", mnk.StrCostMatrix())

	// 2: step 1
	next_step := mnk.step1()
	io.PfYel("\n2: after step 1:\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 2)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{false, false, false})

	// 3: step 2
	next_step = mnk.step2()
	io.PfYel("\n3: after step 2:\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 3)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{false, false, false})

	// 4: step 3
	next_step = mnk.step3()
	io.PfYel("\n4: after step 3:\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 4)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, false, false})

	// 5: step 4
	next_step = mnk.step4()
	io.PfYel("\n5: after step 4:\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 6)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, false, false})

	// 6: step 6
	Ccor = [][]float64{
		{0, 0, 1},
		{0, 1, 3},
		{0, 2, 5},
	}
	next_step = mnk.step6()
	io.PfYel("\n6: after step 6:\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 4)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, false, false})

	// 7: step 4 again (1)
	Mcor = [][]Mask_t{
		{STAR, PRIM, NONE},
		{PRIM, NONE, NONE},
		{NONE, NONE, NONE},
	}
	next_step = mnk.step4()
	io.PfYel("\n7: after step 4 again (1):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 5)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{true, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{false, false, false})

	// 8: step 5
	Mcor = [][]Mask_t{
		{NONE, STAR, NONE},
		{STAR, NONE, NONE},
		{NONE, NONE, NONE},
	}
	next_step = mnk.step5()
	io.PfYel("\n8: after step 5:\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 3)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{false, false, false})

	// 9: step 3 again (1)
	next_step = mnk.step3()
	io.PfYel("\n9: after step 3 again (1):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 4)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, true, false})

	// 10: step 4 again (2)
	next_step = mnk.step4()
	io.PfYel("\n10: after step 4 again (2):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 6)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, true, false})

	// 11: step 6 again (1)
	Ccor = [][]float64{
		{0, 0, 0},
		{0, 1, 2},
		{0, 2, 4},
	}
	next_step = mnk.step6()
	io.PfYel("\n11: after step 6 again (1):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 4)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, true, false})

	// 12: step 4 again (3)
	Mcor = [][]Mask_t{
		{NONE, STAR, PRIM},
		{STAR, NONE, NONE},
		{NONE, NONE, NONE},
	}
	next_step = mnk.step4()
	io.PfYel("\n12: after step 4 again (3):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 6)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{true, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, false, false})

	// 13: step 6 again (2)
	Ccor = [][]float64{
		{1, 0, 0},
		{0, 0, 1},
		{0, 1, 3},
	}
	next_step = mnk.step6()
	io.PfYel("\n13: after step 6 again (2):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 4)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{true, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, false, false})

	// 14: step 4 again (4)
	Mcor = [][]Mask_t{
		{NONE, STAR, PRIM},
		{STAR, PRIM, NONE},
		{PRIM, NONE, NONE},
	}
	next_step = mnk.step4()
	io.PfYel("\n14: after step 4 again (4):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 5)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{true, true, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{false, false, false})

	// 15: step 5 again (1)
	Mcor = [][]Mask_t{
		{NONE, NONE, STAR},
		{NONE, STAR, NONE},
		{STAR, NONE, NONE},
	}
	next_step = mnk.step5()
	io.PfYel("\n15: after step 5 again (1):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 3)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{false, false, false})

	// 15: step 3 again (2)
	next_step = mnk.step3()
	io.PfYel("\n15: after step 3 again (2):\n")
	io.Pf("%v", mnk.StrCostMatrix())
	chk.IntAssert(next_step, 7)
	chk.Matrix(tst, "C", 1e-17, mnk.C, Ccor)
	check_mask_matrix(tst, "M", mnk.M, Mcor)
	chk.Bools(tst, "row_covered", mnk.row_covered, []bool{false, false, false})
	chk.Bools(tst, "col_covered", mnk.col_covered, []bool{true, true, true})
}
Exemple #25
0
func main() {

	// settings: upward movement
	/*
		enabled := []int{1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1}
		areas := []float64{34.00821693709039, 0.09, 9.968259379257471, 35, 15.831579773931853, 8.654957754397607, 11.965649280046627, 19.413683184371774, 7.6546849806620525, 5.387748841496445, 35, 29.504717529844843, 26.86909134752426, 35, 20.10785632243804, 3.446115518045177, 0.09, 35, 26.216339636590078, 9.542311851327804, 35, 0.09, 0.09, 28.407557441773008, 29.933108719044267, 10.922581748461933, 1.8067072461717366, 0.09, 14.7804274343423, 0.09, 11.730811122600027, 35, 35, 0.09, 35, 35}
			weight  = 10169.99460559597
			umax    = 0.03190476190476189
			smax    = 20.518951772912644
	*/

	// settings: upward movement
	//enabled := []int{1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1}
	//areas := []float64{29.673971565565495, 9.804876568305883, 12.722191736896143, 31.128370429558302, 12.28498763291402, 0.09, 1.0976024620675062, 29.054175458117097, 0.09, 12.074834078336714, 0.9518626611813701, 0.804189446111032, 9.620926416457582, 23.064311560926264, 4.903260570239974, 0.09, 14.345604382360431, 31.10942565747464, 0.09, 7.790214820299472, 7.491266591459749, 21.567320209602265, 4.905574834666627, 0.09, 9.065113525395782, 23.84052973418943, 6.7235867554969975, 3.6046158266920836, 24.589638797955896, 0.09, 31.780396612723077, 23.409598016209728, 3.50718429240112, 15.956651688597585, 35, 12.255743491145445}

	//enabled := []int{1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1}
	//areas := []float64{21.480878134095338, 0.09, 14.694965198034584, 24.824367367224532, 6.729854812525405, 0.09, 0.09, 18.170644951273943, 27.43068988046519, 16.340137823665955, 0.09, 35, 33.257655346869484, 0.09, 10.739467844959764, 1.2284583619296825, 0.09, 13.836693890116672, 3.223634459640667, 31.609509632805768, 2.9580912890580233, 0.09, 11.66346650529349, 11.839368679149583, 8.037665593492571, 18.4772618019285, 6.0722754499289335, 8.299339699920758, 18.092667282860184, 0.09, 3.95809930082411, 35, 24.98891088932943, 0.09, 20.001590440636104, 0.4232030075463411}

	//enabled := []int{1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}
	//areas := []float64{1.2035515116115514, 0.811277071473871, 32.37830152936991, 11.012589123896603, 29.419388200704844, 11.517528463414674, 26.842094480154707, 0.09, 7.545801867132738, 22.246892098984826, 33.64813536709853, 35, 18.79453561647245, 19.72091117582699, 24.417433685262015, 17.139485224780174, 14.64143052284774, 6.017622261768879, 18.627730008706013, 6.034380625351308, 15.909160991008125, 3.010643800045916, 35, 1.7855841010723912, 23.882989565364397, 4.179630598025799, 8.060183267136836, 27.61994718378331, 26.443620790772826, 35, 0.9889261275628931, 0.09, 22.110211729649148, 31.153765658657143, 19.868907703384732, 23.523896513200622}

	enabled := []int{1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1}
	areas := []float64{22.757099750148996, 28.986754816914374, 6.957451713927281, 8.528672093936208, 9.26287758087651, 2.4766961118094857, 19.144883540012557, 6.382281135196173, 10.365771948733226, 2.0524134188513186, 3.3776112861797856, 22.444923164834712, 0.09, 0.09, 0.09, 8.68418380122592, 0.09, 0.3395486752846164, 4.356831930853984, 12.792965016026955, 20.651430212430448, 4.881368992183173, 17.009172478115723, 14.806321101924194, 9.298936701386527, 5.820319254311902, 11.792969696093445, 12.323517103405779, 1.4343013440743113, 2.3392600723999366, 0.09, 11.352516128577138, 11.223982208350751, 23.98665707191376, 0.09, 0.09}

	// start simulation
	processing := fem.NewFEM("cantilever.sim", "", true, true, false, false, true, 0)

	// set enabled/disabled
	dom := processing.Domains[0]
	if true {
		set_enabled_disabled(dom, enabled)
	}

	// set stage
	err := processing.SetStage(0)
	if err != nil {
		io.PfRed("SetStage failed:\n%v", err)
		return
	}

	// set areas
	lwds := make(map[int]float64)
	if true {
		weight := 0.0
		for _, elem := range dom.Elems {
			ele := elem.(*fem.ElastRod)
			cid := ele.Cell.Id
			ele.Mdl.A = areas[cid]
			ele.Recompute(false)
			weight += ele.Mdl.Rho * ele.Mdl.A * ele.L
			lwds[cid] = 0.1 + ele.Mdl.A/10.0
		}
		io.Pforan("weight = %v\n", weight)
	}

	// mobility
	n := len(dom.Nodes)
	m := len(dom.Elems)
	d := len(dom.EssenBcs.Bcs)
	F := 2*n - m - d
	io.Pforan("mobility = %v\n", F)

	// plot
	msh := dom.Msh
	msh.Draw2d(true, lwds)
	plt.SaveD("/tmp/goga", "rods.eps")

	// run FE analysis
	err = processing.SolveOneStage(0, true)
	if err != nil {
		io.PfRed("Run failed:\n%v", err)
		return
	}

	// post-processing
	vid := msh.VertTag2verts[-4][0].Id
	nod := dom.Vid2node[vid]
	eqy := nod.GetEq("uy")
	uy := dom.Sol.Y[eqy]
	io.PfYel("%2d : uy = %g\n", vid, uy)
	smax := 0.0
	for _, elem := range dom.Elems {
		ele := elem.(*fem.ElastRod)
		sig := math.Abs(ele.CalcSig(dom.Sol))
		if sig > smax {
			smax = sig
		}
	}
	io.Pfred("smax = %v\n", smax)
}
Exemple #26
0
func Test_nls01(tst *testing.T) {

	//verbose()
	chk.PrintTitle("nls01. 2 eqs system")

	ffcn := func(fx, x []float64) error {
		fx[0] = math.Pow(x[0], 3.0) + x[1] - 1.0
		fx[1] = -x[0] + math.Pow(x[1], 3.0) + 1.0
		return nil
	}
	Jfcn := func(dfdx *la.Triplet, x []float64) error {
		dfdx.Start()
		dfdx.Put(0, 0, 3.0*x[0]*x[0])
		dfdx.Put(0, 1, 1.0)
		dfdx.Put(1, 0, -1.0)
		dfdx.Put(1, 1, 3.0*x[1]*x[1])
		return nil
	}

	x := []float64{0.5, 0.5}
	atol, rtol, ftol := 1e-10, 1e-10, 10*EPS
	fx := make([]float64, len(x))
	neq := len(x)

	prms := map[string]float64{
		"atol":    atol,
		"rtol":    rtol,
		"ftol":    ftol,
		"lSearch": 1.0,
	}

	io.PfYel("\n-------------------- Analytical Jacobian -------------------\n")

	// init
	var nls_ana NlSolver
	nls_ana.Init(neq, ffcn, Jfcn, nil, false, false, prms)
	defer nls_ana.Clean()

	// solve
	err := nls_ana.Solve(x, false)
	if err != nil {
		chk.Panic(err.Error())
	}

	// check
	ffcn(fx, x)
	io.Pf("x    = %v  expected = %v\n", x, []float64{1.0, 0.0})
	io.Pf("f(x) = %v\n", fx)
	chk.Vector(tst, "f(x) = 0? ", 1e-16, fx, []float64{})

	// check Jacobian
	io.Pforan("\nchecking Jacobian @ %v\n", x)
	_, err = nls_ana.CheckJ(x, 1e-5, false, true)
	if err != nil {
		chk.Panic(err.Error())
	}

	io.PfYel("\n\n-------------------- Numerical Jacobian --------------------\n")
	xx := []float64{0.5, 0.5}

	// init
	var nls_num NlSolver
	nls_num.Init(neq, ffcn, nil, nil, false, true, prms)
	defer nls_num.Clean()

	// solve
	err = nls_num.Solve(xx, false)
	if err != nil {
		chk.Panic(err.Error())
	}

	// check
	ffcn(fx, xx)
	io.Pf("xx    = %v  expected = %v\n", xx, []float64{1.0, 0.0})
	io.Pf("f(xx) = %v\n", fx)
	chk.Vector(tst, "f(x) = 0? ", 1e-16, fx, []float64{})
	chk.Vector(tst, "x == xx", 1e-15, x, xx)

	// check Jacobian
	io.Pforan("\nchecking Jacobian @ %v\n", x)
	_, err = nls_ana.CheckJ(x, 1e-5, false, true)
	if err != nil {
		chk.Panic(err.Error())
	}
}
Exemple #27
0
// testing_compare_results_u compares results with u-formulation
func TestingCompareResultsU(tst *testing.T, simfname, cmpfname string, tolK, tolu, tols float64, skipK, verbose bool) {

	// only root can run this test
	if !Global.Root {
		return
	}

	// read summary
	sum := ReadSum(Global.Dirout, Global.Fnkey)
	if sum == nil {
		tst.Error("cannot read summary file for simulation=%q\n", simfname)
		return
	}

	// allocate domain
	distr := false
	d := NewDomain(Global.Sim.Regions[0], distr)
	if !d.SetStage(0, Global.Sim.Stages[0], distr) {
		tst.Errorf("TestingCompareResultsU: SetStage failed\n")
		return
	}

	// read file
	buf, err := io.ReadFile(cmpfname)
	if err != nil {
		tst.Errorf("TestingCompareResultsU: ReadFile failed\n")
		return
	}

	// unmarshal json
	var cmp_set T_results_set
	err = json.Unmarshal(buf, &cmp_set)
	if err != nil {
		tst.Errorf("TestingCompareResultsU: Unmarshal failed\n")
		return
	}

	// run comparisons
	dmult := 1.0
	for idx, cmp := range cmp_set {

		// displacements multiplier
		if idx == 0 && math.Abs(cmp.DispMult) > 1e-10 {
			dmult = cmp.DispMult
		}

		// time index
		tidx := idx + 1
		if verbose {
			io.PfYel("\n\ntidx = %d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n", tidx)
		}

		// load gofem results
		if !d.In(sum, tidx, true) {
			tst.Errorf("TestingCompareResultsU: reading of results failed\n")
			return
		}
		if verbose {
			io.Pfyel("time = %v\n", d.Sol.T)
		}

		// check K matrices
		if !skipK {
			if verbose {
				io.Pfgreen(". . . checking K matrices . . .\n")
			}
			for eid, Ksg := range cmp.Kmats {
				if e, ok := d.Elems[eid].(*ElemU); ok {
					if !e.AddToKb(d.Kb, d.Sol, true) {
						tst.Errorf("TestingCompareResultsU: AddToKb failed\n")
						return
					}
					chk.Matrix(tst, io.Sf("K%d", eid), tolK, e.K, Ksg)
				}
			}
		}

		// check displacements
		if verbose {
			io.Pfgreen(". . . checking displacements . . .\n")
		}
		for nid, usg := range cmp.Disp {
			ix := d.Vid2node[nid].Dofs[0].Eq
			iy := d.Vid2node[nid].Dofs[1].Eq
			chk.AnaNum(tst, "ux", tolu, d.Sol.Y[ix], usg[0]*dmult, verbose)
			chk.AnaNum(tst, "uy", tolu, d.Sol.Y[iy], usg[1]*dmult, verbose)
			if len(usg) == 3 {
				iz := d.Vid2node[nid].Dofs[2].Eq
				chk.AnaNum(tst, "uz", tolu, d.Sol.Y[iz], usg[2]*dmult, verbose)
			}
		}

		// check stresses
		if true {
			if verbose {
				io.Pfgreen(". . . checking stresses . . .\n")
			}
			for eid, sig := range cmp.Sigmas {
				if verbose {
					io.Pforan("eid = %d\n", eid)
				}
				if e, ok := d.Cid2elem[eid].(*ElemU); ok {
					for ip, val := range sig {
						if verbose {
							io.Pfgrey2("ip = %d\n", ip)
						}
						σ := e.States[ip].Sig
						if len(val) == 6 {
							chk.AnaNum(tst, "sx ", tols, σ[0], val[0], verbose)
							chk.AnaNum(tst, "sy ", tols, σ[1], val[1], verbose)
						} else {
							chk.AnaNum(tst, "sx ", tols, σ[0], val[0], verbose)
							chk.AnaNum(tst, "sy ", tols, σ[1], val[1], verbose)
							chk.AnaNum(tst, "sxy", tols, σ[3]/SQ2, val[2], verbose)
							if len(val) > 3 { // sx, sy, sxy, sz
								chk.AnaNum(tst, "sz ", tols, σ[2], val[3], verbose)
							}
						}
					}
				}
			}
		}
	}
}
Exemple #28
0
func Test_geninvs01(tst *testing.T) {

	//verbose()
	chk.PrintTitle("geninvs01")

	// coefficients for smp invariants
	smp_a := -1.0
	smp_b := 0.5
	smp_β := 1e-1 // derivative values become too high with
	smp_ϵ := 1e-1 // small β and ϵ @ zero

	// constants for checking derivatives
	dver := chk.Verbose
	dtol := 1e-6
	dtol2 := 1e-6

	// run tests
	nd := test_nd
	for idxA := 0; idxA < len(test_nd); idxA++ {
		//for idxA := 10; idxA < 11; idxA++ {

		// tensor and eigenvalues
		A := test_AA[idxA]
		a := M_Alloc2(nd[idxA])
		Ten2Man(a, A)
		L := make([]float64, 3)
		M_EigenValsNum(L, a)

		// SMP derivs and SMP director
		dndL := la.MatAlloc(3, 3)
		dNdL := make([]float64, 3)
		d2ndLdL := utl.Deep3alloc(3, 3, 3)
		N := make([]float64, 3)
		F := make([]float64, 3)
		G := make([]float64, 3)
		m := SmpDerivs1(dndL, dNdL, N, F, G, L, smp_a, smp_b, smp_β, smp_ϵ)
		SmpDerivs2(d2ndLdL, L, smp_a, smp_b, smp_β, smp_ϵ, m, N, F, G, dNdL, dndL)
		n := make([]float64, 3)
		SmpUnitDirector(n, m, N)

		// SMP invariants
		p, q, err := GenInvs(L, n, smp_a)
		if err != nil {
			chk.Panic("SmpInvs failed:\n%v", err)
		}

		// output
		io.PfYel("\n\ntst # %d ###################################################################################\n", idxA)
		io.Pfblue2("L = %v\n", L)
		io.Pforan("n = %v\n", n)
		io.Pforan("p = %v\n", p)
		io.Pforan("q = %v\n", q)

		// check invariants
		tvec := make([]float64, 3)
		GenTvec(tvec, L, n)
		proj := make([]float64, 3) // projection of tvec along n
		tdn := la.VecDot(tvec, n)  // tvec dot n
		for i := 0; i < 3; i++ {
			proj[i] = tdn * n[i]
		}
		norm_proj := la.VecNorm(proj)
		norm_tvec := la.VecNorm(tvec)
		q_ := GENINVSQEPS + math.Sqrt(norm_tvec*norm_tvec-norm_proj*norm_proj)
		io.Pforan("proj = %v\n", proj)
		io.Pforan("norm(proj) = %v == p\n", norm_proj)
		chk.Scalar(tst, "p", 1e-14, math.Abs(p), norm_proj)
		chk.Scalar(tst, "q", 1e-13, q, q_)

		// dt/dL
		var tmp float64
		N_tmp := make([]float64, 3)
		n_tmp := make([]float64, 3)
		tvec_tmp := make([]float64, 3)
		dtdL := la.MatAlloc(3, 3)
		GenTvecDeriv1(dtdL, L, n, dndL)
		for i := 0; i < 3; i++ {
			for j := 0; j < 3; j++ {
				dnum, _ := num.DerivCentral(func(x float64, args ...interface{}) (res float64) {
					tmp, L[j] = L[j], x
					m_tmp := SmpDirector(N_tmp, L, smp_a, smp_b, smp_β, smp_ϵ)
					SmpUnitDirector(n_tmp, m_tmp, N_tmp)
					GenTvec(tvec_tmp, L, n_tmp)
					L[j] = tmp
					return tvec_tmp[i]
				}, L[j], 1e-6)
				chk.AnaNum(tst, io.Sf("dt/dL[%d][%d]", i, j), dtol, dtdL[i][j], dnum, dver)
			}
		}

		// d²t/dLdL
		io.Pfpink("\nd²t/dLdL\n")
		dNdL_tmp := make([]float64, 3)
		dndL_tmp := la.MatAlloc(3, 3)
		dtdL_tmp := la.MatAlloc(3, 3)
		for i := 0; i < 3; i++ {
			for j := 0; j < 3; j++ {
				for k := 0; k < 3; k++ {
					dnum, _ := num.DerivCentral(func(x float64, args ...interface{}) (res float64) {
						tmp, L[k] = L[k], x
						m_tmp := SmpDerivs1(dndL_tmp, dNdL_tmp, N_tmp, F, G, L, smp_a, smp_b, smp_β, smp_ϵ)
						SmpUnitDirector(n_tmp, m_tmp, N_tmp)
						GenTvecDeriv1(dtdL_tmp, L, n_tmp, dndL_tmp)
						L[k] = tmp
						return dtdL_tmp[i][j]
					}, L[k], 1e-6)
					dana := GenTvecDeriv2(i, j, k, L, dndL, d2ndLdL[i][j][k])
					chk.AnaNum(tst, io.Sf("d²t[%d]/dL[%d]dL[%d]", i, j, k), dtol2, dana, dnum, dver)
				}
			}
		}

		// change tolerance
		dtol_tmp := dtol
		switch idxA {
		case 5, 11:
			dtol = 1e-5
		case 12:
			dtol = 0.0013
		}

		// first order derivatives
		dpdL := make([]float64, 3)
		dqdL := make([]float64, 3)
		p_, q_, err := GenInvsDeriv1(dpdL, dqdL, L, n, dndL, smp_a)
		if err != nil {
			chk.Panic("%v", err)
		}
		chk.Scalar(tst, "p", 1e-17, p, p_)
		chk.Scalar(tst, "q", 1e-17, q, q_)
		var ptmp, qtmp float64
		io.Pfpink("\ndp/dL\n")
		for j := 0; j < 3; j++ {
			dnum, _ := num.DerivCentral(func(x float64, args ...interface{}) (res float64) {
				tmp, L[j] = L[j], x
				m_tmp := SmpDirector(N_tmp, L, smp_a, smp_b, smp_β, smp_ϵ)
				SmpUnitDirector(n_tmp, m_tmp, N_tmp)
				ptmp, _, err = GenInvs(L, n_tmp, smp_a)
				if err != nil {
					chk.Panic("DerivCentral: SmpInvs failed:\n%v", err)
				}
				L[j] = tmp
				return ptmp
			}, L[j], 1e-6)
			chk.AnaNum(tst, io.Sf("dp/dL[%d]", j), dtol, dpdL[j], dnum, dver)
		}
		io.Pfpink("\ndq/dL\n")
		for j := 0; j < 3; j++ {
			dnum, _ := num.DerivCentral(func(x float64, args ...interface{}) (res float64) {
				tmp, L[j] = L[j], x
				m_tmp := SmpDirector(N_tmp, L, smp_a, smp_b, smp_β, smp_ϵ)
				SmpUnitDirector(n_tmp, m_tmp, N_tmp)
				_, qtmp, err = GenInvs(L, n_tmp, smp_a)
				if err != nil {
					chk.Panic("DerivCentral: SmpInvs failed:\n%v", err)
				}
				L[j] = tmp
				return qtmp
			}, L[j], 1e-6)
			chk.AnaNum(tst, io.Sf("dq/dL[%d]", j), dtol, dqdL[j], dnum, dver)
		}

		// recover tolerance
		dtol = dtol_tmp

		// change tolerance
		io.Pforan("dtol2 = %v\n", dtol2)
		dtol2_tmp := dtol2
		switch idxA {
		case 5:
			dtol2 = 1e-5
		case 10:
			dtol2 = 0.72
		case 11:
			dtol2 = 1e-5
		case 12:
			dtol2 = 544
		}

		// second order derivatives
		dpdL_tmp := make([]float64, 3)
		dqdL_tmp := make([]float64, 3)
		d2pdLdL := la.MatAlloc(3, 3)
		d2qdLdL := la.MatAlloc(3, 3)
		GenInvsDeriv2(d2pdLdL, d2qdLdL, L, n, dpdL, dqdL, p, q, dndL, d2ndLdL, smp_a)
		io.Pfpink("\nd²p/dLdL\n")
		for i := 0; i < 3; i++ {
			for j := 0; j < 3; j++ {
				dnum, _ := num.DerivCentral(func(x float64, args ...interface{}) (res float64) {
					tmp, L[j] = L[j], x
					m_tmp := SmpDerivs1(dndL_tmp, dNdL_tmp, N_tmp, F, G, L, smp_a, smp_b, smp_β, smp_ϵ)
					SmpUnitDirector(n_tmp, m_tmp, N_tmp)
					GenInvsDeriv1(dpdL_tmp, dqdL_tmp, L, n_tmp, dndL_tmp, smp_a)
					L[j] = tmp
					return dpdL_tmp[i]
				}, L[j], 1e-6)
				chk.AnaNum(tst, io.Sf("d²p/dL[%d][%d]", i, j), dtol2, d2pdLdL[i][j], dnum, dver)
			}
		}
		io.Pfpink("\nd²q/dLdL\n")
		for i := 0; i < 3; i++ {
			for j := 0; j < 3; j++ {
				dnum, _ := num.DerivCentral(func(x float64, args ...interface{}) (res float64) {
					tmp, L[j] = L[j], x
					m_tmp := SmpDerivs1(dndL_tmp, dNdL_tmp, N_tmp, F, G, L, smp_a, smp_b, smp_β, smp_ϵ)
					SmpUnitDirector(n_tmp, m_tmp, N_tmp)
					GenInvsDeriv1(dpdL_tmp, dqdL_tmp, L, n_tmp, dndL_tmp, smp_a)
					L[j] = tmp
					return dqdL_tmp[i]
				}, L[j], 1e-6)
				chk.AnaNum(tst, io.Sf("d²q/dL[%d][%d]", i, j), dtol2, d2qdLdL[i][j], dnum, dver)
			}
		}

		// recover tolerance
		dtol2 = dtol2_tmp
	}
}
Exemple #29
0
// Update updates state
//  pl and pg are updated (new) values
func (o Model) Update(s *State, Δpl, Δpg, pl, pg float64) (err error) {

	// auxiliary variables
	slmin := o.Lrm.SlMin()
	Δpc := Δpg - Δpl
	wet := Δpc < 0
	pl0 := pl - Δpl
	pg0 := pg - Δpg
	pc0 := pg0 - pl0
	sl0 := s.A_sl
	pc := pc0 + Δpc
	sl := sl0

	// update liquid saturation
	if pc <= 0.0 {
		sl = 1 // full liquid saturation if capillary pressure is ineffective

	} else if o.nonrateLrm != nil && !o.AllBE {
		sl = o.nonrateLrm.Sl(pc) // handle simple retention models

	} else { // unsaturated case with rate-type model

		// trial liquid saturation update
		fA, e := o.Lrm.Cc(pc0, sl0, wet)
		if e != nil {
			return e
		}
		if o.MEtrial {
			slFE := sl0 + Δpc*fA
			fB, e := o.Lrm.Cc(pc, slFE, wet)
			if e != nil {
				return e
			}
			sl += 0.5 * Δpc * (fA + fB)
		} else {
			sl += Δpc * fA
		}

		// fix trial sl out-of-range values
		if sl < slmin {
			sl = slmin
		}
		if sl > 1 {
			sl = 1
		}

		// message
		if o.ShowR {
			io.PfYel("%6s%18s%18s%18s%18s%8s\n", "it", "Cc", "sl", "δsl", "r", "ex(r)")
		}

		// backward-Euler update
		var f, r, J, δsl float64
		var it int
		for it = 0; it < o.NmaxIt; it++ {
			f, err = o.Lrm.Cc(pc, sl, wet)
			if err != nil {
				return
			}
			r = sl - sl0 - Δpc*f
			if o.ShowR {
				io.Pfyel("%6d%18.14f%18.14f%18.14f%18.10e%8d\n", it, f, sl, δsl, r, utl.Expon(r))
			}
			if math.Abs(r) < o.Itol {
				break
			}
			J, err = o.Lrm.J(pc, sl, wet)
			if err != nil {
				return
			}
			δsl = -r / (1.0 - Δpc*J)
			sl += δsl
			if math.IsNaN(sl) {
				return chk.Err("NaN found: Δpc=%v f=%v r=%v J=%v sl=%v\n", Δpc, f, r, J, sl)
			}
		}

		// message
		if o.ShowR {
			io.Pfgrey("  pc0=%.6f  sl0=%.6f  Δpl=%.6f  Δpg=%.6f  Δpc=%.6f\n", pc0, sl0, Δpl, Δpg, Δpc)
			io.Pfgrey("  converged with %d iterations\n", it)
		}

		// check convergence
		if it == o.NmaxIt {
			return chk.Err("saturation update failed after %d iterations\n", it)
		}
	}

	// check results
	if pc < 0 && sl < 1 {
		return chk.Err("inconsistent results: saturation must be equal to one when the capillary pressure is ineffective. pc = %g < 0 and sl = %g < 1 is incorrect", pc, sl)
	}
	if sl < slmin {
		return chk.Err("inconsistent results: saturation must be greater than minimum saturation. sl = %g < %g is incorrect", sl, slmin)
	}

	// set state
	s.A_sl = sl          // 2
	s.A_ρL += o.Cl * Δpl // 3
	s.A_ρG += o.Cg * Δpg // 4
	s.A_Δpc = Δpc        // 5
	s.A_wet = wet        // 6
	return
}
Exemple #30
0
func Test_nls03(tst *testing.T) {

	//verbose()
	chk.PrintTitle("nls03. 2 eqs system with trig functions")

	e := math.E
	ffcn := func(fx, x []float64) error {
		fx[0] = 0.5*sin(x[0]*x[1]) - 0.25*x[1]/pi - 0.5*x[0]
		fx[1] = (1.0-0.25/pi)*(math.Exp(2.0*x[0])-e) + e*x[1]/pi - 2.0*e*x[0]
		return nil
	}
	Jfcn := func(dfdx *la.Triplet, x []float64) error {
		dfdx.Start()
		dfdx.Put(0, 0, 0.5*x[1]*cos(x[0]*x[1])-0.5)
		dfdx.Put(0, 1, 0.5*x[0]*cos(x[0]*x[1])-0.25/pi)
		dfdx.Put(1, 0, (2.0-0.5/pi)*math.Exp(2.0*x[0])-2.0*e)
		dfdx.Put(1, 1, e/pi)
		return nil
	}
	JfcnD := func(dfdx [][]float64, x []float64) error {
		dfdx[0][0] = 0.5*x[1]*cos(x[0]*x[1]) - 0.5
		dfdx[0][1] = 0.5*x[0]*cos(x[0]*x[1]) - 0.25/pi
		dfdx[1][0] = (2.0-0.5/pi)*math.Exp(2.0*x[0]) - 2.0*e
		dfdx[1][1] = e / pi
		return nil
	}

	x := []float64{0.4, 3.0}
	fx := make([]float64, len(x))
	atol := 1e-6
	rtol := 1e-3
	ftol := 10 * EPS
	neq := len(x)

	prms := map[string]float64{
		"atol":    atol,
		"rtol":    rtol,
		"ftol":    ftol,
		"lSearch": 0.0, // does not work with line search
	}

	// init
	var nls_sps NlSolver // sparse
	var nls_den NlSolver // dense
	nls_sps.Init(neq, ffcn, Jfcn, nil, false, false, prms)
	nls_den.Init(neq, ffcn, nil, JfcnD, true, false, prms)
	defer nls_sps.Clean()
	defer nls_den.Clean()

	io.PfMag("\n/////////////////////// sparse //////////////////////////////////////////\n")

	x = []float64{0.4, 3.0}
	io.PfYel("\n--- sparse ------------- with x = %v --------------\n", x)
	err := nls_sps.Solve(x, false)
	if err != nil {
		chk.Panic(err.Error())
	}
	ffcn(fx, x)
	io.Pf("x    = %v  expected = %v\n", x, []float64{-0.2605992900257, 0.6225308965998})
	io.Pf("f(x) = %v\n", fx)
	chk.Vector(tst, "x", 1e-13, x, []float64{-0.2605992900257, 0.6225308965998})
	chk.Vector(tst, "f(x) = 0? ", 1e-11, fx, nil)

	x = []float64{0.7, 4.0}
	io.PfYel("\n--- sparse ------------- with x = %v --------------\n", x)
	//rtol = 1e-2
	err = nls_sps.Solve(x, false)
	if err != nil {
		chk.Panic(err.Error())
	}
	ffcn(fx, x)
	io.Pf("x    = %v  expected = %v\n", x, []float64{0.5000000377836, 3.1415927055406})
	io.Pf("f(x) = %v\n", fx)
	chk.Vector(tst, "x  ", 1e-7, x, []float64{0.5000000377836, 3.1415927055406})
	chk.Vector(tst, "f(x) = 0? ", 1e-7, fx, nil)

	x = []float64{1.0, 4.0}
	io.PfYel("\n--- sparse ------------- with x = %v ---------------\n", x)
	//lSearch, chkConv := false, true  // this combination fails due to divergence
	//lSearch, chkConv := false, false // this combination works but results are different
	//lSearch, chkConv := true, true   // this combination works but results are wrong => fails
	nls_sps.ChkConv = false
	err = nls_sps.Solve(x, false)
	if err != nil {
		chk.Panic(err.Error())
	}
	ffcn(fx, x)
	io.Pf("x    = %v  expected = %v\n", x, []float64{0.5, pi})
	io.Pf("f(x) = %v << converges to a different solution\n", fx)
	chk.Vector(tst, "f(x) = 0? ", 1e-8, fx, nil)

	io.PfMag("\n/////////////////////// dense //////////////////////////////////////////\n")

	x = []float64{0.4, 3.0}
	io.PfYel("\n--- dense ------------- with x = %v --------------\n", x)
	err = nls_den.Solve(x, false)
	if err != nil {
		chk.Panic(err.Error())
	}
	ffcn(fx, x)
	io.Pf("x    = %v  expected = %v\n", x, []float64{-0.2605992900257, 0.6225308965998})
	io.Pf("f(x) = %v\n", fx)
	chk.Vector(tst, "x", 1e-13, x, []float64{-0.2605992900257, 0.6225308965998})
	chk.Vector(tst, "f(x) = 0? ", 1e-11, fx, nil)

	x = []float64{0.7, 4.0}
	io.PfYel("\n--- dense ------------- with x = %v --------------\n", x)
	//rtol = 1e-2
	err = nls_den.Solve(x, false)
	if err != nil {
		chk.Panic(err.Error())
	}
	ffcn(fx, x)
	io.Pf("x    = %v  expected = %v\n", x, []float64{0.5000000377836, 3.1415927055406})
	io.Pf("f(x) = %v\n", fx)
	chk.Vector(tst, "x  ", 1e-7, x, []float64{0.5000000377836, 3.1415927055406})
	chk.Vector(tst, "f(x) = 0? ", 1e-7, fx, nil)

	x = []float64{1.0, 4.0}
	io.PfYel("\n--- dense ------------- with x = %v ---------------\n", x)
	nls_den.ChkConv = false
	err = nls_den.Solve(x, false)
	if err != nil {
		chk.Panic(err.Error())
	}
	ffcn(fx, x)
	io.Pf("x    = %v  expected = %v\n", x, []float64{0.5, pi})
	io.Pf("f(x) = %v << converges to a different solution\n", fx)
	chk.Vector(tst, "f(x) = 0? ", 1e-8, fx, nil)
}