int fdRecv(int socket, const unsigned int timeoutMS) { std::chrono::high_resolution_clock::time_point deadline = std::chrono::high_resolution_clock::now() + std::chrono::milliseconds(timeoutMS); // Space for the file descriptor union { struct cmsghdr cmh; char control[CMSG_SPACE(sizeof(int))]; } controlUnion; // Describe the data that we want to recive controlUnion.cmh.cmsg_len = CMSG_LEN(sizeof(int)); controlUnion.cmh.cmsg_level = SOL_SOCKET; controlUnion.cmh.cmsg_type = SCM_RIGHTS; // Setup the input buffer // Ensure at least 1 byte is transmited via the socket char buf; struct iovec iov; iov.iov_base = &buf; iov.iov_len = sizeof(char); // Set the ancillary data buffer // The socket has to be connected, so we don't need to specify the name struct msghdr msgh; ::memset(&msgh, 0, sizeof(msgh)); msgh.msg_iov = &iov; msgh.msg_iovlen = 1; msgh.msg_control = controlUnion.control; msgh.msg_controllen = sizeof(controlUnion.control); // Receive for(;;) { ssize_t ret = ::recvmsg(socket, &msgh, MSG_WAITALL); if (ret < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { // Neglected errors, retry } else { THROW_EXCEPTION(UtilsException, "Error during recvmsg()", errno); } } else if (ret == 0) { THROW_EXCEPTION(UtilsException, "Peer disconnected"); } else { // We receive only 1 byte of data. No need to repeat break; } waitForEvent(socket, POLLIN, deadline); } struct cmsghdr *cmhp; cmhp = CMSG_FIRSTHDR(&msgh); if (cmhp == NULL || cmhp->cmsg_len != CMSG_LEN(sizeof(int))) { THROW_EXCEPTION(UtilsException, "Bad cmsg length"); } else if (cmhp->cmsg_level != SOL_SOCKET) { THROW_EXCEPTION(UtilsException, "cmsg_level != SOL_SOCKET"); } else if (cmhp->cmsg_type != SCM_RIGHTS) { THROW_EXCEPTION(UtilsException, "cmsg_type != SCM_RIGHTS"); } return *(reinterpret_cast<int*>(CMSG_DATA(cmhp))); }
bool MinC_1NrmRestorationPhase::PerformRestoration() { DBG_START_METH("MinC_1NrmRestorationPhase::PerformRestoration", dbg_verbosity); // Increase counter for restoration phase calls count_restorations_++; Jnlst().Printf(J_DETAILED, J_MAIN, "Starting Restoration Phase for the %d. time\n", count_restorations_); DBG_ASSERT(IpCq().curr_constraint_violation()>0.); // ToDo set those up during initialize? // Create the restoration phase NLP etc objects SmartPtr<IpoptData> resto_ip_data = new IpoptData(NULL, IpData().cpu_time_start()); SmartPtr<IpoptNLP> resto_ip_nlp = new RestoIpoptNLP(IpNLP(), IpData(), IpCq()); SmartPtr<IpoptCalculatedQuantities> resto_ip_cq = new IpoptCalculatedQuantities(resto_ip_nlp, resto_ip_data); // Determine if this is a square problem bool square_problem = IpCq().IsSquareProblem(); // Decide if we want to use the original option or want to make // some changes SmartPtr<OptionsList> actual_resto_options = resto_options_; if (square_problem) { actual_resto_options = new OptionsList(*resto_options_); // If this is a square problem, the want the restoration phase // never to be left until the problem is converged actual_resto_options->SetNumericValueIfUnset("required_infeasibility_reduction", 0.); } else if (expect_infeasible_problem_) { actual_resto_options = new OptionsList(*resto_options_); actual_resto_options->SetStringValueIfUnset("resto.expect_infeasible_problem", "no"); if (count_restorations_==1 && IpCq().curr_constraint_violation()>1e-3) { // Ask for significant reduction of infeasibility, in the hope // that we do not return from the restoration phase is the // problem is infeasible actual_resto_options->SetNumericValueIfUnset("required_infeasibility_reduction", 1e-3); } } // Initialize the restoration phase algorithm resto_alg_->Initialize(Jnlst(), *resto_ip_nlp, *resto_ip_data, *resto_ip_cq, *actual_resto_options, "resto."); // Set iteration counter and info field for the restoration phase resto_ip_data->Set_iter_count(IpData().iter_count()+1); resto_ip_data->Set_info_regu_x(IpData().info_regu_x()); resto_ip_data->Set_info_alpha_primal(IpData().info_alpha_primal()); resto_ip_data->Set_info_alpha_primal_char(IpData().info_alpha_primal_char()); resto_ip_data->Set_info_alpha_dual(IpData().info_alpha_dual()); resto_ip_data->Set_info_ls_count(IpData().info_ls_count()); resto_ip_data->Set_info_iters_since_header(IpData().info_iters_since_header()); resto_ip_data->Set_info_last_output(IpData().info_last_output()); // Call the optimization algorithm to solve the restoration phase // problem SolverReturn resto_status = resto_alg_->Optimize(true); int retval=-1; if (resto_status != SUCCESS) { SmartPtr<const IteratesVector> resto_curr = resto_ip_data->curr(); if (IsValid(resto_curr)) { // In case of a failure, we still copy the values of primal and // dual variables into the data fields of the regular NLP, so // that they will be returned to the user SmartPtr<IteratesVector> trial = IpData().trial()->MakeNewContainer(); SmartPtr<const Vector> resto_curr_x = resto_curr->x(); SmartPtr<const CompoundVector> cx = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_x)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_x))); SmartPtr<const Vector> resto_curr_s = resto_curr->s(); SmartPtr<const CompoundVector> cs = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_s)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_s))); SmartPtr<const Vector> resto_curr_y_c = resto_curr->y_c(); SmartPtr<const CompoundVector> cy_c = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_y_c)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_y_c))); SmartPtr<const Vector> resto_curr_y_d = resto_curr->y_d(); SmartPtr<const CompoundVector> cy_d = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_y_d)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_y_d))); SmartPtr<const Vector> resto_curr_z_L = resto_curr->z_L(); SmartPtr<const CompoundVector> cz_L = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_z_L)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_z_L))); SmartPtr<const Vector> resto_curr_z_U = resto_curr->z_U(); SmartPtr<const CompoundVector> cz_U = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_z_U)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_z_U))); SmartPtr<const Vector> resto_curr_v_L = resto_curr->v_L(); SmartPtr<const CompoundVector> cv_L = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_v_L)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_v_L))); SmartPtr<const Vector> resto_curr_v_U = resto_curr->v_U(); SmartPtr<const CompoundVector> cv_U = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_v_U)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_v_U))); trial->Set_primal(*cx->GetComp(0), *cs->GetComp(0)); trial->Set_eq_mult(*cy_c->GetComp(0), *cy_d->GetComp(0)); trial->Set_bound_mult(*cz_L->GetComp(0), *cz_U->GetComp(0), *cv_L->GetComp(0), *cv_U->GetComp(0)); IpData().set_trial(trial); IpData().AcceptTrialPoint(); } } if (resto_status == SUCCESS) { if (Jnlst().ProduceOutput(J_DETAILED, J_LINE_SEARCH)) { Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "\nRESTORATION PHASE RESULTS\n"); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "\n\nOptimal solution found! \n"); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Optimal Objective Value = %.16E\n", resto_ip_cq->curr_f()); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Number of Iterations = %d\n", resto_ip_data->iter_count()); } if (Jnlst().ProduceOutput(J_VECTOR, J_LINE_SEARCH)) { resto_ip_data->curr()->Print(Jnlst(), J_VECTOR, J_LINE_SEARCH, "curr"); } retval = 0; } else if (resto_status == STOP_AT_TINY_STEP || resto_status == STOP_AT_ACCEPTABLE_POINT) { Number orig_primal_inf = IpCq().curr_primal_infeasibility(NORM_MAX); // ToDo make the factor in following line an option if (orig_primal_inf <= resto_failure_feasibility_threshold_) { Jnlst().Printf(J_WARNING, J_LINE_SEARCH, "Restoration phase converged to a point with small primal infeasibility.\n"); THROW_EXCEPTION(RESTORATION_CONVERGED_TO_FEASIBLE_POINT, "Restoration phase converged to a point with small primal infeasibility"); } else { THROW_EXCEPTION(LOCALLY_INFEASIBLE, "Restoration phase converged to a point of local infeasibility"); } } else if (resto_status == MAXITER_EXCEEDED) { THROW_EXCEPTION(RESTORATION_MAXITER_EXCEEDED, "Maximal number of iterations exceeded in restoration phase."); } else if (resto_status == CPUTIME_EXCEEDED) { THROW_EXCEPTION(RESTORATION_CPUTIME_EXCEEDED, "Maximal CPU time exceeded in restoration phase."); } else if (resto_status == LOCAL_INFEASIBILITY) { // converged to locally infeasible point - pass this on to the outer algorithm... THROW_EXCEPTION(LOCALLY_INFEASIBLE, "Restoration phase converged to a point of local infeasibility"); } else if (resto_status == RESTORATION_FAILURE) { Jnlst().Printf(J_WARNING, J_LINE_SEARCH, "Restoration phase in the restoration phase failed.\n"); THROW_EXCEPTION(RESTORATION_FAILED, "Restoration phase in the restoration phase failed."); } else if (resto_status == USER_REQUESTED_STOP) { // Use requested stop during restoration phase - rethrow exception THROW_EXCEPTION(RESTORATION_USER_STOP, "User requested stop during restoration phase"); } else { Jnlst().Printf(J_ERROR, J_MAIN, "Sorry, things failed ?!?!\n"); retval = 1; } if (retval == 0) { // Copy the results into the trial fields;. They will be // accepted later in the full algorithm SmartPtr<const Vector> resto_curr_x = resto_ip_data->curr()->x(); SmartPtr<const CompoundVector> cx = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_x)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_x))); SmartPtr<const Vector> resto_curr_s = resto_ip_data->curr()->s(); SmartPtr<const CompoundVector> cs = static_cast<const CompoundVector*>(GetRawPtr(resto_curr_s)); DBG_ASSERT(dynamic_cast<const CompoundVector*>(GetRawPtr(resto_curr_s))); SmartPtr<IteratesVector> trial = IpData().trial()->MakeNewContainer(); trial->Set_primal(*cx->GetComp(0), *cs->GetComp(0)); IpData().set_trial(trial); // If this is a square problem, we are done because a // sufficiently feasible point has been found if (square_problem) { Number constr_viol = IpCq().unscaled_curr_nlp_constraint_violation(NORM_MAX); if (constr_viol <= constr_viol_tol_) { Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Recursive restoration phase algorithm termined successfully for square problem.\n"); IpData().AcceptTrialPoint(); THROW_EXCEPTION(FEASIBILITY_PROBLEM_SOLVED, "Restoration phase converged to sufficiently feasible point of original square problem."); } } // Update the bound multiplers, pretending that the entire // progress in x and s in the restoration phase has been one // [rimal-dual Newton step (and therefore the result of solving // an augmented system) SmartPtr<IteratesVector> delta = IpData().curr()->MakeNewIteratesVector(true); delta->Set(0.0); ComputeBoundMultiplierStep(*delta->z_L_NonConst(), *IpData().curr()->z_L(), *IpCq().curr_slack_x_L(), *IpCq().trial_slack_x_L()); ComputeBoundMultiplierStep(*delta->z_U_NonConst(), *IpData().curr()->z_U(), *IpCq().curr_slack_x_U(), *IpCq().trial_slack_x_U()); ComputeBoundMultiplierStep(*delta->v_L_NonConst(), *IpData().curr()->v_L(), *IpCq().curr_slack_s_L(), *IpCq().trial_slack_s_L()); ComputeBoundMultiplierStep(*delta->v_U_NonConst(), *IpData().curr()->v_U(), *IpCq().curr_slack_s_U(), *IpCq().trial_slack_s_U()); DBG_PRINT_VECTOR(1, "delta_z_L", *delta->z_L()); DBG_PRINT_VECTOR(1, "delta_z_U", *delta->z_U()); DBG_PRINT_VECTOR(1, "delta_v_L", *delta->v_L()); DBG_PRINT_VECTOR(1, "delta_v_U", *delta->v_U()); Number alpha_dual = IpCq().dual_frac_to_the_bound(IpData().curr_tau(), *delta->z_L_NonConst(), *delta->z_U_NonConst(), *delta->v_L_NonConst(), *delta->v_U_NonConst()); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Step size for bound multipliers: %8.2e\n", alpha_dual); IpData().SetTrialBoundMultipliersFromStep(alpha_dual, *delta->z_L(), *delta->z_U(), *delta->v_L(), *delta->v_U() ); // ToDo: Check what to do here: Number bound_mult_max = Max(IpData().trial()->z_L()->Amax(), IpData().trial()->z_U()->Amax(), IpData().trial()->v_L()->Amax(), IpData().trial()->v_U()->Amax()); if (bound_mult_max > bound_mult_reset_threshold_) { trial = IpData().trial()->MakeNewContainer(); Jnlst().Printf(J_DETAILED, J_LINE_SEARCH, "Bound multipliers after restoration phase too large (max=%8.2e). Set all to 1.\n", bound_mult_max); trial->create_new_z_L(); trial->create_new_z_U(); trial->create_new_v_L(); trial->create_new_v_U(); trial->z_L_NonConst()->Set(1.0); trial->z_U_NonConst()->Set(1.0); trial->v_L_NonConst()->Set(1.0); trial->v_U_NonConst()->Set(1.0); IpData().set_trial(trial); } DefaultIterateInitializer::least_square_mults( Jnlst(), IpNLP(), IpData(), IpCq(), eq_mult_calculator_, constr_mult_reset_threshold_); DBG_PRINT_VECTOR(2, "y_c", *IpData().curr()->y_c()); DBG_PRINT_VECTOR(2, "y_d", *IpData().curr()->y_d()); IpData().Set_iter_count(resto_ip_data->iter_count()-1); // Skip the next line, because it would just replicate the first // on during the restoration phase. IpData().Set_info_skip_output(true); IpData().Set_info_iters_since_header(resto_ip_data->info_iters_since_header()); IpData().Set_info_last_output(resto_ip_data->info_last_output()); } return (retval == 0); }
/* * populate the discreteIntervals member with discrete frame sizes * for a given frame size struct * (0: struct frame_size_discrete, 1: struct frame_size_continuous (min res), * 2: struct frame_size_continuous(max res), ) */ JNIEXPORT void JNICALL Java_au_edu_jcu_v4l4j_FrameInterval_doGetDiscrete( JNIEnv *e, jobject t, jint type, jlong o) { int i = -1; jclass this_class, discrete_intv_class, vector_class; jfieldID field; jmethodID add_method, ctor; jobject disc_attr, discrete; struct frame_intv_discrete *d; dprint(LOG_CALLS, "[CALL] Entering %s\n",__PRETTY_FUNCTION__); //get our pointer to struct frame_intv_discrete if((d=get_discrete(o, type)) == NULL) { THROW_EXCEPTION(e, JNI_EXCP, "Error looking up frame intervals"); return; } /* Get handles on Java stuff */ this_class = (*e)->GetObjectClass(e, t); if(this_class == NULL){ info("[V4L4J] Error looking up the FrameInterval class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up FrameInterval class"); return; } field = (*e)->GetFieldID(e, this_class, "discreteValues", "Ljava/util/List;"); if(field == NULL){ info("[V4L4J] Error looking up the discreteValues fieldID\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up the discreteValues fieldID"); return; } disc_attr = (*e)->GetObjectField(e, t, field); if(disc_attr == NULL){ info("[V4L4J] Error looking up the discreteValues member\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up the discreteValues member"); return; } vector_class = (*e)->FindClass(e, "java/util/Vector"); if(vector_class == NULL){ info("[V4L4J] Error looking up the Vector class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up Vector class"); return; } add_method = (*e)->GetMethodID(e, vector_class, "addElement", "(Ljava/lang/Object;)V"); if(add_method == NULL){ info("[V4L4J] Error looking up the add method of Vector class\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up the add method of Vector class"); return; } discrete_intv_class = (*e)->FindClass(e, "au/edu/jcu/v4l4j/FrameInterval$DiscreteInterval"); if(discrete_intv_class == NULL){ info("[V4L4J] Error looking up the DiscreteInterval class\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up DiscreteInterval class"); return; } ctor = (*e)->GetMethodID(e, discrete_intv_class, "<init>", "(II)V"); if(ctor == NULL){ info("[V4L4J] Error looking up the ctor of DiscreteInterval class\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up the ctor of DiscreteInterval class"); return; } while(d[++i].numerator!=0){ //create DiscreteInterval object discrete = (*e)->NewObject(e, discrete_intv_class, ctor, d[i].numerator,d[i].denominator); if(discrete == NULL){ info("[V4L4J] Error creating DiscreteInterval object\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error creating DiscreteInterval object"); return; } dprint(LOG_V4L4J, "[V4L4J] Adding discrete interval %d/%d\n", d[i].numerator,d[i].denominator); //add to vector (*e)->CallVoidMethod(e, disc_attr, add_method, discrete); } }
void TripletHelper::FillRowCol(Index n_entries, const Matrix& matrix, Index* iRow, Index* jCol, Index row_offset/*=0*/, Index col_offset/*=0*/) { const Matrix* mptr = &matrix; const GenTMatrix* gent = dynamic_cast<const GenTMatrix*>(mptr); if (gent) { FillRowCol_(n_entries, *gent, row_offset, col_offset, iRow, jCol); return; } const SymTMatrix* symt = dynamic_cast<const SymTMatrix*>(mptr); if (symt) { FillRowCol_(n_entries, *symt, row_offset, col_offset, iRow, jCol); return; } const ScaledMatrix* scaled = dynamic_cast<const ScaledMatrix*>(mptr); if (scaled) { FillRowCol_(n_entries, *scaled, row_offset, col_offset, iRow, jCol); return; } const SymScaledMatrix* symscaled = dynamic_cast<const SymScaledMatrix*>(mptr); if (symscaled) { FillRowCol_(n_entries, *symscaled, row_offset, col_offset, iRow, jCol); return; } const DiagMatrix* diag = dynamic_cast<const DiagMatrix*>(mptr); if (diag) { FillRowCol_(n_entries, *diag, row_offset, col_offset, iRow, jCol); return; } const IdentityMatrix* ident = dynamic_cast<const IdentityMatrix*>(mptr); if (ident) { FillRowCol_(n_entries, *ident, row_offset, col_offset, iRow, jCol); return; } const ExpansionMatrix* exp = dynamic_cast<const ExpansionMatrix*>(mptr); if (exp) { FillRowCol_(n_entries, *exp, row_offset, col_offset, iRow, jCol); return; } const SumMatrix* sum = dynamic_cast<const SumMatrix*>(mptr); if (sum) { FillRowCol_(n_entries, *sum, row_offset, col_offset, iRow, jCol); return; } const SumSymMatrix* sumsym = dynamic_cast<const SumSymMatrix*>(mptr); if (sumsym) { FillRowCol_(n_entries, *sumsym, row_offset, col_offset, iRow, jCol); return; } const ZeroMatrix* zero = dynamic_cast<const ZeroMatrix*>(mptr); if (zero) { DBG_ASSERT(n_entries == 0); return; } const CompoundMatrix* cmpd = dynamic_cast<const CompoundMatrix*>(mptr); if (cmpd) { FillRowCol_(n_entries, *cmpd, row_offset, col_offset, iRow, jCol); return; } const CompoundSymMatrix* cmpd_sym = dynamic_cast<const CompoundSymMatrix*>(mptr); if (cmpd_sym) { FillRowCol_(n_entries, *cmpd_sym, row_offset, col_offset, iRow, jCol); return; } THROW_EXCEPTION(UNKNOWN_MATRIX_TYPE,"Unknown matrix type passed to TripletHelper::FillRowCol"); }
/* * Init the control interface - Creates a list of controls */ JNIEXPORT jobjectArray JNICALL Java_au_edu_jcu_v4l4j_VideoDevice_doGetControlList(JNIEnv *e, jobject t, jlong object){ dprint(LOG_CALLS, "[CALL] Entering %s\n",__PRETTY_FUNCTION__); struct v4l4j_device *d = (struct v4l4j_device *) (uintptr_t) object; struct control_list *l; jclass v4l2ControlClass; jmethodID ctor; jobjectArray ctrls, names_array; jintArray values_array; jobject element; int i, type; dprint(LOG_LIBVIDEO, "[LIBVIDEO] Calling get_control_list()\n"); l = get_control_list(d->vdev); //Creates the java objects matching v4l2 controls dprint(LOG_V4L4J, "[V4L4J] Creating the Control array[%d]\n", l->count); v4l2ControlClass = (*e)->FindClass(e,CONTROL_CLASS); if(v4l2ControlClass == NULL){ info("[V4L4J] Error looking up the Control class\n"); release_control_list(d->vdev); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up Control class"); return 0; } ctor = (*e)->GetMethodID(e, v4l2ControlClass, "<init>", "(ILjava/lang/String;IIII[Ljava/lang/String;[IJ)V"); if(ctor == NULL){ info("[V4L4J] Error looking up the Control class constructor\n"); release_control_list(d->vdev); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up Control class constructor"); return 0; } //initialise the ctrls field of FrameGrabber object (this) ctrls = (*e)->NewObjectArray(e, l->count, v4l2ControlClass, NULL); if(ctrls == NULL){ info("[V4L4J] Error creating the control array\n"); release_control_list(d->vdev); THROW_EXCEPTION(e, JNI_EXCP, "Error creating the control array"); return 0; } //Construct a V4L2Control Java object for each V4L2control in l for(i = 0; i< l->count; i++) { if(l->controls[i].count_menu==0) { values_array = NULL; names_array = NULL; } else { //create the values and names arrays if((values_array = get_values(e,&l->controls[i])) == NULL) { release_control_list(d->vdev); return 0; } if((names_array = get_names(e,&l->controls[i])) ==NULL){ release_control_list(d->vdev); return 0; } } if((type = translate_type(e, l->controls[i].v4l2_ctrl->type))==-1) return 0; dprint(LOG_V4L4J, "[V4L4J] Creating Control %d - name: %s - type: %d\n", i, l->controls[i].v4l2_ctrl->name, type); element = (*e)->NewObject(e, v4l2ControlClass, ctor, i,\ (*e)->NewStringUTF(e, (const char *)l->controls[i].v4l2_ctrl->name),\ l->controls[i].v4l2_ctrl->minimum, l->controls[i].v4l2_ctrl->maximum, \ l->controls[i].v4l2_ctrl->step, type, names_array, values_array, object); if(element == NULL){ info("[V4L4J] Error creating the control '%s'\n", l->controls[i].v4l2_ctrl->name); release_control_list(d->vdev); THROW_EXCEPTION(e, JNI_EXCP, "Error creating the control '%s'", l->controls[i].v4l2_ctrl->name); return 0; } (*e)->SetObjectArrayElement(e, ctrls, i, element); } return ctrls; }
///Given the enumeration representing the parameter value of this plugin (i.e. the memory ///latency) it returns the corresponding memory latency std::string CacheSubstsPolicyIf::getCachePolicy(int sizeEnum){ bm_type::left_map::const_iterator foundVal = this->param2Enum.left.find(sizeEnum); if(foundVal == this->param2Enum.left.end()) THROW_EXCEPTION("Unable to find the parameter value corresponding to " << sizeEnum); return foundVal->second; }
void TripletHelper::FillValues(Index n_entries, const Matrix& matrix, Number* values) { const Matrix* mptr = &matrix; const GenTMatrix* gent = dynamic_cast<const GenTMatrix*>(mptr); if (gent) { FillValues_(n_entries, *gent, values); return; } const SymTMatrix* symt = dynamic_cast<const SymTMatrix*>(mptr); if (symt) { FillValues_(n_entries, *symt, values); return; } const ScaledMatrix* scaled = dynamic_cast<const ScaledMatrix*>(mptr); if (scaled) { FillValues_(n_entries, *scaled, values); return; } const SymScaledMatrix* symscaled = dynamic_cast<const SymScaledMatrix*>(mptr); if (symscaled) { FillValues_(n_entries, *symscaled, values); return; } const DiagMatrix* diag = dynamic_cast<const DiagMatrix*>(mptr); if (diag) { FillValues_(n_entries, *diag, values); return; } const IdentityMatrix* ident = dynamic_cast<const IdentityMatrix*>(mptr); if (ident) { FillValues_(n_entries, *ident, values); return; } const ExpansionMatrix* exp = dynamic_cast<const ExpansionMatrix*>(mptr); if (exp) { FillValues_(n_entries, *exp, values); return; } const SumMatrix* sum = dynamic_cast<const SumMatrix*>(mptr); if (sum) { FillValues_(n_entries, *sum, values); return; } const SumSymMatrix* sumsym = dynamic_cast<const SumSymMatrix*>(mptr); if (sumsym) { FillValues_(n_entries, *sumsym, values); return; } const ZeroMatrix* zero = dynamic_cast<const ZeroMatrix*>(mptr); if (zero) { DBG_ASSERT(n_entries == 0); return; } const CompoundMatrix* cmpd = dynamic_cast<const CompoundMatrix*>(mptr); if (cmpd) { FillValues_(n_entries, *cmpd, values); return; } const CompoundSymMatrix* cmpd_sym = dynamic_cast<const CompoundSymMatrix*>(mptr); if (cmpd_sym) { FillValues_(n_entries, *cmpd_sym, values); return; } THROW_EXCEPTION(UNKNOWN_MATRIX_TYPE,"Unknown matrix type passed to TripletHelper::FillValues"); }
// -------------------------------------------------------------------------- // // Function // Name: HTTPRequest::Receive(IOStreamGetLine &, int) // Purpose: Read the request from an IOStreamGetLine (and // attached stream). // Returns false if there was no valid request, // probably due to a kept-alive connection closing. // Created: 26/3/04 // // -------------------------------------------------------------------------- bool HTTPRequest::Receive(IOStreamGetLine &rGetLine, int Timeout) { // Check caller's logic if(mMethod != Method_UNINITIALISED) { THROW_EXCEPTION(HTTPException, RequestAlreadyBeenRead); } // Read the first line, which is of a different format to the rest of the lines std::string requestLine; if(!rGetLine.GetLine(requestLine, false /* no preprocessing */, Timeout)) { // Didn't get the request line, probably end of connection which had been kept alive return false; } BOX_TRACE("Request line: " << requestLine); // Check the method size_t p = 0; // current position in string p = requestLine.find(' '); // end of first word if(p == std::string::npos) { // No terminating space, looks bad p = requestLine.size(); } else { mHttpVerb = requestLine.substr(0, p); if (mHttpVerb == "GET") { mMethod = Method_GET; } else if (mHttpVerb == "HEAD") { mMethod = Method_HEAD; } else if (mHttpVerb == "POST") { mMethod = Method_POST; } else if (mHttpVerb == "PUT") { mMethod = Method_PUT; } else { mMethod = Method_UNKNOWN; } } // Skip spaces to find URI const char *requestLinePtr = requestLine.c_str(); while(requestLinePtr[p] != '\0' && requestLinePtr[p] == ' ') { ++p; } // Check there's a URI following... if(requestLinePtr[p] == '\0') { // Didn't get the request line, probably end of connection which had been kept alive return false; } // Read the URI, unescaping any %XX hex codes while(requestLinePtr[p] != ' ' && requestLinePtr[p] != '\0') { // End of URI, on to query string? if(requestLinePtr[p] == '?') { // Put the rest into the query string, without escaping anything ++p; while(requestLinePtr[p] != ' ' && requestLinePtr[p] != '\0') { mQueryString += requestLinePtr[p]; ++p; } break; } // Needs unescaping? else if(requestLinePtr[p] == '+') { mRequestURI += ' '; } else if(requestLinePtr[p] == '%') { // Be tolerant about this... bad things are silently accepted, // rather than throwing an error. char code[4] = {0,0,0,0}; code[0] = requestLinePtr[++p]; if(code[0] != '\0') { code[1] = requestLinePtr[++p]; } // Convert into a char code long c = ::strtol(code, NULL, 16); // Accept it? if(c > 0 && c <= 255) { mRequestURI += (char)c; } } else { // Simple copy of character mRequestURI += requestLinePtr[p]; } ++p; } // End of URL? if(requestLinePtr[p] == '\0') { // Assume HTTP 0.9 mHTTPVersion = HTTPVersion_0_9; } else { // Skip any more spaces while(requestLinePtr[p] != '\0' && requestLinePtr[p] == ' ') { ++p; } // Check to see if there's the right string next... if(::strncmp(requestLinePtr + p, "HTTP/", 5) == 0) { // Find the version numbers int major, minor; if(::sscanf(requestLinePtr + p + 5, "%d.%d", &major, &minor) != 2) { THROW_EXCEPTION_MESSAGE(HTTPException, BadRequest, "Unable to parse HTTP version number: " << requestLinePtr); } // Store version mHTTPVersion = (major * HTTPVersion__MajorMultiplier) + minor; } else { // Not good -- wrong string found THROW_EXCEPTION_MESSAGE(HTTPException, BadRequest, "Unable to parse HTTP request line: " << requestLinePtr); } } BOX_TRACE("HTTPRequest: method=" << mMethod << ", uri=" << mRequestURI << ", version=" << mHTTPVersion); // If HTTP 1.1 or greater, assume keep-alive if(mHTTPVersion >= HTTPVersion_1_1) { mClientKeepAliveRequested = true; } // Decode query string? if((mMethod == Method_GET || mMethod == Method_HEAD) && !mQueryString.empty()) { HTTPQueryDecoder decoder(mQuery); decoder.DecodeChunk(mQueryString.c_str(), mQueryString.size()); decoder.Finish(); } // Now parse the headers ParseHeaders(rGetLine, Timeout); std::string expected; if(GetHeader("Expect", &expected)) { if(expected == "100-continue") { mExpectContinue = true; } } // Parse form data? if(mMethod == Method_POST && mContentLength >= 0) { // Too long? Don't allow people to be nasty by sending lots of data if(mContentLength > MAX_CONTENT_SIZE) { THROW_EXCEPTION(HTTPException, POSTContentTooLong); } // Some data in the request to follow, parsing it bit by bit HTTPQueryDecoder decoder(mQuery); // Don't forget any data left in the GetLine object int fromBuffer = rGetLine.GetSizeOfBufferedData(); if(fromBuffer > mContentLength) fromBuffer = mContentLength; if(fromBuffer > 0) { BOX_TRACE("Decoding " << fromBuffer << " bytes of " "data from getline buffer"); decoder.DecodeChunk((const char *)rGetLine.GetBufferedData(), fromBuffer); // And tell the getline object to ignore the data we just used rGetLine.IgnoreBufferedData(fromBuffer); } // Then read any more data, as required int bytesToGo = mContentLength - fromBuffer; while(bytesToGo > 0) { char buf[4096]; int toRead = sizeof(buf); if(toRead > bytesToGo) toRead = bytesToGo; IOStream &rstream(rGetLine.GetUnderlyingStream()); int r = rstream.Read(buf, toRead, Timeout); if(r == 0) { // Timeout, just error THROW_EXCEPTION_MESSAGE(HTTPException, RequestReadFailed, "Failed to read complete request with the timeout"); } decoder.DecodeChunk(buf, r); bytesToGo -= r; } // Finish off decoder.Finish(); } else if (mContentLength > 0) { IOStream::pos_type bytesToCopy = rGetLine.GetSizeOfBufferedData(); if (bytesToCopy > mContentLength) { bytesToCopy = mContentLength; } Write(rGetLine.GetBufferedData(), bytesToCopy); SetForReading(); mpStreamToReadFrom = &(rGetLine.GetUnderlyingStream()); } return true; }
// -------------------------------------------------------------------------- // // Function // Name: HTTPRequest::Send(IOStream &, int) // Purpose: Write the request to an IOStream using HTTP. // Created: 03/01/09 // // -------------------------------------------------------------------------- bool HTTPRequest::Send(IOStream &rStream, int Timeout, bool ExpectContinue) { switch (mMethod) { case Method_UNINITIALISED: THROW_EXCEPTION(HTTPException, RequestNotInitialised); break; case Method_UNKNOWN: THROW_EXCEPTION(HTTPException, BadRequest); break; case Method_GET: rStream.Write("GET"); break; case Method_HEAD: rStream.Write("HEAD"); break; case Method_POST: rStream.Write("POST"); break; case Method_PUT: rStream.Write("PUT"); break; } rStream.Write(" "); rStream.Write(mRequestURI.c_str()); rStream.Write(" "); switch (mHTTPVersion) { case HTTPVersion_0_9: rStream.Write("HTTP/0.9"); break; case HTTPVersion_1_0: rStream.Write("HTTP/1.0"); break; case HTTPVersion_1_1: rStream.Write("HTTP/1.1"); break; default: THROW_EXCEPTION_MESSAGE(HTTPException, NotImplemented, "Unsupported HTTP version: " << mHTTPVersion); } rStream.Write("\n"); std::ostringstream oss; if (mContentLength != -1) { oss << "Content-Length: " << mContentLength << "\n"; } if (mContentType != "") { oss << "Content-Type: " << mContentType << "\n"; } if (mHostName != "") { if (mHostPort != 80) { oss << "Host: " << mHostName << ":" << mHostPort << "\n"; } else { oss << "Host: " << mHostName << "\n"; } } if (mpCookies) { THROW_EXCEPTION_MESSAGE(HTTPException, NotImplemented, "Cookie support not implemented yet"); } if (mClientKeepAliveRequested) { oss << "Connection: keep-alive\n"; } else { oss << "Connection: close\n"; } for (std::vector<Header>::iterator i = mExtraHeaders.begin(); i != mExtraHeaders.end(); i++) { oss << i->first << ": " << i->second << "\n"; } if (ExpectContinue) { oss << "Expect: 100-continue\n"; } rStream.Write(oss.str().c_str()); rStream.Write("\n"); return true; }
void MoleculePopulateProcess::populateUniformRanged(Species* aSpecies) { Comp* aComp(aSpecies->getComp()); double delta(0); // Increase the compartment dimensions by delta if it is a surface // compartment: if(aComp->dimension == 2) { delta = 0.1; } double maxX(std::min(1.0, OriginX+UniformRadiusX)); double minX(std::max(-1.0, OriginX-UniformRadiusX)); double maxY(std::min(1.0, OriginY+UniformRadiusY)); double minY(std::max(-1.0, OriginY-UniformRadiusY)); double maxZ(std::min(1.0, OriginZ+UniformRadiusZ)); double minZ(std::max(-1.0, OriginZ-UniformRadiusZ)); maxX = aComp->centerPoint.x + maxX*aComp->lengthX/2*(1+delta); minX = aComp->centerPoint.x + minX*aComp->lengthX/2*(1+delta); maxY = aComp->centerPoint.y + maxY*aComp->lengthY/2*(1+delta); minY = aComp->centerPoint.y + minY*aComp->lengthY/2*(1+delta); maxZ = aComp->centerPoint.z + maxZ*aComp->lengthZ/2*(1+delta); minZ = aComp->centerPoint.z + minZ*aComp->lengthZ/2*(1+delta); std::vector<unsigned int> aCoords; for(std::vector<unsigned int>::iterator i(aComp->coords.begin()); i != aComp->coords.end(); ++i) { Voxel* aVoxel(theSpatiocyteStepper->coord2voxel(*i)); Point aPoint(theSpatiocyteStepper->coord2point(aVoxel->coord)); if(aVoxel->id == aSpecies->getVacantID() && aPoint.x < maxX && aPoint.x > minX && aPoint.y < maxY && aPoint.y > minY && aPoint.z < maxZ && aPoint.z > minZ) { aCoords.push_back(*i); } } unsigned int aSize(aSpecies->getPopulateMoleculeSize()); if(aCoords.size() < aSize) { THROW_EXCEPTION(ValueError, String( getPropertyInterface().getClassName()) + "[" + getFullID().asString() + "]: There are " + int2str(aSize) + " " + getIDString(aSpecies) + " molecules that must be uniformly populated in a " + "given range,\n but there are only " + int2str(aCoords.size()) + " vacant voxels of " + getIDString(aSpecies->getVacantSpecies()) + " that can be populated."); } unsigned int aCoordsArray[aCoords.size()]; for(unsigned int i(0); i != aCoords.size(); ++i) { aCoordsArray[i] = aCoords[i]; } gsl_ran_shuffle(getStepper()->getRng(), aCoordsArray, aCoords.size(), sizeof(unsigned int)); for(unsigned int i(0); i != aSize; ++i) { aSpecies->addMolecule(theSpatiocyteStepper->coord2voxel(aCoordsArray[i])); } }
void GradientScaling::DetermineScalingParametersImpl( const SmartPtr<const VectorSpace> x_space, const SmartPtr<const VectorSpace> c_space, const SmartPtr<const VectorSpace> d_space, const SmartPtr<const MatrixSpace> jac_c_space, const SmartPtr<const MatrixSpace> jac_d_space, const SmartPtr<const SymMatrixSpace> h_space, const Matrix& Px_L, const Vector& x_L, const Matrix& Px_U, const Vector& x_U, Number& df, SmartPtr<Vector>& dx, SmartPtr<Vector>& dc, SmartPtr<Vector>& dd) { DBG_ASSERT(IsValid(nlp_)); SmartPtr<Vector> x = x_space->MakeNew(); if (!nlp_->GetStartingPoint(GetRawPtr(x), true, NULL, false, NULL, false, NULL, false, NULL, false)) { THROW_EXCEPTION(FAILED_INITIALIZATION, "Error getting initial point from NLP in GradientScaling.\n"); } // // Calculate grad_f scaling // SmartPtr<Vector> grad_f = x_space->MakeNew(); if (nlp_->Eval_grad_f(*x, *grad_f)) { double max_grad_f = grad_f->Amax(); df = 1.; if (scaling_obj_target_gradient_ == 0.) { if (max_grad_f > scaling_max_gradient_) { df = scaling_max_gradient_ / max_grad_f; } } else { if (max_grad_f == 0.) { Jnlst().Printf(J_WARNING, J_INITIALIZATION, "Gradient of objective function is zero at starting point. Cannot determine scaling factor based on scaling_obj_target_gradient option.\n"); } else { df = scaling_obj_target_gradient_ / max_grad_f; } } df = Max(df, scaling_min_value_); Jnlst().Printf(J_DETAILED, J_INITIALIZATION, "Scaling parameter for objective function = %e\n", df); } else { Jnlst().Printf(J_WARNING, J_INITIALIZATION, "Error evaluating objective gradient at user provided starting point.\n No scaling factor for objective function computed!\n"); df = 1.; } // // No x scaling // dx = NULL; dc = NULL; if (c_space->Dim()>0) { // // Calculate c scaling // SmartPtr<Matrix> jac_c = jac_c_space->MakeNew(); if (nlp_->Eval_jac_c(*x, *jac_c)) { dc = c_space->MakeNew(); const double dbl_min = std::numeric_limits<double>::min(); dc->Set(dbl_min); jac_c->ComputeRowAMax(*dc, false); Number arow_max = dc->Amax(); if (scaling_constr_target_gradient_<=0.) { if (arow_max > scaling_max_gradient_) { dc->ElementWiseReciprocal(); dc->Scal(scaling_max_gradient_); SmartPtr<Vector> dummy = dc->MakeNew(); dummy->Set(1.); dc->ElementWiseMin(*dummy); } else { dc = NULL; } } else { dc->Set(scaling_constr_target_gradient_/arow_max); } if (IsValid(dc) && scaling_min_value_ > 0.) { SmartPtr<Vector> tmp = dc->MakeNew(); tmp->Set(scaling_min_value_); dc->ElementWiseMax(*tmp); } } else { Jnlst().Printf(J_WARNING, J_INITIALIZATION, "Error evaluating Jacobian of equality constraints at user provided starting point.\n No scaling factors for equality constraints computed!\n"); } } dd = NULL; if (d_space->Dim()>0) { // // Calculate d scaling // SmartPtr<Matrix> jac_d = jac_d_space->MakeNew(); if (nlp_->Eval_jac_d(*x, *jac_d)) { dd = d_space->MakeNew(); const double dbl_min = std::numeric_limits<double>::min(); dd->Set(dbl_min); jac_d->ComputeRowAMax(*dd, false); Number arow_max = dd->Amax(); if (scaling_constr_target_gradient_<=0.) { if (arow_max > scaling_max_gradient_) { dd->ElementWiseReciprocal(); dd->Scal(scaling_max_gradient_); SmartPtr<Vector> dummy = dd->MakeNew(); dummy->Set(1.); dd->ElementWiseMin(*dummy); } else { dd = NULL; } } else { dd->Set(scaling_constr_target_gradient_/arow_max); } if (IsValid(dd) && scaling_min_value_ > 0.) { SmartPtr<Vector> tmp = dd->MakeNew(); tmp->Set(scaling_min_value_); dd->ElementWiseMax(*tmp); } } else { Jnlst().Printf(J_WARNING, J_INITIALIZATION, "Error evaluating Jacobian of inequality constraints at user provided starting point.\n No scaling factors for inequality constraints computed!\n"); } } }
SmartPtr<SymLinearSolver> AlgorithmBuilder::SymLinearSolverFactory( const Journalist& jnlst, const OptionsList& options, const std::string& prefix ) { SmartPtr<SparseSymLinearSolverInterface> SolverInterface; std::string linear_solver; options.GetStringValue("linear_solver", linear_solver, prefix); if( linear_solver == "ma27" ) { #ifndef COINHSL_HAS_MA27 # ifdef HAVE_LINEARSOLVERLOADER SolverInterface = new Ma27TSolverInterface(); if (!LSL_isMA27available()) { char buf[256]; int rc = LSL_loadHSL(NULL, buf, 255); if (rc) { std::string errmsg; errmsg = "Selected linear solver MA27 not available.\nTried to obtain MA27 from shared library \""; errmsg += LSL_HSLLibraryName(); errmsg += "\", but the following error occured:\n"; errmsg += buf; THROW_EXCEPTION(OPTION_INVALID, errmsg.c_str()); } } # else THROW_EXCEPTION(OPTION_INVALID, "Support for MA27 has not been compiled into Ipopt."); # endif #else SolverInterface = new Ma27TSolverInterface(); #endif } else if( linear_solver == "ma57" ) { #ifndef COINHSL_HAS_MA57 # ifdef HAVE_LINEARSOLVERLOADER SolverInterface = new Ma57TSolverInterface(); if (!LSL_isMA57available()) { char buf[256]; int rc = LSL_loadHSL(NULL, buf, 255); if (rc) { std::string errmsg; errmsg = "Selected linear solver MA57 not available.\nTried to obtain MA57 from shared library \""; errmsg += LSL_HSLLibraryName(); errmsg += "\", but the following error occured:\n"; errmsg += buf; THROW_EXCEPTION(OPTION_INVALID, errmsg.c_str()); } } # else THROW_EXCEPTION(OPTION_INVALID, "Support for MA57 has not been compiled into Ipopt."); # endif #else SolverInterface = new Ma57TSolverInterface(); #endif } else if( linear_solver == "ma77" ) { #ifndef COINHSL_HAS_MA77 # ifdef HAVE_LINEARSOLVERLOADER SolverInterface = new Ma77SolverInterface(); if (!LSL_isMA77available()) { char buf[256]; int rc = LSL_loadHSL(NULL, buf, 255); if (rc) { std::string errmsg; errmsg = "Selected linear solver HSL_MA77 not available.\nTried to obtain HSL_MA77 from shared library \""; errmsg += LSL_HSLLibraryName(); errmsg += "\", but the following error occured:\n"; errmsg += buf; THROW_EXCEPTION(OPTION_INVALID, errmsg.c_str()); } } # else THROW_EXCEPTION(OPTION_INVALID, "Support for HSL_MA77 has not been compiled into Ipopt."); # endif #else SolverInterface = new Ma77SolverInterface(); #endif } else if( linear_solver == "ma86" ) { #ifndef COINHSL_HAS_MA86 # ifdef HAVE_LINEARSOLVERLOADER SolverInterface = new Ma86SolverInterface(); if (!LSL_isMA86available()) { char buf[256]; int rc = LSL_loadHSL(NULL, buf, 255); if (rc) { std::string errmsg; errmsg = "Selected linear solver HSL_MA86 not available.\nTried to obtain HSL_MA86 from shared library \""; errmsg += LSL_HSLLibraryName(); errmsg += "\", but the following error occured:\n"; errmsg += buf; THROW_EXCEPTION(OPTION_INVALID, errmsg.c_str()); } } # else THROW_EXCEPTION(OPTION_INVALID, "Support for HSL_MA86 has not been compiled into Ipopt."); # endif #else SolverInterface = new Ma86SolverInterface(); #endif } else if( linear_solver == "pardiso" ) { #ifndef HAVE_PARDISO # ifdef HAVE_LINEARSOLVERLOADER SolverInterface = new PardisoSolverInterface(); char buf[256]; int rc = LSL_loadPardisoLib(NULL, buf, 255); if (rc) { std::string errmsg; errmsg = "Selected linear solver Pardiso not available.\nTried to obtain Pardiso from shared library \""; errmsg += LSL_PardisoLibraryName(); errmsg += "\", but the following error occured:\n"; errmsg += buf; THROW_EXCEPTION(OPTION_INVALID, errmsg.c_str()); } # else THROW_EXCEPTION(OPTION_INVALID, "Support for Pardiso has not been compiled into Ipopt."); # endif #else SolverInterface = new PardisoSolverInterface(); #endif } else if( linear_solver == "ma97" ) { #ifndef COINHSL_HAS_MA97 # ifdef HAVE_LINEARSOLVERLOADER SolverInterface = new Ma97SolverInterface(); if (!LSL_isMA97available()) { char buf[256]; int rc = LSL_loadHSL(NULL, buf, 255); if (rc) { std::string errmsg; errmsg = "Selected linear solver HSL_MA97 not available.\nTried to obtain HSL_MA97 from shared library \""; errmsg += LSL_HSLLibraryName(); errmsg += "\", but the following error occured:\n"; errmsg += buf; THROW_EXCEPTION(OPTION_INVALID, errmsg.c_str()); } } # else THROW_EXCEPTION(OPTION_INVALID, "Support for HSL_MA97 has not been compiled into Ipopt."); # endif #else SolverInterface = new Ma97SolverInterface(); #endif } else if( linear_solver == "wsmp" ) { #ifdef HAVE_WSMP bool wsmp_iterative; options.GetBoolValue("wsmp_iterative", wsmp_iterative, prefix); if (wsmp_iterative) { SolverInterface = new IterativeWsmpSolverInterface(); } else { SolverInterface = new WsmpSolverInterface(); } #else THROW_EXCEPTION(OPTION_INVALID, "Selected linear solver WSMP not available."); #endif } else if( linear_solver == "mumps" ) { #ifdef COIN_HAS_MUMPS SolverInterface = new MumpsSolverInterface(); #else THROW_EXCEPTION(OPTION_INVALID, "Selected linear solver MUMPS not available."); #endif } else if( linear_solver == "custom" ) { SolverInterface = NULL; } SmartPtr<TSymScalingMethod> ScalingMethod; std::string linear_system_scaling; if( !options.GetStringValue("linear_system_scaling", linear_system_scaling, prefix) ) { // By default, don't use mc19 for non-HSL solvers, or HSL_MA97 if( linear_solver != "ma27" && linear_solver != "ma57" && linear_solver != "ma77" && linear_solver != "ma86" ) { linear_system_scaling = "none"; } } if( linear_system_scaling == "mc19" ) { #ifndef COINHSL_HAS_MC19 # ifdef HAVE_LINEARSOLVERLOADER ScalingMethod = new Mc19TSymScalingMethod(); if (!LSL_isMC19available()) { char buf[256]; int rc = LSL_loadHSL(NULL, buf, 255); if (rc) { std::string errmsg; errmsg = "Selected linear system scaling method MC19 not available.\n"; errmsg += buf; THROW_EXCEPTION(OPTION_INVALID, errmsg.c_str()); } } # else THROW_EXCEPTION(OPTION_INVALID, "Support for MC19 has not been compiled into Ipopt."); # endif #else ScalingMethod = new Mc19TSymScalingMethod(); #endif } else if( linear_system_scaling == "slack-based" ) { ScalingMethod = new SlackBasedTSymScalingMethod(); } SmartPtr<SymLinearSolver> ScaledSolver = new TSymLinearSolver(SolverInterface, ScalingMethod); return ScaledSolver; }
SolverReturn IpoptAlgorithm::Optimize(bool isResto /*= false */) { DBG_START_METH("IpoptAlgorithm::Optimize", dbg_verbosity); // Start measuring CPU time IpData().TimingStats().OverallAlgorithm().Start(); if (!copyright_message_printed) { print_copyright_message(Jnlst()); } if (!isResto) { Jnlst().Printf(J_ITERSUMMARY, J_MAIN, "This is Ipopt version "IPOPT_VERSION", running with linear solver %s.\n", linear_solver_.c_str()); #ifndef IPOPT_NOMUMPSNOTE if( linear_solver_ == "mumps" ) { Jnlst().Printf(J_ITERSUMMARY, J_MAIN, "NOTE: Other linear solvers might be more efficient (see Ipopt documentation).\n"); } #endif Jnlst().Printf(J_ITERSUMMARY, J_MAIN, "\n"); } SolverReturn retval = UNASSIGNED; try { IpData().TimingStats().InitializeIterates().Start(); // Initialize the iterates InitializeIterates(); IpData().TimingStats().InitializeIterates().End(); if (!skip_print_problem_stats_) { IpData().TimingStats().PrintProblemStatistics().Start(); PrintProblemStatistics(); IpData().TimingStats().PrintProblemStatistics().End(); } IpData().TimingStats().CheckConvergence().Start(); ConvergenceCheck::ConvergenceStatus conv_status = conv_check_->CheckConvergence(); IpData().TimingStats().CheckConvergence().End(); // main loop while (conv_status == ConvergenceCheck::CONTINUE) { // Set the Hessian Matrix IpData().TimingStats().UpdateHessian().Start(); UpdateHessian(); IpData().TimingStats().UpdateHessian().End(); // do all the output for this iteration IpData().TimingStats().OutputIteration().Start(); OutputIteration(); IpData().ResetInfo(); IpData().TimingStats().OutputIteration().End(); // initialize the flag that is set to true if the algorithm // has to continue with an emergency fallback mode. For // example, when no search direction can be computed, continue // with the restoration phase bool emergency_mode = false; // update the barrier parameter IpData().TimingStats().UpdateBarrierParameter().Start(); emergency_mode = !UpdateBarrierParameter(); IpData().TimingStats().UpdateBarrierParameter().End(); if (!emergency_mode) { // solve the primal-dual system to get the full step IpData().TimingStats().ComputeSearchDirection().Start(); emergency_mode = !ComputeSearchDirection(); IpData().TimingStats().ComputeSearchDirection().End(); } // If we are in the emergency mode, ask to line search object // to go to the fallback options. If that isn't possible, // issue error message if (emergency_mode) { bool retval = line_search_->ActivateFallbackMechanism(); if (retval) { Jnlst().Printf(J_WARNING, J_MAIN, "WARNING: Problem in step computation; switching to emergency mode.\n"); } else { Jnlst().Printf(J_ERROR, J_MAIN, "ERROR: Problem in step computation, but emergency mode cannot be activated.\n"); THROW_EXCEPTION(STEP_COMPUTATION_FAILED, "Step computation failed."); } } // Compute the new iterate IpData().TimingStats().ComputeAcceptableTrialPoint().Start(); ComputeAcceptableTrialPoint(); IpData().TimingStats().ComputeAcceptableTrialPoint().End(); // Accept the new iterate IpData().TimingStats().AcceptTrialPoint().Start(); AcceptTrialPoint(); IpData().TimingStats().AcceptTrialPoint().End(); IpData().Set_iter_count(IpData().iter_count()+1); IpData().TimingStats().CheckConvergence().Start(); conv_status = conv_check_->CheckConvergence(); IpData().TimingStats().CheckConvergence().End(); } IpData().TimingStats().OutputIteration().Start(); OutputIteration(); IpData().TimingStats().OutputIteration().End(); if (conv_status == ConvergenceCheck::CONVERGED || conv_status == ConvergenceCheck::CONVERGED_TO_ACCEPTABLE_POINT) { if (IpCq().IsSquareProblem()) { // make the sure multipliers are computed properly ComputeFeasibilityMultipliers(); } } switch (conv_status) { case ConvergenceCheck::CONVERGED: retval = SUCCESS; break; case ConvergenceCheck::CONVERGED_TO_ACCEPTABLE_POINT: retval = STOP_AT_ACCEPTABLE_POINT; break; case ConvergenceCheck::MAXITER_EXCEEDED: retval = MAXITER_EXCEEDED; break; case ConvergenceCheck::CPUTIME_EXCEEDED: retval = CPUTIME_EXCEEDED; break; case ConvergenceCheck::DIVERGING: retval = DIVERGING_ITERATES; break; case ConvergenceCheck::USER_STOP: retval = USER_REQUESTED_STOP; break; default: retval = INTERNAL_ERROR; break; } } catch (TINY_STEP_DETECTED& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().UpdateBarrierParameter().EndIfStarted(); retval = STOP_AT_TINY_STEP; } catch (ACCEPTABLE_POINT_REACHED& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); if (IpCq().IsSquareProblem()) { // make the sure multipliers are computed properly ComputeFeasibilityMultipliers(); } retval = STOP_AT_ACCEPTABLE_POINT; } catch (LOCALLY_INFEASIBLE& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); IpData().TimingStats().CheckConvergence().EndIfStarted(); retval = LOCAL_INFEASIBILITY; } catch (RESTORATION_CONVERGED_TO_FEASIBLE_POINT& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = RESTORATION_FAILURE; } catch (RESTORATION_FAILED& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = RESTORATION_FAILURE; } catch (RESTORATION_MAXITER_EXCEEDED& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = MAXITER_EXCEEDED; } catch (RESTORATION_CPUTIME_EXCEEDED& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = CPUTIME_EXCEEDED; } catch (RESTORATION_USER_STOP& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = USER_REQUESTED_STOP; } catch (STEP_COMPUTATION_FAILED& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = ERROR_IN_STEP_COMPUTATION; } catch (IpoptNLP::Eval_Error& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = INVALID_NUMBER_DETECTED; } catch (FEASIBILITY_PROBLEM_SOLVED& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); if (IpCq().IsSquareProblem()) { // make the sure multipliers are computed properly ComputeFeasibilityMultipliers(); } retval = FEASIBLE_POINT_FOUND; } catch (TOO_FEW_DOF& exc) { exc.ReportException(Jnlst(), J_MOREDETAILED); IpData().TimingStats().ComputeAcceptableTrialPoint().EndIfStarted(); retval = TOO_FEW_DEGREES_OF_FREEDOM; } catch (INTERNAL_ABORT& exc) { exc.ReportException(Jnlst()); retval = INTERNAL_ERROR; } DBG_ASSERT(retval != UNASSIGNED && "Unknown return code in the algorithm"); IpData().TimingStats().OverallAlgorithm().End(); return retval; }
bool fdSend(int socket, int fd, const unsigned int timeoutMS) { std::chrono::high_resolution_clock::time_point deadline = std::chrono::high_resolution_clock::now() + std::chrono::milliseconds(timeoutMS); // Space for the file descriptor union { struct cmsghdr cmh; char control[CMSG_SPACE(sizeof(int))]; } controlUnion; // Ensure at least 1 byte is transmited via the socket struct iovec iov; char buf = '!'; iov.iov_base = &buf; iov.iov_len = sizeof(char); // Fill the message to send: // The socket has to be connected, so we don't need to specify the name struct msghdr msgh; ::memset(&msgh, 0, sizeof(msgh)); // Only iovec to transmit one element msgh.msg_iov = &iov; msgh.msg_iovlen = 1; // Ancillary data buffer msgh.msg_control = controlUnion.control; msgh.msg_controllen = sizeof(controlUnion.control); // Describe the data that we want to send struct cmsghdr *cmhp; cmhp = CMSG_FIRSTHDR(&msgh); cmhp->cmsg_len = CMSG_LEN(sizeof(int)); cmhp->cmsg_level = SOL_SOCKET; cmhp->cmsg_type = SCM_RIGHTS; *(reinterpret_cast<int*>(CMSG_DATA(cmhp))) = fd; // Send for(;;) { ssize_t ret = ::sendmsg(socket, &msgh, MSG_NOSIGNAL); if (ret < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { // Neglected errors, retry } else { THROW_EXCEPTION(UtilsException, "Error during sendmsg()", errno); } } else if (ret == 0) { // Retry the sending } else { // We send only 1 byte of data. No need to repeat break; } waitForEvent(socket, POLLOUT, deadline); } // TODO: It shouldn't return return true; }
bool OptionsList::ReadFromStream(const Journalist& jnlst, std::istream& is) { jnlst.Printf(J_DETAILED, J_MAIN, "Start reading options from stream.\n"); while (true) { std::string tag; std::string value; if (!readnexttoken(is, tag)) { // That's it - end of file reached. jnlst.Printf(J_DETAILED, J_MAIN, "Finished reading options from file.\n"); return true; } if (!readnexttoken(is, value)) { // Can't read value for a given tag jnlst.Printf(J_ERROR, J_MAIN, "Error reading value for tag %s from file.\n", tag.c_str()); return false; } // Now add the value for the options list jnlst.Printf(J_DETAILED, J_MAIN, "Adding option \"%s\" with value \"%s\" to OptionsList.\n", tag.c_str(), value.c_str()); if (IsValid(reg_options_)) { SmartPtr<const RegisteredOption> option = reg_options_->GetOption(tag); if (IsNull(option)) { std::string msg = "Read Option: \""; msg += tag; msg += "\". It is not a valid option. Check the list of available options."; THROW_EXCEPTION(OPTION_INVALID, msg); } if (option->Type() == OT_String) { bool result = SetStringValue(tag, value, false); ASSERT_EXCEPTION(result, OPTION_INVALID, "Error setting string value read from option file."); } else if (option->Type() == OT_Number) { // Some people like to use 'd' instead of 'e' in floating // point numbers. Therefore, we change a 'd' to an 'e' char* buffer = new char[value.length()+1]; strcpy(buffer, value.c_str()); for (int i=0; i<(int)value.length(); ++i) { if (buffer[i]=='d' || buffer[i]=='D') { buffer[i] = 'e'; } } char* p_end; Number retval = strtod(buffer, &p_end); if (*p_end!='\0' && !isspace(*p_end)) { delete [] buffer; std::string msg = "Option \"" + tag + "\": Double value expected, but non-numeric option value \"" + value + "\" found.\n"; THROW_EXCEPTION(OPTION_INVALID, msg); } delete [] buffer; bool result = SetNumericValue(tag, retval, false); ASSERT_EXCEPTION(result, OPTION_INVALID, "Error setting numeric value read from file."); } else if (option->Type() == OT_Integer) { char* p_end; size_t retval = strtol(value.c_str(), &p_end, 10); if (*p_end!='\0' && !isspace(*p_end)) { std::string msg = "Option \"" + tag + "\": Integer value expected, but non-integer option value \"" + value + "\" found.\n"; if (IsValid(jnlst_)) { option->OutputDescription(*jnlst_); } THROW_EXCEPTION(OPTION_INVALID, msg); } bool result = SetIntegerValue(tag, static_cast<Index>(retval), false); ASSERT_EXCEPTION(result, OPTION_INVALID, "Error setting integer value read from option file."); } else { DBG_ASSERT(false && "Option Type: Unknown"); } } else { bool result = SetStringValue(tag, value, false); ASSERT_EXCEPTION(result, OPTION_INVALID, "Error setting value read from option file."); } } }
// -------------------------------------------------------------------------- // // Function // Name: HTTPRequest::ParseHeaders(IOStreamGetLine &, int) // Purpose: Private. Parse the headers of the request // Created: 26/3/04 // // -------------------------------------------------------------------------- void HTTPRequest::ParseHeaders(IOStreamGetLine &rGetLine, int Timeout) { std::string header; bool haveHeader = false; while(true) { if(rGetLine.IsEOF()) { // Header terminates unexpectedly THROW_EXCEPTION(HTTPException, BadRequest) } std::string currentLine; if(!rGetLine.GetLine(currentLine, false /* no preprocess */, Timeout)) { // Timeout THROW_EXCEPTION(HTTPException, RequestReadFailed) } // Is this a continuation of the previous line? bool processHeader = haveHeader; if(!currentLine.empty() && (currentLine[0] == ' ' || currentLine[0] == '\t')) { // A continuation, don't process anything yet processHeader = false; } //TRACE3("%d:%d:%s\n", processHeader, haveHeader, currentLine.c_str()); // Parse the header -- this will actually process the header // from the previous run around the loop. if(processHeader) { // Find where the : is in the line const char *h = header.c_str(); int p = 0; while(h[p] != '\0' && h[p] != ':') { ++p; } // Skip white space int dataStart = p + 1; while(h[dataStart] == ' ' || h[dataStart] == '\t') { ++dataStart; } std::string header_name(ToLowerCase(std::string(h, p))); if (header_name == "content-length") { // Decode number long len = ::strtol(h + dataStart, NULL, 10); // returns zero in error case, this is OK if(len < 0) len = 0; // Store mContentLength = len; } else if (header_name == "content-type") { // Store rest of string as content type mContentType = h + dataStart; } else if (header_name == "host") { // Store host header mHostName = h + dataStart; // Is there a port number to split off? std::string::size_type colon = mHostName.find_first_of(':'); if(colon != std::string::npos) { // There's a port in the string... attempt to turn it into an int mHostPort = ::strtol(mHostName.c_str() + colon + 1, 0, 10); // Truncate the string to just the hostname mHostName = mHostName.substr(0, colon); BOX_TRACE("Host: header, hostname = " << "'" << mHostName << "', host " "port = " << mHostPort); } } else if (header_name == "cookie") { // Parse cookies ParseCookies(header, dataStart); } else if (header_name == "connection") { // Connection header, what is required? const char *v = h + dataStart; if(::strcasecmp(v, "close") == 0) { mClientKeepAliveRequested = false; } else if(::strcasecmp(v, "keep-alive") == 0) { mClientKeepAliveRequested = true; } // else don't understand, just assume default for protocol version } else { mExtraHeaders.push_back(Header(header_name, h + dataStart)); } // Unset have header flag, as it's now been processed haveHeader = false; } // Store the chunk of header the for next time round if(haveHeader) { header += currentLine; } else { header = currentLine; haveHeader = true; } // End of headers? if(currentLine.empty()) { // All done! break; } } }
///Using the current instance of ReSPClient, it queries ReSP for the new ///values of the metrics (i.e. CPI, frequency etc. for a processor) and returns ///this value void CacheSubstsPolicyIf::getStats(RespClient &client, std::map<std::string, float> &toUpdateStats){ //Here I get the stats for all the policies, the current one and all the //others std::string curCache = this->pluginName.substr(0, 1); std::string cacheStatus; client.get_probe_value(curCache + "CacheStatus", cacheStatus); if(cacheStatus.find("DISABLED") != std::string::npos) THROW_EXCEPTION("Error, the " << curCache << " cache is not enabled"); client.get_probe_value("numMemAccesses", toUpdateStats["numMemAccesses"]); client.get_probe_value("numBusAccesses", toUpdateStats["numBusAccesses"]); client.get_probe_value(curCache + "readMissNum", toUpdateStats[curCache + "readMissNum"]); client.get_probe_value(curCache + "readHitNum", toUpdateStats[curCache + "readHitNum"]); client.get_probe_value(curCache + "readMissNum", toUpdateStats[curCache + "readMissNum"]); client.get_probe_value(curCache + "writeHitNum", toUpdateStats[curCache + "writeHitNum"]); client.get_probe_value(curCache + "writeMissNum", toUpdateStats[curCache + "writeMissNum"]); if(curCache == "d"){ client.get_probe_value("readMissNum_dcacheLRU_TH", toUpdateStats["readMissNum_dcacheLRU_TH"]); client.get_probe_value("readMissNum_dcacheLRU_THA", toUpdateStats["readMissNum_dcacheLRU_THA"]); client.get_probe_value("readMissNum_dcacheLRU_B", toUpdateStats["readMissNum_dcacheLRU_B"]); client.get_probe_value("readMissNum_dcacheLRR_TH", toUpdateStats["readMissNum_dcacheLRR_TH"]); client.get_probe_value("readMissNum_dcacheLRR_THA", toUpdateStats["readMissNum_dcacheLRR_THA"]); client.get_probe_value("readMissNum_dcacheLRR_B", toUpdateStats["readMissNum_dcacheLRR_B"]); client.get_probe_value("readMissNum_dcacheRAND_TH", toUpdateStats["readMissNum_dcacheRAND_TH"]); client.get_probe_value("readMissNum_dcacheRAND_THA", toUpdateStats["readMissNum_dcacheRAND_THA"]); client.get_probe_value("readMissNum_dcacheRAND_B", toUpdateStats["readMissNum_dcacheRAND_B"]); client.get_probe_value("writeHitNum_dcacheLRU_TH", toUpdateStats["writeHitNum_dcacheLRU_TH"]); client.get_probe_value("writeHitNum_dcacheLRU_THA", toUpdateStats["writeHitNum_dcacheLRU_THA"]); client.get_probe_value("writeHitNum_dcacheLRU_B", toUpdateStats["writeHitNum_dcacheLRU_B"]); client.get_probe_value("writeHitNum_dcacheLRR_TH", toUpdateStats["writeHitNum_dcacheLRR_TH"]); client.get_probe_value("writeHitNum_dcacheLRR_THA", toUpdateStats["writeHitNum_dcacheLRR_THA"]); client.get_probe_value("writeHitNum_dcacheLRR_B", toUpdateStats["writeHitNum_dcacheLRR_B"]); client.get_probe_value("writeHitNum_dcacheRAND_TH", toUpdateStats["writeHitNum_dcacheRAND_TH"]); client.get_probe_value("writeHitNum_dcacheRAND_THA", toUpdateStats["writeHitNum_dcacheRAND_THA"]); client.get_probe_value("writeHitNum_dcacheRAND_B", toUpdateStats["writeHitNum_dcacheRAND_B"]); client.get_probe_value("writeMissNum_dcacheLRU_TH", toUpdateStats["writeMissNum_dcacheLRU_TH"]); client.get_probe_value("writeMissNum_dcacheLRU_THA", toUpdateStats["writeMissNum_dcacheLRU_THA"]); client.get_probe_value("writeMissNum_dcacheLRU_B", toUpdateStats["writeMissNum_dcacheLRU_B"]); client.get_probe_value("writeMissNum_dcacheLRR_TH", toUpdateStats["writeMissNum_dcacheLRR_TH"]); client.get_probe_value("writeMissNum_dcacheLRR_THA", toUpdateStats["writeMissNum_dcacheLRR_THA"]); client.get_probe_value("writeMissNum_dcacheLRR_B", toUpdateStats["writeMissNum_dcacheLRR_B"]); client.get_probe_value("writeMissNum_dcacheRAND_TH", toUpdateStats["writeMissNum_dcacheRAND_TH"]); client.get_probe_value("writeMissNum_dcacheRAND_THA", toUpdateStats["writeMissNum_dcacheRAND_THA"]); client.get_probe_value("writeMissNum_dcacheRAND_B", toUpdateStats["writeMissNum_dcacheRAND_B"]); client.get_probe_value("readHitNum_dcacheLRU_TH", toUpdateStats["readHitNum_dcacheLRU_TH"]); client.get_probe_value("readHitNum_dcacheLRU_THA", toUpdateStats["readHitNum_dcacheLRU_THA"]); client.get_probe_value("readHitNum_dcacheLRU_B", toUpdateStats["readHitNum_dcacheLRU_B"]); client.get_probe_value("readHitNum_dcacheLRR_TH", toUpdateStats["readHitNum_dcacheLRR_TH"]); client.get_probe_value("readHitNum_dcacheLRR_THA", toUpdateStats["readHitNum_dcacheLRR_THA"]); client.get_probe_value("readHitNum_dcacheLRR_B", toUpdateStats["readHitNum_dcacheLRR_B"]); client.get_probe_value("readHitNum_dcacheRAND_TH", toUpdateStats["readHitNum_dcacheRAND_TH"]); client.get_probe_value("readHitNum_dcacheRAND_THA", toUpdateStats["readHitNum_dcacheRAND_THA"]); client.get_probe_value("readHitNum_dcacheRAND_B", toUpdateStats["readHitNum_dcacheRAND_B"]); } else{ client.get_probe_value("readHitNum_icacheLRU", toUpdateStats["readHitNum_icacheLRU"]); client.get_probe_value("readHitNum_icacheLRR", toUpdateStats["readHitNum_icacheLRR"]); client.get_probe_value("readHitNum_icacheRAND", toUpdateStats["readHitNum_icacheRAND"]); client.get_probe_value("readMissNum_icacheLRU", toUpdateStats["readMissNum_icacheLRU"]); client.get_probe_value("readMissNum_icacheLRR", toUpdateStats["readMissNum_icacheLRR"]); client.get_probe_value("readMissNum_icacheRAND", toUpdateStats["readMissNum_icacheRAND"]); } }
SmartPtr<const Vector> RestoIpoptNLP::grad_f( const Vector& x ) { THROW_EXCEPTION(INTERNAL_ABORT, "ERROR: In RestoIpoptNLP grad_f() is called without mu!"); }
///Given a metric and the new parameter value, we obtain an ///estimation of the metric change from the old value to the new ///one std::pair<float, float> CacheSubstsPolicyIf::changeValue(std::map<PluginIf*, int> ¶meters, int newValue, const std::string &metric, const std::map<std::string, float> ¢roidMap, const std::map<std::string, float> &statistics, const std::map<PluginIf *, std::string> ¶meter_values){ // Note that actually I do not consider the write policy of the instruction cache, so no // action can be performed if we are in the instruction cache std::pair<float, float> retVal; std::string curCache = this->pluginName.substr(0, 1); std::map<std::string, PluginIf* >::const_iterator foundPlugin; int oldValue = parameters[this]; if(centroidMap.find("execTime") == centroidMap.end()) THROW_EXCEPTION("Unable to find the metric execTime"); if(centroidMap.find("energy") == centroidMap.end()) THROW_EXCEPTION("Unable to find the metric energy"); // Now I have, using the difference between the old and new misses, // to compute the new value for the metrics. unsigned int oldReadHitNum = (unsigned int)statistics.find(curCache + "readHitNum")->second; unsigned int oldWriteHitNum = (unsigned int)statistics.find(curCache + "writeHitNum")->second; unsigned int oldReadMissNum = (unsigned int)statistics.find(curCache + "readMissNum")->second; unsigned int oldWriteMissNum = (unsigned int)statistics.find(curCache + "writeMissNum")->second; double modifier = 1.0; std::string newValueString = this->getParameterName(newValue); std::string newAllPolicy; if(newValueString.find("LRU") != std::string::npos) newAllPolicy = "LRU"; else if(newValueString.find("LRR") != std::string::npos) newAllPolicy = "LRR"; else if(newValueString.find("RANDOM") != std::string::npos) { newAllPolicy = "RAND"; modifier = 1.15; } unsigned int newReadHitNum = 0; unsigned int newWriteHitNum = 0; unsigned int newReadMissNum = 0; unsigned int newWriteMissNum = 0; if(curCache == "d"){ std::string curCacheWritePolicy = "TH"; foundPlugin = plugin_handler.find("dcacheWritePolicy"); if(foundPlugin != plugin_handler.end()){ if(parameter_values.find(foundPlugin->second) != parameter_values.end()){ curCacheWritePolicy = parameter_values.find(foundPlugin->second)->second; if(curCacheWritePolicy.find("THROUGH") != std::string::npos) curCacheWritePolicy = "TH"; else if(curCacheWritePolicy.find("BACK") != std::string::npos) curCacheWritePolicy = "B"; else if(curCacheWritePolicy.find("THROUGH_ALL") != std::string::npos) curCacheWritePolicy = "THA"; } } newReadHitNum = (unsigned int)statistics.find("readHitNum_dcache" + newAllPolicy + "_" + curCacheWritePolicy)->second; newWriteHitNum = (unsigned int)statistics.find("writeHitNum_dcache" + newAllPolicy + "_" + curCacheWritePolicy)->second; newReadMissNum = (unsigned int)statistics.find("readMissNum_dcache" + newAllPolicy + "_" + curCacheWritePolicy)->second; newWriteMissNum = (unsigned int)statistics.find("writeMissNum_dcache" + newAllPolicy + "_" + curCacheWritePolicy)->second; } else{ newReadHitNum = (unsigned int)statistics.find("readHitNum_icache" + newAllPolicy)->second; newWriteHitNum = oldWriteHitNum; newReadMissNum = (unsigned int)statistics.find("readMissNum_icache" + newAllPolicy)->second; newWriteMissNum = oldWriteMissNum; } double cacheSize = 4*1024; foundPlugin = plugin_handler.find(curCache + "_cache_size"); if(foundPlugin != plugin_handler.end()){ if(parameter_values.find(foundPlugin->second) != parameter_values.end()){ cacheSize = boost::lexical_cast<double>(parameter_values.find(foundPlugin->second)->second); } } double execTime = centroidMap.find("execTime")->second; double ratio = (double) (newReadMissNum+newWriteMissNum)/(double) (oldReadMissNum+oldWriteMissNum); // Now I have to compute the execution time after the parameter change. Note that // I acutally have the new number of misses and hits with the new policy double newExecTime = execTime*ratio; // cout << "Cache subst Time: " << newExecTime << endl; // cout << "Miss: " << newReadMissNum+newWriteMissNum << " Was: " << (oldReadMissNum+oldWriteMissNum) << endl; // cout << "Cache subst ratio: " << ratio << endl; if(metric == "execTime"){ if( ratio > 1.0 ) { retVal.first = execTime*(1.0/modifier); retVal.second = execTime*ratio*modifier; } else { retVal.first = execTime*ratio*(1.0/modifier); retVal.second = execTime*modifier; } } else if(metric == "energy"){ double curMetricCentroid = centroidMap.find("energy")->second; // // Get new energy values from ReSP // this->model.set_parameter("size", cacheSize); // this->model.set_probe("execution_time", execTime); // this->model.set_probe("readHitNum", oldReadHitNum); // this->model.set_probe("writeHitNum", oldWriteHitNum); // this->model.set_probe("readMissNum", oldReadMissNum); // this->model.set_probe("writeMissNum", oldWriteMissNum); // this->model.update_parameters(); // double oldEnergy = this->model.get_energy(); // // this->model.set_probe("readHitNum", newReadHitNum); // this->model.set_probe("writeHitNum", newWriteHitNum); // this->model.set_probe("readMissNum", newReadMissNum); // this->model.set_probe("writeMissNum", newWriteMissNum); // this->model.set_probe("execution_time", newExecTime); // double newEnergyRatio = this->model.get_energy()/oldEnergy; if( ratio > 1.0 ) { retVal.first = curMetricCentroid*(1.0/modifier); retVal.second = curMetricCentroid*ratio*modifier; } else { retVal.first = curMetricCentroid*ratio*(1.0/modifier); retVal.second = curMetricCentroid*modifier; } } else THROW_EXCEPTION(metric << " Unrecognized metric"); if( retVal.second < 0 || retVal.first < 0 ) THROW_EXCEPTION( this->pluginName+" has negative value ("+boost::lexical_cast<std::string>(retVal.first)+","+boost::lexical_cast<std::string>(retVal.second)+")"); return retVal; }
// -------------------------------------------------------------------------- // // Function // Name: ReadLoggingStream::Close() // Purpose: Closes the underlying stream (not needed) // Created: 2003/07/31 // // -------------------------------------------------------------------------- void ReadLoggingStream::Close() { THROW_EXCEPTION(CommonException, NotSupported); }
Index TripletHelper::GetNumberEntries(const Matrix& matrix) { const Matrix* mptr = &matrix; const GenTMatrix* gent = dynamic_cast<const GenTMatrix*>(mptr); if (gent) { return gent->Nonzeros(); } const SymTMatrix* symt = dynamic_cast<const SymTMatrix*>(mptr); if (symt) { return symt->Nonzeros(); } const ScaledMatrix* scaled = dynamic_cast<const ScaledMatrix*>(mptr); if (scaled) { return GetNumberEntries(*GetRawPtr(scaled->GetUnscaledMatrix())); } const SymScaledMatrix* symscaled = dynamic_cast<const SymScaledMatrix*>(mptr); if (symscaled) { return GetNumberEntries(*GetRawPtr(symscaled->GetUnscaledMatrix())); } const DiagMatrix* diag = dynamic_cast<const DiagMatrix*>(mptr); if (diag) { return diag->Dim(); } const IdentityMatrix* ident = dynamic_cast<const IdentityMatrix*>(mptr); if (ident) { return ident->Dim(); } const ExpansionMatrix* exp = dynamic_cast<const ExpansionMatrix*>(mptr); if (exp) { return exp->NCols(); } const SumMatrix* sum = dynamic_cast<const SumMatrix*>(mptr); if (sum) { return GetNumberEntries_(*sum); } const SumSymMatrix* sumsym = dynamic_cast<const SumSymMatrix*>(mptr); if (sumsym) { return GetNumberEntries_(*sumsym); } const ZeroMatrix* zero = dynamic_cast<const ZeroMatrix*>(mptr); if (zero) { return 0; } const CompoundMatrix* cmpd = dynamic_cast<const CompoundMatrix*>(mptr); if (cmpd) { return GetNumberEntries_(*cmpd); } const CompoundSymMatrix* cmpd_sym = dynamic_cast<const CompoundSymMatrix*>(mptr); if (cmpd_sym) { return GetNumberEntries_(*cmpd_sym); } THROW_EXCEPTION(UNKNOWN_MATRIX_TYPE,"Unknown matrix type passed to TripletHelper::GetNumberEntries"); }
// -------------------------------------------------------------------------- // // Function // Name: ReadLoggingStream::Write(void *, int) // Purpose: Writes bytes to the underlying stream (not supported) // Created: 2003/07/31 // // -------------------------------------------------------------------------- void ReadLoggingStream::Write(const void *pBuffer, int NBytes, int Timeout) { THROW_EXCEPTION(CommonException, NotSupported); }
static int translate_type(JNIEnv *e, int t){ jfieldID fid; jclass constants = (*e)->FindClass(e,CONSTANTS_CLASS); if(constants == NULL){ info("[V4L4J] Error looking up the V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the V4L4JConstants class"); return -1; } if(t == V4L2_CTRL_TYPE_BUTTON){ fid = (*e)->GetStaticFieldID(e, constants, "CTRL_TYPE_BUTTON", "I"); if(fid == NULL){ info( "[V4L4J] Error looking up the BUTTON field in V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the BUTTON field in V4L4JConstants class"); return -1; } } else if(t == V4L2_CTRL_TYPE_BOOLEAN){ fid = (*e)->GetStaticFieldID(e, constants, "CTRL_TYPE_SWITCH", "I"); if(fid == NULL){ info("[V4L4J] Error looking up the SWITCH field in V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the SWITCH field in V4L4JConstants class"); return -1; } } else if(t == V4L2_CTRL_TYPE_INTEGER){ fid = (*e)->GetStaticFieldID(e, constants, "CTRL_TYPE_SLIDER", "I"); if(fid == NULL){ info("[V4L4J] Error looking up the SLIDER field in V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the SLIDER field in V4L4JConstants class"); return -1; } } else if((t == V4L2_CTRL_TYPE_MENU) || (t == V4L2_CTRL_TYPE_INTEGER_MENU)){ fid = (*e)->GetStaticFieldID(e, constants, "CTRL_TYPE_DISCRETE", "I"); if(fid == NULL){ info( "[V4L4J] Error looking up the DISCRETE field in V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the DISCRETE field in V4L4JConstants class"); return -1; } } else if(t == V4L2_CTRL_TYPE_STRING){ fid = (*e)->GetStaticFieldID(e, constants, "CTRL_TYPE_STRING", "I"); if(fid == NULL){ info( "[V4L4J] Error looking up the STRING field in V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the STRING field in V4L4JConstants class"); return -1; } } else if(t == V4L2_CTRL_TYPE_INTEGER64){ fid = (*e)->GetStaticFieldID(e, constants, "CTRL_TYPE_LONG", "I"); if(fid == NULL){ info("[V4L4J] Error looking up the CTRL_TYPE_LONG field in V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the CTRL_TYPE_LONG field in V4L4JConstants class"); return -1; } } else if(t == V4L2_CTRL_TYPE_BITMASK){ fid = (*e)->GetStaticFieldID(e, constants, "CTRL_TYPE_BITMASK", "I"); if(fid == NULL){ info("[V4L4J] Error looking up the CTRL_TYPE_BITMASK field in V4L4JConstants class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up the CTRL_TYPE_BITMASK field in V4L4JConstants class"); return -1; } } else { info("[V4L4J] Unknown control type: %d\n", t); THROW_EXCEPTION(e, JNI_EXCP, "Unknown control type: %d\n", t); return -1; } return (*e)->GetStaticIntField(e, constants, fid); }
/****************************************************************************** * * function: maximallyFlat * * purpose: Calculates coefficients for a linear phase lowpass FIR * filter, with beta being the center frequency of the * transition band (as a fraction of the sampling * frequency), and gamme the width of the transition * band. * ******************************************************************************/ int FIRFilter::maximallyFlat(double beta, double gamma, int* np, double* coefficient) { double a[LIMIT + 1], c[LIMIT + 1], betaMinimum, ac; int nt, numerator, n, ll, i; /* INITIALIZE NUMBER OF POINTS */ *np = 0; /* CUT-OFF FREQUENCY MUST BE BETWEEN 0 HZ AND NYQUIST */ if ((beta <= 0.0) || (beta >= 0.5)) { THROW_EXCEPTION(TRMException, "Beta out of range."); } /* TRANSITION BAND MUST FIT WITH THE STOP BAND */ betaMinimum = ((2.0 * beta) < (1.0 - 2.0 * beta)) ? (2.0 * beta) : (1.0 - 2.0 * beta); if ((gamma <= 0.0) || (gamma >= betaMinimum)) { THROW_EXCEPTION(TRMException, "Gamma out of range."); } /* MAKE SURE TRANSITION BAND NOT TOO SMALL */ nt = (int) (1.0 / (4.0 * gamma * gamma)); if (nt > 160) { THROW_EXCEPTION(TRMException, "Gamma too small."); } /* CALCULATE THE RATIONAL APPROXIMATION TO THE CUT-OFF POINT */ ac = (1.0 + cos((2.0 * M_PI) * beta)) / 2.0; rationalApproximation(ac, &nt, &numerator, np); /* CALCULATE FILTER ORDER */ n = (2 * (*np)) - 1; if (numerator == 0) { numerator = 1; } /* COMPUTE MAGNITUDE AT NP POINTS */ c[1] = a[1] = 1.0; ll = nt - numerator; for (i = 2; i <= *np; i++) { int j; double x, sum = 1.0, y; c[i] = cos((2.0 * M_PI) * ((double) (i - 1) / (double) n)); x = (1.0 - c[i]) / 2.0; y = x; if (numerator == nt) { continue; } for (j = 1; j <= ll; j++) { double z = y; if (numerator != 1) { int jj; for (jj = 1; jj <= (numerator - 1); jj++) { z *= 1.0 + ((double) j / (double) jj); } } y *= x; sum += z; } a[i] = sum * pow((1.0 - x), numerator); } /* CALCULATE WEIGHTING COEFFICIENTS BY AN N-POINT IDFT */ for (i = 1; i <= *np; i++) { int j; coefficient[i] = a[1] / 2.0; for (j = 2; j <= *np; j++) { int m = ((i - 1) * (j - 1)) % n; if (m > nt) { m = n - m; } coefficient[i] += c[m+1] * a[j]; } coefficient[i] *= 2.0 / (double) n; } return 0; }
bool MonotoneMuUpdate::UpdateBarrierParameter() { Number mu = IpData().curr_mu(); Number tau = IpData().curr_tau(); Number sub_problem_error = IpCq().curr_barrier_error(); Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE, "Optimality Error for Barrier Sub-problem = %e\n", sub_problem_error); Number kappa_eps_mu = barrier_tol_factor_ * mu; bool done = false; bool tiny_step_flag = IpData().tiny_step_flag(); IpData().Set_tiny_step_flag(false); while ((sub_problem_error <= kappa_eps_mu || tiny_step_flag) && !done && !first_iter_resto_) { Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE, " sub_problem_error < kappa_eps * mu (%e)\n", kappa_eps_mu); // Compute the new values for mu and tau Number new_mu; Number new_tau; Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE, "Updating mu=%25.16e and tau=%25.16e to ", mu, tau); CalcNewMuAndTau(new_mu, new_tau); Jnlst().Printf(J_DETAILED, J_BARRIER_UPDATE, "new_mu=%25.16e and new_tau=%25.16e\n", new_mu, new_tau); bool mu_changed = (mu != new_mu); if (!mu_changed && tiny_step_flag) { THROW_EXCEPTION(TINY_STEP_DETECTED, "Problem solved to best possible numerical accuracy"); } // Set the new values for mu and tau IpData().Set_mu(new_mu); IpData().Set_tau(new_tau); mu = new_mu; tau = new_tau; // If this is the first iteration or if // mu_allow_fast_monotone_decrease_ is true, we want to check if // we can decrease mu even more if (initialized_ && !mu_allow_fast_monotone_decrease_) { done = true; } else if (!mu_changed) { done = true; } else { sub_problem_error = IpCq().curr_barrier_error(); kappa_eps_mu = barrier_tol_factor_ * mu; done = (sub_problem_error > kappa_eps_mu); } // Reset the line search if (done && mu_changed) { linesearch_->Reset(); } tiny_step_flag = false; } first_iter_resto_ = false; initialized_ = true; return true; }
bool PardisoSolverInterface::InitializeImpl(const OptionsList& options, const std::string& prefix) { Index enum_int; options.GetEnumValue("pardiso_matching_strategy", enum_int, prefix); match_strat_ = PardisoMatchingStrategy(enum_int); options.GetBoolValue("pardiso_redo_symbolic_fact_only_if_inertia_wrong", pardiso_redo_symbolic_fact_only_if_inertia_wrong_, prefix); options.GetBoolValue("pardiso_repeated_perturbation_means_singular", pardiso_repeated_perturbation_means_singular_, prefix); //Index pardiso_out_of_core_power; //options.GetIntegerValue("pardiso_out_of_core_power", // pardiso_out_of_core_power, prefix); options.GetBoolValue("pardiso_skip_inertia_check", skip_inertia_check_, prefix); int pardiso_msglvl; options.GetIntegerValue("pardiso_msglvl", pardiso_msglvl, prefix); int max_iterref_steps; options.GetIntegerValue("pardiso_max_iterative_refinement_steps", max_iterref_steps, prefix); int order; options.GetEnumValue("pardiso_order", order, prefix); #if !defined(HAVE_PARDISO_OLDINTERFACE) && !defined(HAVE_PARDISO_MKL) options.GetBoolValue("pardiso_iterative", pardiso_iterative_, prefix); int pardiso_max_iter; options.GetIntegerValue("pardiso_max_iter", pardiso_max_iter, prefix); Number pardiso_iter_relative_tol; options.GetNumericValue("pardiso_iter_relative_tol", pardiso_iter_relative_tol, prefix); Index pardiso_iter_coarse_size; options.GetIntegerValue("pardiso_iter_coarse_size", pardiso_iter_coarse_size, prefix); Index pardiso_iter_max_levels; options.GetIntegerValue("pardiso_iter_max_levels", pardiso_iter_max_levels, prefix); Number pardiso_iter_dropping_factor; options.GetNumericValue("pardiso_iter_dropping_factor", pardiso_iter_dropping_factor, prefix); Number pardiso_iter_dropping_schur; options.GetNumericValue("pardiso_iter_dropping_schur", pardiso_iter_dropping_schur, prefix); Index pardiso_iter_max_row_fill; options.GetIntegerValue("pardiso_iter_max_row_fill", pardiso_iter_max_row_fill, prefix); Number pardiso_iter_inverse_norm_factor; options.GetNumericValue("pardiso_iter_inverse_norm_factor", pardiso_iter_inverse_norm_factor, prefix); options.GetIntegerValue("pardiso_max_droptol_corrections", pardiso_max_droptol_corrections_, prefix); #else pardiso_iterative_ = false; #endif // Number value = 0.0; // Tell Pardiso to release all memory if it had been used before if (initialized_) { ipfint PHASE = -1; ipfint N = dim_; ipfint NRHS = 0; ipfint ERROR; ipfint idmy; double ddmy; PARDISO_FUNC(PT_, &MAXFCT_, &MNUM_, &MTYPE_, &PHASE, &N, &ddmy, &idmy, &idmy, &idmy, &NRHS, IPARM_, &MSGLVL_, &ddmy, &ddmy, &ERROR, DPARM_); DBG_ASSERT(ERROR==0); } // Reset all private data dim_=0; nonzeros_=0; have_symbolic_factorization_=false; initialized_=false; delete[] a_; a_ = NULL; #ifdef PARDISO_MATCHING_PREPROCESS delete[] ia2; ia2 = NULL; delete[] ja2; ja2 = NULL; delete[] a2_; a2_ = NULL; delete[] perm2; perm2 = NULL; delete[] scale2; scale2 = NULL; #endif // Call Pardiso's initialization routine IPARM_[0] = 0; // Tell it to fill IPARM with default values(?) #if ! defined(HAVE_PARDISO_OLDINTERFACE) && ! defined(HAVE_PARDISO_MKL) ipfint ERROR = 0; ipfint SOLVER = 0; // initialize only direct solver PARDISOINIT_FUNC(PT_, &MTYPE_, &SOLVER, IPARM_, DPARM_, &ERROR); #else PARDISOINIT_FUNC(PT_, &MTYPE_, IPARM_); #endif // Set some parameters for Pardiso IPARM_[0] = 1; // Don't use the default values int num_procs = 1; #if defined(HAVE_PARDISO_PARALLEL) || ! defined(HAVE_PARDISO) // Obtain the numbers of processors from the value of OMP_NUM_THREADS char* var = getenv("OMP_NUM_THREADS"); if (var != NULL) { sscanf( var, "%d", &num_procs ); if (num_procs < 1) { Jnlst().Printf(J_ERROR, J_LINEAR_ALGEBRA, "Invalid value for OMP_NUM_THREADS (\"%s\").\n", var); return false; } Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA, "Using environment OMP_NUM_THREADS = %d as the number of processors for PARDISO.\n", num_procs); } #if defined(HAVE_PARDISO) && ! defined(HAVE_PARDISO_MKL) // If we run Pardiso through the linear solver loader, // we do not know whether it is the parallel version, so we do not report a warning if OMP_NUM_THREADS is not set. // If we run Pardiso from MKL, then OMP_NUM_THREADS does not need to be set, so no warning. else { Jnlst().Printf(J_WARNING, J_LINEAR_ALGEBRA, "You should set the environment variable OMP_NUM_THREADS to the number of processors used in Pardiso (e.g., 1).\n\n"); } #endif #endif #ifdef HAVE_PARDISO_MKL IPARM_[1] = order; // For MKL PARDSIO, the documentation says, "iparm(3) Reserved. Set to zero.", so we don't set IPARM_[2] IPARM_[5] = 1; // Overwrite right-hand side IPARM_[7] = max_iterref_steps; IPARM_[9] = 12; // pivot perturbation (as higher as less perturbation) IPARM_[10] = 2; // enable scaling (recommended for interior-point indefinite matrices) IPARM_[12] = (int)match_strat_; // enable matching (recommended, as above) IPARM_[20] = 3; // bunch-kaufman pivoting IPARM_[23] = 1; // parallel fac IPARM_[24] = 1; // parallel solve //IPARM_[26] = 1; // matrix checker #else IPARM_[1] = order; IPARM_[2] = num_procs; // Set the number of processors IPARM_[5] = 1; // Overwrite right-hand side IPARM_[7] = max_iterref_steps; // Options suggested by Olaf Schenk IPARM_[9] = 12; IPARM_[10] = 2; // Results in better scaling // Matching information: IPARM_[12] = 1 seems ok, but results in a // large number of pivot perturbation // Matching information: IPARM_[12] = 2 robust, but more expensive method IPARM_[12] = (int)match_strat_; IPARM_[20] = 3; // Results in better accuracy IPARM_[23] = 1; // parallel fac IPARM_[24] = 1; // parallel solve IPARM_[28] = 0; // 32-bit factorization IPARM_[29] = 1; //we need this for IPOPT interface //IPARM_[33] = 1; // bit-by-bit identical results in parallel run #endif Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA, "Pardiso matrix ordering (IPARM(2)): %d\n", IPARM_[1]); Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA, "Pardiso max. iterref. steps (IPARM(8)): %d\n", IPARM_[7]); Jnlst().Printf(J_DETAILED, J_LINEAR_ALGEBRA, "Pardiso matching strategy (IPARM(13)): %d\n", IPARM_[12]); if (pardiso_iterative_) { #if defined(HAVE_PARDISO_OLDINTERFACE) || defined(HAVE_PARDISO_MKL) THROW_EXCEPTION(OPTION_INVALID, "You chose to use the iterative version of Pardiso, but you need to use a Pardiso version of at least 4.0."); #else IPARM_[31] = 1 ; // active direct solver DPARM_[ 0] = pardiso_max_iter; // maximum number of Krylov-Subspace Iteration // Default is 300 // 1 <= value <= e.g. 1000 DPARM_[ 1] = pardiso_iter_relative_tol; // Relative Residual Convergence // e.g. pardiso_iter_tol // Default is 1e-6 // 1e-16 <= value < 1 DPARM_[ 2] = pardiso_iter_coarse_size; // Maximum Size of Coarse Grid Matrix // e.g. pardiso_coarse_grid // Default is 5000 // 1 <= value < number of equations DPARM_[ 3] = pardiso_iter_max_levels; // Maximum Number of Grid Levels // e.g. pardiso_max_grid // Default is 10000 // 1 <= value < number of equations DPARM_[ 4] = pardiso_iter_dropping_factor; // dropping value for incomplete factor // e.g. pardiso_dropping_factor // Default is 0.5 // 1e-16 <= value < 1 DPARM_[ 5] = pardiso_iter_dropping_schur; // dropping value for sparsify schur complementfactor // e.g. pardiso_dropping_schur // Default is 0.1 // 1e-16 <= value < 1 DPARM_[ 6] = pardiso_iter_max_row_fill; // max fill for each row // e.g. pardiso_max_fill // Default is 1000 // 1 <= value < 100000 DPARM_[ 7] = pardiso_iter_inverse_norm_factor; // dropping value for sparsify schur complementfactor // e.g. pardiso_inverse_norm_factor // Default is 500 // 2 <= value < 50000 DPARM_[ 8] = 25; // maximum number of non-improvement steps #endif } MSGLVL_ = pardiso_msglvl; // Option for the out of core variant //IPARM_[49] = pardiso_out_of_core_power; return true; }
//============================================================================= // METHOD : SPELLwsWarmStartImpl::restoreState() //============================================================================= PyFrameObject* SPELLwsWarmStartImpl::restoreState() { DEBUG("[WS] Restoring state ========================================"); // We need a separate scope so that we can invoke saveState at the end without deadlock { std::cerr << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << std::endl; std::cerr << "RESTORE STATE START" << std::endl; std::cerr << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << std::endl; // Synchronize so that nothing can be done while saving SPELLmonitor m(m_lock); SPELLsafePythonOperations ops("SPELLwsWarmStartImpl::restoreState()"); // Create a fresh thread state PyThreadState* tstate = PyThreadState_Get(); DEBUG("[WS] Restoring interpreter parameters"); tstate->recursion_depth = m_storage->loadLong(); DEBUG(" - Recursion depth : " + ISTR(tstate->recursion_depth)); tstate->tick_counter = m_storage->loadLong(); DEBUG(" - Tcik counter : " + ISTR(tstate->tick_counter)); tstate->gilstate_counter = m_storage->loadLong(); DEBUG(" - GIL counter : " + ISTR(tstate->gilstate_counter)); int numFrames = m_storage->loadLong(); DEBUG(" - Number of frames: " + ISTR(numFrames)); if (numFrames < 0) { THROW_EXCEPTION("Unable to restore state", "Failed to restore interpreter parameters", SPELL_ERROR_WSTART); } DEBUG("[WS] Restoring frames"); m_frames.clear(); m_recursionDepth = 0; // Restore the frames now. Consider that the top frame is already there // Use the originally created frame to copy globals PyFrameObject* prevFrame = NULL; for( int count = 0; count < numFrames; count++ ) { DEBUG("[WS] Restoring frame " + ISTR(count)); // In recursion depth zero, use the original frame // to copy the globals from DEBUG("[WS] X00"); PyObject* id = m_storage->loadObject(); DEBUG("[WS] X01"); std::string frameId = PYSSTR(id); DEBUG("[WS] Frame identifier: " + frameId); m_topFrame = new SPELLwsFrame( frameId, m_startup, m_frames.size(), prevFrame ); DEBUG("[WS] X1"); m_frames.push_back(m_topFrame); // For the head frame, store its address in the interpreter thread state if (m_recursionDepth == 0) { if (tstate->frame) delete tstate->frame; tstate->frame = m_topFrame->getFrameObject(); } DEBUG("[WS] X2"); m_recursionDepth++; prevFrame = m_topFrame->getFrameObject(); DEBUG("[WS] X3"); } // Update the recursion depth tstate->recursion_depth = m_recursionDepth; DEBUG("[WS] Checking errors"); SPELLpythonHelper::instance().checkError(); DEBUG("[WS] Switching to save state mode"); // Reset the storage now, to mode write delete m_storage; m_storage = new SPELLwsStorage( m_persistentFile, SPELLwsStorage::MODE_WRITE ); std::cerr << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << std::endl; std::cerr << "RESTORE STATE END" << std::endl; std::cerr << "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" << std::endl; } // Re-save the current state, so that the new persistent files are ok saveState(); DEBUG("[WS] Checking errors"); SPELLpythonHelper::instance().checkError(); // Reset values m_startup.recoveryFile = ""; m_startup.performRecovery = false; DEBUG("[WS] State recovered ==========================================="); return m_topFrame->getFrameObject(); }
bool OptionsList::GetNumericValue(const std::string& tag, Number& value, const std::string& prefix) const { SmartPtr<const RegisteredOption> option = NULL; if (IsValid(reg_options_)) { option = reg_options_->GetOption(tag); if (IsNull(option)) { std::string msg = "IPOPT tried to get the value of Option: " + tag; msg += ". It is not a valid registered option."; THROW_EXCEPTION(OPTION_INVALID, msg); } if (option->Type() != OT_Number) { std::string msg = "IPOPT tried to get the value of Option: " + tag; msg += ". It is a valid option, but it is of type "; if (option->Type() == OT_Integer) { msg += " Integer"; } else if (option->Type() == OT_String) { msg += " String"; } else { msg += " Unknown"; } msg += ", not of type Number. Please check the documentation for options."; if (IsValid(jnlst_)) { option->OutputDescription(*jnlst_); } THROW_EXCEPTION(OPTION_INVALID, msg); } } std::string strvalue; if (find_tag(tag, prefix, strvalue)) { // Some people like to use 'd' instead of 'e' in floating point // numbers. Therefore, we change a 'd' to an 'e' char* buffer = new char[strvalue.length()+1]; strcpy(buffer, strvalue.c_str()); for (int i=0; i<(int)strvalue.length(); ++i) { if (buffer[i]=='d' || buffer[i]=='D') { buffer[i] = 'e'; } } char* p_end; Number retval = strtod(buffer, &p_end); if (*p_end!='\0' && !isspace(*p_end)) { delete [] buffer; std::string msg = "Option \"" + tag + "\": Double value expected, but non-numeric value \"" + strvalue+"\" found.\n"; THROW_EXCEPTION(OPTION_INVALID, msg); } delete [] buffer; value = retval; return true; } else if (IsValid(option)) { value = option->DefaultNumber(); return false; } return false; }
/* * populate the stepwiseInterval member with stepwise frame size * for a given frame size struct * (0: struct frame_size_discrete, 1: struct frame_size_continuous (min res), * 2: struct frame_size_continuous(max res) ) */ JNIEXPORT void JNICALL Java_au_edu_jcu_v4l4j_FrameInterval_doGetContinuous( JNIEnv *e, jobject t, jint type, jlong o) { struct frame_intv_continuous *d; jclass this_class, stepwise_intv_class; jmethodID ctor; jfieldID fid; jobject stepwise; dprint(LOG_CALLS, "[CALL] Entering %s\n",__PRETTY_FUNCTION__); //get our pointer to struct frame_intv_continuous if((d=get_continuous(o, type)) == NULL){ THROW_EXCEPTION(e, JNI_EXCP, "Error looking up frame intervals"); return; } /* Get handles on Java stuff */ this_class = (*e)->GetObjectClass(e, t); if(this_class == NULL){ info("[V4L4J] Error looking up the FrameInterval class\n"); THROW_EXCEPTION(e, JNI_EXCP, "Error looking up FrameInterval class"); return; } stepwise_intv_class = (*e)->FindClass(e, "au/edu/jcu/v4l4j/FrameInterval$StepwiseInterval"); if(stepwise_intv_class == NULL){ info("[V4L4J] Error looking up the StepwiseInterval class\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up StepwiseInterval class"); return; } ctor = (*e)->GetMethodID(e, stepwise_intv_class, "<init>", "(IIIIII)V"); if(ctor == NULL){ info("[V4L4J] Error looking up the ctor of StepwiseInterval class\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up the ctor of StepwiseInterval class"); return; } //create StepwiseInterval object stepwise = (*e)->NewObject(e, stepwise_intv_class, ctor, d->min.numerator, d->min.denominator, d->max.numerator, d->max.denominator, d->step.numerator, d->step.denominator); if(stepwise == NULL){ info("[V4L4J] Error creating StepwiseInterval object\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error creating StepwiseInterval object"); return; } //assign it to the stepwiseInterval member fid = (*e)->GetFieldID(e, this_class, "stepwiseInterval", "Lau/edu/jcu/v4l4j/FrameInterval$StepwiseInterval"); if(fid == NULL){ info("[V4L4J] Error looking up the StepwiseInterval fieldID\n"); THROW_EXCEPTION(e, JNI_EXCP, \ "Error looking up the StepwiseInterval fieldID"); return; } (*e)->SetObjectField(e, t, fid, stepwise); dprint(LOG_V4L4J, "[V4L4J] Stepwise frame interval: min:%d/%d max:%d/%d step:%d/%d\n", d->min.numerator, d->min.denominator, d->max.numerator, d->max.denominator, d->step.numerator, d->step.denominator); }
//============================================================================= // METHOD: SPELLdatabaseFileSPB::load() //============================================================================= void SPELLdatabaseFileSPB::load() { std::ifstream file; std::string filename = getFilename(); file.open( filename.c_str(), std::ios::in ); if (!file.is_open()) { filename = getFilename() + "." + SPELLutils::toLower(getExtension()); DEBUG("[SDBF] Second try: " + filename); file.open( filename.c_str(), std::ios::in ); if (!file.is_open()) { filename = getFilename() + "." + SPELLutils::toUpper(getExtension()); DEBUG("[SDBF] Third try: " + filename); file.open( filename.c_str(), std::ios::in ); if (!file.is_open()) { THROW_EXCEPTION("Cannot load database", "Cannot open file '" + getFilename() + "'", SPELL_ERROR_FILESYSTEM); } } } std::vector<std::string> lines; while(!file.eof()) { std::string line = ""; std::getline(file,line); lines.push_back(line); } file.close(); std::vector<std::string>::iterator it; for( it = lines.begin(); it != lines.end(); it++) { std::string lineToProcess = *it; // Remove spaces SPELLutils::trim(lineToProcess); // Process only lines starting with $, and having := if ((lineToProcess.find("$")!=0)||(lineToProcess.find(":=")==std::string::npos)) { continue; } // Replace tabs SPELLutils::replace(lineToProcess,"\t"," "); // Remove \r SPELLutils::replace(lineToProcess,"\n",""); SPELLutils::replace(lineToProcess,"\r",""); // Now process line data int idx = lineToProcess.find(":="); std::string key = lineToProcess.substr(0,idx); idx += 2; std::string origValue = lineToProcess.substr(idx,lineToProcess.size()-idx); SPELLutils::trim(key); SPELLutils::trim(origValue); // Post-process value if (matchesShortDate(origValue)) { // Convert SPB short dates to SPELL short dates origValue = "+" + origValue; } PyObject* value = NULL; //std::string vtype = ""; value = importValue(origValue); std::string format = ""; if (PyLong_Check(value) || PyInt_Check(value)) { if (origValue.find("0x") == 0) { format = LanguageConstants::HEX; } else if (origValue.find("0b") == 0) { format = LanguageConstants::BIN; } else if (origValue.find("0") == 0 && origValue != "0") { format = LanguageConstants::OCT; } } if (value != NULL) { SPELLdatabase::set( SSTRPY(key), value, format ); //TODO if types needed to commit: m_types.insert( std::make_pair(key,vtype)); } } }