void simulate_RT(component c, double a){
	/* Memory Allocation, Structures and Fields */
	grid_volume v = vol2d(size_x,size_y,a); /* Grid volume for computations */
	structure s0(v,air,pml(h_PML,Y));     /* Reference case: no scatterers; PML termination in the y-direction */
	structure s(v,air_glass_grating,pml(h_PML,Y));	/* Structure to be simulated; PML termination in the y-direction */
	fields f0(&s0); /* Fields for reference case */
	fields f(&s);   /* Fields for simulation structure */
	h5file *eps_file_ptr=f.open_h5file(eps_file_name);
	f.output_hdf5(Dielectric, v.surroundings(), eps_file_ptr, true);    /* Outputting dielectric function as .h5 file; <fields>.output_hdf5(<field_type>,<?>) */

	/* Flux Lines for Transmissions and Reflection Detectors */
	volume flux_line_trans(vec(0,h_PML+4*h_sep+d),vec(size_x,h_PML+4*h_sep+d));
	volume flux_line_refl(vec(0,h_PML+2*h_sep),vec(size_x,h_PML+2*h_sep));

	/* Appropriate Bloch Boundary Conditions */
	double k_x=n_air*freq_centre*sin(theta_degrees*const_pi/180.0);
	f0.use_bloch(vec(k_x,0.0));
	f.use_bloch(vec(k_x,0.0));

	/* Light Sources */
	gaussian_src_time src(freq_centre, 0.5/pw_freq_width, 0, 5/pw_freq_width);      /* Time-domain definition of source */
	volume src_line(vec(0,h_PML+h_sep),vec(size_x,h_PML+h_sep));

	f0.add_volume_source(c,src,src_line,src_spatial_modulator,1.0);
	f.add_volume_source(c,src,src_line,src_spatial_modulator,1.0);
	master_printf("# Line source(s) added ...\n");

	/* Fluxes for Transmission, Reflection */
	dft_flux f_t0 = f0.add_dft_flux_plane(flux_line_trans,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);
	dft_flux f_t = f.add_dft_flux_plane(flux_line_trans,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);
	dft_flux f_r0 = f0.add_dft_flux_plane(flux_line_refl,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);
	dft_flux f_r = f.add_dft_flux_plane(flux_line_refl,min2(freq_min,freq_max),max2(freq_min,freq_max),num_freqs);

	angleResolvedDetectors2D *ard = new angleResolvedDetectors2D(h_PML+4*h_sep, h_PML+2*h_sep, size_x, a, angle_res_degrees, freq_min, freq_max, num_freqs, theta_degrees, n_air, n_air, degree);

	master_printf("# Simulating reference structure ...\n");
	double t_final_src_0=f0.last_source_time(), t_final_sim_0=t_final_src_0+duration_factor*num_freqs/pw_freq_width/2;
	master_printf("\tparameter__user_inaccessible:\tt_final_src_0 = %f\n",t_final_src_0);
	master_printf("\tparameter__user_inaccessible:\tt_final_sim_0 = %f\n",t_final_sim_0);
	while(f0.time() < t_final_sim_0){ /* Time-stepping -- reference structure */
		f0.step(); 
		double t=f0.time();
		ard->update(t,f0,reference);
	}
	f_r0.save_hdf5(f0, flux_file_name, "reflection");
	ard->finalize_update(reference);

	master_printf("# Simulating test structure ...\n");
	double t_final_src=f.last_source_time(), t_final_sim=t_final_src+duration_factor*num_freqs/pw_freq_width/2;
	master_printf("\tparameter__user_inaccessible:\tt_final_src = %f\n",t_final_src);
	master_printf("\tparameter__user_inaccessible:\tt_final_sim = %f\n",t_final_sim);
	f_r.load_hdf5(f, flux_file_name, "reflection");
	f_r.scale_dfts(-1.0);
	while(f.time() < t_final_sim){  /* Time-stepping -- simulated structure */
		f.step();
		double t=f.time();
		ard->update(t,f,simulation);
	}
	f.output_hdf5(c, v.surroundings());     /* Outputting electric field as .h5 file; <fields>.output_hdf5(<field_type>,<?>) */
	ard->finalize_update(simulation);

	double *flux_t = f_t.flux();    /* Calculating flux -- integrating? */
	double *flux_t0 = f_t0.flux();  /* Calculating flux -- integrating? */
	double *flux_r = f_r.flux();    /* Calculating flux -- integrating? */
	double *flux_r0 = f_r0.flux();  /* Calculating flux -- integrating? */

	double *T;      /* Array to store transmission coefficients (frequency-dependent) */
	double *R;      /* Array to store reflection coefficients (frequency-dependent) */
	T = new double[num_freqs];
	R = new double[num_freqs];
	for (int i=0; i<num_freqs; ++i){	/* Calculating transmission, reflection coefficients */
		T[i] = flux_t[i] / flux_t0[i];
		R[i] = -flux_r[i] / flux_r0[i];
	}
	double dfreq = pw_freq_width / (num_freqs-1);

	master_printf("transmission:, omega, T\n");
	master_printf("reflection:, omega, R\n");
	master_printf("addition_check:, omega, R+T\n");
	for (int l=0; l<num_freqs; ++l){	/* Printing transmission coefficient values */
		master_printf("transmission:, %f, %f\n",freq_min+l*dfreq,T[l]);
		master_printf("reflection:, %f, %f\n",freq_min+l*dfreq,R[l]);
		master_printf("addition_check:, %f, %f\n",freq_min+l*dfreq,T[l]+R[l]);
	}

	ard->print_angle_unresolved_T();
	ard->print_angle_unresolved_R();
	ard->print_angle_resolved_T(file_name_prefix);
	ard->print_angle_resolved_R(file_name_prefix);

	delete [] eps_file_name;
	delete [] flux_file_name;


	delete [] flux_t;       /* "Garbage collection" at end of code execution */
	delete [] flux_t0;      /* "Garbage collection" at end of code execution */
	delete [] flux_r;       /* "Garbage collection" at end of code execution */
	delete [] flux_r0;      /* "Garbage collection" at end of code execution */

	delete [] T;    /* "Garbage collection" at end of code execution */
	delete [] R;    /* "Garbage collection" at end of code execution */

	delete ard;
}
Example #2
0
/*
double stlgh;
double GetH(const Point3d& p, double x)
{
  return stlgh;//+0.5)*(x+0.5);
}
*/
STLLine* STLLine :: Mesh(const Array<Point<3> >& ap,
                         Array<Point3d>& mp, double ghi,
                         class Mesh& mesh) const
{
    static int timer1a = NgProfiler::CreateTimer ("mesh stl-line 1a");
    static int timer1b = NgProfiler::CreateTimer ("mesh stl-line 1b");
    static int timer2 = NgProfiler::CreateTimer ("mesh stl-line 2");
    static int timer3 = NgProfiler::CreateTimer ("mesh stl-line 3");

    NgProfiler::StartTimer (timer1a);

    STLLine* line = new STLLine(geometry);

    //stlgh = ghi; //uebergangsloesung!!!!

    double len = GetLength(ap);
    double inthl = 0; //integral of 1/h
    double dist = 0;
    double h;
    int ind;
    Point3d p;

    Box<3> bbox;
    GetBoundingBox (ap, bbox);
    double diam = bbox.Diam();

    double minh = mesh.LocalHFunction().GetMinH (bbox.PMin(), bbox.PMax());

    double maxseglen = 0;
    for (int i = 1; i <= GetNS(); i++)
        maxseglen = max2 (maxseglen, GetSegLen (ap, i));

    int nph = 10+int(maxseglen / minh); //anzahl der integralauswertungen pro segment

    Array<double> inthi(GetNS()*nph);
    Array<double> curvelen(GetNS()*nph);

    NgProfiler::StopTimer (timer1a);
    NgProfiler::StartTimer (timer1b);


    for (int i = 1; i <= GetNS(); i++)
    {
        //double seglen = GetSegLen(ap,i);
        for (int j = 1; j <= nph; j++)
        {
            p = GetPointInDist(ap,dist,ind);
            //h = GetH(p,dist/len);
            h = mesh.GetH(p);


            dist += GetSegLen(ap,i)/(double)nph;

            inthl += GetSegLen(ap,i)/nph/(h);
            inthi.Elem((i-1)*nph+j) = GetSegLen(ap,i)/nph/h;
            curvelen.Elem((i-1)*nph+j) = GetSegLen(ap,i)/nph;
        }
    }


    int inthlint = int(inthl+1);

    if ( (inthlint < 3) && (StartP() == EndP()))
    {
        inthlint = 3;
    }
    if ( (inthlint == 1) && ShouldSplit())
    {
        inthlint = 2;
    }

    double fact = inthl/(double)inthlint;
    dist = 0;
    int j = 1;


    p = ap.Get(StartP());
    int pn = AddPointIfNotExists(mp, p, 1e-10*diam);

    int segn = 1;
    line->AddPoint(pn);
    line->AddLeftTrig(GetLeftTrig(segn));
    line->AddRightTrig(GetRightTrig(segn));
    line->AddDist(dist);

    NgProfiler::StopTimer (timer1b);
    NgProfiler::StartTimer (timer2);

    inthl = 0; //restart each meshseg
    for (int i = 1; i <= inthlint; i++)
    {
        while (inthl < 1.000000001 && j <= inthi.Size())
        {
            inthl += inthi.Get(j)/fact;
            dist += curvelen.Get(j);
            j++;
        }

        //went too far:
        j--;
        double tofar = (inthl - 1)/inthi.Get(j);
        inthl -= tofar*inthi.Get(j);
        dist -= tofar*curvelen.Get(j)*fact;

        if (i == inthlint && fabs(dist - len) >= 1E-8)
        {
            PrintSysError("meshline failed!!!");
        }

        if (i != inthlint)
        {
            p = GetPointInDist(ap,dist,ind);
            pn = AddPointIfNotExists(mp, p, 1e-10*diam);
            segn = ind;
            line->AddPoint(pn);
            line->AddLeftTrig(GetLeftTrig(segn));
            line->AddRightTrig(GetRightTrig(segn));
            line->AddDist(dist);
        }

        inthl = tofar*inthi.Get(j);
        dist += tofar*curvelen.Get(j)*fact;
        j++;
    }

    NgProfiler::StopTimer (timer2);
    NgProfiler::StartTimer (timer3);


    p = ap.Get(EndP());
    pn = AddPointIfNotExists(mp, p, 1e-10*diam);
    segn = GetNS();
    line->AddPoint(pn);
    line->AddLeftTrig(GetLeftTrig(segn));
    line->AddRightTrig(GetRightTrig(segn));
    line->AddDist(dist);

    for (int ii = 1; ii <= line->GetNS(); ii++)
    {
        int p1, p2;
        line->GetSeg(ii,p1,p2);
    }
    /*
    (*testout) << "line, " << ap.Get(StartP()) << "-" << ap.Get(EndP())
         << " len = " << Dist (ap.Get(StartP()), ap.Get(EndP())) << endl;
    */

    NgProfiler::StopTimer (timer3);

