コード例 #1
0
#endif

#define SWITCH_NAME "h2w"
#define SWITCH_NAME_ADVANCED "h2w_advanced"
#define SWITCH_NAME_AUX "h2w_aux"

enum {
    NO_DEVICE   = 0,
    LGE_HEADSET = (1 << 0),
    LGE_HEADSET_NO_MIC = (1 << 1),
};

/* (name, mic impedence, left impedence, has button, mode0, mode1,
switch name, switch state, event type,  event code) */
static struct max14688_jack_match max14688_jack_matches[] = {
	JACK_MATCH("3P", Z(0, 50000), Z(0, 4),   false,  LOW,   LOW,   SWITCH_NAME,          LGE_HEADSET_NO_MIC, EV_SW, SW_HEADPHONE_INSERT, NONE),
	JACK_MATCH("4P", Z(120000, 2600000),  Z(0,   4),   true,   HIGH,  LOW,   SWITCH_NAME,          LGE_HEADSET,        EV_SW, SW_HEADPHONE_INSERT, SW_MICROPHONE_INSERT),
#if MAX14688_ADVANCED_JACK_DET
	JACK_MATCH("3P/ADV", Z(0,        50000),  Z(4,  11),   false,  LOW,   LOW,   SWITCH_NAME_ADVANCED, LGE_HEADSET_NO_MIC, EV_SW, SW_ADVANCED_HEADPHONE_INSERT, NONE),
	JACK_MATCH("4P/ADV", Z(120000, 2600000),  Z(4,  11),   true,   HIGH,  LOW,   SWITCH_NAME_ADVANCED, LGE_HEADSET,        EV_SW, SW_ADVANCED_HEADPHONE_INSERT, SW_MICROPHONE_INSERT),
	JACK_MATCH("ACC/AUX", Z(0,        50000),  Z(11, 64),   false,  LOW,   LOW,   SWITCH_NAME_AUX,      LGE_HEADSET_NO_MIC, EV_SW, SW_AUX_ACCESSORY_INSERT, NONE),
	JACK_MATCH("ACC/AUX", Z(120000, 2600000),  Z(11, 64),   true,   HIGH,  LOW,   SWITCH_NAME_AUX,      LGE_HEADSET,        EV_SW, SW_AUX_ACCESSORY_INSERT, SW_MICROPHONE_INSERT),
#else
#endif
};

