Example #1
0
func (o *Plotter) Plot_ed_q(x, y []float64, res []*State, sts [][]float64, last bool) {
	nr := len(res)
	if len(sts) != nr {
		return
	}
	k := nr - 1
	for i := 0; i < nr; i++ {
		x[i] = o.Ed[i] * 100.0
		if o.QdivP {
			y[i] = o.Q[i] / o.P[i]
		} else {
			y[i] = o.Q[i]
		}
		if o.Multq {
			y[i] *= fun.Sign(o.W[i])
		}
	}
	plt.Plot(x, y, io.Sf("'r.', ls='%s', clip_on=0, color='%s', marker='%s', label=r'%s'", o.Ls, o.Clr, o.Mrk, o.Lbl))
	plt.PlotOne(x[0], y[0], io.Sf("'bo', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.SpMrk, o.SpMs))
	plt.PlotOne(x[k], y[k], io.Sf("'bs', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.EpMrk, o.EpMs))
	if last {
		ylbl := "$q$"
		if o.QdivP {
			ylbl = "$q/p$"
		}
		plt.Gll("$\\varepsilon_d\\;[\\%]$", ylbl, "leg_out=1, leg_ncol=4, leg_hlen=1.5")
		if lims, ok := o.Lims["ed,q"]; ok {
			plt.AxisLims(lims)
		}
	}
}
Example #2
0
func (o *Plotter) Plot_Dgam_f(x, y []float64, res []*State, sts [][]float64, last bool) {
	if o.m == nil {
		o.set_empty()
		return
	}
	nr := len(res)
	k := nr - 1
	ys := o.m.YieldFuncs(res[0])
	fc0 := ys[0]
	xmi, xma, ymi, yma := res[0].Dgam, res[0].Dgam, fc0, fc0
	for i := 0; i < nr; i++ {
		x[i] = res[i].Dgam
		ys = o.m.YieldFuncs(res[i])
		y[i] = ys[0]
		xmi = min(xmi, x[i])
		xma = max(xma, x[i])
		ymi = min(ymi, y[i])
		yma = max(yma, y[i])
	}
	//o.DrawRamp(xmi, xma, ymi, yma)
	plt.Plot(x, y, io.Sf("'r.', ls='%s', clip_on=0, color='%s', marker='%s', label=r'%s'", o.Ls, o.Clr, o.Mrk, o.Lbl))
	plt.PlotOne(x[0], y[0], io.Sf("'bo', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.SpMrk, o.SpMs))
	plt.PlotOne(x[k], y[k], io.Sf("'bs', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.EpMrk, o.EpMs))
	if last {
		plt.Gll("$\\Delta\\gamma$", "$f$", "")
		if lims, ok := o.Lims["Dgam,f"]; ok {
			plt.AxisLims(lims)
		}
	}
}
Example #3
0
// PlotYxe plots the function y(x) implemented by Cb_yxe
func PlotYxe(ffcn Cb_yxe, dirout, fname string, xsol, xa, xb float64, np int, xsolLbl, args string, save, show bool, extra func()) (err error) {
	if !save && !show {
		return
	}
	x := utl.LinSpace(xa, xb, np)
	y := make([]float64, np)
	for i := 0; i < np; i++ {
		y[i], err = ffcn(x[i])
		if err != nil {
			return
		}
	}
	var ysol float64
	ysol, err = ffcn(xsol)
	if err != nil {
		return
	}
	plt.Cross("")
	plt.Plot(x, y, args)
	plt.PlotOne(xsol, ysol, io.Sf("'ro', label='%s'", xsolLbl))
	if extra != nil {
		extra()
	}
	plt.Gll("x", "y(x)", "")
	if save {
		os.MkdirAll(dirout, 0777)
		plt.Save(dirout + "/" + fname)
	}
	if show {
		plt.Show()
	}
	return
}
Example #4
0
// PlotFltOva plots flt-ova points
func (o *Optimiser) PlotFltOva(sols0 []*Solution, iFlt, iOva int, ovaMult float64, pp *PlotParams) {
	if pp.YfuncX != nil {
		X := utl.LinSpace(o.FltMin[iFlt], o.FltMax[iFlt], pp.NptsYfX)
		Y := make([]float64, pp.NptsYfX)
		for i := 0; i < pp.NptsYfX; i++ {
			Y[i] = pp.YfuncX(X[i])
		}
		plt.Plot(X, Y, pp.FmtYfX.GetArgs(""))
	}
	if sols0 != nil {
		o.PlotAddFltOva(iFlt, iOva, sols0, ovaMult, &pp.FmtSols0)
	}
	o.PlotAddFltOva(iFlt, iOva, o.Solutions, ovaMult, &pp.FmtSols)
	best, _ := GetBestFeasible(o, iOva)
	if best != nil {
		plt.PlotOne(best.Flt[iFlt], best.Ova[iOva]*ovaMult, pp.FmtBest.GetArgs(""))
	}
	if pp.Extra != nil {
		pp.Extra()
	}
	if pp.AxEqual {
		plt.Equal()
	}
	plt.Gll(io.Sf("$x_{%d}$", iFlt), io.Sf("$f_{%d}$", iOva), "leg_out=1, leg_ncol=4, leg_hlen=1.5")
	plt.SaveD(pp.DirOut, pp.FnKey+pp.FnExt)
}
Example #5
0
// run_rootsol_test runs root solution test
//  Note: xguess is the trial solution for Newton's method (not Brent's)
func run_rootsol_test(tst *testing.T, xa, xb, xguess, tolcmp float64, ffcnA Cb_yxe, ffcnB Cb_f, JfcnB Cb_Jd, fname string, save, show bool) (xbrent float64) {

	// Brent
	io.Pfcyan("\n       - - - - - - - using Brent's method - - -- - - - \n")
	var o Brent
	o.Init(ffcnA)
	var err error
	xbrent, err = o.Solve(xa, xb, false)
	if err != nil {
		chk.Panic("%v", err)
	}
	var ybrent float64
	ybrent, err = ffcnA(xbrent)
	if err != nil {
		chk.Panic("%v", err)
	}
	io.Pforan("x      = %v\n", xbrent)
	io.Pforan("f(x)   = %v\n", ybrent)
	io.Pforan("nfeval = %v\n", o.NFeval)
	io.Pforan("nit    = %v\n", o.It)
	if math.Abs(ybrent) > 1e-10 {
		chk.Panic("Brent failed: f(x) = %g > 1e-10\n", ybrent)
	}

	// Newton
	io.Pfcyan("\n       - - - - - - - using Newton's method - - -- - - - \n")
	var p NlSolver
	p.Init(1, ffcnB, nil, JfcnB, true, false, nil)
	xnewt := []float64{xguess}
	var cnd float64
	cnd, err = p.CheckJ(xnewt, 1e-6, true, !chk.Verbose)
	io.Pforan("cond(J) = %v\n", cnd)
	if err != nil {
		chk.Panic("%v", err.Error())
	}
	err = p.Solve(xnewt, false)
	if err != nil {
		chk.Panic("%v", err.Error())
	}
	var ynewt float64
	ynewt, err = ffcnA(xnewt[0])
	if err != nil {
		chk.Panic("%v", err)
	}
	io.Pforan("x      = %v\n", xnewt[0])
	io.Pforan("f(x)   = %v\n", ynewt)
	io.Pforan("nfeval = %v\n", p.NFeval)
	io.Pforan("nJeval = %v\n", p.NJeval)
	io.Pforan("nit    = %v\n", p.It)
	if math.Abs(ynewt) > 1e-9 {
		chk.Panic("Newton failed: f(x) = %g > 1e-10\n", ynewt)
	}

	// compare Brent's and Newton's solutions
	PlotYxe(ffcnA, "results", fname, xbrent, xa, xb, 101, "Brent", "'b-'", save, show, func() {
		plt.PlotOne(xnewt[0], ynewt, "'g+', ms=15, label='Newton'")
	})
	chk.Scalar(tst, "xbrent - xnewt", tolcmp, xbrent, xnewt[0])
	return
}
Example #6
0
func (o *Plotter) Plot_ed_ev(x, y []float64, res []*State, sts [][]float64, last bool) {
	nr := len(sts)
	k := nr - 1
	for i := 0; i < nr; i++ {
		x[i], y[i] = o.Ed[i]*100.0, o.Ev[i]*100.0
	}
	plt.Plot(x, y, io.Sf("'r.', ls='%s', clip_on=0, color='%s', marker='%s', label=r'%s'", o.Ls, o.Clr, o.Mrk, o.Lbl))
	plt.PlotOne(x[0], y[0], io.Sf("'bo', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.SpMrk, o.SpMs))
	plt.PlotOne(x[k], y[k], io.Sf("'bs', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.EpMrk, o.EpMs))
	if last {
		plt.Gll("$\\varepsilon_d\\;[\\%]$", "$\\varepsilon_v\\;[\\%]$", "leg_out=1, leg_ncol=4, leg_hlen=1.5")
		if lims, ok := o.Lims["ed,ev"]; ok {
			plt.AxisLims(lims)
		}
	}
}
Example #7
0
// PlotTwoVarsContour plots contour for two variables problem. len(x) == 2
//  Input
//   dirout  -- directory to save files
//   fnkey   -- file name key for eps figure
//   x       -- solution. can be <nil>
//   np      -- number of points for contour
//   extra   -- called just before saving figure
//   axequal -- axis.equal
//   vmin    -- min 0 values
//   vmax    -- max 1 values
//   f       -- function to plot filled contour. can be <nil>
//   gs      -- functions to plot contour @ level 0. can be <nil>
func PlotTwoVarsContour(dirout, fnkey string, x []float64, np int, extra func(), axequal bool,
	vmin, vmax []float64, f TwoVarsFunc_t, gs ...TwoVarsFunc_t) {
	if fnkey == "" {
		return
	}
	chk.IntAssert(len(vmin), 2)
	chk.IntAssert(len(vmax), 2)
	V0, V1 := utl.MeshGrid2D(vmin[0], vmax[0], vmin[1], vmax[1], np, np)
	var Zf [][]float64
	var Zg [][][]float64
	if f != nil {
		Zf = la.MatAlloc(np, np)
	}
	if len(gs) > 0 {
		Zg = utl.Deep3alloc(len(gs), np, np)
	}
	xtmp := make([]float64, 2)
	for i := 0; i < np; i++ {
		for j := 0; j < np; j++ {
			xtmp[0], xtmp[1] = V0[i][j], V1[i][j]
			if f != nil {
				Zf[i][j] = f(xtmp)
			}
			for k, g := range gs {
				Zg[k][i][j] = g(xtmp)
			}
		}
	}
	plt.Reset()
	plt.SetForEps(0.8, 350)
	if f != nil {
		cmapidx := 0
		plt.Contour(V0, V1, Zf, io.Sf("fsz=7, cmapidx=%d", cmapidx))
	}
	for k, _ := range gs {
		plt.ContourSimple(V0, V1, Zg[k], false, 8, "zorder=5, levels=[0], colors=['yellow'], linewidths=[2], clip_on=0")
	}
	if x != nil {
		plt.PlotOne(x[0], x[1], "'r*', label='optimum', zorder=10")
	}
	if extra != nil {
		extra()
	}
	if dirout == "" {
		dirout = "."
	}
	plt.Cross("clr='grey'")
	plt.SetXnticks(11)
	plt.SetYnticks(11)
	if axequal {
		plt.Equal()
	}
	plt.AxisRange(vmin[0], vmax[0], vmin[1], vmax[1])
	args := "leg_out='1', leg_ncol=4, leg_hlen=1.5"
	plt.Gll("$x_0$", "$x_1$", args)
	plt.SaveD(dirout, fnkey+".eps")
}
Example #8
0
func main() {

	// GA parameters
	C := goga.ReadConfParams("tsp-simple.json")
	rnd.Init(C.Seed)

	// location / coordinates of stations
	locations := [][]float64{
		{60, 200}, {180, 200}, {80, 180}, {140, 180}, {20, 160}, {100, 160}, {200, 160},
		{140, 140}, {40, 120}, {100, 120}, {180, 100}, {60, 80}, {120, 80}, {180, 60},
		{20, 40}, {100, 40}, {200, 40}, {20, 20}, {60, 20}, {160, 20},
	}
	nstations := len(locations)
	C.SetIntOrd(nstations)
	C.CalcDerived()

	// objective value function
	C.OvaOor = func(ind *goga.Individual, idIsland, time int, report *bytes.Buffer) {
		L := locations
		ids := ind.Ints
		dist := 0.0
		for i := 1; i < nstations; i++ {
			a, b := ids[i-1], ids[i]
			dist += math.Sqrt(math.Pow(L[b][0]-L[a][0], 2.0) + math.Pow(L[b][1]-L[a][1], 2.0))
		}
		a, b := ids[nstations-1], ids[0]
		dist += math.Sqrt(math.Pow(L[b][0]-L[a][0], 2.0) + math.Pow(L[b][1]-L[a][1], 2.0))
		ind.Ovas[0] = dist
		return
	}

	// evolver
	nova, noor := 1, 0
	evo := goga.NewEvolver(nova, noor, C)
	evo.Run()

	// results
	io.Pfgreen("best = %v\n", evo.Best.Ints)
	io.Pfgreen("best OVA = %v  (871.117353844847)\n\n", evo.Best.Ovas[0])

	// plot travelling salesman path
	if C.DoPlot {
		plt.SetForEps(1, 300)
		X, Y := make([]float64, nstations), make([]float64, nstations)
		for k, id := range evo.Best.Ints {
			X[k], Y[k] = locations[id][0], locations[id][1]
			plt.PlotOne(X[k], Y[k], "'r.', ms=5, clip_on=0, zorder=20")
			plt.Text(X[k], Y[k], io.Sf("%d", id), "fontsize=7, clip_on=0, zorder=30")
		}
		plt.Plot(X, Y, "'b-', clip_on=0, zorder=10")
		plt.Plot([]float64{X[0], X[nstations-1]}, []float64{Y[0], Y[nstations-1]}, "'b-', clip_on=0, zorder=10")
		plt.Equal()
		plt.AxisRange(10, 210, 10, 210)
		plt.Gll("$x$", "$y$", "")
		plt.SaveD("/tmp/goga", "test_evo04.eps")
	}
}
Example #9
0
// PlotFltFlt plots flt-flt contour
// use iFlt==-1 || jFlt==-1 to plot all combinations
func (o *Optimiser) PlotFltFltContour(sols0 []*Solution, iFlt, jFlt, iOva int, pp *PlotParams) {
	best, _ := GetBestFeasible(o, iOva)
	plotAll := iFlt < 0 || jFlt < 0
	plotCommands := func(i, j int) {
		o.PlotContour(i, j, iOva, pp)
		if sols0 != nil {
			o.PlotAddFltFlt(i, j, sols0, &pp.FmtSols0)
		}
		o.PlotAddFltFlt(i, j, o.Solutions, &pp.FmtSols)
		if best != nil {
			plt.PlotOne(best.Flt[i], best.Flt[j], pp.FmtBest.GetArgs(""))
		}
		if pp.Extra != nil {
			pp.Extra()
		}
		if pp.AxEqual {
			plt.Equal()
		}
	}
	if plotAll {
		idx := 1
		ncol := o.Nflt - 1
		for row := 0; row < o.Nflt; row++ {
			idx += row
			for col := row + 1; col < o.Nflt; col++ {
				plt.Subplot(ncol, ncol, idx)
				plt.SplotGap(0.0, 0.0)
				plotCommands(col, row)
				if col > row+1 {
					plt.SetXnticks(0)
					plt.SetYnticks(0)
				} else {
					plt.Gll(io.Sf("$x_{%d}$", col), io.Sf("$x_{%d}$", row), "leg=0")
				}
				idx++
			}
		}
		idx = ncol*(ncol-1) + 1
		plt.Subplot(ncol, ncol, idx)
		plt.AxisOff()
		// TODO: fix formatting of open marker, add star to legend
		plt.DrawLegend([]plt.Fmt{pp.FmtSols0, pp.FmtSols, pp.FmtBest}, 8, "center", false, "")
	} else {
		plotCommands(iFlt, jFlt)
		if pp.Xlabel == "" {
			plt.Gll(io.Sf("$x_{%d}$", iFlt), io.Sf("$x_{%d}$", jFlt), pp.LegPrms)
		} else {
			plt.Gll(pp.Xlabel, pp.Ylabel, pp.LegPrms)
		}
	}
	plt.SaveD(pp.DirOut, pp.FnKey+pp.FnExt)
}
Example #10
0
func Test_invs05(tst *testing.T) {

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

	if SAVEPLOT {
		plt.Reset()
		plt.SetForPng(1, 500, 125)
		PlotRosette(1.1, true, true, true, 7)
	}

	addtoplot := func(σa, σb float64, σ []float64) {
		plt.PlotOne(σa, σb, "'ro', ms=5")
		plt.Text(σa, σb, io.Sf("$\\sigma_{123}=(%g,%g,%g)$", σ[0], σ[1], σ[2]), "size=8")
	}

	dotest := func(σ []float64, σacor, σbcor, σccor, θcor, tolσ float64) {
		w := M_w(σ)
		θ2 := math.Asin(w) * 180.0 / (3.0 * math.Pi)
		θ3 := M_θ(σ)
		σa, σb, σc := L2O(σ[0], σ[1], σ[2])
		σ0, σ1, σ2 := O2L(σa, σb, σc)
		σI, σA := make([]float64, 3), []float64{σa, σb, σc}
		la.MatVecMul(σI, 1, O2Lmat(), σA) // σI := L * σA
		io.Pf("σa σb σc = %v %v %v\n", σa, σb, σc)
		io.Pf("w        = %v\n", w)
		io.Pf("θ2, θ3   = %v, %v\n", θ2, θ3)
		chk.Scalar(tst, "σa", 1e-17, σa, σacor)
		chk.Scalar(tst, "σb", 1e-17, σb, σbcor)
		chk.Scalar(tst, "σc", 1e-17, σc, σccor)
		chk.Scalar(tst, "σ0", tolσ, σ0, σ[0])
		chk.Scalar(tst, "σ1", tolσ, σ1, σ[1])
		chk.Scalar(tst, "σ2", tolσ, σ2, σ[2])
		chk.Scalar(tst, "σI0", tolσ, σI[0], σ[0])
		chk.Scalar(tst, "σI1", tolσ, σI[1], σ[1])
		chk.Scalar(tst, "σI2", tolσ, σI[2], σ[2])
		chk.Scalar(tst, "θ2", 1e-6, θ2, θcor)
		chk.Scalar(tst, "θ3", 1e-17, θ3, θ2)
		addtoplot(σa, σb, σ)
	}

	dotest([]float64{-1, 0, 0, 0}, 0, 2.0/SQ6, 1.0/SQ3, 30, 1e-15)
	dotest([]float64{0, -1, 0, 0}, 1.0/SQ2, -1.0/SQ6, 1.0/SQ3, 30, 1e-15)
	dotest([]float64{0, 0, -1, 0}, -1.0/SQ2, -1.0/SQ6, 1.0/SQ3, 30, 1e-15)

	if SAVEPLOT {
		plt.Gll("$\\sigma_a$", "$\\sigma_b$", "")
		plt.Equal()
		plt.SaveD("/tmp/gosl", "fig_invs05.png")
	}
}
Example #11
0
// PlotStar plots star with normalised OVAs
func (o *Optimiser) PlotStar() {
	nf := o.Nf
	dθ := 2.0 * math.Pi / float64(nf)
	θ0 := 0.0
	if nf == 3 {
		θ0 = -math.Pi / 6.0
	}
	for _, ρ := range []float64{0.25, 0.5, 0.75, 1.0} {
		plt.Circle(0, 0, ρ, "ec='gray',lw=0.5,zorder=5")
	}
	arrowM, textM := 1.1, 1.15
	for i := 0; i < nf; i++ {
		θ := θ0 + float64(i)*dθ
		xi, yi := 0.0, 0.0
		xf, yf := arrowM*math.Cos(θ), arrowM*math.Sin(θ)
		plt.Arrow(xi, yi, xf, yf, "sc=10,st='->',lw=0.7,zorder=10,clip_on=0")
		plt.PlotOne(xf, yf, "'k+', ms=0")
		xf, yf = textM*math.Cos(θ), textM*math.Sin(θ)
		plt.Text(xf, yf, io.Sf("%d", i), "size=6,zorder=10,clip_on=0")
	}
	X, Y := make([]float64, nf+1), make([]float64, nf+1)
	clr := false
	neg := false
	step := 1
	count := 0
	colors := []string{"m", "orange", "g", "r", "b", "k"}
	var ρ float64
	for i, sol := range o.Solutions {
		if sol.Feasible() && sol.FrontId == 0 && i%step == 0 {
			for j := 0; j < nf; j++ {
				if neg {
					ρ = 1.0 - sol.Ova[j]/(o.RptFmax[j]-o.RptFmin[j])
				} else {
					ρ = sol.Ova[j] / (o.RptFmax[j] - o.RptFmin[j])
				}
				θ := θ0 + float64(j)*dθ
				X[j], Y[j] = ρ*math.Cos(θ), ρ*math.Sin(θ)
			}
			X[nf], Y[nf] = X[0], Y[0]
			if clr {
				j := count % len(colors)
				plt.Plot(X, Y, io.Sf("'k-',color='%s',markersize=3,clip_on=0", colors[j]))
			} else {
				plt.Plot(X, Y, "'r-',marker='.',markersize=3,clip_on=0")
			}
			count++
		}
	}
	plt.Equal()
	plt.AxisOff()
}
Example #12
0
func draw_truss(dat *FemData, key string, A *goga.Solution, lef, bot, wid, hei float64) (weight, deflection float64) {
	gap := 0.1
	plt.PyCmds(io.Sf(`
from pylab import axes, setp, sca
ax_current = gca()
ax_new = axes([%g, %g, %g, %g], axisbg='#dcdcdc')
setp(ax_new, xticks=[0,720], yticks=[0,360])
axis('equal')
axis('off')
`, lef, bot, wid, hei))
	_, _, weight, deflection, _, _, _ = dat.RunFEM(A.Int, A.Flt, 1, false)
	plt.PyCmds("sca(ax_current)\n")
	plt.PlotOne(weight, deflection, "'g*', zorder=1000, clip_on=0")
	plt.Text(weight, deflection+gap, key, "")
	return
}
Example #13
0
// Draw2d draws bins' grid
func (o *Bins) Draw2d(withtxt bool) {

	// horizontal lines
	x := []float64{o.Xi[0], o.Xi[0] + o.L[0] + o.S}
	y := make([]float64, 2)
	for j := 0; j < o.N[1]+1; j++ {
		y[0] = o.Xi[1] + float64(j)*o.S
		y[1] = y[0]
		plt.Plot(x, y, "'-', color='#4f3677', clip_on=0")
	}

	// vertical lines
	y[0] = o.Xi[1]
	y[1] = o.Xi[1] + o.L[1] + o.S
	for i := 0; i < o.N[0]+1; i++ {
		x[0] = o.Xi[0] + float64(i)*o.S
		x[1] = x[0]
		plt.Plot(x, y, "'k-', color='#4f3677', clip_on=0")
	}

	// plot items
	for _, bin := range o.All {
		if bin == nil {
			continue
		}
		for _, entry := range bin.Entries {
			plt.PlotOne(entry.X[0], entry.X[1], "'r.', clip_on=0")
		}
	}

	// labels
	if withtxt {
		for j := 0; j < o.N[1]; j++ {
			for i := 0; i < o.N[0]; i++ {
				idx := i + j*o.N[0]
				x := o.Xi[0] + float64(i)*o.S + 0.02*o.S
				y := o.Xi[1] + float64(j)*o.S + 0.02*o.S
				plt.Text(x, y, io.Sf("%d", idx), "size=7")
			}
		}
	}

	// setup
	plt.Equal()
	plt.AxisRange(o.Xi[0]-0.1, o.Xf[0]+o.S+0.1, o.Xi[1]-0.1, o.Xf[1]+o.S+0.1)
}
Example #14
0
func Test_cubiceq03(tst *testing.T) {

	//verbose()
	chk.PrintTitle("cubiceq03. y(x) = x³ + c")

	doplot := false
	np := 41
	var X, Y []float64
	if doplot {
		X = utl.LinSpace(-2, 2, np)
		Y = make([]float64, np)
		plt.SetForPng(0.8, 400, 200)
	}

	a, b := 0.0, 0.0
	colors := []string{"red", "green", "blue"}
	for k, c := range []float64{-1, 0, 1} {
		x1, x2, x3, nx := EqCubicSolveReal(a, b, c)
		io.Pforan("\na=%v b=%v c=%v\n", a, b, c)
		io.Pfcyan("nx=%v\n", nx)
		io.Pfcyan("x1=%v x2=%v x3=%v\n", x1, x2, x3)
		chk.IntAssert(nx, 1)
		chk.Scalar(tst, "x1", 1e-17, x1, -c)
		if doplot {
			for i, x := range X {
				Y[i] = x*x*x + a*x*x + b*x + c
			}
			plt.Plot(X, Y, io.Sf("color='%s', label='c=%g'", colors[k], c))
			plt.PlotOne(x1, 0, io.Sf("'ko', color='%s'", colors[k]))
			plt.Cross("")
			plt.Gll("x", "y", "")
		}
	}
	if doplot {
		plt.SaveD("/tmp", "fig_cubiceq03.png")
	}
}
Example #15
0
func plot_spo751(fnkey string) {

	// constants
	nidx := 20 // selected node at outer surface
	didx := 0  // selected  dof index for plot
	nels := 4  // number of elements
	nips := 4  // number of ips

	// selected P values for stress plot
	Psel := []float64{100, 140, 180, 190}
	tolPsel := 2.0    // tolerance to compare P
	GPa2MPa := 1000.0 // conversion factor

	// input data
	Pcen := 200.0         // [Mpa]
	a, b := 100.0, 200.0  // [mm], [mm]
	E, ν := 210000.0, 0.3 // [MPa], [-]
	σy := 240.0           // [MPa]

	// analytical solution
	var sol ana.PressCylin
	sol.Init([]*fun.Prm{
		&fun.Prm{N: "a", V: a}, &fun.Prm{N: "b", V: b},
		&fun.Prm{N: "E", V: E}, &fun.Prm{N: "ν", V: ν},
		&fun.Prm{N: "σy", V: σy},
	})
	np := 41
	P_ana, Ub_ana := sol.CalcPressDisp(np)
	R_ana, Sr_ana, St_ana := sol.CalcStresses(Psel, np)

	// read summary
	sum := ReadSum(Global.Dirout, Global.Fnkey)

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

	// gofem results
	nto := len(sum.OutTimes)
	P := make([]float64, nto)
	Ub := make([]float64, nto)
	R := utl.Deep3alloc(len(Psel), nels, nips)
	Sr := utl.Deep3alloc(len(Psel), nels, nips)
	St := utl.Deep3alloc(len(Psel), nels, nips)
	i := 0
	for tidx, t := range sum.OutTimes {

		// read results from file
		if !d.In(sum, tidx, true) {
			io.PfRed("plot_spo751: cannot read solution\n")
			return
		}

		// collect results for load versus displacement plot
		nod := d.Nodes[nidx]
		eq := nod.Dofs[didx].Eq
		P[tidx] = t * Pcen
		Ub[tidx] = d.Sol.Y[eq]

		// stresses
		if isPsel(Psel, P[tidx], tolPsel) {
			for j, ele := range d.ElemIntvars {
				e := ele.(*ElemU)
				ipsdat := e.OutIpsData()
				for k, dat := range ipsdat {
					res := dat.Calc(d.Sol)
					x, y := dat.X[0], dat.X[1]
					sx := res["sx"] * GPa2MPa
					sy := res["sy"] * GPa2MPa
					sxy := res["sxy"] * GPa2MPa / math.Sqrt2
					R[i][j][k], Sr[i][j][k], St[i][j][k], _ = ana.PolarStresses(x, y, sx, sy, sxy)
				}
			}
			i++
		}
	}

	// auxiliary data for plotting stresses
	colors := []string{"r", "m", "g", "k", "y", "c", "r", "m"}
	markers1 := []string{"o", "s", "x", ".", "^", "*", "o", "s"}
	markers2 := []string{"+", "+", "+", "+", "+", "+", "+", "+"}

	// plot load displacements
	plt.SetForEps(0.8, 300)
	if true {
		//if false {
		plt.Plot(Ub_ana, P_ana, "'b-', ms=2, label='solution', clip_on=0")
		plt.Plot(Ub, P, "'r.--', label='fem: outer', clip_on=0")
		plt.Gll("$u_x\\;\\mathrm{[mm]}$", "$P\\;\\mathrm{[MPa]}$", "")
		plt.SaveD("/tmp", io.Sf("gofem_%s_disp.eps", fnkey))
	}

	// plot radial stresses
	if true {
		//if false {
		plt.Reset()
		for i, Pval := range Psel {
			plt.Plot(R_ana, Sr_ana[i], "'b-'")
			for k := 0; k < nips; k++ {
				for j := 0; j < nels; j++ {
					args := io.Sf("'%s%s'", colors[i], markers1[i])
					if k > 1 {
						args = io.Sf("'k%s', ms=10", markers2[i])
					}
					if k == 0 && j == 0 {
						args += io.Sf(", label='P=%g'", Pval)
					}
					plt.PlotOne(R[i][j][k], Sr[i][j][k], args)
				}
			}
		}
		plt.Gll("$r\\;\\mathrm{[mm]}$", "$\\sigma_r\\;\\mathrm{[MPa]}$", "leg_loc='lower right'")
		plt.AxisXrange(a, b)
		plt.SaveD("/tmp", io.Sf("gofem_%s_sr.eps", fnkey))
	}

	// plot tangential stresses
	if true {
		//if false {
		plt.Reset()
		for i, Pval := range Psel {
			plt.Plot(R_ana, St_ana[i], "'b-'")
			for k := 0; k < nips; k++ {
				for j := 0; j < nels; j++ {
					args := io.Sf("'%s%s'", colors[i], markers1[i])
					if k > 1 {
						args = io.Sf("'k%s', ms=10", markers2[i])
					}
					if k == 0 && j == 0 {
						args += io.Sf(", label='P=%g'", Pval)
					}
					plt.PlotOne(R[i][j][k], St[i][j][k], args)
				}
			}
		}
		plt.Gll("$r\\;\\mathrm{[mm]}$", "$\\sigma_t\\;\\mathrm{[MPa]}$", "leg_loc='upper left'")
		plt.SaveD("/tmp", io.Sf("gofem_%s_st.eps", fnkey))
	}
}
Example #16
0
func Test_flt02(tst *testing.T) {

	//verbose()
	chk.PrintTitle("flt02. circle with equality constraint")

	// parameters
	C := NewConfParams()
	C.Eps1 = 1e-3
	C.Pll = false
	C.Nisl = 4
	C.Ninds = 12
	C.Ntrials = 1
	if chk.Verbose {
		C.Ntrials = 40
	}
	C.Verbose = false
	C.Dtmig = 50
	C.CrowdSize = 3
	C.CompProb = false
	C.GAtype = "crowd"
	C.DiffEvol = true
	C.RangeFlt = [][]float64{
		{-1, 3}, // gene # 0: min and max
		{-1, 3}, // gene # 1: min and max
	}
	C.Latin = true
	C.PopFltGen = PopFltGen
	if chk.Verbose {
		C.FnKey = ""
		if C.Ntrials == 1 {
			C.DoPlot = true
		}
	}
	C.Ops.EnfRange = true
	C.NumFmts = map[string][]string{"flt": {"%8.4f", "%8.4f"}}
	C.ShowDem = true
	C.RegTol = 0.01
	C.CalcDerived()
	rnd.Init(C.Seed)

	// geometry
	xe := 1.0                      // centre of circle
	le := -0.4                     // selected level of f(x)
	ys := xe - (1.0+le)/math.Sqrt2 // coordinates of minimum point with level=le
	y0 := 2.0*ys + xe              // vertical axis intersect of straight line defined by c(x)
	xc := []float64{xe, xe}        // centre
	nx := len(xc)

	// functions
	fcn := func(f, g, h []float64, x []float64) {
		res := 0.0
		for i := 0; i < nx; i++ {
			res += (x[i] - xc[i]) * (x[i] - xc[i])
		}
		f[0] = math.Sqrt(res) - 1
		h[0] = x[0] + x[1] + xe - y0
	}

	// simple problem
	sim := NewSimpleFltProb(fcn, 1, 0, 1, C)
	sim.Run(chk.Verbose)

	// stat
	io.Pf("\n")
	sim.Stat(0, 60, -0.4)

	// plot
	sim.PltExtra = func() {
		plt.PlotOne(ys, ys, "'o', markeredgecolor='yellow', markerfacecolor='none', markersize=10")
	}
	sim.Plot("test_flt02")
}
Example #17
0
// Run computes β starting witn an initial guess
func (o *ReliabFORM) Run(βtrial float64, verbose bool, args ...interface{}) (β float64, μ, σ, x []float64) {

	// initial random variables
	β = βtrial
	nx := len(o.μ)
	μ = make([]float64, nx) // mean values (equivalent normal value)
	σ = make([]float64, nx) // deviation values (equivalent normal value)
	x = make([]float64, nx) // current vector of random variables defining min(β)
	for i := 0; i < nx; i++ {
		μ[i] = o.μ[i]
		σ[i] = o.σ[i]
		x[i] = o.μ[i]
	}

	// lognormal distribution structure
	var lnd DistLogNormal

	// has lognormal random variable?
	haslrv := false
	for _, found := range o.lrv {
		if found {
			haslrv = true
			break
		}
	}

	// function to compute β with x-constant
	//  gβ(β) = g(μ - β・A・σ) = 0
	var err error
	gβfcn := func(fy, y []float64) error {
		βtmp := y[0]
		for i := 0; i < nx; i++ {
			o.xtmp[i] = μ[i] - βtmp*o.α[i]*σ[i]
		}
		fy[0], err = o.gfcn(o.xtmp, args)
		if err != nil {
			chk.Panic("cannot compute gfcn(%v):\n%v", o.xtmp, err)
		}
		return nil
	}

	// derivative of gβ w.r.t β
	hβfcn := func(dfdy [][]float64, y []float64) error {
		βtmp := y[0]
		for i := 0; i < nx; i++ {
			o.xtmp[i] = μ[i] - βtmp*o.α[i]*σ[i]
		}
		err = o.hfcn(o.dgdx, o.xtmp, args)
		if err != nil {
			chk.Panic("cannot compute hfcn(%v):\n%v", o.xtmp, err)
		}
		dfdy[0][0] = 0
		for i := 0; i < nx; i++ {
			dfdy[0][0] -= o.dgdx[i] * o.α[i] * σ[i]
		}
		return nil
	}

	// nonlinear solver with y[0] = β
	// solving:  gβ(β) = g(μ - β・A・σ) = 0
	var nls num.NlSolver
	nls.Init(1, gβfcn, nil, hβfcn, true, false, nil)
	defer nls.Clean()

	// message
	if verbose {
		io.Pf("\n%s", io.StrThickLine(60))
	}

	// plotting
	plot := o.PlotFnk != ""
	if nx != 2 {
		plot = false
	}
	if plot {
		if o.PlotNp < 3 {
			o.PlotNp = 41
		}
		var umin, umax, vmin, vmax float64
		if o.PlotCf < 1 {
			o.PlotCf = 2
		}
		if len(o.PlotUrange) == 0 {
			umin, umax = μ[0]-o.PlotCf*μ[0], μ[0]+o.PlotCf*μ[0]
			vmin, vmax = μ[1]-o.PlotCf*μ[1], μ[1]+o.PlotCf*μ[1]
		} else {
			chk.IntAssert(len(o.PlotUrange), 2)
			chk.IntAssert(len(o.PlotVrange), 2)
			umin, umax = o.PlotUrange[0], o.PlotUrange[1]
			vmin, vmax = o.PlotVrange[0], o.PlotVrange[1]
		}
		o.PlotU, o.PlotV = utl.MeshGrid2D(umin, umax, vmin, vmax, o.PlotNp, o.PlotNp)
		o.PlotZ = la.MatAlloc(o.PlotNp, o.PlotNp)
		plt.SetForEps(0.8, 300)
		for i := 0; i < o.PlotNp; i++ {
			for j := 0; j < o.PlotNp; j++ {
				o.xtmp[0] = o.PlotU[i][j]
				o.xtmp[1] = o.PlotV[i][j]
				o.PlotZ[i][j], err = o.gfcn(o.xtmp, args)
				if err != nil {
					chk.Panic("cannot compute gfcn(%v):\n%v", x, err)
				}
			}
		}
		plt.Contour(o.PlotU, o.PlotV, o.PlotZ, "")
		plt.ContourSimple(o.PlotU, o.PlotV, o.PlotZ, true, 8, "levels=[0], colors=['yellow']")
		plt.PlotOne(x[0], x[1], "'ro', label='initial'")
	}

	// iterations to find β
	var dat VarData
	B := []float64{β}
	itB := 0
	for itB = 0; itB < o.NmaxItB; itB++ {

		// message
		if verbose {
			gx, err := o.gfcn(x, args)
			if err != nil {
				chk.Panic("cannot compute gfcn(%v):\n%v", x, err)
			}
			io.Pf("%s itB=%d β=%g g=%g\n", io.StrThinLine(60), itB, β, gx)
		}

		// plot
		if plot {
			plt.PlotOne(x[0], x[1], "'r.'")
		}

		// compute direction cosines
		itA := 0
		for itA = 0; itA < o.NmaxItA; itA++ {

			// has lognormal random variable (lrv)
			if haslrv {

				// find equivalent normal mean and std deviation for lognormal variables
				for i := 0; i < nx; i++ {
					if o.lrv[i] {

						// set distribution
						dat.M, dat.S = o.μ[i], o.σ[i]
						lnd.Init(&dat)

						// update μ and σ
						fx := lnd.Pdf(x[i])
						Φinvx := (math.Log(x[i]) - lnd.M) / lnd.S
						φx := math.Exp(-Φinvx*Φinvx/2.0) / math.Sqrt2 / math.SqrtPi
						σ[i] = φx / fx
						μ[i] = x[i] - Φinvx*σ[i]
					}
				}
			}

			// compute direction cosines
			err = o.hfcn(o.dgdx, x, args)
			if err != nil {
				chk.Panic("cannot compute hfcn(%v):\n%v", x, err)
			}
			den := 0.0
			for i := 0; i < nx; i++ {
				den += math.Pow(o.dgdx[i]*σ[i], 2.0)
			}
			den = math.Sqrt(den)
			αerr := 0.0 // difference on α
			for i := 0; i < nx; i++ {
				αnew := o.dgdx[i] * σ[i] / den
				αerr += math.Pow(αnew-o.α[i], 2.0)
				o.α[i] = αnew
			}
			αerr = math.Sqrt(αerr)

			// message
			if verbose {
				io.Pf(" itA=%d\n", itA)
				io.Pf("%12s%12s%12s%12s\n", "x", "μ", "σ", "α")
				for i := 0; i < nx; i++ {
					io.Pf("%12.3f%12.3f%12.3f%12.3f\n", x[i], μ[i], σ[i], o.α[i])
				}
			}

			// update x-star
			for i := 0; i < nx; i++ {
				x[i] = μ[i] - β*o.α[i]*σ[i]
			}

			// check convergence on α
			if itA > 1 && αerr < o.TolA {
				if verbose {
					io.Pfgrey(". . . converged on α with αerr=%g . . .\n", αerr)
				}
				break
			}
		}

		// failed to converge on α
		if itA == o.NmaxItA {
			chk.Panic("failed to convege on α")
		}

		// compute new β
		B[0] = β
		nls.Solve(B, o.NlsSilent)
		βerr := math.Abs(B[0] - β)
		β = B[0]
		if o.NlsCheckJ {
			nls.CheckJ(B, o.NlsCheckJtol, true, false)
		}

		// update x-star
		for i := 0; i < nx; i++ {
			x[i] = μ[i] - β*o.α[i]*σ[i]
		}

		// check convergence on β
		if βerr < o.TolB {
			if verbose {
				io.Pfgrey2(". . . converged on β with βerr=%g . . .\n", βerr)
			}
			break
		}
	}

	// failed to converge on β
	if itB == o.NmaxItB {
		chk.Panic("failed to converge on β")
	}

	// message
	if verbose {
		gx, err := o.gfcn(x, args)
		if err != nil {
			chk.Panic("cannot compute gfcn(%v):\n%v", x, err)
		}
		io.Pfgreen("x = %v\n", x)
		io.Pfgreen("g = %v\n", gx)
		io.PfGreen("β = %v\n", β)
	}

	// plot
	if plot {
		plt.Gll("$x_0$", "$x_1$", "")
		plt.Cross("")
		plt.SaveD("/tmp/gosl", "fig_form_"+o.PlotFnk+".eps")
	}
	return
}
Example #18
0
// Plot plots contour
func (o *SimpleFltProb) Plot(fnkey string) {

	// check
	if !o.C.DoPlot {
		return
	}

	// limits and meshgrid
	xmin, xmax := o.C.RangeFlt[0][0], o.C.RangeFlt[0][1]
	ymin, ymax := o.C.RangeFlt[1][0], o.C.RangeFlt[1][1]

	// auxiliary variables
	X, Y := utl.MeshGrid2D(xmin, xmax, ymin, ymax, o.PltNpts, o.PltNpts)
	Zf := utl.DblsAlloc(o.PltNpts, o.PltNpts)
	var Zg [][][]float64
	var Zh [][][]float64
	if o.ng > 0 {
		Zg = utl.Deep3alloc(o.ng, o.PltNpts, o.PltNpts)
	}
	if o.nh > 0 {
		Zh = utl.Deep3alloc(o.nh, o.PltNpts, o.PltNpts)
	}

	// compute values
	x := make([]float64, 2)
	for i := 0; i < o.PltNpts; i++ {
		for j := 0; j < o.PltNpts; j++ {
			x[0], x[1] = X[i][j], Y[i][j]
			o.Fcn(o.ff[0], o.gg[0], o.hh[0], x)
			Zf[i][j] = o.ff[0][o.PltIdxF]
			for k, g := range o.gg[0] {
				Zg[k][i][j] = g
			}
			for k, h := range o.hh[0] {
				Zh[k][i][j] = h
			}
		}
	}

	// prepare plot area
	plt.Reset()
	plt.SetForEps(0.8, 350)

	// plot f
	if o.PltArgs != "" {
		o.PltArgs = "," + o.PltArgs
	}
	if o.PltCsimple {
		plt.ContourSimple(X, Y, Zf, true, 7, "colors=['k'], fsz=7"+o.PltArgs)
	} else {
		plt.Contour(X, Y, Zf, io.Sf("fsz=7, cmapidx=%d"+o.PltArgs, o.PltCmapIdx))
	}

	// plot g
	clr := "yellow"
	if o.PltCsimple {
		clr = "blue"
	}
	for _, g := range Zg {
		plt.ContourSimple(X, Y, g, false, 7, io.Sf("zorder=5, levels=[0], colors=['%s'], linewidths=[%g], clip_on=0", clr, o.PltLwg))
	}

	// plot h
	clr = "yellow"
	if o.PltCsimple {
		clr = "blue"
	}
	for _, h := range Zh {
		plt.ContourSimple(X, Y, h, false, 7, io.Sf("zorder=5, levels=[0], colors=['%s'], linewidths=[%g], clip_on=0", clr, o.PltLwh))
	}

	// initial populations
	l := "initial population"
	for _, pop := range o.PopsIni {
		for _, ind := range pop {
			x := ind.GetFloats()
			plt.PlotOne(x[0], x[1], io.Sf("'k.', zorder=20, clip_on=0, label='%s'", l))
			l = ""
		}
	}

	// final populations
	l = "final population"
	for _, pop := range o.PopsBest {
		for _, ind := range pop {
			x := ind.GetFloats()
			plt.PlotOne(x[0], x[1], io.Sf("'ko', ms=6, zorder=30, clip_on=0, label='%s', markerfacecolor='none'", l))
			l = ""
		}
	}

	// extra
	if o.PltExtra != nil {
		o.PltExtra()
	}

	// best result
	if o.Nfeasible > 0 {
		x, _, _, _ := o.find_best()
		plt.PlotOne(x[0], x[1], "'m*', zorder=50, clip_on=0, label='best', markeredgecolor='m'")
	}

	// save figure
	plt.Cross("clr='grey'")
	if o.PltAxEqual {
		plt.Equal()
	}
	plt.AxisRange(xmin, xmax, ymin, ymax)
	plt.Gll("$x_0$", "$x_1$", "leg_out=1, leg_ncol=4, leg_hlen=1.5")
	plt.SaveD(o.PltDirout, fnkey+".eps")
}
Example #19
0
// Check checks derivatives
func Check(tst *testing.T, mdl Model, pc0, sl0, pcf float64, npts int, tolCc, tolD1a, tolD1b, tolD2a, tolD2b float64, verbose bool, pcSkip []float64, tolSkip float64, doplot bool) {

	// nonrate model
	nr_mdl, is_nonrate := mdl.(Nonrate)
	io.Pforan("is_nonrate = %v\n", is_nonrate)

	// for all pc stations
	Pc := utl.LinSpace(pc0, pcf, npts)
	Sl := make([]float64, npts)
	Sl[0] = sl0
	var err error
	for i := 1; i < npts; i++ {

		// update and plot
		Sl[i], err = Update(mdl, Pc[i-1], Sl[i-1], Pc[i]-Pc[i-1])
		if err != nil {
			tst.Errorf("Update failed: %v\n", err)
			return
		}
		if doplot {
			plt.PlotOne(Pc[i], Sl[i], "'ko', clip_on=0")
		}

		// skip point on checking of derivatives
		if doskip(Pc[i], pcSkip, tolSkip) {
			continue
		}

		// wetting flag
		wet := Pc[i]-Pc[i-1] < 0

		// check Cc = dsl/dpc
		io.Pforan("\npc=%g, sl=%g, wetting=%v\n", Pc[i], Sl[i], wet)
		if is_nonrate {

			// analytical Cc
			Cc_ana, err := mdl.Cc(Pc[i], Sl[i], wet)
			if err != nil {
				tst.Errorf("Cc failed: %v\n", err)
				return
			}

			// numerical Cc
			Cc_num, _ := num.DerivCentral(func(x float64, args ...interface{}) float64 {
				return nr_mdl.Sl(x)
			}, Pc[i], 1e-3)
			chk.AnaNum(tst, "Cc = ∂sl/∂pc    ", tolCc, Cc_ana, Cc_num, verbose)
		}

		// compute all derivatives
		L, Lx, J, Jx, Jy, err := mdl.Derivs(Pc[i], Sl[i], wet)
		if err != nil {
			tst.Errorf("Derivs failed: %v\n", err)
			return
		}
		L_ana_A := L
		L_ana_B, err := mdl.L(Pc[i], Sl[i], wet)
		if err != nil {
			tst.Errorf("L failed: %v\n", err)
			return
		}
		Lx_ana := Lx
		Jx_ana := Jx
		Jy_ana := Jy
		J_ana_A := J
		J_ana_B, err := mdl.J(Pc[i], Sl[i], wet)
		if err != nil {
			tst.Errorf("J failed: %v\n", err)
			return
		}

		// numerical L = ∂Cc/∂pc
		L_num, _ := num.DerivCentral(func(x float64, args ...interface{}) float64 {
			Cctmp, _ := mdl.Cc(x, Sl[i], wet)
			return Cctmp
		}, Pc[i], 1e-3)
		chk.AnaNum(tst, "L  = ∂Cc/∂pc    ", tolD1a, L_ana_A, L_num, verbose)

		// numerical Lx := ∂²Cc/∂pc²
		Lx_num, _ := num.DerivCentral(func(x float64, args ...interface{}) float64 {
			Ltmp, _, _, _, _, _ := mdl.Derivs(x, Sl[i], wet)
			return Ltmp
		}, Pc[i], 1e-3)
		chk.AnaNum(tst, "Lx = ∂²Cc/∂pc²  ", tolD2a, Lx_ana, Lx_num, verbose)

		// numerical J := ∂Cc/∂sl (version A)
		J_num, _ := num.DerivCentral(func(x float64, args ...interface{}) float64 {
			Ccval, _ := mdl.Cc(Pc[i], x, wet)
			return Ccval
		}, Sl[i], 1e-3)
		chk.AnaNum(tst, "J  = ∂Cc/∂sl    ", tolD1b, J_ana_A, J_num, verbose)

		// numerical Jx := ∂²Cc/(∂pc ∂sl)
		Jx_num, _ := num.DerivCentral(func(x float64, args ...interface{}) float64 {
			Ltmp, _, _, _, _, _ := mdl.Derivs(Pc[i], x, wet)
			return Ltmp
		}, Sl[i], 1e-3)
		chk.AnaNum(tst, "Jx = ∂²Cc/∂pc∂sl", tolD2b, Jx_ana, Jx_num, verbose)

		// numerical Jy := ∂²Cc/∂sl²
		Jy_num, _ := num.DerivCentral(func(x float64, args ...interface{}) float64 {
			Jtmp, _ := mdl.J(Pc[i], x, wet)
			return Jtmp
		}, Sl[i], 1e-3)
		chk.AnaNum(tst, "Jy = ∂²Cc/∂sl²  ", tolD2b, Jy_ana, Jy_num, verbose)

		// check A and B derivatives
		chk.Scalar(tst, "L_A == L_B", 1e-17, L_ana_A, L_ana_B)
		chk.Scalar(tst, "J_A == J_B", 1e-17, J_ana_A, J_ana_B)
	}
}
Example #20
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
}
Example #21
0
func Test_mdl01(tst *testing.T) {

	//verbose()
	//doplot := true
	doplot := false
	chk.PrintTitle("mdl01")

	// info
	simfnk := "mdl01"
	matname := "mat1"
	getnew := false
	example := true

	// conductivity model
	cnd := mconduct.GetModel(simfnk, matname, "m1", getnew)
	err := cnd.Init(cnd.GetPrms(example))
	if err != nil {
		tst.Errorf("mconduct.Init failed: %v\n", err)
		return
	}

	// liquid retention model
	lrm_name := "ref-m1"
	//lrm_name := "vg"
	lrm := mreten.GetModel(simfnk, matname, lrm_name, getnew)
	err = lrm.Init(lrm.GetPrms(example))
	if err != nil {
		tst.Errorf("mreten.Init failed: %v\n", err)
		return
	}

	// porous model
	mdl := GetModel(simfnk, matname, getnew)
	err = mdl.Init(mdl.GetPrms(example), cnd, lrm)
	if err != nil {
		tst.Errorf("mporous.Init failed: %v\n", err)
		return
	}
	//mdl.MEtrial = false
	mdl.ShowR = true

	// initial and final values
	pc0 := -5.0
	sl0 := 1.0
	pcf := 20.0

	// plot lrm
	if doplot {
		npts := 41
		plt.Reset()
		mreten.Plot(mdl.Lrm, pc0, sl0, pcf, npts, "'b.-'", "'r+-'", lrm_name)
	}

	// state A
	pcA := 5.0
	A, err := mdl.NewState(mdl.RhoL0, mdl.RhoG0, -pcA, 0)
	if err != nil {
		tst.Errorf("mporous.NewState failed: %v\n", err)
		return
	}

	// state B
	pcB := 10.0
	B, err := mdl.NewState(mdl.RhoL0, mdl.RhoG0, -pcB, 0)
	if err != nil {
		tst.Errorf("mporous.NewState failed: %v\n", err)
		return
	}

	// plot A and B points
	if doplot {
		plt.PlotOne(pcA, A.A_sl, "'gs', clip_on=0, label='A', ms=10")
		plt.PlotOne(pcB, B.A_sl, "'ks', clip_on=0, label='B'")
	}

	// incremental update
	//Δpl := -20.0 // << problems with this one and VG
	Δpl := -5.0
	n := 23
	iwet := 10
	Pc := make([]float64, n)
	Sl := make([]float64, n)
	pl := -pcA
	Pc[0] = pcA
	Sl[0] = A.A_sl
	for i := 1; i < n; i++ {
		if i > iwet {
			Δpl = -Δpl
			iwet = n
		}
		pl += Δpl
		err = mdl.Update(A, Δpl, 0, pl, 0)
		if err != nil {
			tst.Errorf("test failed: %v\n", err)
			return
		}
		Pc[i] = -pl
		Sl[i] = A.A_sl
	}

	// show graph
	if doplot {
		plt.Plot(Pc, Sl, "'ro-', clip_on=0, label='update'")
		mreten.PlotEnd(true)
	}
}
Example #22
0
// Draw2d draws bins' grid
func (o *Bins) Draw2d(withtxt, withgrid, withentries, setup bool, selBins map[int]bool) {

	if withgrid {
		// horizontal lines
		x := []float64{o.Xi[0], o.Xi[0] + o.L[0] + o.S[0]}
		y := make([]float64, 2)
		for j := 0; j < o.N[1]+1; j++ {
			y[0] = o.Xi[1] + float64(j)*o.S[1]
			y[1] = y[0]
			plt.Plot(x, y, "'-', color='#4f3677', clip_on=0")
		}

		// vertical lines
		y[0] = o.Xi[1]
		y[1] = o.Xi[1] + o.L[1] + o.S[1]
		for i := 0; i < o.N[0]+1; i++ {
			x[0] = o.Xi[0] + float64(i)*o.S[0]
			x[1] = x[0]
			plt.Plot(x, y, "'k-', color='#4f3677', clip_on=0")
		}
	}

	// selected bins
	nxy := o.N[0] * o.N[1]
	for idx, _ := range selBins {
		i := idx % o.N[0] // indices representing bin
		j := (idx % nxy) / o.N[0]
		x := o.Xi[0] + float64(i)*o.S[0] // coordinates of bin corner
		y := o.Xi[1] + float64(j)*o.S[1]
		plt.DrawPolyline([][]float64{
			{x, y},
			{x + o.S[0], y},
			{x + o.S[0], y + o.S[1]},
			{x, y + o.S[1]},
		}, &plt.Sty{Fc: "#fbefdc", Ec: "#8e8371", Lw: 0.5, Closed: true}, "clip_on=0")
	}

	// plot items
	if withentries {
		for _, bin := range o.All {
			if bin == nil {
				continue
			}
			for _, entry := range bin.Entries {
				plt.PlotOne(entry.X[0], entry.X[1], "'r.', clip_on=0")
			}
		}
	}

	// labels
	if withtxt {
		for j := 0; j < o.N[1]; j++ {
			for i := 0; i < o.N[0]; i++ {
				idx := i + j*o.N[0]
				x := o.Xi[0] + float64(i)*o.S[0] + 0.02*o.S[0]
				y := o.Xi[1] + float64(j)*o.S[1] + 0.02*o.S[1]
				plt.Text(x, y, io.Sf("%d", idx), "size=7")
			}
		}
	}

	// setup
	if setup {
		plt.Equal()
		plt.AxisRange(o.Xi[0]-0.1, o.Xf[0]+o.S[0]+0.1, o.Xi[1]-0.1, o.Xf[1]+o.S[1]+0.1)
	}
}
Example #23
0
func (o *Plotter) Plot_oct(x, y []float64, res []*State, sts [][]float64, last bool) {
	// stress path
	nr := len(res)
	k := nr - 1
	var σa, σb, xmi, xma, ymi, yma float64
	for i := 0; i < nr; i++ {
		σa, σb, _ = tsr.PQW2O(o.P[i], o.Q[i], o.W[i])
		x[i], y[i] = σa, σb
		o.maxR = max(o.maxR, math.Sqrt(σa*σa+σb*σb))
		if i == 0 {
			xmi, xma = x[i], x[i]
			ymi, yma = y[i], y[i]
		} else {
			xmi = min(xmi, x[i])
			xma = max(xma, x[i])
			ymi = min(ymi, y[i])
			yma = max(yma, y[i])
		}
	}
	plt.Plot(x, y, io.Sf("'r.', ls='%s', clip_on=0, color='%s', marker='%s', label=r'%s'", o.Ls, o.Clr, o.Mrk, o.Lbl))
	plt.PlotOne(x[0], y[0], io.Sf("'bo', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.SpMrk, o.SpMs))
	plt.PlotOne(x[k], y[k], io.Sf("'bs', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.EpMrk, o.EpMs))
	// fix range and max radius
	xmi, xma, ymi, yma = o.fix_range(0, xmi, xma, ymi, yma)
	rr := math.Sqrt((xma-xmi)*(xma-xmi) + (yma-ymi)*(yma-ymi))
	if o.maxR < rr {
		o.maxR = rr
	}
	if o.maxR < 1e-10 {
		o.maxR = 1
	}
	if yma > -xmi {
		xmi = -yma
	}
	if o.OctLims != nil {
		xmi, xma, ymi, yma = o.OctLims[0], o.OctLims[1], o.OctLims[2], o.OctLims[3]
	}
	//xmi, xma, ymi, yma = -20000, 20000, -20000, 20000
	// yield surface
	var σcmax float64
	if o.WithYs && o.m != nil {
		//io.Pforan("xmi,xma ymi,yma = %v,%v %v,%v\n", xmi,xma, ymi,yma)
		dx := (xma - xmi) / float64(o.NptsOct-1)
		dy := (yma - ymi) / float64(o.NptsOct-1)
		xx := la.MatAlloc(o.NptsOct, o.NptsOct)
		yy := la.MatAlloc(o.NptsOct, o.NptsOct)
		zz := la.MatAlloc(o.NptsOct, o.NptsOct)
		var λ0, λ1, λ2, σc float64
		v := NewState(len(res[0].Sig), len(res[0].Alp), false, len(res[0].EpsE) > 0)
		for k := 0; k < nr; k++ {
			copy(v.Alp, res[k].Alp)
			v.Dgam = res[k].Dgam
			σc = tsr.M_p(res[k].Sig) * tsr.SQ3
			//σc = 30000
			σcmax = max(σcmax, σc)
			for i := 0; i < o.NptsOct; i++ {
				for j := 0; j < o.NptsOct; j++ {
					xx[i][j] = xmi + float64(i)*dx
					yy[i][j] = ymi + float64(j)*dy
					λ0, λ1, λ2 = tsr.O2L(xx[i][j], yy[i][j], σc)
					v.Sig[0], v.Sig[1], v.Sig[2] = λ0, λ1, λ2
					ys := o.m.YieldFuncs(v)
					zz[i][j] = ys[0]
				}
			}
			plt.ContourSimple(xx, yy, zz, io.Sf("colors=['%s'], levels=[0], linestyles=['%s'], linewidths=[%g], clip_on=0", o.YsClr0, o.YsLs0, o.YsLw0)+o.ArgsYs)

		}
	}
	// predictor-corrector
	if len(o.PreCor) > 1 {
		var σa, σb, σanew, σbnew float64
		for i := 1; i < len(o.PreCor); i++ {
			σa, σb, _ = tsr.M_oct(o.PreCor[i-1])
			σanew, σbnew, _ = tsr.M_oct(o.PreCor[i])
			if math.Abs(σanew-σa) > 1e-7 || math.Abs(σbnew-σb) > 1e-7 {
				//plt.Plot([]float64{σa,σanew}, []float64{σb,σbnew}, "'k+', ms=3, color='k'")
				plt.Arrow(σa, σb, σanew, σbnew, io.Sf("sc=%d, fc='%s', ec='%s'", o.ArrWid, o.ClrPC, o.ClrPC))
			}
			o.maxR = max(o.maxR, math.Sqrt(σa*σa+σb*σb))
			o.maxR = max(o.maxR, math.Sqrt(σanew*σanew+σbnew*σbnew))
		}
	}
	// rosette and settings
	if last {
		tsr.PlotRefOct(o.Phi, σcmax, true)
		tsr.PlotRosette(o.maxR, false, true, true, 6)
		if o.OctAxOff {
			plt.AxisOff()
		}
		plt.Gll("$\\sigma_a$", "$\\sigma_b$", "")
		if lims, ok := o.Lims["oct"]; ok {
			plt.AxisLims(lims)
		}
		if lims, ok := o.Lims["oct,ys"]; ok {
			plt.AxisLims(lims)
		}
	}
}
Example #24
0
func Test_hyperelast01(tst *testing.T) {

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

	var m HyperElast1
	m.Init(2, false, []*fun.Prm{
		&fun.Prm{N: "kap", V: 0.05},
		&fun.Prm{N: "kapb", V: 20.0},
		&fun.Prm{N: "G0", V: 10000},
		&fun.Prm{N: "pr", V: 2.0},
		&fun.Prm{N: "pt", V: 10.0},
	})
	io.Pforan("m = %+v\n", m)
	pr := m.pr
	pt := m.pt

	np := 21
	Ev := utl.LinSpace(0, -0.2, np)
	P := make([]float64, np)
	Q := make([]float64, np)
	X := make([]float64, np)

	for j, ed := range []float64{0, 0.05, 0.1, 0.15, 0.2} {
		for i, ev := range Ev {
			P[i], Q[i] = m.Calc_pq(ev, ed)
			X[i] = math.Log(1.0 + (P[i]+pt)/pr)
		}
		slope := (Ev[0] - Ev[np-1]) / (X[np-1] - X[0])
		xm := (X[0] + X[np-1]) / 2.0
		ym := (Ev[0]+Ev[np-1])/2.0 - float64(j)*0.01

		plt.Subplot(3, 2, 1)
		plt.Plot(P, Ev, io.Sf("label='$\\\\varepsilon_d=%g$'", ed))
		plt.PlotOne(P[0], Ev[0], "'ro', clip_on=0")
		plt.Gll("$p$", "$\\varepsilon_v$", "")

		plt.Subplot(3, 2, 3)
		plt.Plot(X, Ev, "")
		plt.PlotOne(X[0], Ev[0], "'ro', clip_on=0")
		plt.Text(xm, ym, io.Sf("slope=%g", slope), "")
		plt.Gll("$x=\\log{[1+(p+p_t)/p_r]}$", "$\\varepsilon_v$", "")

		plt.Subplot(3, 2, 5)
		plt.Plot(Q, Ev, "")
		plt.PlotOne(Q[0], Ev[0], "'ro', clip_on=0")
		plt.Gll("$q$", "$\\varepsilon_v$", "")
	}

	Ed := utl.LinSpace(0, -0.2, np)

	for j, ev := range []float64{0, -0.05, -0.1, -0.15, -0.2} {
		for i, ed := range Ed {
			P[i], Q[i] = m.Calc_pq(ev, ed)
			X[i] = math.Log(1.0 + (P[i]+pt)/pr)
		}
		slope := (Ed[0] - Ed[np-1]) / (Q[np-1] - Q[0])
		xm := (Q[0] + Q[np-1]) / 2.0
		ym := (Ed[0]+Ed[np-1])/2.0 - float64(j)*0.01

		plt.Subplot(3, 2, 2)
		plt.Plot(P, Ed, io.Sf("label='$\\\\varepsilon_v=%g$'", ev))
		plt.PlotOne(P[0], Ed[0], "'ro', clip_on=0")
		plt.Gll("$p$", "$\\varepsilon_d$", "")

		plt.Subplot(3, 2, 4)
		plt.Plot(X, Ed, "")
		plt.PlotOne(X[0], Ed[0], "'ro', clip_on=0")
		plt.Gll("$x=\\log{[1+(p+p_t)/p_r]}$", "$\\varepsilon_d$", "")

		plt.Subplot(3, 2, 6)
		plt.Plot(Q, Ed, "")
		plt.PlotOne(Q[0], Ed[0], "'ro', clip_on=0")
		plt.Text(xm, ym, io.Sf("slope=%g", slope), "")
		plt.Gll("$q$", "$\\varepsilon_d$", "")
	}

	//plt.Show()
}
Example #25
0
func (o *Plotter) Plot_p_ev(x, y []float64, res []*State, sts [][]float64, last bool) {
	nr := len(res)
	if len(sts) != nr {
		return
	}
	k := nr - 1
	var x0, x1 []float64
	if !o.NoAlp {
		x0, x1 = make([]float64, nr), make([]float64, nr)
	}
	withα := false
	if o.LogP {
		xmin := o.calc_x(o.P[0])
		xmax := xmin
		for i := 0; i < nr; i++ {
			x[i], y[i] = o.calc_x(o.P[i]), o.Ev[i]*100.0
			if !o.NoAlp && len(res[i].Alp) > 0 {
				withα = true
				x0[i] = o.calc_x(res[i].Alp[0])
				if o.nsurf > 1 {
					x1[i] = o.calc_x(res[i].Alp[1])
				}
			}
			xmin = min(xmin, x[i])
			xmax = max(xmax, x[i])
		}
	} else {
		xmin := o.P[0]
		xmax := xmin
		for i := 0; i < nr; i++ {
			x[i], y[i] = o.P[i], o.Ev[i]*100.0
			if !o.NoAlp && len(res[i].Alp) > 0 {
				withα = true
				x0[i] = res[i].Alp[0]
				if o.nsurf > 1 {
					x1[i] = res[i].Alp[1]
				}
			}
			xmin = min(xmin, x[i])
			xmax = max(xmax, x[i])
		}
	}
	if withα {
		plt.Plot(x0, y, io.Sf("'r-', ls='--', lw=3, clip_on=0, color='grey', label=r'%s'", o.Lbl+" $\\alpha_0$"))
		if o.nsurf > 1 {
			plt.Plot(x1, y, io.Sf("'r-', ls=':', lw=3, clip_on=0, color='grey', label=r'%s'", o.Lbl+" $\\alpha_1$"))
		}
	}
	plt.Plot(x, y, io.Sf("'r.', ls='-', clip_on=0, color='%s', marker='%s', label=r'%s'", o.Clr, o.Mrk, o.Lbl))
	plt.PlotOne(x[0], y[0], io.Sf("'bo', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.SpMrk, o.SpMs))
	plt.PlotOne(x[k], y[k], io.Sf("'bs', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.EpMrk, o.EpMs))
	if last {
		xlbl := "$p$"
		if o.LogP {
			xlbl = "$\\log{[1+(p+p_t)/p_r]}$"
		}
		plt.Gll(xlbl, "$\\varepsilon_v\\;[\\%]$", "leg_out=1, leg_ncol=4, leg_hlen=2")
		if lims, ok := o.Lims["p,ev"]; ok {
			plt.AxisLims(lims)
		}
	}
}
Example #26
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 = 1
	opt.Tf = 500
	opt.Verbose = false
	opt.Nsamples = 2
	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
	var fmin, fmax []float64
	var nf, ng, nh int
	var fcn goga.MinProb_t

	// problems
	switch problem {

	// problem # 1 -- ZDT1, Deb 2001, p356
	case 1:
		opt.Ncpu = 6
		opt.RptName = "ZDT1"
		n := 30
		opt.FltMin = make([]float64, n)
		opt.FltMax = make([]float64, n)
		for i := 0; i < n; i++ {
			opt.FltMin[i] = 0
			opt.FltMax[i] = 1
		}
		nf, ng, nh = 2, 0, 0
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			f[0] = x[0]
			sum := 0.0
			for i := 1; i < n; i++ {
				sum += x[i]
			}
			c0 := 1.0 + 9.0*sum/float64(n-1)
			c1 := 1.0 - math.Sqrt(f[0]/c0)
			f[1] = c0 * c1
		}
		fmin = []float64{0, 0}
		fmax = []float64{1, 1}
		opt.F1F0_func = func(f0 float64) float64 {
			return 1.0 - math.Sqrt(f0)
		}
		// arc length = sqrt(5)/2 + log(sqrt(5)+2)/4 ≈ 1.4789428575445975
		opt.F1F0_arcLenRef = math.Sqrt(5.0)/2.0 + math.Log(math.Sqrt(5.0)+2.0)/4.0

	// problem # 2 -- ZDT2, Deb 2001, p356
	case 2:
		opt.Ncpu = 6
		opt.RptName = "ZDT2"
		n := 30
		opt.FltMin = make([]float64, n)
		opt.FltMax = make([]float64, n)
		for i := 0; i < n; i++ {
			opt.FltMin[i] = 0
			opt.FltMax[i] = 1
		}
		nf, ng, nh = 2, 0, 0
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			f[0] = x[0]
			sum := 0.0
			for i := 1; i < n; i++ {
				sum += x[i]
			}
			c0 := 1.0 + 9.0*sum/float64(n-1)
			c1 := 1.0 - math.Pow(f[0]/c0, 2.0)
			f[1] = c0 * c1
		}
		fmin = []float64{0, 0}
		fmax = []float64{1, 1}
		opt.F1F0_func = func(f0 float64) float64 {
			return 1.0 - math.Pow(f0, 2.0)
		}
		// arc length = sqrt(5)/2 + log(sqrt(5)+2)/4 ≈ 1.4789428575445975
		opt.F1F0_arcLenRef = math.Sqrt(5.0)/2.0 + math.Log(math.Sqrt(5.0)+2.0)/4.0

	// problem # 3 -- ZDT3, Deb 2001, p356
	case 3:
		opt.Ncpu = 6
		opt.RptName = "ZDT3"
		n := 30
		opt.FltMin = make([]float64, n)
		opt.FltMax = make([]float64, n)
		for i := 0; i < n; i++ {
			opt.FltMin[i] = 0
			opt.FltMax[i] = 1
		}
		nf, ng, nh = 2, 0, 0
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			f[0] = x[0]
			sum := 0.0
			for i := 1; i < n; i++ {
				sum += x[i]
			}
			c0 := 1.0 + 9.0*sum/float64(n-1)
			c1 := 1.0 - math.Sqrt(f[0]/c0) - math.Sin(10.0*math.Pi*f[0])*f[0]/c0
			f[1] = c0 * c1
		}
		fmin = []float64{0, -1}
		fmax = []float64{1, 1}
		opt.F1F0_func = func(f0 float64) float64 {
			return 1.0 - math.Sqrt(f0) - math.Sin(10.0*math.Pi*f0)*f0
		}
		opt.F1F0_f0ranges = [][]float64{
			{0.000000100000000, 0.083001534925223},
			{0.182228728029413, 0.257762363387862},
			{0.409313674808657, 0.453882104088830},
			{0.618396794416602, 0.652511703804663},
			{0.823331798326633, 0.851832865436414},
		}
		opt.F1F0_arcLenRef = 1.811

	// problem # 4 -- ZDT4, Deb 2001, p358
	case 4:
		opt.Ncpu = 2
		opt.RptName = "ZDT4"
		n := 10
		opt.FltMin = make([]float64, n)
		opt.FltMax = make([]float64, n)
		opt.FltMin[0] = 0
		opt.FltMax[0] = 1
		for i := 1; i < n; i++ {
			opt.FltMin[i] = -5
			opt.FltMax[i] = 5
		}
		nf, ng, nh = 2, 0, 0
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			f[0] = x[0]
			sum := 0.0
			w := 4.0 * math.Pi
			for i := 1; i < n; i++ {
				sum += x[i]*x[i] - 10.0*math.Cos(w*x[i])
			}
			c0 := 1.0 + 10.0*float64(n-1) + sum
			c1 := 1.0 - math.Sqrt(f[0]/c0)
			f[1] = c0 * c1
		}
		fmin = []float64{0, 0}
		fmax = []float64{1, 1}
		opt.F1F0_func = func(f0 float64) float64 {
			return 1.0 - math.Sqrt(f0)
		}
		// arc length = sqrt(5)/2 + log(sqrt(5)+2)/4 ≈ 1.4789428575445975
		opt.F1F0_arcLenRef = math.Sqrt(5.0)/2.0 + math.Log(math.Sqrt(5.0)+2.0)/4.0

	// problem # 5 -- FON (Fonseca and Fleming 1995), Deb 2001, p339
	case 5:
		opt.DEC = 0.8
		opt.Ncpu = 2
		opt.RptName = "FON"
		n := 10
		opt.FltMin = make([]float64, n)
		opt.FltMax = make([]float64, n)
		for i := 0; i < n; i++ {
			opt.FltMin[i] = -4
			opt.FltMax[i] = 4
		}
		nf, ng, nh = 2, 0, 0
		coef := 1.0 / math.Sqrt(float64(n))
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			sum0, sum1 := 0.0, 0.0
			for i := 0; i < n; i++ {
				sum0 += math.Pow(x[i]-coef, 2.0)
				sum1 += math.Pow(x[i]+coef, 2.0)
			}
			f[0] = 1.0 - math.Exp(-sum0)
			f[1] = 1.0 - math.Exp(-sum1)
		}
		fmin = []float64{0, 0}
		fmax = []float64{0.98, 1}
		opt.F1F0_func = func(f0 float64) float64 {
			return 1.0 - math.Exp(-math.Pow(2.0-math.Sqrt(-math.Log(1.0-f0)), 2.0))
		}
		opt.F1F0_arcLenRef = 1.45831385

	// problem # 6 -- ZDT6, Deb 2001, p360
	case 6:
		opt.Ncpu = 2
		opt.RptName = "ZDT6"
		n := 10
		opt.FltMin = make([]float64, n)
		opt.FltMax = make([]float64, n)
		for i := 0; i < n; i++ {
			opt.FltMin[i] = 0
			opt.FltMax[i] = 1
		}
		nf, ng, nh = 2, 0, 0
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {
			w := 6.0 * math.Pi
			f[0] = 1.0 - math.Exp(-4.0*x[0])*math.Pow(math.Sin(w*x[0]), 6.0)
			sum := 0.0
			for i := 1; i < n; i++ {
				sum += x[i]
			}
			w = float64(n - 1)
			c0 := 1.0 + 9.0*math.Pow(sum/w, 0.25)
			c1 := 1.0 - math.Pow(f[0]/c0, 2.0)
			f[1] = c0 * c1
		}
		opt.F1F0_func = func(f0 float64) float64 {
			return 1.0 - math.Pow(f0, 2.0)
		}
		xs := math.Atan(9.0*math.Pi) / (6.0 * math.Pi)
		f0min := 1.0 - math.Exp(-4.0*xs)*math.Pow(math.Sin(6.0*math.Pi*xs), 6.0)
		f1max := opt.F1F0_func(f0min)
		io.Pforan("xs=%v f0min=%v f1max=%v\n", xs, f0min, f1max)
		// xs=0.08145779687998356 f0min=0.2807753188153699 f1max=0.9211652203441274
		fmin = []float64{f0min, 0}
		fmax = []float64{1, 1}
		opt.F1F0_arcLenRef = 1.184

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

	// number of trial solutions and number of groups
	opt.Nsol = len(opt.FltMin) * 10

	// 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.StatF1F0(opt, true)

	// check
	goga.CheckFront0(opt, true)

	// plot
	if true {
		feasibleOnly := true
		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)
		np := 201
		F0 := utl.LinSpace(fmin[0], fmax[0], np)
		F1 := make([]float64, np)
		for i := 0; i < np; i++ {
			F1[i] = opt.F1F0_func(F0[i])
		}
		plt.Plot(F0, F1, io.Sf("'b-', label='%s'", opt.RptName))
		for _, f0vals := range opt.F1F0_f0ranges {
			f0A, f0B := f0vals[0], f0vals[1]
			f1A, f1B := opt.F1F0_func(f0A), opt.F1F0_func(f0B)
			plt.PlotOne(f0A, f1A, "'g_', mew=1.5, ms=10, clip_on=0")
			plt.PlotOne(f0B, f1B, "'g|', mew=1.5, ms=10, clip_on=0")
		}
		plt.AxisRange(fmin[0], fmax[0], fmin[1], fmax[1])
		plt.Gll("$f_0$", "$f_1$", "")
		plt.SaveD("/tmp/goga", io.Sf("%s.eps", opt.RptName))
	}
	return
}
Example #27
0
func (o *Plotter) Plot_p_q(x, y []float64, res []*State, sts [][]float64, last bool) {
	// stress path
	nr := len(res)
	k := nr - 1
	var xmi, xma, ymi, yma float64
	for i := 0; i < nr; i++ {
		x[i], y[i] = o.P[i], o.Q[i]
		if o.Multq {
			mult := fun.Sign(o.W[i])
			y[i] *= mult
		}
		if o.UseOct {
			x[i] *= tsr.SQ3
			y[i] *= tsr.SQ2by3
		}
		if i == 0 {
			xmi, xma = x[i], x[i]
			ymi, yma = y[i], y[i]
		} else {
			xmi = min(xmi, x[i])
			xma = max(xma, x[i])
			ymi = min(ymi, y[i])
			yma = max(yma, y[i])
		}
		if o.SMPon {
			x[i], y[i], _ = tsr.M_pq_smp(res[i].Sig, o.SMPa, o.SMPb, o.SMPβ, o.SMPϵ)
		}
	}
	plt.Plot(x, y, io.Sf("'r.', ls='%s', clip_on=0, color='%s', marker='%s', label=r'%s'", o.Ls, o.Clr, o.Mrk, o.Lbl))
	plt.PlotOne(x[0], y[0], io.Sf("'bo', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.SpMrk, o.SpMs))
	plt.PlotOne(x[k], y[k], io.Sf("'bs', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.EpMrk, o.EpMs))
	// yield surface
	if o.WithYs && o.m != nil {
		mx, my := 1.0, 1.0
		if o.UseOct {
			mx, my = tsr.SQ3, tsr.SQ2by3
		}
		if o.UsePmin {
			xmi = min(xmi, o.Pmin*mx)
		}
		if o.UsePmax {
			xma = max(xma, o.Pmax*mx)
			yma = max(yma, o.Pmax*my)
		}
		xmi, xma, ymi, yma = o.fix_range(xmi, xmi, xma, ymi, yma)
		if o.PqLims != nil {
			xmi, xma, ymi, yma = o.PqLims[0], o.PqLims[1], o.PqLims[2], o.PqLims[3]
		}
		//io.Pforan("xmi,xma ymi,yma = %v,%v %v,%v\n", xmi,xma, ymi,yma)
		dx := (xma - xmi) / float64(o.NptsPq-1)
		dy := (yma - ymi) / float64(o.NptsPq-1)
		xx := la.MatAlloc(o.NptsPq, o.NptsPq)
		yy := la.MatAlloc(o.NptsPq, o.NptsPq)
		za := la.MatAlloc(o.NptsPq, o.NptsPq)
		zb := la.MatAlloc(o.NptsPq, o.NptsPq)
		var p, q, σa, σb, σc, λ0, λ1, λ2 float64
		v := NewState(len(res[0].Sig), len(res[0].Alp), false, len(res[0].EpsE) > 0)
		for k := 0; k < nr; k++ {
			copy(v.Alp, res[k].Alp)
			v.Dgam = res[k].Dgam
			for i := 0; i < o.NptsPq; i++ {
				for j := 0; j < o.NptsPq; j++ {
					xx[i][j] = xmi + float64(i)*dx
					yy[i][j] = ymi + float64(j)*dy
					p, q = xx[i][j], yy[i][j]
					if o.UseOct {
						p /= tsr.SQ3
						q /= tsr.SQ2by3
					}
					σa, σb, σc = tsr.PQW2O(p, q, o.W[k])
					λ0, λ1, λ2 = tsr.O2L(σa, σb, σc)
					v.Sig[0], v.Sig[1], v.Sig[2] = λ0, λ1, λ2
					ys := o.m.YieldFuncs(v)
					za[i][j] = ys[0]
					if o.nsurf > 1 {
						zb[i][j] = ys[1]
					}
					if o.SMPon {
						xx[i][j], yy[i][j], _ = tsr.M_pq_smp(v.Sig, o.SMPa, o.SMPb, o.SMPβ, o.SMPϵ)
					}
				}
			}
			plt.ContourSimple(xx, yy, za, io.Sf("colors=['%s'], levels=[0], linestyles=['%s'], linewidths=[%g], clip_on=0", o.YsClr0, o.YsLs0, o.YsLw0)+o.ArgsYs)
			if o.nsurf > 1 {
				plt.ContourSimple(xx, yy, zb, io.Sf("colors=['%s'], levels=[0], linestyles=['%s'], linewidths=[%g], clip_on=0", o.YsClr1, o.YsLs1, o.YsLw1)+o.ArgsYs)
			}
		}
	}
	// predictor-corrector
	if len(o.PreCor) > 1 {
		var p, q, pnew, qnew float64
		for i := 1; i < len(o.PreCor); i++ {
			p = tsr.M_p(o.PreCor[i-1])
			q = tsr.M_q(o.PreCor[i-1])
			pnew = tsr.M_p(o.PreCor[i])
			qnew = tsr.M_q(o.PreCor[i])
			if o.UseOct {
				p *= tsr.SQ3
				pnew *= tsr.SQ3
				q *= tsr.SQ2by3
				qnew *= tsr.SQ2by3
			}
			if o.SMPon {
				p, q, _ = tsr.M_pq_smp(o.PreCor[i-1], o.SMPa, o.SMPb, o.SMPβ, o.SMPϵ)
				pnew, qnew, _ = tsr.M_pq_smp(o.PreCor[i], o.SMPa, o.SMPb, o.SMPβ, o.SMPϵ)
			}
			if math.Abs(pnew-p) > 1e-10 || math.Abs(qnew-q) > 1e-10 {
				plt.Arrow(p, q, pnew, qnew, io.Sf("sc=%d, fc='%s', ec='%s'", o.ArrWid, o.ClrPC, o.ClrPC))
			}
		}
	}
	// settings
	if last {
		plt.Equal()
		xl, yl := "$p_{cam}$", "$q_{cam}$"
		if o.UseOct {
			xl, yl = "$p_{oct}$", "$q_{oct}$"
		}
		if o.SMPon {
			xl, yl = "$p_{smp}$", "$q_{smp}$"
		}
		if o.AxLblX != "" {
			xl = o.AxLblX
		}
		if o.AxLblY != "" {
			yl = o.AxLblY
		}
		plt.Gll(xl, yl, "leg_out=1, leg_ncol=4, leg_hlen=1.5")
		if lims, ok := o.Lims["p,q"]; ok {
			plt.AxisLims(lims)
		}
		if lims, ok := o.Lims["p,q,ys"]; ok {
			plt.AxisLims(lims)
		}
	}
}
Example #28
0
func main() {

	PI := math.Pi

	yf := func(x float64) float64 {
		return 1.0 - math.Sqrt(x) - math.Sin(10.0*math.Pi*x)*x
	}

	dydx := func(x float64) float64 {
		return -math.Sin(10.0*PI*x) - 10.0*PI*x*math.Cos(10.0*PI*x) - 1.0/(2.0*math.Sqrt(x))
	}

	var nlsDY num.NlSolver
	nlsDY.Init(1, func(fx, x []float64) error {
		fx[0] = dydx(x[0])
		return nil
	}, nil, nil, false, true, nil)
	defer nlsDY.Clean()

	X := []float64{0.09, 0.25, 0.45, 0.65, 0.85}
	Y := make([]float64, len(X))
	for i, x := range X {

		// find min
		xx := []float64{x}
		err := nlsDY.Solve(xx, true)
		if err != nil {
			io.PfRed("dydx nls failed:\n%v", err)
			return
		}
		X[i] = xx[0]
		Y[i] = yf(X[i])
	}

	// find next point along horizontal line
	Xnext := []float64{0.2, 0.4, 0.6, 0.8}
	Ynext := make([]float64, len(Xnext))
	for i, xnext := range Xnext {
		var nlsX num.NlSolver
		nlsX.Init(1, func(fx, x []float64) error {
			fx[0] = Y[i] - yf(x[0])
			return nil
		}, nil, nil, false, true, nil)
		defer nlsX.Clean()
		xx := []float64{xnext}
		err := nlsX.Solve(xx, true)
		if err != nil {
			io.PfRed("dydx nls failed:\n%v", err)
			return
		}
		Xnext[i] = xx[0]
		Ynext[i] = yf(Xnext[i])
	}

	// auxiliary points
	XX := []float64{
		0, X[0],
		Xnext[0], X[1],
		Xnext[1], X[2],
		Xnext[2], X[3],
		Xnext[3], X[4],
	}
	YY := []float64{
		1, Y[0],
		Ynext[0], Y[1],
		Ynext[1], Y[2],
		Ynext[2], Y[3],
		Ynext[3], Y[4],
	}
	io.Pforan("XX = %.3f\n", XX)
	io.Pforan("YY = %.3f\n", YY)

	// find arc-length
	arclen := 0.0
	for i := 0; i < len(XX); i += 2 {
		a := XX[i]
		b := XX[i+1]
		if i == 0 {
			a += 1e-7
		}
		var quad num.Simp
		quad.Init(func(x float64) float64 {
			return math.Sqrt(1.0 + math.Pow(dydx(x), 2.0))
		}, a, b, 1e-4)
		res, err := quad.Integrate()
		if err != nil {
			io.PfRed("quad failed:\n%v", err)
			return
		}
		arclen += res
		io.Pf("int(...) from %.15f to %.15f = %g\n", a, b, res)
	}
	io.Pforan("arclen = %v\n", arclen)

	np := 201
	xx := utl.LinSpace(0, 1, np)
	yy := make([]float64, np)
	for i := 0; i < np; i++ {
		yy[i] = yf(xx[i])
	}
	plt.Plot(xx, yy, "'b-', clip_on=0")
	for i, x := range X {
		plt.PlotOne(x, Y[i], "'r|', mew=2, ms=30, clip_on=0")
	}
	for i, x := range Xnext {
		plt.PlotOne(x, Ynext[i], "'r_', mew=2, ms=30, clip_on=0")
	}
	for i := 0; i < len(XX); i += 2 {
		x0, y0 := XX[i], YY[i]
		x1, y1 := XX[i+1], YY[i+1]
		plt.Arrow(x0, y0, x1, y1, "")
	}
	plt.SetXnticks(11)
	plt.Gll("x", "y", "")
	plt.SaveD("/tmp/goga", "calcZDT3pts.eps")
}
Example #29
0
func (o *Plotter) Plot_s3_s1(x, y []float64, res []*State, sts [][]float64, last bool) {
	// stress path
	nr := len(res)
	k := nr - 1
	x2 := make([]float64, nr)
	var xmi, xma, ymi, yma float64
	for i := 0; i < nr; i++ {
		σ1, σ2, σ3, err := tsr.M_PrincValsNum(res[i].Sig)
		if err != nil {
			chk.Panic("computation of eigenvalues failed", err)
		}
		x[i], y[i] = -tsr.SQ2*σ3, -σ1
		x2[i] = -tsr.SQ2 * σ2
		if i == 0 {
			xmi, xma = x[i], x[i]
			ymi, yma = y[i], y[i]
		} else {
			xmi = min(min(xmi, x[i]), x2[i])
			xma = max(max(xma, x[i]), x2[i])
			ymi = min(ymi, y[i])
			yma = max(yma, y[i])
		}
	}
	plt.Plot(x, y, io.Sf("'r.', ls='%s', clip_on=0, color='%s', marker='%s', label=r'$\\sigma_3$ %s'", o.Ls, o.Clr, o.Mrk, o.Lbl))
	plt.Plot(x2, y, io.Sf("'r.', ls='%s', clip_on=0, color='%s', marker='%s', label=r'$\\sigma_2$ %s'", o.LsAlt, o.Clr, o.Mrk, o.Lbl))
	plt.PlotOne(x[0], y[0], io.Sf("'bo', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.SpMrk, o.SpMs))
	plt.PlotOne(x[k], y[k], io.Sf("'bs', clip_on=0, color='%s', marker='%s', ms=%d", o.SpClr, o.EpMrk, o.EpMs))
	// yield surface
	if o.WithYs && o.m != nil {
		if o.UsePmin {
			xmi = min(xmi, o.Pmin*tsr.SQ2)
			ymi = min(ymi, o.Pmin)
		}
		if o.UsePmax {
			xma = max(xma, o.Pmax*tsr.SQ2)
			yma = max(yma, o.Pmax)
		}
		xmi, xma, ymi, yma = o.fix_range(0, xmi, xma, ymi, yma)
		if o.S3s1Lims != nil {
			xmi, xma, ymi, yma = o.S3s1Lims[0], o.S3s1Lims[1], o.S3s1Lims[2], o.S3s1Lims[3]
		}
		//io.Pforan("xmi,xma ymi,yma = %v,%v %v,%v\n", xmi,xma, ymi,yma)
		dx := (xma - xmi) / float64(o.NptsSig-1)
		dy := (yma - ymi) / float64(o.NptsSig-1)
		xx := la.MatAlloc(o.NptsSig, o.NptsSig)
		yy := la.MatAlloc(o.NptsSig, o.NptsSig)
		zz := la.MatAlloc(o.NptsSig, o.NptsSig)
		v := NewState(len(res[0].Sig), len(res[0].Alp), false, len(res[0].EpsE) > 0)
		for k := 0; k < nr; k++ {
			copy(v.Alp, res[k].Alp)
			v.Dgam = res[k].Dgam
			for i := 0; i < o.NptsSig; i++ {
				for j := 0; j < o.NptsSig; j++ {
					xx[i][j] = xmi + float64(i)*dx
					yy[i][j] = ymi + float64(j)*dy
					v.Sig[0], v.Sig[1], v.Sig[2] = -yy[i][j], -xx[i][j]/tsr.SQ2, -xx[i][j]/tsr.SQ2
					ys := o.m.YieldFuncs(v)
					zz[i][j] = ys[0]
				}
			}
			plt.ContourSimple(xx, yy, zz, io.Sf("colors=['%s'], levels=[0], linestyles=['%s'], linewidths=[%g], clip_on=0", o.YsClr0, o.YsLs0, o.YsLw0)+o.ArgsYs)
		}
	}
	// predictor-corrector
	if len(o.PreCor) > 1 {
		var σ3, σ1, σ3new, σ1new float64
		for i := 1; i < len(o.PreCor); i++ {
			σ1, _, σ3, _ = tsr.M_PrincValsNum(o.PreCor[i-1])
			σ1new, _, σ3new, _ = tsr.M_PrincValsNum(o.PreCor[i])
			if math.Abs(σ3new-σ3) > 1e-7 || math.Abs(σ1new-σ1) > 1e-7 {
				plt.Arrow(-σ3*tsr.SQ2, -σ1, -σ3new*tsr.SQ2, -σ1new, io.Sf("sc=%d, fc='%s', ec='%s'", o.ArrWid, o.ClrPC, o.ClrPC))
			}
		}
	}
	// settings
	if last {
		plt.Equal()
		plt.Gll("$-\\sqrt{2}\\sigma_3$", "$-\\sigma_1$", "leg=1, leg_out=1, leg_ncol=4, leg_hlen=2")
		if lims, ok := o.Lims["s3,s1"]; ok {
			plt.AxisLims(lims)
		}
		if lims, ok := o.Lims["s3,s1,ys"]; ok {
			plt.AxisLims(lims)
		}
	}
}
Example #30
0
// DistPoint returns the distance from a point to this Bezier curve
// It finds the closest projection which is stored in P
func (o *BezierQuad) DistPoint(X []float64, doplot bool) float64 {

	// TODO:
	//   1) split this into closest projections finding
	//   2) finish distance computation

	// check
	if len(o.Q) != 3 {
		chk.Panic("DistPoint: quadratic Bezier must be initialised first (with 3 control points)")
	}
	ndim := len(o.Q[0])
	chk.IntAssert(len(X), ndim)

	// solve cubic equation
	var A_i, B_i, M_i, a, b, c, d float64
	for i := 0; i < ndim; i++ {
		A_i = o.Q[2][i] - 2.0*o.Q[1][i] + o.Q[0][i]
		B_i = o.Q[1][i] - o.Q[0][i]
		M_i = o.Q[0][i] - X[i]
		a += A_i * A_i
		b += 3.0 * A_i * B_i
		c += 2.0*B_i*B_i + M_i*A_i
		d += M_i * B_i
	}
	//io.Pforan("a=%v b=%v c=%v d=%v\n", a, b, c, d)
	if math.Abs(a) < 1e-7 {
		chk.Panic("DistPoint does not yet work with this type of Bezier (straight line?):\nQ=%v\n", o.Q)
	}
	x1, x2, x3, nx := num.EqCubicSolveReal(b/a, c/a, d/a)
	io.Pfyel("\nx1=%v x2=%v x3=%v nx=%v\n", x1, x2, x3, nx)

	// auxiliary
	if len(o.P) != ndim {
		o.P = make([]float64, ndim)
	}

	// closest projections
	t := x1
	if nx == 2 {
		chk.Panic("nx=2 => not implemented yet")
	}
	if nx == 3 {
		T := []float64{x1, x2, x3}
		D := []float64{-1, -1, -1}
		ok := []bool{
			!(x1 < 0.0 || x1 > 1.0),
			!(x2 < 0.0 || x2 > 1.0),
			!(x3 < 0.0 || x3 > 1.0),
		}
		io.Pforan("ok = %v\n", ok)
		for i, t := range T {
			if ok[i] {
				o.Point(o.P, t)
				if doplot {
					plt.PlotOne(X[0], X[1], "'ko'")
					plt.PlotOne(o.P[0], o.P[1], "'k.'")
					plt.Arrow(X[0], X[1], o.P[0], o.P[1], "ec='none'")
				}
				D[i] = ppdist(X, o.P)
			}
		}
		io.Pforan("D = %v\n", D)
	}
	o.Point(o.P, t)
	io.Pfcyan("P = %v\n", o.P)
	return 0
}