    return line;
}
Example #3
0
/*
	Naive dynamic programming algorithm for comparison purposes. Transposition invariant.
	Handles each track separately.
*/
VALUE c_dynprog_scan(VALUE self, VALUE init_info)
{
	VALUE tracks_ary = Qnil, result_list;
	char *p, *track;
	unsigned int pattern_size, trackind, num_chords = 0, num_notes, num_tracks = 0, i, j, ip, jp;
	int errors, tp, len;
	/* ID = cost of indel operation; sigma = vocabulary size (here size of MIDI pitch range) */
	int sigma = 128, ID = 1;
	int mindistance = INT_MAX, minchordind = 0, mintp = 0, min1, min2, min3;
	int columna[MAX_PATTERN_NOTES + 1], oldcolumna[MAX_PATTERN_NOTES + 1], initcolumn[MAX_PATTERN_NOTES + 1], *temp, *oldcolumn, *column;

	/* Test for pattern and chord array sizes */
	pattern_size = NUM2UINT(rb_iv_get(init_info, "@pattern_size"));
	num_chords = NUM2UINT(rb_iv_get(self, "@num_chords"));
	num_notes = NUM2UINT(rb_iv_get(self, "@num_notes"));
	if (pattern_size > num_chords) return Qnil;

	/* Get the rest of parameters */
	p = (char *) RSTRING_PTR(rb_iv_get(init_info, "@pattern_pitch_string"));
	errors = NUM2INT(rb_iv_get(init_info, "@errors"));
	tracks_ary = rb_iv_get(self, "@tracks");
	num_tracks = NUM2UINT(rb_iv_get(self, "@num_tracks"));
	result_list = rb_iv_get(init_info, "@matches");

	/* initialize first column */
	for (i = 0; i <= pattern_size; i++) initcolumn[i] = i * ID;
	len = sizeof(int) * (pattern_size + 1);
	oldcolumn = oldcolumna;
	column = columna;

	/* for each track */
	for (trackind = 1; trackind <= num_tracks; trackind++)
	{
		track = (char *) RSTRING_PTR(RARRAY_PTR(tracks_ary)[trackind]);

		/* for each transposition */
		for (tp = -sigma + 1; tp < sigma; tp++)
		{
			/* initialize left column (old column) */
			for (i = 0; i <= pattern_size; i++) { oldcolumn[i] = initcolumn[i]; column[i] = 0; }

			/* for each note on the track */
			for (j = 0, jp = 1; j < num_chords; j++, jp++)
			{
				column[0] = j * ID;
				
				for (i = 0, ip = 1; i < pattern_size; i++, ip++)
				{
					min1 = abs(track[jp] - p[ip] - tp) + oldcolumn[i];
					min2 = ID + column[i];
					min3 = ID + oldcolumn[ip];

					if (min1 < min2)
					{
						if (min1 < min3) column[ip] = min1;
						else column[ip] = min3;
					}
					else
					{
						if (min2 < min3) column[ip] = min2;
						else column[ip] = min3;
					}
				}

				if (column[pattern_size] <= mindistance)
				{
					mindistance = column[pattern_size];
					minchordind = j;
					mintp = tp;
				}

				temp = oldcolumn;
				oldcolumn = column;
				column = temp;
			}
		}
	}

	/* Process results */
	if (mindistance <= errors * ID) rb_ary_push(result_list, rb_ary_new3(6, self, INT2NUM(max2(minchordind - (int) pattern_size + 1, 0)), INT2NUM(minchordind), Qnil, INT2FIX(mintp), INT2FIX(mindistance)));

	return result_list;
}
Example #4
0
File: lbfgs.c Project: Kitware/ITK
static int line_search_morethuente(
    int n,
    lbfgsfloatval_t *x,
    lbfgsfloatval_t *f,
    lbfgsfloatval_t *g,
    lbfgsfloatval_t *s,
    lbfgsfloatval_t *stp,
    const lbfgsfloatval_t* xp,
    const lbfgsfloatval_t* gp,
    lbfgsfloatval_t *wa,
    callback_data_t *cd,
    const lbfgs_parameter_t *param
    )
{
    int count = 0;
    int brackt, stage1, uinfo = 0;
    lbfgsfloatval_t dg;
    lbfgsfloatval_t stx, fx, dgx;
    lbfgsfloatval_t sty, fy, dgy;
    lbfgsfloatval_t fxm, dgxm, fym, dgym, fm, dgm;
    lbfgsfloatval_t finit, ftest1, dginit, dgtest;
    lbfgsfloatval_t width, prev_width;
    lbfgsfloatval_t stmin, stmax;

    /* Check the input parameters for errors. */
    if (*stp <= 0.) {
        return LBFGSERR_INVALIDPARAMETERS;
    }

    /* Compute the initial gradient in the search direction. */
    vecdot(&dginit, g, s, n);

    /* Make sure that s points to a descent direction. */
    if (0 < dginit) {
        return LBFGSERR_INCREASEGRADIENT;
    }

    /* Initialize local variables. */
    brackt = 0;
    stage1 = 1;
    finit = *f;
    dgtest = param->ftol * dginit;
    width = param->max_step - param->min_step;
    prev_width = 2.0 * width;

    /*
        The variables stx, fx, dgx contain the values of the step,
        function, and directional derivative at the best step.
        The variables sty, fy, dgy contain the value of the step,
        function, and derivative at the other endpoint of
        the interval of uncertainty.
        The variables stp, f, dg contain the values of the step,
        function, and derivative at the current step.
    */
    stx = sty = 0.;
    fx = fy = finit;
    dgx = dgy = dginit;

    for (;;) {
        /*
            Set the minimum and maximum steps to correspond to the
            present interval of uncertainty.
         */
        if (brackt) {
            stmin = min2(stx, sty);
            stmax = max2(stx, sty);
        } else {
            stmin = stx;
            stmax = *stp + 4.0 * (*stp - stx);
        }

        /* Clip the step in the range of [stpmin, stpmax]. */
        if (*stp < param->min_step) *stp = param->min_step;
        if (param->max_step < *stp) *stp = param->max_step;

        /*
            If an unusual termination is to occur then let
            stp be the lowest point obtained so far.
         */
        if ((brackt && ((*stp <= stmin || stmax <= *stp) || param->max_linesearch <= count + 1 || uinfo != 0)) || (brackt && (stmax - stmin <= param->xtol * stmax))) {
            *stp = stx;
        }

        /*
            Compute the current value of x:
                x <- x + (*stp) * s.
         */
        veccpy(x, xp, n);
        vecadd(x, s, *stp, n);

        /* Evaluate the function and gradient values. */
        *f = cd->proc_evaluate(cd->instance, x, g, cd->n, *stp);
        vecdot(&dg, g, s, n);

        ftest1 = finit + *stp * dgtest;
        ++count;

        /* Test for errors and convergence. */
        if (brackt && ((*stp <= stmin || stmax <= *stp) || uinfo != 0)) {
            /* Rounding errors prevent further progress. */
            return LBFGSERR_ROUNDING_ERROR;
        }
        if (*stp == param->max_step && *f <= ftest1 && dg <= dgtest) {
            /* The step is the maximum value. */
            return LBFGSERR_MAXIMUMSTEP;
        }
        if (*stp == param->min_step && (ftest1 < *f || dgtest <= dg)) {
            /* The step is the minimum value. */
            return LBFGSERR_MINIMUMSTEP;
        }
        if (brackt && (stmax - stmin) <= param->xtol * stmax) {
            /* Relative width of the interval of uncertainty is at most xtol. */
            return LBFGSERR_WIDTHTOOSMALL;
        }
        if (param->max_linesearch <= count) {
            /* Maximum number of iteration. */
            return LBFGSERR_MAXIMUMLINESEARCH;
        }
        if (*f <= ftest1 && fabs(dg) <= param->gtol * (-dginit)) {
            /* The sufficient decrease condition and the directional derivative condition hold. */
            return count;
        }

        /*
            In the first stage we seek a step for which the modified
            function has a nonpositive value and nonnegative derivative.
         */
        if (stage1 && *f <= ftest1 && min2(param->ftol, param->gtol) * dginit <= dg) {
            stage1 = 0;
        }

        /*
            A modified function is used to predict the step only if
            we have not obtained a step for which the modified
            function has a nonpositive function value and nonnegative
            derivative, and if a lower function value has been
            obtained but the decrease is not sufficient.
         */
        if (stage1 && ftest1 < *f && *f <= fx) {
            /* Define the modified function and derivative values. */
            fm = *f - *stp * dgtest;
            fxm = fx - stx * dgtest;
            fym = fy - sty * dgtest;
            dgm = dg - dgtest;
            dgxm = dgx - dgtest;
            dgym = dgy - dgtest;

            /*
                Call update_trial_interval() to update the interval of
                uncertainty and to compute the new step.
             */
            uinfo = update_trial_interval(
                &stx, &fxm, &dgxm,
                &sty, &fym, &dgym,
                stp, &fm, &dgm,
                stmin, stmax, &brackt
                );

            /* Reset the function and gradient values for f. */
            fx = fxm + stx * dgtest;
            fy = fym + sty * dgtest;
            dgx = dgxm + dgtest;
            dgy = dgym + dgtest;
        } else {
            /*
                Call update_trial_interval() to update the interval of
                uncertainty and to compute the new step.
             */
            uinfo = update_trial_interval(
                &stx, &fx, &dgx,
                &sty, &fy, &dgy,
                stp, f, &dg,
                stmin, stmax, &brackt
                );
        }

        /*
            Force a sufficient decrease in the interval of uncertainty.
         */
        if (brackt) {
            if (0.66 * prev_width <= fabs(sty - stx)) {
                *stp = stx + 0.5 * (sty - stx);
            }
            prev_width = width;
            width = fabs(sty - stx);
        }
    }

    return LBFGSERR_LOGICERROR;
}
Example #5
0
TEST(NumericTest, test_max2) {
    float x = 3.8;
    float y = 4.3;
    EXPECT_EQ(y, max2(x, y));
    EXPECT_EQ(y, max2(y, x));
}
Example #6
0
static
__inline
void solveContact(Constraint4& cs, 
	const float4& posA, float4& linVelA, float4& angVelA, float invMassA, const Matrix3x3& invInertiaA,
	const float4& posB, float4& linVelB, float4& angVelB, float invMassB, const Matrix3x3& invInertiaB, 
	float maxRambdaDt[4], float minRambdaDt[4])
{
	float4 dLinVelA = make_float4(0.f);
	float4 dAngVelA = make_float4(0.f);
	float4 dLinVelB = make_float4(0.f);
	float4 dAngVelB = make_float4(0.f);

	for(int ic=0; ic<4; ic++)
	{
		//	dont necessary because this makes change to 0
		if( cs.m_jacCoeffInv[ic] == 0.f ) continue;

		{
			float4 angular0, angular1, linear;
			float4 r0 = cs.m_worldPos[ic] - posA;
			float4 r1 = cs.m_worldPos[ic] - posB;
			setLinearAndAngular( -cs.m_linear, r0, r1, linear, angular0, angular1 );

			float rambdaDt = calcRelVel(cs.m_linear, -cs.m_linear, angular0, angular1,
				linVelA, angVelA, linVelB, angVelB ) + cs.m_b[ic];
			rambdaDt *= cs.m_jacCoeffInv[ic];

			{
				float prevSum = cs.m_appliedRambdaDt[ic];
				float updated = prevSum;
				updated += rambdaDt;
				updated = max2( updated, minRambdaDt[ic] );
				updated = min2( updated, maxRambdaDt[ic] );
				rambdaDt = updated - prevSum;
				cs.m_appliedRambdaDt[ic] = updated;
			}

			float4 linImp0 = invMassA*linear*rambdaDt;
			float4 linImp1 = invMassB*(-linear)*rambdaDt;
			float4 angImp0 = mtMul1(invInertiaA, angular0)*rambdaDt;
			float4 angImp1 = mtMul1(invInertiaB, angular1)*rambdaDt;
#ifdef _WIN32
            btAssert(_finite(linImp0.x));
			btAssert(_finite(linImp1.x));
#endif
			if( JACOBI )
			{
				dLinVelA += linImp0;
				dAngVelA += angImp0;
				dLinVelB += linImp1;
				dAngVelB += angImp1;
			}
			else
			{
				linVelA += linImp0;
				angVelA += angImp0;
				linVelB += linImp1;
				angVelB += angImp1;
			}
		}
	}

	if( JACOBI )
	{
		linVelA += dLinVelA;
		angVelA += dAngVelA;
		linVelB += dLinVelB;
		angVelB += dAngVelB;
	}
}
INT32T max3(INT32T a, INT32T b, INT32T c){
	return max2(max2(a, b), c);
}
Example #8
0
/*
 * NAME:	optimize->binop()
 * DESCRIPTION:	optimize a binary operator expression
 */
