Generates a solution trajectory of variable length.
326036
def _integrate_variable_trajectory(self, h, g, tol, step, relax):
        """"""
        # initialize the solution using initial condition
        solution = np.hstack((self.t, self.y))

        while self.successful():

            self.integrate(self.t + h, step, relax)
            current_step = np.hstack((self.t, self.y))
            solution = np.vstack((solution, current_step))

            if g(self.t, self.y, *self.f_params) < tol:
                break
            else:
                continue

        return solution
651624
private void doGenerateBrownianMotion() {
		if(brownianIncrements != null)
		{
			return;	// Nothing to do
		}

		BrownianMotion generator = new BrownianMotion(timeDiscretization, numberOfFactors, numberOfPaths, seed);

		// Allocate memory
		brownianIncrements = new RandomVariableInterface[generator.getTimeDiscretization().getNumberOfTimeSteps()][generator.getNumberOfFactors()];

		double endTime 		= getTimeDiscretization().getTime(getTimeDiscretization().getNumberOfTimeSteps());
		for(int factor=0; factor<generator.getNumberOfFactors(); factor++) {
			// The end point
			RandomVariableInterface endOfFactor		= end[factor];
			// Initialized the bridge to the start point
			RandomVariableInterface brownianBridge	= start[factor];
			for(int timeIndex=0; timeIndex<getTimeDiscretization().getNumberOfTimeSteps(); timeIndex++) {
				double currentTime	= getTimeDiscretization().getTime(timeIndex);
				double nextTime		= getTimeDiscretization().getTime(timeIndex+1);
				double alpha		= (nextTime-currentTime)/(endTime-currentTime);

				// Calculate the next point using the "scheme" of the Brownian bridge
				RandomVariableInterface nextRealization = brownianBridge.mult(1.0-alpha).add(endOfFactor.mult(alpha)).add(generator.getBrownianIncrement(timeIndex, factor).mult(Math.sqrt(1-alpha)));

				// Store the increment
				brownianIncrements[timeIndex][factor] = nextRealization.sub(brownianBridge);

				// Update the bridge to the current point
				brownianBridge = nextRealization;
			}
		}
	}
1164921
def load_trajectory(name, skip=1, format=None):
    '''

    '''
    df = datafile(name, format=format)
    dt, coords = df.read('trajectory', skip=skip)
    boxes = df.read('boxes')
    viewer.current_traj = coords
    viewer.frame_times = dt
    
    viewer.traj_controls.set_ticks(len(dt))
    
    def update(index):
        
        f = coords[index]        
        
        for fp in _frame_processors:
            f = fp(coords, index)

        # update the current representation
        viewer.representation.update_positions(f)
        viewer.representation.update_box(boxes[index])
        current_system().r_array = f
        current_system().box_vectors = boxes[index]
        viewer.traj_controls.set_time(dt[index])
        viewer.update()
    
    viewer.traj_controls.show()
    viewer.traj_controls.frame_changed.connect(update)
856584
def main(dimension, iterations):
    
    objective_function = minimize(functions.sphere)
    stopping_condition = max_iterations(iterations)
    (solution, metrics) = optimize(objective_function=objective_function,
                                   domain=Domain(-5.12, 5.12, dimension),
                                   stopping_condition=stopping_condition,
                                   parameters={'seed': 3758117674,
                                               'rho': 1.0, 'e_s': 15, 'e_f': 5},
                                   velocity_update=gc_velocity_update,
                                   parameter_update=update_rho,
                                   measurements=[fitness_measurement])
    return solution
469969
def solve(self, S, dimK=None):
        """"""

        # Use dimK specified in __init__ as default
        if dimK is None and self.dimK is not None:
            dimK = self.dimK

        # Start solve timer
        self.timer.start(['solve', 'solve_wo_eval'])

        # Solve CSC problem on S and do dictionary step
        self.init_vars(S, dimK)
        self.xstep(S, self.lmbda, dimK)
        self.dstep()

        # Stop solve timer
        self.timer.stop('solve_wo_eval')

        # Extract and record iteration stats
        self.manage_itstat()

        # Increment iteration count
        self.j += 1

        # Stop solve timer
        self.timer.stop('solve')

        # Return current dictionary
        return self.getdict()