static struct max14688_button_match max14688_button_matches[] = {
  /*           name      mic                left         event   event
                       impedence          impedence      type    code */
    BUTTON_MATCH("MEDIA",  Z(0,      150000), DONTCARE,    EV_KEY, KEY_MEDIA),
    BUTTON_MATCH("VOLUP",  Z(150000, 400000), DONTCARE,    EV_KEY, KEY_VOLUMEUP),
コード例 #2
0
ファイル: ccGriddedTools.cpp プロジェクト: cnyinfei/trunk
bool ccGriddedTools::ComputeNormals(ccPointCloud* cloud,
									const std::vector<int>& indexGrid,
									int width,
									int height,
									bool* canceledByUser/*=0*/,
									int kernelWidth/*=3*/ )
{
	//init
	bool result = true;
	if (canceledByUser)
		*canceledByUser = false;

	//try to compute normals
	if (cloud->reserveTheNormsTable())
	{
		//progress dialog
		ccProgressDialog pdlg(true);
		CCLib::NormalizedProgress nprogress(&pdlg,cloud->size());
		pdlg.setMethodTitle("Compute normals");
		pdlg.setInfo(qPrintable(QString("Number of points: %1").arg(cloud->size())));
		pdlg.start();

		const int* _indexGrid = &(indexGrid[0]);
		CCLib::ReferenceCloud knn(cloud);
		
		//neighborhood 'half-width' (total width = 1 + 2*kernelWidth) 
		//max number of neighbours: (1+2*nw)^2
		knn.reserve((1+2*kernelWidth)*(1+2*kernelWidth));

		//for each grid cell
		for (int j=0; j<height; ++j)
		{
			for (int i=0; i<width; ++i, ++_indexGrid)
			{
				if (*_indexGrid >= 0)
				{
					unsigned pointIndex = static_cast<unsigned>(*_indexGrid);
					//add the point itself
					knn.clear(false);
					knn.addPointIndex(pointIndex); //warning: indexes are shifted (0 = no point)
					const CCVector3* P = cloud->getPoint(pointIndex);

					//look for neighbors
					for (int v=std::max(0,j-kernelWidth); v<std::min<int>(height,j+kernelWidth); ++v)
					{
						if (v != j)
						{
							for (int u=std::max(0,i-kernelWidth); u<std::min<int>(width,i+kernelWidth); ++u)
							{
								if (u != i)
								{
									int indexN = indexGrid[v*width + u];
									if (indexN >= 0)
									{
										//we don't consider points with a too much different depth than the central point
										const CCVector3* Pn = cloud->getPoint(static_cast<unsigned>(indexN));
										if (fabs(Pn->z - P->z) <= std::max(fabs(Pn->x - P->x),fabs(Pn->y - P->y)))
											knn.addPointIndex(static_cast<unsigned>(indexN)); //warning: indexes are shifted (0 = no point)
									}
								}
							}
						}
					}

					CCVector3 N(0,0,1);
					if (knn.size() >= 3)
					{
						CCLib::Neighbourhood Z(&knn);

						//compute normal with quadratic func. (if we have enough points)
						if (false/*knn.size() >= 6*/)
						{
							uchar hfDims[3];
							const PointCoordinateType* h = Z.getHeightFunction(hfDims);
							if (h)
							{
								const CCVector3* gv = Z.getGravityCenter();
								assert(gv);

								const uchar& iX = hfDims[0];
								const uchar& iY = hfDims[1];
								const uchar& iZ = hfDims[2];

								PointCoordinateType lX = P->u[iX] - gv->u[iX];
								PointCoordinateType lY = P->u[iY] - gv->u[iY];

								N.u[iX] = h[1] + (2 * h[3] * lX) + (h[4] * lY);
								N.u[iY] = h[2] + (2 * h[5] * lY) + (h[4] * lX);
								N.u[iZ] = -PC_ONE;

								N.normalize();
							}
						}
						else
#define USE_LSQ_PLANE
#ifdef USE_LSQ_PLANE
						{
							//compute normal with best fit plane
							const CCVector3* _N = Z.getLSQPlaneNormal();
							if (_N)
								N = *_N;
						}
#else
						{
							//compute normals with 2D1/2 triangulation
							CCLib::GenericIndexedMesh* theMesh = Z.triangulateOnPlane();
							if (theMesh)
							{
								unsigned faceCount = theMesh->size();
								N.z = 0;

								//for all triangles
								theMesh->placeIteratorAtBegining();
								for (unsigned j=0; j<faceCount; ++j)
								{
									const CCLib::TriangleSummitsIndexes* tsi = theMesh->getNextTriangleIndexes();
									//we look if the central point is one of the triangle's vertices
									if (tsi->i1 == 0 || tsi->i2 == 0|| tsi->i3 == 0)
									{
										const CCVector3 *A = knn.getPoint(tsi->i1);
										const CCVector3 *B = knn.getPoint(tsi->i2);
										const CCVector3 *C = knn.getPoint(tsi->i3);

										CCVector3 no = (*B - *A).cross(*C - *A);
										//no.normalize();
										N += no;
									}
								}

								delete theMesh;
								theMesh = 0;

								//normalize the 'mean' vector
								N.normalize();
							}
						}
#endif
					}

					//check normal vector sign
					CCVector3 viewVector = *P /*- cloudTrans.getTranslationAsVec3D()*/; //clouds are still in their local coordinate system!
					if (viewVector.dot(N) > 0)
						N *= -PC_ONE;
					cloud->addNorm(N);

					//progress
					if (!nprogress.oneStep())
					{
						result = false;
						if (canceledByUser)
							*canceledByUser = true;
						ccLog::Warning("[ComputeNormals] Process canceled by user!");
						//early stop
						j = height;
						break;
					}
				}
			}
		}

		if (!result)
		{
			cloud->unallocateNorms();
		}
	}
	else
	{
		ccLog::Warning("[ComputeNormals] Not enough memory!");
	}

	return result;
}
コード例 #3
0
ファイル: constexpr-recursion2.C プロジェクト: 0day-ci/gcc
// PR c++/70344
// { dg-do compile { target c++11 } }

struct Z
{
  Z () = default;
  Z (Z const &) = default;
  constexpr Z (Z &&) {}
};

constexpr int
fn (Z v)
{
  return fn (v);
}

auto t = fn (Z ());
コード例 #4
0
    virtual void SetUp() {
        // use a special object for source code generation
        typedef double Base;
        typedef CG<Base> CGD;
        typedef AD<CGD> ADCG;

#ifdef _MODEL1
        for (size_t j = 0; j < n; j++)
            x[j] = j + 2;
#else
        x[0] = 0.5;
#endif
        // independent variables
        std::vector<ADCG> u(n);
        for (size_t j = 0; j < n; j++)
            u[j] = x[j];

        CppAD::Independent(u);

        // dependent variable vector 
        std::vector<ADCG> Z(m);

        /**
         * create the CppAD tape as usual
         */
#ifdef _MODEL1
        Z[0] = cos(u[0]);
        Z[1] = u[1] * u[2] + sin(u[0]);
        Z[2] = u[2] * u[2] + sin(u[1]);
        Z[3] = u[0] / u[2] + u[1] * u[2] + 5.0;
#else
        Z[0] = 1.0 / u[0];
#endif
        // create f: U -> Z and vectors used for derivative calculations
        _fun = new ADFun<CGD>(u, Z);

        /**
         * Create the dynamic library
         * (generate and compile source code)
         */
        ModelCSourceGen<double> compHelp(*_fun, _modelName);

        compHelp.setCreateForwardZero(true);
        compHelp.setCreateForwardOne(true);
        compHelp.setCreateReverseOne(true);
        compHelp.setCreateReverseTwo(true);
        compHelp.setCreateSparseJacobian(true);
        compHelp.setCreateSparseHessian(true);

        GccCompiler<double> compiler;
        prepareTestCompilerFlags(compiler);

        ModelLibraryCSourceGen<double> compDynHelp(compHelp);

        DynamicModelLibraryProcessor<double> p(compDynHelp);

        _dynamicLib = p.createDynamicLibrary(compiler);
        _model = _dynamicLib->model(_modelName);

        // dimensions
        ASSERT_EQ(_model->Domain(), _fun->Domain());
        ASSERT_EQ(_model->Range(), _fun->Range());
    }
コード例 #5
0
ファイル: vmstat.c プロジェクト: outbackdingo/uBSD
void
showkre(void)
{
	float f1, f2;
	int psiz, inttotal;
	int i, l, lc;
	static int failcnt = 0;

	etime = 0;
	for(i = 0; i < CPUSTATES; i++) {
		X(time);
		Q(cp_time);
		etime += s.time[i];
	}
	if (etime < 5.0) {	/* < 5 ticks - ignore this trash */
		if (failcnt++ >= MAXFAIL) {
			clear();
			mvprintw(2, 10, "The alternate system clock has died!");
			mvprintw(3, 10, "Reverting to ``pigs'' display.");
			move(CMDLINE, 0);
			refresh();
			failcnt = 0;
			sleep(5);
			command("pigs");
		}
		return;
	}
	failcnt = 0;
	etime /= hertz;
	etime /= ncpu;
	inttotal = 0;
	for (i = 0; i < nintr; i++) {
		if (s.intrcnt[i] == 0)
			continue;
		X(intrcnt);
		l = (int)((float)s.intrcnt[i]/etime + 0.5);
		inttotal += l;
		if (intrloc[i] == 0) {
			if (nextintsrow == LINES)
				continue;
			intrloc[i] = nextintsrow++;
			mvprintw(intrloc[i], INTSCOL + 6, "%-10.10s",
				intrname[i]);
		}
		putint(l, intrloc[i], INTSCOL, 5);
	}
	putint(inttotal, INTSROW + 1, INTSCOL, 5);
	Z(ncs_goodhits); Z(ncs_badhits); Z(ncs_miss);
	Z(ncs_long); Z(ncs_pass2); Z(ncs_2passes); Z(ncs_neghits);
	s.nchcount = nchtotal.ncs_goodhits + nchtotal.ncs_badhits +
	    nchtotal.ncs_miss + nchtotal.ncs_long + nchtotal.ncs_neghits;
	if (state == TIME)
		s1.nchcount = s.nchcount;

	psiz = 0;
	f2 = 0.0;
	for (lc = 0; lc < CPUSTATES; lc++) {
		i = cpuorder[lc];
		f1 = cputime(i);
		f2 += f1;
		l = (int) ((f2 + 1.0) / 2.0) - psiz;
		putfloat(f1, GRAPHROW, GRAPHCOL + 10 * lc, 4, 1, 0);
		move(GRAPHROW + 2, psiz);
		psiz += l;
		while (l-- > 0)
			addch(cpuchar[lc]);
	}

	putint(ucount(), STATROW, STATCOL, 5);
	putfloat(avenrun[0], STATROW, STATCOL + 20, 5, 2, 0);
	putfloat(avenrun[1], STATROW, STATCOL + 26, 5, 2, 0);
	putfloat(avenrun[2], STATROW, STATCOL + 32, 5, 2, 0);
	mvaddstr(STATROW, STATCOL + 55, buf);
#define pgtokb(pg)	((pg) * (s.v_page_size / 1024))
	putfloat(100.0 * (v_page_count - total.t_free) / v_page_count,
	   STATROW + 1, STATCOL + 15, 2, 0, 1);
	putfloat(100.0 * s.v_kmem_map_size / kmem_size,
	   STATROW + 1, STATCOL + 22, 2, 0, 1);

	putint(pgtokb(total.t_arm), MEMROW + 2, MEMCOL + 4, 7);
	putint(pgtokb(total.t_armshr), MEMROW + 2, MEMCOL + 12, 7);
	putint(pgtokb(total.t_avm), MEMROW + 2, MEMCOL + 20, 8);
	putint(pgtokb(total.t_avmshr), MEMROW + 2, MEMCOL + 29, 8);
	putint(pgtokb(total.t_rm), MEMROW + 3, MEMCOL + 4, 7);
	putint(pgtokb(total.t_rmshr), MEMROW + 3, MEMCOL + 12, 7);
	putint(pgtokb(total.t_vm), MEMROW + 3, MEMCOL + 20, 8);
	putint(pgtokb(total.t_vmshr), MEMROW + 3, MEMCOL + 29, 8);
	putint(pgtokb(total.t_free), MEMROW + 2, MEMCOL + 38, 7);
	putint(total.t_rq - 1, PROCSROW + 2, PROCSCOL, 3);
	putint(total.t_pw, PROCSROW + 2, PROCSCOL + 4, 3);
	putint(total.t_dw, PROCSROW + 2, PROCSCOL + 8, 3);
	putint(total.t_sl, PROCSROW + 2, PROCSCOL + 12, 3);
	putint(total.t_sw, PROCSROW + 2, PROCSCOL + 16, 3);
	PUTRATE(v_io_faults, VMSTATROW, VMSTATCOL + 2, 8 - 2);
	PUTRATE(v_cow_faults, VMSTATROW + 1, VMSTATCOL + 2, 8 - 2);
	PUTRATE(v_zfod, VMSTATROW + 2, VMSTATCOL + 2, 8 - 2);
	PUTRATE(v_ozfod, VMSTATROW + 3, VMSTATCOL, 8);
	putint(s.v_zfod != 0 ? (int)(s.v_ozfod * 100.0 / s.v_zfod) : 0,
	    VMSTATROW + 4, VMSTATCOL + 1, 8 - 1);
	PUTRATE(v_dfree, VMSTATROW + 5, VMSTATCOL + 2, 8 - 2);
	PUTRATE(v_pfree, VMSTATROW + 6, VMSTATCOL + 2, 8 - 2);
	PUTRATE(v_tfree, VMSTATROW + 7, VMSTATCOL, 8);
	PUTRATE(v_reactivated, VMSTATROW + 8, VMSTATCOL, 8);
	PUTRATE(v_pdwakeups, VMSTATROW + 9, VMSTATCOL, 8);
	PUTRATE(v_pdpages, VMSTATROW + 10, VMSTATCOL, 8);
	PUTRATE(v_intrans, VMSTATROW + 11, VMSTATCOL, 8);
	putint(pgtokb(s.v_wire_count), VMSTATROW + 12, VMSTATCOL, 8);
	putint(pgtokb(s.v_active_count), VMSTATROW + 13, VMSTATCOL, 8);
	putint(pgtokb(s.v_inactive_count), VMSTATROW + 14, VMSTATCOL, 8);
	putint(pgtokb(s.v_free_count), VMSTATROW + 16, VMSTATCOL, 8);
	if (LINES - 1 > VMSTATROW + 17)
		putint(s.bufspace / 1024, VMSTATROW + 17, VMSTATCOL, 8);
	PUTRATE(v_vnodein, PAGEROW + 2, PAGECOL + 6, 5);
	PUTRATE(v_vnodeout, PAGEROW + 2, PAGECOL + 12, 5);
	PUTRATE(v_swapin, PAGEROW + 2, PAGECOL + 19, 5);
	PUTRATE(v_swapout, PAGEROW + 2, PAGECOL + 25, 5);
	PUTRATE(v_vnodepgsin, PAGEROW + 3, PAGECOL + 6, 5);
	PUTRATE(v_vnodepgsout, PAGEROW + 3, PAGECOL + 12, 5);
	PUTRATE(v_swappgsin, PAGEROW + 3, PAGECOL + 19, 5);
	PUTRATE(v_swappgsout, PAGEROW + 3, PAGECOL + 25, 5);
	PUTRATE(v_swtch, GENSTATROW + 1, GENSTATCOL, 4);
	PUTRATE(v_trap, GENSTATROW + 1, GENSTATCOL + 5, 4);
	PUTRATE(v_syscall, GENSTATROW + 1, GENSTATCOL + 10, 4);
	PUTRATE(v_intr, GENSTATROW + 1, GENSTATCOL + 15, 4);
	PUTRATE(v_soft, GENSTATROW + 1, GENSTATCOL + 20, 4);
	PUTRATE(v_vm_faults, GENSTATROW + 1, GENSTATCOL + 25, 4);
	for (i = 0, lc = 0; i < num_devices && lc < MAXDRIVES; i++)
		if (dev_select[i].selected) {
			switch(state) {
			case TIME:
				dinfo(i, ++lc, &cur, &last);
				break;
			case RUN:
				dinfo(i, ++lc, &cur, &run);
				break;
			case BOOT:
				dinfo(i, ++lc, &cur, NULL);
				break;
			}
		}
	putint(s.numdirtybuffers, VNSTATROW, VNSTATCOL, 7);
	putint(s.desiredvnodes, VNSTATROW + 1, VNSTATCOL, 7);
	putint(s.numvnodes, VNSTATROW + 2, VNSTATCOL, 7);
	putint(s.freevnodes, VNSTATROW + 3, VNSTATCOL, 7);
	putint(s.nchcount, NAMEIROW + 2, NAMEICOL, 8);
	putint((nchtotal.ncs_goodhits + nchtotal.ncs_neghits),
	   NAMEIROW + 2, NAMEICOL + 9, 7);
#define nz(x)	((x) ? (x) : 1)
	putfloat((nchtotal.ncs_goodhits+nchtotal.ncs_neghits) *
	   100.0 / nz(s.nchcount),
	   NAMEIROW + 2, NAMEICOL + 17, 3, 0, 1);
	putint(nchtotal.ncs_pass2, NAMEIROW + 2, NAMEICOL + 21, 7);
	putfloat(nchtotal.ncs_pass2 * 100.0 / nz(s.nchcount),
	   NAMEIROW + 2, NAMEICOL + 29, 3, 0, 1);
#undef nz
}
コード例 #6
0
ファイル: languages.cpp プロジェクト: Azpidatziak/mkvtoolnix
wxString
optdlg_languages_tab::get_title() {
  return Z("Languages");
}
コード例 #7
0
ファイル: testmatr.cpp プロジェクト: heavilessrose/my-sync
void TestMatrix(ostream& os)
{
    // display a headline
    os << "Matrix test\r\n===========\r\n";

    Matrix<int> A(3,3), B(3,3), C(3,3), D(3,3);

    A(0,0) =   1;
    A(0,1) =   3;
    A(0,2) =  -4;
    A(1,0) =   1;
    A(1,1) =   1;
    A(1,2) =  -2;
    A(2,0) =  -1;
    A(2,1) =  -2;
    A(2,2) =   5;

    B(0,0) =   8;
    B(0,1) =   3;
    B(0,2) =   0;
    B(1,0) =   3;
    B(1,1) =  10;
    B(1,2) =   2;
    B(2,0) =   0;
    B(2,1) =   2;
    B(2,2) =   6;

    D(0,0) =   1;
    D(0,1) =   2;
    D(0,2) =  -1;
    D(1,0) =   2;
    D(1,1) =  -1;
    D(1,2) =  -3;
    D(2,0) =   0;
    D(2,1) =  -2;
    D(2,2) =   4;

    os << "\r\nMatrix A = \r\n";
    ShowMatrix(os,A);

    os << "\r\nMatrix B = \r\n";
    ShowMatrix(os,B);

    C = A % B;
    os << "\r\nMatrix C (A % B) = \r\n";
    ShowMatrix(os,C);

    C = A + B;
    os << "\r\nMatrix C (A + B) = \r\n";
    ShowMatrix(os,C);

    C = A;
    C += B;
    os << "\r\nMatrix C (= A, += B) =\r\n";
    ShowMatrix(os,C);

    C = A + 1;
    os << "\r\nMatrix C (= A + 1) =\r\n";
    ShowMatrix(os,C);

    C += 1;
    os << "\r\nMatrix C (+= 1) =\r\n";
    ShowMatrix(os,C);

    C = A - B;
    os << "\r\nMatrix C (A - B) = \r\n";
    ShowMatrix(os,C);

    C = A;
    C -= B;
    os << "\r\nMatrix C (= A, -= B) =\r\n";
    ShowMatrix(os,C);

    C = A - 1;
    os << "\r\nMatrix C (= A - 1) =\r\n";
    ShowMatrix(os,C);

    C -= 1;
    os << "\r\nMatrix C (-= 1) =\r\n";
    ShowMatrix(os,C);

    C = A * B;
    os << "\r\nMatrix C (A * B) = \r\n";
    ShowMatrix(os,C);

    C = A;
    C *= B;
    os << "\r\nMatrix C (= A, *= B) =\r\n";
    ShowMatrix(os,C);

    C = A * 2;
    os << "\r\nMatrix C (= A * 2) =\r\n";
    ShowMatrix(os,C);

    C *= 2;
    os << "\r\nMatrix C (*= 2) =\r\n";
    ShowMatrix(os,C);

    C = B / A;
    os << "\r\nMatrix C (B / A) = \r\n";
    ShowMatrix(os,C);

    C = B;
    C /= A;
    os << "\r\nMatrix C (= B, /= A) =\r\n";
    ShowMatrix(os,C);

    C = A / 2;
    os << "\r\nMatrix C (= A / 2) =\r\n";
    ShowMatrix(os,C);

    C /= 2;
    os << "\r\nMatrix C (/= 2) =\r\n";
    ShowMatrix(os,C);

    C = -A;
    os << "\r\nMatrix C (-A) = \r\n";
    ShowMatrix(os,C);

    // test comparisons
    os << "\r\nMatrix A = \r\n";
    ShowMatrix(os,A);

    os << "\r\nMatrix D = \r\n";
    ShowMatrix(os,D);

    if (A.Equals(D))
        os << "\r\nERROR: A should not equal D";
    else
        os << "\r\nOKAY: A not equal D";

    C = A;
    if (A.Equals(C))
        os << "\r\nOKAY: A equals C\r\n";
    else
        os << "\r\nERROR: A should equal C\r\n";

    Matrix<bool> I(3,3);

    I = (A == D);
    os << "\r\nMatrix I = (A == D)\r\n";
    ShowMatrix(os,I);

    I = (A != D);
    os << "\r\nMatrix I = (A != D)\r\n";
    ShowMatrix(os,I);

    I = (A < D);
    os << "\r\nMatrix I = (A < D)\r\n";
    ShowMatrix(os,I);

    I = (A <= D);
    os << "\r\nMatrix I = (A <= D)\r\n";
    ShowMatrix(os,I);

    I = (A > D);
    os << "\r\nMatrix I = (A > D)\r\n";
    ShowMatrix(os,I);

    I = (A >= D);
    os << "\r\nMatrix I = (A >= D)\r\n";
    ShowMatrix(os,I);

    // check fill function
    C.Fill(9);
    os << "\r\nC filled with 9 =\r\n";
    ShowMatrix(os,C);

    // check Apply functions
    C = Apply(A, Times2);
    os << "\r\nC = A.Apply(Times2)\r\n";
    ShowMatrix(os,C);

    C.Apply(Times2);
    os << "\r\nApply(C,Times2)\r\n";
    ShowMatrix(os,C);

    // check row and column vector functions
    Matrix<int>   S(1,1);
    Matrix<int> r1A(3,1);
    Matrix<int> c0B(1,3);

    r1A = A.VectorRow(1);
    c0B = B.VectorCol(0);

    os << "\r\nMatrix S = \r\n";
    ShowMatrix(os,S);

    os << "\r\nMatrix R1A = \r\n";
    ShowMatrix(os,r1A);

    os << "\r\nMatrix C0B = \r\n";
    ShowMatrix(os,c0B);

    if (r1A.IsRowVector())
        os << "\r\nOKAY: R1A is row vector";
    else
        os << "\r\nERROR: R1A should be a row vector";

    if (!r1A.IsColVector())
        os << "\r\nOKAY: R1A is not a column vector";
    else
        os << "\r\nERROR: R1A should not be a column vector";

    if (!c0B.IsRowVector())
        os << "\r\nOKAY: C0B is not a row vector";
    else
        os << "\r\nERROR: C0B should not be a row vector";

    if (c0B.IsColVector())
        os << "\r\nOKAY: C0B is column vector";
    else
        os << "\r\nERROR: C0B should be a column vector";

    if (c0B.IsVector())
        os << "\r\nOKAY: C0B is a vector";
    else
        os << "\r\nERROR: C0B should be a vector";

    if (!A.IsVector())
        os << "\r\nOKAY: A is not a vector";
    else
        os << "\r\nERROR: A should not be a vector";

    if (!c0B.IsSquare())
        os << "\r\nOKAY: C0B is not square";
    else
        os << "\r\nERROR: C0B should not be square";

    if (A.IsSquare())
        os << "\r\nOKAY: A is square";
    else
        os << "\r\nERROR: A should be square";

    B.Fill(0);

    if (B.IsZero())
        os << "\r\nOKAY: B is zero";
    else
        os << "\r\nERROR: B should be zero";

    if (!A.IsZero())
        os << "\r\nOKAY: A is not zero";
    else
        os << "\r\nERROR: A should not be zero";

    // test inner product
    int ip = r1A.InnerProduct(c0B);
    os << "\r\n\r\ninner product of R1A and C0B = " << ip << "\r\n";

    // make some bigger matrices
    Matrix<int> M1(5,5), M2(5,5,3), M3(5,5), M4(5,5);

    const int junk[]  = { 1, 5, 3, 0, 1,
                          0, 2, 0, 4, 5,
                          1, 0, 0, 2, 3,
                          7, 1, 3, 0, 0,
                          2, 1, 0, 4, 6 };

    const int ident[] = { 1, 0, 0, 0, 0,
                          0, 1, 0, 0, 0,
                          0, 0, 1, 0, 0,
                          0, 0, 0, 1, 0,
                          0, 0, 0, 0, 1 };

    const int tridi[] = { 1, 1, 0, 0, 0,
                          1, 1, 1, 0, 0,
                          0, 1, 1, 1, 0,
                          0, 0, 1, 1, 1,
                          0, 0, 0, 1, 1 };

    const int utri[]  = { 1, 1, 1, 1, 1,
                          0, 1, 1, 1, 1,
                          0, 0, 1, 1, 1,
                          0, 0, 0, 1, 1,
                          0, 0, 0, 0, 1 };

    const int ltri[]  = { 1, 0, 0, 0, 0,
                          1, 1, 0, 0, 0,
                          1, 1, 1, 0, 0,
                          1, 1, 1, 1, 0,
                          1, 1, 1, 1, 1 };

    const int perm[]  = { 0, 1, 0, 0, 0,
                          1, 0, 0, 0, 0,
                          0, 0, 0, 1, 0,
                          0, 0, 0, 0, 1,
                          0, 0, 1, 0, 0 };

    const int det[]  = { 3, 5, 3, 8, 1,
                         2, 6, 3, 4, 5,
                         1, 4, 5, 2, 3,
                         7, 1, 3, 6, 8,
                         2, 4, 1, 4, 9 };
    M1 = ident;
    M3 = M1 * 2;
    M4 = junk;

    os << "\r\nmatrix M1 = \r\n";
    ShowMatrix(os,M1);

    os << "\r\nmatrix M2 = \r\n";
    ShowMatrix(os,M2);

    os << "\r\nmatrix M3 = \r\n";
    ShowMatrix(os,M3);

    os << "\r\nmatrix M4 = \r\n";
    ShowMatrix(os,M4);

    if (M1.IsDiagonal())
        os << "\r\nOKAY: M1 is diagonal";
    else
        os << "\r\nERROR: M1 should be diagonal";

    if (M1.IsIdentity())
        os << "\r\nOKAY: M1 is an identity matrix";
    else
        os << "\r\nERROR: M1 should be an identity matrix";

    if (!M2.IsDiagonal())
        os << "\r\nOKAY: M2 is not diagonal";
    else
        os << "\r\nERROR: M2 should not be diagonal";

    if (!M2.IsIdentity())
        os << "\r\nOKAY: M2 is not an identity matrix";
    else
        os << "\r\nERROR: M2 should not be an identity matrix";

    if (M3.IsDiagonal())
        os << "\r\nOKAY: M3 is diagonal";
    else
        os << "\r\nERROR: M3 should be diagonal";

    if (!M3.IsIdentity())
        os << "\r\nOKAY: M3 is not an identity matrix";
    else
        os << "\r\nERROR: M3 should not be an identity matrix";

    if (!M4.IsDiagonal())
        os << "\r\nOKAY: M4 is not diagonal";
    else
        os << "\r\nERROR: M4 should not be diagonal";

    if (!M4.IsIdentity())
        os << "\r\nOKAY: M4 is not an identity matrix";
    else
        os << "\r\nERROR: M4 should not be an identity matrix";

    // tridiagonal tests
    M1 = tridi;
    os << "\r\n\r\nmatrix M1 = \r\n";
    ShowMatrix(os,M1);

    if (M1.IsTridiagonal())
        os << "\r\nOKAY: M1 is tridiagonal";
    else
        os << "\r\nERROR: M1 should be tridiagonal";

    if (!M4.IsTridiagonal())
        os << "\r\nOKAY: M4 is not tridiagonal";
    else
        os << "\r\nERROR: M1 should not be tridiagonal";

    // upper triangular tests
    M1 = utri;
    os << "\r\n\r\nmatrix M1 = \r\n";
    ShowMatrix(os,M1);

    if (M1.IsUpperTriangular())
        os << "\r\nOKAY: M1 is upper-triangular";
    else
        os << "\r\nERROR: M1 should be upper-triangular";

    if (!M4.IsUpperTriangular())
        os << "\r\nOKAY: M4 is not upper-triangular";
    else
        os << "\r\nERROR: M4 should not be upper-triangular";

    // lower triangular tests
    M1 = ltri;
    os << "\r\n\r\nmatrix M1 = \r\n";
    ShowMatrix(os,M1);

    if (M1.IsLowerTriangular())
        os << "\r\nOKAY: M1 is lower-triangular";
    else
        os << "\r\nERROR: M1 should be lower-triangular";

    if (!M4.IsLowerTriangular())
        os << "\r\nOKAY: M4 is not lower-triangular";
    else
        os << "\r\nERROR: M4 should not be lower-triangular";

    // permutation tests
    M1 = perm;
    os << "\r\n\r\nmatrix M1 = \r\n";
    ShowMatrix(os,M1);

    M2 = ident;
    os << "\r\n\r\nmatrix M2 = \r\n";
    ShowMatrix(os,M2);

    if (M1.IsPermutation())
        os << "\r\nOKAY: M1 is permutation matrix";
    else
        os << "\r\nERROR: M1 should be permutation";

    if (M2.IsPermutation())
        os << "\r\nOKAY: M2 is permutation matrix";
    else
        os << "\r\nERROR: M2 should be permutation";

    if (!M4.IsPermutation())
        os << "\r\nOKAY: M4 is not permutation";
    else
        os << "\r\nERROR: M4 should not be permutation";

    // check singularity function
    M1(0,1) = 0;
    os << "\r\n\r\nmatrix M1 = \r\n";
    ShowMatrix(os,M1);

    if (M1.IsSingular())
        os << "\r\nOKAY: M1 is singular";
    else
        os << "\r\nERROR: M1 should be singular";

    if (!M2.IsSingular())
        os << "\r\nOKAY: M2 is not singular";
    else
        os << "\r\nERROR: M2 should not be singular";

    if (!M4.IsSingular())
        os << "\r\nOKAY: M4 is not singular";
    else
        os << "\r\nERROR: M4 should not be singular";

    // change main window heading
    os <<endl
       <<"Matrix Tests (manipulations)" <<endl
       <<"============================" <<endl;
    
    // test minors and determinants
    os << "\r\n\r\nmatrix M4 = \r\n";
    ShowMatrix(os,M4);

    os << "\r\nminor M4(1,1) = \r\n";
    ShowMatrix(os,M4.Minor(1,1));

    os << "\r\nminor M4(0,4) = \r\n";
    ShowMatrix(os,M4.Minor(0,4));

    Matrix<int> M5(2,2), M6(3,3);

    M5(0,0) = 1;
    M5(0,1) = 2;
    M5(1,0) = 3;
    M5(1,1) = 4;

    M6(0,0) = 1;
    M6(0,1) = 3;
    M6(0,2) = 2;
    M6(1,0) = 5;
    M6(1,1) = 4;
    M6(1,2) = 7;
    M6(2,0) = 6;
    M6(2,1) = 9;
    M6(2,2) = 8;

    M4 = det;
    Matrix<int> T4(5,5), T5(2,2), T6(3,3);

    T4 = M4.Transpose();
    T5 = M5.Transpose();
    T6 = M6.Transpose();

    os << "\r\nmatrix M5 = \r\n";
    ShowMatrix(os,M5);

    os << "\r\ndeterminant of M5 = "
           << M5.Determinant() << "\r\n";

    os << "\r\nmatrix T5 = \r\n";
    ShowMatrix(os,T5);

    os << "\r\ndeterminant of T5 = "
           << T5.Determinant() << "\r\n";

    os << "\r\nmatrix M6 = \r\n";
    ShowMatrix(os,M6);

    os << "\r\ndeterminant of M6 = "
           << M6.Determinant() << "\r\n";

    os << "\r\nmatrix T6 = \r\n";
    ShowMatrix(os,T6);

    os << "\r\ndeterminant of T6 = "
           << T6.Determinant() << "\r\n";

    os << "\r\nmatrix M4 = \r\n";
    ShowMatrix(os,M4);

    os << "\r\ndeterminant of M4 = "
           << M4.Determinant() << "\r\n";

    os << "\r\nmatrix T4 = \r\n";
    ShowMatrix(os,T4);

    os << "\r\ndeterminant of T4 = "
           << T4.Determinant() << "\r\n";

    Matrix<int> R;
    os << "\r\nMatrix R (def. constr.) = \r\n";
    ShowMatrix(os,R);

    R.Resize(10,10);
    os << "\r\nMatrix R (now 10x10) = \r\n";
    ShowMatrix(os,R);

    // change main window heading
    os <<endl
       <<"Matrix Tests (double)" <<endl
       <<"=====================" <<endl;
    
    // check <double> Matrix
    os << "\r\nFLOATING POINT!";

    Matrix<double> X(3,4), Y(4,3), Z(3,3);

    X(0,0) =  1.0; X(1,0) =  5.0; X(2,0) =  2.0;
    X(0,1) =  2.0; X(1,1) =  2.0; X(2,1) =  4.0;
    X(0,2) =  0.0; X(1,2) =  3.0; X(2,2) =  3.0;
    X(0,3) =  1.0; X(1,3) =  2.0; X(2,3) =  1.0;

    Y(0,0) =  0.0; Y(2,0) =  1.0;
    Y(0,1) =  1.0; Y(2,1) =  0.0;
    Y(0,2) =  2.0; Y(2,2) =  5.0;
    Y(1,0) =  1.0; Y(3,0) =  3.0;
    Y(1,1) =  3.0; Y(3,1) =  1.0;
    Y(1,2) =  2.0; Y(3,2) =  2.0;

    os << "\r\nMatrix X = \r\n";
    ShowMatrix(os,X);
    os << "\r\nMatrix Y = \r\n";
    ShowMatrix(os,Y);

    Z = X % Y;
    os << "\r\nMatrix Z (X % Y) = \r\n";
    ShowMatrix(os,Z);

    // check transposition
    Matrix<double> tX;
    tX = X.Transpose();
    os << "\r\nOriginal X =\r\n";
    ShowMatrix(os,X);
    os << "\r\nTranspose X =\r\n";
    ShowMatrix(os,tX);

    X(0,0) =  1; X(0,1) =  3; X(0,2) = -4; X(0,3) =  8;
    X(1,0) =  1; X(1,1) =  1; X(1,2) = -2; X(1,3) =  2;
    X(2,0) = -1; X(2,1) = -2; X(2,2) =  5; X(2,3) = -1;

    os << "\r\nOriginal X =\r\n";
    ShowMatrix(os,X);

    Matrix<double> lX(X.LinSolve());
    os << "\r\nX after elimination =\r\n";
    ShowMatrix(os,X);

    os << "\r\nlinear equation solution =\r\n";
    ShowMatrix(os,lX);

    X(0,0) =  1.0; X(1,0) =  3.0; X(2,0) =  5.0;
    X(0,1) =  2.0; X(1,1) =  5.0; X(2,1) =  6.0;
    X(0,2) =  0.0; X(1,2) =  4.0; X(2,2) =  3.0;
    X(0,3) =  0.1; X(1,3) = 12.5; X(2,3) = 10.3;

    os << "\r\nOriginal X =\r\n";
    ShowMatrix(os,X);

    lX = X.LinSolve();
    os << "\r\nX after elimination =\r\n";
    ShowMatrix(os,X);

    os << "\r\nlinear equation solution =\r\n";
    ShowMatrix(os,lX);

    Matrix<double> Adbl(3,3), Bdbl(3,1);

    Adbl(0,0) =  1.0; Adbl(0,1) =  2.0; Adbl(0,2) =  0.0;
    Adbl(1,0) =  3.0; Adbl(1,1) =  5.0; Adbl(1,2) =  4.0;
    Adbl(2,0) =  5.0; Adbl(2,1) =  6.0; Adbl(2,2) =  3.0;

    Bdbl(0,0) =  0.1;
    Bdbl(1,0) = 12.5;
    Bdbl(2,0) = 10.3;

    os << "\r\n\r\nmatrix Adbl = \r\n";
    ShowMatrix(os,Adbl);

    os << "\r\nmatrix Bdbl = \r\n";
    ShowMatrix(os,Bdbl);

    Matrix<double> alup(Adbl); // copy Adbl before LUP decomp
    os << "\r\nLU decomp of Adbl (before) = \r\n";
    ShowMatrix(os,alup);

    Matrix<size_t> aperm = alup.LUPDecompose();
    os << "\r\nLU decomp of Adbl (after) = \r\n";
    ShowMatrix(os,alup);

    os << "\r\nPermutation of Adbl = \r\n";
    ShowMatrix(os,aperm);

    Matrix<double> asol = alup.LUPSolve(aperm,Bdbl);
    os << "\r\nlinear solution of Adbl and Bdbl = \r\n";
    ShowMatrix(os,asol);

    Matrix<double> ainv = alup.LUPInvert(aperm);
    os << "\r\ninverse of Adbl and Bdbl = \r\n";
    ShowMatrix(os,ainv);

    Matrix<double> aid = Adbl % ainv;
    os << "\r\ninverse dot Adbl = \r\n";
    ShowMatrix(os,aid);

    Grid<size_t> iperm = ainv.LUPDecompose();
    Matrix<double> invinv = ainv.LUPInvert(iperm);
    os << "\r\ninverse of inverse =\r\n";
    ShowMatrix(os,invinv);
}
コード例 #8
0
ファイル: num.c プロジェクト: ashvtol/asccalc
num_t
num_int_part_sel(pseltype_t op_type, num_t hi, num_t lo, num_t a)
{
	num_t r, m;
	unsigned long mask_shl, lo_ui;

	r = num_new_z(N_TEMP, NULL);
	m = num_new_z(N_TEMP, NULL);
	a = num_new_z(N_TEMP, a);
	hi = num_new_z(N_TEMP, hi);
	if (lo != NULL)
		lo = num_new_z(N_TEMP, lo);

	switch (op_type) {
	case PSEL_SINGLE:
		lo = num_new_z(N_TEMP, hi);
		break;

	case PSEL_FRANGE:
		break;

	case PSEL_DRANGE:
		if (mpz_cmp_si(Z(lo), 0L) < 0) {
			yyxerror("low index of part select operation must be "
			    "positive");
			return NULL;
		}
		mpz_sub_ui(Z(lo), Z(lo), 1UL);
		mpz_sub(Z(lo), Z(hi), Z(lo));
		break;
	}

	if (mpz_cmp_si(Z(hi), 0L) < 0) {
		yyxerror("high index of part select operation must be "
		    "positive");
		return NULL;
	}

	if (mpz_cmp_si(Z(lo), 0L) < 0) {
		yyxerror("low index of part select operation must be "
		    "positive");
		return NULL;
	}

	if (!mpz_fits_ulong_p(Z(hi))) {
		yyxerror("high index of part select operation needs to fit "
		    "into an unsigned long C datatype");
		return NULL;
	}

	if (!mpz_fits_ulong_p(Z(lo))) {
		yyxerror("low index of part select operation needs to fit "
		    "into an unsigned long C datatype");
		return NULL;
	}

	lo_ui = mpz_get_ui(Z(lo));
	mask_shl = 1 + (mpz_get_ui(Z(hi)) - lo_ui);

	/*
	 * We do the part sel by:
	 *  (1) shifting right by 'lo'
	 *  (2) anding with ((1 << mask_shl)-1)
	 */
	mpz_div_2exp(Z(r), Z(a), lo_ui);
	mpz_set_ui(Z(m), 1UL);
	mpz_mul_2exp(Z(m), Z(m), mask_shl);
	mpz_sub_ui(Z(m), Z(m), 1UL);

	mpz_and(Z(r), Z(r), Z(m));

	return r;
}
コード例 #9
0
ファイル: num.c プロジェクト: ashvtol/asccalc
num_t
num_float_two_op(optype_t op_type, num_t a, num_t b)
{
	num_t r, r_z, rem_z, a_z, b_z;
	int both_z = num_both_z(a, b);

	r = num_new_fp(N_TEMP, NULL);
	mpfr_set_prec(F(r), num_max_prec(a, b));

	a = num_new_fp(N_TEMP, a);
	b = num_new_fp(N_TEMP, b);

	if (both_z) {
		r_z = num_new_z(N_TEMP, NULL);
		rem_z = num_new_z(N_TEMP, NULL);
		a_z = num_new_z(N_TEMP, a);
		b_z = num_new_z(N_TEMP, b);
	}

	switch (op_type) {
	case OP_ADD:
		if (both_z) {
			mpz_add(Z(r_z), Z(a_z), Z(b_z));
			return r_z;
		} else {
			mpfr_add(F(r), F(a), F(b), round_mode);
		}
		break;

	case OP_SUB:
		if (both_z) {
			mpz_sub(Z(r_z), Z(a_z), Z(b_z));
			return r_z;
		} else {
			mpfr_sub(F(r), F(a), F(b), round_mode);
		}
		break;

	case OP_MUL:
		if (both_z) {
			mpz_mul(Z(r_z), Z(a_z), Z(b_z));
			return r_z;
		} else {
			mpfr_mul(F(r), F(a), F(b), round_mode);
		}
		break;

	case OP_DIV:
		if (both_z)
			mpz_divmod(Z(r_z), Z(rem_z), Z(a_z), Z(b_z));

		if (both_z && num_is_zero(rem_z))
			return r_z;
		else
			mpfr_div(F(r), F(a), F(b), round_mode);
		break;

	case OP_MOD:
		if (both_z) {
			mpz_mod(Z(r_z), Z(a_z), Z(b_z));
			return r_z;
		} else {
			/*
			 * XXX: mpfr_fmod or mpfr_remainder
			 */
			mpfr_fmod(F(r), F(a), F(b), round_mode);
		}
		break;

	case OP_POW:
		mpfr_pow(F(r), F(a), F(b), round_mode);
		break;

	default:
		yyxerror("Unknown op in num_float_two_op");
	}

	return r;
}
コード例 #10
0
ファイル: num.c プロジェクト: ashvtol/asccalc
num_t
num_new_from_str(int flags, numtype_t typehint, char *str)
{
	numtype_t type = typehint;
	double exp;
	char *suffix, *s;
	int base, type_override, r;
	num_t n;

	n = num_new(flags);

	/*
	 * If it's a decimal number but it doesn't have a floating point, suffix, etc
	 * treat it as an integer.
	 */
	type_override = 1;
	if (typehint == NUM_FP) {
		s = (str[1] == 'd') ? str + 2 : str;
		while (*s != '\0') {
			if (!isdigit(*s++)) {
				type_override = 0;
				break;
			}
		}

		if (type_override)
			type = NUM_INT;
	}

	n->num_type = type;

	base = 0;

	if (str[1] == 'd') {
		base = 10;
		str += 2;
	}

	if (type == NUM_INT) {
		if ((r = mpz_init_set_str(Z(n), str, base)) != 0) {
			yyxerror("mpz_init_set_str");
			mpz_clear(Z(n));
		}
	} else {
		if (str[1] == 'd')
			str += 2;

		mpfr_init(F(n));
		r = mpfr_strtofr(F(n), str, &suffix, 0, round_mode);

		/*
		 * XXX: add support for IEC binary prefixes?
		 */
		if (*suffix != '\0') {
			switch (*suffix) {
			case 'k':
				exp = 1000;
				break;
			case 'M':
				exp = 1000000;
				break;
			case 'G':
				exp = 1000000000;
				break;
			case 'T':
				exp = 1000000000000;
				break;
			case 'P':
				exp = 1000000000000000;
				break;
			case 'E':
				exp = 1000000000000000000;
				break;
			case 'm':
				exp = 0.001;
				break;
			case 'u':
				exp = 0.000001;
				break;
			case 'n':
				exp = 0.000000001;
				break;
			case 'p':
				exp = 0.000000000001;
				break;
			case 'f':
				exp = 0.000000000000001;
				break;
			case 'a':
				exp = 0.000000000000000001;
				break;
			default:
				yyxerror("Unknown suffix");
				exit(1);
			}

			mpfr_mul_d(F(n), F(n), exp, round_mode);
		}
	}

	return n;
}
コード例 #11
0
ファイル: num.c プロジェクト: ashvtol/asccalc
num_t
num_int_two_op(optype_t op_type, num_t a, num_t b)
{
	num_t r;

	r = num_new_z(N_TEMP, NULL);
	a = num_new_z(N_TEMP, a);
	b = num_new_z(N_TEMP, b);

	switch (op_type) {
	case OP_AND:
		mpz_and(Z(r), Z(a), Z(b));
		break;

	case OP_OR:
		mpz_ior(Z(r), Z(a), Z(b));
		break;

	case OP_XOR:
		mpz_xor(Z(r), Z(a), Z(b));
		break;

	case OP_SHR:
		if (!mpz_fits_ulong_p(Z(b))) {
			yyxerror
			    ("Second argument to shift needs to fit into an unsigned long C datatype");
			return NULL;
		}
		mpz_fdiv_q_2exp(Z(r), Z(a), mpz_get_ui(Z(b)));
		break;

	case OP_SHL:
		if (!mpz_fits_ulong_p(Z(b))) {
			yyxerror
			    ("Second argument to shift needs to fit into an unsigned long C datatype");
			return NULL;
		}
		mpz_mul_2exp(Z(r), Z(a), mpz_get_ui(Z(b)));
		break;

	default:
		yyxerror("Unknown op in num_int_two_op");
	}

	return r;
}
コード例 #12
0
std::vector<bytestring> silvia_irma_issuer::get_issue_commands_round_1()
{
	assert(irma_issuer_state == IRMA_ISSUER_SELECTED);
	
	std::vector<bytestring> commands;
	
	////////////////////////////////////////////////////////////////////
	// Step 3: start issuance
	////////////////////////////////////////////////////////////////////
	
	// FIXME: context is randomly generated and kept as state!
	mpz_class context_mpz = silvia_rng::i()->get_random(SYSPAR(l_H));
	context = bytestring(context_mpz);
	bytestring id;
	id += (unsigned char) ((ispec->get_credential_id() & 0xff00) >> 8);
	id += (unsigned char) (ispec->get_credential_id() & 0x00ff);
	
	bytestring attr_count;
	attr_count += (unsigned char) ((ispec->get_attributes().size() + 1) & 0xff00) >> 8; // +1 for expires
	attr_count += (unsigned char) ((ispec->get_attributes().size() + 1) & 0x00ff); 		// +1 for expires
	
	// FIXME: actually do something with these flags!
	bytestring attr_flags = "000000";
	
	bytestring timestamp = (unsigned long) time(NULL);
	timestamp = timestamp.substr(timestamp.size() - 4);
	
	PAD_TO_SYSPAR(context, l_H);
	
	silvia_apdu issue_start(0x80, 0x10, 0x00, 0x00);
	
	issue_start.append_data(id);
	issue_start.append_data(attr_count);
	issue_start.append_data(attr_flags);
	issue_start.append_data(context);
	issue_start.append_data(timestamp);
	
	commands.push_back(issue_start.get_apdu());
	
	////////////////////////////////////////////////////////////////////
	// Step 4: write the public key to the card
	////////////////////////////////////////////////////////////////////
	
	// n
	silvia_apdu issue_set_n(0x80, 0x11, 0x00, 0x00);
	bytestring n(pubkey->get_n());
	
	// Pad if necessary
	PAD_TO_SYSPAR(n, l_n);
	
	issue_set_n.append_data(n);
	
	commands.push_back(issue_set_n.get_apdu());
	
	// S
	silvia_apdu issue_set_S(0x80, 0x11, 0x01, 0x00);
	bytestring S(pubkey->get_S());
	
	// Pad if necessary
	PAD_TO_SYSPAR(S, l_n);
	
	issue_set_S.append_data(S);
	
	commands.push_back(issue_set_S.get_apdu());
	
	// Z
	silvia_apdu issue_set_Z(0x80, 0x11, 0x02, 0x00);
	bytestring Z(pubkey->get_Z());
	
	// Pad if necessary
	PAD_TO_SYSPAR(Z, l_n);
	
	issue_set_Z.append_data(Z);
	
	commands.push_back(issue_set_Z.get_apdu());
	
	for (int i = 0; i < (ispec->get_attributes().size() + 2); i++)
	{
		silvia_apdu issue_set_R(0x80, 0x11, 0x03, (unsigned char) (0x00 + i));
		
		bytestring R(pubkey->get_R()[i]);
		
		// Pad if necessary
		PAD_TO_SYSPAR(R, l_n);
		
		issue_set_R.append_data(R);
		
		commands.push_back(issue_set_R.get_apdu());
	}
	
	////////////////////////////////////////////////////////////////////
	// Step 5: write the attributes to the card
	////////////////////////////////////////////////////////////////////
	
	issue_attributes.clear();
	
	// Create the "expires+metadata" attribute
	bytestring expires_and_metadata;
	
	// Add metadata version number
	expires_and_metadata += IRMA_CREDENTIAL_METADATA_VERSION;
	
	// Add expiration date
	int expires = ispec->get_expires();
	
	expires_and_metadata += (unsigned char) ((expires & 0x00ff0000) >> 16);
	expires_and_metadata += (unsigned char) ((expires & 0x0000ff00) >> 8);
	expires_and_metadata += (unsigned char)  (expires & 0x000000ff);
	
	// Add credential ID
	expires_and_metadata += (unsigned char) ((ispec->get_credential_id() & 0xff00) >> 8);
	expires_and_metadata += (unsigned char) (ispec->get_credential_id() & 0x00ff);
	
	metadata_attribute = new silvia_integer_attribute(expires_and_metadata.mpz_val());
	
	silvia_apdu write_expires_attr(0x80, 0x12, 0x01, 0x00);
	
	write_expires_attr.append_data(metadata_attribute->bs_rep());
	
	commands.push_back(write_expires_attr.get_apdu());
	
	issue_attributes.push_back(metadata_attribute);
	
	// Create all other attributes
	unsigned char ctr = 0x02;
	
	for (std::vector<silvia_attribute*>::iterator i = ispec->get_attributes().begin(); i != ispec->get_attributes().end(); i++, ctr++)
	{
		silvia_apdu write_attr(0x80, 0x12, ctr, 0x00);
		write_attr.append_data((*i)->bs_rep());
		
		commands.push_back(write_attr.get_apdu());
		
		issue_attributes.push_back(*i);
	}
	
	issuer->set_attributes(issue_attributes);
	
	////////////////////////////////////////////////////////////////////
	// Step 6: get issue commitment from card
	////////////////////////////////////////////////////////////////////
	
	silvia_apdu issue_commitment_nonce(0x80, 0x1a, 0x00, 0x00);
	
	bytestring n1(issuer->get_issuer_nonce());
	
	// pad if necessary
	PAD_TO_SYSPAR(n1, l_statzk);
	
	silvia_apdu issue_commitment(0x80, 0x1a, 0x00, 0x00);
	issue_commitment.append_data(n1);
	
	commands.push_back(issue_commitment.get_apdu());
	
	////////////////////////////////////////////////////////////////////
	// Step 7: get proof values c, v'^, s^
	////////////////////////////////////////////////////////////////////
	
	silvia_apdu get_proof_c(0x80, 0x1b, 0x01, 0x00);
	silvia_apdu get_proof_v_prime_hat(0x80, 0x1b, 0x02, 0x00);
	silvia_apdu get_proof_s_hat(0x80, 0x1b, 0x03, 0x00);
	
	commands.push_back(get_proof_c.get_apdu());
	commands.push_back(get_proof_v_prime_hat.get_apdu());
	commands.push_back(get_proof_s_hat.get_apdu());
	
	////////////////////////////////////////////////////////////////////
	// Step 8: get card nonce n2
	////////////////////////////////////////////////////////////////////
	
	silvia_apdu get_card_nonce_n2(0x80, 0x1c, 0x00, 0x00);
	
	commands.push_back(get_card_nonce_n2.get_apdu());
	
	irma_issuer_state = IRMA_ISSUER_WAIT_COMMITMENT;
	
	return commands;
}
コード例 #13
0
ファイル: zbuffer.cpp プロジェクト: tjw/DOJulia
float zbufferDepth(zbuffer * z, unsigned int row, unsigned int col)
{
    return *Z(z, row, col);
}
コード例 #14
0
ファイル: lint64.c プロジェクト: lindianyin/test
static int Ltonumber(lua_State *L)		/** tonumber(z) */
{
 lua_pushnumber(L,(lua_Number)Z(1));
 return 1;
}
コード例 #15
0
ファイル: sstedx.cpp プロジェクト: EmergentOrder/clmagma
extern "C" magma_int_t
magma_sstedx(magma_vec_t range, magma_int_t n, float vl, float vu,
             magma_int_t il, magma_int_t iu, float* d, float* e, float* z, magma_int_t ldz,
             float* work, magma_int_t lwork, magma_int_t* iwork, magma_int_t liwork,
             magmaFloat_ptr dwork, magma_int_t* info, magma_queue_t queue)
{
/*
    -- MAGMA (version 1.1.0) --
    Univ. of Tennessee, Knoxville
    Univ. of California, Berkeley
    Univ. of Colorado, Denver
    @date January 2014

       .. Scalar Arguments ..
      CHARACTER          RANGE
      INTEGER            IL, IU, INFO, LDZ, LIWORK, LWORK, N
      REAL   VL, VU
       ..
       .. Array Arguments ..
      INTEGER            IWORK( * )
      REAL   D( * ), E( * ), WORK( * ), Z( LDZ, * ),
     $                   DWORK ( * )
       ..

    Purpose
    =======

    SSTEDX computes some eigenvalues and, optionally, eigenvectors of a
    symmetric tridiagonal matrix using the divide and conquer method.

    This code makes very mild assumptions about floating point
    arithmetic. It will work on machines with a guard digit in
    add/subtract, or on those binary machines without guard digits
    which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2.
    It could conceivably fail on hexadecimal or decimal machines
    without guard digits, but we know of none.  See SLAEX3 for details.

    Arguments
    =========

    RANGE   (input) CHARACTER*1
            = 'A': all eigenvalues will be found.
            = 'V': all eigenvalues in the half-open interval (VL,VU]
                   will be found.
            = 'I': the IL-th through IU-th eigenvalues will be found.

    N       (input) INTEGER
            The dimension of the symmetric tridiagonal matrix.  N >= 0.

    VL      (input) REAL
    VU      (input) REAL
            If RANGE='V', the lower and upper bounds of the interval to
            be searched for eigenvalues. VL < VU.
            Not referenced if RANGE = 'A' or 'I'.

    IL      (input) INTEGER
    IU      (input) INTEGER
            If RANGE='I', the indices (in ascending order) of the
            smallest and largest eigenvalues to be returned.
            1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0.
            Not referenced if RANGE = 'A' or 'V'.

    D       (input/output) REAL array, dimension (N)
            On entry, the diagonal elements of the tridiagonal matrix.
            On exit, if INFO = 0, the eigenvalues in ascending order.

    E       (input/output) REAL array, dimension (N-1)
            On entry, the subdiagonal elements of the tridiagonal matrix.
            On exit, E has been destroyed.

    Z       (input/output) REAL array, dimension (LDZ,N)
            On exit, if INFO = 0, Z contains the orthonormal eigenvectors
            of the symmetric tridiagonal matrix.

    LDZ     (input) INTEGER
            The leading dimension of the array Z. LDZ >= max(1,N).

    WORK    (workspace/output) REAL array,
                                           dimension (LWORK)
            On exit, if INFO = 0, WORK(1) returns the optimal LWORK.

    LWORK   (input) INTEGER
            The dimension of the array WORK.
            If N > 1 then LWORK must be at least ( 1 + 4*N + N**2 ).
            Note that  if N is less than or
            equal to the minimum divide size, usually 25, then LWORK need
            only be max(1,2*(N-1)).

            If LWORK = -1, then a workspace query is assumed; the routine
            only calculates the optimal size of the WORK array, returns
            this value as the first entry of the WORK array, and no error
            message related to LWORK is issued by XERBLA.

    IWORK   (workspace/output) INTEGER array, dimension (MAX(1,LIWORK))
            On exit, if INFO = 0, IWORK(1) returns the optimal LIWORK.

    LIWORK  (input) INTEGER
            The dimension of the array IWORK.
            LIWORK must be at least ( 3 + 5*N ).
            Note that if N is less than or
            equal to the minimum divide size, usually 25, then LIWORK
            need only be 1.

            If LIWORK = -1, then a workspace query is assumed; the
            routine only calculates the optimal size of the IWORK array,
            returns this value as the first entry of the IWORK array, and
            no error message related to LIWORK is issued by XERBLA.

    DWORK  (device workspace) REAL array, dimension (3*N*N/2+3*N)

    INFO    (output) INTEGER
            = 0:  successful exit.
            < 0:  if INFO = -i, the i-th argument had an illegal value.
            > 0:  The algorithm failed to compute an eigenvalue while
                  working on the submatrix lying in rows and columns
                  INFO/(N+1) through mod(INFO,N+1).

    Further Details
    ===============

    Based on contributions by
       Jeff Rutter, Computer Science Division, University of California
       at Berkeley, USA
    Modified by Francoise Tisseur, University of Tennessee.

    =====================================================================
*/
    magma_vec_t range_ = range;

    float d_zero = 0.;
    float d_one  = 1.;
    magma_int_t izero = 0;
    magma_int_t ione = 1;


    magma_int_t alleig, indeig, valeig, lquery;
    magma_int_t i, j, k, m;
    magma_int_t liwmin, lwmin;
    magma_int_t start, end, smlsiz;
    float eps, orgnrm, p, tiny;

    // Test the input parameters.

    alleig = lapackf77_lsame(lapack_const(range_), "A");
    valeig = lapackf77_lsame(lapack_const(range_), "V");
    indeig = lapackf77_lsame(lapack_const(range_), "I");
    lquery = lwork == -1 || liwork == -1;

    *info = 0;

    if (! (alleig || valeig || indeig)) {
        *info = -1;
    } else if (n < 0) {
        *info = -2;
    } else if (ldz < max(1,n)) {
        *info = -10;
    } else {
        if (valeig) {
            if (n > 0 && vu <= vl) {
                *info = -4;
            }
        } else if (indeig) {
            if (il < 1 || il > max(1,n)) {
                *info = -5;
            } else if (iu < min(n,il) || iu > n) {
                *info = -6;
            }
        }
    }

    if (*info == 0) {
        // Compute the workspace requirements

        smlsiz = get_sstedx_smlsize();
        if( n <= 1 ){
            lwmin = 1;
            liwmin = 1;
        } else {
            lwmin = 1 + 4*n + n*n;
            liwmin = 3 + 5*n;
        }

        work[0] = lwmin;
        iwork[0] = liwmin;

        if (lwork < lwmin && ! lquery) {
            *info = -12;
        } else if (liwork < liwmin && ! lquery) {
            *info = -14;
        }
    }

    if (*info != 0) {
        magma_xerbla( __func__, -(*info));
        return MAGMA_ERR_ILLEGAL_VALUE;
    } else if (lquery) {
        return MAGMA_SUCCESS;
    }

    // Quick return if possible

    if(n==0)
        return MAGMA_SUCCESS;
    if(n==1){
        *z = 1.;
        return MAGMA_SUCCESS;
    }

    // If N is smaller than the minimum divide size (SMLSIZ+1), then
    // solve the problem with another solver.

    if (n < smlsiz){
        char char_I[]= {'I', 0};
        lapackf77_ssteqr(char_I, &n, d, e, z, &ldz, work, info);
    } else {
        char char_F[]= {'F', 0};
        lapackf77_slaset(char_F, &n, &n, &d_zero, &d_one, z, &ldz);

        //Scale.
        char char_M[]= {'M', 0};

        orgnrm = lapackf77_slanst(char_M, &n, d, e);

        if (orgnrm == 0){
            work[0]  = lwmin;
            iwork[0] = liwmin;
            return MAGMA_SUCCESS;
        }

        eps = lapackf77_slamch( "Epsilon" );

        if (alleig){
            start = 0;
            while ( start < n ){

                // Let FINISH be the position of the next subdiagonal entry
                // such that E( END ) <= TINY or FINISH = N if no such
                // subdiagonal exists.  The matrix identified by the elements
                // between START and END constitutes an independent
                // sub-problem.

                for(end = start+1; end < n; ++end){
                    tiny = eps * sqrt( MAGMA_S_ABS(d[end-1]*d[end]));
                    if (MAGMA_S_ABS(e[end-1]) <= tiny)
                        break;
                }

                // (Sub) Problem determined.  Compute its size and solve it.

                m = end - start;
                if (m==1){
                    start = end;
                    continue;
                }
                if (m > smlsiz){

                    // Scale
                    char char_G[] = {'G', 0};
                    orgnrm = lapackf77_slanst(char_M, &m, &d[start], &e[start]);
                    lapackf77_slascl(char_G, &izero, &izero, &orgnrm, &d_one, &m, &ione, &d[start], &m, info);
                    magma_int_t mm = m-1;
                    lapackf77_slascl(char_G, &izero, &izero, &orgnrm, &d_one, &mm, &ione, &e[start], &mm, info);

                    magma_slaex0( m, &d[start], &e[start], Z(start, start), ldz, work, iwork, dwork, MagmaAllVec, vl, vu, il, iu, info, queue);

                    if( *info != 0) {
                        return MAGMA_SUCCESS;
                    }

                    // Scale Back
                    lapackf77_slascl(char_G, &izero, &izero, &d_one, &orgnrm, &m, &ione, &d[start], &m, info);

                } else {

                    char char_I[]= {'I', 0};
                    lapackf77_ssteqr( char_I, &m, &d[start], &e[start], Z(start, start), &ldz, work, info);
                    if (*info != 0){
                        *info = (start+1) *(n+1) + end;
                    }
                }

                start = end;
            }


            // If the problem split any number of times, then the eigenvalues
            // will not be properly ordered.  Here we permute the eigenvalues
            // (and the associated eigenvectors) into ascending order.

            if (m < n){

                // Use Selection Sort to minimize swaps of eigenvectors
                for (i = 1; i < n; ++i){
                    k = i-1;
                    p = d[i-1];
                    for (j = i; j < n; ++j){
                        if (d[j] < p){
                            k = j;
                            p = d[j];
                        }
                    }
                    if(k != i-1) {
                        d[k] = d[i-1];
                        d[i-1] = p;
                        blasf77_sswap(&n, Z(0,i-1), &ione, Z(0,k), &ione);
                    }
                }
            }

        } else {

            // Scale
            char char_G[] = {'G', 0};
            lapackf77_slascl(char_G, &izero, &izero, &orgnrm, &d_one, &n, &ione, d, &n, info);
            magma_int_t nm = n-1;
            lapackf77_slascl(char_G, &izero, &izero, &orgnrm, &d_one, &nm, &ione, e, &nm, info);

            magma_slaex0( n, d, e, z, ldz, work, iwork, dwork, range, vl, vu, il, iu, info, queue);

            if( *info != 0) {
                return MAGMA_SUCCESS;
            }

            // Scale Back
            lapackf77_slascl(char_G, &izero, &izero, &d_one, &orgnrm, &n, &ione, d, &n, info);

        }
    }

    work[0]  = lwmin;
    iwork[0] = liwmin;

    return MAGMA_SUCCESS;

} /* sstedx */
コード例 #16
0
ファイル: Mapper.cpp プロジェクト: moukaddam/LensMapper
double mapping(TString SimData, TString ExpData, TString background = "nobackground"){

/////////////////////// OPEN INPUT AND OUTPUT FILES ///////////////////////
// open the data file
ifstream input_exp;
TString fullpathtofile = Form("%s",ExpData.Data() ) ; 
if(gVerbose>0) cout<<"opening file : |"<<ExpData<< "| ... ";
input_exp.open( ExpData.Data() );
if (!input_exp) { cout<<"problem opening experimental data file " << fullpathtofile << endl; exit(-1);}
else if(gVerbose>0) cout<<"Experimental file is opened "<<endl;

//open the field files from comsol  
ifstream input_sim;
fullpathtofile = Form("%s",SimData.Data() ) ; 
if(gVerbose>0) cout<<"opening file : |"<<SimData<< "| ... ";
input_sim.open(SimData.Data() ) ; 
if(!input_sim.is_open()) {
	if(gVerbose>0) cout<<"problem opening simulation data file |"<< fullpathtofile <<"|"<< endl;
	SimData.ReplaceAll("./input/","");
	fullpathtofile = Form("/data1/moukaddam/MagnetSimulation/%s",SimData.Data()) ;
	if(gVerbose>0) cout<<"trying main directory, opening file : |"<<fullpathtofile<< "| ... ";
	input_sim.open(fullpathtofile.Data() ) ; // from local input if not go seek in data 1
	if (!input_sim.is_open()) { cout<<"problem opening simulation data file |"<< fullpathtofile <<"|"<< endl<<endl; exit(-1);}
}
else if(gVerbose>0) cout<<" Simulation file " <<  fullpathtofile <<  " is opened " <<endl;

// create root output file 
ExpData.ReplaceAll("./input/",""); ExpData.ReplaceAll(".dat",""); ExpData.ReplaceAll(".txt","");
SimData.ReplaceAll("./input/",""); SimData.ReplaceAll(".dat",""); SimData.ReplaceAll(".txt","");
TString  filename = "./output/compare_" + ExpData + "_" + SimData + ".root";
TFile outputFile(filename,"RECREATE");
TDirectory *dirquad[4] ; 
dirquad[0] = outputFile.mkdir("Quad_1");
dirquad[1] = outputFile.mkdir("Quad_2");
dirquad[2] = outputFile.mkdir("Quad_3");
dirquad[3] = outputFile.mkdir("Quad_4");

//Read the simulation file from comsol 
// dump the first lines from the top
string s_buffer="buffer";
Int_t d_buffer=-1;
Int_t counter1=0; // counter on the first lines
Int_t counter2=0; // counter on the first lines
// read the first lines
Int_t dimX, dimY, dimZ;
input_sim>>dimX>>dimY>>dimZ;
if(gVerbose>0) cout<<"\nSimulated Field Table dimensions              X : "<<dimX<<"     Y : "<<dimY<<"     Z : "<<dimZ<<endl;
dimX=dimX+10;
dimY=dimY+10;
dimZ=dimZ+10;
TH3D *f3DHistBx = new TH3D("f3DHistBX", "Bx"         , dimX,-dimX, dimX, dimY,-dimY, dimY, dimZ, -dimZ, dimZ); 
TH3D *f3DHistBy = new TH3D("f3DHistBY", "By"         , dimX,-dimX, dimX, dimY,-dimY, dimY, dimZ, -dimZ, dimZ);  
TH3D *f3DHistBz = new TH3D("f3DHistBZ", "Bz"         , dimX,-dimX, dimX, dimY,-dimY, dimY, dimZ, -dimZ, dimZ);  
TH3D *f3DHistBmag = new TH3D("f3DHistBMAG", "Bmag"   , dimX,-dimX, dimX, dimY,-dimY, dimY, dimZ, -dimZ, dimZ);     
TH3D *f3DHistBtan = new TH3D("f3DHistBTAN", "Btan"   , dimX,-dimX, dimX, dimY,-dimY, dimY, dimZ, -dimZ, dimZ);  
TH3D *f3DHistBdiff = new TH3D("f3DHistBDIFF", "Bdiff", dimX,-dimX, dimX, dimY,-dimY, dimY, dimZ, -dimZ, dimZ); 

d_buffer=-1;
while (d_buffer != 0 && counter1< 15){ // find a solution for this with do while
	input_sim>>d_buffer>>s_buffer;
	counter2++;
	}
getline(input_sim,s_buffer);
if(gVerbose>0) cout<< " Number of skipped lines in comsol file : " <<counter2 << "  last line content : "<<s_buffer<<endl;

// read and fill
SimulationPoint* SimPoint = new SimulationPoint();
Double_t X(0), Y(0), Z(0), EX(-100), EY(-100), EZ(-100), Perm(0);
Double_t BX(0), BY(0), BZ(0);
Int_t line=0;

while ( !input_sim.eof() ) {
	   //Clear parameters
	   SimPoint->ClearParameters();
	   // Choose format
	   if(counter2<9)   input_sim >> X >> Y >> Z >> BX >> BY >> BZ >> Perm ;
	   else   			input_sim >> X >> Y >> Z >> BX >> BY >> BZ >> EX >> EY >> EZ >> Perm ;
	    
		SimPoint->ReadLineAndTreat(X,Y,Z,BX,BY,BZ,EX,EY,EZ,Perm );
		//SimPoint->Show();
		// fill in TH3D all the simulation data
		Int_t binNumber = f3DHistBx->FindBin(X,Y,Z);
		f3DHistBx->SetBinContent(binNumber,BX);
		f3DHistBy->SetBinContent(binNumber,BY);
		f3DHistBz->SetBinContent(binNumber,BZ);	
		f3DHistBmag->SetBinContent(binNumber,SimPoint->fBFieldMag);
		f3DHistBtan->SetBinContent(binNumber,SimPoint->fBFieldTan);
		f3DHistBdiff->SetBinContent(binNumber,SimPoint->fBFieldDiff); //fBFieldMag-fBFieldTan 		
		//count the lines for inspection
		line++;
	   if (line%5000 == 0) {
		   if(gVerbose>0) printf("\r     @line : %d  ... Still reading ...",line);
		   if(gVerbose>1) cout<< X<<"   "<<Y <<"   "<<Z <<"   "<<BX <<"   "<<BY<<"   "<<BZ <<"   "<< EX<<"   "<< EY<<"   "<< EZ<<"   "<< Perm<<endl ;
	   }
}  
コード例 #17
0
/**
    Purpose
    -------
    SSTEDX computes some eigenvalues and, optionally, eigenvectors of a
    symmetric tridiagonal matrix using the divide and conquer method.

    This code makes very mild assumptions about floating point
    arithmetic. It will work on machines with a guard digit in
    add/subtract, or on those binary machines without guard digits
    which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2.
    It could conceivably fail on hexadecimal or decimal machines
    without guard digits, but we know of none.  See SLAEX3 for details.

    Arguments
    ---------
    @param[in]
    ngpu    INTEGER
            Number of GPUs to use. ngpu > 0.

    @param[in]
    range   magma_range_t
      -     = MagmaRangeAll: all eigenvalues will be found.
      -     = MagmaRangeV:   all eigenvalues in the half-open interval (VL,VU]
                             will be found.
      -     = MagmaRangeI:   the IL-th through IU-th eigenvalues will be found.

    @param[in]
    n       INTEGER
            The dimension of the symmetric tridiagonal matrix.  N >= 0.

    @param[in]
    vl      REAL
    @param[in]
    vu      REAL
            If RANGE=MagmaRangeV, the lower and upper bounds of the interval to
            be searched for eigenvalues. VL < VU.
            Not referenced if RANGE = MagmaRangeAll or MagmaRangeI.

    @param[in]
    il      INTEGER
    @param[in]
    iu      INTEGER
            If RANGE=MagmaRangeI, the indices (in ascending order) of the
            smallest and largest eigenvalues to be returned.
            1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0.
            Not referenced if RANGE = MagmaRangeAll or MagmaRangeV.

    @param[in,out]
    d       REAL array, dimension (N)
            On entry, the diagonal elements of the tridiagonal matrix.
            On exit, if INFO = 0, the eigenvalues in ascending order.

    @param[in,out]
    e       REAL array, dimension (N-1)
            On entry, the subdiagonal elements of the tridiagonal matrix.
            On exit, E has been destroyed.

    @param[in,out]
    Z       REAL array, dimension (LDZ,N)
            On exit, if INFO = 0, Z contains the orthonormal eigenvectors
            of the symmetric tridiagonal matrix.

    @param[in]
    ldz     INTEGER
            The leading dimension of the array Z. LDZ >= max(1,N).

    @param[out]
    work    (workspace) REAL array,
                                           dimension (LWORK)
            On exit, if INFO = 0, WORK[0] returns the optimal LWORK.

    @param[in]
    lwork   INTEGER
            The dimension of the array WORK.
            If N > 1 then LWORK >= ( 1 + 4*N + N**2 ).
            Note that  if N is less than or
            equal to the minimum divide size, usually 25, then LWORK need
            only be max(1,2*(N-1)).
    \n
            If LWORK = -1, then a workspace query is assumed; the routine
            only calculates the optimal size of the WORK array, returns
            this value as the first entry of the WORK array, and no error
            message related to LWORK is issued by XERBLA.

    @param[out]
    iwork   (workspace) INTEGER array, dimension (MAX(1,LIWORK))
            On exit, if INFO = 0, IWORK[0] returns the optimal LIWORK.

    @param[in]
    liwork  INTEGER
            The dimension of the array IWORK.
            LIWORK >= ( 3 + 5*N ).
            Note that if N is less than or
            equal to the minimum divide size, usually 25, then LIWORK
            need only be 1.
    \n
            If LIWORK = -1, then a workspace query is assumed; the
            routine only calculates the optimal size of the IWORK array,
            returns this value as the first entry of the IWORK array, and
            no error message related to LIWORK is issued by XERBLA.

    @param[out]
    info    INTEGER
      -     = 0:  successful exit.
      -     < 0:  if INFO = -i, the i-th argument had an illegal value.
      -     > 0:  The algorithm failed to compute an eigenvalue while
                  working on the submatrix lying in rows and columns
                  INFO/(N+1) through mod(INFO,N+1).

    Further Details
    ---------------
    Based on contributions by
       Jeff Rutter, Computer Science Division, University of California
       at Berkeley, USA
    Modified by Francoise Tisseur, University of Tennessee.

    @ingroup magma_ssyev_comp
    ********************************************************************/
extern "C" magma_int_t
magma_sstedx_m(
    magma_int_t ngpu,
    magma_range_t range, magma_int_t n, float vl, float vu,
    magma_int_t il, magma_int_t iu, float *d, float *e,
    float *Z, magma_int_t ldz,
    float *work, magma_int_t lwork,
    magma_int_t *iwork, magma_int_t liwork,
    magma_int_t *info)
{
#define Z(i_,j_) (Z + (i_) + (j_)*ldz)

    float d_zero = 0.;
    float d_one  = 1.;
    magma_int_t izero = 0;
    magma_int_t ione = 1;


    magma_int_t alleig, indeig, valeig, lquery;
    magma_int_t i, j, k, m;
    magma_int_t liwmin, lwmin;
    magma_int_t start, end, smlsiz;
    float eps, orgnrm, p, tiny;

    // Test the input parameters.

    alleig = (range == MagmaRangeAll);
    valeig = (range == MagmaRangeV);
    indeig = (range == MagmaRangeI);
    lquery = (lwork == -1 || liwork == -1);

    *info = 0;

    if (! (alleig || valeig || indeig)) {
        *info = -1;
    } else if (n < 0) {
        *info = -2;
    } else if (ldz < max(1,n)) {
        *info = -10;
    } else {
        if (valeig) {
            if (n > 0 && vu <= vl) {
                *info = -4;
            }
        } else if (indeig) {
            if (il < 1 || il > max(1,n)) {
                *info = -5;
            } else if (iu < min(n,il) || iu > n) {
                *info = -6;
            }
        }
    }

    if (*info == 0) {
        // Compute the workspace requirements

        smlsiz = magma_get_smlsize_divideconquer();
        if ( n <= 1 ) {
            lwmin = 1;
            liwmin = 1;
        } else {
            lwmin = 1 + 4*n + n*n;
            liwmin = 3 + 5*n;
        }

        work[0] = magma_smake_lwork( lwmin );
        iwork[0] = liwmin;

        if (lwork < lwmin && ! lquery) {
            *info = -12;
        } else if (liwork < liwmin && ! lquery) {
            *info = -14;
        }
    }

    if (*info != 0) {
        magma_xerbla( __func__, -(*info));
        return *info;
    } else if (lquery) {
        return *info;
    }

    // Quick return if possible
    if (n == 0)
        return *info;
    if (n == 1) {
        *Z = 1.;
        return *info;
    }

    /* determine the number of threads *///not needed here to be checked Azzam
    //magma_int_t threads = magma_get_parallel_numthreads();
    //magma_int_t mklth   = magma_get_lapack_numthreads();
    //magma_set_lapack_numthreads(mklth);

#ifdef ENABLE_DEBUG
    //printf("  D&C_m is using %d threads\n", threads);
#endif

    // If N is smaller than the minimum divide size (SMLSIZ+1), then
    // solve the problem with another solver.

    if (n < smlsiz) {
        lapackf77_ssteqr("I", &n, d, e, Z, &ldz, work, info);
    } else {
        lapackf77_slaset("F", &n, &n, &d_zero, &d_one, Z, &ldz);

        //Scale.
        orgnrm = lapackf77_slanst("M", &n, d, e);

        if (orgnrm == 0) {
            work[0]  = magma_smake_lwork( lwmin );
            iwork[0] = liwmin;
            return *info;
        }

        eps = lapackf77_slamch( "Epsilon" );

        if (alleig) {
            start = 0;
            while ( start < n ) {
                // Let FINISH be the position of the next subdiagonal entry
                // such that E( END ) <= TINY or FINISH = N if no such
                // subdiagonal exists.  The matrix identified by the elements
                // between START and END constitutes an independent
                // sub-problem.

                for (end = start+1; end < n; ++end) {
                    tiny = eps * sqrt( MAGMA_S_ABS(d[end-1]*d[end]));
                    if (MAGMA_S_ABS(e[end-1]) <= tiny)
                        break;
                }

                // (Sub) Problem determined.  Compute its size and solve it.

                m = end - start;
                if (m == 1) {
                    start = end;
                    continue;
                }
                if (m > smlsiz) {
                    // Scale
                    orgnrm = lapackf77_slanst("M", &m, &d[start], &e[start]);
                    lapackf77_slascl("G", &izero, &izero, &orgnrm, &d_one, &m, &ione, &d[start], &m, info);
                    magma_int_t mm = m-1;
                    lapackf77_slascl("G", &izero, &izero, &orgnrm, &d_one, &mm, &ione, &e[start], &mm, info);

                    magma_slaex0_m( ngpu, m, &d[start], &e[start], Z(start, start), ldz, work, iwork, MagmaRangeAll, vl, vu, il, iu, info);

                    if ( *info != 0) {
                        return *info;
                    }

                    // Scale Back
                    lapackf77_slascl("G", &izero, &izero, &d_one, &orgnrm, &m, &ione, &d[start], &m, info);
                } else {
                    lapackf77_ssteqr( "I", &m, &d[start], &e[start], Z(start, start), &ldz, work, info);
                    if (*info != 0) {
                        *info = (start+1) *(n+1) + end;
                    }
                }

                start = end;
            }


            // If the problem split any number of times, then the eigenvalues
            // will not be properly ordered.  Here we permute the eigenvalues
            // (and the associated eigenvectors) into ascending order.

            if (m < n) {
                // Use Selection Sort to minimize swaps of eigenvectors
                for (i = 1; i < n; ++i) {
                    k = i-1;
                    p = d[i-1];
                    for (j = i; j < n; ++j) {
                        if (d[j] < p) {
                            k = j;
                            p = d[j];
                        }
                    }
                    if (k != i-1) {
                        d[k] = d[i-1];
                        d[i-1] = p;
                        blasf77_sswap(&n, Z(0,i-1), &ione, Z(0,k), &ione);
                    }
                }
            }
        } else {
            // Scale
            lapackf77_slascl("G", &izero, &izero, &orgnrm, &d_one, &n, &ione, d, &n, info);
            magma_int_t nm = n-1;
            lapackf77_slascl("G", &izero, &izero, &orgnrm, &d_one, &nm, &ione, e, &nm, info);

            magma_slaex0_m(ngpu, n, d, e, Z, ldz, work, iwork, range, vl, vu, il, iu, info);

            if ( *info != 0) {
                return *info;
            }

            // Scale Back
            lapackf77_slascl("G", &izero, &izero, &d_one, &orgnrm, &n, &ione, d, &n, info);
        }
    }

    work[0]  = magma_smake_lwork( lwmin );
    iwork[0] = liwmin;

    return *info;
} /* magma_sstedx_m */
コード例 #18
0
ファイル: jacobi.cpp プロジェクト: CalebVDW/smr-motion
void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A,
   Matrix& V, bool eivec)
{
   Real epsilon = FloatingPointPrecision::Epsilon();
   Tracer et("Jacobi");
   REPORT
   int n = X.Nrows(); DiagonalMatrix B(n), Z(n); D.resize(n); A = X;
   if (eivec) { REPORT V.resize(n,n); D = 1.0; V = D; }
   B << A; D = B; Z = 0.0; A.Inject(Z);
   bool converged = false;
   for (int i=1; i<=50; i++)
   {
      Real sm=0.0; Real* a = A.Store(); int p = A.Storage();
      while (p--) sm += fabs(*a++);            // have previously zeroed diags
      if (sm==0.0) { REPORT converged = true; break; }
      Real tresh = (i<4) ? 0.2 * sm / square(n) : 0.0; a = A.Store();
      for (p = 0; p < n; p++)
      {
         Real* ap1 = a + (p*(p+1))/2;
         Real& zp = Z.element(p); Real& dp = D.element(p);
         for (int q = p+1; q < n; q++)
         {
            Real* ap = ap1; Real* aq = a + (q*(q+1))/2;
            Real& zq = Z.element(q); Real& dq = D.element(q);
            Real& apq = A.element(q,p);
            Real g = 100 * fabs(apq); Real adp = fabs(dp); Real adq = fabs(dq);

            if (i>4 && g < epsilon*adp && g < epsilon*adq) { REPORT apq = 0.0; }
            else if (fabs(apq) > tresh)
            {
               REPORT
               Real t; Real h = dq - dp; Real ah = fabs(h);
               if (g < epsilon*ah) { REPORT t = apq / h; }
               else
               {
                  REPORT
                  Real theta = 0.5 * h / apq;
                  t = 1.0 / ( fabs(theta) + sqrt(1.0 + square(theta)) );
                  if (theta<0.0) { REPORT t = -t; }
               }
               Real c = 1.0 / sqrt(1.0 + square(t)); Real s = t * c;
               Real tau = s / (1.0 + c); h = t * apq;
               zp -= h; zq += h; dp -= h; dq += h; apq = 0.0;
               int j = p;
               while (j--)
               {
                  g = *ap; h = *aq;
                  *ap++ = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau);
               }
               int ip = p+1; j = q-ip; ap += ip++; aq++;
               while (j--)
               {
                  g = *ap; h = *aq;
                  *ap = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau);
                  ap += ip++;
               }
               if (q < n-1)             // last loop is non-empty
               {
                  int iq = q+1; j = n-iq; ap += ip++; aq += iq++;
                  for (;;)
                  {
                     g = *ap; h = *aq;
                     *ap = g-s*(h+g*tau); *aq = h+s*(g-h*tau);
                     if (!(--j)) break;
                     ap += ip++; aq += iq++;
                  }
               }
               if (eivec)
               {
                  REPORT
                  RectMatrixCol VP(V,p); RectMatrixCol VQ(V,q);
                  Rotate(VP, VQ, tau, s);
               }
            }
         }
      }
      B = B + Z; D = B; Z = 0.0;
   }
   if (!converged) Throw(ConvergenceException(X));
   if (eivec) SortSV(D, V, true);
   else SortAscending(D);
}
コード例 #19
0
ファイル: regression.cpp プロジェクト: poulson/libskylark
 matrix_type materialize() const { matrix_type Z(_A); return Z; }
