void learn_lvq2(struct codebook *cbdata, struct codebook *cbref, int nbit, flt a0, flt win) { int i,j,nn1,nn2; flt alph = Fzero; for (i = 0; i < nbit; i++) { CHECK_MACHINE("on"); for (j = 0; j < cbdata->ncode; j++) { two_nn(cbdata->code[j].word,cbref,&nn1,&nn2); if (cbdata->code[j].label != cbref->code[nn1].label) { if (cbdata->code[j].label == cbref->code[nn2].label) if (in_window(&(cbref->code[nn1]), &(cbref->code[nn2]), &(cbdata->code[j]), cbdata->ndim, win ) ) { alph=alpha(a0,i,nbit); adapt(&(cbdata->code[j]),&(cbref->code[nn1]),alph,cbdata->ndim); adapt(&(cbdata->code[j]),&(cbref->code[nn2]),-alph,cbdata->ndim); } } } } }
void learn_lvq3(struct codebook *cbdata, struct codebook *cbref, int nbit, flt a0, flt win) { int i,j,nn1,nn2,c; flt alph = Fzero; for (i = 0; i < nbit; i++) { CHECK_MACHINE("on"); for (j = 0; j < cbdata->ncode; j++) { c = cbdata->code[j].label; one_nn_and_a_half(cbdata->code[j].word,cbref,c,&nn1,&nn2); if (c!=cbref->code[nn1].label) { if (nn2<0) error(NIL,"Class not represented in the references", NEW_NUMBER(c)); if (in_window(&(cbref->code[nn1]), &(cbref->code[nn2]), &(cbdata->code[j]), cbdata->ndim, win ) ) { alph=alpha(a0,i,nbit); adapt(&(cbdata->code[j]),&(cbref->code[nn1]),alph,cbdata->ndim); adapt(&(cbdata->code[j]),&(cbref->code[nn2]),-alph,cbdata->ndim); } } } } }
void DataFromNexus::initialiseDataToStream(VDS::Client& client) { if (useMarkerData_) client.EnableMarkerData(); else client.DisableMarkerData(); if (useGrfData_) client.EnableDeviceData(); else client.DisableDeviceData(); client.DisableSegmentData(); client.DisableUnlabeledMarkerData(); cout << "Marker Data Enabled: " << adapt(client.IsMarkerDataEnabled().Enabled) << endl; cout << "Device Data Enabled: " << adapt(client.IsDeviceDataEnabled().Enabled) << endl; cout << "Segments Data Enabled: " << adapt(client.IsSegmentDataEnabled().Enabled) << endl; cout << "Unlabelled Markers Data Enabled: " << adapt(client.IsUnlabeledMarkerDataEnabled().Enabled) << endl; while (client.SetStreamMode(VDS::StreamMode::ServerPush).Result != VDS::Result::Success) cout << "."; cout << endl; if (useMarkerData_) waitForCompleteFrame(client); if (useGrfData_) waitForForcePlates(client); }
void sampler_adaptive::adapt(double *p, const double *a, const double *b, const double *c, const double *d, int r) { double v[3]; double va[3], pa[4]; double vb[3], pb[4]; double vc[3], pc[4]; double vd[3], pd[4]; mid4(v, a, b, c, d); mid2(va, v, a); mid2(vb, v, b); mid2(vc, v, c); mid2(vd, v, d); source->get(pa, va); source->get(pb, vb); source->get(pc, vc); source->get(pd, vd); if (r < 4) { if (contrast(pa[0], pb[0], pc[0], pd[0]) > kr || contrast(pa[1], pb[1], pc[1], pd[1]) > kg || contrast(pa[2], pb[2], pc[2], pd[2]) > kb) { double n[3]; double s[3]; double e[3]; double w[3]; mid2(n, a, b); mid2(s, c, d); mid2(e, a, c); mid2(w, b, d); adapt(pa, a, n, e, v, r + 1); adapt(pb, n, b, v, w, r + 1); adapt(pc, e, v, c, s, r + 1); adapt(pd, v, w, s, d, r + 1); } } switch (source->getc()) { case 4: p[3] = (pa[3] + pb[3] + pc[3] + pd[3]) / 4; case 3: p[2] = (pa[2] + pb[2] + pc[2] + pd[2]) / 4; case 2: p[1] = (pa[1] + pb[1] + pc[1] + pd[1]) / 4; case 1: p[0] = (pa[0] + pb[0] + pc[0] + pd[0]) / 4; } }
bool Adapt<Scalar>::adapt(RefinementSelectors::Selector<Scalar>* refinement_selector, double thr, int strat, int regularize, double to_be_processed) { Hermes::vector<RefinementSelectors::Selector<Scalar> *> refinement_selectors; refinement_selectors.push_back(refinement_selector); return adapt(refinement_selectors, thr, strat, regularize, to_be_processed); }
bool readint(int& n){ // Returns true on success, false on failure if(!adapt()) return false; bool ngtv = *(now - 1) == '-'; for(n = 0; isdigit(*now); n = X10(n) + *now++ - '0'); if(ngtv) n = -n; return true; }
void right_rot(int fa,int x){ int y=tree[x].left; tree[x].left=tree[y].right; tree[y].right=x; tree[y].size=tree[x].size; if (fa){ if (tree[fa].left==x) tree[fa].left=y; else tree[fa].right=y; } adapt(x); root=root==x?y:root; }
void learn_lvq1(struct codebook *cbdata, struct codebook *cbref, int nbit, flt a0) { int i,j,nn1; flt alph = Fzero; for (i = 0; i < nbit; i++) { CHECK_MACHINE("on"); for (j = 0; j < cbdata->ncode; j++) { one_nn(cbdata->code[j].word,cbref,&nn1); if (cbdata->code[j].label != cbref->code[nn1].label) { alph=alpha(a0,i,nbit); adapt(&(cbdata->code[j]),&(cbref->code[nn1]),alph,cbdata->ndim); } else adapt(&(cbdata->code[j]),&(cbref->code[nn1]),-alph,cbdata->ndim); } } }
static void AllocationGenerateScriptMips(RsContext con, RsAllocation va) { Context *rsc = static_cast<Context *>(con); Allocation *texAlloc = static_cast<Allocation *>(va); uint32_t numFaces = texAlloc->getType()->getDimFaces() ? 6 : 1; for (uint32_t face = 0; face < numFaces; face ++) { Adapter2D adapt(rsc, texAlloc); Adapter2D adapt2(rsc, texAlloc); adapt.setFace(face); adapt2.setFace(face); for (uint32_t lod=0; lod < (texAlloc->getType()->getLODCount() -1); lod++) { adapt.setLOD(lod); adapt2.setLOD(lod + 1); mip(adapt2, adapt); } } }
void adapt_bw(double lossrate){ int j; match_ssrc(ssrc, lossrate); j = adapt(); if (j == 1) { if ((cur_bw * D) > min_bw) { packet_size = packet_size * D; cur_bw = get_cur_bw(packet_size); fprintf(stderr, "case1 - pkt lossrate : %lf > upper : %lf, decrease cur_bw to = %lf\n", lossrate, upper, cur_bw); printf("case2 - pkt lossrate : %lf > upper : %lf, decrease cur_bw to = %lf\n", lossrate, upper, cur_bw); } else { packet_size = minbw_pktsize; cur_bw = get_cur_bw(packet_size); fprintf(stderr, "case2 - pkt lossrate : %lf > upper : %lf, decrease cur_bw to = %lf\n", lossrate, upper, cur_bw); printf("case2 - pkt lossrate : %lf > upper : %lf, decrease cur_bw to = %lf\n", lossrate, upper, cur_bw); } } else if (j == 2) { if (cur_bw + I < max_bw) { packet_size = packet_size + minbw_pktsize; cur_bw = get_cur_bw(packet_size); fprintf(stderr, "case3 - pkt lossrate : %lf < lower : %lf, increase cur_bw to = %lf\n", lossrate, lower, cur_bw); printf("case3 - pkt lossrate : %lf < lower : %lf, increase cur_bw to = %lf\n", lossrate, lower, cur_bw); } else { packet_size = minbw_pktsize * 20; cur_bw = get_cur_bw(packet_size); fprintf(stderr, "case4 - pkt lossrate : %lf < lower : %lf, increase cur_bw to = %lf\n", lossrate, lower, cur_bw); printf("case4 - pkt lossrate : %lf < lower : %lf, increase cur_bw to = %lf\n", lossrate, lower, cur_bw); } } else { fprintf(stderr, "case5 - pkt lossrate : %lf, cur_bw is %lf\n", lossrate, cur_bw); printf("case5 - pkt lossrate : %lf, cur_bw is %lf\n", lossrate, cur_bw); } }
// ******************************************************************** int main() { // Create coarse mesh, set Dirichlet BC, enumerate basis functions Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq); mesh->set_bc_left_dirichlet(0, Val_dir_left_0); mesh->set_bc_left_dirichlet(1, Val_dir_left_1); printf("N_dof = %d\n", mesh->assign_dofs()); // Create discrete problem on coarse mesh DiscreteProblem *dp = new DiscreteProblem(); dp->add_matrix_form(0, 0, jacobian_0_0); dp->add_matrix_form(0, 1, jacobian_0_1); dp->add_matrix_form(1, 0, jacobian_1_0); dp->add_matrix_form(1, 1, jacobian_1_1); dp->add_vector_form(0, residual_0); dp->add_vector_form(1, residual_1); // scipy umfpack solver CommonSolverSciPyUmfpack solver; // Initial Newton's loop on coarse mesh newton(dp, mesh, &solver, NEWTON_TOL_COARSE, NEWTON_MAXITER); // Replicate coarse mesh including dof arrays Mesh *mesh_ref = mesh->replicate(); // Refine entire mesh_ref uniformly in 'h' and 'p' int start_elem_id = 0; int num_to_ref = mesh_ref->get_n_active_elem(); mesh_ref->reference_refinement(start_elem_id, num_to_ref); printf("Fine mesh created (%d DOF).\n", mesh_ref->get_n_dof()); // Convergence graph wrt. the number of degrees of freedom GnuplotGraph graph; graph.set_log_y(); graph.set_captions("Convergence History", "Degrees of Freedom", "Error [%]"); graph.add_row("exact error", "k", "-", "o"); graph.add_row("error estimate", "k", "--"); // Main adaptivity loop int adapt_iterations = 1; while(1) { printf("============ Adaptivity step %d ============\n", adapt_iterations); // Newton's loop on fine mesh newton(dp, mesh_ref, &solver, NEWTON_TOL_REF, NEWTON_MAXITER); // Starting with second adaptivity step, obtain new coarse // mesh solution via Newton's method. Initial condition is // the last coarse mesh solution. if (adapt_iterations > 1) { // Newton's loop on coarse mesh newton(dp, mesh, &solver, NEWTON_TOL_COARSE, NEWTON_MAXITER); } // In the next step, estimate element errors based on // the difference between the fine mesh and coarse mesh solutions. double err_est_array[MAX_ELEM_NUM]; double err_est_total = calc_error_estimate(NORM, mesh, mesh_ref, err_est_array); // Calculate the norm of the fine mesh solution double ref_sol_norm = calc_solution_norm(NORM, mesh_ref); // Calculate an estimate of the global relative error double err_est_rel = err_est_total/ref_sol_norm; printf("Relative error (est) = %g %%\n", 100.*err_est_rel); // If exact solution available, also calculate exact error double err_exact_rel; if (EXACT_SOL_PROVIDED) { // Calculate element errors wrt. exact solution double err_exact_total = calc_error_exact(NORM, mesh, exact_sol); // Calculate the norm of the exact solution // (using a fine subdivision and high-order quadrature) int subdivision = 500; // heuristic parameter int order = 20; // heuristic parameter double exact_sol_norm = calc_solution_norm(NORM, exact_sol, N_eq, A, B, subdivision, order); // Calculate an estimate of the global relative error err_exact_rel = err_exact_total/exact_sol_norm; printf("Relative error (exact) = %g %%\n", 100.*err_exact_rel); graph.add_values(0, mesh->get_n_dof(), 100 * err_exact_rel); } // add entry to DOF convergence graph graph.add_values(1, mesh->get_n_dof(), 100 * err_est_rel); // Decide whether the relative error is sufficiently small if(err_est_rel*100 < TOL_ERR_REL) break; // debug // (adapt_iterations == 2) break; // Returns updated coarse and fine meshes, with the last // coarse and fine mesh solutions on them, respectively. // The coefficient vectors and numbers of degrees of freedom // on both meshes are also updated. adapt(NORM, ADAPT_TYPE, THRESHOLD, err_est_array, mesh, mesh_ref); adapt_iterations++; } // Plot meshes, results, and errors adapt_plotting(mesh, mesh_ref, NORM, EXACT_SOL_PROVIDED, exact_sol); // Save convergence graph graph.save("conv_dof.gp"); int success_test = 1; printf("N_dof = %d\n", mesh->get_n_dof()); if (mesh->get_n_dof() > 70) success_test = 0; if (success_test) { printf("Success!\n"); return ERROR_SUCCESS; } else { printf("Failure!\n"); return ERROR_FAILURE; } }
void RecBookFile::SaveContent( ) { wxASSERT( m_xml_root ); TiXmlElement book("book"); int i; book.SetAttribute("RISM", m_RISM.c_str() ); book.SetAttribute("Composer", m_Composer.c_str() ); book.SetAttribute("Title", m_Title.c_str() ); book.SetAttribute("Printer", m_Printer.c_str() ); book.SetAttribute("Year", m_Year.c_str() ); book.SetAttribute("Library", m_Library.c_str() ); m_xml_root->InsertEndChild( book ); TiXmlElement images("images"); wxFileName dirname1 = wxFileName::DirName( m_imgFileDir ); dirname1.MakeRelativeTo( wxFileName( m_filename ).GetFullPath() ); //wxLogDebug( dirname1.GetPath() ); images.SetAttribute("Path", dirname1.GetPath().c_str() ); for ( i = 0; i < (int)m_imgFiles.GetCount(); i++) { TiXmlElement image("image"); image.SetAttribute("filename", m_imgFiles[i].m_filename.c_str() ); image.SetAttribute("flags", wxString::Format("%d", m_imgFiles[i].m_flags ).c_str() ); images.InsertEndChild( image ); } m_xml_root->InsertEndChild( images ); TiXmlElement axfiles("axfiles"); wxFileName dirname2 = wxFileName::DirName( m_axFileDir ); dirname2.MakeRelativeTo( wxFileName( m_filename ).GetFullPath() ); //wxLogDebug( dirname2.GetPath() ); axfiles.SetAttribute("Path", dirname2.GetPath().c_str() ); for ( i = 0; i < (int)m_axFiles.GetCount(); i++) { TiXmlElement axfile("axfile"); axfile.SetAttribute("filename", m_axFiles[i].m_filename.c_str() ); axfile.SetAttribute("flags", wxString::Format("%d", m_axFiles[i].m_flags ).c_str() ); axfiles.InsertEndChild( axfile ); } m_xml_root->InsertEndChild( axfiles ); TiXmlElement adapt("adaptation"); adapt.SetAttribute("full", wxString::Format("%d", m_fullOptimized ).c_str() ); adapt.SetAttribute("nb_files_for_full", wxString::Format("%d", m_nbFilesOptimization ).c_str() ); for ( i = 0; i < (int)m_optFiles.GetCount(); i++) { TiXmlElement adapt_file("file"); adapt_file.SetAttribute("filename", m_optFiles[i].c_str() ); adapt.InsertEndChild( adapt_file ); } m_xml_root->InsertEndChild( adapt ); // binarization variables TiXmlElement binarization( "binarization" ); binarization.SetAttribute( "pre_image_binarization_method", m_pre_image_binarization_method ); binarization.SetAttribute( "pre_page_binarization_method", m_pre_page_binarization_method ); binarization.SetAttribute( "pre_page_binarization_method_size", m_pre_page_binarization_method_size ); binarization.SetAttribute( "pre_page_binarization_select", m_pre_page_binarization_select ); m_xml_root->InsertEndChild( binarization ); }
int main(int argc, char **argv) { int rank=0; int required_thread_support=MPI_THREAD_SINGLE; int provided_thread_support; MPI_Init_thread(&argc, &argv, required_thread_support, &provided_thread_support); assert(required_thread_support==provided_thread_support); MPI_Comm_rank(MPI_COMM_WORLD, &rank); bool verbose = false; if(argc>1) { verbose = std::string(argv[1])=="-v"; } #ifdef HAVE_VTK Mesh<double> *mesh=VTKTools<double>::import_vtu("../data/box200x200.vtu"); mesh->create_boundary(); MetricField<double,2> metric_field(*mesh); size_t NNodes = mesh->get_number_nodes(); for(size_t i=0; i<NNodes; i++) { double m[] = {0.5, 0.0, 0.5}; metric_field.set_metric(m, i); } metric_field.update_mesh(); Coarsen<double,2> adapt(*mesh); double L_up = sqrt(2.0); double L_low = L_up*0.5; double tic = get_wtime(); adapt.coarsen(L_low, L_up); double toc = get_wtime(); mesh->defragment(); int nelements = mesh->get_number_elements(); long double perimeter = mesh->calculate_perimeter(); long double area = mesh->calculate_area(); if(verbose) { if(rank==0) std::cout<<"Coarsen loop time: "<<toc-tic<<std::endl <<"Number elements: "<<nelements<<std::endl <<"Perimeter: "<<perimeter<<std::endl; } VTKTools<double>::export_vtu("../data/test_coarsen_2d", mesh); delete mesh; if(rank==0) { std::cout<<"Expecting 2 elements: "; if(nelements==2) std::cout<<"pass"<<std::endl; else std::cout<<"fail"<<std::endl; long double perimeter_exact(4); std::cout<<"Expecting perimeter = "<<perimeter_exact<<": "<<perimeter<<" ("<<std::abs(perimeter-perimeter_exact)/std::max(perimeter, perimeter_exact)<<") "; if(std::abs(perimeter-perimeter_exact)/std::max(perimeter, perimeter_exact)<DBL_EPSILON) std::cout<<"pass"<<std::endl; else std::cout<<"fail"<<std::endl; long double area_exact = 1; std::cout<<"Expecting area = "<<area_exact<<": "; if(std::abs(area-area_exact)/std::max(area, area_exact)<DBL_EPSILON) std::cout<<"pass"<<std::endl; else std::cout<<"fail"<<std::endl; } #else std::cerr<<"Pragmatic was configured without VTK"<<std::endl; #endif MPI_Finalize(); return 0; }
int main() { // Create coarse mesh, set Dirichlet BC, enumerate // basis functions Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq); mesh->set_bc_left_dirichlet(0, Val_dir_left); mesh->set_bc_right_dirichlet(0, Val_dir_right); mesh->assign_dofs(); // Create discrete problem on coarse mesh DiscreteProblem *dp = new DiscreteProblem(); dp->add_matrix_form(0, 0, jacobian); dp->add_vector_form(0, residual); // Convergence graph wrt. the number of degrees of freedom GnuplotGraph graph; graph.set_log_y(); graph.set_captions("Convergence History", "Degrees of Freedom", "Error"); graph.add_row("exact error [%]", "k", "-", "o"); graph.add_row("max FTR error", "k", "--"); // Main adaptivity loop int adapt_iterations = 1; double ftr_errors[MAX_ELEM_NUM]; // This array decides what // elements will be refined. ElemPtr2 ref_ftr_pairs[MAX_ELEM_NUM]; // To store element pairs from the // FTR solution. Decides how // elements will be hp-refined. for (int i=0; i < MAX_ELEM_NUM; i++) { ref_ftr_pairs[i][0] = new Element(); ref_ftr_pairs[i][1] = new Element(); } while(1) { printf("============ Adaptivity step %d ============\n", adapt_iterations); printf("N_dof = %d\n", mesh->get_n_dof()); // Newton's loop on coarse mesh newton(dp, mesh, NULL, NEWTON_TOL_COARSE, NEWTON_MAXITER); // For every element perform its fast trial refinement (FTR), // calculate the norm of the difference between the FTR // solution and the coarse mesh solution, and store the // error in the ftr_errors[] array. int n_elem = mesh->get_n_active_elem(); for (int i=0; i < n_elem; i++) { printf("=== Starting FTR of Elem [%d]\n", i); // Replicate coarse mesh including solution. Mesh *mesh_ref_local = mesh->replicate(); // Perform FTR of element 'i' mesh_ref_local->reference_refinement(i, 1); printf("Elem [%d]: fine mesh created (%d DOF).\n", i, mesh_ref_local->assign_dofs()); // Newton's loop on the FTR mesh newton(dp, mesh_ref_local, NULL, NEWTON_TOL_REF, NEWTON_MAXITER); // Print FTR solution (enumerated) Linearizer *lxx = new Linearizer(mesh_ref_local); char out_filename[255]; sprintf(out_filename, "solution_ref_%d.gp", i); lxx->plot_solution(out_filename); delete lxx; // Calculate norm of the difference between the coarse mesh // and FTR solutions. // NOTE: later we want to look at the difference in some quantity // of interest rather than error in global norm. double err_est_array[MAX_ELEM_NUM]; ftr_errors[i] = calc_error_estimate(NORM, mesh, mesh_ref_local, err_est_array); //printf("Elem [%d]: absolute error (est) = %g\n", i, ftr_errors[i]); // Copy the reference element pair for element 'i' // into the ref_ftr_pairs[i][] array Iterator *I = new Iterator(mesh); Iterator *I_ref = new Iterator(mesh_ref_local); Element *e, *e_ref; while (1) { e = I->next_active_element(); e_ref = I_ref->next_active_element(); if (e->id == i) { e_ref->copy_into(ref_ftr_pairs[e->id][0]); // coarse element 'e' was split in space if (e->level != e_ref->level) { e_ref = I_ref->next_active_element(); e_ref->copy_into(ref_ftr_pairs[e->id][1]); } break; } } delete I; delete I_ref; delete mesh_ref_local; } // If exact solution available, also calculate exact error if (EXACT_SOL_PROVIDED) { // Calculate element errors wrt. exact solution double err_exact_total = calc_error_exact(NORM, mesh, exact_sol); // Calculate the norm of the exact solution // (using a fine subdivision and high-order quadrature) int subdivision = 500; // heuristic parameter int order = 20; // heuristic parameter double exact_sol_norm = calc_solution_norm(NORM, exact_sol, N_eq, A, B, subdivision, order); // Calculate an estimate of the global relative error double err_exact_rel = err_exact_total/exact_sol_norm; //printf("Relative error (exact) = %g %%\n", 100.*err_exact_rel); graph.add_values(0, mesh->get_n_dof(), 100 * err_exact_rel); } // Calculate max FTR error double max_ftr_error = 0; for (int i=0; i < mesh->get_n_active_elem(); i++) { if (ftr_errors[i] > max_ftr_error) max_ftr_error = ftr_errors[i]; } printf("Max FTR error = %g\n", max_ftr_error); // Add entry to DOF convergence graph graph.add_values(1, mesh->get_n_dof(), max_ftr_error); // Decide whether the max. FTR error is sufficiently small if(max_ftr_error < TOL_ERR_FTR) break; // debug if (adapt_iterations >= 1) break; // Returns updated coarse mesh with the last solution on it. adapt(NORM, ADAPT_TYPE, THRESHOLD, ftr_errors, mesh, ref_ftr_pairs); adapt_iterations++; } // Plot meshes, results, and errors adapt_plotting(mesh, ref_ftr_pairs, NORM, EXACT_SOL_PROVIDED, exact_sol); // Save convergence graph graph.save("conv_dof.gp"); printf("Done.\n"); return 1; }
/* Punycode decoder, RFC 3492 section 6.2. As with punycode_encode(), * read the RFC if you want to understand what this is actually doing. */ static gboolean punycode_decode (const gchar *input, gsize input_length, GString *output) { GArray *output_chars; gunichar n; guint i, bias; guint oldi, w, k, digit, t; const gchar *split; n = PUNYCODE_INITIAL_N; i = 0; bias = PUNYCODE_INITIAL_BIAS; split = input + input_length - 1; while (split > input && *split != '-') split--; if (split > input) { output_chars = g_array_sized_new (FALSE, FALSE, sizeof (gunichar), split - input); input_length -= (split - input) + 1; while (input < split) { gunichar ch = (gunichar)*input++; if (!PUNYCODE_IS_BASIC (ch)) goto fail; g_array_append_val (output_chars, ch); } input++; } else output_chars = g_array_new (FALSE, FALSE, sizeof (gunichar)); while (input_length) { oldi = i; w = 1; for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE) { if (!input_length--) goto fail; digit = decode_digit (*input++); if (digit >= PUNYCODE_BASE) goto fail; if (digit > (G_MAXUINT - i) / w) goto fail; i += digit * w; if (k <= bias) t = PUNYCODE_TMIN; else if (k >= bias + PUNYCODE_TMAX) t = PUNYCODE_TMAX; else t = k - bias; if (digit < t) break; if (w > G_MAXUINT / (PUNYCODE_BASE - t)) goto fail; w *= (PUNYCODE_BASE - t); } bias = adapt (i - oldi, output_chars->len + 1, oldi == 0); if (i / (output_chars->len + 1) > G_MAXUINT - n) goto fail; n += i / (output_chars->len + 1); i %= (output_chars->len + 1); g_array_insert_val (output_chars, i++, n); } for (i = 0; i < output_chars->len; i++) g_string_append_unichar (output, g_array_index (output_chars, gunichar, i)); g_array_free (output_chars, TRUE); return TRUE; fail: g_array_free (output_chars, TRUE); return FALSE; }
/* Punycode encoder, RFC 3492 section 6.3. The algorithm is * sufficiently bizarre that it's not really worth trying to explain * here. */ static gboolean punycode_encode (const gchar *input_utf8, gsize input_utf8_length, GString *output) { guint delta, handled_chars, num_basic_chars, bias, j, q, k, t, digit; gunichar n, m, *input; glong input_length; gboolean success = FALSE; /* Convert from UTF-8 to Unicode code points */ input = g_utf8_to_ucs4 (input_utf8, input_utf8_length, NULL, &input_length, NULL); if (!input) return FALSE; /* Copy basic chars */ for (j = num_basic_chars = 0; j < input_length; j++) { if (PUNYCODE_IS_BASIC (input[j])) { g_string_append_c (output, g_ascii_tolower (input[j])); num_basic_chars++; } } if (num_basic_chars) g_string_append_c (output, '-'); handled_chars = num_basic_chars; /* Encode non-basic chars */ delta = 0; bias = PUNYCODE_INITIAL_BIAS; n = PUNYCODE_INITIAL_N; while (handled_chars < input_length) { /* let m = the minimum {non-basic} code point >= n in the input */ for (m = G_MAXUINT, j = 0; j < input_length; j++) { if (input[j] >= n && input[j] < m) m = input[j]; } if (m - n > (G_MAXUINT - delta) / (handled_chars + 1)) goto fail; delta += (m - n) * (handled_chars + 1); n = m; for (j = 0; j < input_length; j++) { if (input[j] < n) { if (++delta == 0) goto fail; } else if (input[j] == n) { q = delta; for (k = PUNYCODE_BASE; ; k += PUNYCODE_BASE) { if (k <= bias) t = PUNYCODE_TMIN; else if (k >= bias + PUNYCODE_TMAX) t = PUNYCODE_TMAX; else t = k - bias; if (q < t) break; digit = t + (q - t) % (PUNYCODE_BASE - t); g_string_append_c (output, encode_digit (digit)); q = (q - t) / (PUNYCODE_BASE - t); } g_string_append_c (output, encode_digit (q)); bias = adapt (delta, handled_chars + 1, handled_chars == num_basic_chars); delta = 0; handled_chars++; } } delta++; n++; } success = TRUE; fail: g_free (input); return success; }
//////////////////////////////////////////////////////////////////////////////// // Simulation::init_terminals // // // // initializes terminals for a new iteration // //////////////////////////////////////////////////////////////////////////////// void Simulation::init_terminals(){ adapt_struct adapt (sim_par.get_TxMode(), sim_par.get_AdaptMode(), sim_par.get_TxPowerMax(), sim_par.get_TxPowerMin(), sim_par.get_TxPowerStepUp(),sim_par.get_TxPowerStepDown(), sim_par.get_TargetPER(),sim_par.get_LAMaxSucceedCounter(), sim_par.get_LAFailLimit(), sim_par.get_UseRxMode()); mac_struct mac(sim_par.get_RetryLimit(), sim_par.get_RTSThreshold(), sim_par.get_FragmentationThresh(), sim_par.get_QueueSize(), sim_par.get_set_BA_agg()); PHY_struct phy(sim_par.get_NoiseVariance(), sim_par.get_CCASensitivity()); traffic_struct tr_dl(sim_par.get_DataRateDL(), sim_par.get_PacketLength(), sim_par.get_ArrivalTime()); traffic_struct tr_ul(sim_par.get_DataRateUL(), sim_par.get_PacketLength(), sim_par.get_ArrivalTime()); timestamp tr_time = sim_par.get_TransientTime(); for (unsigned i = 0; i < sim_par.get_NumberAPs(); i++) { AccessPoint* ap = new AccessPoint(sim_par.get_APPosition(i), &main_sch, ch, &randgent, &log, mac, phy, tr_time); term_vector.push_back(ap); if (log(log_type::setup)) log << *ap << " created at position " << sim_par.get_APPosition(i) << '\n' << endl; } double cell_radius = sim_par.get_Radius(); // Array containing the amount of connections belonging to each AC unsigned ppArray[5] = {round(2*sim_par.get_ppAC_BK()*sim_par.get_NumberStas()), round(2*sim_par.get_ppAC_BE()*sim_par.get_NumberStas()), round(2*sim_par.get_ppAC_VI()*sim_par.get_NumberStas()), round(2*sim_par.get_ppAC_VO()*sim_par.get_NumberStas()), round(2*sim_par.get_ppLegacy()*sim_par.get_NumberStas())}; unsigned sum = 0; for(int k = 0; k < 5; k++) { sum = sum + ppArray[k]; } int diff = sum - 2*sim_par.get_NumberStas(); if(diff > 0) { for(int k = 0; k < 5; k++) { while(ppArray[k] > 0 && diff > 0){ ppArray[k]--; diff--; } } } if(diff < 0) { ppArray[0] = (-1)*diff; } vector<int> noZe_ppArray; accCat MS_AC = AC_BK; accCat AP_AC = AC_BK; int idx = 0; for (unsigned i = 0; i < sim_par.get_NumberStas(); i++) { // Vector containing elements of ppArray that are non-zero noZe_ppArray.clear(); for(int k = 0; k < 5; k++) { if(ppArray[k] != 0) noZe_ppArray.push_back(k); } // Choose one access category randomly if(noZe_ppArray.size() != 0) { idx = randgent.from_vec(noZe_ppArray); MS_AC = allACs[idx]; ppArray[idx]--; } // if just one mobile station, then distance = cell radius Position pos(cell_radius,0); // else Stas are uniformly distributed if (sim_par.get_NumberStas() > 1) { do { pos = Position (randgent.uniform(-cell_radius,cell_radius), randgent.uniform(-cell_radius,cell_radius)); } while(pos.distance() > cell_radius); } MobileStation* ms = new MobileStation(pos, &main_sch, ch, &randgent, &log, mac, phy, tr_time); term_vector.push_back(ms); double min_dist = HUGE_VAL; int min_index = -1; for (unsigned count = 0; count < sim_par.get_NumberAPs(); count++) { double dist = pos.distance(sim_par.get_APPosition(count)); if (dist < min_dist) { min_dist = dist; min_index = count; } } // Vector containing elements of ppArray that are non-zero noZe_ppArray.clear(); for(int k = 0; k < 5; k++) { if(ppArray[k] != 0) noZe_ppArray.push_back(k); } // Choose one access category randomly if(noZe_ppArray.size() != 0) { idx = randgent.from_vec(noZe_ppArray); AP_AC = allACs[idx]; ppArray[idx]--; } // Connect mobile terminal to closest AP connect_two(term_vector[min_index], AP_AC, ms, MS_AC, ch, adapt, tr_dl, tr_ul); if (log(log_type::setup)) log << *ms << " created at position " << pos << " with distance " << min_dist << " m to " << *term_vector[min_index] << "\nMobile station AC: "<< MS_AC << ". Access Point AC: " << AP_AC << "." <<endl; } if (log(log_type::setup)) log_connections(); }
Py::Object fromShape(const Py::Tuple& args) { PyObject *pcObj; if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj)) throw Py::Exception(); TopoDS_Shape shape; try { if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) { shape = static_cast<Part::TopoShapePy*>(pcObj)->getTopoShapePtr()->getShape(); } else { throw Py::TypeError("the given object is not a shape"); } if (!shape.IsNull()) { if (shape.ShapeType() == TopAbs_WIRE) { Path::Toolpath result; bool first = true; Base::Placement last; TopExp_Explorer ExpEdges (shape,TopAbs_EDGE); while (ExpEdges.More()) { const TopoDS_Edge& edge = TopoDS::Edge(ExpEdges.Current()); TopExp_Explorer ExpVerts(edge,TopAbs_VERTEX); bool vfirst = true; while (ExpVerts.More()) { const TopoDS_Vertex& vert = TopoDS::Vertex(ExpVerts.Current()); gp_Pnt pnt = BRep_Tool::Pnt(vert); Base::Placement tpl; tpl.setPosition(Base::Vector3d(pnt.X(),pnt.Y(),pnt.Z())); if (first) { // add first point as a G0 move Path::Command cmd; std::ostringstream ctxt; ctxt << "G0 X" << tpl.getPosition().x << " Y" << tpl.getPosition().y << " Z" << tpl.getPosition().z; cmd.setFromGCode(ctxt.str()); result.addCommand(cmd); first = false; vfirst = false; } else { if (vfirst) vfirst = false; else { Path::Command cmd; cmd.setFromPlacement(tpl); // write arc data if needed BRepAdaptor_Curve adapt(edge); if (adapt.GetType() == GeomAbs_Circle) { gp_Circ circ = adapt.Circle(); gp_Pnt c = circ.Location(); bool clockwise = false; gp_Dir n = circ.Axis().Direction(); if (n.Z() < 0) clockwise = true; Base::Vector3d center = Base::Vector3d(c.X(),c.Y(),c.Z()); // center coords must be relative to last point center -= last.getPosition(); cmd.setCenter(center,clockwise); } result.addCommand(cmd); } } ExpVerts.Next(); last = tpl; } ExpEdges.Next(); } return Py::asObject(new PathPy(new Path::Toolpath(result))); } else { throw Py::TypeError("the given shape must be a wire"); } } else { throw Py::TypeError("the given shape is empty"); } } catch (const Base::Exception& e) { throw Py::RuntimeError(e.what()); } return Py::None(); }
int main() { // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Create coarse mesh, set Dirichlet BC, enumerate basis functions. Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ); info("N_dof = %d.", Space::get_num_dofs(space)); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(jacobian); wf.add_vector_form(residual); // Initialize the FE problem. bool is_linear = false; DiscreteProblem *dp_coarse = new DiscreteProblem(&wf, space, is_linear); // Newton's loop on coarse mesh. // Obtain the number of degrees of freedom. int ndof = Space::get_num_dofs(space); // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec_coarse = new double[Space::get_num_dofs(space)]; solution_to_vector(space, coeff_vec_coarse); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix_coarse = create_matrix(matrix_solver); Vector* rhs_coarse = create_vector(matrix_solver); Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof_coarse = Space::get_num_dofs(space); // Assemble the Jacobian matrix and residual vector. dp_coarse->assemble(matrix_coarse, rhs_coarse); // Calculate the l2-norm of residual vector. double res_norm = 0; for(int i=0; i<ndof_coarse; i++) res_norm += rhs_coarse->get(i)*rhs_coarse->get(i); res_norm = sqrt(res_norm); // Info for user. info("---- Newton iter %d, residual norm: %.15f", it, res_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_norm < NEWTON_TOL_COARSE && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i<ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i)); // Solve the linear system. if(!solver_coarse->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. vector_to_solution(coeff_vec_coarse, space); it++; } // Cleanup. delete matrix_coarse; delete rhs_coarse; delete solver_coarse; delete dp_coarse; delete [] coeff_vec_coarse; // DOF and CPU convergence graphs. SimpleGraph graph_dof_est, graph_cpu_est; SimpleGraph graph_dof_exact, graph_cpu_exact; // Main adaptivity loop. int as = 1; while(1) { info("============ Adaptivity step %d ============", as); // Construct globally refined reference mesh and setup reference space. Space* ref_space = construct_refined_space(space); // Initialize the FE problem. bool is_linear = false; DiscreteProblem* dp = new DiscreteProblem(&wf, ref_space, is_linear); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); // Newton's loop on fine mesh. // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec = new double[Space::get_num_dofs(ref_space)]; solution_to_vector(ref_space, coeff_vec); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof = Space::get_num_dofs(ref_space); // Assemble the Jacobian matrix and residual vector. dp->assemble(matrix, rhs); // Calculate the l2-norm of residual vector. double res_norm = 0; for(int i=0; i<ndof; i++) res_norm += rhs->get(i)*rhs->get(i); res_norm = sqrt(res_norm); // Info for user. info("---- Newton iter %d, residual norm: %.15f", it, res_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_norm < NEWTON_TOL_REF && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i<ndof; i++) rhs->set(i, -rhs->get(i)); // Solve the linear system. if(!solver->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. vector_to_solution(coeff_vec, ref_space); it++; } // Cleanup. delete matrix; delete rhs; delete solver; delete dp; delete [] coeff_vec; // Starting with second adaptivity step, obtain new coarse // space solution via Newton's method. Initial condition is // the last coarse mesh solution. if (as > 1) { //Info for user. info("Solving on coarse mesh"); // Initialize the FE problem. bool is_linear = false; DiscreteProblem* dp_coarse = new DiscreteProblem(&wf, space, is_linear); // Newton's loop on coarse mesh. // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec_coarse = new double[Space::get_num_dofs(space)]; solution_to_vector(space, coeff_vec_coarse); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix_coarse = create_matrix(matrix_solver); Vector* rhs_coarse = create_vector(matrix_solver); Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof_coarse = Space::get_num_dofs(space); // Assemble the Jacobian matrix and residual vector. dp_coarse->assemble(matrix_coarse, rhs_coarse); // Calculate the l2-norm of residual vector. double res_norm = 0; for(int i=0; i<ndof_coarse; i++) res_norm += rhs_coarse->get(i)*rhs_coarse->get(i); res_norm = sqrt(res_norm); // Info for user. info("---- Newton iter %d, residual norm: %.15f", it, res_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_norm < NEWTON_TOL_COARSE && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i<ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i)); // Solve the linear system. if(!solver_coarse->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. vector_to_solution(coeff_vec_coarse, space); it++; } // Cleanup. delete matrix_coarse; delete rhs_coarse; delete solver_coarse; delete dp_coarse; delete [] coeff_vec_coarse; } // In the next step, estimate element errors based on // the difference between the fine mesh and coarse mesh solutions. double err_est_array[MAX_ELEM_NUM]; double err_est_rel = calc_err_est(NORM, space, ref_space, err_est_array) * 100; // Info for user. info("Relative error (est) = %g %%", err_est_rel); // Time measurement. cpu_time.tick(); // If exact solution available, also calculate exact error. if (EXACT_SOL_PROVIDED) { // Calculate element errors wrt. exact solution. double err_exact_rel = calc_err_exact(NORM, space, exact_sol, NEQ, A, B) * 100; // Info for user. info("Relative error (exact) = %g %%", err_exact_rel); // Add entry to DOF and CPU convergence graphs. graph_dof_exact.add_values(Space::get_num_dofs(space), err_exact_rel); graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel); } // Add entry to DOF and CPU convergence graphs. graph_dof_est.add_values(Space::get_num_dofs(space), err_est_rel); graph_cpu_est.add_values(cpu_time.accumulated(), err_est_rel); // Decide whether the relative error is sufficiently small. if(err_est_rel < TOL_ERR_REL) break; // Returns updated coarse and fine meshes, with the last // coarse and fine mesh solutions on them, respectively. // The coefficient vectors and numbers of degrees of freedom // on both meshes are also updated. adapt(NORM, ADAPT_TYPE, THRESHOLD, err_est_array, space, ref_space); as++; // Plot meshes, results, and errors. adapt_plotting(space, ref_space, NORM, EXACT_SOL_PROVIDED, exact_sol); // Cleanup. delete ref_space; } // Save convergence graphs. graph_dof_est.save("conv_dof_est.dat"); graph_cpu_est.save("conv_cpu_est.dat"); graph_dof_exact.save("conv_dof_exact.dat"); graph_cpu_exact.save("conv_cpu_exact.dat"); int success_test = 1; info("N_dof = %d.", Space::get_num_dofs(space)); if (Space::get_num_dofs(space) > 40) success_test = 0; if (success_test) { info("Success!"); return ERROR_SUCCESS; } else { info("Failure!"); return ERROR_FAILURE; } }
int main() { // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Create coarse mesh, set Dirichlet BC, enumerate basis functions. Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ); // Enumerate basis functions, info for user. int ndof = Space::get_num_dofs(space); info("ndof: %d", ndof); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(jacobian); wf.add_vector_form(residual); double elem_errors[MAX_ELEM_NUM]; // This array decides what // elements will be refined. ElemPtr2 ref_elem_pairs[MAX_ELEM_NUM]; // To store element pairs from the // FTR solution. Decides how // elements will be hp-refined. for (int i=0; i < MAX_ELEM_NUM; i++) { ref_elem_pairs[i][0] = new Element(); ref_elem_pairs[i][1] = new Element(); } // DOF and CPU convergence graphs. SimpleGraph graph_dof_exact, graph_cpu_exact; /// Adaptivity loop: int as = 1; bool done = false; do { info("---- Adaptivity step %d:", as); // Initialize the FE problem. bool is_linear = false; DiscreteProblem *dp_coarse = new DiscreteProblem(&wf, space, is_linear); // Newton's loop on coarse mesh. // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec_coarse = new double[Space::get_num_dofs(space)]; get_coeff_vector(space, coeff_vec_coarse); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix_coarse = create_matrix(matrix_solver); Vector* rhs_coarse = create_vector(matrix_solver); Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof_coarse = Space::get_num_dofs(space); // Assemble the Jacobian matrix and residual vector. dp_coarse->assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs_coarse); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_COARSE && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i<ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i)); // Solve the linear system. if(!solver_coarse->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec_coarse, space); it++; } // Cleanup. delete matrix_coarse; delete rhs_coarse; delete solver_coarse; delete [] coeff_vec_coarse; delete dp_coarse; // For every element perform its fast trial refinement (FTR), // calculate the norm of the difference between the FTR // solution and the coarse space solution, and store the // error in the elem_errors[] array. int n_elem = space->get_n_active_elem(); for (int i=0; i < n_elem; i++) { info("=== Starting FTR of Elem [%d].", i); // Replicate coarse space including solution. Space *space_ref_local = space->replicate(); // Perform FTR of element 'i' space_ref_local->reference_refinement(i, 1); info("Elem [%d]: fine space created (%d DOF).", i, space_ref_local->assign_dofs()); // Initialize the FE problem. bool is_linear = false; DiscreteProblem* dp = new DiscreteProblem(&wf, space_ref_local, is_linear); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); // Newton's loop on the FTR space. // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec = new double[Space::get_num_dofs(space_ref_local)]; get_coeff_vector(space_ref_local, coeff_vec); memset(coeff_vec, 0, Space::get_num_dofs(space_ref_local)*sizeof(double)); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof = Space::get_num_dofs(space_ref_local); // Assemble the Jacobian matrix and residual vector. dp->assemble(coeff_vec, matrix, rhs); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space_ref_local), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_REF && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i<ndof; i++) rhs->set(i, -rhs->get(i)); // Solve the linear system. if(!solver->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec, space_ref_local); it++; } // Cleanup. delete matrix; delete rhs; delete solver; delete dp; delete [] coeff_vec; // Print FTR solution (enumerated). //Linearizer *lxx = new Linearizer(space_ref_local); //char out_filename[255]; //sprintf(out_filename, "solution_ref_%d.gp", i); //lxx->plot_solution(out_filename); //delete lxx; // Calculate norm of the difference between the coarse space // and FTR solutions. // NOTE: later we want to look at the difference in some quantity // of interest rather than error in global norm. double err_est_array[MAX_ELEM_NUM]; elem_errors[i] = calc_err_est(NORM, space, space_ref_local, err_est_array) * 100; info("Elem [%d]: absolute error (est) = %g%%", i, elem_errors[i]); // Copy the reference element pair for element 'i'. // into the ref_elem_pairs[i][] array Iterator *I = new Iterator(space); Iterator *I_ref = new Iterator(space_ref_local); Element *e, *e_ref; while (1) { e = I->next_active_element(); e_ref = I_ref->next_active_element(); if (e->id == i) { e_ref->copy_into(ref_elem_pairs[e->id][0]); // coarse element 'e' was split in space. if (e->level != e_ref->level) { e_ref = I_ref->next_active_element(); e_ref->copy_into(ref_elem_pairs[e->id][1]); } break; } } delete I; delete I_ref; delete space_ref_local; } // Time measurement. cpu_time.tick(); // If exact solution available, also calculate exact error. if (EXACT_SOL_PROVIDED) { // Calculate element errors wrt. exact solution. double err_exact_rel = calc_err_exact(NORM, space, exact_sol, NEQ, A, B) * 100; // Info for user. info("Relative error (exact) = %g %%", err_exact_rel); // Add entry to DOF and CPU convergence graphs. graph_dof_exact.add_values(Space::get_num_dofs(space), err_exact_rel); graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel); } // Calculate max FTR error. double max_ftr_error = 0; for (int i=0; i < space->get_n_active_elem(); i++) { if (elem_errors[i] > max_ftr_error) max_ftr_error = elem_errors[i]; } info("Max FTR error = %g%%.", max_ftr_error); // Decide whether the max. FTR error is sufficiently small. if(max_ftr_error < TOL_ERR_FTR) break; // debug //if (as >= 1) break; // Returns updated coarse space with the last solution on it. adapt(NORM, ADAPT_TYPE, THRESHOLD, elem_errors, space, ref_elem_pairs); // Plot spaces, results, and errors. //adapt_plotting(space, ref_elem_pairs, NORM, EXACT_SOL_PROVIDED, exact_sol); as++; } while (done == false); info("Total running time: %g s", cpu_time.accumulated()); // Save convergence graphs. graph_dof_exact.save("conv_dof_exact.dat"); graph_cpu_exact.save("conv_cpu_exact.dat"); // Test variable. bool success = true; info("ndof = %d.", Space::get_num_dofs(space)); if (Space::get_num_dofs(space) > 35) success = false; if (success) { info("Success!"); return ERROR_SUCCESS; } else { info("Failure!"); return ERROR_FAILURE; } }
enum punycode_status punycode_encode( punycode_uint input_length, const punycode_uint input[], const unsigned char case_flags[], punycode_uint *output_length, char output[] ) { punycode_uint n, delta, h, b, out, max_out, bias, j, m, q, k, t; /* Initialize the state: */ n = initial_n; delta = out = 0; max_out = *output_length; bias = initial_bias; /* Handle the basic code points: */ for (j = 0; j < input_length; ++j) { if (basic(input[j])) { if (max_out - out < 2) return punycode_big_output; output[out++] = (char) (case_flags ? encode_basic(input[j], case_flags[j]) : input[j]); } /* else if (input[j] < n) return punycode_bad_input; */ /* (not needed for Punycode with unsigned code points) */ } h = b = out; /* h is the number of code points that have been handled, b is the */ /* number of basic code points, and out is the number of characters */ /* that have been output. */ if (b > 0) output[out++] = delimiter; /* Main encoding loop: */ while (h < input_length) { /* All non-basic code points < n have been */ /* handled already. Find the next larger one: */ for (m = maxint, j = 0; j < input_length; ++j) { /* if (basic(input[j])) continue; */ /* (not needed for Punycode) */ if (input[j] >= n && input[j] < m) m = input[j]; } /* Increase delta enough to advance the decoder's */ /* <n,i> state to <m,0>, but guard against overflow: */ if (m - n > (maxint - delta) / (h + 1)) return punycode_overflow; delta += (m - n) * (h + 1); n = m; for (j = 0; j < input_length; ++j) { /* Punycode does not need to check whether input[j] is basic: */ if (input[j] < n /* || basic(input[j]) */ ) { if (++delta == 0) return punycode_overflow; } if (input[j] == n) { /* Represent delta as a generalized variable-length integer: */ for (q = delta, k = base; ; k += base) { if (out >= max_out) return punycode_big_output; t = k <= bias /* + tmin */ ? tmin : /* +tmin not needed */ k >= bias + tmax ? tmax : k - bias; if (q < t) break; output[out++] = encode_digit(t + (q - t) % (base - t), 0); q = (q - t) / (base - t); } output[out++] = encode_digit(q, case_flags && case_flags[j]); bias = adapt(delta, h + 1, h == b); delta = 0; ++h; } } ++delta, ++n; } *output_length = out; return punycode_success; }
void MCMCLoop::run() { QString mDate =QDateTime::currentDateTime().toString("dddd dd MMMM yyyy"); QTime startChainTime = QTime::currentTime(); QString mTime = startChainTime.toString("hh:mm:ss.zzz"); QString log= "Start " +mDate+" ->>> " +mTime; //int timeDiff = 0; //QTime startTotalTime = QTime::currentTime(); //----------------------- Calibrating -------------------------------------- emit stepChanged(tr("Calibrating data..."), 0, 0); //QTime startCalibTime = QTime::currentTime(); mAbortedReason = this->calibrate(); if(!mAbortedReason.isEmpty()) { return; } /*QTime endCalibTime = QTime::currentTime(); int timeDiff = startCalibTime.msecsTo(endCalibTime); log += line("Calib done in " + QString::number(timeDiff) + " ms");*/ //----------------------- Chains -------------------------------------- QStringList seeds; mInitLog = QString(); for(mChainIndex = 0; mChainIndex < mChains.size(); ++mChainIndex) { log += "<hr>"; log += line("Chain : " + QString::number(mChainIndex + 1) + "/" + QString::number(mChains.size())); Chain& chain = mChains[mChainIndex]; Generator::initGenerator(chain.mSeed); log += line("Seed : " + QString::number(chain.mSeed)); seeds << QString::number(chain.mSeed); this->initVariablesForChain(); //----------------------- Initializing -------------------------------------- emit stepChanged("Chain " + QString::number(mChainIndex+1) + "/" + QString::number(mChains.size()) + " : " + tr("Initializing MCMC"), 0, 0); //QTime startInitTime = QTime::currentTime(); try { this->initMCMC(); } catch(QString error) { mAbortedReason = error; return; } /*QTime endInitTime = QTime::currentTime(); timeDiff = startInitTime.msecsTo(endInitTime); log += "=> Init done in " + QString::number(timeDiff) + " ms\n";*/ //----------------------- Burning -------------------------------------- emit stepChanged("Chain " + QString::number(mChainIndex+1) + "/" + QString::number(mChains.size()) + " : " + tr("Burning"), 0, chain.mNumBurnIter); mState = eBurning; //QTime startBurnTime = QTime::currentTime(); while(chain.mBurnIterIndex < chain.mNumBurnIter) { if(isInterruptionRequested()) { mAbortedReason = ABORTED_BY_USER; return; } try { this->update(); } catch(QString error) { mAbortedReason = error; return; } ++chain.mBurnIterIndex; ++chain.mTotalIter; emit stepProgressed(chain.mBurnIterIndex); } /*QTime endBurnTime = QTime::currentTime(); timeDiff = startBurnTime.msecsTo(endBurnTime); log += "=> Burn done in " + QString::number(timeDiff) + " ms\n";*/ //----------------------- Adapting -------------------------------------- emit stepChanged("Chain " + QString::number(mChainIndex+1) + "/" + QString::number(mChains.size()) + " : " + tr("Adapting"), 0, chain.mMaxBatchs * chain.mNumBatchIter); mState = eAdapting; //QTime startAdaptTime = QTime::currentTime(); while(chain.mBatchIndex * chain.mNumBatchIter < chain.mMaxBatchs * chain.mNumBatchIter) { if(isInterruptionRequested()) { mAbortedReason = ABORTED_BY_USER; return; } chain.mBatchIterIndex = 0; while(chain.mBatchIterIndex < chain.mNumBatchIter) { if(isInterruptionRequested()) { mAbortedReason = ABORTED_BY_USER; return; } try { this->update(); } catch(QString error) { mAbortedReason = error; return; } ++chain.mBatchIterIndex; ++chain.mTotalIter; emit stepProgressed(chain.mBatchIndex * chain.mNumBatchIter + chain.mBatchIterIndex); } ++chain.mBatchIndex; if(adapt()) { break; } } log += line("Adapt OK at batch : " + QString::number(chain.mBatchIndex) + "/" + QString::number(chain.mMaxBatchs)); /* QTime endAdaptTime = QTime::currentTime(); timeDiff = startAdaptTime.msecsTo(endAdaptTime); log += "=> Adapt done in " + QString::number(timeDiff) + " ms\n";*/ //----------------------- Running -------------------------------------- emit stepChanged("Chain " + QString::number(mChainIndex+1) + "/" + QString::number(mChains.size()) + " : " + tr("Running"), 0, chain.mNumRunIter); mState = eRunning; //QTime startRunTime = QTime::currentTime(); while(chain.mRunIterIndex < chain.mNumRunIter) { if(isInterruptionRequested()) { mAbortedReason = ABORTED_BY_USER; return; } try { this->update(); } catch(QString error) { mAbortedReason = error; return; } ++chain.mRunIterIndex; ++chain.mTotalIter; emit stepProgressed(chain.mRunIterIndex); } /*QTime endRunTime = QTime::currentTime(); timeDiff = startRunTime.msecsTo(endRunTime); log += "=> Acquire done in " + QString::number(timeDiff) + " ms\n";*/ //----------------------------------------------------------------------- /* QTime endChainTime = QTime::currentTime(); timeDiff = startChainTime.msecsTo(endChainTime); log += "=> Chain done in " + QString::number(timeDiff) + " ms\n";*/ } log += line("List of used chains seeds (to be copied for re-use in MCMC Settings) :<br>" + seeds.join(";")); /*QTime endTotalTime = QTime::currentTime(); timeDiff = startTotalTime.msecsTo(endTotalTime); log += "=> MCMC done in " + QString::number(timeDiff) + " ms\n"; QTime startFinalizeTime = QTime::currentTime();*/ //----------------------------------------------------------------------- emit stepChanged(tr("Computing posterior distributions and numerical results (HPD, credibility, ...)"), 0, 0); try { this->finalize(); } catch(QString error) { mAbortedReason = error; return; } /* QTime endFinalizeTime = QTime::currentTime(); timeDiff = startFinalizeTime.msecsTo(endFinalizeTime); log += "=> Histos and results computed in " + QString::number(timeDiff) + " ms\n"; log += "End time : " + endFinalizeTime.toString() + "\n"; */ //----------------------------------------------------------------------- mChainsLog = log; }
int main() { // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Create coarse mesh, set Dirichlet BC, enumerate basis functions. Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ); // Enumerate basis functions, info for user. int ndof = Space::get_num_dofs(space); info("ndof: %d", ndof); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(jacobian); wf.add_vector_form(residual); // Initialize the FE problem. bool is_linear = false; DiscreteProblem *dp_coarse = new DiscreteProblem(&wf, space, is_linear); if(JFNK == 0) { // Newton's loop on coarse mesh. // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec_coarse = new double[Space::get_num_dofs(space)]; get_coeff_vector(space, coeff_vec_coarse); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix_coarse = create_matrix(matrix_solver); Vector* rhs_coarse = create_vector(matrix_solver); Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof_coarse = Space::get_num_dofs(space); // Assemble the Jacobian matrix and residual vector. dp_coarse->assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs_coarse); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_COARSE && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i = 0; i < ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i)); // Solve the linear system. if(!solver_coarse->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec_coarse, space); it++; } // Cleanup. delete matrix_coarse; delete rhs_coarse; delete solver_coarse; delete [] coeff_vec_coarse; } else jfnk_cg(dp_coarse, space, MATRIX_SOLVER_TOL, MATRIX_SOLVER_MAXITER, JFNK_EPSILON, NEWTON_TOL_COARSE, NEWTON_MAX_ITER, matrix_solver); // Cleanup. delete dp_coarse; // DOF and CPU convergence graphs. SimpleGraph graph_dof_est, graph_cpu_est; SimpleGraph graph_dof_exact, graph_cpu_exact; // Adaptivity loop: int as = 1; double ftr_errors[MAX_ELEM_NUM]; // This array decides what // elements will be refined. bool done = false; do { info("---- Adaptivity step %d:", as); // Construct globally refined reference mesh and setup reference space. Space* ref_space = construct_refined_space(space); // Initialize the FE problem. bool is_linear = false; DiscreteProblem* dp = new DiscreteProblem(&wf, ref_space, is_linear); if(JFNK == 0) { // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); // Newton's loop on the fine mesh. info("Solving on fine mesh:"); // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec = new double[Space::get_num_dofs(ref_space)]; get_coeff_vector(ref_space, coeff_vec); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof = Space::get_num_dofs(ref_space); // Assemble the Jacobian matrix and residual vector. dp->assemble(coeff_vec, matrix, rhs); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(ref_space), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_REF && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i = 0; i < ndof; i++) rhs->set(i, -rhs->get(i)); // Solve the linear system. if(!solver->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec, ref_space); it++; } // Cleanup. delete matrix; delete rhs; delete solver; delete [] coeff_vec; } else jfnk_cg(dp, ref_space, MATRIX_SOLVER_TOL, MATRIX_SOLVER_MAXITER, JFNK_EPSILON, NEWTON_TOL_COARSE, NEWTON_MAX_ITER, matrix_solver); // Cleanup. delete dp; // Starting with second adaptivity step, obtain new coarse // mesh solution via projecting the fine mesh solution. if(as > 1) { info("Projecting the fine mesh solution onto the coarse mesh."); // Project the fine mesh solution (defined on space_ref) onto the coarse mesh (defined on space). OGProjection::project_global(space, ref_space, matrix_solver); } double max_qoi_err_est = 0; for (int i=0; i < space->get_n_active_elem(); i++) { if (GOAL_ORIENTED == 1) { // Use quantity of interest. double qoi_est = quantity_of_interest(space, X_QOI); double qoi_ref_est = quantity_of_interest(ref_space, X_QOI); ftr_errors[i] = fabs(qoi_ref_est - qoi_est); } else { // Use global norm double err_est_array[MAX_ELEM_NUM]; ftr_errors[i] = calc_err_est(NORM, space, ref_space, err_est_array); } // Info for user. info("Elem [%d]: absolute error (est) = %g%%", i, ftr_errors[i]); // Time measurement. cpu_time.tick(); // Calculating maximum of QOI FTR error for plotting purposes if (GOAL_ORIENTED == 1) { if (ftr_errors[i] > max_qoi_err_est) max_qoi_err_est = ftr_errors[i]; } else { double qoi_est = quantity_of_interest(space, X_QOI); double qoi_ref_est = quantity_of_interest(ref_space, X_QOI); double err_est = fabs(qoi_ref_est - qoi_est); if (err_est > max_qoi_err_est) max_qoi_err_est = err_est; } } // Add entries to convergence graphs. if (EXACT_SOL_PROVIDED) { double qoi_est = quantity_of_interest(space, X_QOI); double u[MAX_EQN_NUM], dudx[MAX_EQN_NUM]; exact_sol(X_QOI, u, dudx); double err_qoi_exact = fabs(u[0] - qoi_est); // Info for user. info("Relative error (exact) = %g %%", err_qoi_exact); // Add entry to DOF and CPU convergence graphs. graph_dof_exact.add_values(Space::get_num_dofs(space), err_qoi_exact); graph_cpu_exact.add_values(cpu_time.accumulated(), err_qoi_exact); } // Add entry to DOF and CPU convergence graphs. graph_dof_est.add_values(Space::get_num_dofs(space), max_qoi_err_est); graph_cpu_est.add_values(cpu_time.accumulated(), max_qoi_err_est); // Decide whether the max. FTR error in the quantity of interest // is sufficiently small. if(max_qoi_err_est < TOL_ERR_QOI) break; // Returns updated coarse and fine meshes, with the last // coarse and fine mesh solutions on them, respectively. // The coefficient vectors and numbers of degrees of freedom // on both meshes are also updated. adapt(NORM, ADAPT_TYPE, THRESHOLD, ftr_errors, space, ref_space); as++; // Plot meshes, results, and errors. adapt_plotting(space, ref_space, NORM, EXACT_SOL_PROVIDED, exact_sol); // Cleanup. delete ref_space; } while (done == false); info("Total running time: %g s", cpu_time.accumulated()); // Save convergence graphs. graph_dof_est.save("conv_dof_est.dat"); graph_cpu_est.save("conv_cpu_est.dat"); graph_dof_exact.save("conv_dof_exact.dat"); graph_cpu_exact.save("conv_cpu_exact.dat"); // Test variable. bool success = true; info("ndof = %d.", Space::get_num_dofs(space)); if (Space::get_num_dofs(space) > 150) success = false; if (success) { info("Success!"); return ERROR_SUCCESS; } else { info("Failure!"); return ERROR_FAILURE; } }
bool SelfLearningMeasurementModel::adapt(shared_ptr<VersionedImage> image, const vector<shared_ptr<Sample>>& samples, const Sample& target) { return adapt(image, samples); }
QFont Kleo::KConfigBasedKeyFilter::font( const QFont & f ) const { if ( mUseFullFont ) return resizedFont( mFont, f.pointSize(), mStrikeOut ); else return adapt( f, mItalic, mBold, mStrikeOut ); }
int main() { // Create coarse mesh, set Dirichlet BC, enumerate // basis functions Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq); mesh->set_bc_left_dirichlet(0, Val_dir_left); mesh->set_bc_right_dirichlet(0, Val_dir_right); mesh->assign_dofs(); // Create discrete problem on coarse mesh DiscreteProblem *dp = new DiscreteProblem(); dp->add_matrix_form(0, 0, jacobian); dp->add_vector_form(0, residual); // Convergence graph wrt. the number of degrees of freedom // (goal-oriented adaptivity) GnuplotGraph graph_ftr; graph_ftr.set_log_y(); graph_ftr.set_captions("Convergence History", "Degrees of Freedom", "QOI error"); graph_ftr.add_row("QOI error - FTR (exact)", "k", "-", "o"); graph_ftr.add_row("QOI error - FTR (est)", "k", "--"); // Main adaptivity loop int adapt_iterations = 1; double ftr_errors[MAX_ELEM_NUM]; // This array decides what // elements will be refined. ElemPtr2 ref_ftr_pairs[MAX_ELEM_NUM]; // To store element pairs from the // FTR solution. Decides how // elements will be hp-refined. for (int i=0; i < MAX_ELEM_NUM; i++) { ref_ftr_pairs[i][0] = new Element(); ref_ftr_pairs[i][1] = new Element(); } while(1) { printf("============ Adaptivity step %d ============\n", adapt_iterations); printf("N_dof = %d\n", mesh->get_n_dof()); // Newton's loop on coarse mesh int success; if(JFNK == 0) { newton(dp, mesh, NULL, NEWTON_TOL_COARSE, NEWTON_MAXITER); } else { jfnk_cg(dp, mesh, MATRIX_SOLVER_TOL, MATRIX_SOLVER_MAXITER, JFNK_EPSILON, NEWTON_TOL_COARSE, NEWTON_MAXITER); } // For every element perform its fast trial refinement (FTR), // calculate the norm of the difference between the FTR // solution and the coarse mesh solution, and store the // error in the ftr_errors[] array. int n_elem = mesh->get_n_active_elem(); double max_qoi_err_est = 0; for (int i=0; i < n_elem; i++) { printf("=== Starting FTR of Elem [%d]\n", i); // Replicate coarse mesh including solution. Mesh *mesh_ref_local = mesh->replicate(); // Perform FTR of element 'i' mesh_ref_local->reference_refinement(i, 1); printf("Elem [%d]: fine mesh created (%d DOF).\n", i, mesh_ref_local->assign_dofs()); // Newton's loop on the FTR mesh if(JFNK == 0) { newton(dp, mesh_ref_local, NULL, NEWTON_TOL_COARSE, NEWTON_MAXITER); } else { jfnk_cg(dp, mesh_ref_local, MATRIX_SOLVER_TOL, MATRIX_SOLVER_MAXITER, JFNK_EPSILON, NEWTON_TOL_REF, NEWTON_MAXITER); } // Print FTR solution (enumerated) Linearizer *lxx = new Linearizer(mesh_ref_local); char out_filename[255]; sprintf(out_filename, "solution_ref_%d.gp", i); lxx->plot_solution(out_filename); delete lxx; // Calculate FTR errors for refinement purposes if (GOAL_ORIENTED == 1) { // Use quantity of interest. double qoi_est = quantity_of_interest(mesh, X_QOI); double qoi_ref_est = quantity_of_interest(mesh_ref_local, X_QOI); ftr_errors[i] = fabs(qoi_ref_est - qoi_est); } else { // Use global norm double err_est_array[MAX_ELEM_NUM]; ftr_errors[i] = calc_error_estimate(NORM, mesh, mesh_ref_local, err_est_array); } // Calculating maximum of QOI FTR error for plotting purposes if (GOAL_ORIENTED == 1) { if (ftr_errors[i] > max_qoi_err_est) max_qoi_err_est = ftr_errors[i]; } else { double qoi_est = quantity_of_interest(mesh, X_QOI); double qoi_ref_est = quantity_of_interest(mesh_ref_local, X_QOI); double err_est = fabs(qoi_ref_est - qoi_est); if (err_est > max_qoi_err_est) max_qoi_err_est = err_est; } // Copy the reference element pair for element 'i' // into the ref_ftr_pairs[i][] array Iterator *I = new Iterator(mesh); Iterator *I_ref = new Iterator(mesh_ref_local); Element *e, *e_ref; while (1) { e = I->next_active_element(); e_ref = I_ref->next_active_element(); if (e->id == i) { e_ref->copy_into(ref_ftr_pairs[e->id][0]); // coarse element 'e' was split in space if (e->level != e_ref->level) { e_ref = I_ref->next_active_element(); e_ref->copy_into(ref_ftr_pairs[e->id][1]); } break; } } delete I; delete I_ref; delete mesh_ref_local; } // Add entries to convergence graphs if (EXACT_SOL_PROVIDED) { double qoi_est = quantity_of_interest(mesh, X_QOI); double u[MAX_EQN_NUM], dudx[MAX_EQN_NUM]; exact_sol(X_QOI, u, dudx); double err_qoi_exact = fabs(u[0] - qoi_est); // plotting error in quantity of interest wrt. exact value graph_ftr.add_values(0, mesh->get_n_dof(), err_qoi_exact); } graph_ftr.add_values(1, mesh->get_n_dof(), max_qoi_err_est); // Decide whether the max. FTR error in the quantity of interest // is sufficiently small if(max_qoi_err_est < TOL_ERR_QOI) break; // debug if (adapt_iterations == 3) break; // Returns updated coarse mesh with the last solution on it. adapt(NORM, ADAPT_TYPE, THRESHOLD, ftr_errors, mesh, ref_ftr_pairs); adapt_iterations++; } // Plot meshes, results, and errors adapt_plotting(mesh, ref_ftr_pairs, NORM, EXACT_SOL_PROVIDED, exact_sol); // Save convergence graph graph_ftr.save("conv_dof.gp"); printf("Done.\n"); return 1; }
enum punycode_status punycode_decode( punycode_uint input_length, const char input[], punycode_uint *output_length, punycode_uint output[], unsigned char case_flags[] ) { punycode_uint n, out, i, max_out, bias, b, j, in, oldi, w, k, digit, t; /* Initialize the state: */ n = initial_n; out = i = 0; max_out = *output_length; bias = initial_bias; /* Handle the basic code points: Let b be the number of input code */ /* points before the last delimiter, or 0 if there is none, then */ /* copy the first b code points to the output. */ for (b = j = 0; j < input_length; ++j) if (delim(input[j])) b = j; if (b > max_out) return punycode_big_output; for (j = 0; j < b; ++j) { if (case_flags) case_flags[out] = flagged(input[j]); if (!basic(input[j])) return punycode_bad_input; output[out++] = input[j]; } /* Main decoding loop: Start just after the last delimiter if any */ /* basic code points were copied; start at the beginning otherwise. */ for (in = b > 0 ? b + 1 : 0; in < input_length; ++out) { /* in is the index of the next character to be consumed, and */ /* out is the number of code points in the output array. */ /* Decode a generalized variable-length integer into delta, */ /* which gets added to i. The overflow checking is easier */ /* if we increase i as we go, then subtract off its starting */ /* value at the end to obtain delta. */ for (oldi = i, w = 1, k = base; ; k += base) { if (in >= input_length) return punycode_bad_input; digit = decode_digit(input[in++]); if (digit >= base) return punycode_bad_input; if (digit > (maxint - i) / w) return punycode_overflow; i += digit * w; t = k <= bias /* + tmin */ ? tmin : /* +tmin not needed */ k >= bias + tmax ? tmax : k - bias; if (digit < t) break; if (w > maxint / (base - t)) return punycode_overflow; w *= (base - t); } bias = adapt(i - oldi, out + 1, oldi == 0); /* i was supposed to wrap around from out+1 to 0, */ /* incrementing n each time, so we'll fix that now: */ if (i / (out + 1) > maxint - n) return punycode_overflow; n += i / (out + 1); i %= (out + 1); /* Insert n at position i of the output: */ /* not needed for Punycode: */ /* if (decode_digit(n) <= base) return punycode_invalid_input; */ if (out >= max_out) return punycode_big_output; if (case_flags) { memmove(case_flags + i + 1, case_flags + i, out - i); /* Case of last character determines uppercase flag: */ case_flags[i] = flagged(input[in - 1]); } memmove(output + i + 1, output + i, (out - i) * sizeof *output); output[i++] = n; } *output_length = out; return punycode_success; }
void readint(int &n) { adapt(); n = 0; while (isdigit(*now)) n = n * 10 + *now++ - '0'; }
int main() { // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Create coarse mesh, set Dirichlet BC, enumerate basis functions. Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ); // Enumerate basis functions, info for user. int ndof = Space::get_num_dofs(space); info("ndof: %d", ndof); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(jacobian); wf.add_vector_form(residual); // Initialize the FE problem. bool is_linear = false; DiscreteProblem *dp_coarse = new DiscreteProblem(&wf, space, is_linear); // Newton's loop on coarse mesh. // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec_coarse = new double[Space::get_num_dofs(space)]; get_coeff_vector(space, coeff_vec_coarse); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix_coarse = create_matrix(matrix_solver); Vector* rhs_coarse = create_vector(matrix_solver); Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof_coarse = Space::get_num_dofs(space); // Assemble the Jacobian matrix and residual vector. dp_coarse->assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs_coarse); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_COARSE && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i < ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i)); // Solve the linear system. if(!solver_coarse->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec_coarse, space); it++; } // Cleanup. delete matrix_coarse; delete rhs_coarse; delete solver_coarse; delete [] coeff_vec_coarse; delete dp_coarse; // DOF and CPU convergence graphs. SimpleGraph graph_dof_est, graph_cpu_est; SimpleGraph graph_dof_exact, graph_cpu_exact; // Adaptivity loop: int as = 1; bool done = false; do { info("---- Adaptivity step %d:", as); // Construct globally refined reference mesh and setup reference space. Space* ref_space = construct_refined_space(space); // Initialize the FE problem. bool is_linear = false; DiscreteProblem* dp = new DiscreteProblem(&wf, ref_space, is_linear); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); // Newton's loop on the fine mesh. info("Solving on fine mesh:"); // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec = new double[Space::get_num_dofs(ref_space)]; get_coeff_vector(ref_space, coeff_vec); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof = Space::get_num_dofs(ref_space); // Assemble the Jacobian matrix and residual vector. dp->assemble(coeff_vec, matrix, rhs); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(ref_space), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_REF && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i = 0; i < ndof; i++) rhs->set(i, -rhs->get(i)); // Solve the linear system. if(!solver->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec, ref_space); it++; } // Starting with second adaptivity step, obtain new coarse // mesh solution via projecting the fine mesh solution. if(as > 1) { info("Projecting the fine mesh solution onto the coarse mesh."); // Project the fine mesh solution (defined on space_ref) onto the coarse mesh (defined on space). OGProjection::project_global(space, ref_space, matrix_solver); } // Calculate element errors and total error estimate. info("Calculating error estimate."); double err_est_array[MAX_ELEM_NUM]; double err_est_rel = calc_err_est(NORM, space, ref_space, err_est_array) * 100; // Report results. info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%", Space::get_num_dofs(space), Space::get_num_dofs(ref_space), err_est_rel); // Time measurement. cpu_time.tick(); // If exact solution available, also calculate exact error. if (EXACT_SOL_PROVIDED) { // Calculate element errors wrt. exact solution. double err_exact_rel = calc_err_exact(NORM, space, exact_sol, NEQ, A, B) * 100; // Info for user. info("Relative error (exact) = %g %%", err_exact_rel); // Add entry to DOF and CPU convergence graphs. graph_dof_exact.add_values(Space::get_num_dofs(space), err_exact_rel); graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel); } // Add entry to DOF and CPU convergence graphs. graph_dof_est.add_values(Space::get_num_dofs(space), err_est_rel); graph_cpu_est.add_values(cpu_time.accumulated(), err_est_rel); // If err_est_rel too large, adapt the mesh. if (err_est_rel < NEWTON_TOL_REF) done = true; else { info("Adapting the coarse mesh."); adapt(NORM, ADAPT_TYPE, THRESHOLD, err_est_array, space, ref_space); } as++; // Plot meshes, results, and errors. adapt_plotting(space, ref_space, NORM, EXACT_SOL_PROVIDED, exact_sol); // Cleanup. delete solver; delete matrix; delete rhs; delete ref_space; delete dp; delete [] coeff_vec; } while (done == false); info("Total running time: %g s", cpu_time.accumulated()); // Save convergence graphs. graph_dof_est.save("conv_dof_est.dat"); graph_cpu_est.save("conv_cpu_est.dat"); graph_dof_exact.save("conv_dof_exact.dat"); graph_cpu_exact.save("conv_cpu_exact.dat"); return 0; }
void readll(long long int &n) { adapt(); n = 0; while (isdigit(*now)) n = n * 10 + *now++ - '0'; }