Evaluate in silico growth rates.
12300
def evaluate(self, model, threshold=0.1):
        """"""
        with model:
            if self.medium is not None:
                self.medium.apply(model)
            if self.objective is not None:
                model.objective = self.objective
            model.add_cons_vars(self.constraints)
            threshold *= model.slim_optimize()
            growth = list()
            for row in self.data.itertuples(index=False):
                with model:
                    exchange = model.reactions.get_by_id(row.exchange)
                    if bool(exchange.reactants):
                        exchange.lower_bound = -row.uptake
                    else:
                        exchange.upper_bound = row.uptake
                    growth.append(model.slim_optimize() >= threshold)
        return DataFrame({
            "exchange": self.data["exchange"],
            "growth": growth
        })
63459
public void process() {

		int width = widthSubregion*widthGrid;
		int radius = width/2;

		int X0 = radius,X1 = savedAngle.width-radius;
		int Y0 = radius,Y1 = savedAngle.height-radius;

		int numX = (int)((X1-X0)/periodColumns);
		int numY = (int)((Y1-Y0)/periodRows);

		descriptors.reset();
		sampleLocations.reset();

		for (int i = 0; i < numY; i++) {
			int y = (Y1-Y0)*i/(numY-1) + Y0;

			for (int j = 0; j < numX; j++) {
				int x = (X1-X0)*j/(numX-1) + X0;

				TupleDesc_F64 desc = descriptors.grow();

				computeDescriptor(x,y,desc);
				sampleLocations.grow().set(x,y);
			}
		}
	}
959382
def benchmark(src_dir, compiler, include_dirs, iter_count):
    """"""

    files = list(files_in_dir(src_dir, 'cpp'))
    random.shuffle(files)
    has_string_templates = True
    string_template_file_cnt = sum(1 for file in files if 'bmp' in file)
    file_count = len(files) + string_template_file_cnt

    started_at = time.time()
    result = {}
    for filename in files:
        progress = len(result)
        result[filename] = benchmark_file(
            os.path.join(src_dir, filename),
            compiler,
            include_dirs,
            (float(progress) / file_count, float(progress + 1) / file_count),
            iter_count
        )
        if 'bmp' in filename and has_string_templates:
            try:
                temp_result = benchmark_file(
                    os.path.join(src_dir, filename),
                    compiler,
                    include_dirs,
                    (float(progress + 1) / file_count, float(progress + 2) / file_count),
                    iter_count,
                    '-Xclang -fstring-literal-templates'
                )
                result[filename.replace('bmp', 'slt')] = temp_result
            except:
                has_string_templates = False
                file_count -= string_template_file_cnt
                print 'Stopping the benchmarking of string literal templates'

        elapsed = time.time() - started_at
        total = float(file_count * elapsed) / len(result)
        print 'Elapsed time: {0}, Remaining time: {1}'.format(
            format_time(elapsed),
            format_time(total - elapsed)
        )
    return result
1124783
private void growReactionArray() {
        growArraySize = reactions.length;
        IReaction[] newreactions = new IReaction[reactions.length + growArraySize];
        System.arraycopy(reactions, 0, newreactions, 0, reactions.length);
        reactions = newreactions;
    }
285377
private void grow(int minCapacity) {
		int oldCapacity = segment.size();
		int newCapacity = oldCapacity + (oldCapacity >> 1);
		if (newCapacity - minCapacity < 0) {
			newCapacity = minCapacity;
		}
		segment = MemorySegmentFactory.wrap(Arrays.copyOf(segment.getArray(), newCapacity));
		afterGrow();
	}
852039
def calculate_columns(self):
        """"""

        self.cols = int(math.ceil(len(self.elements) / float(self.rows)))
146314
def main():
    """"""
    arguments = docopt.docopt(__doc__, version=__version__)
    colorlogs()
    # Read input file file


    wrapper = BMIWrapper(
        engine=arguments['<engine>'],
        configfile=arguments['<config>'] or ''
    )


    # add logger if required
    if not arguments['--disable-logger']:
        logging.root.setLevel(logging.DEBUG)
        wrapper.set_logger(logging.root)

    with wrapper as model:
        # if siginfo is supported by OS (BSD)
        def handler(signum, frame):
            """report progress information"""
            t_start = model.get_start_time()
            t_end = model.get_end_time()
            t_current = model.get_current_time()
            total = (t_end - t_start)
            now = (t_current - t_start)
            if total > 0:
                logging.info("progress: %s%%", 100.0 * now / total)
            else:
                logging.info("progress: unknown")

        if hasattr(signal, 'SIGINFO'):
            # attach a siginfo handler (CTRL-t) to print progress
            signal.signal(signal.SIGINFO, handler)

        if arguments['--info']:
            logging.info("%s", trace(model))
        t_end = model.get_end_time()
        t = model.get_start_time()
        while t < t_end:
            model.update(-1)
            t = model.get_current_time()
        if arguments['--info']:
            logging.info("%s", trace(model))
