Exemplo n.º 1
0
func Test_dist_lognormal_01(tst *testing.T) {

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

	_, dat, err := io.ReadTable("data/lognormal.dat")
	if err != nil {
		tst.Errorf("cannot read comparison results:\n%v\n", err)
		return
	}

	X, ok := dat["x"]
	if !ok {
		tst.Errorf("cannot get x values\n")
		return
	}
	N, ok := dat["n"]
	if !ok {
		tst.Errorf("cannot get n values\n")
		return
	}
	Z, ok := dat["z"]
	if !ok {
		tst.Errorf("cannot get z values\n")
		return
	}
	YpdfCmp, ok := dat["ypdf"]
	if !ok {
		tst.Errorf("cannot get ypdf values\n")
		return
	}
	YcdfCmp, ok := dat["ycdf"]
	if !ok {
		tst.Errorf("cannot get ycdf values\n")
		return
	}

	var dist DistLogNormal

	nx := len(X)
	for i := 0; i < nx; i++ {
		w := Z[i] * Z[i]
		μ := math.Exp(N[i] + w/2.0)
		σ := μ * math.Sqrt(math.Exp(w)-1.0)
		dist.Init(&VarData{M: μ, S: σ})
		Ypdf := dist.Pdf(X[i])
		Ycdf := dist.Cdf(X[i])
		err := chk.PrintAnaNum("ypdf", 1e-14, YpdfCmp[i], Ypdf, chk.Verbose)
		if err != nil {
			tst.Errorf("pdf failed: %v\n", err)
			return
		}
		err = chk.PrintAnaNum("ycdf", 1e-15, YcdfCmp[i], Ycdf, chk.Verbose)
		if err != nil {
			tst.Errorf("cdf failed: %v\n", err)
			return
		}
	}
}
Exemplo n.º 2
0
func Test_dist_gumbel_01(tst *testing.T) {

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

	_, dat, err := io.ReadTable("data/gumbel.dat")
	if err != nil {
		tst.Errorf("cannot read comparison results:\n%v\n", err)
		return
	}

	X, ok := dat["x"]
	if !ok {
		tst.Errorf("cannot get x values\n")
		return
	}
	U, ok := dat["u"]
	if !ok {
		tst.Errorf("cannot get u values\n")
		return
	}
	B, ok := dat["b"]
	if !ok {
		tst.Errorf("cannot get b values\n")
		return
	}
	YpdfCmp, ok := dat["ypdf"]
	if !ok {
		tst.Errorf("cannot get ypdf values\n")
		return
	}
	YcdfCmp, ok := dat["ycdf"]
	if !ok {
		tst.Errorf("cannot get ycdf values\n")
		return
	}

	var dist DistGumbel

	nx := len(X)
	for i := 0; i < nx; i++ {
		dist.U = U[i]
		dist.B = B[i]
		Ypdf := dist.Pdf(X[i])
		Ycdf := dist.Cdf(X[i])
		err := chk.PrintAnaNum("ypdf", 1e-14, YpdfCmp[i], Ypdf, chk.Verbose)
		if err != nil {
			tst.Errorf("pdf failed: %v\n", err)
			return
		}
		err = chk.PrintAnaNum("ycdf", 1e-15, YcdfCmp[i], Ycdf, chk.Verbose)
		if err != nil {
			tst.Errorf("cdf failed: %v\n", err)
			return
		}
	}
}
Exemplo n.º 3
0
func Test_dist_uniform_01(tst *testing.T) {

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

	_, dat, err := io.ReadTable("data/uniform.dat")
	if err != nil {
		tst.Errorf("cannot read comparison results:\n%v\n", err)
		return
	}

	X, ok := dat["x"]
	if !ok {
		tst.Errorf("cannot get x values\n")
		return
	}
	A, ok := dat["a"] // min
	if !ok {
		tst.Errorf("cannot get a values\n")
		return
	}
	B, ok := dat["b"] // max
	if !ok {
		tst.Errorf("cannot get b values\n")
		return
	}
	YpdfCmp, ok := dat["ypdf"]
	if !ok {
		tst.Errorf("cannot get ypdf values\n")
		return
	}
	YcdfCmp, ok := dat["ycdf"]
	if !ok {
		tst.Errorf("cannot get ycdf values\n")
		return
	}

	var dist DistUniform

	nx := len(X)
	for i := 0; i < nx; i++ {
		dist.Init(&VarData{Min: A[i], Max: B[i]})
		Ypdf := dist.Pdf(X[i])
		Ycdf := dist.Cdf(X[i])
		err := chk.PrintAnaNum("ypdf", 1e-14, YpdfCmp[i], Ypdf, chk.Verbose)
		if err != nil {
			tst.Errorf("pdf failed: %v\n", err)
			return
		}
		err = chk.PrintAnaNum("ycdf", 1e-15, YcdfCmp[i], Ycdf, chk.Verbose)
		if err != nil {
			tst.Errorf("cdf failed: %v\n", err)
			return
		}
	}
}
Exemplo n.º 4
0
func Test_norm01(tst *testing.T) {

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

	_, dat, err := io.ReadTable("data/normal.dat")
	if err != nil {
		tst.Errorf("cannot read comparison results:\n%v\n", err)
		return
	}

	X, ok := dat["x"]
	if !ok {
		tst.Errorf("cannot get x values\n")
		return
	}
	Mu, ok := dat["mu"]
	if !ok {
		tst.Errorf("cannot get mu values\n")
		return
	}
	Sig, ok := dat["sig"]
	if !ok {
		tst.Errorf("cannot get sig values\n")
		return
	}
	YpdfCmp, ok := dat["ypdf"]
	if !ok {
		tst.Errorf("cannot get ypdf values\n")
		return
	}
	YcdfCmp, ok := dat["ycdf"]
	if !ok {
		tst.Errorf("cannot get ycdf values\n")
		return
	}

	var dist DistNormal

	n := len(X)
	for i := 0; i < n; i++ {
		dist.Init(&VarData{M: Mu[i], S: Sig[i]})
		Ypdf := dist.Pdf(X[i])
		Ycdf := dist.Cdf(X[i])
		err := chk.PrintAnaNum("ypdf", 1e-15, YpdfCmp[i], Ypdf, chk.Verbose)
		if err != nil {
			tst.Errorf("pdf failed: %v\n", err)
			return
		}
		err = chk.PrintAnaNum("ycdf", 1e-15, YcdfCmp[i], Ycdf, chk.Verbose)
		if err != nil {
			tst.Errorf("cdf failed: %v\n", err)
			return
		}
	}
}
Exemplo n.º 5
0
// ReadGraphTable reads data and allocate graph
func ReadGraphTable(fname string, bargera bool) *Graph {

	// data
	var ne int
	var edges [][]int
	var weights []float64

	// Bar-Gera format files from: http://www.bgu.ac.il/~bargera/tntp/
	if bargera {
		k := 0
		reading_meta := true
		io.ReadLines(fname, func(idx int, line string) (stop bool) {
			if len(line) < 1 {
				return false
			}
			line = strings.TrimSpace(line)
			if line[0] == '~' {
				return false
			}
			if reading_meta {
				switch {
				case strings.HasPrefix(line, "<NUMBER OF LINKS>"):
					res := strings.Split(line, "<NUMBER OF LINKS>")
					ne = io.Atoi(strings.TrimSpace(res[1]))
					edges = make([][]int, ne)
					weights = make([]float64, ne)
				case strings.HasPrefix(line, "<END OF METADATA>"):
					reading_meta = false
				}
				return false
			}
			l := strings.Fields(line)
			edges[k] = []int{io.Atoi(l[0]) - 1, io.Atoi(l[1]) - 1}
			weights[k] = io.Atof(l[4])
			k++
			return false
		})
	} else {
		_, dat, err := io.ReadTable(fname)
		if err != nil {
			chk.Panic("cannot read datafile\n%v", err)
		}
		ne = len(dat["from"]) // number of edges
		edges = make([][]int, ne)
		weights = make([]float64, ne)
		for i := 0; i < ne; i++ {
			edges[i] = []int{int(dat["from"][i]) - 1, int(dat["to"][i]) - 1}
			weights[i] = dat["cost"][i]
		}
	}

	// graph
	var G Graph
	G.Init(edges, weights, nil, nil)
	return &G
}
Exemplo n.º 6
0
// ReadTable loads path from datafile in table format
//  Note: n -- number of lines to read. use -1 to read all lines
func (o *Path) ReadTable(ndim, nincs, niout int, fname string, n int, mσ, mε float64, stresspath bool) (err error) {

	// constants
	o.Nincs, o.Niout = nincs, niout

	// read data table
	keys, d, err := io.ReadTable(fname)
	if err != nil {
		return
	}
	if n < 0 {
		n = len(d[keys[0]])
	}

	// find x-y-z keys
	ex, ey, ez := "ex", "ey", "ez"
	sx, sy, sz := "sx", "sy", "sz"
	for _, key := range keys {
		switch key {
		case "Ex":
			ex, ey, ez = "Ex", "Ey", "Ez"
		case "Ea":
			ex, ey, ez = "Et", "Er", "Ea"
		case "ea":
			ex, ey, ez = "et", "er", "ea"
		case "Sx":
			sx, sy, sz = "Sx", "Sy", "Sz"
		case "Sa":
			sx, sy, sz = "St", "Sr", "Sa"
		case "sa":
			sx, sy, sz = "st", "sr", "sa"
		}
	}

	// set stress path
	if stresspath {
		o.Sx, o.Sy, o.Sz = make([]float64, n), make([]float64, n), make([]float64, n)
		for i := 0; i < n; i++ {
			o.Sx[i], o.Sy[i], o.Sz[i] = mσ*d[sx][i], mσ*d[sy][i], mσ*d[sz][i]
		}
		o.UseS = utl.IntVals(n, 1)

		// set strain path
	} else {
		o.Ex, o.Ey, o.Ez = make([]float64, n), make([]float64, n), make([]float64, n)
		for i := 0; i < n; i++ {
			o.Ex[i], o.Ey[i], o.Ez[i] = mε*d[ex][i], mε*d[ey][i], mε*d[ez][i]
		}
		o.Sx, o.Sy, o.Sz = []float64{mσ * d[sx][0]}, []float64{mσ * d[sy][0]}, []float64{mσ * d[sz][0]}
		o.UseE = utl.IntVals(n, 1)
	}

	// set additional information
	return o.Init(ndim)
}
Exemplo n.º 7
0
func Test_flt04(tst *testing.T) {

	//verbose()
	chk.PrintTitle("flt04. two-bar truss. Pareto-optimal")

	// data. from Coelho (2007) page 19
	ρ := 0.283 // lb/in³
	H := 100.0 // in
	P := 1e4   // lb
	E := 3e7   // lb/in²
	σ0 := 2e4  // lb/in²

	// parameters
	var opt Optimiser
	opt.Default()
	opt.Nsol = 30
	opt.Ncpu = 1
	opt.Tf = 100
	opt.LatinDup = 5
	opt.FltMin = []float64{0.1, 0.5}
	opt.FltMax = []float64{2.25, 2.5}
	nf, ng, nh := 2, 2, 0

	// initialise optimiser
	TSQ2 := 2.0 * math.Sqrt2
	opt.Init(GenTrialSolutions, nil, func(f, g, h, x []float64, ξ []int, cpu int) {
		f[0] = 2.0 * ρ * H * x[1] * math.Sqrt(1.0+x[0]*x[0])
		f[1] = P * H * math.Pow(1.0+x[0]*x[0], 1.5) * math.Sqrt(1.0+math.Pow(x[0], 4.0)) / (TSQ2 * E * x[0] * x[0] * x[1])
		g[0] = σ0 - P*(1.0+x[0])*math.Sqrt(1.0+x[0]*x[0])/(TSQ2*x[0]*x[1])
		g[1] = σ0 - P*(1.0-x[0])*math.Sqrt(1.0+x[0]*x[0])/(TSQ2*x[0]*x[1])
	}, nf, ng, nh)

	// initial solutions
	sols0 := opt.GetSolutionsCopy()

	// solve
	opt.Solve()

	// plot
	if chk.Verbose {
		_, dat, _ := io.ReadTable("data/coelho-fig1.6.dat")
		pp := NewPlotParams(false)
		pp.FnKey = "fig-flt04"
		pp.FmtSols.C = "gray"
		pp.WithAll = true
		pp.Extra = func() {
			plt.Plot(dat["f1"], dat["f2"], "'b-',ms=3,markeredgecolor='b'")
			plt.AxisRange(0, 250, 0, 0.15)
		}
		opt.PlotOvaOvaPareto(sols0, 0, 1, pp)
	}
}
Exemplo n.º 8
0
// NewSpheresFromFile add spheres (e.g. particles) by reading a file in the following format
//   x    y    z    r
//  0.0  0.0  0.0  0.1
//  1.0  0.0  0.0  0.1
//   ...
func NewSpheresFromFile(filename string) *Spheres {
	_, dat, err := io.ReadTable(filename)
	if err != nil {
		chk.Panic("NewSpheresFromFile failed:\n%v", err)
	}
	return &Spheres{
		X:     dat["x"],
		Y:     dat["y"],
		Z:     dat["z"],
		R:     dat["r"],
		Color: []float64{1, 0, 0, 1},
	}
}
Exemplo n.º 9
0
func main() {

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

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

	// start analysis process
	out.Start(simfn, 0, 0)

	// define entities
	out.Define("a", out.P{{18, 8}})

	// load results
	out.LoadResults(nil)

	nf_a := out.GetRes("nf", "a", -1)
	pl_a := out.GetRes("pl", "a", -1)
	pc_a := make([]float64, len(pl_a))
	for i, _ := range pl_a {
		pc_a[i] = -pl_a[i]
	}

	out.Splot("LRM")
	_, d, _ := io.ReadTable("lrm.dat")
	plt.Plot(d["pc"], d["sl"], "'c-',lw=2")

	out.Plot(pc_a, "sl", "a", plt.Fmt{M: "o"}, -1)
	out.Csplot.Xlbl = "$p_c$"

	out.Splot("porosity")
	out.Plot("t", nf_a, "a", plt.Fmt{M: "+"}, -1)
	out.Csplot.Ylbl = "$n_f$"

	// show
	out.Draw("", "", true, nil)
}
Exemplo n.º 10
0
func main() {

	// filename
	filename, fnkey := io.ArgToFilename(0, "sg1121", ".sim", true)

	// results
	out.Start(filename, 0, 0)
	out.Define("A", out.N{30})
	out.LoadResults(nil)

	// plot FEM results
	out.Plot("t", "uy", "A", plt.Fmt{C: "k", Ls: "-", L: "gofem"}, -1)

	// old results
	b, err := io.ReadFile("cmp/sg1121gofemold.json")
	if err != nil {
		io.PfRed("cannot read comparison file\n")
		return
	}
	var gofemold struct {
		Time, Uy30 []float64
	}
	err = json.Unmarshal(b, &gofemold)
	if err != nil {
		io.PfRed("cannot unmarshal comparison file\n")
		return
	}

	// mechsys results
	_, res, err := io.ReadTable("cmp/sg1121mechsysN30.cmp")
	if err != nil {
		io.PfRed("cannot read mechsys comparison file\n")
		return
	}

	// save
	plt.SetForPng(0.8, 400, 200)
	out.Draw("/tmp", fnkey+".png", false, func(i, j, n int) {
		plt.Plot(gofemold.Time, gofemold.Uy30, "'r-', lw=2, label='gofemOld'")
		plt.Plot(res["Time"], res["uy"], "'b-', label='mechsys'")
	})
}
Exemplo n.º 11
0
func main() {

	// filename
	filename, fnkey := io.ArgToFilename(0, "a-coarse-elast-d2-q9", ".sim", true)

	// start analysis process
	out.Start(filename, 0, 0)

	// define entities
	out.Define("a", out.P{{18, 8}})

	// load results
	out.LoadResults(nil)

	nf_a := out.GetRes("nf", "a", -1)
	pl_a := out.GetRes("pl", "a", -1)
	pc_a := make([]float64, len(pl_a))
	for i, _ := range pl_a {
		pc_a[i] = -pl_a[i]
	}

	out.Splot("LRM")
	_, d, _ := io.ReadTable("lrm.dat")
	plt.Plot(d["pc"], d["sl"], "'c-',lw=2")

	out.Plot(pc_a, "sl", "a", plt.Fmt{M: "o"}, -1)
	out.Csplot.Xlbl = "$p_c$"

	out.Splot("porosity")
	out.Plot("t", nf_a, "a", plt.Fmt{M: "+"}, -1)
	out.Csplot.Ylbl = "$n_f$"

	// show
	plt.SetForPng(1.2, 500, 200)
	out.Draw("/tmp", "up_indentation2d_unsat_lrm_"+fnkey+".png", false, nil)
}
Exemplo n.º 12
0
func runone(ncpu int) (nsol, tf int, elaspsedTime time.Duration) {

	// input filename
	fn, fnkey := io.ArgToFilename(0, "ground10", ".sim", true)

	// GA parameters
	var opt goga.Optimiser
	opt.Read("ga-" + fnkey + ".json")
	opt.GenType = "rnd"
	nsol, tf = opt.Nsol, opt.Tf
	postproc := true
	if ncpu > 0 {
		opt.Ncpu = ncpu
		postproc = false
	}

	// FEM
	data := make([]*FemData, opt.Ncpu)
	for i := 0; i < opt.Ncpu; i++ {
		data[i] = NewData(fn, fnkey, i)
	}
	io.Pforan("MaxWeight = %v\n", data[0].MaxWeight)

	// set integers
	if data[0].Opt.BinInt {
		opt.CxInt = goga.CxInt
		opt.MtInt = goga.MtIntBin
		opt.BinInt = data[0].Ncells
	}

	// set floats
	opt.FltMin = make([]float64, data[0].Nareas)
	opt.FltMax = make([]float64, data[0].Nareas)
	for i := 0; i < data[0].Nareas; i++ {
		opt.FltMin[i] = data[0].Opt.Amin
		opt.FltMax[i] = data[0].Opt.Amax
	}

	// initialise optimiser
	opt.Nova = 2 // weight and deflection
	opt.Noor = 4 // mobility, feasibility, maxdeflection, stress
	opt.Init(goga.GenTrialSolutions, func(sol *goga.Solution, cpu int) {
		mob, fail, weight, umax, _, errU, errS := data[cpu].RunFEM(sol.Int, sol.Flt, 0, false)
		sol.Ova[0] = weight
		sol.Ova[1] = umax
		sol.Oor[0] = mob
		sol.Oor[1] = fail
		sol.Oor[2] = errU
		sol.Oor[3] = errS
	}, nil, 0, 0, 0)

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

	// benchmark
	initialTime := time.Now()
	defer func() {
		elaspsedTime = time.Now().Sub(initialTime)
	}()

	// solve
	opt.Verbose = true
	opt.Solve()
	goga.SortByOva(opt.Solutions, 0)

	// post processing
	if !postproc {
		return
	}

	// check
	nfailed, front0 := goga.CheckFront0(&opt, true)

	// save results
	var log, res bytes.Buffer
	io.Ff(&log, opt.LogParams())
	io.Ff(&res, PrintSolutions(data[0], opt.Solutions))
	io.Ff(&res, io.Sf("\n\nnfailed = %d\n", nfailed))
	io.WriteFileVD("/tmp/goga", fnkey+".log", &log)
	io.WriteFileVD("/tmp/goga", fnkey+".res", &res)

	// plot Pareto-optimal front
	feasibleOnly := true
	plt.SetForEps(0.8, 350)
	if strings.HasPrefix(fnkey, "ground10") {
		_, ref, _ := io.ReadTable("p460_fig300.dat")
		plt.Plot(ref["w"], ref["u"], "'b-', label='reference'")
	}
	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)
	plt.Gll("weight ($f_0$)", "deflection ($f_1)$", "") //, "leg_out=1, leg_ncol=4, leg_hlen=1.5")
	if strings.HasPrefix(fnkey, "ground10") {
		plt.AxisRange(1800, 14000, 1, 6)
	}

	// plot selected results
	ia, ib, ic, id, ie := 0, 0, 0, 0, 0
	nfront0 := len(front0)
	io.Pforan("nfront0 = %v\n", nfront0)
	if nfront0 > 4 {
		ib = nfront0 / 10
		ic = nfront0 / 5
		id = nfront0 / 2
		ie = nfront0 - 1
	}
	A := front0[ia]
	B := front0[ib]
	C := front0[ic]
	D := front0[id]
	E := front0[ie]
	wid, hei := 0.20, 0.10
	draw_truss(data[0], "A", A, 0.17, 0.75, wid, hei)
	draw_truss(data[0], "B", B, 0.20, 0.55, wid, hei)
	draw_truss(data[0], "C", C, 0.28, 0.33, wid, hei)
	draw_truss(data[0], "D", D, 0.47, 0.22, wid, hei)
	draw_truss(data[0], "E", E, 0.70, 0.18, wid, hei)

	// save figure
	plt.SaveD("/tmp/goga", fnkey+".eps")

	// tex file
	title := "Shape and topology optimisation. Results."
	label := "topoFront"
	document := true
	compact := true
	tex_results("/tmp/goga", "tmp_"+fnkey, title, label, data[0], A, B, C, D, E, document, compact)
	document = false
	tex_results("/tmp/goga", fnkey, title, label, data[0], A, B, C, D, E, document, compact)
	return
}
Exemplo n.º 13
0
// Hairer-Wanner VII-p3 Eq.(1.4) Robertson's Equation
func Test_ode03(tst *testing.T) {

	//verbose()
	chk.PrintTitle("ode03: Hairer-Wanner VII-p3 Eq.(1.4) Robertson's Equation")

	fcn := func(f []float64, dx, x float64, y []float64, args ...interface{}) error {
		f[0] = -0.04*y[0] + 1.0e4*y[1]*y[2]
		f[1] = 0.04*y[0] - 1.0e4*y[1]*y[2] - 3.0e7*y[1]*y[1]
		f[2] = 3.0e7 * y[1] * y[1]
		return nil
	}
	jac := func(dfdy *la.Triplet, dx, x float64, y []float64, args ...interface{}) error {
		if dfdy.Max() == 0 {
			dfdy.Init(3, 3, 9)
		}
		dfdy.Start()
		dfdy.Put(0, 0, -0.04)
		dfdy.Put(0, 1, 1.0e4*y[2])
		dfdy.Put(0, 2, 1.0e4*y[1])
		dfdy.Put(1, 0, 0.04)
		dfdy.Put(1, 1, -1.0e4*y[2]-6.0e7*y[1])
		dfdy.Put(1, 2, -1.0e4*y[1])
		dfdy.Put(2, 0, 0.0)
		dfdy.Put(2, 1, 6.0e7*y[1])
		dfdy.Put(2, 2, 0.0)
		return nil
	}

	// data
	silent := false
	fixstp := false
	//method := "Dopri5"
	method := "Radau5"
	xa, xb := 0.0, 0.3
	ya := []float64{1.0, 0.0, 0.0}
	ndim := len(ya)

	// structure to hold numerical results
	res := Results{Method: method}

	// allocate ODE object
	var o Solver
	o.Init(method, ndim, fcn, jac, nil, SimpleOutput, silent)

	// tolerances and initial step size
	rtol := 1e-2
	atol := rtol * 1e-6
	o.SetTol(atol, rtol)
	o.IniH = 1.0e-6

	// solve problem
	y := make([]float64, ndim)
	copy(y, ya)
	if fixstp {
		o.Solve(y, xa, xb, 0.01, fixstp, &res)
	} else {
		o.Solve(y, xa, xb, xb-xa, fixstp, &res)
	}

	// plot
	if chk.Verbose {
		plt.SetForEps(1.5, 400)
		args := "'b-', marker='.', lw=1, clip_on=0"
		Plot("/tmp/gosl/ode", "rober.eps", &res, nil, xa, xb, "", args, func() {
			_, T, err := io.ReadTable("data/rober_radau5_cpp.dat")
			if err != nil {
				chk.Panic("%v", err)
			}
			plt.Subplot(4, 1, 1)
			plt.Plot(T["x"], T["y0"], "'k+',label='reference',ms=10")
			plt.Subplot(4, 1, 2)
			plt.Plot(T["x"], T["y1"], "'k+',label='reference',ms=10")
			plt.Subplot(4, 1, 3)
			plt.Plot(T["x"], T["y2"], "'k+',label='reference',ms=10")
		})
	}
}
Exemplo n.º 14
0
func main() {

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

	if mpi.Rank() == 0 {
		chk.PrintTitle("ode02: Hairer-Wanner VII-p5 Eq.(1.5) Van der Pol's Equation")
	}
	if mpi.Size() != 2 {
		chk.Panic(">> error: this test requires 2 MPI processors\n")
		return
	}

	eps := 1.0e-6
	w := make([]float64, 2) // workspace
	fcn := func(f []float64, dx, x float64, y []float64, args ...interface{}) error {
		f[0], f[1] = 0, 0
		switch mpi.Rank() {
		case 0:
			f[0] = y[1]
		case 1:
			f[1] = ((1.0-y[0]*y[0])*y[1] - y[0]) / eps
		}
		// join all f
		mpi.AllReduceSum(f, w)
		return nil
	}
	jac := func(dfdy *la.Triplet, dx, x float64, y []float64, args ...interface{}) error {
		if dfdy.Max() == 0 {
			dfdy.Init(2, 2, 4)
		}
		dfdy.Start()
		if false { // per column
			switch mpi.Rank() {
			case 0:
				dfdy.Put(0, 0, 0.0)
				dfdy.Put(1, 0, (-2.0*y[0]*y[1]-1.0)/eps)
			case 1:
				dfdy.Put(0, 1, 1.0)
				dfdy.Put(1, 1, (1.0-y[0]*y[0])/eps)
			}
		} else { // per row
			switch mpi.Rank() {
			case 0:
				dfdy.Put(0, 0, 0.0)
				dfdy.Put(0, 1, 1.0)
			case 1:
				dfdy.Put(1, 0, (-2.0*y[0]*y[1]-1.0)/eps)
				dfdy.Put(1, 1, (1.0-y[0]*y[0])/eps)
			}
		}
		return nil
	}

	// method and flags
	silent := false
	fixstp := false
	//method := "Dopri5"
	method := "Radau5"
	numjac := false
	xa, xb := 0.0, 2.0
	ya := []float64{2.0, -0.6}
	ndim := len(ya)

	// structure to hold numerical results
	res := ode.Results{Method: method}

	// allocate ODE object
	var o ode.Solver
	o.Distr = true
	if numjac {
		o.Init(method, ndim, fcn, nil, nil, ode.SimpleOutput, silent)
	} else {
		o.Init(method, ndim, fcn, jac, nil, ode.SimpleOutput, silent)
	}

	// tolerances and initial step size
	rtol := 1e-4
	atol := rtol
	o.IniH = 1.0e-4
	o.SetTol(atol, rtol)
	//o.NmaxSS = 2

	// solve problem
	y := make([]float64, ndim)
	copy(y, ya)
	t0 := time.Now()
	if fixstp {
		o.Solve(y, xa, xb, 0.05, fixstp, &res)
	} else {
		o.Solve(y, xa, xb, xb-xa, fixstp, &res)
	}

	// plot
	if mpi.Rank() == 0 {
		io.Pfmag("elapsed time = %v\n", time.Now().Sub(t0))
		plt.SetForEps(1.5, 400)
		args := "'b-', marker='.', lw=1, ms=4, clip_on=0"
		ode.Plot("/tmp/gosl/ode", "vdpolA_mpi.eps", &res, nil, xa, xb, "", args, func() {
			_, T, err := io.ReadTable("data/vdpol_radau5_for.dat")
			if err != nil {
				chk.Panic("%v", err)
			}
			plt.Subplot(3, 1, 1)
			plt.Plot(T["x"], T["y0"], "'k+',label='reference',ms=7")
			plt.Subplot(3, 1, 2)
			plt.Plot(T["x"], T["y1"], "'k+',label='reference',ms=7")
		})
	}
}
Exemplo n.º 15
0
func Test_sg1121(tst *testing.T) {

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

	// run simulation
	if !Start("data/sg1121.sim", true, chk.Verbose) {
		tst.Errorf("test failed\n")
		return
	}

	// make sure to flush log
	defer End()

	// run simulation
	if !Run() {
		tst.Errorf("test failed\n")
		return
	}

	// plot
	doplot := false
	if doplot {

		// 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) {
			tst.Errorf("SetStage failed\n")
			return
		}

		// selected node and dof index
		nidx := 30
		didx := 1

		// new results
		ntout := len(sum.OutTimes)
		uy := make([]float64, ntout)
		for tidx := 0; tidx < ntout; tidx++ {
			if !d.ReadSol(sum.Dirout, sum.Fnkey, tidx) {
				tst.Errorf("test failed:\n")
				return
			}
			nod := d.Nodes[nidx]
			eq := nod.Dofs[didx].Eq
			uy[tidx] = d.Sol.Y[eq]
			// check
			if math.Abs(d.Sol.T-sum.OutTimes[tidx]) > 1e-14 {
				tst.Errorf("output times do not match time in solution array")
				return
			}
		}
		plt.Plot(sum.OutTimes, uy, "'k*-', clip_on=0, label='gofem'")

		// old results
		b, err := io.ReadFile("cmp/sg1121gofemold.json")
		if err != nil {
			tst.Errorf("cannot read comparison file\n")
			return
		}
		var gofemold struct {
			Time, Uy30 []float64
		}
		err = json.Unmarshal(b, &gofemold)
		if err != nil {
			tst.Errorf("cannot unmarshal comparison file\n")
			return
		}
		plt.Plot(gofemold.Time, gofemold.Uy30, "'ro-', label='gofemOld'")

		// mechsys results
		_, res, err := io.ReadTable("cmp/sg1121mechsysN30.cmp")
		if err != nil {
			tst.Errorf("cannot read mechsys comparison file\n")
			return
		}
		plt.Plot(res["Time"], res["uy"], "'b+-', label='mechsys'")

		// show figure
		plt.Gll("$t$", "$u_y$", "")
		plt.Show()
	}
}
Exemplo n.º 16
0
func Test_dist_frechet_01(tst *testing.T) {

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

	_, dat, err := io.ReadTable("data/frechet.dat")
	if err != nil {
		tst.Errorf("cannot read comparison results:\n%v\n", err)
		return
	}

	X, ok := dat["x"]
	if !ok {
		tst.Errorf("cannot get x values\n")
		return
	}
	L, ok := dat["l"] // location
	if !ok {
		tst.Errorf("cannot get l values\n")
		return
	}
	C, ok := dat["c"] // scale
	if !ok {
		tst.Errorf("cannot get c values\n")
		return
	}
	A, ok := dat["a"] // shape
	if !ok {
		tst.Errorf("cannot get a values\n")
		return
	}
	YpdfCmp, ok := dat["ypdf"]
	if !ok {
		tst.Errorf("cannot get ypdf values\n")
		return
	}
	YcdfCmp, ok := dat["ycdf"]
	if !ok {
		tst.Errorf("cannot get ycdf values\n")
		return
	}

	var dist DistFrechet

	nx := len(X)
	for i := 0; i < nx; i++ {
		dist.Init(&VarData{L: L[i], C: C[i], A: A[i]})
		Ypdf := dist.Pdf(X[i])
		Ycdf := dist.Cdf(X[i])
		err := chk.PrintAnaNum("ypdf", 1e-14, YpdfCmp[i], Ypdf, chk.Verbose)
		if err != nil {
			tst.Errorf("pdf failed: %v\n", err)
			return
		}
		err = chk.PrintAnaNum("ycdf", 1e-15, YcdfCmp[i], Ycdf, chk.Verbose)
		if err != nil {
			tst.Errorf("cdf failed: %v\n", err)
			return
		}
	}
}
Exemplo n.º 17
0
// Hairer-Wanner VII-p5 Eq.(1.5) Van der Pol's Equation
func Test_ode02(tst *testing.T) {

	//verbose()
	chk.PrintTitle("ode02: Hairer-Wanner VII-p5 Eq.(1.5) Van der Pol's Equation")

	// problem definition
	eps := 1.0e-6
	fcn := func(f []float64, dx, x float64, y []float64, args ...interface{}) error {
		f[0] = y[1]
		f[1] = ((1.0-y[0]*y[0])*y[1] - y[0]) / eps
		return nil
	}
	jac := func(dfdy *la.Triplet, dx, x float64, y []float64, args ...interface{}) error {
		if dfdy.Max() == 0 {
			dfdy.Init(2, 2, 4)
		}
		dfdy.Start()
		dfdy.Put(0, 0, 0.0)
		dfdy.Put(0, 1, 1.0)
		dfdy.Put(1, 0, (-2.0*y[0]*y[1]-1.0)/eps)
		dfdy.Put(1, 1, (1.0-y[0]*y[0])/eps)
		return nil
	}

	// method and flags
	silent := false
	fixstp := false
	//method := "Dopri5"
	method := "Radau5"
	numjac := false
	xa, xb := 0.0, 2.0
	ya := []float64{2.0, -0.6}
	ndim := len(ya)

	// structure to hold numerical results
	res := Results{Method: method}

	// allocate ODE object
	var o Solver
	if numjac {
		o.Init(method, ndim, fcn, nil, nil, SimpleOutput, silent)
	} else {
		o.Init(method, ndim, fcn, jac, nil, SimpleOutput, silent)
	}

	// tolerances and initial step size
	rtol := 1e-4
	atol := rtol
	o.IniH = 1.0e-4
	o.SetTol(atol, rtol)
	//o.NmaxSS = 2

	// solve problem
	y := make([]float64, ndim)
	copy(y, ya)
	t0 := time.Now()
	if fixstp {
		o.Solve(y, xa, xb, 0.05, fixstp, &res)
	} else {
		o.Solve(y, xa, xb, xb-xa, fixstp, &res)
	}
	io.Pfmag("elapsed time = %v\n", time.Now().Sub(t0))

	// plot
	if chk.Verbose {
		plt.SetForEps(1.5, 400)
		args := "'b-', marker='.', lw=1, ms=4, clip_on=0"
		Plot("/tmp/gosl/ode", "vdpolA.eps", &res, nil, xa, xb, "", args, func() {
			_, T, err := io.ReadTable("data/vdpol_radau5_for.dat")
			if err != nil {
				chk.Panic("%v", err)
			}
			plt.Subplot(3, 1, 1)
			plt.Plot(T["x"], T["y0"], "'k+',label='reference',ms=7")
			plt.Subplot(3, 1, 2)
			plt.Plot(T["x"], T["y1"], "'k+',label='reference',ms=7")
		})
	}
}
Exemplo n.º 18
0
func Test_flt04(tst *testing.T) {

	//verbose()
	chk.PrintTitle("flt04. two-bar truss. Pareto-optimal")

	// configuration
	C := NewConfParams()
	C.Nisl = 4
	C.Ninds = 24
	C.GAtype = "crowd"
	C.DiffEvol = true
	C.CrowdSize = 3
	C.ParetoPhi = 0.05
	C.Tf = 100
	C.Dtmig = 25
	C.RangeFlt = [][]float64{{0.1, 2.25}, {0.5, 2.5}}
	C.PopFltGen = PopFltGen
	C.CalcDerived()
	rnd.Init(C.Seed)

	// data
	// from Coelho (2007) page 19
	ρ := 0.283 // lb/in³
	H := 100.0 // in
	P := 1e4   // lb
	E := 3e7   // lb/in²
	σ0 := 2e4  // lb/in²

	// functions
	TSQ2 := 2.0 * math.Sqrt2
	fcn := func(f, g, h []float64, x []float64) {
		f[0] = 2.0 * ρ * H * x[1] * math.Sqrt(1.0+x[0]*x[0])
		f[1] = P * H * math.Pow(1.0+x[0]*x[0], 1.5) * math.Sqrt(1.0+math.Pow(x[0], 4.0)) / (TSQ2 * E * x[0] * x[0] * x[1])
		g[0] = σ0 - P*(1.0+x[0])*math.Sqrt(1.0+x[0]*x[0])/(TSQ2*x[0]*x[1])
		g[1] = σ0 - P*(1.0-x[0])*math.Sqrt(1.0+x[0]*x[0])/(TSQ2*x[0]*x[1])
	}

	// objective value function
	C.OvaOor = func(ind *Individual, idIsland, t int, report *bytes.Buffer) {
		x := ind.GetFloats()
		f := make([]float64, 2)
		g := make([]float64, 2)
		fcn(f, g, nil, x)
		ind.Ovas[0] = f[0]
		ind.Ovas[1] = f[1]
		ind.Oors[0] = utl.GtePenalty(g[0], 0, 1)
		ind.Oors[1] = utl.GtePenalty(g[1], 0, 1)
	}

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

	// results
	if chk.Verbose {

		// reference data
		_, dat, _ := io.ReadTable("data/coelho-fig1.6.dat")

		// Pareto-front
		feasible := sim.Evo.GetFeasible()
		ovas, _ := sim.Evo.GetResults(feasible)
		ovafront, _ := sim.Evo.GetParetoFront(feasible, ovas, nil)
		xova, yova := sim.Evo.GetFrontOvas(0, 1, ovafront)

		// plot
		plt.SetForEps(0.75, 355)
		plt.Plot(dat["f1"], dat["f2"], "'k+',ms=3")
		x := utl.DblsGetColumn(0, ovas)
		y := utl.DblsGetColumn(1, ovas)
		plt.Plot(x, y, "'r.'")
		plt.Plot(xova, yova, "'ko',markerfacecolor='none',ms=6")
		plt.Gll("$f_1$", "$f_2$", "")
		plt.SaveD("/tmp/goga", "test_flt04.eps")
	}
}
Exemplo n.º 19
0
func main() {

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

	if mpi.Rank() == 0 {
		chk.PrintTitle("ode04: Hairer-Wanner VII-p376 Transistor Amplifier\n")
	}
	if mpi.Size() != 3 {
		chk.Panic(">> error: this test requires 3 MPI processors\n")
		return
	}

	// data
	UE, UB, UF, ALPHA, BETA := 0.1, 6.0, 0.026, 0.99, 1.0e-6
	R0, R1, R2, R3, R4, R5 := 1000.0, 9000.0, 9000.0, 9000.0, 9000.0, 9000.0
	R6, R7, R8, R9 := 9000.0, 9000.0, 9000.0, 9000.0
	W := 2.0 * 3.141592654 * 100.0

	// initial values
	xa := 0.0
	ya := []float64{0.0,
		UB,
		UB / (R6/R5 + 1.0),
		UB / (R6/R5 + 1.0),
		UB,
		UB / (R2/R1 + 1.0),
		UB / (R2/R1 + 1.0),
		0.0}

	// endpoint of integration
	xb := 0.05
	//xb = 0.0123 // OK
	//xb = 0.01235 // !OK

	// right-hand side of the amplifier problem
	w := make([]float64, 8) // workspace
	fcn := func(f []float64, dx, x float64, y []float64, args ...interface{}) error {
		UET := UE * math.Sin(W*x)
		FAC1 := BETA * (math.Exp((y[3]-y[2])/UF) - 1.0)
		FAC2 := BETA * (math.Exp((y[6]-y[5])/UF) - 1.0)
		la.VecFill(f, 0)
		switch mpi.Rank() {
		case 0:
			f[0] = y[0] / R9
		case 1:
			f[1] = (y[1]-UB)/R8 + ALPHA*FAC1
			f[2] = y[2]/R7 - FAC1
		case 2:
			f[3] = y[3]/R5 + (y[3]-UB)/R6 + (1.0-ALPHA)*FAC1
			f[4] = (y[4]-UB)/R4 + ALPHA*FAC2
			f[5] = y[5]/R3 - FAC2
			f[6] = y[6]/R1 + (y[6]-UB)/R2 + (1.0-ALPHA)*FAC2
			f[7] = (y[7] - UET) / R0
		}
		mpi.AllReduceSum(f, w)
		return nil
	}

	// Jacobian of the amplifier problem
	jac := func(dfdy *la.Triplet, dx, x float64, y []float64, args ...interface{}) error {
		FAC14 := BETA * math.Exp((y[3]-y[2])/UF) / UF
		FAC27 := BETA * math.Exp((y[6]-y[5])/UF) / UF
		if dfdy.Max() == 0 {
			dfdy.Init(8, 8, 16)
		}
		NU := 2
		dfdy.Start()
		switch mpi.Rank() {
		case 0:
			dfdy.Put(2+0-NU, 0, 1.0/R9)
			dfdy.Put(2+1-NU, 1, 1.0/R8)
			dfdy.Put(1+2-NU, 2, -ALPHA*FAC14)
			dfdy.Put(0+3-NU, 3, ALPHA*FAC14)
			dfdy.Put(2+2-NU, 2, 1.0/R7+FAC14)
		case 1:
			dfdy.Put(1+3-NU, 3, -FAC14)
			dfdy.Put(2+3-NU, 3, 1.0/R5+1.0/R6+(1.0-ALPHA)*FAC14)
			dfdy.Put(3+2-NU, 2, -(1.0-ALPHA)*FAC14)
			dfdy.Put(2+4-NU, 4, 1.0/R4)
			dfdy.Put(1+5-NU, 5, -ALPHA*FAC27)
		case 2:
			dfdy.Put(0+6-NU, 6, ALPHA*FAC27)
			dfdy.Put(2+5-NU, 5, 1.0/R3+FAC27)
			dfdy.Put(1+6-NU, 6, -FAC27)
			dfdy.Put(2+6-NU, 6, 1.0/R1+1.0/R2+(1.0-ALPHA)*FAC27)
			dfdy.Put(3+5-NU, 5, -(1.0-ALPHA)*FAC27)
			dfdy.Put(2+7-NU, 7, 1.0/R0)
		}
		return nil
	}

	// matrix "M"
	c1, c2, c3, c4, c5 := 1.0e-6, 2.0e-6, 3.0e-6, 4.0e-6, 5.0e-6
	var M la.Triplet
	M.Init(8, 8, 14)
	M.Start()
	NU := 1
	switch mpi.Rank() {
	case 0:
		M.Put(1+0-NU, 0, -c5)
		M.Put(0+1-NU, 1, c5)
		M.Put(2+0-NU, 0, c5)
		M.Put(1+1-NU, 1, -c5)
		M.Put(1+2-NU, 2, -c4)
		M.Put(1+3-NU, 3, -c3)
	case 1:
		M.Put(0+4-NU, 4, c3)
		M.Put(2+3-NU, 3, c3)
		M.Put(1+4-NU, 4, -c3)
	case 2:
		M.Put(1+5-NU, 5, -c2)
		M.Put(1+6-NU, 6, -c1)
		M.Put(0+7-NU, 7, c1)
		M.Put(2+6-NU, 6, c1)
		M.Put(1+7-NU, 7, -c1)
	}

	// flags
	silent := false
	fixstp := false
	//method := "Dopri5"
	method := "Radau5"
	ndim := len(ya)
	numjac := false

	// structure to hold numerical results
	res := ode.Results{Method: method}

	// ODE solver
	var osol ode.Solver
	osol.Pll = true

	// solve problem
	if numjac {
		osol.Init(method, ndim, fcn, nil, &M, ode.SimpleOutput, silent)
	} else {
		osol.Init(method, ndim, fcn, jac, &M, ode.SimpleOutput, silent)
	}
	osol.IniH = 1.0e-6 // initial step size

	// set tolerances
	atol, rtol := 1e-11, 1e-5
	osol.SetTol(atol, rtol)

	// run
	t0 := time.Now()
	if fixstp {
		osol.Solve(ya, xa, xb, 0.01, fixstp, &res)
	} else {
		osol.Solve(ya, xa, xb, xb-xa, fixstp, &res)
	}

	// plot
	if mpi.Rank() == 0 {
		io.Pfmag("elapsed time = %v\n", time.Now().Sub(t0))
		plt.SetForEps(2.0, 400)
		args := "'b-', marker='.', lw=1, clip_on=0"
		ode.Plot("/tmp/gosl/ode", "hwamplifier_mpi.eps", &res, nil, xa, xb, "", args, func() {
			_, T, err := io.ReadTable("data/radau5_hwamplifier.dat")
			if err != nil {
				chk.Panic("%v", err)
			}
			for j := 0; j < ndim; j++ {
				plt.Subplot(ndim+1, 1, j+1)
				plt.Plot(T["x"], T[io.Sf("y%d", j)], "'k+',label='reference',ms=10")
			}
		})
	}
}