Sets up the hypercube given a solver configuration
433169
def _setup_hypercube(cube, slvr_cfg):
    
    mbu.register_default_dimensions(cube, slvr_cfg)

    # Configure the dimensions of the beam cube
    cube.register_dimension('beam_lw', 2,
                            description='E Beam cube l width')

    cube.register_dimension('beam_mh', 2,
                            description='E Beam cube m height')

    cube.register_dimension('beam_nud', 2,
                            description='E Beam cube nu depth')

    # =========================================
    # Register hypercube Arrays and Properties
    # =========================================

    from montblanc.impl.rime.tensorflow.config import (A, P)

    def _massage_dtypes(A, T):
        def _massage_dtype_in_dict(D):
            new_dict = D.copy()
            new_dict['dtype'] = mbu.dtype_from_str(D['dtype'], T)
            return new_dict

        return [_massage_dtype_in_dict(D) for D in A]

    dtype = slvr_cfg['dtype']
    is_f32 = dtype == 'float'

    T = {
        'ft' : np.float32 if is_f32 else np.float64,
        'ct' : np.complex64 if is_f32 else np.complex128,
        'int' : int,
    }

    cube.register_properties(_massage_dtypes(P, T))
    cube.register_arrays(_massage_dtypes(A, T))
539311
def set_for_computations(self, value):
        
        if self.mesh._compute_at_vertices:
            self._vertices = value
        else:
            self._centers = value
1050549
void putIntoCanonical( SquareGrid grid ) {

		boolean rowOdd = grid.rows%2 == 1;
		boolean colOdd = grid.columns%2 == 1;

		if( colOdd == rowOdd ) {
			// if odd and square then 4 solutions.  Otherwise just two solution that are on
			// opposite sides on the grid
			if( rowOdd && grid.rows == grid.columns ) {
				int best = -1;
				double bestDistance = Double.MAX_VALUE;
				for (int i = 0; i < 4; i++) {
					SquareNode n = grid.getCornerByIndex(i);
					double d = n.center.normSq();
					if( d < bestDistance ) {
						best = i;
						bestDistance = d;
					}
				}

				for (int i = 0; i < best; i++) {
					tools.rotateCCW(grid);
				}
			} else {
				double first = grid.get(0,0).center.normSq();
				double last = grid.getCornerByIndex(2).center.normSq();

				if( last < first ) {
					tools.reverse(grid);
				}
			}
		}
		// if only one is odd then there is a unique solution.  Since uber is already in a legit
		// configuration nothing needs ot be done
	}
934154
public void updateGrid(List<S> solutionList) {
    //Update lower and upper limits
    updateLimits(solutionList);

    //Calculate the division size
    for (int obj = 0; obj < numberOfObjectives; obj++) {
      divisionSize[obj] = gridUpperLimits[obj] - gridLowerLimits[obj];
    }

    //Clean the hypercubes
    for (int i = 0; i < hypercubes.length; i++) {
      hypercubes[i] = 0;
    }

    //Add the population
    addSolutionSet(solutionList);
  }
1196645
def solvers(config_file, profile, solver_def, list_solvers):
    

    with Client.from_config(
            config_file=config_file, profile=profile, solver=solver_def) as client:

        try:
            solvers = client.get_solvers(**client.default_solver)
        except SolverNotFoundError:
            click.echo("Solver(s) {} not found.".format(solver_def))
            return 1

        if list_solvers:
            for solver in solvers:
                click.echo(solver.id)
            return

        # ~YAML output
        for solver in solvers:
            click.echo("Solver: {}".format(solver.id))
            click.echo("  Parameters:")
            for name, val in sorted(solver.parameters.items()):
                click.echo("    {}: {}".format(name, strtrunc(val) if val else '?'))
            solver.properties.pop('parameters', None)
            click.echo("  Properties:")
            for name, val in sorted(solver.properties.items()):
                click.echo("    {}: {}".format(name, strtrunc(val)))
            click.echo("  Derived properties:")
            for name in sorted(solver.derived_properties):
                click.echo("    {}: {}".format(name, strtrunc(getattr(solver, name))))
            click.echo()
480876
def setupz(Np: int, zmin: float, gridmin: float, gridmax: float) -> np.ndarray:
    

    dz = _ztanh(Np, gridmin, gridmax)

    return np.insert(np.cumsum(dz)+zmin, 0, zmin)[:-1]