20387
def _fromiter(it, dtype, count, progress, log):
    """"""
    if progress > 0:
        it = _iter_withprogress(it, progress, log)
    if count is not None:
        a = np.fromiter(it, dtype=dtype, count=count)
    else:
        a = np.fromiter(it, dtype=dtype)
    return a
517285
def _int_growth(z, **cosmo):
    

    zmax = 200

    if hasattr(z, "__len__"):
        for zval in z:
            assert(zval < zmax)
    else:
        assert(z < zmax)

    y, yerr = scipy.integrate.quad(
        lambda z: (1 + z)/(cosmo['omega_M_0']*(1 + z)**3 +
                           cosmo['omega_lambda_0'])**(1.5),
        z, zmax)

    return(y)
416690
def evaluate(dataloader):
    """"""
    total_L = 0.0
    total_sample_num = 0
    total_correct_num = 0
    start_log_interval_time = time.time()
    print('Begin Testing...')
    for i, ((data, valid_length), label) in enumerate(dataloader):
        data = mx.nd.transpose(data.as_in_context(context))
        valid_length = valid_length.as_in_context(context).astype(np.float32)
        label = label.as_in_context(context)
        output = net(data, valid_length)
        L = loss(output, label)
        pred = (output > 0.5).reshape((-1,))
        total_L += L.sum().asscalar()
        total_sample_num += label.shape[0]
        total_correct_num += (pred == label).sum().asscalar()
        if (i + 1) % args.log_interval == 0:
            print('[Batch {}/{}] elapsed {:.2f} s'.format(
                i + 1, len(dataloader), time.time() - start_log_interval_time))
            start_log_interval_time = time.time()
    avg_L = total_L / float(total_sample_num)
    acc = total_correct_num / float(total_sample_num)
    return avg_L, acc
773805
def run_evolution(path,name,E0,laser_frequencies,  N_iter,dt,N_states,
				spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
				rho0=None,print_steps=False,
				integrate=False,
				save_systems=False,save_eigenvalues=False,rk4=False,use_netcdf=True):
	""""""
	def py2f_bool(bool_var):
		if bool_var:
			return ".true.\n"
		else:
			return ".false.\n"

	if rk4:
		return run_rk4(path,name,E0,laser_frequencies,  N_iter,dt,N_states,
				spectrum_of_laser=spectrum_of_laser,N_delta=N_delta,
				frequency_step=frequency_step, frequency_end=frequency_end,
				rho0=rho0,print_steps=print_steps,
				integrate=integrate,save_systems=save_systems)

	t0=time()
	params =str(N_iter)+'\n'
	params+=str(dt)+'\n'
	#We give the flag on wether to print each time step.
	params+=py2f_bool(print_steps)

	#We give the initial value of rho
	N_vars=N_states*(N_states+1)/2-1
	if rho0==None:
		params+=''.join(['(0.0,0.0) ' for i in range(N_states**2-1)])
	elif len(rho0)==N_states-1:
		if sage_included:
			params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
		else:
			params+=''.join(['('+str(i.real)+','+str(i.imag)+') ' for i in rho0])
		params+=''.join(['(0.0,0.0) ' for i in range( N_states**2 -N_states)])
	elif len(rho0)==N_vars:
		params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
	else:
		raise ValueError,'rho0 had an invalid number of elements.'

	params+='\n'
	#We give the amplitude of the electrical fields.
	params+=''.join([str(i)+' ' for i in E0])+'\n'

	#We give the detuning of each laser (taken from the lowest frequency transition).
	params+=''.join([str(i)+' ' for i in laser_frequencies])+'\n'

	#We give the flag on wether to calculate spectrums or time evolution.
	if spectrum_of_laser==None:
		params+='.false.\n'
		params+=py2f_bool(save_systems)
		params+=py2f_bool(save_eigenvalues)
		params+=py2f_bool(use_netcdf)
		params+=py2f_bool(integrate)

	else:
		if frequency_end !=None:
			if frequency_step !=None:
				raise ValueError,'both frequency_end and frequency_step were specified.'
			if N_delta==1:
				frequency_step=0.0
			else:
				frequency_step=(frequency_end-laser_frequencies[spectrum_of_laser-1])/(N_delta-1)

		#frequency_step=frequency_end
		params+='.true.\n'
		params+=py2f_bool(save_systems)
		params+=py2f_bool(save_eigenvalues)
		params+=py2f_bool(use_netcdf)
		params+=py2f_bool(integrate)

		params+=str(spectrum_of_laser)+'\n'
		params+=str(N_delta)+'\n'
		params+=str(frequency_step)
	#print params

	f=file(path+name+'_params.dat','w')
	f.write(params)
	f.close()

	os.system(path+name)
	return time()-t0
