Exemple #1
0
int testvector(struct cube *c, int p0, int p1, int p2, int p3,
               struct point *p)
{
    int i;
    struct point econtra, eco[3], h;


    for (i = 0; i < 3; i++) {
        eco[0].x[i] = c->p[p1]->d.p->x[i] - c->p[p0]->d.p->x[i];
        eco[1].x[i] = c->p[p2]->d.p->x[i] - c->p[p0]->d.p->x[i];
        eco[2].x[i] = c->p[p3]->d.p->x[i] - c->p[p0]->d.p->x[i];
        h.x[i] = p->x[i] - c->p[p0]->d.p->x[i];
    }

    VECTOR(&econtra, &eco[2], &eco[1]);

    if (SCALAR(&econtra, &h) < 0.0) {
        return 0;
    }

    VECTOR(&econtra, &eco[0], &eco[2]);

    if (SCALAR(&econtra, &h) < 0.0) {
        return 0;
    }

    VECTOR(&econtra, &eco[1], &eco[0]);

    if (SCALAR(&econtra, &h) < 0.0) {
        return 0;
    }

    return 1;
}
Exemple #2
0
/**
 * @name angle_change
 *
 * Return the change in angle (degrees) of the line segments between
 * points one and two, and two and three.
 */
int Wordrec::angle_change(EDGEPT *point1, EDGEPT *point2, EDGEPT *point3) {
  VECTOR vector1;
  VECTOR vector2;

  int angle;

  /* Compute angle */
  vector1.x = point2->pos.x - point1->pos.x;
  vector1.y = point2->pos.y - point1->pos.y;
  vector2.x = point3->pos.x - point2->pos.x;
  vector2.y = point3->pos.y - point2->pos.y;
  /* Use cross product */
  float length = std::sqrt(static_cast<float>(LENGTH(vector1)) * LENGTH(vector2));
  if (static_cast<int>(length) == 0)
    return (0);
  angle = static_cast<int>(floor(asin(CROSS (vector1, vector2) /
                                      length) / M_PI * 180.0 + 0.5));

  /* Use dot product */
  if (SCALAR (vector1, vector2) < 0)
    angle = 180 - angle;
  /* Adjust angle */
  if (angle > 180)
    angle -= 360;
  if (angle <= -180)
    angle += 360;
  return (angle);
}
Exemple #3
0
inline SCALAR dsign(SCALAR s) {
    SCALAR abs_s = myabs(s);
    if (abs_s==SCALAR(0.0)) {
        throw std::runtime_error("dsign: s must not be zero");
    } else {
        return s/abs_s;
    }
}
Exemple #4
0
// Test code.
void solve(Solver &solver, int n) {
  if (solver.solve()) {
    scalar *sln = solver.get_solution();
    for (int i = 0; i < n; i++) {
      printf(SCALAR_FMT"\n", SCALAR(sln[i]));
    }
  }
  else {
    printf("Unable to solve.\n");
  }
}
Exemple #5
0
Ioss::NodeBlock::NodeBlock(Ioss::DatabaseIO *io_database,
			   const std::string &my_name,
			   int64_t node_count,
			   int64_t degrees_of_freedom)
  : Ioss::EntityBlock(io_database, my_name, "node", node_count)
{
  properties.add(Ioss::Property("component_degree",
				static_cast<int>(degrees_of_freedom)));

  std::string vector_name;
  assert(degrees_of_freedom == 1 || degrees_of_freedom == 2 || degrees_of_freedom == 3);

  if (degrees_of_freedom == 1)
    vector_name = SCALAR();
  else if (degrees_of_freedom == 2)
    vector_name = VECTOR_2D();
  else if (degrees_of_freedom == 3)
    vector_name = VECTOR_3D();
  
  fields.add(Ioss::Field("mesh_model_coordinates",
			 Ioss::Field::REAL, vector_name,
			 Ioss::Field::MESH, node_count));

  // Permit access 1-coordinate at a time
  fields.add(Ioss::Field("mesh_model_coordinates_x",
			 Ioss::Field::REAL, SCALAR(),
			 Ioss::Field::MESH, node_count));
  if (degrees_of_freedom > 1)
    fields.add(Ioss::Field("mesh_model_coordinates_y",
			   Ioss::Field::REAL, SCALAR(),
			   Ioss::Field::MESH, node_count));

  if (degrees_of_freedom > 2)
    fields.add(Ioss::Field("mesh_model_coordinates_z",
			   Ioss::Field::REAL, SCALAR(),
			   Ioss::Field::MESH, node_count));
  
  fields.add(Ioss::Field("node_connectivity_status",
			 Ioss::Field::CHARACTER, SCALAR(),
			 Ioss::Field::MESH, node_count));
}
Exemple #6
0
int main(int argc, char **argv) {
	int res = ERR_SUCCESS;

#ifdef WITH_PETSC
	PetscInitialize(&argc, &argv, (char *) PETSC_NULL, PETSC_NULL);
#endif
	set_verbose(false);

	if (argc < 3) error("Not enough parameters");

	HcurlShapesetLobattoHex shapeset;

	printf("* Loading mesh '%s'\n", argv[1]);
	Mesh mesh;
	Mesh3DReader mesh_loader;
	if (!mesh_loader.load(argv[1], &mesh)) error("Loading mesh file '%s'\n", argv[1]);

	printf("* Setting the space up\n");
	HcurlSpace space(&mesh, &shapeset);
	space.set_bc_types(bc_types);

	int order;
	sscanf(argv[2], "%d", &order);
	int dir_x = order, dir_y = order, dir_z = order;
	order3_t o(dir_x, dir_y, dir_z);
	printf("  - Setting uniform order to (%d, %d, %d)\n", o.x, o.y ,o.z);
	space.set_uniform_order(o);

	int ndofs = space.assign_dofs();
	printf("  - Number of DOFs: %d\n", ndofs);

	printf("* Calculating a solution\n");

#if defined WITH_UMFPACK
	UMFPackMatrix mat;
	UMFPackVector rhs;
	UMFPackLinearSolver solver(&mat, &rhs);
#elif defined WITH_PARDISO
	PardisoMatrix mat;
	PardisoVector rhs;
	PardisoSolver solver(&mat, &rhs);
#elif defined WITH_PETSC
	PetscMatrix mat;
	PetscVector rhs;
	PetscLinearSolver solver(&mat, &rhs);
#elif defined WITH_MUMPS
	MumpsMatrix mat;
	MumpsVector rhs;
	MumpsSolver solver(&mat, &rhs);
#endif

	WeakForm wf;
	wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<ord_t, ord_t>, SYM);
	wf.add_matrix_form_surf(bilinear_form_surf<double, scalar>, bilinear_form_surf<ord_t, ord_t>);
	wf.add_vector_form(linear_form<double, scalar>, linear_form<ord_t, ord_t>);
	wf.add_vector_form_surf(linear_form_surf<double, scalar>, linear_form_surf<ord_t, ord_t>);

	LinearProblem lp(&wf, &space);

	// assemble stiffness matrix
	Timer assemble_timer("Assembling stiffness matrix");
	assemble_timer.start();
	lp.assemble(&mat, &rhs);
	assemble_timer.stop();

	// solve the stiffness matrix
	Timer solve_timer("Solving stiffness matrix");
	solve_timer.start();
	bool solved = solver.solve();
	solve_timer.stop();

