static void ns87415_set_mode(struct ata_port *ap, struct ata_device *adev, u8 mode) { struct pci_dev *dev = to_pci_dev(ap->host->dev); int unit = 2 * ap->port_no + adev->devno; int timing = 0x44 + 2 * unit; unsigned long T = 1000000000 / 33333; /* PCI clocks */ struct ata_timing t; u16 clocking; u8 iordy; u8 status; /* Timing register format is 17 - low nybble read timing with the high nybble being 16 - x for recovery time in PCI clocks */ ata_timing_compute(adev, adev->pio_mode, &t, T, 0); clocking = 17 - FIT(t.active, 2, 17); clocking |= (16 - FIT(t.recover, 1, 16)) << 4; /* Use the same timing for read and write bytes */ clocking |= (clocking << 8); pci_write_config_word(dev, timing, clocking); /* Set the IORDY enable versus DMA enable on or off properly */ pci_read_config_byte(dev, 0x42, &iordy); iordy &= ~(1 << (4 + unit)); if (mode >= XFER_MW_DMA_0 || !ata_pio_need_iordy(adev)) iordy |= (1 << (4 + unit)); /* Paranoia: We shouldn't ever get here with busy write buffers but if so wait */ pci_read_config_byte(dev, 0x43, &status); while (status & 0x03) { udelay(1); pci_read_config_byte(dev, 0x43, &status); } /* Flip the IORDY/DMA bits now we are sure the write buffers are clear */ pci_write_config_byte(dev, 0x42, iordy); /* TODO: Set byte 54 command timing to the best 8bit mode shared by all four devices */ }
static void ns87410_set_piomode(struct ata_port *ap, struct ata_device *adev) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); int port = 0x40 + 4 * ap->port_no; u8 idetcr, idefr; struct ata_timing at; static const u8 activebits[15] = { 0, 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7 }; static const u8 recoverbits[12] = { 0, 1, 2, 3, 4, 5, 6, 6, 7, 7, 7, 7 }; pci_read_config_byte(pdev, port + 3, &idefr); if (ata_pio_need_iordy(adev)) idefr |= 0x04; /* IORDY enable */ else idefr &= ~0x04; if (ata_timing_compute(adev, adev->pio_mode, &at, 30303, 1) < 0) { dev_printk(KERN_ERR, &pdev->dev, "unknown mode %d.\n", adev->pio_mode); return; } at.active = FIT(at.active, 2, 16) - 2; at.setup = FIT(at.setup, 1, 4) - 1; at.recover = FIT(at.recover, 1, 12) - 1; idetcr = (at.setup << 6) | (recoverbits[at.recover] << 3) | activebits[at.active]; pci_write_config_byte(pdev, port, idetcr); pci_write_config_byte(pdev, port + 3, idefr); /* We use ap->private_data as a pointer to the device currently loaded for timing */ ap->private_data = adev; }
// status functions static void print_state( const size_t iter , gsl_multifit_fdfsolver *s , const int NPARAMS ) { int i ; printf ("\niter: %lu \n" , iter ) ; for( i = 0 ; i < NPARAMS ; i++ ) { printf( "param[%d] %15.8f \n" , i , FIT(i) ) ; } printf( "|f(x)| = %e\n\n" , gsl_blas_dnrm2( s->f ) ) ; return ; }
static void cy82c693_set_piomode(struct ata_port *ap, struct ata_device *adev) { struct pci_dev *pdev = to_pci_dev(ap->host->dev); struct ata_timing t; const unsigned long T = 1000000 / 33; short time_16, time_8; u32 addr; if (ata_timing_compute(adev, adev->pio_mode, &t, T, 1) < 0) { printk(KERN_ERR DRV_NAME ": mome computation failed.\n"); return; } time_16 = FIT(t.recover, 0, 15) | (FIT(t.active, 0, 15) << 4); time_8 = FIT(t.act8b, 0, 15) | (FIT(t.rec8b, 0, 15) << 4); if (adev->devno == 0) { pci_read_config_dword(pdev, CY82_IDE_ADDRSETUP, &addr); addr &= ~0x0F; /* Mask bits */ addr |= FIT(t.setup, 0, 15); pci_write_config_dword(pdev, CY82_IDE_ADDRSETUP, addr); pci_write_config_byte(pdev, CY82_IDE_MASTER_IOR, time_16); pci_write_config_byte(pdev, CY82_IDE_MASTER_IOW, time_16); pci_write_config_byte(pdev, CY82_IDE_MASTER_8BIT, time_8); } else { pci_read_config_dword(pdev, CY82_IDE_ADDRSETUP, &addr); addr &= ~0xF0; /* Mask bits */ addr |= (FIT(t.setup, 0, 15) << 4); pci_write_config_dword(pdev, CY82_IDE_ADDRSETUP, addr); pci_write_config_byte(pdev, CY82_IDE_SLAVE_IOR, time_16); pci_write_config_byte(pdev, CY82_IDE_SLAVE_IOW, time_16); pci_write_config_byte(pdev, CY82_IDE_SLAVE_8BIT, time_8); } }
int main (void) { const gsl_multifit_fdfsolver_type *T = gsl_multifit_fdfsolver_lmsder; gsl_multifit_fdfsolver *s; int status, info; size_t i; const size_t n = N; const size_t p = 3; gsl_matrix *J = gsl_matrix_alloc(n, p); gsl_matrix *covar = gsl_matrix_alloc (p, p); double y[N], weights[N]; struct data d = { n, y }; gsl_multifit_function_fdf f; double x_init[3] = { 1.0, 0.0, 0.0 }; gsl_vector_view x = gsl_vector_view_array (x_init, p); gsl_vector_view w = gsl_vector_view_array(weights, n); const gsl_rng_type * type; gsl_rng * r; gsl_vector *res_f; double chi, chi0; const double xtol = 1e-8; const double gtol = 1e-8; const double ftol = 0.0; gsl_rng_env_setup(); type = gsl_rng_default; r = gsl_rng_alloc (type); f.f = &expb_f; f.df = &expb_df; /* set to NULL for finite-difference Jacobian */ f.n = n; f.p = p; f.params = &d; /* This is the data to be fitted */ for (i = 0; i < n; i++) { double t = i; double yi = 1.0 + 5 * exp (-0.1 * t); double si = 0.1 * yi; double dy = gsl_ran_gaussian(r, si); weights[i] = 1.0 / (si * si); y[i] = yi + dy; printf ("data: %zu %g %g\n", i, y[i], si); }; s = gsl_multifit_fdfsolver_alloc (T, n, p); /* initialize solver with starting point and weights */ gsl_multifit_fdfsolver_wset (s, &f, &x.vector, &w.vector); /* compute initial residual norm */ res_f = gsl_multifit_fdfsolver_residual(s); chi0 = gsl_blas_dnrm2(res_f); /* solve the system with a maximum of 20 iterations */ status = gsl_multifit_fdfsolver_driver(s, 20, xtol, gtol, ftol, &info); gsl_multifit_fdfsolver_jac(s, J); gsl_multifit_covar (J, 0.0, covar); /* compute final residual norm */ chi = gsl_blas_dnrm2(res_f); #define FIT(i) gsl_vector_get(s->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) fprintf(stderr, "summary from method '%s'\n", gsl_multifit_fdfsolver_name(s)); fprintf(stderr, "number of iterations: %zu\n", gsl_multifit_fdfsolver_niter(s)); fprintf(stderr, "function evaluations: %zu\n", f.nevalf); fprintf(stderr, "Jacobian evaluations: %zu\n", f.nevaldf); fprintf(stderr, "reason for stopping: %s\n", (info == 1) ? "small step size" : "small gradient"); fprintf(stderr, "initial |f(x)| = %g\n", chi0); fprintf(stderr, "final |f(x)| = %g\n", chi); { double dof = n - p; double c = GSL_MAX_DBL(1, chi / sqrt(dof)); fprintf(stderr, "chisq/dof = %g\n", pow(chi, 2.0) / dof); fprintf (stderr, "A = %.5f +/- %.5f\n", FIT(0), c*ERR(0)); fprintf (stderr, "lambda = %.5f +/- %.5f\n", FIT(1), c*ERR(1)); fprintf (stderr, "b = %.5f +/- %.5f\n", FIT(2), c*ERR(2)); } fprintf (stderr, "status = %s\n", gsl_strerror (status)); gsl_multifit_fdfsolver_free (s); gsl_matrix_free (covar); gsl_matrix_free (J); gsl_rng_free (r); return 0; }
//------------------------------------------------------------------------------ // findCorrection () : Uses a GSL Levenberg-Marquardt algorithm to fit the lines // in FittedLines to the wavenumbers in the user-specified calibration standard. // The result is the optimal wavenumber correction factor for the uncalibrated // data, which is stored in the class variable WaveCorrection. Information about // the fit residuals are saved by calling calcDiffStats(). // void ListCal::findCorrection () { // Prepare the GSL Solver and associated objects. A non-linear solver is used, // the precise type of which is determined by SOLVER_TYPE, defined in // MgstFcn.h. const size_t NumParameters = 1; const size_t NumLines = FittedLines.size (); double GuessArr [NumParameters]; for (unsigned int i = 0; i < NumParameters; i ++) { GuessArr[i] = WaveCorrection; } const gsl_multifit_fdfsolver_type *SolverType; gsl_multifit_fdfsolver *Solver; gsl_multifit_function_fdf FitFunction; gsl_matrix *Covariance = gsl_matrix_alloc (NumParameters, NumParameters); gsl_vector_view VectorView = gsl_vector_view_array (GuessArr, NumParameters); FitFunction.f = &fitFn; FitFunction.df = &derivFn; FitFunction.fdf = &fitAndDerivFns; FitFunction.n = NumLines; FitFunction.p = NumParameters; FitFunction.params = &FittedLines; SolverType = SOLVER_TYPE; Solver = gsl_multifit_fdfsolver_alloc(SolverType, NumLines, NumParameters); gsl_multifit_fdfsolver_set (Solver, &FitFunction, &VectorView.vector); // Perform the fitting, one iteration at a time until one of the following // conditions is met: The absolute and relative changes in the fit parameters // become smaller than SOLVER_TOL, or the max number of allowed iterations, // SOLVER_MAX_ITERATIONS, is reached. unsigned int Iteration = 0; int Status; do { Iteration ++; Status = gsl_multifit_fdfsolver_iterate (Solver); if (Status) break; Status = gsl_multifit_test_delta (Solver->dx, Solver->x, SOLVER_TOL, SOLVER_TOL); } while (Status == GSL_CONTINUE && Iteration < SOLVER_MAX_ITERATIONS); // Output all the fit parameters with their associated error. gsl_multifit_covar (Solver -> J, 0.0, Covariance); #define FIT(i) gsl_vector_get (Solver -> x, i) #define ERR(i) sqrt (gsl_matrix_get (Covariance, i, i)) double chi = gsl_blas_dnrm2 (Solver -> f); double dof = NumLines - double(NumParameters); double c = chi / sqrt (dof); cout << "Correction factor: " << FIT(0) << " +/- " << c*ERR(0) << " (" << "reduced chi^2 = " << pow(chi, 2) / dof << ", " << "lines fitted = " << NumLines << ", c = " << c << ")" << endl; // Apply the wavenumber correction to all the lines loaded from the // uncalibrated spectrum WaveCorrection = FIT(0); WaveCorrectionError = c*ERR(0); calcDiffStats (); cout << "dSig/Sig Mean Residual: " << DiffMean / LC_DATA_SCALE << ", StdDev: " << DiffStdDev / LC_DATA_SCALE << ", StdErr: " << DiffStdErr / LC_DATA_SCALE << endl; // Clean up the memory and exit gsl_multifit_fdfsolver_free (Solver); gsl_matrix_free (Covariance); }
int main (void) { const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust; gsl_multifit_nlinear_workspace *w; gsl_multifit_nlinear_fdf fdf; gsl_multifit_nlinear_parameters fdf_params = gsl_multifit_nlinear_default_parameters(); const size_t n = N; const size_t p = 3; gsl_vector *f; gsl_matrix *J; gsl_matrix *covar = gsl_matrix_alloc (p, p); double y[N], weights[N]; struct data d = { n, y }; double x_init[3] = { 1.0, 1.0, 0.0 }; /* starting values */ gsl_vector_view x = gsl_vector_view_array (x_init, p); gsl_vector_view wts = gsl_vector_view_array(weights, n); gsl_rng * r; double chisq, chisq0; int status, info; size_t i; const double xtol = 1e-8; const double gtol = 1e-8; const double ftol = 0.0; gsl_rng_env_setup(); r = gsl_rng_alloc(gsl_rng_default); /* define the function to be minimized */ fdf.f = expb_f; fdf.df = expb_df; /* set to NULL for finite-difference Jacobian */ fdf.fvv = NULL; /* not using geodesic acceleration */ fdf.n = n; fdf.p = p; fdf.params = &d; /* this is the data to be fitted */ for (i = 0; i < n; i++) { double t = i; double yi = 1.0 + 5 * exp (-0.1 * t); double si = 0.1 * yi; double dy = gsl_ran_gaussian(r, si); weights[i] = 1.0 / (si * si); y[i] = yi + dy; printf ("data: "F_ZU" %g %g\n", i, y[i], si); }; /* allocate workspace with default parameters */ w = gsl_multifit_nlinear_alloc (T, &fdf_params, n, p); /* initialize solver with starting point and weights */ gsl_multifit_nlinear_winit (&x.vector, &wts.vector, &fdf, w); /* compute initial cost function */ f = gsl_multifit_nlinear_residual(w); gsl_blas_ddot(f, f, &chisq0); /* solve the system with a maximum of 20 iterations */ status = gsl_multifit_nlinear_driver(20, xtol, gtol, ftol, callback, NULL, &info, w); /* compute covariance of best fit parameters */ J = gsl_multifit_nlinear_jac(w); gsl_multifit_nlinear_covar (J, 0.0, covar); /* compute final cost */ gsl_blas_ddot(f, f, &chisq); #define FIT(i) gsl_vector_get(w->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) fprintf(stderr, "summary from method '%s/%s'\n", gsl_multifit_nlinear_name(w), gsl_multifit_nlinear_trs_name(w)); fprintf(stderr, "number of iterations: "F_ZU"\n", gsl_multifit_nlinear_niter(w)); fprintf(stderr, "function evaluations: "F_ZU"\n", fdf.nevalf); fprintf(stderr, "Jacobian evaluations: "F_ZU"\n", fdf.nevaldf); fprintf(stderr, "reason for stopping: %s\n", (info == 1) ? "small step size" : "small gradient"); fprintf(stderr, "initial |f(x)| = %f\n", sqrt(chisq0)); fprintf(stderr, "final |f(x)| = %f\n", sqrt(chisq)); { double dof = n - p; double c = GSL_MAX_DBL(1, sqrt(chisq / dof)); fprintf(stderr, "chisq/dof = %g\n", chisq / dof); fprintf (stderr, "A = %.5f +/- %.5f\n", FIT(0), c*ERR(0)); fprintf (stderr, "lambda = %.5f +/- %.5f\n", FIT(1), c*ERR(1)); fprintf (stderr, "b = %.5f +/- %.5f\n", FIT(2), c*ERR(2)); } fprintf (stderr, "status = %s\n", gsl_strerror (status)); gsl_multifit_nlinear_free (w); gsl_matrix_free (covar); gsl_rng_free (r); return 0; }
int cspl_qrs_fit (void * params) { int status; unsigned int iter; struct cspl_qrs_data * data = (struct cspl_qrs_data *) params; /* This is the data to be fitted */ gsl_multifit_function_fdf f; // const gsl_rng_type * type; // gsl_rng * r; // gsl_rng_env_setup(); // type = gsl_rng_default; // r = gsl_rng_alloc (type); f.f = &cspl_qrs_f; f.df = &cspl_qrs_df; f.fdf = &cspl_qrs_fdf; f.n = data->n; f.p = data->p; f.params = data; gsl_multifit_fdfsolver_set (data->s, &f, &data->x.vector); iter = 0; //print_state (iter, data->s); do { iter++; status = gsl_multifit_fdfsolver_iterate (data->s); #ifdef DEBUG printf ("status = %s\n", gsl_strerror (status)); print_state (iter, data->s); #endif if (status) break; status = gsl_multifit_test_delta (data->s->dx, data->s->x, 1e-12, 1e-12); } while (status == GSL_CONTINUE && iter < 500); gsl_multifit_covar (data->s->J, 0.0, data->covar); double chi = gsl_blas_dnrm2(data->s->f); double dof = data->n - data->p; double c = GSL_MAX_DBL(1, chi / sqrt(dof)); data->c = c; data->chisq_pdof = pow(chi, 2.0) / dof; #ifdef DEBUG #define FIT(i) gsl_vector_get(data->s->x, i) #define ERR(i) sqrt(gsl_matrix_get(data->covar,i,i)) printf("chisq/dof = %g\n", pow(chi, 2.0) / dof); printf ("A = %.5f +/- %.5f\n", FIT(0), c*ERR(0)); printf ("t_beat = %.5f +/- %.5f\n", FIT(1), c*ERR(1)); printf ("S_0 = %.5f +/- %.5f\n", FIT(2), c*ERR(2)); printf ("S_1 = %.5f +/- %.5f\n", FIT(3), c*ERR(3)); printf ("status = %s\n", gsl_strerror (status)); #endif // gsl_rng_free (r); return GSL_SUCCESS; }
int InterpolaVPR_GSL::interpola_VPR(const float* vpr, int hvprmax, int livmin) { LOG_CATEGORY("radar.vpr"); static const unsigned N = 10; const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; int status; unsigned int i; const size_t n = N; const size_t p = 5; char file_vprint[512]; gsl_matrix *covar = gsl_matrix_alloc (p, p); double a[5]; struct data d(N); gsl_multifit_function_fdf f; double x_init[5] = { 4, 0.2, 3. , 1.4, -0.4 }; gsl_vector_view x = gsl_vector_view_array (x_init, p); ////////////////////////////////////////////////////////////////////////////// int ier_int=0; double xint,yint; /* punti interessanti per inizializzare parametri*/ int in1=(int)((hvprmax-TCK_VPR/2)/TCK_VPR); //indice del massimo int in2=(int)((hvprmax+HALF_BB)/TCK_VPR); //indice del massimo + 500 m int in3=in2+1; int in4=in2+5; //indice del massimo + 1000 m if (in4 > NMAXLAYER-1) { ier_int=1; return ier_int; } B=vpr[in1]-vpr[in2]; E=hvprmax/1000.; G=0.25; C=vpr[in2-1]; F=vpr[in4]<vpr[in3]?(vpr[in4]-vpr[in3])/((in4-in3)*TCK_VPR/1000.):0.; // fprintf(stderr, "const unsigned NMAXLAYER=%d;\n", NMAXLAYER); // fprintf(stderr, "float vpr[] = {"); // for (unsigned i = 0; i < NMAXLAYER; ++i) // fprintf(stderr, "%s%f", i==0?"":",", (double)vpr[i]); // fprintf(stderr, "};\n"); x_init[0]= a[0]=B; x_init[1]= a[1]=E; x_init[2]= a[2]=G; x_init[3]= a[3]=C; x_init[4]= a[4]=F; ///////////////////////////////////////////////////////////////////////////////////////////////////////// f.f = &expb_f; f.df = &expb_df; f.fdf = &expb_fdf; f.n = n; f.p = p; f.params = &d; /* This is the data to be fitted */ for (i = 0; i < n; i++) { d.t[i]= ((hvprmax-1000.)>livmin)? (i*TCK_VPR+(hvprmax-800)-TCK_VPR)/1000. : (livmin+i*TCK_VPR)/1000.; d.y[i]= ((hvprmax-1000.)>livmin)? vpr[i+(int)(((hvprmax-800)-TCK_VPR)/TCK_VPR)] : vpr[i+(int)(livmin/TCK_VPR)]; d.sigma[i] = 0.5; }; T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, &f, &x.vector); //print_state (0, s); bool found = false; for (unsigned iter = 0; !found && iter < 500; ++iter) { //fprintf(stderr, "Iter %d\n", iter); //d.print(); int status = gsl_multifit_fdfsolver_iterate (s); if (status != 0) { LOG_ERROR("gsl_multifit_fdfsolver_iterate: %s", gsl_strerror(status)); return 1; } //print_state (iter, s); status = gsl_multifit_test_delta (s->dx, s->x, 1e-4, 1e-4); switch (status) { case GSL_SUCCESS: found = true; break; case GSL_CONTINUE: break; default: LOG_ERROR("gsl_multifit_test_delta: %s", gsl_strerror(status)); return 1; } } #if GSL_MAJOR_VERSION == 2 // Use of GSL 2.0 taken from https://sft.its.cern.ch/jira/browse/ROOT-7776 gsl_matrix* J = gsl_matrix_alloc(s->fdf->n, s->fdf->p); gsl_multifit_fdfsolver_jac(s, J); gsl_multifit_covar(J, 0.0, covar); #else gsl_multifit_covar(s->J, 0.0, covar); #endif #define FIT(i) gsl_vector_get(s->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) { double chi = gsl_blas_dnrm2(s->f); double dof = n - p; double c = GSL_MAX_DBL(1, chi / sqrt(dof)); // printf("chisq/dof = %g\n", pow(chi, 2.0) / dof); // printf ("B = %.5f +/- %.5f\n", FIT(0), c*ERR(0)); // printf ("E = %.5f +/- %.5f\n", FIT(1), c*ERR(1)); // printf ("G = %.5f +/- %.5f\n", FIT(2), c*ERR(2)); // printf ("C = %.5f +/- %.5f\n", FIT(3), c*ERR(3)); // printf ("F = %.5f +/- %.5f\n", FIT(4), c*ERR(4)); } B = a[0] = FIT(0); E = a[1] = FIT(1); G = a[2] = FIT(2); C = a[3] = FIT(3); F = a[4] = FIT(4); gsl_multifit_fdfsolver_free (s); gsl_matrix_free (covar); ///////////////////////////////////////////////////////// if (testfit(a) == 1) return 1; for (i=1; i<=N; i++) { xint=(i*TCK_VPR-TCK_VPR/2)/1000.; yint= lineargauss(xint, a); vpr_int[i-1] = yint; } return 0; }
double fit_n(set_const* Init, double n0){ const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; int status; unsigned int i, iter = 0; const size_t n = 11; const size_t p = 5; double k = n0/0.16; gsl_matrix *covar = gsl_matrix_alloc (p, p); double y[11] = {4.45, 6.45 , 9.65, 13.29, 17.94, 22.92, 27.49, 38.82, 54.95, 75.13, 99.75}; double t[11] = {k*0.02,k*0.04, k*0.08,k*0.12,k*0.16,k*0.2,k*0.24, k*0.32, k*0.4,k*0.48, k*0.56}; struct data d = { n, y, t, Init}; gsl_multifit_function_fdf f; double x_init[5] = {Init->C_s,Init->C_o, Init->b,Init->c, Init->C_r}; //double x_init[6] = {11.56279437,7.49931859,0.00871711,0.00267620,0.86859184,0.5}; //double x_init[4] = { sqrt(130.746),sqrt(120.7244),1.0,10.0}; gsl_vector_view x = gsl_vector_view_array (x_init, p); const gsl_rng_type * type; gsl_rng * r; gsl_rng_env_setup(); type = gsl_rng_default; r = gsl_rng_alloc (type); f.f = &func_fit_n; f.df = NULL; f.fdf = NULL; f.n = n; f.p = p; f.params = &d; /* This is the data to be fitted */ /*for (i = 0; i < n; i++) { double t = i; y[i] = 1.0 + 5 * exp (-0.1 * t) + gsl_ran_gaussian (r, 0.1); sigma[i] = 0.1; printf ("data: %u %g %g\n", i, y[i], sigma[i]); };*/ T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, &f, &x.vector); print_state (iter, s); do { iter++; status = gsl_multifit_fdfsolver_iterate (s); //printf ("status = %s\n", gsl_strerror (status)); print_state (iter, s); if (status) break; status = gsl_multifit_test_delta (s->dx, s->x, 1e-15, 0.0); } while (status == GSL_CONTINUE && iter < 2000); gsl_multifit_covar (s->J, 0.0, covar); #define FIT(i) gsl_vector_get(s->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) cond(Init, FIT(0), FIT(1), FIT(2), FIT(3), FIT(4)); { double chi = gsl_blas_dnrm2(s->f); double dof = n - p; double c = GSL_MAX_DBL(1, chi / sqrt(dof)); //double c = 1.0; /*printf("chisq/dof = %g\n", pow(chi, 2.0) / dof); printf ("Cs = %.5f +/- %.5f\n", Init->C_s, c*ERR(0)); printf ("Co = %.5f +/- %.5f\n", Init->C_o, c*ERR(1)); printf ("b = %.5f +/- %.5f\n", Init->c, c*ERR(2)); printf ("c = %.5f +/- %.5f\n", Init->b, c*ERR(3)); printf ("Cr = %.5f +/- %.5f\n", Init->C_r, c*ERR(4));*/ } // printf ("status = %s\n", gsl_strerror (status)); double z = 0.65; gsl_matrix_free (covar); gsl_rng_free (r); double yi = 0; /*for (int i = 0; i < 11; i++){ double yi = EoS::t_E(t[i],0, Init)/(D*t[i]) - m_n ; printf("n = %.3f, %.3f %.3f %.3f \n", t[i], yi, y[i], yi-y[i]); }*/ /*return *(new set_const("APR_fit return constant set",FIT(0), FIT(1), 10.0, FIT(2),abs(FIT(3)), z, [](double f){return (1-f);}, [](double f){return 1.0;}, [=](double f){return eta_o(f);}, [](double f){return 1.0;}));*/ double rr = gsl_blas_dnrm2(s->x); gsl_multifit_fdfsolver_free (s); return rr; }
int main (void) { const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; int status; unsigned int i, iter = 0; const size_t n = N; const size_t p = 3; gsl_matrix *covar = gsl_matrix_alloc (p, p); double y[N], sigma[N]; struct data d = { n, y, sigma}; gsl_multifit_function_fdf f; double x_init[3] = { 1.0, 0.0, 0.0 }; gsl_vector_view x = gsl_vector_view_array (x_init, p); const gsl_rng_type * type; gsl_rng * r; gsl_rng_env_setup(); type = gsl_rng_default; r = gsl_rng_alloc (type); f.f = &expb_f; f.df = &expb_df; f.fdf = &expb_fdf; f.n = n; f.p = p; f.params = &d; /* This is the data to be fitted */ for (i = 0; i < n; i++) { double t = i; y[i] = 1.0 + 5 * exp (-0.1 * t) + gsl_ran_gaussian (r, 0.1); sigma[i] = 0.1; printf ("data: %u %g %g\n", i, y[i], sigma[i]); }; T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, &f, &x.vector); print_state (iter, s); do { iter++; status = gsl_multifit_fdfsolver_iterate (s); printf ("status = %s\n", gsl_strerror (status)); print_state (iter, s); if (status) break; status = gsl_multifit_test_delta (s->dx, s->x, 1e-4, 1e-4); } while (status == GSL_CONTINUE && iter < 500); gsl_multifit_covar (s->J, 0.0, covar); #define FIT(i) gsl_vector_get(s->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) { double chi = gsl_blas_dnrm2(s->f); double dof = n - p; double c = GSL_MAX_DBL(1, chi / sqrt(dof)); printf("chisq/dof = %g\n", pow(chi, 2.0) / dof); printf ("A = %.5f +/- %.5f\n", FIT(0), c*ERR(0)); printf ("lambda = %.5f +/- %.5f\n", FIT(1), c*ERR(1)); printf ("b = %.5f +/- %.5f\n", FIT(2), c*ERR(2)); } printf ("status = %s\n", gsl_strerror (status)); gsl_multifit_fdfsolver_free (s); gsl_matrix_free (covar); gsl_rng_free (r); return 0; }
/* * Gaussian parameters calculation y=A/sqrt(2*pi*sigma^2) exp(-(x-x_0)^2/2/sigma^2), * which approximates the points set pts * Parameters A_, sigma_, x0_ may be NULL (if you don't need any of them) */ void gauss_fit(Points *pts, double *C_, double *A_, double *sigma_, double *x0_){ // VVVV lower parameters may be formed as a structure to change as function argument double epsabs = 1e-8,// absolute error epsrel = 1e-5,// relative error chi_max = 0.01;// max chi value for iterations criteria int max_iter = 300; // limit iterations number of gsl_multifit_fdfsolver size_t N_MIN = 10; // minimum points for approximation double x_init[4]; // AAAA upper parameters may be formed as a structure to change as function argument /* x_init, the best approximations: * x0 - not far from real (the nearest is the better) * sigma - not far from real (the nearest is the better) * A - not large ~10 (it has a weak effect) */ const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; int status; #ifdef EBUG int appNo = 0; #endif int iter; size_t i, j, n = pts->n, oldn; const size_t p = 4; gsl_matrix *covar = gsl_matrix_alloc (p, p); #ifdef EBUG double t0; #endif double *x, *y, *dy, chi, C, A, sigma, x0; if(n < 1) return; x = malloc(n * sizeof(double)); y = malloc(n * sizeof(double)); dy = malloc(n * sizeof(double)); struct data d = {n, x, y, dy}; gsl_multifit_function_fdf f; gsl_vector_view xx = gsl_vector_view_array(x_init, p); const gsl_rng_type *type; gsl_rng *r; gsl_rng_env_setup(); type = gsl_rng_default; r = gsl_rng_alloc (type); f.f = &gauss_f; f.df = &gauss_df; f.fdf = &gauss_fdf; f.n = n; f.p = p; f.params = &d; // fill data structure. Don't forget Okkam's razor!!! { Point *pt = pts->data; double *px = x, *py = y, *pdy = dy, sum = 0.; for(i = 0; i < n; i++, pt++){ *pdy++ = 1.; // I have no idea what is it, so init by 1 *px++ = pt->x; *py++ = pt->y; sum += pt->y; //DBG("point %d: (%g, %g)", i, pt->x, pt->y); } // fill x_init: x0, sigma, C, A (it can be a funtion parameter) x_init[3] = (*(--px) + *x) / 2.; x_init[2] = fabs((*x - *px) / 4.); x_init[0] = sum/(double)n; x_init[1] = sum; DBG("\nInitial parameters: x0=%.1f, sigma=%.1f, A=%.1f, C=%.1f", x_init[3], x_init[2], x_init[1], x_init[0]); } T = gsl_multifit_fdfsolver_lmder; // or also gsl_multifit_fdfsolver_lmsder s = gsl_multifit_fdfsolver_alloc(T, n, p); #ifdef EBUG t0 = dtime(); #endif do{ double dof, tres, c; DBG("\n************ Approximation %d ******************\n", appNo++); iter = 0; gsl_multifit_fdfsolver_set(s, &f, &xx.vector); do{ iter++; status = gsl_multifit_fdfsolver_iterate(s); if(status) break; status = gsl_multifit_test_delta(s->dx, s->x, epsabs, epsrel); }while(status == GSL_CONTINUE && iter < max_iter); DBG("time=%g\n", dtime()-t0); gsl_multifit_covar(s->J, 0.0, covar); chi = gsl_blas_dnrm2(s->f); dof = n - p; tres = chi; c = chi / sqrt(dof); // GSL_MAX_DBL(1., chi / sqrt(dof)); C = FIT(0), A = FIT(1), sigma = FIT(2), x0 = FIT(3); DBG("Number of iteratons = %d\n", iter); DBG("chi = %g, chi/dof = %g\n", chi, chi / sqrt(dof)); DBG("C = %.5f +/- %.5f\n", C, c*ERR(0)); DBG("A = %.5f +/- %.5f\n", A, c*ERR(1)); DBG("sigma = %.5f +/- %.5f\n", sigma, c*ERR(2)); DBG("x0 = %.5f +/- %.5f\n", x0, c*ERR(3)); j = 0; oldn = n; if(c < chi_max) break; // throw out bad (by chi) data for(i = 0; i < n; i++){ if(fabs(FN(i)) < tres){ if(i != j){ x[j] = x[i]; y[j] = y[i]; dy[j] = dy[i]; } j++; continue; } } if(j != n){ DBG("Chi tresholding %g, %zd points of %zd\n", tres, j, n); n = j; d.n = n; } }while(chi > chi_max && n != oldn && n > N_MIN); if(C_) *C_ = C; if(A_) *A_ = A; if(sigma_) *sigma_ = sigma; if(x0_) *x0_ = x0; //printf ("status = %s\n", gsl_strerror (status)); gsl_multifit_fdfsolver_free(s); gsl_matrix_free(covar); gsl_rng_free(r); free(x); free(y); free(dy); }
f_all_sol do_fit_duplex(f_info *f, int n, real *t_min, real *t_max, bool bVerbose, bool bUpdate) { int i,j,k; int iter=0; int tot_points=0; int status; int tot_abs=0; int tot_inv_t=0; real inv_t=0; real tss_inv=0; real mean_inv_t=0; real abs_t=0; real mean_abs_t=0; real tss_abs=0; real tss_tot=0; f_all_sol fit; f_info *local_f; snew(local_f,n); // count points within boundaries, allocate // and copy to new array. Only copy the xp (derivative) // as is the one that matters for the fitting for(i=0; i<n; i++){ for(j=0; j<f[i].nts; j++){ if( f[i].xp[0][j] >= t_min[i] && f[i].xp[0][j] <= t_max[i] ) { local_f[i].nts++ ; } } snew(local_f[i].xp[0],local_f[i].nts); snew(local_f[i].xp[1],local_f[i].nts); } // now copy the data // not only the derivatives of the absorbance, also the conc k=0; for(i=0; i<n; i++){ local_f[i].conc = f[i].conc ; for(j=0; j<f[i].nts; j++){ if( f[i].xp[0][j] >= t_min[i] && f[i].xp[0][j] <= t_max[i] ) { local_f[i].xp[0][k] = f[i].xp[0][j] ; local_f[i].xp[1][k] = f[i].xp[1][j] ; // we use this loop to compute the TSS, the total sum of squares of the // "y" data, to be used for r_squared after we know chi_sq abs_t += local_f[i].xp[1][k] ; tot_abs++; k++; } } k=0; } // Total number of points to fit size_t pp = 4; const gsl_multifit_fdfsolver_type *T; T = gsl_multifit_fdfsolver_lmsder; gsl_multifit_fdfsolver *s; // do a fit for each triplex curve for (i=0; i<n; i++){ // Total number of points to fit if (bVerbose){printf("Working on curve n %d\n",i);} struct fit_data d = { n,i, local_f}; tot_points = local_f[i].nts ; gsl_matrix *covar = gsl_matrix_alloc (pp, pp); gsl_multifit_function_fdf ff; gsl_vector *x; x = gsl_vector_alloc(pp); gsl_vector_set(x,0,f[i].tm2); gsl_vector_set(x,1,f[i].c); gsl_vector_set(x,2,-70); gsl_vector_set(x,3,-0.1); s = gsl_multifit_fdfsolver_alloc (T, tot_points, pp); // copy data to function ff.f = &eq_fit; ff.df = NULL; ff.fdf = NULL; ff.p = pp; // total number of points is total of points // in the curve plus the number of points for the inv. fit ff.n = tot_points; ff.params = &d; gsl_multifit_fdfsolver_set (s, &ff, x); iter=0; do { iter++; status = gsl_multifit_fdfsolver_iterate (s); if(bVerbose){ printf ("iter: %3u x = % 15.8f % 15.8f %15.8f " "|f(x)| = %g\n",iter, gsl_vector_get (s->x, 0), gsl_vector_get (s->x, 1), gsl_vector_get (s->x, 2), gsl_blas_dnrm2 (s->f)); } if (status) break; status = gsl_multifit_test_delta (s->dx, s->x, 1e-8, 1e-8); } while (status == GSL_CONTINUE && iter < 500); gsl_multifit_covar (s->J, 0.0, covar); gsl_matrix_free (covar); gsl_vector_free(x); // copy tm2 data adjusted from each curve local_f[i].tm2 = gsl_vector_get(s->x, 0); } //free first solver gsl_multifit_fdfsolver_free (s); // do the 1/tm vs ln(ct) fitting const gsl_multifit_fdfsolver_type *Tl; gsl_multifit_fdfsolver *sl; // fit params in the straight line int ppl = 2; gsl_matrix *covarl = gsl_matrix_alloc (ppl, ppl); struct fit_data dl = { n,i, local_f}; gsl_multifit_function_fdf ffl; gsl_vector *xl; xl = gsl_vector_alloc(ppl); // DH and DS gsl_vector_set(xl,0,-70); gsl_vector_set(xl,1,-0.1); Tl = gsl_multifit_fdfsolver_lmsder; sl = gsl_multifit_fdfsolver_alloc (Tl, n, ppl); // copy data to function ffl.f=&eq_fit_straight; ffl.df = NULL; ffl.fdf = NULL; ffl.p = ppl; // total number of points the number of curves ffl.n = n; ffl.params = &dl; gsl_multifit_fdfsolver_set (sl, &ffl, xl); iter=0; do { iter++; status = gsl_multifit_fdfsolver_iterate (sl); if(bVerbose){ printf ("iter: %3u x = % 15.8f % 15.8f " "|f(x)| = %g\n",iter, gsl_vector_get (sl->x, 0), gsl_vector_get (sl->x, 1), gsl_blas_dnrm2 (sl->f)); } if (status) break; status = gsl_multifit_test_delta (sl->dx, sl->x, 1e-8, 1e-8); } while (status == GSL_CONTINUE && iter < 500); gsl_multifit_covar (sl->J, 0.0, covarl); #define FIT(i) gsl_vector_get(sl->x, i) #define ERR(i) sqrt(gsl_matrix_get(covarl,i,i)) // compute contribution of inverse temperature to TSS for(i=0;i<n;i++){ inv_t += ((real)1.0/(real)local_f[i].tm2); tot_inv_t++; } mean_inv_t = inv_t / (real)tot_inv_t; for(i=0;i<n;i++){ tss_inv += (1.0/(real)local_f[i].tm2 - mean_inv_t ) * (1.0/(real)local_f[i].tm2 - mean_inv_t); } if (bUpdate){ fit.dh2 = gsl_vector_get(sl->x, 0); fit.ds2 = gsl_vector_get(sl->x, 1); fit.dg2 = fit.dh2 - 298.15*fit.ds2; for(i=0; i<n; i++){ f[i].tm2 = local_f[i].tm2 ; } } tss_tot = tss_inv ; double chi = gsl_blas_dnrm2(sl->f); fit.r2 = 1.0 - ( chi*chi / tss_tot ) ; double dof = n - ppl; double c = GSL_MAX_DBL(1, chi / sqrt(dof)); if(bVerbose) { printf ("chisq/dof = %g\n", pow(chi, 2.0) / dof); printf ("r2 = %g\n", fit.r2); printf ("DH3 = %.5f +/- %.5f\n", FIT(0), c*ERR(0)); printf ("DS3 = %.5f +/- %.5f\n", FIT(1), c*ERR(1)); printf ("DG3 = %.5f +/- %.5f\n", FIT(0)-298*FIT(1),c*ERR(1)+c*298*ERR(0)); printf ("status = %s\n", gsl_strerror (status)); } gsl_multifit_fdfsolver_free (sl); gsl_matrix_free (covarl); gsl_vector_free(xl); return fit; }