コード例 #20
0
void
showkre(void)
{
	float f1, f2;
	int psiz;
	int i, lc;
	long inttotal;
	long l;
	static int failcnt = 0;
	double total_time;

	etime = 0;
	CP_UPDATE(cp_time.cp_user);
	CP_UPDATE(cp_time.cp_nice);
	CP_UPDATE(cp_time.cp_sys);
	CP_UPDATE(cp_time.cp_intr);
	CP_UPDATE(cp_time.cp_idle);

	total_time = etime;
	if (total_time == 0.0)
		total_time = 1.0;

	if (etime < 100000.0) {	/* < 100ms ignore this trash */
		if (failcnt++ >= MAXFAIL) {
			clear();
			mvprintw(2, 10, "The alternate system clock has died!");
			mvprintw(3, 10, "Reverting to ``pigs'' display.");
			move(CMDLINE, 0);
			refresh();
			failcnt = 0;
			sleep(5);
			command("pigs");
		}
		return;
	}
	failcnt = 0;
	etime /= 1000000.0;
	etime /= ncpu;
	if (etime == 0)
		etime = 1;
	inttotal = 0;
	for (i = 0; i < nintr; i++) {
		if (s.intrcnt[i] == 0)
			continue;
		if (intrloc[i] == 0) {
			if (nextintsrow == LINES)
				continue;
			intrloc[i] = nextintsrow++;
			mvprintw(intrloc[i], INTSCOL + 9, "%-10.10s",
				intrname[i]);
		}
		X(intrcnt);
		l = (long)((float)s.intrcnt[i]/etime + 0.5);
		inttotal += l;
		put64(l, intrloc[i], INTSCOL + 2, 6, 'D');
	}
	put64(inttotal, INTSROW + 1, INTSCOL + 2, 6, 'D');
	Z(ncs_goodhits); Z(ncs_badhits); Z(ncs_miss);
	Z(ncs_longhits); Z(ncs_longmiss); Z(ncs_neghits);
	s.nchcount = nchtotal.ncs_goodhits + nchtotal.ncs_badhits +
	    nchtotal.ncs_miss + nchtotal.ncs_neghits;
	s.nchpathcount = nchtotal.ncs_longhits + nchtotal.ncs_longmiss;
	if (state == TIME) {
		s1.nchcount = s.nchcount;
		s1.nchpathcount = s.nchpathcount;
	}

	psiz = 0;
	f2 = 0.0;
	for (lc = 0; lc < CPUSTATES; lc++) {
		uint64_t val = *(uint64_t *)(((uint8_t *)&s.cp_time) +
		    cpuoffsets[lc]);
		f1 = 100.0 * val / total_time;
		f2 += f1;
		l = (int) ((f2 + 1.0) / 2.0) - psiz;
		if (f1 > 99.9)
			f1 = 99.9;	/* no room to display 100.0 */
		putfloat(f1, GRAPHROW, GRAPHCOL + 10 * lc, 4, 1, 0);
		move(GRAPHROW + 2, psiz);
		psiz += l;
		while (l-- > 0)
			addch(cpuchar[lc]);
	}

	put64(ucount(), STATROW, STATCOL, 3, 'D');
	putfloat(avenrun[0], STATROW, STATCOL + 18, 6, 2, 0);
	putfloat(avenrun[1], STATROW, STATCOL + 25, 6, 2, 0);
	putfloat(avenrun[2], STATROW, STATCOL + 32, 6, 2, 0);
	mvaddstr(STATROW, STATCOL + 53, buf);
#define pgtokb(pg) (int64_t)((intmax_t)(pg) * vms.v_page_size / 1024)
#define pgtomb(pg) (int64_t)((intmax_t)(pg) * vms.v_page_size / (1024 * 1024))
#define pgtob(pg)  (int64_t)((intmax_t)(pg) * vms.v_page_size)
	put64(pgtob(total.t_arm), MEMROW + 2, MEMCOL + 4, 6, 0);
	put64(pgtob(total.t_armshr), MEMROW + 2, MEMCOL + 11, 6, 0);
	put64(pgtob(total.t_avm), MEMROW + 2, MEMCOL + 19, 6, 0);
	put64(pgtob(total.t_avmshr), MEMROW + 2, MEMCOL + 26, 6, 0);
	put64(pgtob(total.t_rm), MEMROW + 3, MEMCOL + 4, 6, 0);
	put64(pgtob(total.t_rmshr), MEMROW + 3, MEMCOL + 11, 6, 0);
	put64(pgtob(total.t_vm), MEMROW + 3, MEMCOL + 19, 6, 0);
	put64(pgtob(total.t_vmshr), MEMROW + 3, MEMCOL + 26, 6, 0);
	put64(pgtob(total.t_free), MEMROW + 2, MEMCOL + 34, 6, 0);
	put64(total.t_rq - 1, PROCSROW + 1, PROCSCOL + 0, 3, 'D');
	put64(total.t_pw, PROCSROW + 1, PROCSCOL + 3, 3, 'D');
	put64(total.t_dw, PROCSROW + 1, PROCSCOL + 6, 3, 'D');
	put64(total.t_sl, PROCSROW + 1, PROCSCOL + 9, 3, 'D');
	put64(total.t_sw, PROCSROW + 1, PROCSCOL + 12, 3, 'D');
	if (extended_vm_stats == 0) {
		PUTRATE(Vmm.v_zfod, VMSTATROW + 0, VMSTATCOL, 7);
	}
	PUTRATE(Vmm.v_cow_faults, VMSTATROW + 1, VMSTATCOL, 7);
	put64(pgtob(vms.v_wire_count), VMSTATROW + 2, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_active_count), VMSTATROW + 3, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_inactive_count), VMSTATROW + 4, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_cache_count), VMSTATROW + 5, VMSTATCOL, 7, 0);
	put64(pgtob(vms.v_free_count), VMSTATROW + 6, VMSTATCOL, 7, 0);
	PUTRATE(Vmm.v_dfree, VMSTATROW + 7, VMSTATCOL, 7);
	PUTRATE(Vmm.v_pfree, VMSTATROW + 8, VMSTATCOL, 7);
	PUTRATE(Vmm.v_reactivated, VMSTATROW + 9, VMSTATCOL, 7);
	PUTRATE(Vmm.v_pdwakeups, VMSTATROW + 10, VMSTATCOL, 7);
	PUTRATE(Vmm.v_pdpages, VMSTATROW + 11, VMSTATCOL, 7);
	PUTRATE(Vmm.v_intrans, VMSTATROW + 12, VMSTATCOL, 7);

	if (extended_vm_stats) {
		PUTRATE(Vmm.v_zfod, VMSTATROW + 11, VMSTATCOL - 16, 9);
		PUTRATE(Vmm.v_ozfod, VMSTATROW + 12, VMSTATCOL - 16, 9);
#define nz(x)	((x) ? (x) : 1)
		put64((s.Vmm.v_zfod - s.Vmm.v_ozfod) * 100 / nz(s.Vmm.v_zfod),
		    VMSTATROW + 13, VMSTATCOL - 16, 9, 'D');
#undef nz
		PUTRATE(Vmm.v_tfree, VMSTATROW + 14, VMSTATCOL - 16, 9);
	}

	put64(s.bufspace, VMSTATROW + 13, VMSTATCOL, 7, 0);
	put64(s.dirtybufspace/1024, VMSTATROW + 14, VMSTATCOL, 7, 'k');
	put64(s.desiredvnodes, VMSTATROW + 15, VMSTATCOL, 7, 'D');
	put64(s.numvnodes, VMSTATROW + 16, VMSTATCOL, 7, 'D');
	put64(s.freevnodes, VMSTATROW + 17, VMSTATCOL, 7, 'D');
	PUTRATE(Vmm.v_vnodein, PAGEROW + 2, PAGECOL + 6, 4);
	PUTRATE(Vmm.v_vnodeout, PAGEROW + 2, PAGECOL + 11, 4);
	PUTRATE(Vmm.v_swapin, PAGEROW + 2, PAGECOL + 18, 4);
	PUTRATE(Vmm.v_swapout, PAGEROW + 2, PAGECOL + 23, 4);
	PUTRATE(Vmm.v_vnodepgsin, PAGEROW + 3, PAGECOL + 6, 4);
	PUTRATE(Vmm.v_vnodepgsout, PAGEROW + 3, PAGECOL + 11, 4);
	PUTRATE(Vmm.v_swappgsin, PAGEROW + 3, PAGECOL + 18, 4);
	PUTRATE(Vmm.v_swappgsout, PAGEROW + 3, PAGECOL + 23, 4);
	PUTRATE(Vmm.v_swtch, GENSTATROW + 1, GENSTATCOL + 1, 4);
	PUTRATE(Vmm.v_trap, GENSTATROW + 1, GENSTATCOL + 6, 4);
	PUTRATE(Vmm.v_syscall, GENSTATROW + 1, GENSTATCOL + 11, 4);
	PUTRATE(Vmm.v_intr, GENSTATROW + 1, GENSTATCOL + 16, 4);
	PUTRATE(Vmm.v_soft, GENSTATROW + 1, GENSTATCOL + 21, 4);
	PUTRATE(Vmm.v_vm_faults, GENSTATROW + 1, GENSTATCOL + 26, 4);
	mvprintw(DISKROW, DISKCOL + 5, "                              ");
	for (i = 0, lc = 0; i < num_devices && lc < MAXDRIVES; i++)
		if (dev_select[i].selected) {
			char tmpstr[80];
			sprintf(tmpstr, "%s%d", dev_select[i].device_name,
				dev_select[i].unit_number);
			mvprintw(DISKROW, DISKCOL + 5 + 6 * lc,
				" %5.5s", tmpstr);
			switch(state) {
			case TIME:
				dinfo(i, ++lc, &cur, &last);
				break;
			case RUN:
				dinfo(i, ++lc, &cur, &run);
				break;
			case BOOT:
				dinfo(i, ++lc, &cur, NULL);
				break;
			}
		}
