Beispiel #1
0
func plot_pareto_test(buf *bytes.Buffer, fnkey string, Φ, Zu []float64, show, negative bool) {
	io.Ff(buf, "from gosl import SetForEps, Save\n")
	io.Ff(buf, "from mpl_toolkits.mplot3d import Axes3D\n")
	io.Ff(buf, "import matplotlib.pyplot as plt\n")
	io.Ff(buf, "import numpy as np\n")
	io.Ff(buf, "fig = plt.figure()\n")
	io.Ff(buf, "ax = fig.add_subplot(111, projection='3d')\n")
	write_python_array(buf, "phi", Φ)
	write_python_array(buf, "dz", Zu)
	io.Ff(buf, "SetForEps(0.75, 455, mplclose=0, text_usetex=0)\n")
	io.Ff(buf, "n=len(phi)\nx,y=np.meshgrid(phi,np.linspace(0,1,7))\nx=x.flatten()\ny=y.flatten()\nz=np.zeros(n*7)\n")
	io.Ff(buf, "ax.bar3d(x,y,z,dx=0.1*np.ones(n*7),dy=0.1*np.ones(n*7),dz=dz, color='#cee9ff')\n")
	io.Ff(buf, "ax.set_xlabel('$\\phi$')\n")
	io.Ff(buf, "ax.set_zlabel('u-wins [%%]')\n")
	io.Ff(buf, "ax.set_xticks([0,0.25,0.5,0.75,1])\n")
	io.Ff(buf, "ax.set_xticklabels(['0.0','0.25','0.5','0.75','1.0'])\n")
	if negative {
		io.Ff(buf, "ax.set_yticklabels(['u=[-1 -2 -3 -4 -5 -6]', 'u=[-2 -2 -3 -4 -5 -6]', 'u=[-2 -3 -3 -4 -5 -6]', 'u=[-2 -3 -4 -4 -5 -6]', 'u=[-2 -3 -4 -5 -5 -6]', 'u=[-2 -3 -4 -5 -6 -6]', 'u=[-2 -3 -4 -5 -6 -7]'], rotation=-15,verticalalignment='baseline',horizontalalignment='left')\n")
	} else {
		io.Ff(buf, "ax.set_yticklabels(['v=[1 2 3 4 5 6]', 'v=[2 2 3 4 5 6]', 'v=[2 3 3 4 5 6]', 'v=[2 3 4 4 5 6]', 'v=[2 3 4 5 5 6]', 'v=[2 3 4 5 6 6]', 'v=[2 3 4 5 6 7]'], rotation=-15,verticalalignment='baseline',horizontalalignment='left')\n")
	}
	io.Ff(buf, "import matplotlib.patheffects as path_effects\n")
	io.Ff(buf, "for i, xval in enumerate(x): ax.text(xval,y[i],dz[i],'%%.2f'%%dz[i],color='#bf0000',fontsize=10, path_effects=[path_effects.withSimplePatchShadow(offset=(1,-1),shadow_rgbFace='white')])\n")
	if show {
		io.Ff(buf, "plt.show()\n")
	} else {
		io.Ff(buf, "plt.savefig('/tmp/gosl/%s.eps')\n", fnkey)
		io.Ff(buf, "print 'file </tmp/gosl/%s.eps> witten'\n", fnkey)
	}
	io.WriteFileVD("/tmp/gosl", io.Sf("%s.py", fnkey), buf)
}
Beispiel #2
0
func WriteAllValues(dirout, fnkey string, opt *Optimiser) {
	var buf bytes.Buffer
	io.Ff(&buf, "%5s", "front")
	for i := 0; i < opt.Nova; i++ {
		io.Ff(&buf, "%24s", io.Sf("f%d", i))
	}
	for i := 0; i < opt.Noor; i++ {
		io.Ff(&buf, "%24s", io.Sf("u%d", i))
	}
	for i := 0; i < opt.Nflt; i++ {
		io.Ff(&buf, "%24s", io.Sf("x%d", i))
	}
	for i := 0; i < opt.Nint; i++ {
		io.Ff(&buf, "%24s", io.Sf("y%d", i))
	}
	io.Ff(&buf, "\n")
	for _, sol := range opt.Solutions {
		io.Ff(&buf, "%5d", sol.FrontId)
		for i := 0; i < opt.Nova; i++ {
			io.Ff(&buf, "%24g", sol.Ova[i])
		}
		for i := 0; i < opt.Noor; i++ {
			io.Ff(&buf, "%24g", sol.Oor[i])
		}
		for i := 0; i < opt.Nflt; i++ {
			io.Ff(&buf, "%24g", sol.Flt[i])
		}
		for i := 0; i < opt.Nint; i++ {
			io.Ff(&buf, "%24g", sol.Int[i])
		}
		io.Ff(&buf, "\n")
	}
	io.WriteFileVD(dirout, fnkey+".res", &buf)
}
Beispiel #3
0
func vtu_write(geo, dat *bytes.Buffer) {
	if geo == nil || dat == nil {
		return
	}
	nv := len(verts)
	nc := len(cells)
	var hdr, foo bytes.Buffer
	io.Ff(&hdr, "<?xml version=\"1.0\"?>\n<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n<UnstructuredGrid>\n")
	io.Ff(&hdr, "<Piece NumberOfPoints=\"%d\" NumberOfCells=\"%d\">\n", nv, nc)
	io.Ff(&foo, "</Piece>\n</UnstructuredGrid>\n</VTKFile>\n")
	io.WriteFileVD(dirout, fnkey+".vtu", &hdr, geo, dat, &foo)
}
Beispiel #4
0
func Test_pareto04(tst *testing.T) {

	//verbose()
	chk.PrintTitle("pareto04. Pareto front")

	ovs := [][]float64{
		{1.0, 8.0}, {1.8, 7.0}, {2.2, 6.5}, {2.5, 6.0}, {2.8, 5.5}, {3.0, 6.0},
		{3.1, 7.3}, {3.0, 6.0}, {3.5, 4.5}, {3.9, 6.8}, {4.0, 5.5}, {4.1, 3.8},
		{4.3, 6.7}, {4.4, 3.6}, {4.5, 6.0}, {5.0, 3.0}, {5.1, 5.0}, {5.5, 2.8},
		{6.0, 2.5}, {6.5, 7.4}, {6.5, 6.5}, {7.0, 4.0}, {7.0, 2.0}, {8.0, 1.8},
	}

	front := ParetoFront(ovs)
	chk.Ints(tst, "front", front, []int{0, 1, 2, 3, 4, 8, 11, 13, 15, 17, 18, 22, 23})

	if chk.Verbose {

		n := len(front)
		Xp := make([]float64, n)
		Yp := make([]float64, n)
		for k, i := range front {
			Xp[k] = ovs[i][0]
			Yp[k] = ovs[i][1]
		}

		var buf bytes.Buffer
		io.Ff(&buf, "from gosl import SetForEps, Save, Gll\n")
		io.Ff(&buf, "import matplotlib.pyplot as plt\n")
		io.Ff(&buf, "import numpy as np\n")
		io.Ff(&buf, "SetForEps(0.75, 355)\n")
		write_python_matrix(&buf, "XY", ovs)
		write_python_array(&buf, "Xp", Xp)
		write_python_array(&buf, "Yp", Yp)
		io.Ff(&buf, "plt.plot(XY[:,0],XY[:,1],'r.',clip_on=0)\n")
		io.Ff(&buf, "plt.plot(Xp,Yp,'ko',markerfacecolor='none',ms=7,clip_on=0)\n")
		io.Ff(&buf, "Gll('x','y','')\n")
		io.Ff(&buf, "Save('/tmp/gosl/test_pareto04.eps')\n")
		io.Ff(&buf, "print 'file </tmp/gosl/test_pareto04.eps> witten'\n")
		io.WriteFileVD("/tmp/gosl", "test_pareto04.py", &buf)
	}
}
Beispiel #5
0
func main() {

	buf := goga.TexDocumentStart()

	io.Ff(buf, `
\begin{table} [!t] \centering
\caption{Random variables used in benchmark tests.}

\begin{tabular}[c]{ccccccc} \toprule
P & var & $\mu$ & $\sigma$ & distr & min & max \\ \hline
`)

	for i := 1; i < 19; i++ {
		opt := new(goga.Optimiser)
		opt.ProbNum = i
		_, vars := get_simple_data(opt)
		v := vars[0]
		io.Pforan("vars = %v\n", vars)
		io.Ff(buf, `%d & $x_0$ & %g & %g & %s & %g & %g \\`, i, v.M, v.S, rnd.GetDistrName(v.D), v.Min, v.Max)
		for j := 1; j < len(vars); j++ {
			v = vars[j]
			io.Ff(buf, ` & $x_%d$ & %g & %g & %s & %g & %g \\`, j, v.M, v.S, rnd.GetDistrName(v.D), v.Min, v.Max)
			io.Ff(buf, "\n")
		}
		io.Ff(buf, " \\hline\n\n")
	}

	io.Ff(buf, `
\end{tabular}
\label{tab:prms-simple}
\end{table}
`)

	goga.TexDocumentEnd(buf)
	io.WriteFileVD("/tmp/goga", "prms-table-simple.tex", buf)
}
Beispiel #6
0
func main() {

	// catch errors
	defer func() {
		if err := recover(); err != nil {
			io.PfRed("ERROR: %v\n", err)
		}
	}()

	// input data
	filename, fnkey := io.ArgToFilename(0, "data/equations.txt", "", true)
	io.Pf("\n%s\n", io.ArgsTable("INPUT ARGUMENTS",
		"file with equations", "filename", filename,
	))

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

	// open file
	f, err := io.OpenFileR(filename)
	if err != nil {
		return
	}

	// constants
	MAXNIDX := 100
	INDICES := []string{"i", "j", "k", "l", "m", "n", "r", "s", "p", "q"}

	// read file
	var buf bytes.Buffer
	io.ReadLinesFile(f, func(idx int, line string) (stop bool) {

		// indices
		l := line
		for i := 0; i < MAXNIDX; i++ {
			l = strings.Replace(l, io.Sf("[%d]", i), io.Sf("_{%d}", i), -1)
		}
		for _, idx := range INDICES {
			l = strings.Replace(l, io.Sf("[%s]", idx), io.Sf("_{%s}", idx), -1)
		}

		// constants
		l = strings.Replace(l, "math.Sqrt2", "\\sqrt{2}", -1)
		l = strings.Replace(l, "SQ2", "\\sqrt{2}", -1)

		// functions
		l = strings.Replace(l, "math.Sqrt", "\\sqrt", -1)
		l = strings.Replace(l, "math.Pow", "\\pow", -1)
		l = strings.Replace(l, "math.Exp", "\\exp", -1)
		l = strings.Replace(l, "math.Sin", "\\sin", -1)
		l = strings.Replace(l, "math.Cos", "\\cos", -1)

		// star
		l = strings.Replace(l, "*", " \\, ", -1)

		// colon-equal
		l = strings.Replace(l, ":=", "=", -1)

		// add to results
		io.Ff(&buf, "%s\n", l)
		return
	})

	// write file
	io.WriteFileVD("/tmp/gosl", fnkey+".tex", &buf)
}
Beispiel #7
0
func main() {

	// read README.md file
	md, err := io.ReadFile("README.md")
	if err != nil {
		io.PfRed("cannot read README.md\n")
		return
	}

	// process markdown
	//html := string(blackfriday.MarkdownCommon(md))

	flags := 0 |
		blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_USE_SMARTYPANTS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES

	extensions := 0 |
		blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
		blackfriday.EXTENSION_TABLES |
		blackfriday.EXTENSION_FENCED_CODE |
		blackfriday.EXTENSION_AUTOLINK |
		blackfriday.EXTENSION_STRIKETHROUGH |
		blackfriday.EXTENSION_SPACE_HEADERS |
		blackfriday.EXTENSION_HEADER_IDS |
		blackfriday.EXTENSION_BACKSLASH_LINE_BREAK |
		blackfriday.EXTENSION_DEFINITION_LISTS

	renderer := blackfriday.HtmlRenderer(flags, "", "")
	html := string(blackfriday.MarkdownOptions(md, renderer, blackfriday.Options{Extensions: extensions}))

	// environment variable => figures path
	path := os.ExpandEnv("${GOPATH}/src/github.com/cpmech/gofem/")
	io.Pforan("path = %v\n", path)

	// set path of figures
	html = strings.Replace(html, "img src=\"", io.Sf("img src=\"%s/examples/", path), -1)

	// set header and footer
	html = `<!DOCTYPE HTML>
<html>
<head>
<title>Gofem &ndash; Examples</title>
<meta charset="utf-8" />

<style>
h1 {color:#0064cb; font-family:verdana; font-size:200%;}
h2 {color:#0064cb}
h3 {color:#0064cb}
a:hover {background-color:#5397dc;}
#container {
	width:500px;
	text-align:center;
}
#container img {
	max-width:100%;
	height:auto;
}
</style>

</head>
<body>
` + html + `
</body>
</html>`

	// write file
	io.WriteFileVD("/tmp", "gofem-README.html", bytes.NewBuffer([]byte(html)))
	//io.WriteFileVD("/tmp", "gofem-README.html", bytes.NewBuffer(html))
}
Beispiel #8
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
}
Beispiel #9
0
func tex_results(dirout, fnkey, title, label string, dat *FemData, A, B, C, D, E *goga.Solution, document, compact bool) {
	if len(A.Flt) != 10 {
		chk.Panic("tex_results works with len(Areas)==10 only\n")
		return
	}
	buf := new(bytes.Buffer)
	if document {
		io.Ff(buf, `\documentclass[a4paper]{article}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{booktabs}
\usepackage[margin=1.5cm,footskip=0.5cm]{geometry}

\title{GOGA Report}
\author{Dorival Pedroso}

\begin{document}

`)
	}
	io.Ff(buf, `\begin{table} \centering
\caption{%s}
`, title)
	if compact {
		io.Ff(buf, `\begin{tabular}[c]{cccccccc} \toprule
point & weight & deflection &  $A_0$ & $A_1$ & $A_2$ & $A_3$ & $A_4$   \\
      &        &            &  $A_5$ & $A_6$ & $A_7$ & $A_8$ & $A_9$   \\ \hline
`)
	} else {
		io.Ff(buf, `\begin{tabular}[c]{ccccccccccccc} \toprule
point & weight & deflection & $A_0$ & $A_1$ & $A_2$ & $A_3$ & $A_4$ & $A_5$ & $A_6$ & $A_7$ & $A_8$ & $A_9$ \\ \hline
`)
	}

	writeline := func(pt string, E []int, A []float64) {
		_, _, weight, deflection, _, _, _ := dat.RunFEM(E, A, 0, false)
		if compact {
			io.Ff(buf, "%s & $%.2f$ & $%.6f$ &  $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ \\\\\n", pt, weight, deflection, A[0], A[1], A[2], A[3], A[4])
			io.Ff(buf, "   &        &        &  $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ \\\\\n", A[5], A[6], A[7], A[8], A[9])
		} else {
			io.Ff(buf, "%s & $%.2f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ & $%.6f$ \\\\\n", pt, weight, deflection, A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[8], A[9])
		}
	}

	writeline("A", A.Int, A.Flt)
	writeline("B", B.Int, B.Flt)
	writeline("C", C.Int, C.Flt)
	writeline("D", D.Int, D.Flt)
	writeline("E", E.Int, E.Flt)

	io.Ff(buf, `
\bottomrule
\end{tabular}
\label{tab:%s}
\end{table}
`, label)
	if document {
		io.Ff(buf, ` \end{document}`)
	}

	tex := fnkey + ".tex"
	if document {
		io.WriteFileD(dirout, tex, buf)
		_, err := io.RunCmd(true, "pdflatex", "-interaction=batchmode", "-halt-on-error", "-output-directory=/tmp/goga/", tex)
		if err != nil {
			chk.Panic("%v", err)
		}
		io.PfBlue("file <%s/%s.pdf> generated\n", dirout, fnkey)
	} else {
		io.WriteFileVD(dirout, tex, buf)
	}
}
Beispiel #10
0
// WriteMshD writes .msh file
// Input:
//   vtagged -- maps hashed id of control point to vertex tag
//   ctagged -- maps idOfNurbs_localIdOfElem to cell tag
//   tol     -- tolerance for normalized numbers comparison when generating hashes, e.g. 1e-7
func WriteMshD(dirout, fnk string, nurbss []*Nurbs, vtagged map[int]int, ctagged map[string]int, tol float64) {

	// compute limits
	xmin, xmax, xdel := GetLimits(nurbss[0])
	for r := 1; r < len(nurbss); r++ {
		xmi, xma, _ := GetLimits(nurbss[r])
		for i := 0; i < 3; i++ {
			xmin[i] = utl.Min(xmin[i], xmi[i])
			xmax[i] = utl.Min(xmax[i], xma[i])
		}
	}
	if len(nurbss) > 1 {
		for i := 0; i < 3; i++ {
			xdel[i] = xmax[i] - xmin[i]
		}
	}

	var buf bytes.Buffer
	io.Ff(&buf, "{\n  \"verts\" : [\n")
	verts := make(map[int]int)
	vid := 0
	for _, o := range nurbss {
		for k := 0; k < o.n[2]; k++ {
			for j := 0; j < o.n[1]; j++ {
				for i := 0; i < o.n[0]; i++ {
					x := o.GetQ(i, j, k)
					hsh := HashPoint(x, xmin, xdel, tol)
					if _, ok := verts[hsh]; !ok {
						tag := 0
						if vtagged != nil {
							if val, tok := vtagged[hsh]; tok {
								tag = val
							}
						}

						// TODO: remove this
						if math.Abs(x[0]) < 1e-7 {
							tag = -100 // vertical
						}
						if math.Abs(x[1]) < 1e-7 {
							tag = -200 // horizontal
						}

						if len(verts) > 0 {
							io.Ff(&buf, ",\n")
						}
						io.Ff(&buf, "    { \"id\":%3d, \"tag\":%3d, \"c\":[%24.17e,%24.17e,%24.17e,%24.17e] }", vid, tag, x[0], x[1], x[2], x[3])
						verts[hsh] = vid
						vid += 1
					}
				}
			}
		}
	}
	io.Ff(&buf, "\n  ],\n  \"nurbss\" : [\n")
	for sid, o := range nurbss {
		if sid > 0 {
			io.Ff(&buf, ",\n")
		}
		io.Ff(&buf, "    { \"id\":%d, \"gnd\":%d, \"ords\":[%d,%d,%d],\n", sid, o.gnd, o.p[0], o.p[1], o.p[2])
		io.Ff(&buf, "      \"knots\":[\n")
		for d := 0; d < o.gnd; d++ {
			if d > 0 {
				io.Ff(&buf, ",\n")
			}
			io.Ff(&buf, "        [")
			for i, t := range o.b[d].T {
				if i > 0 {
					io.Ff(&buf, ",")
				}
				io.Ff(&buf, "%24.17e", t)
			}
			io.Ff(&buf, "]")
		}
		io.Ff(&buf, "\n      ],\n      \"ctrls\":[")
		first := true
		for k := 0; k < o.n[2]; k++ {
			for j := 0; j < o.n[1]; j++ {
				for i := 0; i < o.n[0]; i++ {
					if !first {
						io.Ff(&buf, ",")
					}
					x := o.GetQ(i, j, k)
					hsh := HashPoint(x, xmin, xdel, tol)
					io.Ff(&buf, "%d", verts[hsh])
					if first {
						first = false
					}
				}
			}
		}
		io.Ff(&buf, "]\n    }")
	}
	io.Ff(&buf, "\n  ],\n  \"cells\" : [\n")
	ndim := nurbss[0].gnd
	bry := make([]bool, 2*ndim)
	fti2d := []int{2, 1, 3, 0}
	ftags := []int{-10, -11, -20, -21, -30, -31}
	cid := 0
	for sid, o := range nurbss {
		spanmin := make([]int, ndim)
		spanmax := make([]int, ndim)
		for i := 0; i < ndim; i++ {
			spanmin[i] = o.p[i]
			spanmax[i] = o.n[i] // TODO: check this
		}
		elems := o.Elements()
		for eid, e := range elems {
			ibasis := o.IndBasis(e)
			if cid > 0 {
				io.Ff(&buf, ",\n")
			}
			tag := -1
			if ctagged != nil {
				if val, tok := ctagged[io.Sf("%d_%d", sid, eid)]; tok {
					tag = val
				}
			}

			// TODO: find a better way to tag cells
			if e[1] == spanmax[0] && e[2] == spanmin[1] {
				tag = -2
			}

			io.Ff(&buf, "    { \"id\":%3d, \"tag\":%2d, \"nrb\":%d, \"part\":0, \"type\":\"nurbs\",", cid, tag, sid)
			io.Ff(&buf, " \"span\":[")
			for k, idx := range e {
				if k > 0 {
					io.Ff(&buf, ",")
				}
				io.Ff(&buf, "%d", idx)
			}
			io.Ff(&buf, "], \"verts\":[")
			for i, l := range ibasis {
				if i > 0 {
					io.Ff(&buf, ",")
				}
				x := o.GetQl(l)
				hsh := HashPoint(x, xmin, xdel, tol)
				io.Ff(&buf, "%d", verts[hsh])
			}
			var onbry bool
			for i := 0; i < 2*ndim; i++ {
				bry[i] = false
			}
			for i := 0; i < ndim; i++ {
				smin, smax := e[i*ndim], e[i*ndim+1]
				if smin == spanmin[i] {
					bry[i*ndim] = true
					onbry = true
				}
				if smax == spanmax[i] {
					bry[i*ndim+1] = true
					onbry = true
				}
			}
			io.Ff(&buf, "]")
			if onbry && ndim > 1 {
				io.Ff(&buf, ", \"ftags\":[")
				for i := 0; i < 2*ndim; i++ {
					tag := 0
					I := i
					if ndim == 2 {
						I = fti2d[i]
					}
					if bry[I] {
						if ndim == 2 {
							tag = ftags[fti2d[i]]

							// TODO: replace this by a better approach
							if i == 2 {
								r := spanmin[0] + (spanmax[0]-spanmin[0])/2
								//io.Pforan("e[0]=%v r=%v\n", e[0], r)
								if e[0] >= r {
									tag = -24
								}
							}

						} else {
							tag = ftags[i]
						}
					}
					if i > 0 {
						io.Ff(&buf, ",")
					}
					io.Ff(&buf, "%d", tag)
				}
				io.Ff(&buf, "]")
			}
			io.Ff(&buf, " }")
			cid += 1
		}
	}
	io.Ff(&buf, "\n  ]\n}")
	io.WriteFileVD(dirout, fnk+".msh", &buf)
}
Beispiel #11
0
func main() {

	// catch errors
	defer func() {
		if err := recover(); err != nil {
			io.PfRed("ERROR: %v\n", err)
		}
	}()

	// input data
	mshfn, fnkey := io.ArgToFilename(0, "data/sgm57", ".msh", true)

	// old mesh
	var old OldMesh

	// read file
	b, err := io.ReadFile(mshfn)
	if err != nil {
		chk.Panic("%v", err)
	}

	// decode
	err = json.Unmarshal(b, &old)
	if err != nil {
		chk.Panic("%v", err)
	}

	// verts: find largest strings
	var ndim int
	L := make([]int, 5)
	for _, v := range old.Verts {
		L[0] = utl.Imax(L[0], len(io.Sf("%d", v.Id)))
		L[1] = utl.Imax(L[1], len(io.Sf("%d", v.Tag)))
		for j, x := range v.C {
			L[2+j] = utl.Imax(L[2+j], len(io.Sf("%g", x)))
		}
		ndim = len(v.C)
	}
	S := make([]string, 5)
	for i, l := range L {
		S[i] = io.Sf("%d", l)
	}

	// write vertices
	buf := new(bytes.Buffer)
	io.Ff(buf, "{\n  \"verts\":[\n")
	for i, v := range old.Verts {
		if i > 0 {
			io.Ff(buf, ",\n")
		}
		io.Ff(buf, "    {\"i\":%"+S[0]+"d, \"t\":%"+S[1]+"d, \"x\":[", v.Id, v.Tag)
		for j, x := range v.C {
			if j > 0 {
				io.Ff(buf, ", ")
			}
			io.Ff(buf, "%"+S[2+j]+"g", x)
		}
		io.Ff(buf, "] }")
	}

	// cells: find largest strings
	n := 30
	L = make([]int, n*2)
	for _, c := range old.Cells {
		L[0] = utl.Imax(L[0], len(io.Sf("%d", c.Id)))
		L[1] = utl.Imax(L[1], len(io.Sf("%d", c.Tag)))
		L[2] = utl.Imax(L[2], len(io.Sf("%d", c.Part)))
		for j, v := range c.Verts {
			L[3+j] = utl.Imax(L[3+j], len(io.Sf("%d", v)))
		}
	}
	S = make([]string, n*2)
	for i, l := range L {
		S[i] = io.Sf("%d", l)
	}
	io.Ff(buf, "\n  ],")

	// write cells
	io.Ff(buf, "\n  \"cells\":[\n")
	for i, c := range old.Cells {
		if i > 0 {
			io.Ff(buf, ",\n")
		}
		io.Ff(buf, "    {\"i\":%"+S[0]+"d, \"t\":%"+S[1]+"d, \"p\":%"+S[2]+"d, \"y\":%q, \"v\":[", c.Id, c.Tag, c.Part, c.Type)
		for j, v := range c.Verts {
			if j > 0 {
				io.Ff(buf, ", ")
			}
			io.Ff(buf, "%"+S[3+j]+"d", v)
		}
		io.Ff(buf, "]")
		if len(c.FTags) > 0 {
			io.Ff(buf, ", ")
			if ndim == 2 {
				io.Ff(buf, "\"et\":[")
			} else {
				io.Ff(buf, "\"ft\":[")
			}
			for j, t := range c.FTags {
				if j > 0 {
					io.Ff(buf, ", ")
				}
				io.Ff(buf, "%d", t)
			}
			io.Ff(buf, "]")
		}
		io.Ff(buf, " }")
	}
	io.Ff(buf, "\n  ]\n}")
	io.WriteFileVD("/tmp/gosl", fnkey+"-new.msh", buf)

	// check
	m, err := msh.Read("/tmp/gosl/" + fnkey + "-new.msh")
	if err != nil {
		chk.Panic("cannot read new mesh:\n%v", err)
	}
	m.Check()
}
Beispiel #12
0
func solve_problem(fnkey string, problem int) (opt *goga.Optimiser) {

	// GA parameters
	opt = new(goga.Optimiser)
	opt.Default()

	// options for report
	opt.RptFmtF = "%.4f"
	opt.RptFmtX = "%.3f"
	opt.RptFmtFdev = "%.1e"
	opt.RptWordF = "\\beta"
	opt.HistFmt = "%.2f"
	opt.HistNdig = 3
	opt.HistDelFmin = 0.005
	opt.HistDelFmax = 0.005

	// FORM data
	var lsft LSF_T
	var vars rnd.Variables

	// simple problem or FEM sim
	if fnkey == "simple" {
		opt.Read("ga-simple.json")
		opt.ProbNum = problem
		lsft, vars = get_simple_data(opt)
		fnkey += io.Sf("-%d", opt.ProbNum)
		io.Pf("\n----------------------------------- simple problem %d --------------------------------\n", opt.ProbNum)
	} else {
		opt.Read("ga-" + fnkey + ".json")
		lsft, vars = get_femsim_data(opt, fnkey)
		io.Pf("\n----------------------------------- femsim %s --------------------------------\n", fnkey)
	}

	// set limits
	nx := len(vars)
	opt.FltMin = make([]float64, nx)
	opt.FltMax = make([]float64, nx)
	for i, dat := range vars {
		opt.FltMin[i] = dat.Min
		opt.FltMax[i] = dat.Max
	}

	// log input
	var buf bytes.Buffer
	io.Ff(&buf, "%s", opt.LogParams())
	io.WriteFileVD("/tmp/gosl", fnkey+".log", &buf)

	// initialise distributions
	err := vars.Init()
	if err != nil {
		chk.Panic("cannot initialise distributions:\n%v", err)
	}

	// plot distributions
	if opt.PlotSet1 {
		io.Pf(". . . . . . . .  plot distributions  . . . . . . . .\n")
		np := 201
		for i, dat := range vars {
			plt.SetForEps(0.75, 250)
			dat.PlotPdf(np, "'b-',lw=2,zorder=1000")
			//plt.AxisXrange(dat.Min, dat.Max)
			plt.SetXnticks(15)
			plt.SaveD("/tmp/sims", io.Sf("distr-%s-%d.eps", fnkey, i))
		}
		return
	}

	// objective function
	nf := 1
	var ng, nh int
	var fcn goga.MinProb_t
	var obj goga.ObjFunc_t
	switch opt.Strategy {

	// argmin_x{ β(y(x)) | lsf(x) ≤ 0 }
	//  f ← sqrt(y dot y)
	//  g ← -lsf(x) ≥ 0
	//  h ← out-of-range in case Transform fails
	case 0:
		ng, nh = 1, 1
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {

			// original and normalised variables
			h[0] = 0
			y, invalid := vars.Transform(x)
			if invalid {
				h[0] = 1
				return
			}

			// objective value
			f[0] = math.Sqrt(la.VecDot(y, y)) // β

			// inequality constraint
			lsf, failed := lsft(x, cpu)
			g[0] = -lsf
			h[0] = failed
		}

	// argmin_x{ β(y(x)) | lsf(x) = 0 }
	//  f  ← sqrt(y dot y)
	//  h0 ← lsf(x)
	//  h1 ← out-of-range in case Transform fails
	case 1:
		ng, nh = 0, 2
		fcn = func(f, g, h, x []float64, ξ []int, cpu int) {

			// original and normalised variables
			h[0], h[1] = 0, 0
			y, invalid := vars.Transform(x)
			if invalid {
				h[0], h[1] = 1, 1
				return
			}

			// objective value
			f[0] = math.Sqrt(la.VecDot(y, y)) // β

			// equality constraint
			lsf, failed := lsft(x, cpu)
			h[0] = lsf
			h[1] = failed

			// induce minmisation of h0
			//f[0] += math.Abs(lsf)
		}

	case 2:
		opt.Nova = 1
		opt.Noor = 2
		obj = func(sol *goga.Solution, cpu int) {

			// clear out-of-range values
			sol.Oor[0] = 0 // invalid transformation or FEM failed
			sol.Oor[1] = 0 // g(x) ≤ 0 was violated

			// original and normalised variables
			x := sol.Flt
			y, invalid := vars.Transform(x)
			if invalid {
				sol.Oor[0] = goga.INF
				sol.Oor[1] = goga.INF
				return
			}

			// objective value
			sol.Ova[0] = math.Sqrt(la.VecDot(y, y)) // β

			// inequality constraint
			lsf, failed := lsft(x, cpu)
			sol.Oor[0] = failed
			sol.Oor[1] = fun.Ramp(lsf)
		}

	default:
		chk.Panic("strategy %d is not available", opt.Strategy)
	}

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

	// solve
	io.Pf(". . . . . . . .  running  . . . . . . . .\n")
	opt.RunMany("", "")
	goga.StatF(opt, 0, true)
	io.Pfblue2("Tsys = %v\n", opt.SysTimeAve)

	// check
	goga.CheckFront0(opt, true)

	// results
	sols := goga.GetFeasible(opt.Solutions)
	if len(sols) > 0 {
		goga.SortByOva(sols, 0)
		best := sols[0]
		io.Pforan("x    = %.6f\n", best.Flt)
		io.Pforan("xref = %.6f\n", opt.RptXref)
		io.Pforan("β = %v  (%v)\n", best.Ova[0], opt.RptFref[0])
	}
	return
}
Beispiel #13
0
// Generate generates report
func (o *TexReport) Generate() {

	// functions
	o.col4 = "error"
	o.col5 = io.Sf("histogram ($N_{samples}=%d$)", o.nsamples)
	addHeader := o.normalTableHeader
	addRow := o.oneNormalAddRow
	switch o.Type {
	case 1:
		o.col4 = "objective"
	case 2:
		o.col5 = "spread"
		addRow = o.twoAddRow
	case 3:
		addRow = o.multiAddRow
	case 4:
		addHeader = o.compactTableHeader
		addRow = o.oneCompactAddRow
	}

	// number of rows per table
	nRowPerTab := o.NRowPerTab
	if nRowPerTab < 1 {
		nRowPerTab = len(o.Opts)
	}
	if o.RefLabel == "" {
		o.RefLabel = o.Fnkey
	}

	// input and xres tables
	o.inputHeader()
	o.xResHeader()

	// add rows
	idxtab := 0
	contd := ""
	for i, opt := range o.Opts {
		if i%nRowPerTab == 0 {
			if i > 0 {
				o.tableFooter(idxtab) // end previous table
				io.Ff(o.buf, "\n\n\n")
				contd = " (contd.)"
				idxtab++
			}
			addHeader(contd) // begin new table
		} else {
			if i > 0 {
				if o.Type != 4 {
					io.Ff(o.buf, "\\hline\n")
				}
				//io.Ff(o.bxres, "\n\\hline\n")
				io.Ff(o.buf, "\n")
			}
		}
		addRow(opt)
		o.inputRow(opt)
		o.xResRow(opt)
	}

	// close tables
	o.inputFooter()
	io.Ff(o.binp, "\n\n\n")
	o.xResFooter()
	o.tableFooter(idxtab) // end previous table
	io.Ff(o.buf, "\n\n\n")

	// write table
	tex := o.Fnkey + ".tex"
	io.WriteFileVD(o.DirOut, tex, o.buf, o.binp, o.bxres)

	// generate PDF
	if o.RunPDF {
		header := new(bytes.Buffer)
		footer := new(bytes.Buffer)
		str := ""
		if o.UseGeom {
			str = `\usepackage[margin=1.5cm,footskip=0.5cm]{geometry}`
		}
		io.Ff(header, `\documentclass[a4paper]{article}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{booktabs}
%s

\title{GOGA Report}
\author{Dorival Pedroso}

\begin{document}
`, str)
		io.Ff(footer, `
\end{document}`)

		// write temporary TeX file
		tex = "tmp_" + tex
		io.WriteFileD(o.DirOut, tex, header, o.buf, o.binp, o.bxres, footer)

		// run pdflatex
		_, err := io.RunCmd(false, "pdflatex", "-interaction=batchmode", "-halt-on-error", "-output-directory="+o.DirOut, tex)
		if err != nil {
			io.PfRed("pdflatex failed: %v\n", err)
			return
		}
		io.PfBlue("file <%s/tmp_%s.pdf> generated\n", o.DirOut, o.Fnkey)
	}
}
Beispiel #14
0
func Test_flt03(tst *testing.T) {

	//verbose()
	chk.PrintTitle("flt03. sin⁶(5 π x) multimodal")

	// configuration
	C := NewConfParams()
	C.Nova = 1
	C.Noor = 2
	C.Nisl = 4
	C.Ninds = 24
	C.GAtype = "crowd"
	C.DiffEvol = true
	C.CrowdSize = 3
	C.ParetoPhi = 0.01
	C.CompProb = true
	C.Tf = 100
	C.Dtmig = 60
	C.RangeFlt = [][]float64{{0, 0.9999999999999}}
	C.PopFltGen = PopFltGen
	C.CalcDerived()
	rnd.Init(C.Seed)

	// post-processing function
	values := utl.Deep3alloc(C.Tf/10, C.Nisl, C.Ninds)
	C.PostProc = func(idIsland, time int, pop Population) {
		if time%10 == 0 {
			k := time / 10
			for i, ind := range pop {
				values[k][idIsland][i] = ind.GetFloat(0)
			}
		}
	}

	// functions
	yfcn := func(x float64) float64 { return math.Pow(math.Sin(5.0*math.Pi*x), 6.0) }
	fcn := func(f, g, h []float64, x []float64) {
		f[0] = -yfcn(x[0])
	}

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

	// write histograms and plot
	if chk.Verbose {

		// write histograms
		var buf bytes.Buffer
		hist := rnd.Histogram{Stations: utl.LinSpace(0, 1, 13)}
		for k := 0; k < C.Tf/10; k++ {
			for i := 0; i < C.Nisl; i++ {
				clear := false
				if i == 0 {
					clear = true
				}
				hist.Count(values[k][i], clear)
			}
			io.Ff(&buf, "\ntime=%d\n%v", k*10, rnd.TextHist(hist.GenLabels("%4.2f"), hist.Counts, 60))
		}
		io.WriteFileVD("/tmp/goga", "test_flt03_hist.txt", &buf)

		// plot
		plt.SetForEps(0.8, 300)
		xmin := sim.Evo.Islands[0].Pop[0].GetFloat(0)
		xmax := xmin
		for k := 0; k < C.Nisl; k++ {
			for _, ind := range sim.Evo.Islands[k].Pop {
				x := ind.GetFloat(0)
				y := yfcn(x)
				xmin = utl.Min(xmin, x)
				xmax = utl.Max(xmax, x)
				plt.PlotOne(x, y, "'r.',clip_on=0,zorder=20")
			}
		}
		np := 401
		X := utl.LinSpace(0, 1, np)
		Y := make([]float64, np)
		for i := 0; i < np; i++ {
			Y[i] = yfcn(X[i])
		}
		plt.Plot(X, Y, "'b-',clip_on=0,zorder=10")
		plt.Gll("$x$", "$y$", "")
		plt.SaveD("/tmp/goga", "test_flt03_func.eps")
	}
}
Beispiel #15
0
// WriteMshD writes .msh file
// Input: vtagged maps hashed id of control point to vertex tag
//        ctagged maps idOfNurbs_localIdOfElem to cell tag
func WriteMshD(dirout, fnk string, nurbss []*Nurbs, vtagged map[int]int, ctagged map[string]int) {
	var buf bytes.Buffer
	io.Ff(&buf, "{\n  \"verts\" : [\n")
	verts := make(map[int]int)
	vid := 0
	for _, o := range nurbss {
		for k := 0; k < o.n[2]; k++ {
			for j := 0; j < o.n[1]; j++ {
				for i := 0; i < o.n[0]; i++ {
					x := o.GetQ(i, j, k)
					hsh := HashPoint(x[0], x[1], x[2])
					if _, ok := verts[hsh]; !ok {
						tag := 0
						if vtagged != nil {
							if val, tok := vtagged[hsh]; tok {
								tag = val
							}
						}
						if len(verts) > 0 {
							io.Ff(&buf, ",\n")
						}
						io.Ff(&buf, "    { \"id\":%3d, \"tag\":%3d, \"c\":[%24.17e,%24.17e,%24.17e,%24.17e] }", vid, tag, x[0], x[1], x[2], x[3])
						verts[hsh] = vid
						vid += 1
					}
				}
			}
		}
	}
	io.Ff(&buf, "\n  ],\n  \"nurbss\" : [\n")
	for sid, o := range nurbss {
		if sid > 0 {
			io.Ff(&buf, ",\n")
		}
		io.Ff(&buf, "    { \"id\":%d, \"gnd\":%d, \"ords\":[%d,%d,%d],\n", sid, o.gnd, o.p[0], o.p[1], o.p[2])
		io.Ff(&buf, "      \"knots\":[\n")
		for d := 0; d < o.gnd; d++ {
			if d > 0 {
				io.Ff(&buf, ",\n")
			}
			io.Ff(&buf, "        [")
			for i, t := range o.b[d].T {
				if i > 0 {
					io.Ff(&buf, ",")
				}
				io.Ff(&buf, "%24.17e", t)
			}
			io.Ff(&buf, "]")
		}
		io.Ff(&buf, "\n      ],\n      \"ctrls\":[")
		first := true
		for k := 0; k < o.n[2]; k++ {
			for j := 0; j < o.n[1]; j++ {
				for i := 0; i < o.n[0]; i++ {
					if !first {
						io.Ff(&buf, ",")
					}
					x := o.GetQ(i, j, k)
					hsh := HashPoint(x[0], x[1], x[2])
					io.Ff(&buf, "%d", verts[hsh])
					if first {
						first = false
					}
				}
			}
		}
		io.Ff(&buf, "]\n    }")
	}
	io.Ff(&buf, "\n  ],\n  \"cells\" : [\n")
	cid := 0
	for sid, o := range nurbss {
		elems := o.Elements()
		enodes := o.Enodes()
		for eid, e := range elems {
			if cid > 0 {
				io.Ff(&buf, ",\n")
			}
			tag := -1
			if ctagged != nil {
				if val, tok := ctagged[io.Sf("%d_%d", sid, eid)]; tok {
					tag = val
				}
			}
			io.Ff(&buf, "    { \"id\":%3d, \"tag\":%2d, \"nrb\":%d, \"part\":0, \"geo\":%d,", cid, tag, sid, NURBS_GEO)
			io.Ff(&buf, " \"span\":[")
			for k, idx := range e {
				if k > 0 {
					io.Ff(&buf, ",")
				}
				io.Ff(&buf, "%d", idx)
			}
			io.Ff(&buf, "], \"verts\":[")
			for i, l := range enodes[eid] {
				if i > 0 {
					io.Ff(&buf, ",")
				}
				x := o.GetQl(l)
				hsh := HashPoint(x[0], x[1], x[2])
				io.Ff(&buf, "%d", verts[hsh])
			}
			io.Ff(&buf, "] }")
			cid += 1
		}
	}
	io.Ff(&buf, "\n  ]\n}")
	io.WriteFileVD(dirout, fnk+".msh", &buf)
}