Setup of the options for the spline interpolation

        Args:
            spline_options (dict): Options for cubic spline. For example,
                {"saddle_point": "zero_slope"} forces the slope at the saddle to
                be zero.
350809
def setup_spline(self, spline_options=None):
        
        self.spline_options = spline_options
        relative_energies = self.energies - self.energies[0]
        if scipy_old_piecewisepolynomial:
            if self.spline_options:
                raise RuntimeError('Option for saddle point not available with'
                                   'old scipy implementation')
            self.spline = PiecewisePolynomial(
                self.r, np.array([relative_energies, -self.forces]).T,
                orders=3)
        else:
            # New scipy implementation for scipy > 0.18.0
            if self.spline_options.get('saddle_point', '') == 'zero_slope':
                imax = np.argmax(relative_energies)
                self.spline = CubicSpline(x=self.r[:imax + 1],
                                          y=relative_energies[:imax + 1],
                                          bc_type=((1, 0.0), (1, 0.0)))
                cspline2 = CubicSpline(x=self.r[imax:], y=relative_energies[imax:],
                                       bc_type=((1, 0.0), (1, 0.0)))
                self.spline.extend(c=cspline2.c, x=cspline2.x[1:])
            else:
                self.spline = CubicSpline(x=self.r, y=relative_energies,
                                          bc_type=((1, 0.0), (1, 0.0)))
955703
def sim(model: HybridOde, options: Dict = None,  # noqa: too-complex
        user_callback=None) -> Dict[str, np.array]:
    
    if model.f_x_rhs.shape[0] < 1:
        raise ValueError("there are no ODE equations to simulate, "
                         "check that the model is explicit")

    ic = {}
    for f in ['x', 'y', 'm', 'p']:
        ic[f] = []
        for x in ca.vertsplit(getattr(model, f)):
            start = model.prop[x.name()]['start']
            value = model.prop[x.name()]['value']
            if start is not None:
                ic[f].append(ca.reshape(start, x.numel(), 1))
            elif value is not None:
                ic[f].append(ca.reshape(value, x.numel(), 1))
            else:
                ic[f].append(ca.DM.zeros(x.numel(), 1))
                Warning("using default start value for", x.name())

        ic[f] = np.array([ic[f]], dtype=float).T

    # set options
    opt = {
        'x0': ic['x'],
        'p': ic['p'],
        't0': 0,
        'tf': 1,
        'dt': None,
        'integrator': 'dopri5',
        'atol': 1e-6,
        'rtol': 1e-6,
        'max_step': None,
        'record_event_times': True,
        'verbose': False,
    }
    if options is not None:
        for k in options.keys():
            if k in opt.keys():
                opt[k] = options[k]
            else:
                raise ValueError("unknown option {:s}".format(k))
    if opt['dt'] is None:
        opt['dt'] = opt['tf']/100
    if opt['max_step'] is None:
        opt['max_step'] = opt['dt']/2

    # create functions
    f_y = model.create_function_f_y()
    f_c = model.create_function_f_c()
    f_m = model.create_function_f_m()
    f_x_rhs = model.create_function_f_x_rhs()
    f_J = model.create_function_f_J()
    f_i = model.create_function_f_i()

    # initialize sim loop
    t0 = opt['t0']
    tf = opt['tf']
    x = opt['x0']
    ng = np.zeros(model.ng.shape[0])
    nu = np.zeros(model.nu.shape[0])
    m = ic['m']
    p = opt['p']
    y0 = ic['y']
    pre_c = np.array(f_c(t0, x, y0, m, p, ng, nu))
    c = pre_c
    y = f_y(t0, x, m, p, c, ng, nu)
    dt = opt['dt']
    t_vect = np.arange(t0, tf, dt)
    n = len(t_vect)
    data = {
        't': [],
        'x': [],
        'm': [],
        'y': [],
        'c': [],
    }

    # create integrator
    integrator = scipy.integrate.ode(f_x_rhs, f_J)
    integrator.set_integrator(
        opt['integrator'],
        first_step=opt['max_step'],
        atol=opt['atol'],
        rtol=opt['rtol'],
        max_step=opt['max_step'],
    )

    # try to catch events with sol out, (root finding)
    def sol_out(t, x):
        c = np.array(f_c(t, x, y, m, p, ng, nu))
        if np.any(c != pre_c):
            # print('event', t)
            return -1
        return 0
    if opt['integrator'] in ['dopri5', 'dopri853']:
        integrator.set_solout(sol_out)

    # run sim loop
    i = 0
    dt_f_i = 0
    dt_integrate = 0
    integrator.set_initial_value(opt['x0'], t0)

    while i < n:
        t = integrator.t

        # resample noise
        ng = np.random.randn(model.ng.shape[0])
        nu = np.random.randn(model.nu.shape[0])

        # call reinit
        start = time.time()
        x = f_i(t, x, y, m, p, c, pre_c, ng, nu)
        dt_f_i += (time.time() - start)

        # setup next continuous integration step
        integrator.set_initial_value(x, t)
        integrator.set_f_params(y, m, p, c, ng, nu)
        integrator.set_jac_params(y, m, p, c, ng, nu)

        # integrate
        t_goal = t0 + i*dt
        start = time.time()
        integrator.integrate(t_goal)
        dt_integrate += (time.time() - start)
        x = integrator.y

        # compute new conditions
        pre_c = c
        c = np.array(f_c(t, x, y, m, p, ng, nu))

        # compute output
        y = f_y(t, x, m, p, c, ng, nu)

        # compute discrete states
        m = f_m(t, x, y, m, p, c, pre_c, ng, nu)

        # store data
        if opt['record_event_times'] or (integrator.t - t_goal == 0):
            data['t'].append(t)
            data['x'].append(ca.vertsplit(x))
            data['y'].append(ca.vertsplit(y))
            data['m'].append(ca.vertsplit(m))
            data['c'].append(ca.vertsplit(c))
            if user_callback is not None:
                user_callback(t, x, y, m, p, c)

        # increment time goal if reached
        if integrator.t - t_goal == 0:
            # update discrete states
            # TODO: make this use sampling
            i += 1

    for k in data.keys():
        data[k] = np.array(data[k])

    data['labels'] = {}
    for field in ['x', 'y', 'c', 'm']:
        data['labels'][field] = [x.name() for x in ca.vertsplit(getattr(model, field))]

    if opt['verbose']:
        print('dt_f_i\t\t\t:', dt_f_i)
        print('dt_integrate\t:', dt_integrate)
    return data