#define nz(x)	((x) ? (x) : 1)
	put64(s.nchpathcount, NAMEIROW + 1, NAMEICOL + 6, 6, 'D');
	put64(nchtotal.ncs_longhits, NAMEIROW + 1, NAMEICOL + 13, 6, 'D');
	putfloat(nchtotal.ncs_longhits * 100.0 / nz(s.nchpathcount),
	    NAMEIROW + 1, NAMEICOL + 19, 4, 0, 0);

	putfloat((double)s.nchcount / nz(s.nchpathcount),
	    NAMEIROW + 1, NAMEICOL + 27, 5, 2, 1);
#undef nz
}
コード例 #21
0
void MpViewArray2dEval::Accept (void)
{
    // check if data set is available
    int set = SetSelect->GetValue();
    if (!data->DataSetExists(set) ||
            !data->DS(set).isMatrix()) {
        MpViewDisplay::Message("No 2d matrix data are available");
        return;
    }

    // reference data matrix
    Matrix &Z = data->DS(set).MatrixData();

    int RLO = Z.Rlo(), RHI = Z.Rhi(),
        CLO = Z.Clo(), CHI = Z.Chi(),
        rlo,rhi,clo,chi;

    // get index range and check it
    if ( ! IndRow1->Get(rlo) || ! IndRow2->Get(rhi) ||
            ! IndCol1->Get(clo) || ! IndCol2->Get(chi) ||
            rlo > rhi || clo > chi ||
            rlo < RLO || rhi > RHI ||
            clo < CLO || chi > CHI) {
        MpViewDisplay::Message("Index Range: Expected integer indices within matrix range");
        return;
    }

    // get variable range
    double x1,x2,y1,y2;
    if ( ! VarX1->Get(x1) || ! VarX2->Get(x2) ||
            ! VarY1->Get(y1) || ! VarY2->Get(y2) ) {
        MpViewDisplay::Message("Variable Range: Expected real values");
        return;
    }

    // inform user
    disp->SetWaitCursor();

    char expression[512];
    string error;

    double xinc = (rhi-rlo) ? (x2-x1)/(rhi-rlo) : 0,
           yinc = (chi-clo) ? (y2-y1)/(chi-clo) : 0;

    for (int r = rlo; r <= rhi; r++) {
        double x = x1 + (r-rlo) * xinc;

        for (int c = clo; c <= chi; c++) {
            double y = y1 + (c-clo) * yinc;

            // set x, y, current z-value, and expression
            sprintf(expression,"x=%.15g; y=%.15g; z=%.15g; %s",
                    x, y, Z(r,c), Formula->Get().c_str());

            // evaluate the expressions
            double value = disp->Numex->EvalNumex(expression,error);
            if (error.size()) {
                MpViewDisplay::Message(error);
                goto failure;
            }

            // set matrix element to return value
            Z(r,c) = value;
        }
    }

    // reset defaults for all graphs linking this set
    data->NewDataSet(set,-1);

failure:

    disp->UnsetWaitCursor();

    data->DS(set).SetModified();

    // finally always call method of base class
    MpViewPanel::Accept();
}
コード例 #22
0
Ref SateliteCam::GetRef()
{
	Point3D Y(0,1,0);
	Point3D Z(0,0,1);
	return Ref(m_Vehicle->MyRef.Position+Z*m_height,Z*(-1.f)+Y*.001f,m_Vehicle->MyRef.GetDirection());
}
コード例 #23
0
ファイル: bin_elf64.c プロジェクト: Ekleog/radare2
static RBuffer* create(RBin* bin, const ut8 *code, int codelen, const ut8 *data, int datalen) {
	ut32 p_start, p_phoff, p_phdr;
	ut32 p_vaddr, p_paddr, p_fs, p_fs2;
	ut32 p_ehdrsz, p_phdrsz;
	ut64 filesize, code_va, code_pa, phoff;
	ut16 ehdrsz, phdrsz;
	ut64 baddr = 0x400000LL;
	RBuffer *buf = r_buf_new ();

#define B(x,y) r_buf_append_bytes(buf,(const ut8*)x,y)
#define Q(x) r_buf_append_ut64(buf,x)
#define D(x) r_buf_append_ut32(buf,x)
#define H(x) r_buf_append_ut16(buf,x)
#define Z(x) r_buf_append_nbytes(buf,x)
#define W(x,y,z) r_buf_write_at(buf,x,(const ut8*)y,z)

	/* Ehdr */
	B ("\x7F" "ELF" "\x02\x01\x01\x00", 8); // e_ident (ei_class = ELFCLASS64)
	Z (8);
	H (2); // e_type = ET_EXEC
	H (62); // e_machine = EM_X86_64
	D (1); // e_version = EV_CURRENT
	p_start = buf->length;
	Q (-1); // e_entry = 0xFFFFFFFF
	p_phoff = buf->length;
	Q (-1); // e_phoff = 0xFFFFFFFF
	Q (0);  // e_shoff = 0xFFFFFFFF
	D (0);  // e_flags
	p_ehdrsz = buf->length;
	H (-1); // e_ehsize = 0xFFFFFFFF
	p_phdrsz = buf->length;
	H (-1); // e_phentsize = 0xFFFFFFFF
	H (1);  // e_phnum
	H (0);  // e_shentsize
	H (0);  // e_shnum
	H (0);  // e_shstrndx

	/* Phdr */
	p_phdr = buf->length;
	D (1);  // p_type
	D (5);  // p_flags = PF_R | PF_X
	Q (0);  // p_offset 
	p_vaddr = buf->length;
	Q (-1); // p_vaddr = 0xFFFFFFFF
	p_paddr = buf->length;
	Q (-1); // p_paddr = 0xFFFFFFFF
	p_fs = buf->length;
	Q (-1); // p_filesz
	p_fs2 = buf->length;
	Q (-1); // p_memsz
	Q (0x200000); // p_align

	/* Calc fields */
	ehdrsz = p_phdr;
	phdrsz = buf->length - p_phdr;
	code_pa = buf->length;
	code_va = code_pa + baddr;
	phoff = p_phdr;
	filesize = code_pa + codelen + datalen;

	/* Write fields */
	W (p_start, &code_va, 8);
	W (p_phoff, &phoff, 8);
	W (p_ehdrsz, &ehdrsz, 2);
	W (p_phdrsz, &phdrsz, 2);
	W (p_fs, &filesize, 8);
	W (p_fs2, &filesize, 8);

	W (p_vaddr, &baddr, 8);
	W (p_paddr, &baddr, 8);

	/* Append code */
	B (code, codelen);

	if (data && datalen>0) {
		eprintf ("Warning: DATA section not support for ELF yet\n");
		B (data, datalen);
	}
	return buf;
}
コード例 #24
0
int
main( int argc, char* argv[] )
{
    El::Environment env( argc, argv );
    El::mpi::Comm comm = El::mpi::COMM_WORLD;
    const int commRank = El::mpi::Rank( comm );
    const int commSize = El::mpi::Size( comm );

    try
    {
        typedef double Real;
        typedef El::Complex<Real> Scalar;

        const char trans = El::Input("--trans","orientation",'N');
        const El::Int m = El::Input("--height","height of matrix",100);
        const El::Int n = El::Input("--width","width of matrix",100);
        const El::Int numRhs = El::Input("--numRhs","# of right-hand sides",1);
        const El::Int blocksize =
          El::Input("--blocksize","algorithmic blocksize",64);
        El::Int gridHeight = El::Input("--gridHeight","grid height",0);
        El::ProcessInput();
        El::PrintInputReport();

        const El::Orientation orientation = El::CharToOrientation( trans );

        // Set the algorithmic blocksize
        El::SetBlocksize( blocksize );

        // If the grid height wasn't specified, then we should attempt to build
        // a nearly-square process grid
        if( gridHeight == 0 )
            gridHeight = El::Grid::FindFactor( commSize );
        const El::Grid grid( comm, gridHeight );

        // Set up random A and B, then make the copy X := B
        El::DistMatrix<Scalar> A(grid), B(grid), X(grid), Z(grid);
        for( El::Int test=0; test<3; ++test )
        {
            const El::Int k = orientation==El::NORMAL ? m : n;
            const El::Int N = orientation==El::NORMAL ? n : m;
            El::Uniform( A, m, n );
            El::Zeros( B, k, numRhs );

            // Form B in the range of op(A)
            El::Uniform( Z, N, numRhs );
            El::Gemm( orientation, El::NORMAL, Scalar(1), A, Z, Scalar(0), B );

            // Perform the QR/LQ factorization and solve
            if( commRank == 0 )
                El::Output("Starting LeastSquares...");
            El::mpi::Barrier( comm );
            double startTime = El::mpi::Time();
            El::LeastSquares( orientation, A, B, X );
            El::mpi::Barrier();
            double stopTime = El::mpi::Time();
            if( commRank == 0 )
                El::Output(stopTime-startTime," seconds.");

            // Form R := op(A) X - B
            El::DistMatrix<Scalar> R( B );
            El::Gemm( orientation, El::NORMAL, Scalar(1), A, X, Scalar(-1), R );

            // Compute the relevant Frobenius norms and a relative residual
            const Real eps = El::limits::Epsilon<Real>();
            const Real AFrobNorm = El::FrobeniusNorm( A );
            const Real BFrobNorm = El::FrobeniusNorm( B );
            const Real XFrobNorm = El::FrobeniusNorm( X );
            const Real RFrobNorm = El::FrobeniusNorm( R );
            const Real frobResidual = RFrobNorm / (AFrobNorm*XFrobNorm*eps*n);
            if( commRank == 0 )
                El::Output
                ("|| A ||_F       = ",AFrobNorm,"\n",
                 "|| B ||_F       = ",BFrobNorm,"\n",
                 "|| X ||_F       = ",XFrobNorm,"\n",
                 "|| A X - B ||_F = ",RFrobNorm,"\n",
                 "|| op(A) X - B ||_F / (|| A ||_F || X ||_F eps n) = ",
                 frobResidual,"\n");
        }
    }
    catch( std::exception& e ) { El::ReportException(e); }

    return 0;
}
コード例 #25
0
ファイル: dhseqr.c プロジェクト: deepakantony/vispack
/* Subroutine */ int dhseqr_(char *job, char *compz, integer *n, integer *ilo,
	 integer *ihi, doublereal *h, integer *ldh, doublereal *wr, 
	doublereal *wi, doublereal *z, integer *ldz, doublereal *work, 
	integer *lwork, integer *info)
{
/*  -- LAPACK routine (version 2.0) --   
       Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,   
       Courant Institute, Argonne National Lab, and Rice University   
       September 30, 1994   


    Purpose   
    =======   

    DHSEQR computes the eigenvalues of a real upper Hessenberg matrix H   
    and, optionally, the matrices T and Z from the Schur decomposition   
    H = Z T Z**T, where T is an upper quasi-triangular matrix (the Schur 
  
    form), and Z is the orthogonal matrix of Schur vectors.   

    Optionally Z may be postmultiplied into an input orthogonal matrix Q, 
  
    so that this routine can give the Schur factorization of a matrix A   
    which has been reduced to the Hessenberg form H by the orthogonal   
    matrix Q:  A = Q*H*Q**T = (QZ)*T*(QZ)**T.   

    Arguments   
    =========   

    JOB     (input) CHARACTER*1   
            = 'E':  compute eigenvalues only;   
            = 'S':  compute eigenvalues and the Schur form T.   

    COMPZ   (input) CHARACTER*1   
            = 'N':  no Schur vectors are computed;   
            = 'I':  Z is initialized to the unit matrix and the matrix Z 
  
                    of Schur vectors of H is returned;   
            = 'V':  Z must contain an orthogonal matrix Q on entry, and   
                    the product Q*Z is returned.   

    N       (input) INTEGER   
            The order of the matrix H.  N >= 0.   

    ILO     (input) INTEGER   
    IHI     (input) INTEGER   
            It is assumed that H is already upper triangular in rows   
            and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally   
            set by a previous call to DGEBAL, and then passed to SGEHRD   
            when the matrix output by DGEBAL is reduced to Hessenberg   
            form. Otherwise ILO and IHI should be set to 1 and N   
            respectively.   
            1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0.   

    H       (input/output) DOUBLE PRECISION array, dimension (LDH,N)   
            On entry, the upper Hessenberg matrix H.   
            On exit, if JOB = 'S', H contains the upper quasi-triangular 
  
            matrix T from the Schur decomposition (the Schur form);   
            2-by-2 diagonal blocks (corresponding to complex conjugate   
            pairs of eigenvalues) are returned in standard form, with   
            H(i,i) = H(i+1,i+1) and H(i+1,i)*H(i,i+1) < 0. If JOB = 'E', 
  
            the contents of H are unspecified on exit.   

    LDH     (input) INTEGER   
            The leading dimension of the array H. LDH >= max(1,N).   

    WR      (output) DOUBLE PRECISION array, dimension (N)   
    WI      (output) DOUBLE PRECISION array, dimension (N)   
            The real and imaginary parts, respectively, of the computed   
            eigenvalues. If two eigenvalues are computed as a complex   
            conjugate pair, they are stored in consecutive elements of   
            WR and WI, say the i-th and (i+1)th, with WI(i) > 0 and   
            WI(i+1) < 0. If JOB = 'S', the eigenvalues are stored in the 
  
            same order as on the diagonal of the Schur form returned in   
            H, with WR(i) = H(i,i) and, if H(i:i+1,i:i+1) is a 2-by-2   
            diagonal block, WI(i) = sqrt(H(i+1,i)*H(i,i+1)) and   
            WI(i+1) = -WI(i).   

    Z       (input/output) DOUBLE PRECISION array, dimension (LDZ,N)   
            If COMPZ = 'N': Z is not referenced.   
            If COMPZ = 'I': on entry, Z need not be set, and on exit, Z   
            contains the orthogonal matrix Z of the Schur vectors of H.   
            If COMPZ = 'V': on entry Z must contain an N-by-N matrix Q,   
            which is assumed to be equal to the unit matrix except for   
            the submatrix Z(ILO:IHI,ILO:IHI); on exit Z contains Q*Z.   
            Normally Q is the orthogonal matrix generated by DORGHR after 
  
            the call to DGEHRD which formed the Hessenberg matrix H.   

    LDZ     (input) INTEGER   
            The leading dimension of the array Z.   
            LDZ >= max(1,N) if COMPZ = 'I' or 'V'; LDZ >= 1 otherwise.   

    WORK    (workspace) DOUBLE PRECISION array, dimension (N)   

    LWORK   (input) INTEGER   
            This argument is currently redundant.   

    INFO    (output) INTEGER   
            = 0:  successful exit   
            < 0:  if INFO = -i, the i-th argument had an illegal value   
            > 0:  if INFO = i, DHSEQR failed to compute all of the   
                  eigenvalues in a total of 30*(IHI-ILO+1) iterations;   
                  elements 1:ilo-1 and i+1:n of WR and WI contain those   
                  eigenvalues which have been successfully computed.   

    ===================================================================== 
  


       Decode and test the input parameters   

    
   Parameter adjustments   
       Function Body */
    /* Table of constant values */
    static doublereal c_b9 = 0.;
    static doublereal c_b10 = 1.;
    static integer c__4 = 4;
    static integer c_n1 = -1;
    static integer c__2 = 2;
    static integer c__8 = 8;
    static integer c__15 = 15;
    static logical c_false = FALSE_;
    static integer c__1 = 1;
    
    /* System generated locals */
    address a__1[2];
    integer h_dim1, h_offset, z_dim1, z_offset, i__1, i__2, i__3[2], i__4, 
	    i__5;
    doublereal d__1, d__2;
    char ch__1[2];
    /* Builtin functions   
       Subroutine */ int s_cat(char *, char **, integer *, integer *, ftnlen);
    /* Local variables */
    static integer maxb;
    static doublereal absw;
    static integer ierr;
    static doublereal unfl, temp, ovfl;
    static integer i, j, k, l;
    static doublereal s[225]	/* was [15][15] */, v[16];
    extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, 
	    integer *);
    extern logical lsame_(char *, char *);
    extern /* Subroutine */ int dgemv_(char *, integer *, integer *, 
	    doublereal *, doublereal *, integer *, doublereal *, integer *, 
	    doublereal *, doublereal *, integer *);
    static integer itemp;
    extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, 
	    doublereal *, integer *);
    static integer i1, i2;
    static logical initz, wantt, wantz;
    extern doublereal dlapy2_(doublereal *, doublereal *);
    extern /* Subroutine */ int dlabad_(doublereal *, doublereal *);
    static integer ii, nh;
    extern doublereal dlamch_(char *);
    extern /* Subroutine */ int dlarfg_(integer *, doublereal *, doublereal *,
	     integer *, doublereal *);
    static integer nr, ns;
    extern integer idamax_(integer *, doublereal *, integer *);
    static integer nv;
    extern doublereal dlanhs_(char *, integer *, doublereal *, integer *, 
	    doublereal *);
    extern /* Subroutine */ int dlahqr_(logical *, logical *, integer *, 
	    integer *, integer *, doublereal *, integer *, doublereal *, 
	    doublereal *, integer *, integer *, doublereal *, integer *, 
	    integer *);
    static doublereal vv[16];
    extern /* Subroutine */ int dlacpy_(char *, integer *, integer *, 
	    doublereal *, integer *, doublereal *, integer *);
    extern integer ilaenv_(integer *, char *, char *, integer *, integer *, 
	    integer *, integer *, ftnlen, ftnlen);
    extern /* Subroutine */ int dlaset_(char *, integer *, integer *, 
	    doublereal *, doublereal *, doublereal *, integer *), 
	    dlarfx_(char *, integer *, integer *, doublereal *, doublereal *, 
	    doublereal *, integer *, doublereal *), xerbla_(char *, 
	    integer *);
    static doublereal smlnum;
    static integer itn;
    static doublereal tau;
    static integer its;
    static doublereal ulp, tst1;