26793
def _setup_gc2_framework(self):
        
        # Generate cartesian edge set
        edge_sets = self._get_cartesian_edge_set()
        self.gc2_config = {}
        # Determine furthest two points apart
        endpoint_set = numpy.vstack([cep for cep in self.cartesian_endpoints])
        dmat = squareform(pdist(endpoint_set))
        irow, icol = numpy.unravel_index(numpy.argmax(dmat), dmat.shape)
        # Join further points to form a vector (a_hat in Spudich & Chiou)
        # According to Spudich & Chiou, a_vec should be eastward trending
        if endpoint_set[irow, 0] > endpoint_set[icol, 0]:
            # Row point is to the east of column point
            beginning = endpoint_set[icol, :2]
            ending = endpoint_set[irow, :2]
        else:
            # Column point is to the east of row point
            beginning = endpoint_set[irow, :2]
            ending = endpoint_set[icol, :2]

        # Convert to unit vector
        a_vec = ending - beginning
        self.gc2_config["a_hat"] = a_vec / numpy.linalg.norm(a_vec)
        # Get e_j set
        self.gc2_config["ejs"] = []
        for c_edges in self.cartesian_edges:
            self.gc2_config["ejs"].append(
                numpy.dot(c_edges[-1, :2] - c_edges[0, :2],
                          self.gc2_config["a_hat"]))
        # A "total E" is defined as the sum of the e_j values
        self.gc2_config["e_tot"] = sum(self.gc2_config["ejs"])
        sign_etot = numpy.sign(self.gc2_config["e_tot"])
        b_vec = numpy.zeros(2)
        self.gc2_config["sign"] = []
        for i, c_edges in enumerate(self.cartesian_edges):
            segment_sign = numpy.sign(self.gc2_config["ejs"][i]) * sign_etot
            self.gc2_config["sign"].append(segment_sign)
            if segment_sign < 0:
                # Segment is discordant - reverse the points
                c_edges = numpy.flipud(c_edges)
                self.cartesian_edges[i] = c_edges
                self.cartesian_endpoints[i] = numpy.flipud(
                    self.cartesian_endpoints[i])
            b_vec += (c_edges[-1, :2] - c_edges[0, :2])

        # Get unit vector
        self.gc2_config["b_hat"] = b_vec / numpy.linalg.norm(b_vec)
        if numpy.dot(a_vec, self.gc2_config["b_hat"]) >= 0.0:
            self.p0 = beginning
        else:
            self.p0 = ending
        # To later calculate Ry0 it is necessary to determine the maximum
        # GC2-U coordinate for the fault
        self._get_gc2_coordinates_for_rupture(edge_sets)
826975
def prepare(cls, options, round_manager):
    """"""
    super(NodeResolve, cls).prepare(options, round_manager)
    for resolver in cls._resolver_by_type.values():
      resolver.prepare(options, round_manager)
452566
public Grid setupGrid(float[] vertices) {
        int vc = vertices.length / 3;
        //CTM_POSITION_ELEMENT_COUNT == 3
        // Calculate the mesh boundinggrid. box
        float[] min = new float[3];
        float[] max = new float[3];
        int[] division = new int[3];

        for (int i = 0; i < 3; ++i) {
            min[i] = max[i] = vertices[i];

        }
        for (int i = 1; i < vc; ++i) {
            for (int j = 0; j < 3; j++) {
                min[j] = min(min[j], vertices[i * 3 + j]);
                max[j] = max(max[j], vertices[i * 3 + j]);
            }
        }

        // Determine optimal grid resolution, based on the number of vertices and
        // the bounding box.
        // NOTE: This algorithm is quite crude, and could very well be optimized for
        // better compression levels in the future without affecting the file format
        // or backward compatibility at all.

        float[] factor = new float[3];
        for (int i = 0; i < 3; ++i) {
            factor[i] = max[i] - min[i];
        }

        float sum = factor[0] + factor[1] + factor[2];

        if (sum > 1e-30f) {
            sum = 1.0f / sum;
            for (int i = 0; i < 3; ++i) {
                factor[i] *= sum;
            }
            double wantedGrids = pow(100.0f * vc, 1.0f / 3.0f);
            for (int i = 0; i < 3; ++i) {
                division[i] = (int) ceil(wantedGrids * factor[i]);
                if (division[i] < 1) {
                    division[i] = 1;
                }
            }
        } else {
            division[0] = 4;
            division[1] = 4;
            division[2] = 4;
        }

        return new Grid(Vec3f.from(min), Vec3f.from(max), Vec3i.from(division));
    }
223603
@Override
    public void solve(ZMatrixRMaj B, ZMatrixRMaj X) {
        if( X.numRows != numCols )
            throw new IllegalArgumentException("Unexpected dimensions for X");
        else if( B.numRows != numRows || B.numCols != X.numCols )
            throw new IllegalArgumentException("Unexpected dimensions for B");

        int BnumCols = B.numCols;

        Y.reshape(numRows,1);
        Z.reshape(numRows,1);

        // solve each column one by one
        for( int colB = 0; colB < BnumCols; colB++ ) {

            // make a copy of this column in the vector
            for( int i = 0; i < numRows; i++ ) {
                int indexB = B.getIndex(i,colB);
                Y.data[i*2]   = B.data[indexB];
                Y.data[i*2+1] = B.data[indexB+1];
            }

            // Solve Qa=b
            // a = Q'b
            CommonOps_ZDRM.mult(Qt, Y, Z);

            // solve for Rx = b using the standard upper triangular solver
            TriangularSolver_ZDRM.solveU(R.data, Z.data, numCols);

            // save the results
            for( int i = 0; i < numCols; i++ ) {
                X.set(i,colB,Z.data[i*2],Z.data[i*2+1]);
            }
        }
    }