static Uint opt_binop(node **m)
{
    node *n, *t;
    Uint d1, d2, d;
    xfloat f1, f2;

    n = *m;
    if (n->type == N_ADD && n->r.right->type == N_ADD &&
	n->l.left->mod == n->r.right->mod &&
	(n->mod == T_STRING || (n->mod & T_REF) != 0)) {
	/*
	 * a + (b + c) --> (a + b) + c
	 * the order in which these are added won't affect the final result
	 */
	t = n->l.left;
	n->l.left = n->r.right;
	n->r.right = n->l.left->r.right;
	n->l.left->r.right = n->l.left->l.left;
	n->l.left->l.left = t;
    }

    d1 = opt_expr(&n->l.left, FALSE);
    d2 = opt_expr(&n->r.right, FALSE);

    if (n->type == N_SUM) {
	if (n->l.left->type == N_RANGE) {
	    d1 = max2(d1, 3);
	} else if (n->l.left->type != N_SUM) {
	    d1++;
	}
	if (n->r.right->type == N_RANGE) {
	    d2 = max2(d2, 3);
	} else {
	    d2++;
	}
	return d1 + d2;
    }
    if (n->type == N_ADD) {
	if (n->r.right->type == N_STR &&
	    (n->l.left->type == N_ADD || n->l.left->type == N_SUM) &&
	    n->l.left->r.right->type == N_STR) {
	    /* (x + s1) + s2 */
	    node_tostr(n->r.right, str_add(n->l.left->r.right->l.string,
					   n->r.right->l.string));
	    n->l.left = n->l.left->l.left;
	    return d1;
	}

	if (n->l.left->mod == T_STRING || (n->l.left->mod & T_REF) != 0) {
	    /*
	     * see if the summand operator can be used
	     */
	    switch (n->l.left->type) {
	    case N_ADD:
		n->l.left->type = N_SUM;
		d1 += 2;			/* (-2) on both sides */
		if (n->l.left->l.left->type == N_RANGE) {
		    d1++;
		}
		n->type = N_SUM;
		if (n->r.right->type == N_RANGE) {
		    d2 = max2(d2, 3);		/* at least 3 */
		} else {
		    d2++;			/* add (-2) */
		}
		return d1 + d2;

	    default:
		if (n->r.right->type != N_RANGE && n->r.right->type != N_AGGR) {
		    break;
		}
		/* fall through */
	    case N_AGGR:
		d1++;				/* add (-2) */
		n->type = N_SUM;
		if (n->r.right->type == N_RANGE) {
		    d2 = max2(d2, 3);		/* at least 3 */
		} else {
		    d2++;			/* add (-2) */
		}
		return d1 + d2;

	    case N_RANGE:
		d1 = max2(d1, 3);		/* at least 3 */
		/* fall through */
	    case N_SUM:
		n->type = N_SUM;
		if (n->r.right->type == N_RANGE) {
		    d2 = max2(d2, 3);		/* at least 3 */
		} else {
		    d2++;			/* add (-2) */
		}
		return d1 + d2;
	    }
	}
    }

    if (n->l.left->flags & F_CONST) {
	if (n->r.right->flags & F_CONST) {
	    /* c1 . c2 */
	    return opt_binconst(m);
	}
	switch (n->type) {
	case N_ADD:
	    if (!T_ARITHMETIC(n->l.left->mod) || !T_ARITHMETIC(n->r.right->mod))
	    {
		break;
	    }
	    /* fall through */
	case N_ADD_INT:
	case N_AND:
	case N_AND_INT:
	case N_EQ:
	case N_EQ_INT:
	case N_MULT:
	case N_MULT_INT:
	case N_NE:
	case N_NE_INT:
	case N_OR:
	case N_OR_INT:
	case N_XOR:
	case N_XOR_INT:
	    /* swap constant to the right */
	    t = n->l.left;
	    n->l.left = n->r.right;
	    n->r.right = t;
	    d = d1;
	    d1 = d2;
	    d2 = d;
	    break;
	}
    }
    d = max2(d1, d2 + 1);

    if ((n->r.right->type == N_INT && n->r.right->l.number == 0 &&
	 n->l.left->mod == T_INT) ||
	(n->r.right->type == N_FLOAT && NFLT_ISZERO(n->r.right) &&
	 n->l.left->mod == T_FLOAT) ||
	(n->r.right->type == nil_node && n->r.right->l.number == 0 &&
	 n->l.left->mod != T_MIXED && T_POINTER(n->l.left->mod))) {
	/*
	 * int == 0, float == 0.0, ptr == nil
	 */
	switch (n->type) {
	case N_EQ:
	case N_EQ_INT:
	    *m = opt_not(n->l.left);
	    return d1;

	case N_NE:
	case N_NE_INT:
	    *m = opt_tst(n->l.left);
	    return d1;
	}
    }

    if (T_ARITHMETIC(n->mod) && n->mod == n->l.left->mod &&
	n->mod == n->r.right->mod) {
	if (n->r.right->flags & F_CONST) {
	    /* x . c */
	    if ((n->type == n->l.left->type ||
		 (n->mod == T_INT && n->l.left->mod == T_INT &&
		  n->type == n->l.left->type + 1)) &&
		(n->l.left->r.right->flags & F_CONST)) {
		/* (x . c1) . c2 */
		switch (n->type) {
		case N_ADD:
		case N_SUB:
		    NFLT_GET(n->l.left->r.right, f1);
		    NFLT_GET(n->r.right, f2);
		    flt_add(&f1, &f2);
		    NFLT_PUT(n->l.left->r.right, f1);
		    *m = n->l.left;
		    d = d1;
		    break;

		case N_ADD_INT:
		case N_SUB_INT:
		case N_LSHIFT_INT:
		case N_RSHIFT_INT:
		    n->l.left->r.right->l.number += n->r.right->l.number;
		    *m = n->l.left;
		    d = d1;
		    break;

		case N_AND_INT:
		    n->l.left->r.right->l.number &= n->r.right->l.number;
		    *m = n->l.left;
		    d = d1;
		    break;

		case N_DIV:
		case N_MULT:
		    NFLT_GET(n->l.left->r.right, f1);
		    NFLT_GET(n->r.right, f2);
		    flt_mult(&f1, &f2);
		    NFLT_PUT(n->l.left->r.right, f1);
		    *m = n->l.left;
		    d = d1;
		    break;

		case N_DIV_INT:
		case N_MULT_INT:
		    n->l.left->r.right->l.number *= n->r.right->l.number;
		    *m = n->l.left;
		    d = d1;
		    break;

		case N_OR_INT:
		    n->l.left->r.right->l.number |= n->r.right->l.number;
		    *m = n->l.left;
		    d = d1;
		    break;

		case N_XOR_INT:
		    n->l.left->r.right->l.number ^= n->r.right->l.number;
		    *m = n->l.left;
		    d = d1;
		    break;
		}
	    } else {
		switch (n->type) {
		case N_ADD:
		    if (n->l.left->type == N_SUB) {
			if (n->l.left->l.left->type == N_FLOAT) {
			    /* (c1 - x) + c2 */
			    NFLT_GET(n->l.left->l.left, f1);
			    NFLT_GET(n->r.right, f2);
			    flt_add(&f1, &f2);
			    NFLT_PUT(n->l.left->l.left, f1);
			    *m = n->l.left;
			    return d1;
			}
			if (n->l.left->r.right->type == N_FLOAT) {
			    /* (x - c1) + c2 */
			    NFLT_GET(n->l.left->r.right, f1);
			    NFLT_GET(n->r.right, f2);
			    flt_sub(&f1, &f2);
			    NFLT_PUT(n->l.left->r.right, f1);
			    *m = n->l.left;
			    d = d1;
			}
		    }
		    break;

		case N_ADD_INT:
		    if (n->l.left->type == N_SUB ||
			n->l.left->type == N_SUB_INT) {
			if (n->l.left->l.left->type == N_INT) {
			    /* (c1 - x) + c2 */
			    n->l.left->l.left->l.number += n->r.right->l.number;
			    *m = n->l.left;
			    return d1;
			}
			if (n->l.left->r.right->type == N_INT) {
			    /* (x - c1) + c2 */
			    n->l.left->r.right->l.number -=
							n->r.right->l.number;
			    *m = n->l.left;
			    d = d1;
			}
		    }
		    break;

		case N_DIV:
		    if (n->l.left->type == N_MULT &&
			n->l.left->r.right->type == N_FLOAT &&
			!NFLT_ISZERO(n->r.right)) {
			/* (x * c1) / c2 */
			NFLT_GET(n->l.left->r.right, f1);
			NFLT_GET(n->r.right, f2);
			flt_div(&f1, &f2);
			NFLT_PUT(n->l.left->r.right, f1);
			*m = n->l.left;
			d = d1;
		    }
		    break;

		case N_MULT:
		    if (n->l.left->type == N_DIV) {
			if (n->l.left->l.left->type == N_FLOAT) {
			    /* (c1 / x) * c2 */
			    NFLT_GET(n->l.left->l.left, f1);
			    NFLT_GET(n->r.right, f2);
			    flt_mult(&f1, &f2);
			    NFLT_PUT(n->l.left->l.left, f1);
			    *m = n->l.left;
			    return d1;
			}
			if (n->l.left->r.right->type == N_FLOAT &&
			    !NFLT_ISZERO(n->l.left->r.right)) {
			    /* (x / c1) * c2 */
			    NFLT_GET(n->r.right, f1);
			    NFLT_GET(n->l.left->r.right, f2);
			    flt_div(&f1, &f2);
			    NFLT_PUT(n->r.right, f1);
			    n->l.left = n->l.left->l.left;
			    d = d1;
			}
		    }
		    break;

		case N_SUB:
		    if (n->l.left->type == N_ADD &&
			n->l.left->r.right->type == N_FLOAT) {
			/* (x + c1) - c2 */
			NFLT_GET(n->l.left->r.right, f1);
			NFLT_GET(n->r.right, f2);
			flt_sub(&f1, &f2);
			NFLT_PUT(n->l.left->r.right, f1);
			*m = n->l.left;
			d = d1;
		    }
		    break;

		case N_SUB_INT:
		    if (n->l.left->type == N_ADD_INT &&
			n->l.left->r.right->type == N_INT) {
			/* (x + c1) - c2 */
			n->l.left->r.right->l.number -= n->r.right->l.number;
			*m = n->l.left;
			d = d1;
		    }
		    break;
		}
	    }
	} else if (n->l.left->flags & F_CONST) {
	    /* c . x */
	    switch (n->type) {
	    case N_SUB:
		if (n->r.right->type == N_SUB) {
		    if (n->r.right->l.left->type == N_FLOAT) {
			/* c1 - (c2 - x) */
			NFLT_GET(n->l.left, f1);
			NFLT_GET(n->r.right->l.left, f2);
			flt_sub(&f1, &f2);
			n->type = N_ADD;
			n->l.left = n->r.right->r.right;
			n->r.right = n->r.right->l.left;
			NFLT_PUT(n->r.right, f1);
			d = d2;
		    } else if (n->r.right->r.right->type == N_FLOAT) {
			/* c1 - (x - c2) */
			NFLT_GET(n->l.left, f1);
			NFLT_GET(n->r.right->r.right, f2);
			flt_add(&f1, &f2);
			NFLT_PUT(n->l.left, f1);
			n->r.right = n->r.right->l.left;
			return d2 + 1;
		    }
		} else if (n->r.right->type == N_ADD &&
			   n->r.right->r.right->type == N_FLOAT) {
		    /* c1 - (x + c2) */
		    NFLT_GET(n->l.left, f1);
		    NFLT_GET(n->r.right->r.right, f2);
		    flt_sub(&f1, &f2);
		    NFLT_PUT(n->l.left, f1);
		    n->r.right = n->r.right->l.left;
		    return d2 + 1;
		}
		break;

	    case N_SUB_INT:
		if ((n->r.right->type == N_SUB ||
		     n->r.right->type == N_SUB_INT)) {
		    if (n->r.right->l.left->type == N_INT) {
			/* c1 - (c2 - x) */
			n->r.right->l.left->l.number -= n->l.left->l.number;
			n->type = n->r.right->type;
			n->l.left = n->r.right->r.right;
			n->r.right = n->r.right->l.left;
			d = d2;
		    } else if (n->r.right->r.right->type == N_INT) {
			/* c1 - (x - c2) */
			n->l.left->l.number += n->r.right->r.right->l.number;
			n->r.right->r.right = n->r.right->l.left;
			n->r.right->l.left = n->l.left;
			*m = n->r.right;
			return d2 + 1;
		    }
		} else if (n->r.right->type == N_ADD_INT &&
			   n->r.right->r.right->type == N_INT) {
		    /* c1 - (x + c2) */
		    n->l.left->l.number -= n->r.right->r.right->l.number;
		    n->r.right = n->r.right->l.left;
		    return d2 + 1;
		}
		break;

	    case N_DIV:
		if (n->r.right->type == N_DIV) {
		    if (n->r.right->l.left->type == N_FLOAT &&
			!NFLT_ISZERO(n->r.right->l.left)) {
			/* c1 / (c2 / x) */
			NFLT_GET(n->l.left, f1);
			NFLT_GET(n->r.right->l.left, f2);
			flt_div(&f1, &f2);
			n->type = N_MULT;
			n->l.left = n->r.right->r.right;
			n->r.right = n->r.right->l.left;
			NFLT_PUT(n->r.right, f1);
			d = d2;
		    } else if (n->r.right->r.right->type == N_FLOAT) {
			/* c1 / (x / c2) */
			NFLT_GET(n->l.left, f1);
			NFLT_GET(n->r.right->r.right, f2);
			flt_mult(&f1, &f2);
			NFLT_PUT(n->l.left, f1);
			n->r.right = n->r.right->l.left;
			return d2 + 1;
		    }
		} else if (n->r.right->type == N_MULT &&
			   n->r.right->r.right->type == N_FLOAT &&
			   !NFLT_ISZERO(n->r.right->r.right)) {
		    /* c1 / (x * c2) */
		    NFLT_GET(n->l.left, f1);
		    NFLT_GET(n->r.right->r.right, f2);
		    flt_div(&f1, &f2);
		    NFLT_PUT(n->l.left, f1);
		    n->r.right = n->r.right->l.left;
		    return d2 + 1;
		}
		break;
	    }
	}
	n = *m;

	if (T_ARITHMETIC(n->l.left->mod) && (n->r.right->flags & F_CONST)) {
	    switch (n->type) {
	    case N_ADD:
	    case N_SUB:
		if (NFLT_ISZERO(n->r.right)) {
		    *m = n->l.left;
		    d = d1;
		}
		break;

	    case N_ADD_INT:
	    case N_SUB_INT:
	    case N_LSHIFT_INT:
	    case N_RSHIFT_INT:
	    case N_XOR_INT:
		if (n->r.right->l.number == 0) {
		    *m = n->l.left;
		    d = d1;
		}
		break;

	    case N_AND_INT:
		if (n->r.right->l.number == 0) {
		    n->type = N_COMMA;
		    return opt_expr(m, FALSE);
		}
		if (n->r.right->l.number == -1) {
		    *m = n->l.left;
		    d = d1;
		}
		break;

	    case N_MULT:
		if (NFLT_ISZERO(n->r.right)) {
		    n->type = N_COMMA;
		    return opt_expr(m, FALSE);
		}
		/* fall through */
	    case N_DIV:
		if (NFLT_ISONE(n->r.right)) {
		    *m = n->l.left;
		    d = d1;
		}
		break;

	    case N_MULT_INT:
		if (n->r.right->l.number == 0) {
		    n->type = N_COMMA;
		    return opt_expr(m, FALSE);
		}
		/* fall through */
	    case N_DIV_INT:
		if (n->r.right->l.number == 1) {
		    *m = n->l.left;
		    d = d1;
		}
		break;

	    case N_MOD_INT:
		if (n->r.right->l.number == 1) {
		    n->r.right->l.number = 0;
		    n->type = N_COMMA;
		    return opt_expr(m, FALSE);
		}
		break;

	    case N_OR_INT:
		if (n->r.right->l.number == -1) {
		    n->type = N_COMMA;
		    return opt_expr(m, FALSE);
		}
		if (n->r.right->l.number == 0) {
		    *m = n->l.left;
		    d = d1;
		}
		break;
	    }
	}
    }

    return d;
}
Example #9
0
void GraphBlock::calculateBounds()
{
   QFontMetrics metrics( m_font );
   float fontHeight = metrics.height();

   // calculate the size of the caption
   float captionWidth = metrics.width( m_caption.c_str() );
   float captionHeight = fontHeight + 6;

   // go through the sockets, include their width and calculate the required block height
   float longestLeftSocketName = 0;
   float longestRightSocketName = 0;
   unsigned int leftSocketsCount = 0;
   unsigned int rightSocketsCount = 0;
   for ( std::vector< GraphBlockSocket* >::const_iterator it = m_sockets.begin(); it != m_sockets.end(); ++it )
   {
      GraphBlockSocket* socket = *it;
      switch( socket->getPosition() )
      {
      case GBSP_INPUT:
         {
            longestLeftSocketName = max2( longestLeftSocketName, socket->getNameWidth() );
            ++leftSocketsCount;
            break;
         }
      
      case GBSP_OUTPUT:
         {
            longestRightSocketName = max2( longestRightSocketName, socket->getNameWidth() );
            ++rightSocketsCount;
            break;
         }
      }
   }
   float socketSize = metrics.height() + 6;
   float socketsHeight = max2( leftSocketsCount, rightSocketsCount ) * socketSize;

   // calculate the bounds
   QRectF centralWidgetBounds = m_centralWidget->subWidgetRect( m_embeddedWidget );

   float blockWidth = max2( captionWidth, longestLeftSocketName + longestRightSocketName );
   blockWidth = max2( blockWidth, (float)centralWidgetBounds.width() ); // make sure the block isn't too narrow
   blockWidth = max2( blockWidth, 100.0f ); // make sure the block isn't too narrow
   float blockHeight = captionHeight + centralWidgetBounds.height() + socketsHeight;

   // set the caption bounds
   m_captionBounds.setWidth( blockWidth );
   m_captionBounds.setHeight( captionHeight );
   m_totalBounds = m_captionBounds;

   // set the block bounds
   m_bounds.setTop( captionHeight );
   m_bounds.setWidth( blockWidth );
   m_bounds.setHeight( blockHeight );

   // calculate the bounds of this block
   m_totalBounds = m_totalBounds.united( m_bounds );

   // set the position of the central widget
   m_centralWidget->setPos( ( blockWidth - centralWidgetBounds.width() ) * 0.5f, captionHeight );

   // position the sockets
   float leftSocketsSpacing = ( leftSocketsCount > 0 ) ? ( socketsHeight / (float)leftSocketsCount ) : 0;
   float rightSocketsSpacing = ( rightSocketsCount > 0 ) ? ( socketsHeight / (float)rightSocketsCount ) : 0;

   float rightSocketY = rightSocketsSpacing * 0.5f;
   float leftSocketY = leftSocketsSpacing * 0.5f;
   float socketsVertOffset = captionHeight + centralWidgetBounds.height();
   for ( std::vector< GraphBlockSocket* >::const_iterator it = m_sockets.begin(); it != m_sockets.end(); ++it )
   {
      GraphBlockSocket* socket = *it;

      switch( socket->getPosition() )
      {
      case GBSP_INPUT:
         {
            socket->setPos( 0, socketsVertOffset + leftSocketY );
            leftSocketY += leftSocketsSpacing;
            break;
         }

      case GBSP_OUTPUT:
         {
            socket->setPos( blockWidth - GraphWidgetUtils::g_socketWidth, socketsVertOffset + rightSocketY );
            rightSocketY += rightSocketsSpacing;
            break;
         }
      }
   }

   // include the size of the sockets in the block's bounding box
   m_totalBounds = QRectF( m_totalBounds.left() - 11, m_totalBounds.top(), m_totalBounds.right() + 21, m_totalBounds.bottom() ); 
}
Example #10
0
int max4(int a, int b, int c, int d)
{
  return max2(max2(a, b), max2(c, d));
}
inline int max3(int a, int b, int c)
{
    return max2(max2(a,b),c);
}
Example #12
0
INLINE Real rel_diff_with_floor(Real a, Real b, Real floor = EPSILON) {
  Real am = fabs(a);
  Real bm = fabs(b);
  if (am <= floor && bm <= floor) return 0.0;
  return fabs(b - a) / max2(am, bm);
}
Example #13
0
INLINE Real max_norm(Matrix<m, n> a) {
  Real x = 0.0;
  for (Int j = 0; j < n; ++j)
    for (Int i = 0; i < m; ++i) x = max2(x, fabs(a[j][i]));
  return x;
}
Example #14
0
int max4(int a,int b,int c,int d) 
{int max2(int a,int b);
 return max2(max2(max2(a,b),c),d);         /* ×Ðϸ·ÖÎö´ËÐÐ */
  
}
Example #15
0
float arrmax2(int n)
{	if (n == 1)
		return x[0];
	else
		return max2(x[n-1], arrmax2(n-1));
}
Example #16
0
/*
 * NAME:	optimize->expr()
 * DESCRIPTION:	optimize an expression
 */