#define S(I) s[(I)]
#define WAS(I) was[(I)]
#define V(I) v[(I)]
#define VV(I) vv[(I)]
#define WR(I) wr[(I)-1]
#define WI(I) wi[(I)-1]
#define WORK(I) work[(I)-1]

#define H(I,J) h[(I)-1 + ((J)-1)* ( *ldh)]
#define Z(I,J) z[(I)-1 + ((J)-1)* ( *ldz)]

    wantt = lsame_(job, "S");
    initz = lsame_(compz, "I");
    wantz = initz || lsame_(compz, "V");

    *info = 0;
    if (! lsame_(job, "E") && ! wantt) {
	*info = -1;
    } else if (! lsame_(compz, "N") && ! wantz) {
	*info = -2;
    } else if (*n < 0) {
	*info = -3;
    } else if (*ilo < 1 || *ilo > max(1,*n)) {
	*info = -4;
    } else if (*ihi < min(*ilo,*n) || *ihi > *n) {
	*info = -5;
    } else if (*ldh < max(1,*n)) {
	*info = -7;
    } else if (*ldz < 1 || wantz && *ldz < max(1,*n)) {
	*info = -11;
    }
    if (*info != 0) {
	i__1 = -(*info);
	xerbla_("DHSEQR", &i__1);
	return 0;
    }