323663
def demo():
    """"""
    from time import sleep
    maxProgress = 1000
    with ProgressBar(max=maxProgress) as progressbar:
        for i in range(-100, maxProgress):
            sleep(0.01)
            progressbar.update(i)
    progressbar2 = ProgressBar(max=maxProgress)
    for s in progressbar2.iterate(range(maxProgress)):
        sleep(0.01)
    for s in progressbar2.iterate(range(maxProgress), format='iteration %d'):
        sleep(0.01)
308325
def evaluate(self, data):
        """"""
        try:
            inputs = copy.deepcopy(data.input)
            hydrate_input_references(inputs, data.process.input_schema)
            hydrate_input_uploads(inputs, data.process.input_schema)

            # Include special 'proc' variable in the context.
            inputs['proc'] = {
                'data_id': data.id,
                'data_dir': self.manager.get_executor().resolve_data_path(),
            }

            # Include special 'requirements' variable in the context.
            inputs['requirements'] = data.process.requirements
            # Inject default values and change resources according to
            # the current Django configuration.
            inputs['requirements']['resources'] = data.process.get_resource_limits()

            script_template = data.process.run.get('program', '')

            # Get the appropriate expression engine. If none is defined, do not evaluate
            # any expressions.
            expression_engine = data.process.requirements.get('expression-engine', None)
            if not expression_engine:
                return script_template

            return self.get_expression_engine(expression_engine).evaluate_block(
                script_template, inputs,
                escape=self._escape,
                safe_wrapper=SafeString,
            )
        except EvaluationError as error:
            raise ExecutionError('{}'.format(error))
1158704
def evaluate(self, data):
        """"""
        return 'PYTHONPATH="{runtime}" python3 -u -m resolwe.process {program} --slug {slug} --inputs {inputs}'.format(
            runtime=PYTHON_RUNTIME_VOLUME,
            program=PYTHON_PROGRAM_VOLUME,
            slug=shlex.quote(data.process.slug),
            inputs=PYTHON_INPUTS_VOLUME,
        )
1294924
def demo():
    """"""
    A = poisson((100, 100), format='csr')  # 2D FD Poisson problem
    B = None                               # no near-null spaces guesses for SA
    b = sp.rand(A.shape[0], 1)          # a random right-hand side

    # use AMG based on Smoothed Aggregation (SA) and display info
    mls = smoothed_aggregation_solver(A, B=B)
    print(mls)

    # Solve Ax=b with no acceleration ('standalone' solver)
    standalone_residuals = []
    x = mls.solve(b, tol=1e-10, accel=None, residuals=standalone_residuals)

    # Solve Ax=b with Conjugate Gradient (AMG as a preconditioner to CG)
    accelerated_residuals = []
    x = mls.solve(b, tol=1e-10, accel='cg', residuals=accelerated_residuals)
    del x

    # Compute relative residuals
    standalone_residuals = \
        np.array(standalone_residuals) / standalone_residuals[0]
    accelerated_residuals = \
        np.array(accelerated_residuals) / accelerated_residuals[0]

    # Compute (geometric) convergence factors
    factor1 = standalone_residuals[-1]**(1.0/len(standalone_residuals))
    factor2 = accelerated_residuals[-1]**(1.0/len(accelerated_residuals))

    print("                     MG convergence factor: %g" % (factor1))
    print("MG with CG acceleration convergence factor: %g" % (factor2))

    # Plot convergence history
    try:
        import matplotlib.pyplot as plt
        plt.figure()
        plt.title('Convergence History')
        plt.xlabel('Iteration')
        plt.ylabel('Relative Residual')
        plt.semilogy(standalone_residuals, label='Standalone',
                     linestyle='-', marker='o')
        plt.semilogy(accelerated_residuals, label='Accelerated',
                     linestyle='-', marker='s')
        plt.legend()
        plt.show()
    except ImportError:
        print("\n\nNote: pylab not available on your system.")
833702
def _bnd(self, xloc, dist, cache):
        """"""
        return numpy.log(evaluation.evaluate_bound(
            dist, numpy.e**xloc, cache=cache))
1271506
private void grow() {
        /* Double the size of the topmost array. */
        T[][] newArrays = (T[][]) new Object[mArrays.length * 2][];

        /* The new arrays each have size 2^(n + 1).  We need 2^(n - 1) of them
         * to hold the old elements.  Allocate those here and copy everything
         * over.
         */
        for (int i = 0; i < mArrays.length; i += 2) {
            /* Allocate the array. */
            newArrays[i / 2] = (T[]) new Object[newArrays.length];

            /* Use System.arraycopy to move everything over. */
            System.arraycopy(mArrays[i], 0, newArrays[i / 2], 0, mArrays.length);
            System.arraycopy(mArrays[i + 1], 0, newArrays[i / 2], mArrays.length, mArrays.length);

            /* Null out the old arrays to be nice to the GC during this
             * potentially stressful time.
             */
            mArrays[i] = mArrays[i + 1] = null;
        }

        /* Switch out this new array for the old. */
        mArrays = newArrays;

        /* Bump up lg2 of the size. */
        ++mLgSize;
    }