374002
def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1):
        
        if simple=='auto': simple=self.simple


        # get the min and max
        if xmin=="auto": xmin = self.xmin
        if xmax=="auto": xmax = self.xmax
        if clear: _pylab.gca().clear()

        if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values]

        for y in y_values:
            # define a new simple function to plot, then plot it
            def f(x): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, xmin, xmax, steps, 0, True)

            # label it
            a = _pylab.gca()
            th = "th"
            if x_derivative == 1: th = "st"
            if x_derivative == 2: th = "nd"
            if x_derivative == 3: th = "rd"
            if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline")
            else:            a.set_ylabel(self.zlabel)
            a.set_xlabel(self.xlabel)
            a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel)
            a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y))
        if format: _s.format_figure()
        return a
1251698
def init(options):
    

    # Set matlplotlib's backend so LIVVkit can plot to files.
    import matplotlib
    matplotlib.use('agg')

    livvkit.output_dir = os.path.abspath(options.out_dir)
    livvkit.index_dir = livvkit.output_dir
    livvkit.verify = True if options.verify is not None else False
    livvkit.validate = True if options.validate is not None else False
    livvkit.publish = options.publish

    # Get a list of bundles that provide model specific implementations
    available_bundles = [mod for imp, mod, ispkg in pkgutil.iter_modules(bundles.__path__)]

    if options.verify is not None:
        livvkit.model_dir = os.path.normpath(options.verify[0])
        livvkit.bench_dir = os.path.normpath(options.verify[1])
        if not os.path.isdir(livvkit.model_dir):
            print("")
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            print("                       UH OH!")
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            print("    Your comparison directory does not exist; please check")
            print("    the path:")
            print("\n"+livvkit.model_dir+"\n\n")
            sys.exit(1)

        if not os.path.isdir(livvkit.bench_dir):
            print("")
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            print("                       UH OH!")
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            print("    Your benchmark directory does not exist; please check")
            print("    the path:")
            print("\n"+livvkit.bench_dir+"\n\n")
            sys.exit(1)

        livvkit.model_bundle = os.path.basename(livvkit.model_dir)
        livvkit.bench_bundle = os.path.basename(livvkit.bench_dir)

        if livvkit.model_bundle in available_bundles:
            livvkit.numerics_model_config = os.path.join(
                livvkit.bundle_dir, livvkit.model_bundle, "numerics.json")
            livvkit.numerics_model_module = importlib.import_module(
                ".".join(["livvkit.bundles", livvkit.model_bundle, "numerics"]))

            livvkit.verification_model_config = os.path.join(
                 livvkit.bundle_dir, livvkit.model_bundle, "verification.json")
            livvkit.verification_model_module = importlib.import_module(
                 ".".join(["livvkit.bundles", livvkit.model_bundle, "verification"]))

            livvkit.performance_model_config = os.path.join(
                 livvkit.bundle_dir, livvkit.model_bundle, "performance.json")
            # NOTE: This isn't used right now...
            # livvkit.performance_model_module = importlib.import_module(
            #      ".".join(["livvkit.bundles", livvkit.model_bundle, "performance"]))
        else:
            # TODO: Should implement some error checking here...
            livvkit.verify = False

    if options.validate is not None:
        livvkit.validation_model_configs = options.validate

    if not (livvkit.verify or livvkit.validate) and not options.serve:
        print("")
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        print("                       UH OH!")
        print("----------------------------------------------------------")
        print("    No verification or validation tests found/submitted!")
        print("")
        print("    Use either one or both of the --verify and")
        print("    --validate options to run tests.  For more ")
        print("    information use the --help option, view the README")
        print("    or check https://livvkit.github.io/Docs/")
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        print("")
        sys.exit(1)

    return options