/*     Initialize Z, if necessary */

    if (initz) {
	dlaset_("Full", n, n, &c_b9, &c_b10, &Z(1,1), ldz);
    }

/*     Store the eigenvalues isolated by DGEBAL. */

    i__1 = *ilo - 1;
    for (i = 1; i <= *ilo-1; ++i) {
	WR(i) = H(i,i);
	WI(i) = 0.;
/* L10: */
    }
    i__1 = *n;
    for (i = *ihi + 1; i <= *n; ++i) {
	WR(i) = H(i,i);
	WI(i) = 0.;
/* L20: */
    }

/*     Quick return if possible. */

    if (*n == 0) {
	return 0;
    }
    if (*ilo == *ihi) {
	WR(*ilo) = H(*ilo,*ilo);
	WI(*ilo) = 0.;
	return 0;
    }

/*     Set rows and columns ILO to IHI to zero below the first   
       subdiagonal. */

    i__1 = *ihi - 2;
    for (j = *ilo; j <= *ihi-2; ++j) {
	i__2 = *n;
	for (i = j + 2; i <= *n; ++i) {
	    H(i,j) = 0.;
/* L30: */
	}
/* L40: */
    }
    nh = *ihi - *ilo + 1;

/*     Determine the order of the multi-shift QR algorithm to be used.   

   Writing concatenation */
    i__3[0] = 1, a__1[0] = job;
    i__3[1] = 1, a__1[1] = compz;
    s_cat(ch__1, a__1, i__3, &c__2, 2L);
    ns = ilaenv_(&c__4, "DHSEQR", ch__1, n, ilo, ihi, &c_n1, 6L, 2L);