//#ifdef OUTPUT_DIR
	mat.dump(stdout, "a");
	rhs.dump(stdout, "b");
//#endif

	if (solved) {
		scalar *s = solver.get_solution();

		Solution sln(&mesh);
		sln.set_coeff_vector(&space, s);

		printf("* Solution:\n");
		for (int i = 1; i <= ndofs; i++) {
			printf(" x[% 3d] = " SCALAR_FMT "\n", i, SCALAR(s[i]));
		}

		// output the measured values
		printf("%s: %s (%lf secs)\n", assemble_timer.get_name(), assemble_timer.get_human_time(), assemble_timer.get_seconds());
		printf("%s: %s (%lf secs)\n", solve_timer.get_name(), solve_timer.get_human_time(), solve_timer.get_seconds());

		// norm
		ExactSolution ex_sln(&mesh, exact_solution);
		double hcurl_sln_norm = hcurl_norm(&sln);
		double hcurl_err_norm = hcurl_error(&sln, &ex_sln);
		printf(" - Hcurl solution norm: % le\n", hcurl_sln_norm);
		printf(" - Hcurl error norm:    % le\n", hcurl_err_norm);

		double l2_sln_norm = l2_norm_hcurl(&sln);
		double l2_err_norm = l2_error_hcurl(&sln, &ex_sln);
		printf(" - L2 solution norm:    % le\n", l2_sln_norm);
		printf(" - L2 error norm:       % le\n", l2_err_norm);

		if (hcurl_err_norm > EPS || l2_err_norm > EPS) {
			// calculated solution is not enough precise
			res = ERR_FAILURE;
		}


#if 0 //def OUTPUT_DIR
		// output
		printf("starting output\n");
		const char *of_name = OUTPUT_DIR "/solution.vtk";
		FILE *ofile = fopen(of_name, "w");
		if (ofile != NULL) {
			ExactSolution ex_sln(&mesh, exact_solution_0, exact_solution_1, exact_solution_2);

			RealPartFilter real_sln(&mesh, &sln, FN_VAL);
			ImagPartFilter imag_sln(&mesh, &sln, FN_VAL);

			DiffFilter eh(&mesh, &sln, &ex_sln);
			DiffFilter eh_dx(&mesh, &sln, &ex_sln, FN_DX, FN_DX);
//			DiffFilter eh_dy(&mesh, &sln, &ex_sln, FN_DY, FN_DY);
//			DiffFilter eh_dz(&mesh, &sln, &ex_sln, FN_DZ, FN_DZ);

//			GmshOutputEngine output(ofile);
			VtkOutputEngine output(ofile);

			output.out(&real_sln, "real_Uh", FN_VAL);
			output.out(&imag_sln, "imag_Uh", FN_VAL);

			output.out(&real_sln, "real_Uh_0", FN_VAL_0);
			output.out(&real_sln, "real_Uh_1", FN_VAL_1);
			output.out(&real_sln, "real_Uh_2", FN_VAL_2);

			output.out(&imag_sln, "imag_Uh_0", FN_VAL_0);
			output.out(&imag_sln, "imag_Uh_1", FN_VAL_1);
			output.out(&imag_sln, "imag_Uh_2", FN_VAL_2);

			fclose(ofile);
		}
		else {
			warning("Can not open '%s' for writing.", of_name);
		}
#endif
	}

#ifdef WITH_PETSC
	mat.free();
	rhs.free();
	PetscFinalize();
#endif

	return res;
}
Exemple #7
0
/* sentinel. If reached during dispatch, throw type error. */
#define EOV {0, 0, 0, 0, 0}