static Uint opt_expr(node **m, int pop)
{
    Uint d1, d2, i;
    node *n;
    node **oldside, *side;
    Uint olddepth;

    n = *m;
    switch (n->type) {
    case N_FLOAT:
    case N_GLOBAL:
    case N_INT:
    case N_LOCAL:
    case N_STR:
    case N_NIL:
	return !pop;

    case N_TOINT:
    case N_CAST:
	return opt_expr(&n->l.left, FALSE);

    case N_CATCH:
	oldside = side_start(&side, &olddepth);
	d1 = opt_expr(&n->l.left, TRUE);
	d1 = max2(d1, side_end(&n->l.left, side, oldside, olddepth));
	if (d1 == 0) {
	    *m = node_nil();
	    (*m)->line = n->line;
	    return !pop;
	}
	return d1;

    case N_TOFLOAT:
	if (n->l.left->mod != T_INT) {
	    return opt_expr(&n->l.left, FALSE);
	}
	/* fall through */
    case N_NOT:
    case N_TST:
	if (pop) {
	    *m = n->l.left;
	    return opt_expr(m, TRUE);
	}
	return opt_expr(&n->l.left, FALSE);

    case N_TOSTRING:
	if (pop && (n->l.left->mod == T_INT || n->l.left->mod == T_FLOAT)) {
	    *m = n->l.left;
	    return opt_expr(m, TRUE);
	}
	return opt_expr(&n->l.left, FALSE);

    case N_LVALUE:
	return opt_lvalue(n->l.left);

    case N_ADD_EQ_1:
    case N_ADD_EQ_1_INT:
    case N_SUB_EQ_1:
    case N_SUB_EQ_1_INT:
	return opt_lvalue(n->l.left) + 1;

    case N_MIN_MIN:
	if (pop) {
	    n->type = N_SUB_EQ_1;
	}
	return opt_lvalue(n->l.left) + 1;

    case N_MIN_MIN_INT:
	if (pop) {
	    n->type = N_SUB_EQ_1_INT;
	}
	return opt_lvalue(n->l.left) + 1;

    case N_PLUS_PLUS:
	if (pop) {
	    n->type = N_ADD_EQ_1;
	}
	return opt_lvalue(n->l.left) + 1;

    case N_PLUS_PLUS_INT:
	if (pop) {
	    n->type = N_ADD_EQ_1_INT;
	}
	return opt_lvalue(n->l.left) + 1;

    case N_FUNC:
	m = &n->l.left->r.right;
	n = *m;
	if (n == (node *) NULL) {
	    return 1;
	}

	d1 = 0;
	for (i = 0; n->type == N_PAIR; ) {
	    oldside = side_start(&side, &olddepth);
	    d2 = opt_expr(&n->l.left, FALSE);
	    d1 = max3(d1, i + d2,
		      i + side_end(&n->l.left, side, oldside, olddepth));
	    m = &n->r.right;
	    n = n->l.left;
	    i += (n->type == N_LVALUE ||
		  (n->type == N_COMMA && n->r.right->type == N_LVALUE)) ? 4 : 1;
	    n = *m;
	}
	if (n->type == N_SPREAD) {
	    m = &n->l.left;
	}
	oldside = side_start(&side, &olddepth);
	d2 = opt_expr(m, FALSE);
	return max3(d1, i + d2, i + side_end(m, side, oldside, olddepth));

    case N_INSTANCEOF:
	return opt_expr(&n->l.left, FALSE) + 1;

    case N_GE:
    case N_GT:
    case N_LE:
    case N_LT:
	if (n->l.left->mod != n->r.right->mod) {
	    return max2(opt_expr(&n->l.left, FALSE),
			opt_expr(&n->r.right, FALSE) + 1);
	}
	/* fall through */
    case N_EQ:
    case N_NE:
	if (pop) {
	    d1 = opt_expr(&n->l.left, TRUE);
	    if (d1 == 0) {
		*m = n->r.right;
		return opt_expr(m, TRUE);
	    }
	    d2 = opt_expr(&n->r.right, TRUE);
	    if (d2 == 0) {
		*m = n->l.left;
		return d1;
	    }
	    n->type = N_COMMA;
	    side_add(m, d1);
	    return d2;
	}
	return opt_binop(m);

    case N_DIV_INT:
    case N_MOD_INT:
	if (n->r.right->type == N_INT && n->r.right->l.number == 0) {
	    d1 = opt_binop(m);
	    return (d1 == 1) ? !pop : d1;
	}
	/* fall through */
    case N_ADD_INT:
    case N_AND_INT:
    case N_EQ_INT:
    case N_GE_INT:
    case N_GT_INT:
    case N_LE_INT:
    case N_LSHIFT_INT:
    case N_LT_INT:
    case N_MULT_INT:
    case N_NE_INT:
    case N_OR_INT:
    case N_RSHIFT_INT:
    case N_SUB_INT:
    case N_XOR_INT:
	if (pop) {
	    d1 = opt_expr(&n->l.left, TRUE);
	    if (d1 == 0) {
		*m = n->r.right;
		return opt_expr(m, TRUE);
	    }
	    d2 = opt_expr(&n->r.right, TRUE);
	    if (d2 == 0) {
		*m = n->l.left;
		return d1;
	    }
	    n->type = N_COMMA;
	    side_add(m, d1);
	    return d2;
	}
	/* fall through */
    case N_ADD:
    case N_AND:
    case N_DIV:
    case N_LSHIFT:
    case N_MOD:
    case N_MULT:
    case N_OR:
    case N_RSHIFT:
    case N_SUB:
    case N_SUM:
    case N_XOR:
	d1 = opt_binop(m);
	return (d1 == 1) ? !pop : d1;

    case N_INDEX:
	if (n->l.left->type == N_STR && n->r.right->type == N_INT) {
	    if (n->r.right->l.number < 0 ||
		n->r.right->l.number >= (long) n->l.left->l.string->len) {
		return 2;
	    }
	    node_toint(n, (Int) str_index(n->l.left->l.string,
					  (long) n->r.right->l.number));
	    return !pop;
	}
	if (n->l.left->type == N_FUNC && n->r.right->mod == T_INT) {
	    if (n->l.left->r.number == kf_status) {
		n->type = N_FUNC;
		if (n->l.left->l.left->r.right != (node *) NULL) {
		    /* status(obj)[i] */
		    n = n->l.left;
		    n->type = N_STR;
		    n->r.right = n->l.left;
		    n->l.string = n->l.left->l.string;
		    n = n->r.right;
		    n->type = N_PAIR;
		    n->l.left = n->r.right;
		    n->r.right = (*m)->r.right;
		    (*m)->r.number = ((long) KFCALL << 24) | KF_STATUSO_IDX;
		} else {
		    /* status()[i] */
		    n->l.left = n->l.left->l.left;
		    n->l.left->r.right = n->r.right;
		    n->r.number = ((long) KFCALL << 24) | KF_STATUS_IDX;
		}
		return opt_expr(m, pop);
	    }
	    if (n->l.left->r.number == kf_call_trace) {
		/* call_trace()[i] */
		n->type = N_FUNC;
		n->l.left = n->l.left->l.left;
		n->l.left->r.right = n->r.right;
		n->r.number = ((long) KFCALL << 24) | KF_CALLTR_IDX;
		return opt_expr(m, pop);
	    }
	}
	return max2(opt_expr(&n->l.left, FALSE),
		    opt_expr(&n->r.right, FALSE) + 1);

    case N_ADD_EQ:
    case N_ADD_EQ_INT:
    case N_AND_EQ:
    case N_AND_EQ_INT:
    case N_DIV_EQ:
    case N_DIV_EQ_INT:
    case N_LSHIFT_EQ:
    case N_LSHIFT_EQ_INT:
    case N_MOD_EQ:
    case N_MOD_EQ_INT:
    case N_MULT_EQ:
    case N_MULT_EQ_INT:
    case N_OR_EQ:
    case N_OR_EQ_INT:
    case N_RSHIFT_EQ:
    case N_RSHIFT_EQ_INT:
    case N_SUB_EQ:
    case N_SUB_EQ_INT:
    case N_SUM_EQ:
    case N_XOR_EQ:
    case N_XOR_EQ_INT:
	return opt_asgnexp(m, pop);

    case N_ASSIGN:
	if (n->l.left->type == N_AGGR) {
	    d2 = 0;
	    for (n = n->l.left->l.left; n->type == N_PAIR; n = n->r.right) {
		d1 = opt_lvalue(n->l.left);
		d2 += (d1 < 4) ? d1 : 4;
	    }
	    d1 = opt_lvalue(n);
	    d2 += (d1 < 4) ? d1 : 4;
	    return d2 + max2(2, opt_expr(&(*m)->r.right, FALSE));
	} else {
	    d1 = opt_lvalue(n->l.left);
	    return max2(d1, ((d1 < 4) ? d1 : 4) + opt_expr(&n->r.right, FALSE));
	}

    case N_COMMA:
	side_add(m, opt_expr(&n->l.left, TRUE));
	return opt_expr(m, pop);

    case N_LAND:
	d1 = opt_cond(&n->l.left, FALSE);
	if (n->l.left->flags & F_CONST) {
	    if (!opt_ctest(n->l.left)) {
		/* false && x */
		*m = n->l.left;
		return !pop;
	    }
	    /* true && x */
	    n->type = N_TST;
	    n->l.left = n->r.right;
	    return opt_expr(m, pop);
	}

	oldside = side_start(&side, &olddepth);
	d2 = opt_cond(&n->r.right, pop);
	d2 = max2(d2, side_end(&n->r.right, side, oldside, olddepth));
	if (n->r.right->flags & F_CONST) {
	    if (pop) {
		*m = n->l.left;
		return opt_expr(m, TRUE);
	    }
	    if (!opt_ctest(n->r.right)) {
		/* x && false */
		n->type = N_COMMA;
		return opt_expr(m, FALSE);
	    }
	    /* x && true */
	    n->type = N_TST;
	    return d1;
	}
	if (n->r.right->type == N_COMMA) {
	    n = n->r.right;
	    if ((n->r.right->flags & F_CONST) && !opt_ctest(n->r.right)) {
		/* x && (y, false) --> (x && y, false) */
		(*m)->r.right = n->l.left;
		n->l.left = *m;
		*m = n;
		return opt_expr(m, pop);
	    }
	}
	return max2(d1, d2);

    case N_LOR:
	d1 = opt_cond(&n->l.left, FALSE);
	if (n->l.left->flags & F_CONST) {
	    if (opt_ctest(n->l.left)) {
		/* true || x */
		*m = n->l.left;
		return !pop;
	    }
	    /* false || x */
	    n->type = N_TST;
	    n->l.left = n->r.right;
	    return opt_expr(m, pop);
	}

	oldside = side_start(&side, &olddepth);
	d2 = opt_cond(&n->r.right, pop);
	d2 = max2(d2, side_end(&n->r.right, side, oldside, olddepth));
	if (n->r.right->flags & F_CONST) {
	    if (pop) {
		*m = n->l.left;
		return opt_expr(m, TRUE);
	    }
	    if (opt_ctest(n->r.right)) {
		/* x || true */
		n->type = N_COMMA;
		return opt_expr(m, FALSE);
	    }
	    /* x || false */
	    n->type = N_TST;
	    return d1;
	}
	if (n->r.right->type == N_COMMA) {
	    n = n->r.right;
	    if ((n->r.right->flags & F_CONST) && opt_ctest(n->r.right)) {
		/* x || (y, true) --> (x || y, true) */
		(*m)->r.right = n->l.left;
		n->l.left = *m;
		*m = n;
		return opt_expr(m, pop);
	    }
	}
	return max2(d1, d2);

    case N_QUEST:
	i = opt_cond(&n->l.left, FALSE);
	if (n->l.left->flags & F_CONST) {
	    if (opt_ctest(n->l.left)) {
		*m = n->r.right->l.left;
	    } else {
		*m = n->r.right->r.right;
	    }
	    return opt_expr(m, pop);
	}
	if (n->l.left->type == N_COMMA && (n->l.left->r.right->flags & F_CONST))
	{
	    side_add(&n->l.left, i);
	    if (opt_ctest(n->l.left)) {
		*m = n->r.right->l.left;
	    } else {
		*m = n->r.right->r.right;
	    }
	    return opt_expr(m, pop);
	}

	n = n->r.right;
	oldside = side_start(&side, &olddepth);
	d1 = opt_expr(&n->l.left, pop);
	d1 = max2(d1, side_end(&n->l.left, side, oldside, olddepth));
	if (d1 == 0) {
	    n->l.left = (node *) NULL;
	}
	oldside = side_start(&side, &olddepth);
	d2 = opt_expr(&n->r.right, pop);
	d2 = max2(d2, side_end(&n->r.right, side, oldside, olddepth));
	if (d2 == 0) {
	    n->r.right = (node *) NULL;
	}
	return max3(i, d1, d2);

    case N_RANGE:
	d1 = opt_expr(&n->l.left, FALSE);
	d2 = 1;
	if (n->r.right->l.left != (node *) NULL) {
	    d2 = opt_expr(&n->r.right->l.left, FALSE);
	    if ((n->l.left->mod == T_STRING || (n->l.left->mod & T_REF) != 0) &&
		n->r.right->l.left->type == N_INT &&
		n->r.right->l.left->l.number == 0) {
		/*
		 * str[0 .. x] or arr[0 .. x]
		 */
		n->r.right->l.left = (node *) NULL;
		d2 = 1;
	    } else {
		d1 = max2(d1, d2 + 1);
		d2 = 2;
	    }
	}
	if (n->r.right->r.right != (node *) NULL) {
	    d1 = max2(d1, d2 + opt_expr(&n->r.right->r.right, FALSE));
	}
	if (n->l.left->type == N_STR) {
	    long from, to;

	    if (n->r.right->l.left == (node *) NULL) {
		from = 0;
	    } else {
		if (n->r.right->l.left->type != N_INT) {
		    return d1;
		}
		from = n->r.right->l.left->l.number;
	    }
	    if (n->r.right->r.right == (node *) NULL) {
		to = n->l.left->l.string->len - 1;
	    } else {
		if (n->r.right->r.right->type != N_INT) {
		    return d1;
		}
		to = n->r.right->r.right->l.number;
	    }
	    if (from >= 0 && from <= to + 1 &&
		to < (long) n->l.left->l.string->len) {
		node_tostr(n, str_range(n->l.left->l.string, from, to));
		return !pop;
	    }
	}
	return d1;

    case N_AGGR:
	if (n->mod == T_MAPPING) {
	    n = n->l.left;
	    if (n == (node *) NULL) {
		return 1;
	    }

	    d1 = 0;
	    for (i = 0; n->type == N_PAIR; i += 2) {
		oldside = side_start(&side, &olddepth);
		d2 = opt_expr(&n->l.left->l.left, FALSE);
		d1 = max3(d1, i + d2, i + side_end(&n->l.left->l.left,
						   side, oldside, olddepth));
		oldside = side_start(&side, &olddepth);
		d2 = opt_expr(&n->l.left->r.right, FALSE);
		d1 = max3(d1, i + 1 + d2,
			  i + 1 + side_end(&n->l.left->r.right, side, oldside,
					   olddepth));
		n = n->r.right;
	    }
	    oldside = side_start(&side, &olddepth);
	    d2 = opt_expr(&n->l.left, FALSE);
	    d1 = max3(d1, i + d2,
		      i + side_end(&n->l.left, side, oldside, olddepth));
	    oldside = side_start(&side, &olddepth);
	    d2 = opt_expr(&n->r.right, FALSE);
	    return max3(d1, i + 1 + d2,
			i + 1 + side_end(&n->r.right, side, oldside, olddepth));
	} else {
	    m = &n->l.left;
	    n = *m;
	    if (n == (node *) NULL) {
		return 1;
	    }

	    d1 = 0;
	    for (i = 0; n->type == N_PAIR; i++) {
		oldside = side_start(&side, &olddepth);
		d2 = opt_expr(&n->l.left, FALSE);
		d1 = max3(d1, i + d2,
			  i + side_end(&n->l.left, side, oldside, olddepth));
		m = &n->r.right;
		n = *m;
	    }
	    oldside = side_start(&side, &olddepth);
	    d2 = opt_expr(m, FALSE);
	    return max3(d1, i + d2, i + side_end(m, side, oldside, olddepth));
	}
    }

# ifdef DEBUG
    fatal("unknown expression type %d", n->type);
# endif
    return 0;
}
Example #17
0
/*
 * NAME:	optimize->stmt()
 * DESCRIPTION:	optimize a statement
 */