/* Writing concatenation */
    i__3[0] = 1, a__1[0] = job;
    i__3[1] = 1, a__1[1] = compz;
    s_cat(ch__1, a__1, i__3, &c__2, 2L);
    maxb = ilaenv_(&c__8, "DHSEQR", ch__1, n, ilo, ihi, &c_n1, 6L, 2L);
    if (ns <= 2 || ns > nh || maxb >= nh) {

/*        Use the standard double-shift algorithm */

	dlahqr_(&wantt, &wantz, n, ilo, ihi, &H(1,1), ldh, &WR(1), &WI(1)
		, ilo, ihi, &Z(1,1), ldz, info);
	return 0;
    }
    maxb = max(3,maxb);
/* Computing MIN */
    i__1 = min(ns,maxb);
    ns = min(i__1,15);

/*     Now 2 < NS <= MAXB < NH.   

       Set machine-dependent constants for the stopping criterion.   
       If norm(H) <= sqrt(OVFL), overflow should not occur. */

    unfl = dlamch_("Safe minimum");
    ovfl = 1. / unfl;
    dlabad_(&unfl, &ovfl);
    ulp = dlamch_("Precision");
    smlnum = unfl * (nh / ulp);

/*     I1 and I2 are the indices of the first row and last column of H   
       to which transformations must be applied. If eigenvalues only are 
  
       being computed, I1 and I2 are set inside the main loop. */

    if (wantt) {
	i1 = 1;
	i2 = *n;
    }

/*     ITN is the total number of multiple-shift QR iterations allowed. */

    itn = nh * 30;

/*     The main loop begins here. I is the loop index and decreases from 
  
       IHI to ILO in steps of at most MAXB. Each iteration of the loop   
       works with the active submatrix in rows and columns L to I.   
       Eigenvalues I+1 to IHI have already converged. Either L = ILO or   
       H(L,L-1) is negligible so that the matrix splits. */

    i = *ihi;
L50:
    l = *ilo;
    if (i < *ilo) {
	goto L170;
    }

/*     Perform multiple-shift QR iterations on rows and columns ILO to I 
  
       until a submatrix of order at most MAXB splits off at the bottom   
       because a subdiagonal element has become negligible. */

    i__1 = itn;
    for (its = 0; its <= itn; ++its) {

/*        Look for a single small subdiagonal element. */

	i__2 = l + 1;
	for (k = i; k >= l+1; --k) {
	    tst1 = (d__1 = H(k-1,k-1), abs(d__1)) + (d__2 = 
		    H(k,k), abs(d__2));
	    if (tst1 == 0.) {
		i__4 = i - l + 1;
		tst1 = dlanhs_("1", &i__4, &H(l,l), ldh, &WORK(1));
	    }
/* Computing MAX */
	    d__2 = ulp * tst1;
	    if ((d__1 = H(k,k-1), abs(d__1)) <= max(d__2,
		    smlnum)) {
		goto L70;
	    }
/* L60: */
	}
L70:
	l = k;
	if (l > *ilo) {

/*           H(L,L-1) is negligible. */

	    H(l,l-1) = 0.;
	}

/*        Exit from loop if a submatrix of order <= MAXB has split off
. */

	if (l >= i - maxb + 1) {
	    goto L160;
	}

/*        Now the active submatrix is in rows and columns L to I. If 
  
          eigenvalues only are being computed, only the active submatr
ix   
          need be transformed. */

	if (! wantt) {
	    i1 = l;
	    i2 = i;
	}

	if (its == 20 || its == 30) {

/*           Exceptional shifts. */

	    i__2 = i;
	    for (ii = i - ns + 1; ii <= i; ++ii) {
		WR(ii) = ((d__1 = H(ii,ii-1), abs(d__1)) + (
			d__2 = H(ii,ii), abs(d__2))) * 1.5;
		WI(ii) = 0.;
/* L80: */
	    }
	} else {

/*           Use eigenvalues of trailing submatrix of order NS as 
shifts. */

	    dlacpy_("Full", &ns, &ns, &H(i-ns+1,i-ns+1), 
		    ldh, s, &c__15);
	    dlahqr_(&c_false, &c_false, &ns, &c__1, &ns, s, &c__15, &WR(i - 
		    ns + 1), &WI(i - ns + 1), &c__1, &ns, &Z(1,1), ldz, &
		    ierr);
	    if (ierr > 0) {

/*              If DLAHQR failed to compute all NS eigenvalues
, use the   
                unconverged diagonal elements as the remaining
 shifts. */

		i__2 = ierr;
		for (ii = 1; ii <= ierr; ++ii) {
		    WR(i - ns + ii) = S(ii + ii * 15 - 16);
		    WI(i - ns + ii) = 0.;
/* L90: */
		}
	    }
	}

/*        Form the first column of (G-w(1)) (G-w(2)) . . . (G-w(ns)) 
  
          where G is the Hessenberg submatrix H(L:I,L:I) and w is   
          the vector of shifts (stored in WR and WI). The result is   
          stored in the local array V. */

	V(0) = 1.;
	i__2 = ns + 1;
	for (ii = 2; ii <= ns+1; ++ii) {
	    V(ii - 1) = 0.;
/* L100: */
	}
	nv = 1;
	i__2 = i;
	for (j = i - ns + 1; j <= i; ++j) {
	    if (WI(j) >= 0.) {
		if (WI(j) == 0.) {

/*                 real shift */

		    i__4 = nv + 1;
		    dcopy_(&i__4, v, &c__1, vv, &c__1);
		    i__4 = nv + 1;
		    d__1 = -WR(j);
		    dgemv_("No transpose", &i__4, &nv, &c_b10, &H(l,l), ldh, vv, &c__1, &d__1, v, &c__1);
		    ++nv;
		} else if (WI(j) > 0.) {

/*                 complex conjugate pair of shifts */

		    i__4 = nv + 1;
		    dcopy_(&i__4, v, &c__1, vv, &c__1);
		    i__4 = nv + 1;
		    d__1 = WR(j) * -2.;
		    dgemv_("No transpose", &i__4, &nv, &c_b10, &H(l,l), ldh, v, &c__1, &d__1, vv, &c__1);
		    i__4 = nv + 1;
		    itemp = idamax_(&i__4, vv, &c__1);
/* Computing MAX */
		    d__2 = (d__1 = VV(itemp - 1), abs(d__1));
		    temp = 1. / max(d__2,smlnum);
		    i__4 = nv + 1;
		    dscal_(&i__4, &temp, vv, &c__1);
		    absw = dlapy2_(&WR(j), &WI(j));
		    temp = temp * absw * absw;
		    i__4 = nv + 2;
		    i__5 = nv + 1;
		    dgemv_("No transpose", &i__4, &i__5, &c_b10, &H(l,l), ldh, vv, &c__1, &temp, v, &c__1);
		    nv += 2;
		}

/*              Scale V(1:NV) so that max(abs(V(i))) = 1. If V
 is zero,   
                reset it to the unit vector. */

		itemp = idamax_(&nv, v, &c__1);
		temp = (d__1 = V(itemp - 1), abs(d__1));
		if (temp == 0.) {
		    V(0) = 1.;
		    i__4 = nv;
		    for (ii = 2; ii <= nv; ++ii) {
			V(ii - 1) = 0.;
/* L110: */
		    }
		} else {
		    temp = max(temp,smlnum);
		    d__1 = 1. / temp;
		    dscal_(&nv, &d__1, v, &c__1);
		}
	    }
/* L120: */
	}

/*        Multiple-shift QR step */

	i__2 = i - 1;
	for (k = l; k <= i-1; ++k) {

/*           The first iteration of this loop determines a reflect
ion G   
             from the vector V and applies it from left and right 
to H,   
             thus creating a nonzero bulge below the subdiagonal. 
  

             Each subsequent iteration determines a reflection G t
o   
             restore the Hessenberg form in the (K-1)th column, an
d thus   
             chases the bulge one step toward the bottom of the ac
tive   
             submatrix. NR is the order of G.   

   Computing MIN */
	    i__4 = ns + 1, i__5 = i - k + 1;
	    nr = min(i__4,i__5);
	    if (k > l) {
		dcopy_(&nr, &H(k,k-1), &c__1, v, &c__1);
	    }
	    dlarfg_(&nr, v, &V(1), &c__1, &tau);
	    if (k > l) {
		H(k,k-1) = V(0);
		i__4 = i;
		for (ii = k + 1; ii <= i; ++ii) {
		    H(ii,k-1) = 0.;
/* L130: */
		}
	    }
	    V(0) = 1.;

/*           Apply G from the left to transform the rows of the ma
trix in   
             columns K to I2. */

	    i__4 = i2 - k + 1;
	    dlarfx_("Left", &nr, &i__4, v, &tau, &H(k,k), ldh, &
		    WORK(1));

/*           Apply G from the right to transform the columns of th
e   
             matrix in rows I1 to min(K+NR,I).   

   Computing MIN */
	    i__5 = k + nr;
	    i__4 = min(i__5,i) - i1 + 1;
	    dlarfx_("Right", &i__4, &nr, v, &tau, &H(i1,k), ldh, &
		    WORK(1));

	    if (wantz) {

/*              Accumulate transformations in the matrix Z */

		dlarfx_("Right", &nh, &nr, v, &tau, &Z(*ilo,k), 
			ldz, &WORK(1));
	    }
/* L140: */
	}

/* L150: */
    }

