// NewCubicSplineFunction creates a cubic spline function based on a
// set of points.
761217
func NewCubicSplineFunction(points Points) *CubicSplineFunction {
	if points.Len() < 3 {
		return nil
	}
	csf := &CubicSplineFunction{
		points: points,
	}
	// Calculating differences between points.
	intervals := points.Len() - 1
	differences := make([]float64, intervals)
	for i := 0; i < intervals; i++ {
		differences[i] = points[i+1].X() - points[i].X()
	}
	mu := make([]float64, intervals)
	z := make([]float64, points.Len())
	var g float64
	for i := 1; i < intervals; i++ {
		g = 2.0*points.XDifference(i+1, i-1) - differences[i-1]*mu[i-1]
		mu[i] = differences[i] / g
		z[i] = (3.0*(points.YAt(i+1)*differences[i-1]-points.YAt(i)*
			points.XDifference(i+1, i-1)+points.YAt(i-1)*differences[i])/
			(differences[i-1]*differences[i]) - differences[i-1]*z[i-1]) / g
	}
	// Cubic spline coefficients (b is linear, c is quadratic, d is cubic).
	b := make([]float64, intervals)
	c := make([]float64, points.Len())
	d := make([]float64, intervals)
	for i := intervals - 1; i >= 0; i-- {
		c[i] = z[i] - mu[i]*c[i+1]
		b[i] = points.YDifference(i+1, i)/differences[i] - differences[i]*(c[i+1]+2.0*c[i])/3.0
		d[i] = (c[i+1] - c[i]) / (3.0 * differences[i])
	}
	// Build polymonials.
	csf.polynomials = make([]*PolynomialFunction, intervals)
	coefficients := make([]float64, 4)
	for i := 0; i < intervals; i++ {
		coefficients[0] = points.YAt(i)
		coefficients[1] = b[i]
		coefficients[2] = c[i]
		coefficients[3] = d[i]
		csf.polynomials[i] = NewPolynomialFunction(coefficients)
	}
	return csf
}
1171865
func NewMultiLineStringFlat(layout Layout, flatCoords []float64, ends []int) *MultiLineString {
	g := new(MultiLineString)
	g.layout = layout
	g.stride = layout.Stride()
	g.flatCoords = flatCoords
	g.ends = ends
	return g
}
712606
func NewFromPointers(points []geo.Pointer) *Quadtree {
	if len(points) == 0 {
		// This is kind of meaningless but is what will happen
		// if using an empty pointset above.
		return New(geo.NewBound(0, 0, 0, 0))
	}

	b := geo.NewBoundFromPoints(points[0].Point(), points[0].Point())
	for _, p := range points {
		b.Extend(p.Point())
	}

	q := New(b, len(points))

	for _, p := range points {
		q.Insert(p)
	}

	return q
}
323138
func NewCustomBicubicFilter(b, c float64) Filter {
	f := &bicubic{}
	f.a = 1 - b/3
	f.b = -3 + 2*b + c
	f.c = 2 - 3*b/2 - c
	f.d = 4*b/3 + 4*c
	f.e = -2*b - 8*c
	f.f = b + 5*c
	f.g = -b/6 - c
	return f
}
961255
func NewZlispWithFuncs(funcs map[string]ZlispUserFunction) *Zlisp {
	env := new(Zlisp)
	env.baseTypeCtor = MakeUserFunction("__basetype_ctor", BaseTypeConstructorFunction)
	env.parser = env.NewParser()
	env.parser.Start()
	env.datastack = env.NewStack(DataStackSize)
	env.linearstack = env.NewStack(ScopeStackSize)

	glob := env.NewNamedScope("global")
	glob.IsGlobal = true
	env.linearstack.Push(glob)
	env.addrstack = env.NewStack(CallStackSize)
	env.loopstack = env.NewStack(LoopStackSize)
	env.builtins = make(map[int]*SexpFunction)
	env.reserved = make(map[int]bool)
	env.macros = make(map[int]*SexpFunction)
	env.symtable = make(map[string]int)
	env.revsymtable = make(map[int]string)
	env.nextsymbol = 1
	env.before = []PreHook{}
	env.after = []PostHook{}
	env.infixOps = make(map[string]*InfixOp)
	env.AddGlobal("null", SexpNull)
	env.AddGlobal("nil", SexpNull)

	for key, function := range funcs {
		sym := env.MakeSymbol(key)
		env.builtins[sym.number] = MakeUserFunction(key, function)
		env.AddFunction(key, function)
	}

	for _, word := range ReservedWords {
		sym := env.MakeSymbol(word)
		env.reserved[sym.number] = true
	}

	env.mainfunc = env.MakeFunction("__main", 0, false,
		make([]Instruction, 0), nil)
	env.curfunc = env.mainfunc
	env.pc = 0
	env.debugSymbolNotFound = false
	//env.debugSymbolNotFound = true
	//env.debugExec = true
	env.InitInfixOps()

	return env

}
561732
func newGenericFunc(methodName, paramName string, fn interface{}, validateFunc func(*functionCache) error) (*genericFunc, error) {
	cache := &functionCache{}
	cache.FnValue = reflect.ValueOf(fn)

	if cache.FnValue.Kind() != reflect.Func {
		return nil, fmt.Errorf("%s: parameter [%s] is not a function type. It is a '%s'", methodName, paramName, cache.FnValue.Type())
	}
	cache.MethodName = methodName
	cache.ParamName = paramName
	cache.FnType = cache.FnValue.Type()
	numTypesIn := cache.FnType.NumIn()
	cache.TypesIn = make([]reflect.Type, numTypesIn)
	for i := 0; i < numTypesIn; i++ {
		cache.TypesIn[i] = cache.FnType.In(i)
	}

	numTypesOut := cache.FnType.NumOut()
	cache.TypesOut = make([]reflect.Type, numTypesOut)
	for i := 0; i < numTypesOut; i++ {
		cache.TypesOut[i] = cache.FnType.Out(i)
	}
	if err := validateFunc(cache); err != nil {
		return nil, err
	}

	return &genericFunc{Cache: cache}, nil
}
408734
func (o *DSCPForwardingClassTable) CreateDSCPForwardingClassMapping(child *DSCPForwardingClassMapping) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
646136
func (er *expressionRewriter) newFunction(funcName string, retType *types.FieldType, args ...expression.Expression) (expression.Expression, error) {
	if er.disableFoldCounter > 0 {
		return expression.NewFunctionBase(er.ctx, funcName, retType, args...)
	}
	return expression.NewFunction(er.ctx, funcName, retType, args...)
}
1094387
func NewPCMFloatBuffer(data []float64, format *Format) *PCMBuffer {
	return &PCMBuffer{
		Format:   format,
		DataType: Float,
		Floats:   data,
	}
}
547749
func Flatten(path *Path, flattener Flattener, scale float64) {
	// First Point
	var startX, startY float64
	// Current Point
	var x, y float64
	var i int
	for _, cmp := range path.Components {
		switch cmp {
		case MoveToComponent:
			x, y = path.Points[i], path.Points[i+1]
			startX, startY = x, y
			if i != 0 {
				flattener.End()
			}
			flattener.MoveTo(x, y)
			i += 2
		case LineToComponent:
			x, y = path.Points[i], path.Points[i+1]
			flattener.LineTo(x, y)
			flattener.LineJoin()
			i += 2
		case QuadCurveToComponent:
			// we include the previous point for the start of the curve
			TraceQuad(flattener, path.Points[i-2:], 0.5)
			x, y = path.Points[i+2], path.Points[i+3]
			flattener.LineTo(x, y)
			i += 4
		case CubicCurveToComponent:
			TraceCubic(flattener, path.Points[i-2:], 0.5)
			x, y = path.Points[i+4], path.Points[i+5]
			flattener.LineTo(x, y)
			i += 6
		case ArcToComponent:
			x, y = TraceArc(flattener, path.Points[i], path.Points[i+1], path.Points[i+2], path.Points[i+3], path.Points[i+4], path.Points[i+5], scale)
			flattener.LineTo(x, y)
			i += 6
		case CloseComponent:
			flattener.LineTo(startX, startY)
			flattener.Close()
		}
	}
	flattener.End()
}
1271685
func NewFromPointSet(set *geo.PointSet) *Quadtree {
	q := New(set.Bound(), set.Length())

	ps := []geo.Point(*set)
	for i := range ps {
		q.Insert(&ps[i])
	}

	return q
}
1324324
func interpolationFuncFlatten() ast.Function {
	return ast.Function{
		ArgTypes:   []ast.Type{ast.TypeList},
		ReturnType: ast.TypeList,
		Variadic:   false,
		Callback: func(args []interface{}) (interface{}, error) {
			inputList := args[0].([]ast.Variable)

			var outputList []ast.Variable
			return flattener(outputList, inputList), nil
		},
	}
}
568503
func TraceCubic(t Liner, cubic []float64, flatteningThreshold float64) {
	// Allocation curves
	var curves [CurveRecursionLimit * 8]float64
	copy(curves[0:8], cubic[0:8])
	i := 0

	// current curve
	var c []float64

	var dx, dy, d2, d3 float64

	for i >= 0 {
		c = curves[i*8:]
		dx = c[6] - c[0]
		dy = c[7] - c[1]

		d2 = math.Abs((c[2]-c[6])*dy - (c[3]-c[7])*dx)
		d3 = math.Abs((c[4]-c[6])*dy - (c[5]-c[7])*dx)

		// if it's flat then trace a line
		if (d2+d3)*(d2+d3) < flatteningThreshold*(dx*dx+dy*dy) || i == len(curves)-1 {
			t.LineTo(c[6], c[7])
			i--
		} else {
			// second half of bezier go lower onto the stack
			SubdivideCubic(c, curves[(i+1)*8:], curves[i*8:])
			i++
		}
	}
}
1188608
func NewPoint(l Layout) *Point {
	return NewPointFlat(l, make([]float64, l.Stride()))
}
227877
func newplanFunc(e *expr, fn GraphiteFunc, context Context, stable bool, reqs []Req) ([]Req, error) {
	// first comes the interesting task of validating the arguments as specified by the function,
	// against the arguments that were parsed.

	argsExp, _ := fn.Signature()
	var err error

	// note:
	// * signature may have seriesLists in it, which means one or more args of type seriesList
	//   so it's legal to have more e.args than signature args in that case.
	// * we can't do extensive, accurate validation of the type here because what the output from a function we depend on
	//   might be dynamically typed. e.g. movingAvg returns 1..N series depending on how many it got as input

	// first validate the mandatory args
	pos := 0    // e.args[pos]     : next given arg to process
	cutoff := 0 // argsExp[cutoff] : will be first optional arg (if any)
	var argExp Arg
	for cutoff, argExp = range argsExp {
		if argExp.Optional() {
			break
		}
		if len(e.args) <= pos {
			return nil, ErrMissingArg
		}
		pos, err = e.consumeBasicArg(pos, argExp)
		if err != nil {
			return nil, err
		}
	}
	if !argExp.Optional() {
		cutoff++
	}

	// we stopped iterating the mandatory args.
	// any remaining args should be due to optional args otherwise there's too many
	// we also track here which keywords can also be used for the given optional args
	// so that those args should not be specified via their keys anymore.

	seenKwargs := make(map[string]struct{})
	for _, argOpt := range argsExp[cutoff:] {
		if len(e.args) <= pos {
			break // no more args specified. we're done.
		}
		pos, err = e.consumeBasicArg(pos, argOpt)
		if err != nil {
			return nil, err
		}
		seenKwargs[argOpt.Key()] = struct{}{}
	}
	if len(e.args) > pos {
		return nil, ErrTooManyArg
	}

	// for any provided keyword args, verify that they are what the function stipulated
	// and that they have not already been specified via their position
	for key := range e.namedArgs {
		_, ok := seenKwargs[key]
		if ok {
			return nil, ErrKwargSpecifiedTwice{key}
		}
		err = e.consumeKwarg(key, argsExp[cutoff:])
		if err != nil {
			return nil, err
		}
		seenKwargs[key] = struct{}{}
	}

	// functions now have their non-series input args set,
	// so they should now be able to specify any context alterations
	context = fn.Context(context)
	// now that we know the needed context for the data coming into
	// this function, we can set up the input arguments for the function
	// that are series
	pos = 0
	for _, argExp = range argsExp {
		if pos >= len(e.args) {
			break // no more args specified. we're done.
		}
		switch argExp.(type) {
		case ArgSeries, ArgSeriesList, ArgSeriesLists, ArgIn:
			pos, reqs, err = e.consumeSeriesArg(pos, argExp, context, stable, reqs)
			if err != nil {
				return nil, err
			}
		default:
			pos++
		}
	}
	return reqs, err
}
391226
func (lsf *LeastSquaresFunction) AppendPoint(x, y float64) {
	p := NewPoint(x, y)
	if lsf.count == 0 {
		lsf.xBar = p.X()
		lsf.yBar = p.Y()
	} else {
		dx := p.X() - lsf.xBar
		dy := p.Y() - lsf.yBar

		lsf.sumXX += dx * dx * float64(lsf.count) / float64(lsf.count+1.0)
		lsf.sumYY += dy * dy * float64(lsf.count) / float64(lsf.count+1.0)
		lsf.sumXY += dx * dy * float64(lsf.count) / float64(lsf.count+1.0)

		lsf.xBar += dx / float64(lsf.count+1.0)
		lsf.yBar += dy / float64(lsf.count+1.0)
	}
	lsf.sumX += p.X()
	lsf.sumY += p.Y()
	lsf.count++
}
497572
func ChordAngleBetweenPoints(x, y Point) s1.ChordAngle {
	return s1.ChordAngle(math.Min(4.0, x.Sub(y.Vector).Norm2()))
}