#define SCALAR(fname, flags) \
        { TI, TI, fname ## II, TI, flags },     \
        { TI, TF, fname ## IF, TF, flags },     \
        { TF, TI, fname ## FI, TF, flags },     \
        { TF, TF, fname ## FF, TF, flags }

/*********
 * Verbs *
 *********/

d_table(d_plus) = {
        SCALAR(plus, VF_SAME_SIZE),
        EOV
};

d_table(d_minus) = {
        SCALAR(minus, VF_SAME_SIZE),
        EOV
};


d_table(d_asterisk) = {
        SCALAR(times, VF_SAME_SIZE),
        EOV
};

Exemple #8
0
int
main(int argc, char *argv[])
{
	static char verskey[] = _PWD_VERSION_KEY;
	char version = _PWD_CURRENT_VERSION;
	DB *dp, *sdp, *pw_db;
	DBT data, sdata, key;
	FILE *fp, *oldfp;
	sigset_t set;
	int ch, cnt, ypcnt, makeold, tfd, yp_enabled = 0;
	unsigned int len;
	uint32_t store;
	const char *t;
	char *p;
	char buf[MAX(MAXPATHLEN, LINE_MAX * 2)], tbuf[1024];
	char sbuf[MAX(MAXPATHLEN, LINE_MAX * 2)];
	char buf2[MAXPATHLEN];
	char sbuf2[MAXPATHLEN];
	char *username;
	u_int method, methoduid;
	int Cflag, dflag, iflag;
	int nblock = 0;

	iflag = dflag = Cflag = 0;
	strcpy(prefix, _PATH_PWD);
	makeold = 0;
	username = NULL;
	oldfp = NULL;
	while ((ch = getopt(argc, argv, "BCLNd:ips:u:v")) != -1)
		switch(ch) {
		case 'B':			/* big-endian output */
			openinfo.lorder = BIG_ENDIAN;
			break;
		case 'C':                       /* verify only */
			Cflag = 1;
			break;
		case 'L':			/* little-endian output */
			openinfo.lorder = LITTLE_ENDIAN;
			break;
		case 'N':			/* do not wait for lock	*/
			nblock = LOCK_NB;	/* will fail if locked */
			break;
		case 'd':
			dflag++;
			strlcpy(prefix, optarg, sizeof(prefix));
			break;
		case 'i':
			iflag++;
			break;
		case 'p':			/* create V7 "file.orig" */
			makeold = 1;
			break;
		case 's':			/* change default cachesize */
			openinfo.cachesize = atoi(optarg) * 1024 * 1024;
			break;
		case 'u':			/* only update this record */
			username = optarg;
			break;
		case 'v':                       /* backward compatible */
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc != 1 || (username && (*username == '+' || *username == '-')))
		usage();

	/*
	 * This could be changed to allow the user to interrupt.
	 * Probably not worth the effort.
	 */
	sigemptyset(&set);
	sigaddset(&set, SIGTSTP);
	sigaddset(&set, SIGHUP);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGQUIT);
	sigaddset(&set, SIGTERM);
	(void)sigprocmask(SIG_BLOCK, &set, (sigset_t *)NULL);

	/* We don't care what the user wants. */
	(void)umask(0);

	pname = *argv;

	/*
	 * Open and lock the original password file.  We have to check
	 * the hardlink count after we get the lock to handle any potential
	 * unlink/rename race.
	 *
	 * This lock is necessary when someone runs pwd_mkdb manually, directly
	 * on master.passwd, to handle the case where a user might try to
	 * change his password while pwd_mkdb is running. 
	 */
	for (;;) {
		struct stat st;

		if (!(fp = fopen(pname, "r")))
			error(pname);
		if (flock(fileno(fp), LOCK_EX|nblock) < 0 && !(dflag && iflag))
			error("flock");
		if (fstat(fileno(fp), &st) < 0)
			error(pname);
		if (st.st_nlink != 0)
			break;
		fclose(fp);
		fp = NULL;
	}

	/* check only if password database is valid */
	if (Cflag) {
		while (scan(fp, &pwd))
			if (!is_comment && strlen(pwd.pw_name) >= MAXLOGNAME) {
				warnx("%s: username too long", pwd.pw_name);
				exit(1);
			}
		exit(0);
	}

	/* Open the temporary insecure password database. */
	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
	(void)snprintf(sbuf, sizeof(sbuf), "%s/%s.tmp", prefix, _SMP_DB);
	if (username) {
		int use_version;

		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
		(void)snprintf(sbuf2, sizeof(sbuf2), "%s/%s", prefix, _SMP_DB);

		clean = FILE_INSECURE;
		cp(buf2, buf, PERM_INSECURE);
		dp = dbopen(buf,
		    O_RDWR|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
		if (dp == NULL)
			error(buf);

		clean = FILE_SECURE;
		cp(sbuf2, sbuf, PERM_SECURE);
		sdp = dbopen(sbuf,
		    O_RDWR|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
		if (sdp == NULL)
			error(sbuf);

		/*
		 * Do some trouble to check if we should store this users 
		 * uid. Don't use getpwnam/getpwuid as that interferes 
		 * with NIS.
		 */
		pw_db = dbopen(_PATH_MP_DB, O_RDONLY, 0, DB_HASH, NULL);
		if (!pw_db)
			error(_MP_DB);

		key.data = verskey;
		key.size = sizeof(verskey)-1;
		if ((pw_db->get)(pw_db, &key, &data, 0) == 0)
			use_version = *(unsigned char *)data.data;
		else
			use_version = 3;
		buf[0] = _PW_VERSIONED(_PW_KEYBYNAME, use_version);
		len = strlen(username);

		/* Only check that username fits in buffer */
		memmove(buf + 1, username, MIN(len, sizeof(buf) - 1));
		key.data = (u_char *)buf;
		key.size = len + 1;
		if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
			p = (char *)data.data;

			/* jump over pw_name and pw_passwd, to get to pw_uid */
			while (*p++)
				;
			while (*p++)
				;

			buf[0] = _PW_VERSIONED(_PW_KEYBYUID, use_version);
			memmove(buf + 1, p, sizeof(store));
			key.data = (u_char *)buf;
			key.size = sizeof(store) + 1;

			if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
				/* First field of data.data holds pw_pwname */
				if (!strcmp(data.data, username))
					methoduid = 0;
				else
					methoduid = R_NOOVERWRITE;
			} else {
				methoduid = R_NOOVERWRITE;
			}
		} else {
			methoduid = R_NOOVERWRITE;
		}
		if ((pw_db->close)(pw_db))
			error("close pw_db");
		method = 0;
	} else {
		dp = dbopen(buf,
		    O_RDWR|O_CREAT|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
		if (dp == NULL)
			error(buf);
		clean = FILE_INSECURE;

		sdp = dbopen(sbuf,
		    O_RDWR|O_CREAT|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
		if (sdp == NULL)
			error(sbuf);
		clean = FILE_SECURE;

		method = R_NOOVERWRITE;
		methoduid = R_NOOVERWRITE;
	}

	/*
	 * Open file for old password file.  Minor trickiness -- don't want to
	 * chance the file already existing, since someone (stupidly) might
	 * still be using this for permission checking.  So, open it first and
	 * fdopen the resulting fd.  The resulting file should be readable by
	 * everyone.
	 */
	if (makeold) {
		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
		if ((tfd = open(buf,
		    O_WRONLY|O_CREAT|O_EXCL, PERM_INSECURE)) < 0)
			error(buf);
		if ((oldfp = fdopen(tfd, "w")) == NULL)
			error(buf);
		clean = FILE_ORIG;
	}

	/*
	 * The databases actually contain three copies of the original data.
	 * Each password file entry is converted into a rough approximation
	 * of a ``struct passwd'', with the strings placed inline.  This
	 * object is then stored as the data for three separate keys.  The
	 * first key * is the pw_name field prepended by the _PW_KEYBYNAME
	 * character.  The second key is the pw_uid field prepended by the
	 * _PW_KEYBYUID character.  The third key is the line number in the
	 * original file prepended by the _PW_KEYBYNUM character.  (The special
	 * characters are prepended to ensure that the keys do not collide.)
	 */
	/* In order to transition this file into a machine-independent
	 * form, we have to change the format of entries.  However, since
	 * older binaries will still expect the old MD format entries, we 
	 * create those as usual and use versioned tags for the new entries.
	 */
	if (username == NULL) {
		/* Do not add the VERSION tag when updating a single
		 * user.  When operating on `old format' databases, this
		 * would result in applications `seeing' only the updated
		 * entries.
		 */
		key.data = verskey;
		key.size = sizeof(verskey)-1;
		data.data = &version;
		data.size = 1;
		if ((dp->put)(dp, &key, &data, 0) == -1)
			error("put");
		if ((dp->put)(sdp, &key, &data, 0) == -1)
			error("put");
	}
	ypcnt = 0;
	data.data = (u_char *)buf;
	sdata.data = (u_char *)sbuf;
	key.data = (u_char *)tbuf;
	for (cnt = 1; scan(fp, &pwd); ++cnt) {
		if (!is_comment && 
		    (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-')) {
			yp_enabled = 1;
			ypcnt++;
		}
		if (is_comment)
			--cnt;
#define	COMPACT(e)	t = e; while ((*p++ = *t++));
#define SCALAR(e)	store = htonl((uint32_t)(e));      \
			memmove(p, &store, sizeof(store)); \
			p += sizeof(store);
#define	LSCALAR(e)	store = HTOL((uint32_t)(e));       \
			memmove(p, &store, sizeof(store)); \
			p += sizeof(store);
#define	HTOL(e)		(openinfo.lorder == BYTE_ORDER ? \
			(uint32_t)(e) : \
			bswap32((uint32_t)(e)))
		if (!is_comment && 
		    (!username || (strcmp(username, pwd.pw_name) == 0))) {
			/* Create insecure data. */
			p = buf;
			COMPACT(pwd.pw_name);
			COMPACT("*");
			SCALAR(pwd.pw_uid);
			SCALAR(pwd.pw_gid);
			SCALAR(pwd.pw_change);
			COMPACT(pwd.pw_class);
			COMPACT(pwd.pw_gecos);
			COMPACT(pwd.pw_dir);
			COMPACT(pwd.pw_shell);
			SCALAR(pwd.pw_expire);
			SCALAR(pwd.pw_fields);
			data.size = p - buf;

			/* Create secure data. */
			p = sbuf;
			COMPACT(pwd.pw_name);
			COMPACT(pwd.pw_passwd);
			SCALAR(pwd.pw_uid);
			SCALAR(pwd.pw_gid);
			SCALAR(pwd.pw_change);
			COMPACT(pwd.pw_class);
			COMPACT(pwd.pw_gecos);
			COMPACT(pwd.pw_dir);
			COMPACT(pwd.pw_shell);
			SCALAR(pwd.pw_expire);
			SCALAR(pwd.pw_fields);
			sdata.size = p - sbuf;

			/* Store insecure by name. */
			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNAME);
			len = strlen(pwd.pw_name);
			memmove(tbuf + 1, pwd.pw_name, len);
			key.size = len + 1;
			if ((dp->put)(dp, &key, &data, method) == -1)
				error("put");

			/* Store insecure by number. */
			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNUM);
			store = htonl(cnt);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((dp->put)(dp, &key, &data, method) == -1)
				error("put");

			/* Store insecure by uid. */
			tbuf[0] = CURRENT_VERSION(_PW_KEYBYUID);
			store = htonl(pwd.pw_uid);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((dp->put)(dp, &key, &data, methoduid) == -1)
				error("put");

			/* Store secure by name. */
			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNAME);
			len = strlen(pwd.pw_name);
			memmove(tbuf + 1, pwd.pw_name, len);
			key.size = len + 1;
			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
				error("put");

			/* Store secure by number. */
			tbuf[0] = CURRENT_VERSION(_PW_KEYBYNUM);
			store = htonl(cnt);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
				error("put");

			/* Store secure by uid. */
			tbuf[0] = CURRENT_VERSION(_PW_KEYBYUID);
			store = htonl(pwd.pw_uid);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((sdp->put)(sdp, &key, &sdata, methoduid) == -1)
				error("put");

			/* Store insecure and secure special plus and special minus */
			if (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-') {
				tbuf[0] = CURRENT_VERSION(_PW_KEYYPBYNUM);
				store = htonl(ypcnt);
				memmove(tbuf + 1, &store, sizeof(store));
				key.size = sizeof(store) + 1;
				if ((dp->put)(dp, &key, &data, method) == -1)
					error("put");
				if ((sdp->put)(sdp, &key, &sdata, method) == -1)
					error("put");
			}

			/* Create insecure data. (legacy version) */
			p = buf;
			COMPACT(pwd.pw_name);
			COMPACT("*");
			LSCALAR(pwd.pw_uid);
			LSCALAR(pwd.pw_gid);
			LSCALAR(pwd.pw_change);
			COMPACT(pwd.pw_class);
			COMPACT(pwd.pw_gecos);
			COMPACT(pwd.pw_dir);
			COMPACT(pwd.pw_shell);
			LSCALAR(pwd.pw_expire);
			LSCALAR(pwd.pw_fields);
			data.size = p - buf;

			/* Create secure data. (legacy version) */
			p = sbuf;
			COMPACT(pwd.pw_name);
			COMPACT(pwd.pw_passwd);
			LSCALAR(pwd.pw_uid);
			LSCALAR(pwd.pw_gid);
			LSCALAR(pwd.pw_change);
			COMPACT(pwd.pw_class);
			COMPACT(pwd.pw_gecos);
			COMPACT(pwd.pw_dir);
			COMPACT(pwd.pw_shell);
			LSCALAR(pwd.pw_expire);
			LSCALAR(pwd.pw_fields);
			sdata.size = p - sbuf;

			/* Store insecure by name. */
			tbuf[0] = LEGACY_VERSION(_PW_KEYBYNAME);
			len = strlen(pwd.pw_name);
			memmove(tbuf + 1, pwd.pw_name, len);
			key.size = len + 1;
			if ((dp->put)(dp, &key, &data, method) == -1)
				error("put");

			/* Store insecure by number. */
			tbuf[0] = LEGACY_VERSION(_PW_KEYBYNUM);
			store = HTOL(cnt);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((dp->put)(dp, &key, &data, method) == -1)
				error("put");

			/* Store insecure by uid. */
			tbuf[0] = LEGACY_VERSION(_PW_KEYBYUID);
			store = HTOL(pwd.pw_uid);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((dp->put)(dp, &key, &data, methoduid) == -1)
				error("put");

			/* Store secure by name. */
			tbuf[0] = LEGACY_VERSION(_PW_KEYBYNAME);
			len = strlen(pwd.pw_name);
			memmove(tbuf + 1, pwd.pw_name, len);
			key.size = len + 1;
			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
				error("put");

			/* Store secure by number. */
			tbuf[0] = LEGACY_VERSION(_PW_KEYBYNUM);
			store = HTOL(cnt);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
				error("put");

			/* Store secure by uid. */
			tbuf[0] = LEGACY_VERSION(_PW_KEYBYUID);
			store = HTOL(pwd.pw_uid);
			memmove(tbuf + 1, &store, sizeof(store));
			key.size = sizeof(store) + 1;
			if ((sdp->put)(sdp, &key, &sdata, methoduid) == -1)
				error("put");

			/* Store insecure and secure special plus and special minus */
			if (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-') {
				tbuf[0] = LEGACY_VERSION(_PW_KEYYPBYNUM);
				store = HTOL(ypcnt);
				memmove(tbuf + 1, &store, sizeof(store));
				key.size = sizeof(store) + 1;
				if ((dp->put)(dp, &key, &data, method) == -1)
					error("put");
				if ((sdp->put)(sdp, &key, &sdata, method) == -1)
					error("put");
			}
		}
		/* Create original format password file entry */
		if (is_comment && makeold){	/* copy comments */
			if (fprintf(oldfp, "%s\n", line) < 0)
				error("write old");
		} else if (makeold) {
			char uidstr[20];
			char gidstr[20];

			snprintf(uidstr, sizeof(uidstr), "%u", pwd.pw_uid);
			snprintf(gidstr, sizeof(gidstr), "%u", pwd.pw_gid);

			if (fprintf(oldfp, "%s:*:%s:%s:%s:%s:%s\n",
			    pwd.pw_name, pwd.pw_fields & _PWF_UID ? uidstr : "",
			    pwd.pw_fields & _PWF_GID ? gidstr : "",
			    pwd.pw_gecos, pwd.pw_dir, pwd.pw_shell) < 0)
				error("write old");
		}
	}
	/* If YP enabled, set flag. */
	if (yp_enabled) {
		buf[0] = yp_enabled + 2;
		data.size = 1;
		key.size = 1;
		tbuf[0] = CURRENT_VERSION(_PW_KEYYPENABLED);
		if ((dp->put)(dp, &key, &data, method) == -1)
			error("put");
		if ((sdp->put)(sdp, &key, &data, method) == -1)
			error("put");
		tbuf[0] = LEGACY_VERSION(_PW_KEYYPENABLED);
		key.size = 1;
		if ((dp->put)(dp, &key, &data, method) == -1)
			error("put");
		if ((sdp->put)(sdp, &key, &data, method) == -1)
			error("put");
	}

	if ((dp->close)(dp) == -1)
		error("close");
	if ((sdp->close)(sdp) == -1)
		error("close");
	if (makeold) {
		(void)fflush(oldfp);
		if (fclose(oldfp) == EOF)
			error("close old");
	}

	/* Set master.passwd permissions, in case caller forgot. */
	(void)fchmod(fileno(fp), S_IRUSR|S_IWUSR);

	/* Install as the real password files. */
	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
	mv(buf, buf2);
	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _SMP_DB);
	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _SMP_DB);
	mv(buf, buf2);
	if (makeold) {
		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _PASSWD);
		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
		mv(buf, buf2);
	}
	/*
	 * Move the master password LAST -- chpass(1), passwd(1) and vipw(8)
	 * all use flock(2) on it to block other incarnations of themselves.
	 * The rename means that everything is unlocked, as the original file
	 * can no longer be accessed.
	 */
	(void)snprintf(buf, sizeof(buf), "%s/%s", prefix, _MASTERPASSWD);
	mv(pname, buf);

	/*
	 * Close locked password file after rename()
	 */
	if (fclose(fp) == EOF)
		error("close fp");

	exit(0);
}
Exemple #9
0
Ioex::SuperElement::SuperElement(std::string filename, const std::string &my_name)
    : Ioss::GroupingEntity(nullptr, my_name, 1), fileName(std::move(filename)), numDOF(0),
      num_nodes(0), numEIG(0), num_dim(0), filePtr(-1)
{

  // For now, we will open the raw netcdf file here and parse the
  // dimensions. This is probably not how this should be done long
  // term, but is better than putting netcdf calls in application...

  // Check that file specified by filename exists...
  // Add working directory if needed.
  std::string local_filename = fileName;

  int status = nc_open(local_filename.c_str(), NC_NOWRITE, &filePtr);
  if (status != NC_NOERR) {
    std::ostringstream errmsg;
    errmsg << "ERROR: Failed to open superelement file '" << local_filename << "'.";
    IOSS_ERROR(errmsg);
  }

  // At this point have a valid netcdf file handle.
  // Read some dimensions to determine size of Mass and Stiffness
  // matrix.
  nc_get_dimension(filePtr, "NumDof", "number of degrees of freedom", &numDOF);

  nc_get_dimension(filePtr, "num_nodes", "number of nodes", &num_nodes);

  nc_get_dimension(filePtr, "NumEig", "number of eigenvalues", &numEIG);

  nc_get_dimension(filePtr, "num_dim", "number of dimensions", &num_dim);

  size_t num_constraints = 0;
  nc_get_dimension(filePtr, "NumConstraints", "number of interface dof", &num_constraints);
  assert(num_constraints == numDOF - numEIG);

  // Add the standard properties...
  properties.add(Ioss::Property(this, "numDOF", Ioss::Property::INTEGER));
  if (num_nodes > 0) {
    properties.add(Ioss::Property(this, "num_nodes", Ioss::Property::INTEGER));
  }
  properties.add(Ioss::Property(this, "numEIG", Ioss::Property::INTEGER));

  properties.add(Ioss::Property(this, "numDIM", Ioss::Property::INTEGER));

  properties.add(Ioss::Property(this, "numConstraints", Ioss::Property::INTEGER));

  // Add the standard fields...
  if (num_nodes > 0) {
    fields.add(Ioss::Field("coordx", Ioss::Field::REAL, SCALAR(), Ioss::Field::MESH, num_nodes));
    fields.add(Ioss::Field("coordy", Ioss::Field::REAL, SCALAR(), Ioss::Field::MESH, num_nodes));
    fields.add(Ioss::Field("coordz", Ioss::Field::REAL, SCALAR(), Ioss::Field::MESH, num_nodes));
    fields.add(
        Ioss::Field("node_num_map", Ioss::Field::REAL, SCALAR(), Ioss::Field::MESH, num_nodes));
    fields.add(Ioss::Field("cbmap", Ioss::Field::REAL, SCALAR(), Ioss::Field::MESH,
                           2 * num_nodes * num_dim));
  }

  fields.add(Ioss::Field("Kr", Ioss::Field::REAL, SCALAR(), Ioss::Field::MESH, numDOF * numDOF));

  fields.add(Ioss::Field("Mr", Ioss::Field::REAL, SCALAR(), Ioss::Field::MESH, numDOF * numDOF));

  // There are additional properties and fields on the netcdf file,
  // but for now we only need "Kr" and "Mr"
}
Exemple #10
0
/* in t is the old structure (NULL is possible), newtype is the new type1 of
   the thing and c is for the orientation */