/*     Failure to converge in remaining number of iterations */

    *info = i;
    return 0;

L160:

/*     A submatrix of order <= MAXB in rows and columns L to I has split 
  
       off. Use the double-shift QR algorithm to handle it. */

    dlahqr_(&wantt, &wantz, n, &l, &i, &H(1,1), ldh, &WR(1), &WI(1), ilo,
	     ihi, &Z(1,1), ldz, info);
    if (*info > 0) {
	return 0;
    }

/*     Decrement number of remaining iterations, and return to start of   
       the main loop with a new value of I. */

    itn -= its;
    i = l - 1;
    goto L50;

L170:
    return 0;

/*     End of DHSEQR */

} /* dhseqr_ */
コード例 #26
0
// Move the viewer and swap blocks as needed (X North, Y East, Z Down)
void TViewPoint::Update(const Tpoint *position )
{
    float	altAGL;
    int		level;

    // Lock everyone else out of this viewpoint while it is being updated
    EnterCriticalSection( &cs_update );

    // JB 010608 for weather effects start
    static unsigned long prevvuxGameTime;
    if (vuxGameTime != prevvuxGameTime) {
        float dist =
            (float)sqrt(((pos.x - position->x)*(pos.x - position->x) + (pos.y - position->y)*(pos.y - position->y)));
        dist = sqrt(dist * dist + (pos.z - position->z)*(pos.z - position->z));
        Speed = dist * FT_TO_NM / ((vuxGameTime - prevvuxGameTime) / (3600000.0F));
        prevvuxGameTime = vuxGameTime;
    }
    // JB 010608 for weather effects end

    // Store the viewer's position
    pos = *position;

    // Ask the list at each level to do any required flushing and/or prefetching of blocks
    for (level=maxLOD; level>=minLOD; level--) {
        blockLists[level].Update( X(), Y() );
    }

    // TODO:  FIX THIS CRITICAL SECTION STUFF (NO NESTING!!!)
    LeaveCriticalSection( &cs_update );

    // Figure out the viewer's height above the terrain
    // At this point convert from Z down to positive altitude up so
    // that the following conditional tree is less confusing
    altAGL = GetGroundLevelApproximation( X(), Y() ) - Z();

    // TODO:  FIX THIS CRITICAL SECTION STUFF (NO NESTING!!!)
    EnterCriticalSection( &cs_update );

    // Adjust the range of active LODs based on altitude
    // (THW: In a perfect world, we would also look at FOV and Screen Res...)
    // THW 2003-11-14 Let's be a bit more generous...this isn't 1998 anymore ;-)
    //THW 2003-11-14 Make it configurable
    if ( altAGL < (500.0f * g_fTexDetailFactor)) {
        highDetail	= minLOD;
        lowDetail	= maxLOD-g_nLowDetailFactor;
    }
    else if ( altAGL < (6000.0f * g_fTexDetailFactor)) {
        highDetail	= minLOD;
        lowDetail	= maxLOD;
    }
    else if ( altAGL < (24000.0f * g_fTexDetailFactor)) {
        highDetail	= minLOD+1;
        lowDetail	= maxLOD;
    }
    else if ( altAGL < (36000.0f * g_fTexDetailFactor)) {
        highDetail	= minLOD+2;
        lowDetail	= maxLOD;
    }
    else {
        if (g_bDisableHighFartiles) {
            highDetail = minLOD+2;
        }
        else {
            highDetail = minLOD+3;
        }
        lowDetail	= maxLOD;
    }

    // Clamp the values to the avialable range of LODs
    if ( lowDetail  < minLOD )		lowDetail	= minLOD;
    if ( lowDetail  > maxLOD )		lowDetail	= maxLOD;
    if ( highDetail > lowDetail )	highDetail	= lowDetail;
    if ( highDetail < minLOD )		highDetail	= minLOD;

    // Unlock the viewpoint so others can query it
    LeaveCriticalSection( &cs_update );
}
コード例 #27
0
ファイル: addrinfo-test.c プロジェクト: Akasurde/krb5
int main (int argc, char *argv[])
{
    struct addrinfo *ap, *ap2;
    int err, numerichost = 0, numericserv = 0;
    char *hname, *port = 0, *sep;
    struct addrinfo hints;

    whoami = strrchr(argv[0], '/');
    if (whoami == 0)
        whoami = argv[0];
    else
        whoami = whoami+1;

    memset(&hints, 0, sizeof(hints));
    hints.ai_flags = 0;
    hints.ai_socktype = 0;

    hname = 0;
    hints.ai_family = 0;

    if (argc == 1)
        usage ();

    while (++argv, --argc > 0) {
        char *arg;
        arg = *argv;

        if (*arg != '-')
            hname = arg;
        else if (arg[1] == 0 || arg[2] != 0)
            usage ();
        else
            switch (arg[1]) {
            case 'u':
                hints.ai_protocol = IPPROTO_UDP;
                break;
            case 't':
                hints.ai_protocol = IPPROTO_TCP;
                break;
            case 'R':
                hints.ai_protocol = IPPROTO_RAW;
                break;
            case 'I':
                hints.ai_protocol = IPPROTO_ICMP;
                break;
            case 'd':
                hints.ai_socktype = SOCK_DGRAM;
                break;
            case 's':
                hints.ai_socktype = SOCK_STREAM;
                break;
            case 'r':
                hints.ai_socktype = SOCK_RAW;
                break;
            case 'p':
                if (argv[1] == 0 || argv[1][0] == 0 || argv[1][0] == '-')
                    usage ();
                port = argv[1];
                argc--, argv++;
                break;
            case '4':
                hints.ai_family = AF_INET;
                break;
#ifdef AF_INET6
            case '6':
                hints.ai_family = AF_INET6;
                break;
#endif
            case 'N':
                numerichost = 1;
                break;
            case 'n':
                numericserv = 1;
                break;
            case 'P':
                hints.ai_flags |= AI_PASSIVE;
                break;
            default:
                usage ();
            }
    }

    if (hname && !numerichost)
        hints.ai_flags |= AI_CANONNAME;
    if (numerichost) {
#ifdef AI_NUMERICHOST
        hints.ai_flags |= AI_NUMERICHOST;
#else
        fprintf(stderr, "AI_NUMERICHOST not defined on this platform\n");
        exit(1);
#endif
    }
    if (numericserv) {
#ifdef AI_NUMERICSERV
        hints.ai_flags |= AI_NUMERICSERV;
#else
        fprintf(stderr, "AI_NUMERICSERV not defined on this platform\n");
        exit(1);
#endif
    }

    printf("getaddrinfo(hostname %s, service %s,\n"
           "            hints { ",
           hname ? hname : "(null)", port ? port : "(null)");
    sep = "";
#define Z(FLAG) if (hints.ai_flags & AI_##FLAG) printf("%s%s", sep, #FLAG), sep = "|"
    Z(CANONNAME);
    Z(PASSIVE);
#ifdef AI_NUMERICHOST
    Z(NUMERICHOST);
#endif
#ifdef AI_NUMERICSERV
    Z(NUMERICSERV);
#endif
    if (sep[0] == 0)
        printf ("no-flags");
    if (hints.ai_family)
        printf(" %s", familyname(hints.ai_family));
    if (hints.ai_socktype)
        printf(" SOCK_%s", socktypename(hints.ai_socktype));
    if (hints.ai_protocol)
        printf(" IPPROTO_%s", protoname(hints.ai_protocol));
    printf(" }):\n");

    err = getaddrinfo(hname, port, &hints, &ap);
    if (err) {
        printf("\terror => %s\n", eaistr(err));
        return 1;
    }

    for (ap2 = ap; ap2; ap2 = ap2->ai_next) {
        char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
        /* If we don't do this, even AIX's own getnameinfo will reject
           the sockaddr structures.  The sa_len field doesn't get set
           either, on AIX, but getnameinfo won't complain.  */
        if (ap2->ai_addr->sa_family == 0) {
            printf("BAD: sa_family zero! fixing...\n");
            ap2->ai_addr->sa_family = ap2->ai_family;
        } else if (ap2->ai_addr->sa_family != ap2->ai_family) {
            printf("BAD: sa_family != ai_family! fixing...\n");
            ap2->ai_addr->sa_family = ap2->ai_family;
        }
        if (getnameinfo(ap2->ai_addr, ap2->ai_addrlen, hbuf, sizeof(hbuf),
                        pbuf, sizeof(pbuf), NI_NUMERICHOST | NI_NUMERICSERV)) {
            strlcpy(hbuf, "...", sizeof(hbuf));
            strlcpy(pbuf, "...", sizeof(pbuf));
        }
        printf("%p:\n"
               "\tfamily = %s\tproto = %-4s\tsocktype = %s\n",
               (void *) ap2, familyname(ap2->ai_family),
               protoname (ap2->ai_protocol),
               socktypename (ap2->ai_socktype));
        if (ap2->ai_canonname) {
            if (ap2->ai_canonname[0])
                printf("\tcanonname = %s\n", ap2->ai_canonname);
            else
                printf("BAD: ai_canonname is set but empty!\n");
        } else if (ap2 == ap && (hints.ai_flags & AI_CANONNAME)) {
            printf("BAD: first ai_canonname is null!\n");
        }
        printf("\taddr = %-28s\tport = %s\n", hbuf, pbuf);

        err = getnameinfo(ap2->ai_addr, ap2->ai_addrlen, hbuf, sizeof (hbuf),
                          pbuf, sizeof(pbuf), NI_NAMEREQD);
        if (err)
            printf("\tgetnameinfo(NI_NAMEREQD): %s\n", eaistr(err));
        else
            printf("\tgetnameinfo => %s, %s\n", hbuf, pbuf);
    }
    freeaddrinfo(ap);
    return 0;
}
コード例 #28
0
ファイル: Active.cpp プロジェクト: mmaulwurff/FREG
const XyzInt Active::GetXyz() const { return {X(), Y(), Z()}; }
コード例 #29
0
int main(int argc, char *argv[]) {
  MPI_Init(&argc, &argv);
  //typedef rokko::matrix_row_major matrix_major;
  typedef rokko::matrix_col_major matrix_major;

  if (argc <= 1) {
    std::cerr << "error: " << argv[0] << " solver_name" << std::endl;
    MPI_Abort(MPI_COMM_WORLD, 34);
  }
  rokko::timer timer;
  timer.registrate( 1, "diagonalize");
  std::string solver_name(argv[1]);

  int L = 12;
  std::vector<std::pair<int, int> > lattice;
  for (int i=0; i<L-1; ++i) {
    lattice.push_back(std::make_pair(i, i+1));
  }
  
  std::cout << "L=" << L << std::endl;

  int dim = 1 << L;
  std::cout << "dim=" << dim << std::endl;
  rokko::parallel_dense_solver solver(solver_name);
  solver.initialize(argc, argv);

  MPI_Comm comm = MPI_COMM_WORLD;
  rokko::grid g(comm);
  int myrank = g.get_myrank();
  int nprocs = g.get_nprocs();

  const int root = 0;

  rokko::distributed_matrix<double, matrix_major> mat(dim, dim, g, solver);
  rokko::heisenberg_hamiltonian::generate(L, lattice, mat);
  std::cout << "finished generate" << std::endl;

  rokko::localized_vector<double> w(dim);
  rokko::distributed_matrix<double, matrix_major> Z(dim, dim, g, solver);

  for (int count=0; count<1; ++count) {
    try {
      solver.diagonalize(mat, w, Z);
    }

    catch (const char *e) {
      std::cout << "Exception : " << e << std::endl;
      MPI_Abort(MPI_COMM_WORLD, 22);
    }
  }
  std::cout << "finished eigensolver" << std::endl;

  /*
  // gather of eigenvectors
  rokko::localized_matrix<double, matrix_major> eigvec_global;
  rokko::localized_matrix<double, matrix_major> eigvec_sorted(dim, dim);
  rokko::localized_vector<double> eigval_sorted(dim);
  rokko::gather(Z, eigvec_global, root);
  Z.print();
  //if (myrank == root) {
  //  std::cout << "eigvec:" << std::endl << eigvec_global << std::endl;
  //}

  std::cout.precision(20);
  */

  /*
  std::cout << "w=" << std::endl;
  for (int i=0; i<dim; ++i) {
    std::cout << w[i] << " ";
  }
  std::cout << std::endl;
  */

  if (myrank == 0) {

    std::cout << "num_procs = " << nprocs << std::endl;
#ifdef _OPENMP_
    std::cout << "num_threads = " << omp_get_max_threads() << std::endl;
    //std::cout << "num_threads = " << mkl_get_num_threads() << std::endl;
#endif
    std::cout << "solver_name = " << solver_name << std::endl;
    std::cout << "matrix = frank" << std::endl;
    std::cout << "dim = " << dim << std::endl;
    std::cout << "time = " << timer.get_average(1) << std::endl;
    std::cout << "rokko_version = " << ROKKO_VERSION << std::endl;
    std::cout << "hostname = " << boost::asio::ip::host_name() << std::endl;
    std::time_t now = std::time(0);
    std::cout << "date = " << ctime(&now)<< std::endl;
  }

  solver.finalize();
  MPI_Finalize();
  return 0;
}
コード例 #30
0
ファイル: a_movingcamera.cpp プロジェクト: ibm5155/zdoom
bool APathFollower::Interpolate ()
{
	fixed_t dx = 0, dy = 0, dz = 0;

	if ((args[2] & 8) && Time > 0.f)
	{
		dx = X();
		dy = Y();
		dz = Z();
	}

	if (CurrNode->Next==NULL) return false;

	UnlinkFromWorld ();
	fixed_t x, y, z;
	if (args[2] & 1)
	{	// linear
		x = FLOAT2FIXED(Lerp (FIXED2FLOAT(CurrNode->X()), FIXED2FLOAT(CurrNode->Next->X())));
		y = FLOAT2FIXED(Lerp (FIXED2FLOAT(CurrNode->Y()), FIXED2FLOAT(CurrNode->Next->Y())));
		z = FLOAT2FIXED(Lerp (FIXED2FLOAT(CurrNode->Z()), FIXED2FLOAT(CurrNode->Next->Z())));
	}
	else
	{	// spline
		if (CurrNode->Next->Next==NULL) return false;

		x = FLOAT2FIXED(Splerp (FIXED2FLOAT(PrevNode->X()), FIXED2FLOAT(CurrNode->X()),
								FIXED2FLOAT(CurrNode->Next->X()), FIXED2FLOAT(CurrNode->Next->Next->X())));
		y = FLOAT2FIXED(Splerp (FIXED2FLOAT(PrevNode->Y()), FIXED2FLOAT(CurrNode->Y()),
								FIXED2FLOAT(CurrNode->Next->Y()), FIXED2FLOAT(CurrNode->Next->Next->Y())));
		z = FLOAT2FIXED(Splerp (FIXED2FLOAT(PrevNode->Z()), FIXED2FLOAT(CurrNode->Z()),
								FIXED2FLOAT(CurrNode->Next->Z()), FIXED2FLOAT(CurrNode->Next->Next->Z())));
	}
	SetXYZ(x, y, z);
	LinkToWorld ();

	if (args[2] & 6)
	{
		if (args[2] & 8)
		{
			if (args[2] & 1)
			{ // linear
				dx = CurrNode->Next->X() - CurrNode->X();
				dy = CurrNode->Next->Y() - CurrNode->Y();
				dz = CurrNode->Next->Z() - CurrNode->Z();
			}
			else if (Time > 0.f)
			{ // spline
				dx = x - dx;
				dy = y - dy;
				dz = z - dz;
			}
			else
			{
				int realarg = args[2];
				args[2] &= ~(2|4|8);
				Time += 0.1f;
				dx = x;
				dy = y;
				dz = z;
				Interpolate ();
				Time -= 0.1f;
				args[2] = realarg;
				dx = x - dx;
				dy = y - dy;
				dz = z - dz;
				x -= dx;
				y -= dy;
				z -= dz;
				SetXYZ(x, y, z);
			}
			if (args[2] & 2)
			{ // adjust yaw
				angle = R_PointToAngle2 (0, 0, dx, dy);
			}
			if (args[2] & 4)
			{ // adjust pitch; use floats for precision
				double fdx = FIXED2DBL(dx);
				double fdy = FIXED2DBL(dy);
				double fdz = FIXED2DBL(-dz);
				double dist = sqrt (fdx*fdx + fdy*fdy);
				double ang = dist != 0.f ? atan2 (fdz, dist) : 0;
				pitch = (fixed_t)RAD2ANGLE(ang);
			}
		}
		else
		{
			if (args[2] & 2)
			{ // interpolate angle
				float angle1 = (float)CurrNode->angle;
				float angle2 = (float)CurrNode->Next->angle;
				if (angle2 - angle1 <= -2147483648.f)
				{
					float lerped = Lerp (angle1, angle2 + 4294967296.f);
					if (lerped >= 4294967296.f)
					{
						angle = xs_CRoundToUInt(lerped - 4294967296.f);
					}
					else
					{
						angle = xs_CRoundToUInt(lerped);
					}
				}
				else if (angle2 - angle1 >= 2147483648.f)
				{
					float lerped = Lerp (angle1, angle2 - 4294967296.f);
					if (lerped < 0.f)
					{
						angle = xs_CRoundToUInt(lerped + 4294967296.f);
					}
					else
					{
						angle = xs_CRoundToUInt(lerped);
					}
				}
				else
				{
					angle = xs_CRoundToUInt(Lerp (angle1, angle2));
				}
			}
			if (args[2] & 1)
			{ // linear
				if (args[2] & 4)
				{ // interpolate pitch
					pitch = FLOAT2FIXED(Lerp (FIXED2FLOAT(CurrNode->pitch), FIXED2FLOAT(CurrNode->Next->pitch)));
				}
			}
			else
			{ // spline
				if (args[2] & 4)
				{ // interpolate pitch
					pitch = FLOAT2FIXED(Splerp (FIXED2FLOAT(PrevNode->pitch), FIXED2FLOAT(CurrNode->pitch),
						FIXED2FLOAT(CurrNode->Next->pitch), FIXED2FLOAT(CurrNode->Next->Next->pitch)));
				}
			}
		}
	}

	return true;
}