689270
def _make_options(x):
    
    # Check if x is a mapping of labels to values
    if isinstance(x, Mapping):
        import warnings
        warnings.warn("Support for mapping types has been deprecated and will be dropped in a future release.", DeprecationWarning)
        return tuple((unicode_type(k), v) for k, v in x.items())

    # only iterate once through the options.
    xlist = tuple(x)

    # Check if x is an iterable of (label, value) pairs
    if all((isinstance(i, (list, tuple)) and len(i) == 2) for i in xlist):
        return tuple((unicode_type(k), v) for k, v in xlist)

    # Otherwise, assume x is an iterable of values
    return tuple((unicode_type(i), i) for i in xlist)
1014272
def __generate_spline(self, x, y, closed=False, steps=20):
        

        if closed:
            x = x.tolist()
            x.insert(0, x[-1])
            x.append(x[1])
            x.append(x[2])

            y = y.tolist()
            y.insert(0, y[-1])
            y.append(y[1])
            y.append(y[2])

        points = np.vstack((x,y)).T

        curve = []

        if not closed:
            curve.append(points[0])

        for j in range(1, len(points)-2):
            for s in range(steps):
                t = 1. * s / steps
                p0, p1, p2, p3 = points[j-1], points[j], points[j+1], points[j+2]
                pnew = 0.5 *((2 * p1) + (-p0 + p2) * t + (2*p0 - 5*p1 + 4*p2 - p3) * t**2 + (-p0 + 3*p1- 3*p2 + p3) * t**3)
                curve.append(pnew)

        if not closed:
            curve.append(points[-1])

        curve = np.array(curve)
        return curve[:, 0], curve[:, 1]
1318575
def set_params(self, **kwargs):
        
        self._check_deprecated_params(**kwargs)
        normal_params, cb_params, special_params = {}, {}, {}
        virtual_params = {}

        for key, val in kwargs.items():
            if self._is_virtual_param(key):
                virtual_params[key] = val
            elif key.startswith('callbacks'):
                cb_params[key] = val
            elif any(key.startswith(prefix) for prefix in self.prefixes_):
                special_params[key] = val
            else:
                normal_params[key] = val

        self._apply_virtual_params(virtual_params)
        BaseEstimator.set_params(self, **normal_params)

        for key, val in special_params.items():
            if key.endswith('_'):
                raise ValueError(
                    "Something went wrong here. Please open an issue on "
                    "https://github.com/dnouri/skorch/issues detailing what "
                    "caused this error.")
            else:
                setattr(self, key, val)

        # Below: Re-initialize parts of the net if necessary.

        if cb_params:
            # callbacks need special treatmeant since they are list of tuples
            self.initialize_callbacks()
            self._set_params_callback(**cb_params)

        if any(key.startswith('criterion') for key in special_params):
            self.initialize_criterion()

        module_triggers_optimizer_reinit = False
        if any(key.startswith('module') for key in special_params):
            self.initialize_module()
            module_triggers_optimizer_reinit = True

        optimizer_changed = (
            any(key.startswith('optimizer') for key in special_params) or
            'lr' in normal_params
        )
        if module_triggers_optimizer_reinit or optimizer_changed:
            # Model selectors such as GridSearchCV will set the
            # parameters before .initialize() is called, therefore we
            # need to make sure that we have an initialized model here
            # as the optimizer depends on it.
            if not hasattr(self, 'module_'):
                self.initialize_module()

            # If we reached this point but the optimizer was not
            # changed, it means that optimizer initialization was
            # triggered indirectly.
            self.initialize_optimizer(triggered_directly=optimizer_changed)

        vars(self).update(kwargs)

        return self
