// 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 }
// ReadSmat reads a smat matrix back func ReadSmat(fn string) *Triplet { var t Triplet io.ReadLines(fn, func(idx int, line string) (stop bool) { r := strings.Fields(line) if idx == 0 { m, n, nnz := io.Atoi(r[0]), io.Atoi(r[1]), io.Atoi(r[2]) t.Init(m, n, nnz) } else { t.Put(io.Atoi(r[0]), io.Atoi(r[1]), io.Atof(r[2])) } return }) return &t }
func main() { // input data simfile := "simfile.sim" zmin := 0.0 zmax := 3.0 npts := 11 // parse flags flag.Parse() if len(flag.Args()) > 0 { simfile = flag.Arg(0) } if len(flag.Args()) > 1 { zmin = io.Atof(flag.Arg(1)) } if len(flag.Args()) > 2 { zmax = io.Atob(flag.Arg(2)) } if len(flag.Args()) > 3 { npts = io.Atoi(flag.Arg(3)) } // print input data io.Pf("\nInput data\n") io.Pf("==========\n") io.Pf(" simfile = %30s // simulation filename\n", simfile) io.Pf(" zmin = %30s // min elevation\n", zmin) io.Pf(" zmax = %30v // max elevation\n", zmax) io.Pf(" npts = %30v // number of points\n", npts) io.Pf("\n") // sim file sim := inp.ReadSim("", simfile, false) if sim == nil { io.PfRed("cannot read sim file\n") return } // layer var lay fem.GeoLayer lay.Zmin = zmin lay.Zmax = zmax lay.Cl = sim.WaterRho0 / sim.WaterBulk //if !lay.ReadPorousParameters(sim.Regions[0], // TODO }
func main() { // default input data fn := "nurbs01.msh" ctrl := true ids := true npts := 41 // parse flags flag.Parse() if len(flag.Args()) > 0 { fn = flag.Arg(0) } if len(flag.Args()) > 1 { ctrl = io.Atob(flag.Arg(1)) } if len(flag.Args()) > 2 { ids = io.Atob(flag.Arg(2)) } if len(flag.Args()) > 3 { npts = io.Atoi(flag.Arg(3)) } // print input data io.Pforan("Input data\n") io.Pforan("==========\n") io.Pfblue2(" fn = %v\n", fn) io.Pfblue2(" ctrl = %v\n", ctrl) io.Pfblue2(" ids = %v\n", ids) io.Pfblue2(" npts = %v\n", npts) // load nurbss fnk := io.FnKey(fn) B := gm.ReadMsh(fnk) // plot plt.SetForEps(0.75, 500) for _, b := range B { if ctrl { b.DrawCtrl2d(ids, "", "") } b.DrawElems2d(npts, ids, "", "") } plt.Equal() plt.Save(fnk + ".eps") }
func main() { // input data simfn := "elast.sim" matname := "lrm1" pcmax := 30.0 npts := 101 // parse flags flag.Parse() if len(flag.Args()) > 0 { simfn = flag.Arg(0) } if len(flag.Args()) > 1 { matname = flag.Arg(1) } if len(flag.Args()) > 2 { pcmax = io.Atof(flag.Arg(2)) } if len(flag.Args()) > 3 { npts = io.Atoi(flag.Arg(3)) } // check extension if io.FnExt(simfn) == "" { simfn += ".sim" } // print input data io.Pf("\nInput data\n") io.Pf("==========\n") io.Pf(" simfn = %30s // simulation filename\n", simfn) io.Pf(" matname = %30s // material name\n", matname) io.Pf(" pcmax = %30v // max pc\n", pcmax) io.Pf(" npts = %30v // number of points\n", npts) io.Pf("\n") // load simulation sim := inp.ReadSim("", simfn, "lrm_", false) if sim == nil { io.PfRed("cannot load simulation\n") return } // get material data mat := sim.Mdb.Get(matname) if mat == nil { io.PfRed("cannot get material\n") return } io.Pforan("mat = %v\n", mat) // get and initialise model mdl := mreten.GetModel(simfn, matname, mat.Model, false) if mdl == nil { io.PfRed("cannot allocate model\n") return } mdl.Init(mat.Prms) // plot drying path d_Pc := utl.LinSpace(0, pcmax, npts) d_Sl := make([]float64, npts) d_Sl[0] = 1 var err error for i := 1; i < npts; i++ { d_Sl[i], err = mreten.Update(mdl, d_Pc[i-1], d_Sl[i-1], d_Pc[i]-d_Pc[i-1]) if err != nil { io.PfRed("drying: cannot updated model\n%v\n", err) return } } plt.Plot(d_Pc, d_Sl, io.Sf("'b-', label='%s (dry)', clip_on=0", matname)) // plot wetting path w_Pc := utl.LinSpace(pcmax, 0, npts) w_Sl := make([]float64, npts) w_Sl[0] = d_Sl[npts-1] for i := 1; i < npts; i++ { w_Sl[i], err = mreten.Update(mdl, w_Pc[i-1], w_Sl[i-1], w_Pc[i]-w_Pc[i-1]) if err != nil { io.PfRed("wetting: cannot updated model\n%v\n", err) return } } plt.Plot(w_Pc, w_Sl, io.Sf("'c-', label='%s (wet)', clip_on=0", matname)) // save results type Results struct{ Pc, Sl []float64 } res := Results{append(d_Pc, w_Pc...), append(d_Sl, w_Sl...)} var buf bytes.Buffer enc := json.NewEncoder(&buf) err = enc.Encode(&res) if err != nil { io.PfRed("cannot encode results\n") return } fn := path.Join(sim.Data.DirOut, matname+".dat") io.WriteFile(fn, &buf) io.Pf("file <[1;34m%s[0m> written\n", fn) // show figure plt.AxisYrange(0, 1) plt.Cross() plt.Gll("$p_c$", "$s_{\\ell}$", "") plt.Show() }
func (o *STEP) ParseDATA(dat string) (err error) { // remove newlines and split commands sdat := strings.Replace(dat, "\n", "", -1) res := strings.Split(sdat, ";") // allocate maps o.Points = make(map[string]*Cartesian_point) o.BScurves = make(map[string]*B_spline_curve_with_knots) o.Scurves = make(map[string]*Surface_curve) // for each line reading_data := false for _, lin := range res { // activate data reading lin = strings.TrimSpace(strings.ToLower(lin)) if reading_data { if strings.HasPrefix(lin, "endsec") { return } } else { if strings.HasPrefix(lin, "data") { reading_data = true } continue } // left- and right-hand-sides => key = function lhs_rhs := strings.Split(lin, "=") if len(lhs_rhs) != 2 { continue } // key lhs := strings.TrimSpace(lhs_rhs[0]) // function call rhs := strings.ToLower(strings.TrimSpace(lhs_rhs[1])) // extract entities switch { // Cartesian point case strings.HasPrefix(rhs, "cartesian_point"): sargs := strings.TrimPrefix(rhs, "cartesian_point") args := io.SplitWithinParentheses(sargs) n := len(args) if n != 2 { err = chk.Err("cartesian_point has the wrong number of arguments. %d != %d", n, 2) return } p := Cartesian_point{ Name: args[0], Coordinates: io.SplitFloats(args[1]), } o.Points[lhs] = &p // B-spline curve case strings.HasPrefix(rhs, "b_spline_curve_with_knots"): sargs := strings.TrimPrefix(rhs, "b_spline_curve_with_knots") args := io.SplitWithinParentheses(sargs) n := len(args) if n != 9 { err = chk.Err("b_spline_curve_with_knots has the wrong number of arguments. %d != %d", n, 9) return } b := B_spline_curve_with_knots{ Name: args[0], Degree: io.Atoi(args[1]), Control_points_list: strings.Fields(args[2]), Curve_form: args[3], Closed_curve: atob(args[4]), Self_intersect: atob(args[5]), Knot_multiplicities: io.SplitInts(args[6]), Knots: io.SplitFloats(args[7]), Knot_spec: args[8], } chk.IntAssert(len(b.Knot_multiplicities), len(b.Knots)) o.BScurves[lhs] = &b // surface curve case strings.HasPrefix(rhs, "surface_curve"): sargs := strings.TrimPrefix(rhs, "surface_curve") args := io.SplitWithinParentheses(sargs) n := len(args) if n != 4 { err = chk.Err("surface_curve has the wrong number of arguments. %d != %d", n, 4) return } b := Surface_curve{ Name: args[0], Curve_3d: args[1], Associated_geometry: io.SplitWithinParentheses(args[2]), Master_representation: args[3], } o.Scurves[lhs] = &b } } return }
func Test_extrapapolation(tst *testing.T) { //verbose() chk.PrintTitle("Test extrapolation") GetIpNums := func(name string) []int { var nums []int for key, _ := range ipsfactory { name_n := strings.Split(key, "_") if name_n[0] == name { nip := io.Atoi(name_n[1]) nums = append(nums, nip) } } return nums } for name, shape := range factory { gndim := shape.Gndim if gndim == 1 { continue } io.Pfyel("--------------------------------- %-6s---------------------------------\n", name) for _, nip := range GetIpNums(shape.Type) { if nip <= 1 { continue } io.Pfblue("nip = %v\n", nip) tol := 1.0e-13 // create a N vector with nodal values nverts := shape.Nverts X := shape.NatCoords delta := rand.Float64() N := make([]float64, shape.Nverts) for i := 0; i < shape.Nverts; i++ { var x, y, z float64 x = X[0][i] y = X[1][i] if shape.Gndim == 3 { z = X[2][i] } N[i] = x + y + z + delta } io.Pfblue("N = %v\n", N) // calculate P vector with corresponding values at ips key := name + "_" + strconv.Itoa(nip) ips := ipsfactory[key] P := make([]float64, nip) Xip := la.MatAlloc(nip, 4) // ips local coordinates for i := 0; i < nip; i++ { var x, y, z float64 x = ips[i][0] y = ips[i][1] z = ips[i][2] Xip[i][0] = x Xip[i][1] = y Xip[i][2] = z P[i] = x + y + z + delta } // Allocate E matrix E := la.MatAlloc(nverts, nip) // Calculate extrapolator matrix shape.Extrapolator(E, ips) // Recalculate nodal values NN = E*P NN := make([]float64, shape.Nverts) la.MatVecMul(NN, 1.0, E, P) io.Pfblue("N ext= %v\n", NN) // Compare vectors N and NN msg := name + "_" + strconv.Itoa(nip) chk.Vector(tst, msg, tol, NN, N) } } }
func main() { // input data simfnA := "o2elastCO" skip := 0 simfnB := "" labelA := "" labelB := "" flag.Parse() if len(flag.Args()) > 0 { simfnA = flag.Arg(0) } if len(flag.Args()) > 1 { skip = io.Atoi(flag.Arg(1)) } if len(flag.Args()) > 2 { simfnB = flag.Arg(2) } if len(flag.Args()) > 3 { labelA = flag.Arg(3) } if len(flag.Args()) > 4 { labelB = flag.Arg(4) } // print input data io.Pf("\nInput data\n") io.Pf("==========\n") io.Pf(" simfnA = %30s // simulation filename\n", simfnA) io.Pf(" skip = %30d // number of initial increments to skip\n", skip) io.Pf(" simfnB = %30s // simulation filename for comparison\n", simfnB) io.Pf(" labelA = %30s // label for histogram\n", labelA) io.Pf(" labelB = %30s // label for histogram\n", labelB) io.Pf("\n") // read residuals residA, fnkA := read_summary(simfnA) residB, fnkB := read_summary(simfnB) // residuals: it => residuals io.Pf("\nResiduals A\n") io.Pf("============\n") residA.Print("%10.2e") if simfnB != "" { io.Pf("\nResiduals B\n") io.Pf("============\n") residB.Print("%10.2e") } io.Pf("\n") // plot convergence curves plot_conv_curve(fnkA, skip, residA) if simfnB != "" { plot_conv_curve(fnkB, skip, residB) } // plot histogram io.Pf("\n") X := [][]float64{count_iters(residA)} labels := []string{fnkA} if labelA != "" { labels[0] = labelA } if simfnB != "" { X = append(X, count_iters(residB)) labels = append(labels, fnkB) if labelB != "" { labels[1] = labelB } } plt.Reset() plt.SetForEps(0.75, 300) plt.Hist(X, labels, "") plt.Gll("number of iterations", "counts", "") plt.SaveD("/tmp", "gofem_residplot_"+fnkA+"_"+fnkB+"_hist.eps") }
func main() { // finalise analysis process and catch errors defer out.End() // input data simfn := "data/twoqua4.sim" exnwl := false stgidx := 0 // parse flags flag.Parse() if len(flag.Args()) > 0 { simfn = flag.Arg(0) } if len(flag.Args()) > 1 { exnwl = io.Atob(flag.Arg(1)) } if len(flag.Args()) > 2 { stgidx = io.Atoi(flag.Arg(2)) } // check extension if io.FnExt(simfn) == "" { simfn += ".sim" } // print input data io.Pf("\nInput data\n") io.Pf("==========\n") io.Pf(" simfn = %30s // simulation filename\n", simfn) io.Pf(" exnwl = %30v // extrapolate nwl\n", exnwl) io.Pf(" stgidx = %30v // stage index\n", stgidx) io.Pf("\n") // start analysis process out.Start(simfn, stgidx, 0) // global variables ndim = out.Dom.Msh.Ndim verts = out.Dom.Msh.Verts cells = out.Dom.Msh.Cells nodes = out.Dom.Nodes elems = out.Dom.Elems dirout = fem.Global.Sim.Data.DirOut fnkey = fem.Global.Sim.Data.FnameKey steady = fem.Global.Sim.Data.Steady // flags has_u := out.Dom.YandC["ux"] has_pl := out.Dom.YandC["pl"] has_pg := out.Dom.YandC["pg"] has_sig := out.Ipkeys["sx"] has_nwl := out.Ipkeys["nwlx"] has_p := has_pl || has_pg lbb := has_u && has_p if fem.Global.Sim.Data.NoLBB { lbb = false } // buffers pvd := make(map[string]*bytes.Buffer) geo := make(map[string]*bytes.Buffer) vtu := make(map[string]*bytes.Buffer) if _, ok := out.Dom.YandC["ux"]; ok { pvd["u"] = new(bytes.Buffer) geo["u"] = new(bytes.Buffer) vtu["u"] = new(bytes.Buffer) } if _, ok := out.Dom.YandC["fl"]; ok { pvd["fl"] = new(bytes.Buffer) geo["fl"] = new(bytes.Buffer) vtu["fl"] = new(bytes.Buffer) } if _, ok := out.Dom.YandC["pl"]; ok { pvd["pl"] = new(bytes.Buffer) geo["pl"] = new(bytes.Buffer) vtu["pl"] = new(bytes.Buffer) } if _, ok := out.Dom.YandC["pg"]; ok { pvd["pg"] = new(bytes.Buffer) geo["pg"] = new(bytes.Buffer) vtu["pg"] = new(bytes.Buffer) } if len(out.Ipkeys) > 0 { pvd["ips"] = new(bytes.Buffer) geo["ips"] = new(bytes.Buffer) vtu["ips"] = new(bytes.Buffer) } if exnwl { pvd["ex_nwl"] = new(bytes.Buffer) geo["ex_nwl"] = new(bytes.Buffer) vtu["ex_nwl"] = new(bytes.Buffer) } // extrapolated values keys extrap_keys := []string{"nwlx", "nwly"} if ndim == 3 { extrap_keys = []string{"nwlx", "nwly", "nwlz"} } // headers for _, b := range pvd { pvd_header(b) } // process results for tidx, t := range out.Sum.OutTimes { // input results into domain if !out.Dom.In(out.Sum, tidx, true) { chk.Panic("cannot load results into domain; please check log file") } // message io.PfWhite("time = %g\r", t) // generate topology if tidx == 0 { for label, b := range geo { topology(b, label == "ips", lbb) } // allocate integration points values ipvals = make([]map[string]float64, len(out.Ipoints)) for i, _ := range out.Ipoints { ipvals[i] = make(map[string]float64) } } // get integration points values @ time t for i, p := range out.Ipoints { vals := p.Calc(out.Dom.Sol) for key, val := range vals { ipvals[i][key] = val } } // compute extrapolated values if exnwl { out.ComputeExtrapolatedValues(extrap_keys) } // for each data buffer for label, b := range vtu { // reset buffer b.Reset() // points data if label == "ips" { pdata_open(b) if has_sig { pdata_write(b, "sig", skeys, true) } if has_nwl { pdata_write(b, "nwl", nwlkeys, true) } for key, _ := range out.Ipkeys { if !is_sig[key] && !is_nwl[key] { pdata_write(b, key, []string{key}, true) } } pdata_close(b) } else { pdata_open(b) pdata_write(b, label, label2keys[label], false) pdata_close(b) } // cells data cdata_write(b, label == "ips") // write vtu file vtu_write(geo[label], b, tidx, label) } // pvd for label, b := range pvd { pvd_line(b, tidx, t, label) } } // write pvd files for label, b := range pvd { pvd_write(b, label) } }
// ReadLPfortran reads linear program from particular fortran file // download LP files from here: http://users.clas.ufl.edu/hager/coap/format.html // Output: // A -- compressed-column sparse matrix where: // Ap -- pointers to the begining of storage of column (size n+1) // Ai -- row indices for each non zero entry (input, nnz A) // Ax -- non zero entries (input, nnz A) // b -- right hand side (input, size m) // c -- objective vector (minimize, size n) // l -- lower bounds on variables (size n) // u -- upper bounds on variables (size n) func ReadLPfortran(fn string) (A *la.CCMatrix, b, c, l, u []float64) { // variables var m int // number or rows (input) var n int // number of columns (input) var Ap []int // pointers to the begining of storage of column (size n+1) var Ai []int // row indices for each non zero entry (input, nnz A) var Ax []float64 // non zero entries (input, nnz A) var z0 float64 // initial fixed value for objective // auxiliary reading_Ap := false reading_Ai := false reading_Ax := false reading_b := false reading_c := false reading_z0 := false reading_l := false reading_u := false atof := func(s string) float64 { return io.Atof(strings.Replace(s, "D", "E", 1)) } // read data k := 0 io.ReadLines(fn, func(idx int, line string) (stop bool) { if idx == 0 { // skip name return } str := strings.Fields(line) if idx == 1 { // read m and m m, n = io.Atoi(str[0]), io.Atoi(str[1]) Ap = make([]int, n+1) k = 0 reading_Ap = true return } for _, s := range str { if reading_Ap { if k == n+1 { reading_Ap = false reading_Ai = true nnz := Ap[n] Ai = make([]int, nnz) Ax = make([]float64, nnz) b = make([]float64, m) c = make([]float64, n) l = make([]float64, n) u = make([]float64, n) k = 0 } else { Ap[k] = io.Atoi(s) - 1 // subtract 1 because of Fortran indexing } } if reading_Ai { if k == Ap[n] { reading_Ai = false reading_Ax = true k = 0 } else { Ai[k] = io.Atoi(s) - 1 // subtract 1 because of Fortran indexing } } if reading_Ax { if k == Ap[n] { reading_Ax = false reading_b = true k = 0 } else { Ax[k] = atof(s) } } if reading_b { if k == m { reading_b = false reading_c = true k = 0 } else { b[k] = atof(s) } } if reading_c { if k == n { reading_c = false reading_z0 = true k = 0 } else { c[k] = atof(s) } } if reading_z0 { z0 = atof(s) _ = z0 reading_z0 = false reading_l = true k = 0 return } if reading_l { if k == n { reading_l = false reading_u = true k = 0 } else { l[k] = atof(s) } } if reading_u { if k == n { reading_u = false k = 0 } else { u[k] = atof(s) } } k++ } return }) // debug if false { io.Pforan("Ap = %v\n", Ap) io.Pfcyan("Ai = %v\n", Ai) io.Pfyel("Ax = %v\n", Ax) io.Pf("b = %v\n", b) io.Pforan("c = %v\n", c) io.Pfcyan("l = %v\n", l) io.Pfyel("u = %v\n", u) } // results A = new(la.CCMatrix) A.Set(m, n, Ap, Ai, Ax) return }
// register element func init() { // information allocator infogetters["rod"] = func(cellType string, faceConds []*FaceCond) *Info { // new info var info Info // number of nodes in element nverts := shp.GetNverts(cellType) // solution variables ykeys := []string{"ux", "uy"} if Global.Ndim == 3 { ykeys = []string{"ux", "uy", "uz"} } info.Dofs = make([][]string, nverts) for m := 0; m < nverts; m++ { info.Dofs[m] = ykeys } // maps info.Y2F = map[string]string{"ux": "fx", "uy": "fy", "uz": "fz"} // t1 and t2 variables info.T2vars = ykeys return &info } // element allocator eallocators["rod"] = func(cellType string, faceConds []*FaceCond, cid int, edat *inp.ElemData, x [][]float64) Elem { // basic data var o Rod o.Cid = cid o.X = x o.Shp = shp.Get(cellType) ndim := Global.Ndim o.Nu = ndim * o.Shp.Nverts var err error // material model name matname := edat.Mat matdata := Global.Sim.Mdb.Get(matname) if LogErrCond(matdata == nil, "materials database failed on getting %q material\n", matname) { return nil } mdlname := matdata.Model o.Model = msolid.GetOnedSolid(Global.Sim.Data.FnameKey, matname, mdlname, false) if LogErrCond(o.Model == nil, "cannot find model named %s\n", mdlname) { return nil } err = o.Model.Init(ndim, matdata.Prms) if LogErr(err, "Model.Init failed") { return nil } // parameters for _, p := range matdata.Prms { switch p.N { case "A": o.A = p.V case "rho": o.Rho = p.V } } // integration points var nip int if s_nip, found := io.Keycode(edat.Extra, "nip"); found { nip = io.Atoi(s_nip) } o.IpsElem, err = shp.GetIps(o.Shp.Type, nip) if LogErr(err, "GetIps failed") { return nil } nip = len(o.IpsElem) // scratchpad. computed @ each ip o.K = la.MatAlloc(o.Nu, o.Nu) o.M = la.MatAlloc(o.Nu, o.Nu) o.ue = make([]float64, o.Nu) o.Rus = make([]float64, o.Nu) // scratchpad. computed @ each ip o.grav = make([]float64, ndim) o.us = make([]float64, ndim) o.fi = make([]float64, o.Nu) // return new element return &o } }