1211758
private void doGenerateBrownianMotion() {
		if(brownianIncrements != null) {
			return;	// Nothing to do
		}

		// Create random number sequence generator
		MersenneTwister mersenneTwister = new MersenneTwister(seed);

		// Allocate memory
		double[][][] brownianIncrementsArray = new double[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors][numberOfPaths];

		// Pre-calculate square roots of deltaT
		double[] sqrtOfTimeStep = new double[timeDiscretization.getNumberOfTimeSteps()];
		for(int timeIndex=0; timeIndex<sqrtOfTimeStep.length; timeIndex++) {
			sqrtOfTimeStep[timeIndex] = Math.sqrt(timeDiscretization.getTimeStep(timeIndex));
		}

		/*
		 * Generate normal distributed independent increments.
		 *
		 * The inner loop goes over time and factors.
		 * MersenneTwister is known to generate "independent" increments in 623 dimensions.
		 * Since we want to generate independent streams (paths), the loop over path is the outer loop.
		 */
		for(int path=0; path<numberOfPaths; path++) {
			for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
				double sqrtDeltaT = sqrtOfTimeStep[timeIndex];
				// Generate uncorrelated Brownian increment
				for(int factor=0; factor<numberOfFactors; factor++) {
					double uniformIncrement = mersenneTwister.nextDouble();
					brownianIncrementsArray[timeIndex][factor][path] = net.finmath.functions.NormalDistribution.inverseCumulativeDistribution(uniformIncrement) * sqrtDeltaT;
				}
			}
		}

		// Allocate memory for RandomVariable wrapper objects.
		brownianIncrements = new RandomVariableInterface[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors];

		// Wrap the values in RandomVariable objects
		for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
			double time = timeDiscretization.getTime(timeIndex+1);
			for(int factor=0; factor<numberOfFactors; factor++) {
				brownianIncrements[timeIndex][factor] =
						randomVariableFactory.createRandomVariable(time, brownianIncrementsArray[timeIndex][factor]);
			}
		}
	}
1338843
def downsample_trajectories(trajectories, downsampler, *args, **kwargs):
  '''
  '''
  X = np.vstack(trajectories)
  traj_lengths = list(map(len, trajectories))
  inds = np.sort(downsampler(X, *args, **kwargs))
  new_traj = []
  for stop in np.cumsum(traj_lengths):
    n = np.searchsorted(inds, stop)
    new_traj.append(X[inds[:n]])
    inds = inds[n:]
  return new_traj
200212
def solve(self):
        '''
        
        '''
        aNrm       = self.prepareToCalcEndOfPrdvP()
        EndOfPrdvP = self.calcEndOfPrdvP()
        solution   = self.makeBasicSolution(EndOfPrdvP,aNrm,self.makeLinearcFunc)
        solution   = self.addMPCandHumanWealth(solution)
        return solution
437565
def generate(num, prompt_default=True):
    """"""
    p = Problem(num)

    problem_text = p.text

    msg = "Generate file for problem %i?" % num
    click.confirm(msg, default=prompt_default, abort=True)

    # Allow skipped problem files to be recreated
    if p.glob:
        filename = str(p.file)
        msg = '"{}" already exists. Overwrite?'.format(filename)
        click.confirm(click.style(msg, fg='red'), abort=True)
    else:
        # Try to keep prefix consistent with existing files
        previous_file = Problem(num - 1).file
        prefix = previous_file.prefix if previous_file else ''
        filename = p.filename(prefix=prefix)

    header = 'Project Euler Problem %i' % num
    divider = '=' * len(header)
    text = '\n'.join([header, divider, '', problem_text])
    content = '\n'.join(['"""', text, '"""'])

    with open(filename, 'w') as f:
        f.write(content + '\n\n\n')

    click.secho('Successfully created "{}".'.format(filename), fg='green')

    # Copy over problem resources if required
    if p.resources:
        p.copy_resources()
950865
def _get_linear_trajectory(x0, velocity, t):
  
  x0 = tf.convert_to_tensor(x0)
  velocity = tf.convert_to_tensor(velocity)
  t = tf.convert_to_tensor(t)
  if x0.shape.ndims != 1:
    raise ValueError("x0 must be a rank 1 tensor")
  if velocity.shape.ndims != 1:
    raise ValueError("velocity must be a rank 1 tensor")
  if t.shape.ndims != 1:
    raise ValueError("t must be a rank 1 tensor")
  x0 = tf.expand_dims(x0, axis=0)
  velocity = tf.expand_dims(velocity, axis=0)
  dx = velocity * tf.expand_dims(t, axis=-1)
  linear_trajectories = x0 + dx
  assert linear_trajectories.shape.ndims == 2, \
    "linear_trajectories should be a rank 2 tensor"
  return linear_trajectories