1306813
def click_estimate_slope():
    

    c1 = _pylab.ginput()
    if len(c1)==0:
        return None

    c2 = _pylab.ginput()
    if len(c2)==0:
        return None

    return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])
23564
def set_params(self, l2_regularization=0.0, optimizer=None, optimizer_kwargs=None):
        
        self.l2_regularization = l2_regularization
        self._optimizer = optimizer
        self._optimizer_kwargs = optimizer_kwargs
        return self
541030
def derivatives_ctrlpts(**kwargs):
        
        r1 = kwargs.get('r1')  # minimum span on the u-direction
        r2 = kwargs.get('r2')  # maximum span on the u-direction
        s1 = kwargs.get('s1')  # minimum span on the v-direction
        s2 = kwargs.get('s2')  # maximum span on the v-direction

        deriv_order = kwargs.get('deriv_order')
        ctrlpts_size = kwargs.get('ctrlpts_size')
        degree = kwargs.get('degree')
        knotvector = kwargs.get('knotvector')
        ctrlpts = kwargs.get('ctrlpts')
        dimension = kwargs.get('dimension')

        PKL = [[[[[None for _ in range(dimension)]
                  for _ in range(ctrlpts_size[1])] for _ in range(ctrlpts_size[0])]
                for _ in range(deriv_order + 1)] for _ in range(deriv_order + 1)]

        du = min(degree[0], deriv_order)
        dv = min(degree[1], deriv_order)

        r = r2 - r1
        s = s2 - s1

        # Control points of the U derivatives of every U-curve
        for j in range(s1, s2 + 1):
            PKu = CurveEvaluator2.derivatives_ctrlpts(r1=r1, r2=r2,
                                                      degree=degree[0],
                                                      knotvector=knotvector[0],
                                                      ctrlpts=[ctrlpts[j + (ctrlpts_size[1] * i)] for i in range(ctrlpts_size[0])],
                                                      dimension=dimension,
                                                      deriv_order=du)

            # Copy into output as the U partial derivatives
            for k in range(0, du + 1):
                for i in range(0, r - k + 1):
                    PKL[k][0][i][j - s1] = PKu[k][i]

        # Control points of the V derivatives of every U-differentiated V-curve
        for k in range(0, du):
            for i in range(0, r - k + 1):
                dd = min(deriv_order - k, dv)

                PKuv = CurveEvaluator2.derivatives_ctrlpts(r1=0, r2=s,
                                                           degree=degree[1],
                                                           knotvector=knotvector[1][s1:],
                                                           ctrlpts=PKL[k][0][i],
                                                           dimension=dimension,
                                                           deriv_order=dd)

                # Copy into output
                for l in range(1, dd + 1):
                    for j in range(0, s - l + 1):
                        PKL[k][l][i][j] = PKuv[l][j]

        return PKL
1373413
function (options) {

    var
      context     = options.context,
      lineWidth   = options.lineWidth,
      shadowSize  = options.shadowSize,
      offset;

    context.save();
    context.lineJoin = 'round';

    if (shadowSize) {

      context.lineWidth = shadowSize / 2;
      offset = lineWidth / 2 + context.lineWidth / 2;
      
      // @TODO do this instead with a linear gradient
      context.strokeStyle = "rgba(0,0,0,0.1)";
      this.plot(options, offset + shadowSize / 2, false);

      context.strokeStyle = "rgba(0,0,0,0.2)";
      this.plot(options, offset, false);
    }

    context.lineWidth = lineWidth;
    context.strokeStyle = options.color;

    this.plot(options, 0, true);

    context.restore();
  }
913332
def flatten(self):
        
        if self._flat is None:
            flat = {}
            for arg in self.args:
                if isinstance(arg, Option):
                    flat[arg.name] = arg

                elif isinstance(arg, ListOption):
                    flat[arg.name] = arg

                elif isinstance(arg, DictOption):
                    flat[arg.name] = arg
                    if arg.scheme:
                        for k, v in arg.scheme.flatten().items():
                            flat[arg.name + '.' + k] = v

            self._flat = flat
        return self._flat
