Exemplo n.º 1
0
double calc_norm(MeshFunction* ref_sln, int norm_type)
{
  double norm = -1.0;
  switch (norm_type) {
  case HERMES_L2_NORM:
    norm = calc_norm(norm_fn_l2, ref_sln);
    break;
  case HERMES_H1_NORM:
    norm = calc_norm(norm_fn_h1, ref_sln);
    break;
  case HERMES_HCURL_NORM:
    norm = calc_norm(norm_fn_hc, ref_sln);
    break;
  case HERMES_HDIV_NORM:
    norm = calc_norm(norm_fn_hdiv, ref_sln);
    break;
  default: error("Unknown norm in calc_norm().");
  }

  return norm;
}
Exemplo n.º 2
0
void euclid_lsh::similar_row(
    const common::sfv_t& query,
    vector<pair<string, float> >& ids,
    size_t ret_num) const {
  storage::lsh_index_storage& lsh_index = *mixable_storage_->get_model();
  ids.clear();

  const vector<float> hash = lsh_function(
      query, lsh_index.all_lsh_num(), bin_width_);
  const float norm = calc_norm(query);
  lsh_index.similar_row(hash, norm, num_probe_, ret_num, ids);
}
Exemplo n.º 3
0
void GradientDescent::run(lbfgsfloatval_t *weights)
{

    uint n = ot->get_level_sites(ot->current_level);
    lbfgsfloatval_t* g = new lbfgsfloatval_t[n];

    int iteration = 0;
    int continue_optimization = 0;

    float step_size = 0.5f;
    float min_step = 0.05f;
    float descendent = 0.999f;
    do{
        iteration++;
        lbfgsfloatval_t val = ot->evaluate(weights, g, n, 1.0);

        for (uint i=0; i<n; i++)
        {
            weights[i] -= (step_size*g[i]);
        }

        step_size *= descendent;
        if(step_size < min_step){
            step_size = min_step;
        }

        std::cout << "step size: " << step_size << std::endl;

        lbfgsfloatval_t gnorm = calc_norm(g, n);
        lbfgsfloatval_t xnorm = calc_norm(weights, n);

        continue_optimization = ot->progress(weights, g, val, xnorm, gnorm, 1.0, n, iteration, 1);
    }while(continue_optimization == 0);

    delete[] g;
}
Exemplo n.º 4
0
// Wrappers
extern "C" SEXP rth_norm(SEXP x_, SEXP p_, SEXP nthreads)
{
  double *x = REAL(x_);
  int len = LENGTH(x_);
  double p = REAL(p_)[0];
  
  SEXP nrm;
  PROTECT(nrm = allocVector(REALSXP, 1));
  
  RTH_GEN_NTHREADS(nthreads);
  
  REAL(nrm)[0] = calc_norm(x, len, p);
  
  UNPROTECT(1);
  return nrm;
}
Exemplo n.º 5
0
// function used to combine the contributions from solution components to the total error 
double error_total(	double (*efn)(MeshFunction*, MeshFunction*, RefMap*, RefMap*), 
										double (*nfn)(MeshFunction*, RefMap*), 
										Tuple<Solution*>& slns1, 
										Tuple<Solution*>& slns2	)
{
  Tuple<Solution*>::iterator it1, it2;
  double error = 0.0, norm = 0.0;

  for (it1=slns1.begin(), it2=slns2.begin(); it1 < slns1.end(); it1++, it2++) {
    assert(it2 < slns2.end());
    error += sqr(calc_error(efn, *it1, *it2));
    if (nfn) norm += sqr(calc_norm(nfn, *it2));
  }

  return (nfn ? sqrt(error/norm) : sqrt(error));
}
Exemplo n.º 6
0
// Euclidean distance of two vectors
double calc_dist(double *x, const double *y, const int len, const double p)
{
  int i;
  double *diff;
  double dist;
  
  diff = (double *) malloc(len * sizeof(diff));
  
  for (i=0; i<len; i++)
    diff[i] = x[i] - y[i];
  
  dist = calc_norm(diff, len, p);
  
  free(diff);
  
  return dist;
}
Exemplo n.º 7
0
void euclid_lsh::update_row(const string& id, const sfv_diff_t& diff) {
  if (unlearner_ && !unlearner_->can_touch(id)) {
    throw JUBATUS_EXCEPTION(common::exception::runtime_error(
        "cannot add new row as number of sticky rows reached "
            "the maximum size of unlearner: " + id));
  }
  storage::lsh_index_storage& lsh_index = *mixable_storage_->get_model();
  orig_.set_row(id, diff);
  common::sfv_t row;
  orig_.get_row(id, row);

  const vector<float> hash = calculate_lsh(row);
  const float norm = calc_norm(row);
  lsh_index.set_row(id, hash, norm);
  if (unlearner_) {
    unlearner_->touch(id);
  }
}
Exemplo n.º 8
0
bool calc_errors(Hermes::vector<Solution* > left, Hermes::vector<Solution *> right, Hermes::vector<double> & err_abs, Hermes::vector<double> & norm_vals,
                 double & err_abs_total, double & norm_total, double & err_rel_total, Hermes::vector<ProjNormType> norms)
{
  bool default_norms = false;
  // Checks.
  if(left.size() != right.size())
    return false;
  if (norms != Hermes::vector<ProjNormType>())
  {
    if(left.size() != norms.size())
      return false;
  }
  else
    default_norms = true;

  // Zero the resulting Tuples.
  err_abs.clear();
  norm_vals.clear();

  // Zero the sums.
  err_abs_total = 0;
  norm_total = 0;
  err_rel_total = 0;

  // Calculation.
  for(unsigned int i = 0; i < left.size(); i++)
  {
    err_abs.push_back(calc_abs_error(left[i], right[i], default_norms ? HERMES_H1_NORM : norms[i]));
    norm_vals.push_back(calc_norm(right[i], default_norms ? HERMES_H1_NORM : norms[i]));
    err_abs_total += err_abs[i] * err_abs[i];
    norm_total += norm_vals[i] * norm_vals[i];
  }

  err_abs_total = sqrt(err_abs_total);
  norm_total = sqrt(norm_total);
  err_rel_total = err_abs_total / norm_total * 100.;

  // Everything went well, return appropriate flag.
  return true;
}
Exemplo n.º 9
0
void verify(char *Class, logical *verified)
{
  double norm, epsilon, norm_dif, norm_ref;

  // tolerance level
  epsilon = 1.0e-08;

  // compute the temperature integral over the whole domain
  norm = calc_norm();

  *verified = true;
  if ( *Class == 'S' ) {
    norm_ref = 0.1890013110962E-02;
  } else if ( *Class == 'W' ) {
    norm_ref = 0.2569794837076E-04;
  } else if ( *Class == 'A' ) {
    norm_ref = 0.8939996281443E-04;
  } else if ( *Class == 'B' ) {
    norm_ref = 0.4507561922901E-04;
  } else if ( *Class == 'C' ) {
    norm_ref = 0.1544736587100E-04;
  } else if ( *Class == 'D' ) {
    norm_ref = 0.1577586272355E-05;
  } else {
    *Class = 'U';
    norm_ref = 1.0;
    *verified = false;
  }         

  norm_dif = fabs((norm - norm_ref)/norm_ref);

  //---------------------------------------------------------------------
  // Output the comparison of computed results to known cases.
  //---------------------------------------------------------------------
  printf("\n");

  if (*Class != 'U') {
    printf(" Verification being performed for class %c\n", *Class);
    printf(" accuracy setting for epsilon = %20.13E\n", epsilon);
  } else { 
    printf(" Unknown class\n");
  }

  if (*Class != 'U') {
    printf(" Comparison of temperature integrals\n");
  } else {
    printf(" Temperature integral\n");
  }

  if (*Class == 'U') {
    printf("          %20.13E\n", norm);
  } else if (norm_dif <= epsilon) {
    printf("          %20.13E%20.13E%20.13E\n", norm, norm_ref, norm_dif);
  } else { 
    *verified = false;
    printf(" FAILURE: %20.13E%20.13E%20.13E\n", norm, norm_ref, norm_dif);
  }

  if (*Class == 'U') {
    printf(" No reference values provided\n");
    printf(" No verification performed\n");
  } else if (*verified) {
    printf(" Verification Successful\n");
  } else {
    printf(" Verification failed\n");
  }
}
Exemplo n.º 10
0
double h1_norm_axisym(MeshFunction* sln)
{
  return calc_norm(norm_fn_h1_axisym, sln);
}
Exemplo n.º 11
0
double h1_error_axisym(MeshFunction* sln1, MeshFunction* sln2)
{
  double error = calc_abs_error(error_fn_h1_axisym, sln1, sln2);
  double norm = calc_norm(norm_fn_h1_axisym, sln2);
  return error/norm;
}
Exemplo n.º 12
0
/*!
   \brief Calculate normals

   OPTIMIZED for constant dy & dx

   The norm array is always the same size, but diff resolutions
   force resampled data points to have their normals recalculated,
   then only those norms are passed to n3f during drawing.
   Norms are converted to a packed unsigned int for storage,
   must be converted back at time of use.

   \todo fix to correctly calculate norms when mapped to sphere!

   Uses the previous and next cells (when available) for normal 
   calculations to produce smoother normals

   \param gs surface (geosurf)

   \return 1 on success
   \return 0 on failure
 */