struct thing *changething(struct thing *t, struct thing *clone, int newtype,
                          struct cube *c)
{
    struct thing *t2;
    struct point coords[3];
    int j, i, starts[11];
    size_t size = 0;
    void *data = NULL;
    struct node *n;


    if (t != NULL && newtype == t->type1) {
        return t;
    }

    switch (newtype) {
        case tt1_robot:
            size = init.d_ver >= d2_10_sw ? sizeof(struct D2_robot) :
                   sizeof(struct D1_robot);
            data = init.d_ver >=
                   d2_10_sw ? (void *)&D2_stdrobot : (void *)&D1_stdrobot;
            break;

        case tt1_hostage:
            size = sizeof(struct item);
            data = &stdhostage;
            break;

        case tt1_secretstart: /* secret start */
            size = sizeof(struct start);

            if (l->secretstart) {
                waitmsg(TXT_ONLYONESECRETSTART, l->secretstart->no);
            }

            for (n = l->sdoors.head; n->next != NULL; n = n->next) {
                if (n->d.sd->type == switch_secretexit) {
                    break;
                }
            }

            if (n->next == NULL) {
                waitmsg(TXT_NOSECRETDOORFORSTART);
            }

            data = &stdsecretstart;
            break;

        case tt1_dmstart:
        case tt1_coopstart:
            size = sizeof(struct start);
            data = newtype == tt1_dmstart ? &stdstart : &stdcoopstart;

            if (init.d_ver >= d2_10_sw && newtype == tt1_coopstart) {
                for (n = l->things.head, j = 0; n->next != NULL; n =
                         n->next) {
                    if (n->d.t->type1 == newtype) {
                        j++;
                    }
                }

                ( (struct thing *)data )->type2 = 0;

                if (j >= 4) {
                    waitmsg(TXT_TOOMANYSTARTS);
                }
            }
            else {
                for (i = 0; i < 11; i++) {
                    starts[i] = 0;
                }

                for (n = l->things.head; n->next != NULL; n = n->next) {
                    if (n->d.t->type1 == newtype && n->d.t->type2 < 11) {
                        starts[n->d.t->type2] = 1;
                    }
                }

                for (i = (newtype == 4 ? 0 : 8), j = 0;
                     i < (newtype == 4 ? 8 : 11) && !j; i++) {
                    if (starts[i] == 0) {
                        j = 1;
                        ( (struct thing *)data )->type2 = newtype ==
                                                          4 ? i : 0;
                    }
                }

                if (!j) {
                    waitmsg(TXT_TOOMANYSTARTS);
                }
            }

            break;

        case tt1_mine:
            size = sizeof(struct mine);
            data = &stdmine;
            break;

        case tt1_item:
            size = sizeof(struct item);
            data = &stditem;
            break;

        case tt1_reactor:
            size = sizeof(struct reactor);
            data = &stdreactor;
            break;

        default:
            fprintf(errf, "Unknown thingtype: %d\n", newtype);
            my_assert(0);
    }