node *opt_stmt(node *first, Uint *depth)
{
    node *n, **m, **prev;
    Uint d;
    Uint d1, d2;
    int i;
    node *side;


    if (first == (node *) NULL) {
	*depth = 0;
	return (node *) NULL;
    }

    d = 0;
    prev = m = &first;

    for (;;) {
	n = ((*m)->type == N_PAIR) ? (*m)->l.left : *m;
	switch (n->type) {
	case N_BLOCK:
	    n->l.left = opt_stmt(n->l.left, &d1);
	    if (n->l.left == (node *) NULL) {
		n = (node *) NULL;
	    }
	    d = max2(d, d1);
	    break;

	case N_CASE:
	    n->l.left = opt_stmt(n->l.left, &d1);
	    d = max2(d, d1);
	    break;

	case N_COMPOUND:
	    n->l.left = opt_stmt(n->l.left, &d1);
	    if (n->l.left == (node *) NULL) {
		n = (node *) NULL;
	    } else if (n->r.right != (node *) NULL) {
		n->r.right = opt_stmt(n->r.right, &d2);
		d1 = max2(d1, d2);
	    }
	    d = max2(d, d1);
	    break;

	case N_DO:
	    n->r.right = opt_stmt(n->r.right, &d1);
	    side_start(&side, depth);
	    d2 = opt_cond(&n->l.left, FALSE);
	    d2 = max2(d2, side_end(&n->l.left, side, (node **) NULL, 0));
	    d = max3(d, d1, d2);
	    break;

	case N_FOR:
	    side_start(&side, depth);
	    d1 = opt_cond(&n->l.left, FALSE);
	    d1 = max2(d1, side_end(&n->l.left, side, (node **) NULL, 0));
	    i = opt_const(n->l.left);
	    if (i == 0) {
		/* never */
		n->r.right = opt_skip(n->r.right);
		if (n->r.right == (node *) NULL) {
		    n->type = N_POP;
		    n = opt_stmt(n, &d1);
		    d = max2(d, d1);
		    break;
		}
	    } else if (i > 0) {
		/* always */
		n->type = N_FOREVER;
		n = opt_stmt(n, &d1);
		d = max2(d, d1);
		break;
	    }

	    n->r.right = opt_stmt(n->r.right, &d2);
	    d = max3(d, d1, d2);
	    break;

	case N_FOREVER:
	    if (n->l.left != (node *) NULL) {
		side_start(&side, depth);
		d1 = opt_expr(&n->l.left, TRUE);
		d1 = max2(d1, side_end(&n->l.left, side, (node **) NULL, 0));
		if (d1 == 0) {
		    n->l.left = (node *) NULL;
		}
	    } else {
		d1 = 0;
	    }
	    n->r.right = opt_stmt(n->r.right, &d2);
	    d = max3(d, d1, d2);
	    break;

	case N_RLIMITS:
	    side_start(&side, depth);
	    d1 = opt_expr(&n->l.left->l.left, FALSE);
	    d1 = max2(d1, side_end(&n->l.left->l.left, side, (node **) NULL,
				   0));

	    side_start(&side, depth);
	    d2 = opt_expr(&n->l.left->r.right, FALSE);
	    d2 = max2(d2, side_end(&n->l.left->r.right, side, (node **) NULL,
				   0));

	    d1 = max2(d1, d2 + 1);
	    n->r.right = opt_stmt(n->r.right, &d2);
	    d = max3(d, d1, d2);
	    break;

	case N_CATCH:
	    n->l.left = opt_stmt(n->l.left, &d1);
	    if (n->l.left == (node *) NULL) {
		n = opt_stmt(opt_skip(n->r.right), &d1);
		d = max2(d, d1);
	    } else {
		n->r.right = opt_stmt(n->r.right, &d2);
		d = max3(d, d1, d2);
	    }
	    break;

	case N_IF:
	    side_start(&side, depth);
	    d1 = opt_cond(&n->l.left, FALSE);
	    d1 = max2(d1, side_end(&n->l.left, side, (node **) NULL, 0));

	    i = opt_const(n->l.left);
	    if (i == 0) {
		n->r.right->l.left = opt_skip(n->r.right->l.left);
	    } else if (i > 0) {
		n->r.right->r.right = opt_skip(n->r.right->r.right);
	    }
	    n->r.right->l.left = opt_stmt(n->r.right->l.left, &d2);
	    d1 = max2(d1, d2);
	    n->r.right->r.right = opt_stmt(n->r.right->r.right, &d2);

	    if (n->r.right->l.left == (node *) NULL) {
		if (n->r.right->r.right == (node *) NULL) {
		    n->type = N_POP;
		    n = opt_stmt(n, &d1);
		    d = max2(d, d1);
		    break;
		}
		n->l.left = opt_not(n->l.left);
		n->r.right->l.left = n->r.right->r.right;
		n->r.right->r.right = (node *) NULL;
	    }
	    d = max3(d, d1, d2);
	    break;

	case N_PAIR:
	    n = opt_stmt(n, &d1);
	    d = max2(d, d1);
	    break;

	case N_POP:
	    side_start(&side, depth);
	    d1 = opt_expr(&n->l.left, TRUE);
	    if (d1 == 0) {
		n->l.left = (node *) NULL;
	    }
	    d = max3(d, d1, side_end(&n->l.left, side, (node **) NULL, 0));
	    if (n->l.left == (node *) NULL) {
		n = (node *) NULL;
	    }
	    break;

	case N_RETURN:
	    side_start(&side, depth);
	    d1 = opt_expr(&n->l.left, FALSE);
	    d = max3(d, d1, side_end(&n->l.left, side, (node **) NULL, 0));
	    break;

	case N_SWITCH_INT:
	case N_SWITCH_RANGE:
	case N_SWITCH_STR:
	    n->r.right->r.right = opt_stmt(n->r.right->r.right, &d1);
	    if (n->r.right->r.right == (node *) NULL) {
		n = n->r.right;
		n->type = N_POP;
		n = opt_stmt(n, &d1);
		d = max2(d, d1);
	    } else {
		side_start(&side, depth);
		d2 = opt_expr(&n->r.right->l.left, FALSE);
		d2 = max2(d2, side_end(&n->r.right->l.left, side,
				       (node **) NULL, 0));
		d = max3(d, d1, d2);
	    }
	    break;
	}

	if ((*m)->type == N_PAIR) {
	    if (n == (node *) NULL) {
		*m = (*m)->r.right;
	    } else {
		(*m)->l.left = n;
		if (n->flags & F_END) {
		    n = opt_skip((*m)->r.right);
		    if (n == (node *) NULL) {
			*m = (*m)->l.left;
			break;
		    }
		    (*m)->r.right = n;
		}
		prev = m;
		m = &(*m)->r.right;
	    }
	} else {
	    *m = n;
	    if (n == (node *) NULL && prev != m) {
		*prev = (*prev)->l.left;
	    }
	    break;
	}
    }

    *depth = d;
    return first;
}
Example #18
0
File: common.c Project: RAOF/piglit
static float max3(float x, float y, float z)
{
	return max2(x, max2(y, z));
}
Example #19
0
static double max4(double a, double b, double c, double d)
{
    return max2(max2(a,b), max2(c,d));
}
Example #20
0
/*
 * TODO move this function to similarity.c
 * TODO this function is a smithwatermangotoh() clone
 */