775158
def generator(self, t):
        """"""
        self.check_fit()

        return (1.0 / self.theta) * (np.power(t, -self.theta) - 1)
918854
def get_4pt_bezier(steps, points):
    """"""
    for i in range(steps):
        t = i / float(steps)

        xloc = (math.pow(1 - t, 3) * points[0][0] +
                3 * t * math.pow(1 - t, 2) * points[1][0] +
                3 * (1 - t) * math.pow(t, 2) * points[2][0] +
                math.pow(t, 3) * points[3][0])
        yloc = (math.pow(1 - t, 3) * points[0][1] +
                3 * t * math.pow(1 - t, 2) * points[1][1] +
                3 * (1 - t) * math.pow(t, 2) * points[2][1] +
                math.pow(t, 3) * points[3][1])

        yield (xloc, yloc)
724724
def bootstrap_trajectories(trajs, correlation_length):
    
    from scipy.stats import rv_discrete
    # if we have just one trajectory, put it into a one-element list:
    if (isinstance(trajs[0], (int, int, float))):
        trajs = [trajs]
    ntraj = len(trajs)

    # determine correlation length to be used
    lengths = determine_lengths(trajs)
    Ltot = np.sum(lengths)
    Lmax = np.max(lengths)
    if (correlation_length < 1):
        correlation_length = Lmax

        # assign probabilites to select trajectories
    w_trajs = np.zeros((len(trajs)))
    for i in range(ntraj):
        w_trajs[i] = len(trajs[i])
    w_trajs /= np.sum(w_trajs)  # normalize to sum 1.0
    distrib_trajs = rv_discrete(values=(list(range(ntraj)), w_trajs))

    # generate subtrajectories
    Laccum = 0
    subs = []
    while (Laccum < Ltot):
        # pick a random trajectory
        itraj = distrib_trajs.rvs()
        # pick a starting frame
        t0 = random.randint(0, max(1, len(trajs[itraj]) - correlation_length))
        t1 = min(len(trajs[itraj]), t0 + correlation_length)
        # add new subtrajectory
        subs.append(trajs[itraj][t0:t1])
        # increment available states
        Laccum += (t1 - t0)

    # and return
    return subs
249376
def load_trajectory(name, format=None, skip=1):
    '''

    '''
    df = datafile(name, format=format)

    ret = {}
    t, coords = df.read('trajectory', skip=skip)
    boxes = df.read('boxes')
    ret['t'] = t
    ret['coords'] = coords
    ret['boxes'] = boxes

    return ret
950719
def number_of_trajectories(self, stride=None):
        
        """
        if not IteratorState.is_uniform_stride(stride):
            n = len(np.unique(stride[:, 0]))
        else:
            n = self.ntraj
        return n
1046551
def to_ode(self) -> HybridOde:
        """"""
        res_split = split_dae_alg(self.f_x, self.dx)
        alg = res_split['alg']
        dae = res_split['dae']

        x_rhs = tangent_approx(dae, self.dx, assert_linear=True)
        y_rhs = tangent_approx(alg, self.y, assert_linear=True)

        return HybridOde(
            c=self.c,
            dx=self.dx,
            f_c=self.f_c,
            f_i=self.f_i,
            f_m=self.f_m,
            f_x_rhs=x_rhs,
            y_rhs=y_rhs,
            m=self.m,
            ng=self.ng,
            nu=self.nu,
            p=self.p,
            pre_m=self.pre_m,
            pre_c=self.pre_c,
            prop=self.prop,
            sym=self.sym,
            t=self.t,
            x=self.x,
            y=self.y,
        )
1130220
def generate_displacements(self,
                               distance=0.01,
                               is_plusminus='auto',
                               is_diagonal=True,
                               is_trigonal=False):
        """"""
        displacement_directions = get_least_displacements(
            self._symmetry,
            is_plusminus=is_plusminus,
            is_diagonal=is_diagonal,
            is_trigonal=is_trigonal,
            log_level=self._log_level)
        displacement_dataset = directions_to_displacement_dataset(
            displacement_directions,
            distance,
            self._supercell)
        self.set_displacement_dataset(displacement_dataset)