1298871
function resolveOptions(opt) {

        opt.directions = util.result(opt, 'directions');
        opt.penalties = util.result(opt, 'penalties');
        opt.paddingBox = util.result(opt, 'paddingBox');
        opt.padding = util.result(opt, 'padding');

        if (opt.padding) {
            // if both provided, opt.padding wins over opt.paddingBox
            var sides = util.normalizeSides(opt.padding);
            opt.paddingBox = {
                x: -sides.left,
                y: -sides.top,
                width: sides.left + sides.right,
                height: sides.top + sides.bottom
            };
        }

        util.toArray(opt.directions).forEach(function(direction) {

            var point1 = new g.Point(0, 0);
            var point2 = new g.Point(direction.offsetX, direction.offsetY);

            direction.angle = g.normalizeAngle(point1.theta(point2));
        });
    }
894210
def _get_interpolator(method, vectorizeable_only=False, **kwargs):
    '''
    '''
    interp1d_methods = ['linear', 'nearest', 'zero', 'slinear', 'quadratic',
                        'cubic', 'polynomial']
    valid_methods = interp1d_methods + ['barycentric', 'krog', 'pchip',
                                        'spline', 'akima']

    has_scipy = True
    try:
        from scipy import interpolate
    except ImportError:
        has_scipy = False

    # prioritize scipy.interpolate
    if (method == 'linear' and not
            kwargs.get('fill_value', None) == 'extrapolate' and
            not vectorizeable_only):
        kwargs.update(method=method)
        interp_class = NumpyInterpolator

    elif method in valid_methods:
        if not has_scipy:
            raise ImportError(
                'Interpolation with method `%s` requires scipy' % method)

        if method in interp1d_methods:
            kwargs.update(method=method)
            interp_class = ScipyInterpolator
        elif vectorizeable_only:
            raise ValueError('{} is not a vectorizeable interpolator. '
                             'Available methods are {}'.format(
                                 method, interp1d_methods))
        elif method == 'barycentric':
            interp_class = interpolate.BarycentricInterpolator
        elif method == 'krog':
            interp_class = interpolate.KroghInterpolator
        elif method == 'pchip':
            interp_class = interpolate.PchipInterpolator
        elif method == 'spline':
            kwargs.update(method=method)
            interp_class = SplineInterpolator
        elif method == 'akima':
            interp_class = interpolate.Akima1DInterpolator
        else:
            raise ValueError('%s is not a valid scipy interpolator' % method)
    else:
        raise ValueError('%s is not a valid interpolator' % method)

    return interp_class, kwargs
727287
function _setOptions(obj, options) {
    options = options || {};
    obj.separator = (typeof options.separator !== 'undefined') ? options.separator : ',';
    obj.quotechar = (typeof options.quote !== 'undefined') ? options.quote : '"';
    obj.escapechar = (typeof options.escape !== 'undefined') ? options.escape : '"';
    obj.commentchar = (typeof options.comment !== 'undefined') ? options.comment : '';
    obj.columnNames = (typeof options.columnNames !== 'undefined') ? options.columnNames : [];
    obj.columnsFromHeader = (typeof options.columnsFromHeader !== 'undefined') ? options.columnsFromHeader : false;
    obj.nestedQuotes = (typeof options.nestedQuotes !== 'undefined') ? options.nestedQuotes : false;
    obj.escapeFormulas = (typeof options.escapeFormulas !== 'undefined') ? options.escapeFormulas : false;
}
363547
function interpolateScalars(values, num) {
  var out = new Float32Array(num*(values.length-1) + 1);
  var index = 0;
  var bf = 0.0, af = 0.0;
  var delta = 1/num;
  for (var i = 0; i < values.length-1; ++i) {
    bf = values[i];
    af = values[i + 1];
    for (var j = 0; j < num; ++j) {
      var t = delta * j;
      out[index+0] = bf*(1-t)+af*t;
      index+=1;
    }
  }
  out[index+0] = af;
  return out;
}
563789
def setup_option_actions(self, mute_inline_plotting, show_plot_outline):
        """"""
        self.setup_in_progress = True
        self.mute_inline_action = create_action(
            self, _("Mute inline plotting"),
            tip=_("Mute inline plotting in the ipython console."),
            toggled=lambda state:
            self.option_changed('mute_inline_plotting', state)
            )
        self.mute_inline_action.setChecked(mute_inline_plotting)

        self.show_plot_outline_action = create_action(
            self, _("Show plot outline"),
            tip=_("Show the plot outline."),
            toggled=self.show_fig_outline_in_viewer
            )
        self.show_plot_outline_action.setChecked(show_plot_outline)

        self.actions = [self.mute_inline_action, self.show_plot_outline_action]
        self.setup_in_progress = False