static double _mongeelkan(char *a, char *b)
{
	float		**matrix;		/* dynamic programming matrix */
	int		alen, blen;
	int		i, j;
	double		maxvalue;

	alen = strlen(a);
	blen = strlen(b);

	elog(DEBUG2, "alen: %d; blen: %d", alen, blen);

	if (alen == 0)
		return blen;
	if (blen == 0)
		return alen;

	matrix = (float **) malloc((alen + 1) * sizeof(float *));

	if (matrix == NULL)
		elog(ERROR, "memory exaushted for array size %d", alen);

	for (i = 0; i <= alen; i++)
	{
		matrix[i] = (float *) malloc((blen + 1) * sizeof(float));
		if (matrix[i] == NULL)
			elog(ERROR, "memory exaushted for array size %d", blen);
	}

#ifdef PGS_IGNORE_CASE
	elog(DEBUG2, "case-sensitive turns off");
	for (i = 0; i < alen; i++)
		a[i] = tolower(a[i]);
	for (j = 0; j < blen; j++)
		b[j] = tolower(b[j]);
#endif

	maxvalue = 0.0;

	/* initial values */
	for (i = 0; i <= alen; i++)
	{
		float c = megapcost(a, b, i, 0);

		if (i == 0)
			matrix[0][0] = max2(0.0, c);
		else
		{
			float	maxgapcost = 0.0;
			int		wstart = i - PGS_SWG_WINDOW_SIZE;
			int		k;

			if (wstart < 1)
				wstart = 1;

			for (k = wstart; k < i; k++)
				maxgapcost = max2(maxgapcost, matrix[i - k][0] - swggapcost(i - k, i));
			matrix[i][0] = max3(0.0, maxgapcost, c);
		}

		if (matrix[i][0] > maxvalue)
			maxvalue = matrix[i][0];
	}
	for (j = 0; j <= blen; j++)
	{
		float c = megapcost(a, b, 0, j);

		if (j == 0)
			matrix[0][0] = max2(0.0, c);
		else
		{
			float	maxgapcost = 0.0;
			int		wstart = j - PGS_SWG_WINDOW_SIZE;
			int		k;

			if (wstart < 1)
				wstart = 1;

			for (k = wstart; k < j; k++)
				maxgapcost = max2(maxgapcost, matrix[0][j - k] - swggapcost(j - k, j));
			matrix[0][j] = max3(0.0, maxgapcost, c);
		}

		if (matrix[0][j] > maxvalue)
			maxvalue = matrix[0][j];
	}

	for (i = 1; i <= alen; i++)
	{
		for (j = 1; j <= blen; j++)
		{
			int		wstart;
			int		k;
			float	maxgapcost1 = 0.0,
					maxgapcost2 = 0.0;

			/* get operation cost */
			float c = megapcost(a, b, i, j);

			wstart = i - PGS_SWG_WINDOW_SIZE;
			if (wstart < 1)
				wstart = 1;
			for (k = wstart; k < i; k++)
				maxgapcost1 = max2(maxgapcost1, matrix[i - k][0] - swggapcost(i - k, i));

			wstart = j - PGS_SWG_WINDOW_SIZE;
			if (wstart < 1)
				wstart = 1;
			for (k = wstart; k < j; k++)
				maxgapcost2 = max2(maxgapcost2, matrix[0][j - k] - swggapcost(j - k, j));

			matrix[i][j] = max4(0.0,
								maxgapcost1,
								maxgapcost2,
								matrix[i - 1][j - 1] + c);
			elog(DEBUG2,
				 "(i, j) = (%d, %d); cost(%c, %c): %.3f; max(zero, top, left, diag) = (0.0, %.3f, %.3f, %.3f) = %.3f",
				 i, j, a[i - 1], b[j - 1], c,
				 maxgapcost1,
				 maxgapcost2,
				 matrix[i - 1][j - 1] + c, matrix[i][j]);

			if (matrix[i][j] > maxvalue)
				maxvalue = matrix[i][j];
		}
	}

	for (i = 0; i <= alen; i++)
		free(matrix[i]);
	free(matrix);

	return maxvalue;
}
Example #21
0
int cg(
  int n,
  double* x,
  double* pfx,
  lbfgs_evaluate_t evaluate,
  lbfgs_progress_t progress,
  void* instance,
  const lbfgs_parameter_t* _param
) {
  static const double RHO = 0.01;
  static const double SIG = 0.5;
  static const double INT = 0.1;
  static const double EXT = 3.0;
  static const double RATIO = 100.0;

  int ret;
  int k, ls_count, ls_success, ls_failed = 0, n_evaluate = 0;
  lbfgs_parameter_t param = (_param) ? (*_param) : default_param;
  double f0, f1, f2 = 0.0, f3, d1, d2, d3, z1, z2 = 0.0, z3, limit, A, B, C;
  double xnorm, gnorm, rate;
  double* df0, *df1, *df2, *s, *x0;
  double* pf = 0;

  if (progress == 0) {
    progress = default_lbfgs_progress;
  }

  if (n <= 0) {
    return LBFGSERR_INVALID_N;
  }
  if (param.epsilon < 0.0) {
    return LBFGSERR_INVALID_EPSILON;
  }
  if (param.past < 0) {
    return LBFGSERR_INVALID_TESTPERIOD;
  }
  if (param.delta < 0.0) {
    return LBFGSERR_INVALID_DELTA;
  }
  if (param.max_linesearch <= 0) {
    return LBFGSERR_INVALID_MAXLINESEARCH;
  }

  df0 = vecalloc(n);
  df1 = vecalloc(n);
  df2 = vecalloc(n);
  s = vecalloc(n);
  x0 = vecalloc(n);

  if (param.past > 0) {
    pf = vecalloc((size_t)param.past);
  }

  f1 = evaluate(instance, n, x, df1, 0);
  n_evaluate++;

  if (pf) {
    pf[0] = f1;
  }

  vec2norm(&xnorm, x, n);
  vec2norm(&gnorm, df1, n);
  if (xnorm < 1.0) {
    xnorm = 1.0;
  }
  if (gnorm / xnorm <= param.epsilon) {
    ret = LBFGS_ALREADY_MINIMIZED;
    goto cg_exit;
  }

  vecncpy(s, df1, n);
  vecdot(&d1, s, s, n);
  d1 = -d1;
  /**
  * Compute the initial step z1:
  */
  z1 = 1.0 / (1.0 - d1);

  k = 1;
  for (;;) {
    /* Store the current position and gradient vectors. */
    f0 = f1;
    veccpy(x0, x, n);
    veccpy(df0, df1, n);

    /* update x using current step: x=x+z1*s */
    vecadd(x, s, z1, n);

    f2 = evaluate(instance, n, x, df2, 0);
    n_evaluate++;

    vecdot(&d2, df2, s, n);
    /* set point 3 equal to point 1 */
    f3 = f1;
    d3 = d1;
    z3 = -z1;

    /* begin line search */
    ls_success = 0;
    ls_count = 0;
    limit = -1.0;
    for (;;) {
      while (f2 > f1 + RHO * z1 * d1 || d2 > -SIG * d1) {
        limit = z1;
        if (f2 > f1) {
          /* quadratic fit */
          z2 = z3 - (0.5 * d3 * z3 * z3) / (d3 * z3 + f2 - f3);
        } else {
          /* cubic fit */
          A = 6 * (f2 - f3) / z3 + 3 * (d2 + d3);
          B = 3 * (f3 - f2) - z3 * (d3 + 2 * d2);
          z2 = (sqrt(B * B - A * d2 * z3 * z3) - B) / A;
        }

        if (isinf(z2) || isnan(z2)) {
          /* if we had a numerical problem then bisect */
          z2 = z3 / 2.0;
        }

        /* don't accept too close to limits */
        z2 = max2(min2(z2, INT* z3), (1.0 - INT) * z3);
        /* update step and x */
        z1 = z1 + z2;
        vecadd(x, s, z2, n);

        f2 = evaluate(instance, n, x, df2, 0);
        n_evaluate++;
        ls_count++;

        vecdot(&d2, df2, s, n);
        z3 = z3 - z2;
      }

      if (f2 > f1 + z1 * RHO * d1 || d2 > -SIG * d1) {
        /* a line search failure */
        break;
      } else if (d2 > SIG * d1) {
        /* a line search success */
        ls_success = 1;
        break;
      } else if (ls_count >= param.max_linesearch) {
        ret = LBFGSERR_MAXIMUMLINESEARCH;
        goto cg_exit;
      }

      /* cubic extrapolation */
      A = 6.0 * (f2 - f3) / z3 + 3.0 * (d2 + d3);
      B = 3.0 * (f3 - f2) - z3 * (d3 + 2 * d2);
      z2 = -d2 * z3 * z3 / (B + sqrt(B * B - A * d2 * z3 * z3));
      /* adjust current step z2 for many cases */
      if (isnan(z2) || isinf(z2) || z2 < 0.0) {
        if (limit < -0.5) {
          z2 = z1 * (EXT - 1.0);
        } else {
          z2 = (limit - z1) / 2.0;
        }
      } else if (limit > -0.5 && z2 + z1 > limit) {
        z2 = (limit - z1) / 2.0;
      } else if (limit < -0.5 && z2 + z1 > z1 * EXT) {
        z2 = z1 * (EXT - 1.0);
      } else if (z2 < -z3 * INT) {
        z2 = -z3 * INT;
      } else if (limit > -0.5 && z2 < (limit - z1) * (1.0 - INT)) {
        z2 = (limit - z1) * (1.0 - INT);
      }

      /* set point 3 equal to point 2 */
      f3 = f2;
      d3 = d2;
      z3 = -z2;

      z1 = z1 + z2;
      vecadd(x, s, z2, n);

      f2 = evaluate(instance, n, x, df2, 0);
      n_evaluate++;
      ls_count++;

      vecdot(&d2, df2, s, n);
    }

    if (ls_success) {
      vec2norm(&xnorm, x, n);
      vec2norm(&gnorm, df2, n);
      if ((ret = progress(instance, n, x, df2, f2, xnorm, gnorm, z2, k, n_evaluate)) != 0) {
        ret = LBFGSERR_CANCELED;
        break;
      }
      if (xnorm < 1.0) {
        xnorm = 1.0;
      }
      if (gnorm / xnorm <= param.epsilon) {
        ret = LBFGS_CONVERGENCE;
        break;
      }

      if (pf) {
        if (param.past <= k) {
          rate = (pf[k % param.past] - f2) / f2;
          if (rate < param.delta) {
            ret = LBFGS_CONVERGENCE_DELTA;
            break;
          }
        }
        pf[k % param.past] = f2;
      }

      if (param.max_iterations != 0 && param.max_iterations < k + 1) {
        ret = LBFGSERR_MAXIMUMITERATION;
        break;
      }
      k++;


      f1 = f2;
      /**
      * Polack-Ribiere direction
      * s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2
      */
      vecdot(&A, df2, df2, n);
      vecdot(&B, df1, df2, n);
      vecdot(&C, df1, df1, n);
      vecscale(s, (A - B) / C, n);
      vecadd(s, df2, -1.0, n);

      vecswap(df1, df2, n);
      vecdot(&d2, df1, s, n);

      if (d2 > 0) {
        vecncpy(s, df1, n);
        vecdot(&d2, s, s, n);
        d2 = -d2;
      }

      z1 = z1 * min2(RATIO, d1 / (d2 - DBL_MIN));
      d1 = d2;
      ls_failed = 0;
    } else {
      /* restore previous point */
      f1 = f0;
      veccpy(x, x0, n);
      veccpy(df1, df0, n);

      if (ls_failed) {
        /* line search failed twice */
        ret = LBFGSERR_LINE_SEARCH_FAILED;
        break;
      }

      vecswap(df1, df2, n);
      vecncpy(s, df1, n);/* try steepest */
      vecdot(&d1, s, s, n);
      d1 = -d1;
      z1 = 1.0 / (1.0 - d1);
      ls_failed = 1;
    }
  }

cg_exit:
  if (pfx) {
    *pfx = f2;
  }

  vecfree(pf);
  vecfree(x0);
  vecfree(s);
  vecfree(df2);
  vecfree(df1);
  vecfree(df0);
  return ret;
}
Example #22
0
inline static double max3(double a, double b, double c) {
  return max2(max2(a, b), c);
}
Example #23
0
	static
	__inline
	void solveFriction(Constraint4& cs, 
		const float4& posA, float4& linVelA, float4& angVelA, float invMassA, const Matrix3x3& invInertiaA,
		const float4& posB, float4& linVelB, float4& angVelB, float invMassB, const Matrix3x3& invInertiaB, 
		float maxRambdaDt[4], float minRambdaDt[4])
	{
		if( cs.m_fJacCoeffInv[0] == 0 && cs.m_fJacCoeffInv[0] == 0 ) return;
		const float4& center = cs.m_center;

		float4 n = -cs.m_linear;

		float4 tangent[2];
#if 1		
		btPlaneSpace1 (&n, &tangent[0],&tangent[1]);
#else
		float4 r = cs.m_worldPos[0]-center;
		tangent[0] = cross3( n, r );
		tangent[1] = cross3( tangent[0], n );
		tangent[0] = normalize3( tangent[0] );
		tangent[1] = normalize3( tangent[1] );
#endif

		float4 angular0, angular1, linear;
		float4 r0 = center - posA;
		float4 r1 = center - posB;
		for(int i=0; i<2; i++)
		{
			setLinearAndAngular( tangent[i], r0, r1, linear, angular0, angular1 );
			float rambdaDt = calcRelVel(linear, -linear, angular0, angular1,
				linVelA, angVelA, linVelB, angVelB );
			rambdaDt *= cs.m_fJacCoeffInv[i];

				{
					float prevSum = cs.m_fAppliedRambdaDt[i];
					float updated = prevSum;
					updated += rambdaDt;
					updated = max2( updated, minRambdaDt[i] );
					updated = min2( updated, maxRambdaDt[i] );
					rambdaDt = updated - prevSum;
					cs.m_fAppliedRambdaDt[i] = updated;
				}

			float4 linImp0 = invMassA*linear*rambdaDt;
			float4 linImp1 = invMassB*(-linear)*rambdaDt;
			float4 angImp0 = mtMul1(invInertiaA, angular0)*rambdaDt;
			float4 angImp1 = mtMul1(invInertiaB, angular1)*rambdaDt;
#ifdef _WIN32
			btAssert(_finite(linImp0.x));
			btAssert(_finite(linImp1.x));
#endif
			linVelA += linImp0;
			angVelA += angImp0;
			linVelB += linImp1;
			angVelB += angImp1;
		}

		{	//	angular damping for point constraint
			float4 ab = normalize3( posB - posA );
			float4 ac = normalize3( center - posA );
			if( dot3F4( ab, ac ) > 0.95f || (invMassA == 0.f || invMassB == 0.f))
			{
				float angNA = dot3F4( n, angVelA );
				float angNB = dot3F4( n, angVelB );

				angVelA -= (angNA*0.1f)*n;
				angVelB -= (angNB*0.1f)*n;
			}
		}
	}