    if (clone != NULL) {
        data = clone;
    }

    checkmem( t2 = MALLOC(size) );
    memcpy(t2, data, size);

    if (t != NULL) {
        t2->p[0] = t->p[0];
        t2->nc = t->nc;
        t2->type1 = newtype;
        t2->tagged = t->tagged;
    }
    else {
        t2->nc = NULL;
    }

    if (t != NULL) { /* orientation */
        for (j = 0; j < 9; j++) {
            t2->orientation[j] = t->orientation[j];
        }
    }
    else {
        for (j = 0; j < 3; j++) {
            coords[0].x[j] =
                c->p[wallpts[view.currwall][(view.curredge -
                                             1) & 3]]->d.p->x[j]
                - c->p[wallpts[view.currwall][view.curredge]]->d
                .p->x[j];
            coords[2].x[j] =
                c->p[wallpts[view.currwall][(view.curredge +
                                             1) & 3]]->d.p->x[j]
                - c->p[wallpts[view.currwall][view.curredge]]->d
                .p->x[j];
        }

        normalize(&coords[0]);

        for (j = 0; j < 3; j++) {
            coords[2].x[j] -= SCALAR(&coords[0], &coords[2]) * coords[0].x[j];
        }

        normalize(&coords[2]);
        VECTOR(&coords[1], &coords[2], &coords[0]);

        for (j = 0; j < 3; j++) {
            for (i = 0; i < 3; i++) {
                t2->orientation[j * 3 + i] = coords[j].x[i] * 65536;
            }
        }
    }