929959
def cublasZsyrk(handle, uplo, trans, n, k, alpha, A, lda, beta, C, ldc):
    
    
    status = _libcublas.cublasZsyrk_v2(handle,
                                       _CUBLAS_FILL_MODE[uplo], 
                                       _CUBLAS_OP[trans], 
                                       n, k, ctypes.byref(cuda.cuDoubleComplex(alpha.real,    
                                                                               alpha.imag)),
                                       int(A), lda,
                                       ctypes.byref(cuda.cuDoubleComplex(beta.real,
                                                                         beta.imag)),
                                       int(C), ldc)
    cublasCheckStatus(status)
776553
def cublasDsyrk(handle, uplo, trans, n, k, alpha, A, lda, beta, C, ldc):
    
    
    status = _libcublas.cublasDsyrk_v2(handle,
                                       _CUBLAS_FILL_MODE[uplo], 
                                       _CUBLAS_OP[trans], 
                                       n, k, ctypes.byref(cuda.cuFloatComplex(alpha.real,     
                                                                              alpha.imag)),
                                       int(A), lda, 
                                       ctypes.byref(cuda.cuFloatComplex(beta.real,
                                                                        beta.imag)),
                                       int(C), ldc)
    cublasCheckStatus(status)
862174
def initialize(
            self, M_c, M_r, T, seed, initialization=b'from_the_prior',
            row_initialization=-1, n_chains=1,
            ROW_CRP_ALPHA_GRID=(), COLUMN_CRP_ALPHA_GRID=(),
            S_GRID=(), MU_GRID=(), N_GRID=31,):
        
        # FIXME: why is M_r passed?
        arg_tuples = self.get_initialize_arg_tuples(
            M_c, M_r, T, initialization, row_initialization, n_chains,
            ROW_CRP_ALPHA_GRID, COLUMN_CRP_ALPHA_GRID, S_GRID, MU_GRID, N_GRID,
            make_get_next_seed(seed),)

        chain_tuples = self.mapper(self.do_initialize, arg_tuples)
        X_L_list, X_D_list = zip(*chain_tuples)
        if n_chains == 1:
            X_L_list, X_D_list = X_L_list[0], X_D_list[0]

        return X_L_list, X_D_list
1037664
public static int cusolverRfSetupHost(
        int n, 
        int nnzA, 
        Pointer h_csrRowPtrA, 
        Pointer h_csrColIndA, 
        Pointer h_csrValA, 
        int nnzL, 
        Pointer h_csrRowPtrL, 
        Pointer h_csrColIndL, 
        Pointer h_csrValL, 
        int nnzU, 
        Pointer h_csrRowPtrU, 
        Pointer h_csrColIndU, 
        Pointer h_csrValU, 
        Pointer h_P, 
        Pointer h_Q, 
        /** Output */
        cusolverRfHandle handle)
    {
        return checkResult(cusolverRfSetupHostNative(n, nnzA, h_csrRowPtrA, h_csrColIndA, h_csrValA, nnzL, h_csrRowPtrL, h_csrColIndL, h_csrValL, nnzU, h_csrRowPtrU, h_csrColIndU, h_csrValU, h_P, h_Q, handle));
    }
992165
private void addSolutionSet(List<S> solutionList) {
    //Calculate the location of all individuals and update the grid
    mostPopulatedHypercube = 0;
    int location;

    for (int ind = 0; ind < solutionList.size(); ind++) {
      location = location(solutionList.get(ind));
      hypercubes[location]++;
      if (hypercubes[location] > hypercubes[mostPopulatedHypercube]) {
        mostPopulatedHypercube = location;
      }
    }

    //The grid has been updated, so also update ocuppied's hypercubes
    calculateOccupied();
  }
636316
function(w, h) {
    grid.set( space.size.$multiply( 0.1 ) ).to( space.size.$multiply( 0.9 ) ).init( 10, 10, "fix", "fix" );
    space.clear();
    buffer = [];
  }
1341496
def _setup_gin():
  """"""
  # Imports for configurables
  # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable
  from tensor2tensor.trax import models as _trax_models
  from tensor2tensor.trax import optimizers as _trax_opt
  # pylint: disable=g-import-not-at-top,unused-import,g-bad-import-order,reimported,unused-variable

  configs = FLAGS.config or []
  # Override with --dataset and --model
  if FLAGS.dataset:
    configs.append("inputs.dataset_name='%s'" % FLAGS.dataset)
    if FLAGS.data_dir:
      configs.append("inputs.data_dir='%s'" % FLAGS.data_dir)
  if FLAGS.model:
    configs.append("train.model=@trax.models.%s" % FLAGS.model)
  gin.parse_config_files_and_bindings(FLAGS.config_file, configs)