Example #24
0
int setdf(float mval)
{
  int i,j,k,n,nflat,ni,ip,imin,err,jn,in,np1,nt;
  float fact[9],per=1.;

/*  Initialize boundaries  */
  for(i=i1; i< n1; i++)
  {
     dir[i][i2]= -1;
     dir[i][n2-1]= -1;
  }
  for(i=i2; i< n2; i++)
  {
     dir[i1][i]= -1;
     dir[n1-1][i]= -1;
  }
/*  initialize internal pointers */
  for(i=i2+1; i< n2-1; i++)for(j=i1+1; j<n1-1; j++)
  {
    if(elev[j][i] <= mval)dir[j][i]= -1;
    else dir[j][i] = 0;
  }
/*  Direction factors  */
  for(k=1; k<= 8; k++)
    fact[k]=(float)(1./sqrt(d1[k]*dy*d1[k]*dy+d2[k]*d2[k]*dx*dx));
/*  printf("Problem Pixels \n");   */
/*  printf("     Flats   Unresolved\n");  */   
/*  Set positive slope directions - store unresolved on stack */
/*ttt  n=1;      Avoid iterating - work with stack only
  while(n >= 1)
  {       */
  nis=0;
  for(i=i2+1; i< n2-1; i++)for(j=i1+1; j<n1-1; j++)
  {
    if(elev[j][i] > mval)set(i,j,fact,mval);
/*  Put unresolved pixels on stack  */
    if(dir[j][i] == 0)
    {
		err=addstack(i,j);
    }
   }
   nflat=nis;
/* routine to drain flats to neighbors  */
   SetWorkingStatus();  
   imin=vdn(nflat);
   n=nis;
 
   printf("Number of pits to resolve: %d\n",n);  
   np1=n;
   nt=np1*(1-per/100);

/*  initialize apool to zero  */
   for(i=i2; i< n2; i++)for(j=i1; j<n1; j++)
    apool[j][i]=0;
/*  store unresolved stack location in apool for easy deletion  
  for(k=1; k<=nis; k++)
    apool[js[k]][is[k]]= - k;   */
/*  pooln=0;  */
  while(nis > 0)   /*  While AA */
  {
/*    fp=fopen("temp.dat","w");
	for(ip=1; ip <= nis; ip++)
	{
		i=is[ip];
		j=js[ip];
       fprintf(fp,"%d %d %f\n",i,j,elev[j][i]);
	}
    fclose(fp);   */

    i=is[imin];
    j=js[imin];
/*	if(i == 12 && j == 27)
	{
		printf("Here");
	}    */
/*    pooln=pooln+1;  */
	pooln=1;
    npool=0;
    nf = 0;  /*  reset flag to that new min elev is found */
    pool(i,j);  /*  Recursive call on unresolved point with lowest elevation */
/*  Find the pour point of the pool  */
/*	 err = gridwrite("pool.asc",(void **)apool,RPSHRDTYPE,nx,ny,dx,dy,
             bndbox,csize,-9999,0);   */ 
 
	for(ip=1; ip<=npool; ip++)
	{
		i=ipool[ip];
		j=jpool[ip];
		for(k=1; k <=8; k++)	
        {
			 jn=j+d2[k];
			 in=i+d1[k];
			 if(apool[jn][in] != pooln)  /*  neighbor not in pool  */
			 {
                et=max2(elev[j][i],elev[jn][in]);
                if(nf == 0)  /*  this is the first edge found  */
                {
                  emin=et;
                  nf=1;
/*				  ipour=i;
				  jpour=j;   */
                }
                else
                {
                  /*  emin=min2(emin,et);  */
					if(emin > et)
					{
						emin = et;
/*						ipour=i;
						jpour=j;    */
					}
                }
			 }
		}
	}
/*  Fill the pool  */
    for(k=1; k<=npool; k++)
	{
		i=ipool[k];
		j=jpool[k];
      if(elev[j][i] <= emin)
	  {
		  if(dir[j][i] > 0)   /*  Can be in pool, but not flat   */
		  {
			  dir[j][i]=0;
			  /*  Add to stack  */
			  err=addstack(i,j);
		  }
		  for(ip=1; ip <=8; ip++)
		  {
			  jn=j+d2[ip];
			  in=i+d1[ip];
			  if(elev[jn][in] > elev[j][i] && dir[jn][in] > 0)
/*    Only zero direction of neighbors that are higher - because
      lower  or equal may be a pour point in a pit that must not be disrupted  */
			  {
				  dir[jn][in] = 0;
				  err=addstack(in,jn);
			  }
		  }
		  elev[j][i] =emin;

	  }
	  apool[j][i]=0;  /*  Reinitialize for next time round  */
	}

/* reset unresolved stack  */
    ni=0;
    for(ip=1; ip <= nis; ip++)
    {
       set(is[ip],js[ip],fact,mval);  
	   if(dir[js[ip]][is[ip]] == 0)  /* still on stack */
       {
          ni++;
          is[ni]=is[ip];
          js[ni]=js[ip];
/*          apool[js[ni]][is[ni]] = -ni;  /*  Need to resave stack locations
                                         since the stack is being shortened */
       }
/*	   else
		   apool[js[ip]][is[ip]] = 0;   /*  Out of pool   */
     }
/*    fp=fopen("temp.dat","w");
	for(ip=1; ip <= nis; ip++)
	{
		i=is[ip];
		j=js[ip];
       fprintf(fp,"%d %d %f\n",i,j,elev[j][i]);
	}
    fclose(fp);      */

	 n=nis;
 	 imin=vdn(ni);
	 if(nis < nt){
		 printf("Percentage done %f\n",per);
		 per=per+1;
		 nt=np1*(1-per/100);
	 }
	 /*  Debug writes   
     err = gridwrite("elev.asc",(void **)elev,RPFLTDTYPE,nx,ny,dx,dy,
             bndbox,csize,mval,0); 
	 err = gridwrite("pool.asc",(void **)apool,RPSHRDTYPE,nx,ny,dx,dy,
             bndbox,csize,-9999,0);   */  
  }  /*  end of while AA  */

  return(err);
}
Example #25
0
File: lbfgs.c Project: Kitware/ITK
/**
 * Update a safeguarded trial value and interval for line search.
 *
 *  The parameter x represents the step with the least function value.
 *  The parameter t represents the current step. This function assumes
 *  that the derivative at the point of x in the direction of the step.
 *  If the bracket is set to true, the minimizer has been bracketed in
 *  an interval of uncertainty with endpoints between x and y.
 *
 *  @param  x       The pointer to the value of one endpoint.
 *  @param  fx      The pointer to the value of f(x).
 *  @param  dx      The pointer to the value of f'(x).
 *  @param  y       The pointer to the value of another endpoint.
 *  @param  fy      The pointer to the value of f(y).
 *  @param  dy      The pointer to the value of f'(y).
 *  @param  t       The pointer to the value of the trial value, t.
 *  @param  ft      The pointer to the value of f(t).
 *  @param  dt      The pointer to the value of f'(t).
 *  @param  tmin    The minimum value for the trial value, t.
 *  @param  tmax    The maximum value for the trial value, t.
 *  @param  brackt  The pointer to the predicate if the trial value is
 *                  bracketed.
 *  @retval int     Status value. Zero indicates a normal termination.
 *
 *  @see
 *      Jorge J. More and David J. Thuente. Line search algorithm with
 *      guaranteed sufficient decrease. ACM Transactions on Mathematical
 *      Software (TOMS), Vol 20, No 3, pp. 286-307, 1994.
 */