    if (t) {
        if (t->nc) {
            for (n = t->nc->d.c->things.head; n->next != NULL; n =
                     n->next)                   {
                if (n->d.t == t) {
                    break;
                }
            }

            if (n->next) {
                n->d.t = t2;
            }
        }

        FREE(t);
    }

    setthingpts(t2);
    setthingcube(t2);
    return t2;
}
/**
 * Simulate a pulsar signal to best accuracy possible.
 * \author Reinhard Prix
 * \date 2005
 *
 * The motivation for this function is to provide functions to
 * simulate pulsar signals <em>with the best possible accuracy</em>,
 * i.e. using no approximations, contrary to LALGeneratePulsarSignal().
 *
 * Obviously this is not meant as a fast code to be used in a Monte-Carlo
 * simulation, but rather as a <em>reference</em> to compare other (faster)
 * functions agains, in order to be able to gauge the quality of a given
 * signal-generation routine.
 *
 * We want to calculate \f$h(t)\f$, given by
 * \f[
 * h(t) = F_+(t)\, h_+(t) + F_\times(t) \,h_\times(t)\,,
 * \f]
 * where \f$F_+\f$ and \f$F_x\f$ are called the <em>beam-pattern</em> functions,
 * which depend of the wave polarization \f$\psi\f$,
 * the source position \f$\alpha\f$, \f$\delta\f$ and the detector position and
 * orientation (\f$\gamma\f$, \f$\lambda\f$, \f$L\f$ and \f$\xi\f$). The expressions for
 * the beam-pattern functions are given in \cite JKS98 , which we write as
 * \f{eqnarray}{
 * F_+(t) = \sin \zeta \cos 2\psi \, a(t)  + \sin \zeta \sin 2\psi \, b(t)\,,\\
 * F_\times(t) = \sin\zeta  \cos 2\psi \,b(t) - \sin\zeta \sin 2\psi \, a(t) \,,
 * \f}
 * where \f$\zeta\f$ is the angle between the interferometer arms, and
 * \f{eqnarray}{
 * a(t) &=& a_1 \cos[ 2 (\alpha - T)) ] + a_2 \sin[ 2(\alpha - T)]
 * + a_3 \cos[ \alpha - T ] + a_4 \sin [ \alpha - T ] + a_5\,,\\
 * b(t) &=& b_1 \cos[ 2(\alpha - T)] + b_2 \sin[ 2(\alpha - T) ]
 * + b_3 \cos[ \alpha - T ] + b_4 \sin[ \alpha - T]\,,
 * \f}
 * where \f$T\f$ is the local (mean) sidereal time of the detector, and the
 * time-independent coefficients \f$a_i\f$ and \f$b_i\f$ are given by
 * \f{eqnarray}{
 * a_1 &=& \frac{1}{16} \sin 2\gamma \,(3- \cos 2\lambda)\,(3 - \cos 2\delta)\,,\\
 * a_2 &=& -\frac{1}{4}\cos 2\gamma \,\sin \lambda \,(3 - \cos 2\delta) \,,\\
 * a_3 &=& \frac{1}{4} \sin 2\gamma \,\sin 2\lambda \,\sin 2\delta  \,\\
 * a_4 &=& -\frac{1}{2} \cos 2\gamma \,\cos \lambda \,\sin 2 \delta\,,\\
 * a_5 &=& \frac{3}{4} \sin 2\gamma \, \cos^2 \lambda \,\cos^2 \delta\,,
 * \f}
 * and
 * \f{eqnarray}{
 * b_1 &=& \cos 2\gamma \,\sin \lambda \,\sin \delta\,,\\
 * b_2 &=& \frac{1}{4} \sin 2\gamma \,(3-\cos 2\lambda)\, \sin \delta\,,\\
 * b_3 &=& \cos 2\gamma \,\cos \lambda \,\cos\delta \,, \\
 * b_4 &=& \frac{1}{2} \sin2\gamma \,\sin 2\lambda \,\cos\delta\,,
 * \f}
 *
 * The source model considered is a plane-wave
 * \f{eqnarray}{
 * h_+(t) &=& A_+\, \cos \Psi(t)\,,\\
 * h_\times(t) &=& A_\times \, \sin \Psi(t)\,,
 * \f}
 * where the wave-phase is \f$\Psi(t) = \Phi_0 + \Phi(t)\f$, and for an
 * isolated pulsar we have
 * \f{equation}{
 * \Phi(t) = 2\pi \left[\sum_{s=0} \frac{f^{(s)}(\tau_\mathrm{ref})}{
 * (s+1)!} \left( \tau(t) - \tau_\mathrm{ref} \right)^{s+1} \right]\,,
 * \f}
 * where \f$\tau_\mathrm{ref}\f$ is the "reference time" for the definition
 * of the pulsar-parameters \f$f^{(s)}\f$ in the solar-system barycenter
 * (SSB), and \f$\tau(t)\f$ is the SSB-time of the phase arriving at the
 * detector at UTC-time \f$t\f$, which depends on the source-position
 * (\f$\alpha\f$, \f$\delta\f$) and the detector-position, namely
 * \f{equation}{
 * \tau (t) = t + \frac{ \vec{r}(t)\cdot\vec{n}}{c}\,,
 * \f}
 * where \f$\vec{r}(t)\f$ is the vector from SSB to the detector, and \f$\vec{n}\f$
 * is the unit-vector pointing <em>to</em> the source.
 *
 * This is a standalone "clean-room" implementation using no other
 * outside-functions <em>except</em> for LALGPStoLMST1() to calculate
 * the local (mean) sidereal time at the detector for given GPS-time,
 * (which I double-checked with an independent Mathematica script),
 * and and XLALBarycenter() to calculate \f$\tau(t)\f$.
 *
 * NOTE: currently only isolated pulsars are supported
 *
 * NOTE2: we don't really use the highest possible accuracy right now,
 * as we blatently neglect all relativistic timing effects (i.e. using dT=v.n/c)
 *
 * NOTE3: no heterodyning is performed here, the time-series is generated and sampled
 * at the given rate, that's all! ==\> the caller needs to make sure about the
 * right sampling rate to use (-\>aliasing) and do the proper post-treatment...
 *
 */