int gs_calc_normals(geosurf * gs)
{
    int row, col;
    int xcnt, ycnt;
    int xmod, ymod;

    if (!gs->norm_needupdate || !gs->norms) {
	return (0);
    }

    gs->norm_needupdate = 0;
    gs_update_curmask(gs);

    xmod = gs->x_mod;
    ymod = gs->y_mod;

    xcnt = VCOLS(gs);
    ycnt = VROWS(gs);

    init_vars(gs);

    G_debug(5, "gs_calc_normals(): id=%d", gs->gsurf_id);

    /* first row - just use single cell */
    /* first col - use bottom & right neighbors */
    calc_norm(gs, 0, 0, NBR);

    for (col = 1; col < xcnt; col++) {
	/* turn off top neighbor for first row */
	calc_norm(gs, 0, col * xmod, ~NTOP);
    }

    /* use bottom & left neighbors for last col */
    calc_norm(gs, 0, col * xmod, NBL);

    /* now use four neighboring points for rows 1 - (n-1) */
    for (row = 1; row < ycnt; row++) {
	if (!(row % 100))
	    G_debug(5, "gs_calc_normals(): row=%d", row);

	/* turn off left neighbor for first col */
	calc_norm(gs, row * ymod, 0, ~NLFT);

	/* use all 4 neighbors until last col */
	for (col = 1; col < xcnt; col++) {
	    calc_norm(gs, row * ymod, col * xmod, NALL);
	}

	/* turn off right neighbor for last col */
	calc_norm(gs, row * ymod, col * xmod, ~NRGT);
    }

    /* last row */
    /* use top & right neighbors for first col */
    calc_norm(gs, row * ymod, 0, NTR);

    for (col = 1; col < xcnt; col++) {
	/* turn off bottom neighbor for last row */
	calc_norm(gs, row * ymod, col * xmod, ~NBOT);
    }

    /* use top & left neighbors for last column */
    calc_norm(gs, row * ymod, col * xmod, NTL);

    return (1);
}
Exemplo n.º 13
0
int main(int argc, char* argv[])
{
  // Choose a Butcher's table or define your own.
  ButcherTable bt(butcher_table_type);
  if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size());
  if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size());
  if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size());

  // Load the mesh.
  Mesh mesh;
  H2DReader mloader;
  mloader.load("wall.mesh", &mesh);

  // Perform initial mesh refinements.
  for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();
  mesh.refine_towards_boundary(BDY_BOTTOM, INIT_REF_NUM_BDY);

  // Enter boundary markers.
  BCTypes bc_types;
  bc_types.add_bc_neumann(Hermes::vector<int>(BDY_RIGHT, BDY_LEFT));
  bc_types.add_bc_newton(Hermes::vector<int>(BDY_BOTTOM, BDY_TOP));

  // Initialize an H1 space with default shapeset.
  H1Space space(&mesh, &bc_types, NULL, P_INIT);
  int ndof = Space::get_num_dofs(&space);
  info("ndof = %d.", ndof);
 
  // Previous and next time level solutions.
  Solution* sln_time_prev = new Solution(&mesh, TEMP_INIT);
  Solution* sln_time_new = new Solution(&mesh);
  Solution* time_error_fn = new Solution(&mesh, 0.0);

  // Initialize weak formulation.
  WeakForm wf;
  wf.add_matrix_form(stac_jacobian_vol, stac_jacobian_vol_ord, HERMES_NONSYM, HERMES_ANY, sln_time_prev);
  wf.add_vector_form(stac_residual_vol, stac_residual_vol_ord, HERMES_ANY, sln_time_prev);
  wf.add_matrix_form_surf(stac_jacobian_bottom, stac_jacobian_bottom_ord, BDY_BOTTOM, sln_time_prev);
  wf.add_vector_form_surf(stac_residual_bottom, stac_residual_bottom_ord, BDY_BOTTOM, sln_time_prev);
  wf.add_matrix_form_surf(stac_jacobian_top, stac_jacobian_top_ord, BDY_TOP, sln_time_prev);
  wf.add_vector_form_surf(stac_residual_top, stac_residual_top_ord, BDY_TOP, sln_time_prev);

  // Initialize the FE problem.
  bool is_linear = true;
  DiscreteProblem dp(&wf, &space, is_linear);

  // Initialize views.
  ScalarView Tview("Temperature", new WinGeom(0, 0, 1500, 400));
  Tview.fix_scale_width(40);
  ScalarView eview("Temporal error", new WinGeom(0, 450, 1500, 400));
  eview.fix_scale_width(40);

  // Graph for time step history.
  SimpleGraph time_step_graph;
  info("Time step history will be saved to file time_step_history.dat.");

  // Time stepping loop:
  double current_time = 0; int ts = 1;
  do 
  {
    // Perform one Runge-Kutta time step according to the selected Butcher's table.
    info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).", 
         current_time, time_step, bt.get_size());
    bool verbose = true;
    bool is_linear = true;
    if (!rk_time_step(current_time, time_step, &bt, sln_time_prev, sln_time_new, time_error_fn, &dp, matrix_solver,
		      verbose, is_linear)) {
      error("Runge-Kutta time step failed, try to decrease time step size.");
    }

    // Plot error function.
    char title[100];
    sprintf(title, "Temporal error, t = %g", current_time);
    eview.set_title(title);
    AbsFilter abs_tef(time_error_fn);
    eview.show(&abs_tef, HERMES_EPS_VERYHIGH);

    // Calculate relative time stepping error and decide whether the 
    // time step can be accepted. If not, then the time step size is 
    // reduced and the entire time step repeated. If yes, then another
    // check is run, and if the relative error is very low, time step 
    // is increased.
    double rel_err_time = calc_norm(time_error_fn, HERMES_H1_NORM) / calc_norm(sln_time_new, HERMES_H1_NORM) * 100;
    info("rel_err_time = %g%%", rel_err_time);
    if (rel_err_time > TIME_TOL_UPPER) {
      info("rel_err_time above upper limit %g%% -> decreasing time step from %g to %g and restarting time step.", 
           TIME_TOL_UPPER, time_step, time_step * TIME_STEP_DEC_RATIO);
      time_step *= TIME_STEP_DEC_RATIO;
      continue;
    }
    if (rel_err_time < TIME_TOL_LOWER) {
      info("rel_err_time = below lower limit %g%% -> increasing time step from %g to %g", 
           TIME_TOL_UPPER, time_step, time_step * TIME_STEP_INC_RATIO);
      time_step *= TIME_STEP_INC_RATIO;
    }

    // Add entry to the timestep graph.
    time_step_graph.add_values(current_time, time_step);
    time_step_graph.save("time_step_history.dat");

    // Update time.
    current_time += time_step;

    // Show the new time level solution.
    sprintf(title, "Time %3.2f s", current_time);
    Tview.set_title(title);
    Tview.show(sln_time_new);

    // Copy solution for the new time step.
    sln_time_prev->copy(sln_time_new);

    // Increase counter of time steps.
    ts++;
  } 
  while (current_time < T_FINAL);

  // Cleanup.
  delete sln_time_prev;
  delete sln_time_new;
  delete time_error_fn;

  // Wait for the view to be closed.
  View::wait();
  return 0;
}
Exemplo n.º 14
0
/*
* H*x will make [c+2~m] zero, c is script, Error
*/
static Matrix* householder(Matrix *v, int c)
{
	Matrix* oldAns = ans;
	Matrix* oldAns2;
	Matrix* temp = NULL;
	int i;
	double norm;
	int k;
	if (v == NULL)
	{
		//Error
		return NULL;
	}
	if (v->n != 1)
	{
		//Error
		return NULL;
	}
	ans = NULL;
	if (!stor_createMatrix(&temp, v->m, 1))
	{
		//Error
		return NULL;
	}
	if (!stor_assign(temp, v))
	{
		//Error
		return NULL;
	}
	for (i = 0; i < c; i++)
	{
		*stor_entry(temp, i, 0) = 0;
	}
	if (!calc_norm(temp))//NULL
	{
		//Error
		return NULL;
	}
	norm = *stor_entry(ans, 0, 0);
	k = c;
	*stor_entry(temp, k, 0) += norm;
	if (!calc_norm(temp))
	{
		//Error
		return NULL;
	}
	norm = *stor_entry(ans, 0, 0);
	if (util_isZero(norm))
	{
		//Error
		return NULL;
	}
	if (!calc_numMul(calc_mul(temp, calc_trans(temp)),(double)2.0/(norm*norm)))
	{
		//Error
		return NULL;
	}
	oldAns2 = ans;
	ans = NULL;
	if (!calc_sub(calc_eye(temp->m), oldAns2))
	{
		//Error
		return NULL;
	}
	stor_freeMatrix(oldAns2);
	stor_freeMatrix(oldAns);
	return ans;
}
Exemplo n.º 15
0
real
calc_phi_SOR
(
          real * const phi,
    const real * const u,
    const real * const v,
    const real dt,
    const real beta,
    const Mesh & mesh
){
    real sum_for_numerator   = 0.0;
    real sum_for_denominator = 0.0;

    boundary_update_phi( phi, mesh );

    const int k = mesh.hn() ;
    for ( int j = mesh.hn() ; j < mesh.hnf(1) ; j++ ) {
    for ( int i = mesh.hn() ; i < mesh.hnf(0) ; i++ ) {

        const int id = mesh.id(i,j,k);

        //if ( i != mesh.hn() || j != mesh.hn() ) {


            const int id_e = mesh.id(i+1,j,k);
            const int id_w = mesh.id(i-1,j,k);

            const int id_n = mesh.id(i,j+1,k);
            const int id_s = mesh.id(i,j-1,k);

            const real B_x  = 1.0 / std::pow(mesh.delta(0), 2);
            const real B_y  = 1.0 / std::pow(mesh.delta(1), 2);

            const real B_ij = 2.0 * ( B_x + B_y );

            const real psi = psi_ij( u, v, id, dt, mesh );

            const real nabla_phi =   B_y  * ( phi[id_s] + phi[id_n] )
                                   + B_x  * ( phi[id_w] + phi[id_e] )
                                   - B_ij * phi[id];

            const real adjust = nabla_phi - psi;
            
            phi[id] += beta / B_ij * adjust;

            sum_for_numerator   += std::pow(nabla_phi - psi, 2);
            sum_for_denominator += std::pow(psi, 2);

        //} else {
            //phi[id] = 0.0;
        //}
    }}

    boundary_update_phi( phi, mesh );

    const int nn = mesh.n(0) * mesh.n(1);
    const real numerator   = calc_norm( sum_for_numerator, nn );
    const real denominator = calc_norm( sum_for_denominator, nn );

    return numerator / denominator;
}