static int update_trial_interval(
    lbfgsfloatval_t *x,
    lbfgsfloatval_t *fx,
    lbfgsfloatval_t *dx,
    lbfgsfloatval_t *y,
    lbfgsfloatval_t *fy,
    lbfgsfloatval_t *dy,
    lbfgsfloatval_t *t,
    lbfgsfloatval_t *ft,
    lbfgsfloatval_t *dt,
    const lbfgsfloatval_t tmin,
    const lbfgsfloatval_t tmax,
    int *brackt
    )
{
    int bound;
    int dsign = fsigndiff(dt, dx);
    lbfgsfloatval_t mc; /* minimizer of an interpolated cubic. */
    lbfgsfloatval_t mq; /* minimizer of an interpolated quadratic. */
    lbfgsfloatval_t newt;   /* new trial value. */
    USES_MINIMIZER;     /* for CUBIC_MINIMIZER and QUARD_MINIMIZER. */

    /* Check the input parameters for errors. */
    if (*brackt) {
        if (*t <= min2(*x, *y) || max2(*x, *y) <= *t) {
            /* The trival value t is out of the interval. */
            return LBFGSERR_OUTOFINTERVAL;
        }
        if (0. <= *dx * (*t - *x)) {
            /* The function must decrease from x. */
            return LBFGSERR_INCREASEGRADIENT;
        }
        if (tmax < tmin) {
            /* Incorrect tmin and tmax specified. */
            return LBFGSERR_INCORRECT_TMINMAX;
        }
    }

    /*
        Trial value selection.
     */
    if (*fx < *ft) {
        /*
            Case 1: a higher function value.
            The minimum is brackt. If the cubic minimizer is closer
            to x than the quadratic one, the cubic one is taken, else
            the average of the minimizers is taken.
         */
        *brackt = 1;
        bound = 1;
        CUBIC_MINIMIZER(mc, *x, *fx, *dx, *t, *ft, *dt);
        QUARD_MINIMIZER(mq, *x, *fx, *dx, *t, *ft);
        if (fabs(mc - *x) < fabs(mq - *x)) {
            newt = mc;
        } else {
            newt = mc + 0.5 * (mq - mc);
        }
    } else if (dsign) {
        /*
            Case 2: a lower function value and derivatives of
            opposite sign. The minimum is brackt. If the cubic
            minimizer is closer to x than the quadratic (secant) one,
            the cubic one is taken, else the quadratic one is taken.
         */
        *brackt = 1;
        bound = 0;
        CUBIC_MINIMIZER(mc, *x, *fx, *dx, *t, *ft, *dt);
        QUARD_MINIMIZER2(mq, *x, *dx, *t, *dt);
        if (fabs(mc - *t) > fabs(mq - *t)) {
            newt = mc;
        } else {
            newt = mq;
        }
    } else if (fabs(*dt) < fabs(*dx)) {
        /*
            Case 3: a lower function value, derivatives of the
            same sign, and the magnitude of the derivative decreases.
            The cubic minimizer is only used if the cubic tends to
            infinity in the direction of the minimizer or if the minimum
            of the cubic is beyond t. Otherwise the cubic minimizer is
            defined to be either tmin or tmax. The quadratic (secant)
            minimizer is also computed and if the minimum is brackt
            then the the minimizer closest to x is taken, else the one
            farthest away is taken.
         */
        bound = 1;
        CUBIC_MINIMIZER2(mc, *x, *fx, *dx, *t, *ft, *dt, tmin, tmax);
        QUARD_MINIMIZER2(mq, *x, *dx, *t, *dt);
        if (*brackt) {
            if (fabs(*t - mc) < fabs(*t - mq)) {
                newt = mc;
            } else {
                newt = mq;
            }
        } else {
            if (fabs(*t - mc) > fabs(*t - mq)) {
                newt = mc;
            } else {
                newt = mq;
            }
        }
    } else {
        /*
            Case 4: a lower function value, derivatives of the
            same sign, and the magnitude of the derivative does
            not decrease. If the minimum is not brackt, the step
            is either tmin or tmax, else the cubic minimizer is taken.
         */
        bound = 0;
        if (*brackt) {
            CUBIC_MINIMIZER(newt, *t, *ft, *dt, *y, *fy, *dy);
        } else if (*x < *t) {
            newt = tmax;
        } else {
            newt = tmin;
        }
    }

    /*
        Update the interval of uncertainty. This update does not
        depend on the new step or the case analysis above.

        - Case a: if f(x) < f(t),
            x <- x, y <- t.
        - Case b: if f(t) <= f(x) && f'(t)*f'(x) > 0,
            x <- t, y <- y.
        - Case c: if f(t) <= f(x) && f'(t)*f'(x) < 0,
            x <- t, y <- x.
     */
    if (*fx < *ft) {
        /* Case a */
        *y = *t;
        *fy = *ft;
        *dy = *dt;
    } else {
        /* Case c */
        if (dsign) {
            *y = *x;
            *fy = *fx;
            *dy = *dx;
        }
        /* Cases b and c */
        *x = *t;
        *fx = *ft;
        *dx = *dt;
    }

    /* Clip the new trial value in [tmin, tmax]. */
    if (tmax < newt) newt = tmax;
    if (newt < tmin) newt = tmin;

    /*
        Redefine the new trial value if it is close to the upper bound
        of the interval.
     */
    if (*brackt && bound) {
        mq = *x + 0.66 * (*y - *x);
        if (*x < *y) {
            if (mq < newt) newt = mq;
        } else {
            if (newt < mq) newt = mq;
        }
    }

    /* Return the new trial value. */
    *t = newt;
    return 0;
}
Example #26
0
int
Rwm_init_frame(struct R_window *frame)
{
    struct R_app *app;
    struct R_wm *wm;
    struct R_window *client;
    struct R_window *window;
#if (USE_IMLIB2)
    struct R_image *image;
#endif
    int x;
    int y;
    int w;
    int h;
    int border;
    int i;
    XWindowAttributes attr;

    frame->typeflags |= R_WINDOW_FRAME_FLAG;
    client = frame->child;
    if (!client) {

        return;
    }
    app = client->app;
    wm = app->client;
    if (!wm) {

        return;
    }
    border = client->border;
    memset(&attr, 0, sizeof(attr));
    frame = client->parent;
    _ignbadwindow = 1;
    XGetWindowAttributes(client->app->display,
                         client->id,
                         &attr);
    XSync(client->app->display,
          False);
    _ignbadwindow = 0;
#if 0
    client->w = min2(client->w,
                     wm->desktop->w - frame->left - frame->right);
    client->h = min2(client->h,
                     wm->desktop->h - frame->top - frame->bottom - RWM_MENU_ITEM_WIDTH);
#endif
    /* frame */
    frame->typeflags = R_WINDOW_FRAME_FLAG;
#if 0
    frame->x = client->x;
    frame->y = max2(client->y, RWM_MENU_ITEM_HEIGHT);
#endif
    frame->x = attr.x;
#if (RWM_EXEC_RL)
    frame->y = max2(attr.y, RL_BUTTON_HEIGHT + RWM_MENU_ITEM_HEIGHT);
#else
    frame->y = max2(attr.y, RWM_MENU_ITEM_HEIGHT);
#endif
    frame->w = frame->left + client->w + frame->right;
    frame->h = frame->top + client->h + frame->bottom;
    Rwm_move_resize_window(frame,
                           frame->x,
                           frame->y,
                           frame->w,
                           frame->h);

    /* top */
    x = 0;
    y = 0;
    window = frame->chain;
//    window->typeflags = R_WINDOW_FRAME_FLAG;
    window->parent = frame;
    w = frame->w;
    h = frame->top;
#if (USE_IMLIB2)
    for (i = 0 ; i < R_WINDOW_STATES ; i++) {
        image = &Rwm_frame_images[RWM_TOP_FRAME][i];
        window->images[i] = image;
    }
    RWM_SET_WINDOW_IMAGE(window,
                         R_WINDOW_NORMAL_STATE);
#endif
    Rwm_move_resize_window(window,
                           x,
                           y,
                           w,
                           h);
#if (USE_IMLIB2)
#if (!RWM_STATIC_FRAME_PIXMAPS)
    R_render_image_imlib2(window->image,
                          window,
                          window->image->w,
                          window->image->h,
                          0);
#endif
    window->str = client->str;
    window->font = _titlefont;
    R_set_background_imlib2(window->image,
                            window,
                            window->image->w,
                            window->image->h,
                            0);
#endif
    window->child = client;
    R_add_window(window);

    /* bottom */
    window = window->chain;
//    window->typeflags = R_WINDOW_FRAME_FLAG;
    window->parent = frame;
    w = frame->w;
    h = frame->bottom;
    y = frame->top + client->h;
    XDefineCursor(window->app->display,
                  window->id,
                  Rwm_frame_cursors[RWM_BOTTOM_FRAME]);
#if (USE_IMLIB2)
    for (i = 0 ; i < R_WINDOW_STATES ; i++) {
        image = &Rwm_frame_images[RWM_BOTTOM_FRAME][i];
        window->images[i] = image;
    }
    RWM_SET_WINDOW_IMAGE(window,
                         R_WINDOW_NORMAL_STATE);
#endif
    Rwm_move_resize_window(window,
                           x,
                           y,
                           w,
                           h);
#if (USE_IMLIB2)
#if (!RWM_STATIC_FRAME_PIXMAPS)
    R_render_image_imlib2(window->image,
                          window,
                          window->image->w,
                          window->image->h,
                          0);
#endif
    R_set_background_imlib2(window->image,
                            window,
                            window->image->w,
                            window->image->h,
                            0);
#endif
    window->child = client;
    R_add_window(window);

    /* left */
    window = window->chain;
//    window->typeflags = R_WINDOW_FRAME_FLAG;
    window->parent = frame;
    x = 0;
#if (RWM_ORIGINAL_THEME)
    y = frame->top;
#else
    y = 0;
#endif
    w = frame->left;
#if (RWM_ORIGINAL_THEME)
    h = client->h;
#else
    h = client->h + frame->top;
#endif
#if (USE_IMLIB2)
    for (i = 0 ; i < R_WINDOW_STATES ; i++) {
        image = &Rwm_frame_images[RWM_LEFT_FRAME][i];
        window->images[i] = image;
    }
    RWM_SET_WINDOW_IMAGE(window,
                         R_WINDOW_NORMAL_STATE);
#endif
    Rwm_move_resize_window(window,
                           x,
                           y,
                           w,
                           h);
#if (USE_IMLIB2)
#if (!RWM_STATIC_FRAME_PIXMAPS)
    R_render_image_imlib2(window->image,
                          window,
                          window->image->w,
                          window->image->h,
                          0);
#endif
    R_set_background_imlib2(window->image,
                            window,
                            window->image->w,
                            window->image->h,
                            0);
#endif
    window->child = client;
    R_add_window(window);

    /* right */
    window = window->chain;
//    window->typeflags = R_WINDOW_FRAME_FLAG;
    window->parent = frame;
    x = client->w + frame->left;
    w = frame->right;
    XDefineCursor(window->app->display,
                  window->id,
                  Rwm_frame_cursors[RWM_RIGHT_FRAME]);
#if (USE_IMLIB2)
    for (i = 0 ; i < R_WINDOW_STATES ; i++) {
        image = &Rwm_frame_images[RWM_RIGHT_FRAME][i];
        window->images[i] = image;
    }
    RWM_SET_WINDOW_IMAGE(window,
                         R_WINDOW_NORMAL_STATE);
#endif
    Rwm_move_resize_window(window,
                           x,
                           y,
                           w,
                           h);
#if (USE_IMLIB2)
#endif
#if (!RMW_STATIC_FRAME_PIXMAPS)
    R_render_image_imlib2(window->image,
                          window,
                          window->image->w,
                          window->image->h,
                          0);
#endif
    R_set_background_imlib2(window->image,
                            window,
                            window->image->w,
                            window->image->h,
                            0);
    window->child = client;
    R_add_window(window);
    _ignbadwindow = 1;
    Rwm_reparent_window(client,
                        frame,
                        frame->left,
                        frame->top);
    Rwm_reparent_window(frame,
                        wm->desktop,
                        attr.x,
                        attr.y);
    R_map_subwindows(frame);
    XSync(client->app->display, False);
    _ignbadwindow = 0;

    return 0;
}
Example #27
0
int max3(int a, int b, int c) {
	int t = max2(a, b);
	return c > t ? c : t;
}
Example #28
0
/*
 * NAME:	optimize->asgnexp()
 * DESCRIPTION:	optimize an assignment expression
 */
static Uint opt_asgnexp(node **m, bool pop)
{
    node *n;
    Uint d1, d2;

    n = *m;
    d2 = opt_expr(&n->r.right, FALSE);

    if ((n->r.right->type == N_INT || n->r.right->type == N_FLOAT) &&
	n->l.left->mod == n->r.right->mod) {
	switch (n->type) {
	case N_ADD_EQ:
	    if (NFLT_ISZERO(n->r.right)) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    if (NFLT_ISONE(n->r.right)) {
		n->type = N_ADD_EQ_1;
		return opt_lvalue(n->l.left) + 1;
	    }
	    if (NFLT_ISMONE(n->r.right)) {
		n->type = N_SUB_EQ_1;
		return opt_lvalue(n->l.left) + 1;
	    }
	    break;

	case N_ADD_EQ_INT:
	    if (n->r.right->l.number == 0) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    if (n->r.right->l.number == 1) {
		n->type = N_ADD_EQ_1_INT;
		return opt_lvalue(n->l.left) + 1;
	    }
	    if (n->r.right->l.number == -1) {
		n->type = N_SUB_EQ_1_INT;
		return opt_lvalue(n->l.left) + 1;
	    }
	    break;

	case N_AND_EQ_INT:
	    if (n->r.right->l.number == 0) {
		n->type = N_ASSIGN;
		return opt_expr(m, pop);
	    }
	    if (n->r.right->l.number == -1) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    break;

	case N_MULT_EQ:
	    if (NFLT_ISZERO(n->r.right)) {
		n->type = N_ASSIGN;
		return opt_expr(m, pop);
	    }
	    /* fall through */
	case N_DIV_EQ:
	    if (NFLT_ISONE(n->r.right)) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    break;

	case N_MULT_EQ_INT:
	    if (n->r.right->l.number == 0) {
		n->type = N_ASSIGN;
		return opt_expr(m, pop);
	    }
	    /* fall through */
	case N_DIV_EQ_INT:
	    if (n->r.right->l.number == 1) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    break;

	case N_LSHIFT_EQ_INT:
	case N_RSHIFT_EQ_INT:
	    if (n->r.right->l.number == 0) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    break;

	case N_MOD_EQ_INT:
	    if (n->r.right->l.number == 1) {
		n->type = N_ASSIGN;
		n->r.right->l.number = 0;
		return opt_expr(m, pop);
	    }
	    break;

	case N_OR_EQ_INT:
	    if (n->r.right->l.number == 0) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    if (n->r.right->l.number == -1) {
		n->type = N_ASSIGN;
		return opt_expr(m, pop);
	    }
	    break;

	case N_SUB_EQ:
	    if (NFLT_ISZERO(n->r.right)) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    if (NFLT_ISONE(n->r.right)) {
		n->type = N_SUB_EQ_1;
		return opt_lvalue(n->l.left) + 1;
	    }
	    if (NFLT_ISMONE(n->r.right)) {
		n->type = N_ADD_EQ_1;
		return opt_lvalue(n->l.left) + 1;
	    }
	    break;

	case N_SUB_EQ_INT:
	    if (n->r.right->l.number == 0) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    if (n->r.right->l.number == 1) {
		n->type = N_SUB_EQ_1_INT;
		return opt_lvalue(n->l.left) + 1;
	    }
	    if (n->r.right->l.number == -1) {
		n->type = N_ADD_EQ_1_INT;
		return opt_lvalue(n->l.left) + 1;
	    }
	    break;

	case N_XOR_EQ_INT:
	    if (n->r.right->l.number == 0) {
		*m = n->l.left;
		return opt_expr(m, pop);
	    }
	    break;
	}
    }

    d1 = opt_lvalue(n->l.left) + 1;

    if (n->type == N_SUM_EQ) {
	d1++;
	return max2(d1, ((d1 < 5) ? d1 : 5) + d2);
    }
    if (n->type == N_ADD_EQ &&
	(n->mod == T_STRING || (n->mod & T_REF) != 0) &&
	(n->r.right->mod == T_STRING || (n->r.right->mod & T_REF) != 0 ||
	 n->r.right->type == N_RANGE)) {
	/*
	 * see if the summand operator can be used
	 */
	switch (n->r.right->type) {
	case N_ADD:
	    n->r.right->type = N_SUM;
	    d2 += 2;				/* (-2) on both sides */
	    if (n->r.right->l.left->type == N_RANGE) {
		d1++;
	    }
	    n->type = N_SUM_EQ;
	    d1++;				/* add (-2) */
	    return max2(d1, ((d1 < 5) ? d1 : 5) + d2);

	case N_AGGR:
	    d2++;				/* add (-2) */
	    n->type = N_SUM_EQ;
	    d1++;				/* add (-2) */
	    return max2(d1, ((d1 < 5) ? d1 : 5) + d2);

	case N_RANGE:
	    d2 = max2(d2, 3);			/* at least 3 */
	    /* fall through */
	case N_SUM:
	    n->type = N_SUM_EQ;
	    d1++;				/* add (-2) */
	    return max2(d1, ((d1 < 5) ? d1 : 5) + d2);
	}
    }

    return max2(d1, ((d1 < 4) ? d1 : 4) + d2);
}
Example #29
0
int max3(int x1, int x2, int x3) {
	return max2(x1,max2(x2,x3));
}
Example #30
0
Datum
needlemanwunsch(PG_FUNCTION_ARGS)
{
	char		*a, *b;
	double		minvalue, maxvalue;
	float8		res;

	a = DatumGetPointer(DirectFunctionCall1(textout,
											PointerGetDatum(PG_GETARG_TEXT_P(0))));
	b = DatumGetPointer(DirectFunctionCall1(textout,
											PointerGetDatum(PG_GETARG_TEXT_P(1))));

	if (strlen(a) > PGS_MAX_STR_LEN || strlen(b) > PGS_MAX_STR_LEN)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("argument exceeds the maximum length of %d bytes",
						PGS_MAX_STR_LEN)));

	maxvalue = (float8) max2(strlen(a), strlen(b));

	res = (float8) _nwunsch(a, b, pgs_nw_gap_penalty);

	elog(DEBUG1, "is normalized: %d", pgs_nw_is_normalized);
	elog(DEBUG1, "maximum length: %.3f", maxvalue);
	elog(DEBUG1, "nwdistance(%s, %s) = %.3f", a, b, res);

	if (maxvalue == 0.0)
		PG_RETURN_FLOAT8(1.0);
	else if (pgs_nw_is_normalized)
	{
		/* FIXME normalize nw result */
		minvalue = maxvalue;
		if (PGS_LEV_MAX_COST > pgs_nw_gap_penalty)
			maxvalue *= PGS_LEV_MAX_COST;
		else
			maxvalue *= pgs_nw_gap_penalty;

		if (PGS_LEV_MIN_COST < pgs_nw_gap_penalty)
			minvalue *= PGS_LEV_MIN_COST;
		else
			minvalue *= pgs_nw_gap_penalty;

		if (minvalue < 0.0)
		{
			maxvalue -= minvalue;
			res -= minvalue;
		}

		/* paranoia ? */
		if (maxvalue == 0.0)
			PG_RETURN_FLOAT8(0.0);
		else
		{
			res = 1.0 - (res / maxvalue);
			elog(DEBUG1, "nw(%s, %s) = %.3f", a, b, res);
			PG_RETURN_FLOAT8(res);
		}
	}
	else
		PG_RETURN_FLOAT8(res);
}