REAL4TimeSeries *
XLALSimulateExactPulsarSignal ( const PulsarSignalParams *params )
{
  XLAL_CHECK_NULL ( params != NULL, XLAL_EINVAL, "Invalid NULL input 'params'\n");
  XLAL_CHECK_NULL ( params->samplingRate > 0, XLAL_EDOM, "Sampling rate must be positive, got samplingRate = %g\n", params->samplingRate );

  /* don't accept heterodyning frequency */
  XLAL_CHECK_NULL ( params->fHeterodyne == 0, XLAL_EINVAL, "Heterodyning frequency must be set to 0, got params->fHeterodyne = %g\n", params->fHeterodyne );

  UINT4 numSpins = 3;

  /* get timestamps of timeseries plus detector-states */
  REAL8 dt = 1.0 / params->samplingRate;
  LIGOTimeGPSVector *timestamps;
  XLAL_CHECK_NULL ( (timestamps = XLALMakeTimestamps ( params->startTimeGPS, params->duration, dt, 0 )) != NULL, XLAL_EFUNC );

  UINT4 numSteps = timestamps->length;

  DetectorStateSeries *detStates = XLALGetDetectorStates ( timestamps, params->site, params->ephemerides, 0 );
  XLAL_CHECK_NULL ( detStates != NULL, XLAL_EFUNC, "XLALGetDetectorStates() failed.\n");

  XLALDestroyTimestampVector ( timestamps );
  timestamps = NULL;

  AMCoeffs *amcoe = XLALComputeAMCoeffs ( detStates, params->pulsar.position );
  XLAL_CHECK_NULL ( amcoe != NULL, XLAL_EFUNC, "XLALComputeAMCoeffs() failed.\n");

  /* create output timeseries (FIXME: should really know *detector* here, not just site!!) */
  const LALFrDetector *site = &(params->site->frDetector);
  CHAR *channel = XLALGetChannelPrefix ( site->name );
  XLAL_CHECK_NULL ( channel != NULL, XLAL_EFUNC, "XLALGetChannelPrefix( %s ) failed.\n", site->name );

  REAL4TimeSeries *ts = XLALCreateREAL4TimeSeries ( channel, &(detStates->data[0].tGPS), 0, dt, &emptyUnit, numSteps );
  XLAL_CHECK_NULL ( ts != NULL, XLAL_EFUNC, "XLALCreateREAL4TimeSeries() failed.\n");
  XLALFree ( channel );
  channel = NULL;

  /* orientation of detector arms */
  REAL8 xAzi = site->xArmAzimuthRadians;
  REAL8 yAzi = site->yArmAzimuthRadians;
  REAL8 Zeta =  xAzi - yAzi;
  if (Zeta < 0) {
    Zeta = -Zeta;
  }
  if ( params->site->type == LALDETECTORTYPE_CYLBAR ) {
    Zeta = LAL_PI_2;
  }
  REAL8 sinZeta = sin(Zeta);

  /* get source skyposition */
  REAL8 Alpha = params->pulsar.position.longitude;
  REAL8 Delta = params->pulsar.position.latitude;
  REAL8 vn[3];
  vn[0] = cos(Delta) * cos(Alpha);
  vn[1] = cos(Delta) * sin(Alpha);
  vn[2] = sin(Delta);

  /* get spin-parameters (restricted to maximally 3 spindowns right now) */
  REAL8 phi0 = params->pulsar.phi0;
  REAL8 f0   = params->pulsar.f0;

  REAL8 f1dot = 0, f2dot = 0, f3dot = 0;
  if ( params->pulsar.spindown && (params->pulsar.spindown->length > numSpins) ) {
    XLAL_ERROR_NULL ( XLAL_EDOM, "Currently only supports up to %d spindowns!\n", numSpins );
  }
  if ( params->pulsar.spindown && (params->pulsar.spindown->length >= 3 ) ) {
    f3dot = params->pulsar.spindown->data[2];
  }
  if ( params->pulsar.spindown && (params->pulsar.spindown->length >= 2 ) ) {
    f2dot = params->pulsar.spindown->data[1];
  }
  if ( params->pulsar.spindown && (params->pulsar.spindown->length >= 1 ) ) {
    f1dot = params->pulsar.spindown->data[0];
  }

  /* internally we always work with refTime = startTime->SSB, therefore
   * we need to translate the pulsar spin-params and initial phase to the
   * startTime
   */
  REAL8 startTimeSSB = XLALGPSGetREAL8 ( &(detStates->data[0].tGPS) ) + SCALAR ( vn, detStates->data[0].rDetector );
  REAL8 refTime;
  if ( params->pulsar.refTime.gpsSeconds != 0 )
    {
      REAL8 refTime0 = XLALGPSGetREAL8 ( &(params->pulsar.refTime) );
      REAL8 deltaRef = startTimeSSB - refTime0;
      LIGOTimeGPS newEpoch;
      PulsarSpins fkdotNew;

      XLALGPSSetREAL8( &newEpoch, startTimeSSB );

      PulsarSpins XLAL_INIT_DECL(fkdotOld);
      fkdotOld[0] = f0;
      fkdotOld[1] = f1dot;
      fkdotOld[2] = f2dot;
      fkdotOld[3] = f3dot;
      REAL8 DeltaTau = XLALGPSDiff ( &newEpoch, &(params->pulsar.refTime) );

      int ret = XLALExtrapolatePulsarSpins ( fkdotNew, fkdotOld, DeltaTau );
      XLAL_CHECK_NULL ( ret == XLAL_SUCCESS, XLAL_EFUNC, "XLALExtrapolatePulsarSpins() failed.\n");

      /* Finally, need to propagate phase */
      phi0 += LAL_TWOPI * (               f0    * deltaRef
			    + (1.0/2.0) * f1dot * deltaRef * deltaRef
			    + (1.0/6.0) * f2dot * deltaRef * deltaRef * deltaRef
			    + (1.0/24.0)* f3dot * deltaRef * deltaRef * deltaRef * deltaRef
			    );

      f0    = fkdotNew[0];
      f1dot = fkdotNew[1];
      f2dot = fkdotNew[2];
      f3dot = fkdotNew[3];

      refTime = startTimeSSB;

    } /* if refTime given */
  else  { /* if not given: use startTime -> SSB */
    refTime = startTimeSSB;
  }

  /* get 4 amplitudes A_\mu */
  REAL8 aPlus  = sinZeta * params->pulsar.aPlus;
  REAL8 aCross = sinZeta * params->pulsar.aCross;
  REAL8 twopsi = 2.0 * params->pulsar.psi;

  REAL8 A1 =  aPlus * cos(phi0) * cos(twopsi) - aCross * sin(phi0) * sin(twopsi);
  REAL8 A2 =  aPlus * cos(phi0) * sin(twopsi) + aCross * sin(phi0) * cos(twopsi);
  REAL8 A3 = -aPlus * sin(phi0) * cos(twopsi) - aCross * cos(phi0) * sin(twopsi);
  REAL8 A4 = -aPlus * sin(phi0) * sin(twopsi) + aCross * cos(phi0) * cos(twopsi);

  /* main loop: generate time-series */
  for ( UINT4 i = 0; i < numSteps; i++)
    {
      LIGOTimeGPS *tiGPS = &(detStates->data[i].tGPS);

      REAL8 ti = XLALGPSGetREAL8 ( tiGPS );
      REAL8 deltati = ti - refTime;
      REAL8 dT = SCALAR(vn, detStates->data[i].rDetector );
      REAL8 taui = deltati + dT;

      REAL8 phi_i = LAL_TWOPI * ( f0 * taui
			    + (1.0/2.0) * f1dot * taui*taui
			    + (1.0/6.0) * f2dot * taui*taui*taui
			    + (1.0/24.0)* f3dot * taui*taui*taui*taui
			    );

      REAL8 cosphi_i = cos(phi_i);
      REAL8 sinphi_i = sin(phi_i);

      REAL8 ai = amcoe->a->data[i];
      REAL8 bi = amcoe->b->data[i];

      REAL8 hi = A1 * ai * cosphi_i
	+  A2 * bi * cosphi_i
	+  A3 * ai * sinphi_i
	+  A4 * bi * sinphi_i;

      ts->data->data[i] = (REAL4)hi;

    } /* for i < numSteps */

  XLALDestroyDetectorStateSeries( detStates );
  XLALDestroyAMCoeffs ( amcoe );

  return ts;

} /* XLALSimulateExactPulsarSignal() */