/** * FSAL_proxy_setclientid_force: * Client ID negociation * * \param p_context (input): * Authentication context for the operation (user,...). * * \return Major error codes : * - ERR_FSAL_NO_ERROR (no error) * - ERR_FSAL_FAULT (a NULL pointer was passed as mandatory argument) * - Other error codes can be returned : * ERR_FSAL_ACCESS, ERR_FSAL_IO, ... */ fsal_status_t FSAL_proxy_setclientid_force(proxyfsal_op_context_t * p_context) { int rc; fsal_status_t fsal_status; COMPOUND4args argnfs4; COMPOUND4res resnfs4; #define FSAL_CLIENTID_NB_OP_ALLOC 1 nfs_argop4 argoparray[FSAL_CLIENTID_NB_OP_ALLOC]; nfs_resop4 resoparray[FSAL_CLIENTID_NB_OP_ALLOC]; nfs_client_id4 nfsclientid; cb_client4 cbproxy; char clientid_name[MAXNAMLEN]; char cbaddr[MAXNAMLEN]; char cbnetid[MAXNAMLEN]; clientid4 resultclientid; struct timeval timeout = TIMEOUTRPC; LogEvent( COMPONENT_FSAL, "Negociating a new ClientId with the remote server" ) ; /* sanity checks. */ if(!p_context) Return(ERR_FSAL_FAULT, 0, INDEX_FSAL_InitClientContext); /* Client id negociation is to be done only one time for the whole FSAL */ P(fsal_clientid_mutex_renew); /* Setup results structures */ argnfs4.argarray.argarray_val = argoparray; resnfs4.resarray.resarray_val = resoparray; argnfs4.minorversion = 0; argnfs4.tag.utf8string_val = NULL; argnfs4.tag.utf8string_len = 0; argnfs4.argarray.argarray_len = 0; snprintf(clientid_name, MAXNAMLEN, "GANESHA NFSv4 Proxy Pid=%u", getpid()); nfsclientid.id.id_len = strlen(clientid_name); nfsclientid.id.id_val = clientid_name; snprintf(nfsclientid.verifier, NFS4_VERIFIER_SIZE, "%x", (int)ServerBootTime); cbproxy.cb_program = 0; strncpy(cbnetid, "tcp", MAXNAMLEN); strncpy(cbaddr, "127.0.0.1", MAXNAMLEN); #ifdef _USE_NFS4_1 cbproxy.cb_location.na_r_netid = cbnetid; cbproxy.cb_location.na_r_addr = cbaddr; #else cbproxy.cb_location.r_netid = cbnetid; cbproxy.cb_location.r_addr = cbaddr; #endif COMPOUNDV4_ARG_ADD_OP_SETCLIENTID(argnfs4, nfsclientid, cbproxy); TakeTokenFSCall(); p_context->user_credential.user = 0; p_context->user_credential.group = 0; p_context->user_credential.nbgroups = 0; /* Call the NFSv4 function */ rc = COMPOUNDV4_EXECUTE_SIMPLE(p_context, argnfs4, resnfs4); if(rc != RPC_SUCCESS) { ReleaseTokenFSCall(); V(fsal_clientid_mutex_renew); Return(ERR_FSAL_IO, rc, INDEX_FSAL_unlink); } ReleaseTokenFSCall(); if(resnfs4.status != NFS4_OK) { V(fsal_clientid_mutex_renew); return fsal_internal_proxy_error_convert(resnfs4.status, INDEX_FSAL_InitClientContext); } resultclientid = resnfs4.resarray.resarray_val[0].nfs_resop4_u.opsetclientid.SETCLIENTID4res_u. resok4.clientid; /* Step 2: Confirm the client id */ argnfs4.minorversion = 0; argnfs4.tag.utf8string_val = NULL; argnfs4.tag.utf8string_len = 0; argnfs4.argarray.argarray_len = 0; argnfs4.argarray.argarray_val[0].argop = NFS4_OP_SETCLIENTID_CONFIRM; argnfs4.argarray.argarray_val[0].nfs_argop4_u.opsetclientid_confirm.clientid = resnfs4.resarray.resarray_val[0].nfs_resop4_u.opsetclientid.SETCLIENTID4res_u. resok4.clientid; memcpy((char *)argnfs4.argarray.argarray_val[0].nfs_argop4_u.opsetclientid_confirm. setclientid_confirm, (char *)resnfs4.resarray.resarray_val[0].nfs_resop4_u.opsetclientid. SETCLIENTID4res_u.resok4.setclientid_confirm, NFS4_VERIFIER_SIZE); argnfs4.argarray.argarray_len = 1; /* Call the NFSv4 function */ rc = COMPOUNDV4_EXECUTE_SIMPLE(p_context, argnfs4, resnfs4); if(rc != RPC_SUCCESS) { ReleaseTokenFSCall(); V(fsal_clientid_mutex_renew); Return(ERR_FSAL_IO, rc, INDEX_FSAL_unlink); } ReleaseTokenFSCall(); if(resnfs4.status != NFS4_OK) return fsal_internal_proxy_error_convert(resnfs4.status, INDEX_FSAL_InitClientContext); /* Keep the confirmed client id */ fsal_clientid = argnfs4.argarray.argarray_val[0].nfs_argop4_u.opsetclientid_confirm.clientid; clientid_renewed = time( NULL ) ; V(fsal_clientid_mutex_renew); p_context->clientid = fsal_clientid; p_context->last_lease_renewal = 0; /* Needs to be renewed */ fsal_status.major = ERR_FSAL_NO_ERROR; fsal_status.minor = 0; return fsal_status; } /* FSAL_proxy_setclientid_force */
vector Cart(float r, float t) { return V(r*cos(t),r*sin(t)); }
/* Subroutine */ int dggsvd_(char *jobu, char *jobv, char *jobq, integer *m, integer *n, integer *p, integer *k, integer *l, doublereal *a, integer *lda, doublereal *b, integer *ldb, doublereal *alpha, doublereal *beta, doublereal *u, integer *ldu, doublereal *v, integer *ldv, doublereal *q, integer *ldq, doublereal *work, integer *iwork, integer *info) { /* -- LAPACK driver 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 ======= DGGSVD computes the generalized singular value decomposition (GSVD) of an M-by-N real matrix A and P-by-N real matrix B: U'*A*Q = D1*( 0 R ), V'*B*Q = D2*( 0 R ) where U, V and Q are orthogonal matrices, and Z' is the transpose of Z. Let K+L = the effective numerical rank of the matrix (A',B')', then R is a K+L-by-K+L nonsingular upper triangular matrix, D1 and D2 are M-by-(K+L) and P-by-(K+L) "diagonal" matrices and of the following structures, respectively: If M-K-L >= 0, K L D1 = K ( I 0 ) L ( 0 C ) M-K-L ( 0 0 ) K L D2 = L ( 0 S ) P-L ( 0 0 ) N-K-L K L ( 0 R ) = K ( 0 R11 R12 ) L ( 0 0 R22 ) where C = diag( ALPHA(K+1), ... , ALPHA(K+L) ), S = diag( BETA(K+1), ... , BETA(K+L) ), C**2 + S**2 = I. R is stored in A(1:K+L,N-K-L+1:N) on exit. If M-K-L < 0, K M-K K+L-M D1 = K ( I 0 0 ) M-K ( 0 C 0 ) K M-K K+L-M D2 = M-K ( 0 S 0 ) K+L-M ( 0 0 I ) P-L ( 0 0 0 ) N-K-L K M-K K+L-M ( 0 R ) = K ( 0 R11 R12 R13 ) M-K ( 0 0 R22 R23 ) K+L-M ( 0 0 0 R33 ) where C = diag( ALPHA(K+1), ... , ALPHA(M) ), S = diag( BETA(K+1), ... , BETA(M) ), C**2 + S**2 = I. (R11 R12 R13 ) is stored in A(1:M, N-K-L+1:N), and R33 is stored ( 0 R22 R23 ) in B(M-K+1:L,N+M-K-L+1:N) on exit. The routine computes C, S, R, and optionally the orthogonal transformation matrices U, V and Q. In particular, if B is an N-by-N nonsingular matrix, then the GSVD of A and B implicitly gives the SVD of A*inv(B): A*inv(B) = U*(D1*inv(D2))*V'. If ( A',B')' has orthonormal columns, then the GSVD of A and B is also equal to the CS decomposition of A and B. Furthermore, the GSVD can be used to derive the solution of the eigenvalue problem: A'*A x = lambda* B'*B x. In some literature, the GSVD of A and B is presented in the form U'*A*X = ( 0 D1 ), V'*B*X = ( 0 D2 ) where U and V are orthogonal and X is nonsingular, D1 and D2 are ``diagonal''. The former GSVD form can be converted to the latter form by taking the nonsingular matrix X as X = Q*( I 0 ) ( 0 inv(R) ). Arguments ========= JOBU (input) CHARACTER*1 = 'U': Orthogonal matrix U is computed; = 'N': U is not computed. JOBV (input) CHARACTER*1 = 'V': Orthogonal matrix V is computed; = 'N': V is not computed. JOBQ (input) CHARACTER*1 = 'Q': Orthogonal matrix Q is computed; = 'N': Q is not computed. M (input) INTEGER The number of rows of the matrix A. M >= 0. N (input) INTEGER The number of columns of the matrices A and B. N >= 0. P (input) INTEGER The number of rows of the matrix B. P >= 0. K (output) INTEGER L (output) INTEGER On exit, K and L specify the dimension of the subblocks described in the Purpose section. K + L = effective numerical rank of (A',B')'. A (input/output) DOUBLE PRECISION array, dimension (LDA,N) On entry, the M-by-N matrix A. On exit, A contains the triangular matrix R, or part of R. See Purpose for details. LDA (input) INTEGER The leading dimension of the array A. LDA >= max(1,M). B (input/output) DOUBLE PRECISION array, dimension (LDB,N) On entry, the P-by-N matrix B. On exit, B contains the triangular matrix R if M-K-L < 0. See Purpose for details. LDB (input) INTEGER The leading dimension of the array B. LDA >= max(1,P). ALPHA (output) DOUBLE PRECISION array, dimension (N) BETA (output) DOUBLE PRECISION array, dimension (N) On exit, ALPHA and BETA contain the generalized singular value pairs of A and B; ALPHA(1:K) = 1, BETA(1:K) = 0, and if M-K-L >= 0, ALPHA(K+1:K+L) = C, BETA(K+1:K+L) = S, or if M-K-L < 0, ALPHA(K+1:M)=C, ALPHA(M+1:K+L)=0 BETA(K+1:M) =S, BETA(M+1:K+L) =1 and ALPHA(K+L+1:N) = 0 BETA(K+L+1:N) = 0 U (output) DOUBLE PRECISION array, dimension (LDU,M) If JOBU = 'U', U contains the M-by-M orthogonal matrix U. If JOBU = 'N', U is not referenced. LDU (input) INTEGER The leading dimension of the array U. LDU >= max(1,M) if JOBU = 'U'; LDU >= 1 otherwise. V (output) DOUBLE PRECISION array, dimension (LDV,P) If JOBV = 'V', V contains the P-by-P orthogonal matrix V. If JOBV = 'N', V is not referenced. LDV (input) INTEGER The leading dimension of the array V. LDV >= max(1,P) if JOBV = 'V'; LDV >= 1 otherwise. Q (output) DOUBLE PRECISION array, dimension (LDQ,N) If JOBQ = 'Q', Q contains the N-by-N orthogonal matrix Q. If JOBQ = 'N', Q is not referenced. LDQ (input) INTEGER The leading dimension of the array Q. LDQ >= max(1,N) if JOBQ = 'Q'; LDQ >= 1 otherwise. WORK (workspace) DOUBLE PRECISION array, dimension (max(3*N,M,P)+N) IWORK (workspace) INTEGER array, dimension (N) INFO (output)INTEGER = 0: successful exit < 0: if INFO = -i, the i-th argument had an illegal value. > 0: if INFO = 1, the Jacobi-type procedure failed to converge. For further details, see subroutine DTGSJA. Internal Parameters =================== TOLA DOUBLE PRECISION TOLB DOUBLE PRECISION TOLA and TOLB are the thresholds to determine the effective rank of (A',B')'. Generally, they are set to TOLA = MAX(M,N)*norm(A)*MAZHEPS, TOLB = MAX(P,N)*norm(B)*MAZHEPS. The size of TOLA and TOLB may affect the size of backward errors of the decomposition. ===================================================================== Test the input parameters Parameter adjustments Function Body */ /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, q_dim1, q_offset, u_dim1, u_offset, v_dim1, v_offset, i__1; /* Local variables */ static doublereal tola, tolb, unfl; extern logical lsame_(char *, char *); static doublereal anorm, bnorm; static logical wantq, wantu, wantv; extern doublereal dlamch_(char *), dlange_(char *, integer *, integer *, doublereal *, integer *, doublereal *); extern /* Subroutine */ int dtgsja_(char *, char *, char *, integer *, integer *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *); static integer ncycle; extern /* Subroutine */ int xerbla_(char *, integer *), dggsvp_( char *, char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, integer *, doublereal *, doublereal *, integer *); static doublereal ulp; #define ALPHA(I) alpha[(I)-1] #define BETA(I) beta[(I)-1] #define WORK(I) work[(I)-1] #define IWORK(I) iwork[(I)-1] #define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)] #define B(I,J) b[(I)-1 + ((J)-1)* ( *ldb)] #define U(I,J) u[(I)-1 + ((J)-1)* ( *ldu)] #define V(I,J) v[(I)-1 + ((J)-1)* ( *ldv)] #define Q(I,J) q[(I)-1 + ((J)-1)* ( *ldq)] wantu = lsame_(jobu, "U"); wantv = lsame_(jobv, "V"); wantq = lsame_(jobq, "Q"); *info = 0; if (! (wantu || lsame_(jobu, "N"))) { *info = -1; } else if (! (wantv || lsame_(jobv, "N"))) { *info = -2; } else if (! (wantq || lsame_(jobq, "N"))) { *info = -3; } else if (*m < 0) { *info = -4; } else if (*n < 0) { *info = -5; } else if (*p < 0) { *info = -6; } else if (*lda < max(1,*m)) { *info = -10; } else if (*ldb < max(1,*p)) { *info = -12; } else if (*ldu < 1 || wantu && *ldu < *m) { *info = -16; } else if (*ldv < 1 || wantv && *ldv < *p) { *info = -18; } else if (*ldq < 1 || wantq && *ldq < *n) { *info = -20; } if (*info != 0) { i__1 = -(*info); xerbla_("DGGSVD", &i__1); return 0; } /* Compute the Frobenius norm of matrices A and B */ anorm = dlange_("1", m, n, &A(1,1), lda, &WORK(1)); bnorm = dlange_("1", p, n, &B(1,1), ldb, &WORK(1)); /* Get machine precision and set up threshold for determining the effective numerical rank of the matrices A and B. */ ulp = dlamch_("Precision"); unfl = dlamch_("Safe Minimum"); tola = max(*m,*n) * max(anorm,unfl) * ulp; tolb = max(*p,*n) * max(bnorm,unfl) * ulp; /* Preprocessing */ dggsvp_(jobu, jobv, jobq, m, p, n, &A(1,1), lda, &B(1,1), ldb, & tola, &tolb, k, l, &U(1,1), ldu, &V(1,1), ldv, &Q(1,1), ldq, &IWORK(1), &WORK(1), &WORK(*n + 1), info); /* Compute the GSVD of two upper "triangular" matrices */ dtgsja_(jobu, jobv, jobq, m, p, n, k, l, &A(1,1), lda, &B(1,1), ldb, &tola, &tolb, &ALPHA(1), &BETA(1), &U(1,1), ldu, &V(1,1), ldv, &Q(1,1), ldq, &WORK(1), &ncycle, info); return 0; /* End of DGGSVD */ } /* dggsvd_ */
void test_uloc(void) { ZNotice_t z1, z2, z0, z4; String *s1, *s2, *s0, *s4; struct sockaddr_in who1, who2, who3, who0, who4; int ret; puts("uloc storage routines"); TEST(ulogin_find_user("nonexistent") == -1); /* fake up just enough */ who1.sin_family = AF_INET; who1.sin_port = 1; who1.sin_addr.s_addr = INADDR_LOOPBACK; z1.z_class_inst = "user1"; z1.z_port = 1; z1.z_message = "here\0now\0this\0"; z1.z_message_len = 14; s1 = make_string(z1.z_class_inst, 0); TEST(ulogin_add_user(&z1, NET_ANN, &who1) == 0); TEST(ulogin_find_user("user1") != -1); who2.sin_family = AF_INET; who2.sin_port = 2; who2.sin_addr.s_addr = INADDR_LOOPBACK; z2.z_class_inst = "user2"; z2.z_port = 2; z2.z_message = "here\0now\0this\0"; z2.z_message_len = 14; s2 = make_string(z2.z_class_inst, 0); TEST(ulogin_add_user(&z2, NET_ANN, &who2) == 0); TEST(ulogin_find_user("user2") != -1); TEST(locations[ulogin_find_user("user1")].user == s1); TEST(locations[ulogin_find_user("user2")].user == s2); TEST(ulogin_add_user(&z1, NET_ANN, &who1) == 0); TEST(locations[ulogin_find_user("user1")].user == s1); TEST(locations[ulogin_find_user("user2")].user == s2); who3.sin_family = AF_INET; who3.sin_port = 3; who3.sin_addr.s_addr = INADDR_LOOPBACK; TEST(ulogin_find("user1", &who3.sin_addr, 3) == -1); who0.sin_family = AF_INET; who0.sin_port = 3; who0.sin_addr.s_addr = INADDR_LOOPBACK; z0.z_class_inst = "user0"; z0.z_port = 3; z0.z_message = "here\0now\0this\0"; z0.z_message_len = 14; s0 = make_string(z0.z_class_inst, 0); TEST(ulogin_add_user(&z0, NET_ANN, &who0) == 0); TEST(ulogin_find_user("user0") != -1); TEST(locations[ulogin_find_user("user1")].user == s1); TEST(locations[ulogin_find_user("user2")].user == s2); TEST(ulogin_remove_user(&z0, &who0, &ret) == NET_ANN && ret == 0); /* 1 = NOLOC */ TEST(ulogin_remove_user(&z0, &who0, &ret) == NONE && ret == 1); TEST(ulogin_add_user(&z0, NET_ANN, &who0) == 0); TEST(ulogin_remove_user(&z1, &who0, &ret) == NET_ANN && ret == 0); V(ulogin_flush_user(&z0)); TEST(ulogin_find_user("user0") == -1); TEST(ulogin_add_user(&z0, NET_ANN, &who0) == 0); TEST(ulogin_add_user(&z1, NET_ANN, &who1) == 0); V(ulogin_flush_user(&z1)); TEST(ulogin_find_user("user1") == -1); who4.sin_family = AF_INET; who4.sin_port = 4; who4.sin_addr.s_addr = INADDR_ANY; z4.z_class_inst = "user4"; z4.z_port = 4; z4.z_message = "here\0now\0this\0"; z4.z_message_len = 14; s4 = make_string(z4.z_class_inst, 0); TEST(ulogin_add_user(&z4, NET_ANN, &who4) == 0); V(uloc_flush_client(&who2)); TEST(locations[ulogin_find_user("user0")].user == s0); TEST(ulogin_find_user("user1") == -1); TEST(ulogin_find_user("user2") == -1); TEST(locations[ulogin_find_user("user4")].user == s4); V(uloc_hflush(&who0.sin_addr)); TEST(ulogin_find_user("user0") == -1); TEST(ulogin_find_user("user1") == -1); TEST(ulogin_find_user("user2") == -1); TEST(locations[ulogin_find_user("user4")].user == s4); }
/* Subroutine */ int zggbak_(char *job, char *side, integer *n, integer *ilo, integer *ihi, doublereal *lscale, doublereal *rscale, integer *m, doublecomplex *v, integer *ldv, 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 ======= ZGGBAK forms the right or left eigenvectors of a complex generalized eigenvalue problem A*x = lambda*B*x, by backward transformation on the computed eigenvectors of the balanced pair of matrices output by ZGGBAL. Arguments ========= JOB (input) CHARACTER*1 Specifies the type of backward transformation required: = 'N': do nothing, return immediately; = 'P': do backward transformation for permutation only; = 'S': do backward transformation for scaling only; = 'B': do backward transformations for both permutation and scaling. JOB must be the same as the argument JOB supplied to ZGGBAL. SIDE (input) CHARACTER*1 = 'R': V contains right eigenvectors; = 'L': V contains left eigenvectors. N (input) INTEGER The number of rows of the matrix V. N >= 0. ILO (input) INTEGER IHI (input) INTEGER The integers ILO and IHI determined by ZGGBAL. 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. LSCALE (input) DOUBLE PRECISION array, dimension (N) Details of the permutations and/or scaling factors applied to the left side of A and B, as returned by ZGGBAL. RSCALE (input) DOUBLE PRECISION array, dimension (N) Details of the permutations and/or scaling factors applied to the right side of A and B, as returned by ZGGBAL. M (input) INTEGER The number of columns of the matrix V. M >= 0. V (input/output) COMPLEX*16 array, dimension (LDV,M) On entry, the matrix of right or left eigenvectors to be transformed, as returned by ZTGEVC. On exit, V is overwritten by the transformed eigenvectors. LDV (input) INTEGER The leading dimension of the matrix V. LDV >= max(1,N). INFO (output) INTEGER = 0: successful exit. < 0: if INFO = -i, the i-th argument had an illegal value. Further Details =============== See R.C. Ward, Balancing the generalized eigenvalue problem, SIAM J. Sci. Stat. Comp. 2 (1981), 141-152. ===================================================================== Test the input parameters Parameter adjustments Function Body */ /* System generated locals */ integer v_dim1, v_offset, i__1; /* Local variables */ static integer i, k; extern logical lsame_(char *, char *); static logical leftv; extern /* Subroutine */ int zswap_(integer *, doublecomplex *, integer *, doublecomplex *, integer *), xerbla_(char *, integer *), zdscal_(integer *, doublereal *, doublecomplex *, integer *); static logical rightv; #define LSCALE(I) lscale[(I)-1] #define RSCALE(I) rscale[(I)-1] #define V(I,J) v[(I)-1 + ((J)-1)* ( *ldv)] rightv = lsame_(side, "R"); leftv = lsame_(side, "L"); *info = 0; if (! lsame_(job, "N") && ! lsame_(job, "P") && ! lsame_( job, "S") && ! lsame_(job, "B")) { *info = -1; } else if (! rightv && ! leftv) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*ilo < 1) { *info = -4; } else if (*ihi < *ilo || *ihi > max(1,*n)) { *info = -5; } else if (*m < 0) { *info = -6; } else if (*ldv < max(1,*n)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("ZGGBAK", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (*m == 0) { return 0; } if (lsame_(job, "N")) { return 0; } if (*ilo == *ihi) { goto L30; } /* Backward balance */ if (lsame_(job, "S") || lsame_(job, "B")) { /* Backward transformation on right eigenvectors */ if (rightv) { i__1 = *ihi; for (i = *ilo; i <= *ihi; ++i) { zdscal_(m, &RSCALE(i), &V(i,1), ldv); /* L10: */ } } /* Backward transformation on left eigenvectors */ if (leftv) { i__1 = *ihi; for (i = *ilo; i <= *ihi; ++i) { zdscal_(m, &LSCALE(i), &V(i,1), ldv); /* L20: */ } } } /* Backward permutation */ L30: if (lsame_(job, "P") || lsame_(job, "B")) { /* Backward permutation on right eigenvectors */ if (rightv) { if (*ilo == 1) { goto L50; } for (i = *ilo - 1; i >= 1; --i) { k = (integer) RSCALE(i); if (k == i) { goto L40; } zswap_(m, &V(i,1), ldv, &V(k,1), ldv); L40: ; } L50: if (*ihi == *n) { goto L70; } i__1 = *n; for (i = *ihi + 1; i <= *n; ++i) { k = (integer) RSCALE(i); if (k == i) { goto L60; } zswap_(m, &V(i,1), ldv, &V(k,1), ldv); L60: ; } } /* Backward permutation on left eigenvectors */ L70: if (leftv) { if (*ilo == 1) { goto L90; } for (i = *ilo - 1; i >= 1; --i) { k = (integer) LSCALE(i); if (k == i) { goto L80; } zswap_(m, &V(i,1), ldv, &V(k,1), ldv); L80: ; } L90: if (*ihi == *n) { goto L110; } i__1 = *n; for (i = *ihi + 1; i <= *n; ++i) { k = (integer) LSCALE(i); if (k == i) { goto L100; } zswap_(m, &V(i,1), ldv, &V(k,1), ldv); L100: ; } } } L110: return 0; /* End of ZGGBAK */ } /* zggbak_ */
int UbermasterProcess::main_loop() { boost::timer::auto_cpu_timer t; program_options.splash_screen(); //parse the options program_options.startup(); // tests for existence of necessary files, etc. //if desired, display the options if (program_options.verbose_level()>=3) program_options.display_current_options(); parse_preproc_data("preproc_data", &solve_options.PPD); int num_vars = get_num_vars_PPD(solve_options.PPD); NumericalIrreducibleDecomposition witness_data; witness_data.populate(&solve_options.T); WitnessSet W = witness_data.choose(program_options); if (W.num_points()==0) { std::cout << "no witness points, cannot decompose anything..." << std::endl; return 1; } W.get_variable_names(num_vars); W.set_input_filename(program_options.input_filename()); if (program_options.verbose_level()>=1) { W.print_to_screen(); } VertexSet V(num_vars); V.set_tracker_config(&solve_options.T); V.set_same_point_tolerance(1e1*solve_options.T.real_threshold); vec_mp *pi = (vec_mp *) br_malloc(W.dimension()*sizeof(vec_mp )); for (int ii=0; ii<W.dimension(); ii++) { init_vec_mp2(pi[ii],W.num_variables(), solve_options.T.AMP_max_prec); pi[ii]->size = W.num_variables(); } get_projection(pi, program_options, W.num_variables(), W.dimension()); for (int ii=0; ii<W.dimension(); ii++) { V.add_projection(pi[ii]); } if (program_options.primary_mode()==BERTINIREAL) { bertini_real(W,pi,V); } else if(program_options.primary_mode()==CRIT) { critreal(W,pi,V); } for (int ii=0; ii<W.dimension(); ii++) clear_vec_mp(pi[ii]); free(pi); // dismiss the workers int sendme = TERMINATE; MPI_Bcast(&sendme, 1, MPI_INT, 0, MPI_COMM_WORLD); return SUCCESSFUL; }
static void magma_ctile_bulge_applyQ( magma_int_t core_id, magma_side_t side, magma_int_t n_loc, magma_int_t n, magma_int_t nb, magma_int_t Vblksiz, magmaFloatComplex *E, magma_int_t lde, magmaFloatComplex *V, magma_int_t ldv, magmaFloatComplex *TAU, magmaFloatComplex *T, magma_int_t ldt) //, magma_int_t* info) { //%=========================== //% local variables //%=========================== magma_int_t firstcolj; magma_int_t bg, rownbm; magma_int_t st,ed,fst,vlen,vnb,colj; magma_int_t vpos,tpos; magma_int_t cur_blksiz,avai_blksiz, ncolinvolvd; magma_int_t nbgr, colst, coled; if (n <= 0) return; if (n_loc <= 0) return; //info = 0; magma_int_t INFO=0; magma_int_t nbGblk = magma_ceildiv(n-1, Vblksiz); /* * version v1: for each chunck it apply all the V's then move to * the other chunck. the locality here inside each * chunck meaning that thread t apply V_k then move * to V_k+1 which overlap with V_k meaning that the * E_k+1 overlap with E_k. so here is the * locality however thread t had to read V_k+1 and * T_k+1 at each apply. note that all thread if they * run at same speed they might reading the same V_k * and T_k at the same time. * */ magma_int_t nb_loc = 128; //$$$$$$$$ magma_int_t lwork = 2*nb_loc*max(Vblksiz,64); magmaFloatComplex *work, *work2; magma_cmalloc_cpu(&work, lwork); magma_cmalloc_cpu(&work2, lwork); magma_int_t nbchunk = magma_ceildiv(n_loc, nb_loc); /* SIDE LEFT meaning apply E = Q*E = (q_1*q_2*.....*q_n) * E ==> so traverse Vs in reverse order (forward) from q_n to q_1 * each q_i consist of applying V to a block of row E(row_i,:) and applies are overlapped meaning * that q_i+1 overlap a portion of the E(row_i, :). * IN parallel E is splitten in vertical block over the threads */ /* SIDE RIGHT meaning apply E = E*Q = E * (q_1*q_2*.....*q_n) ==> so tarverse Vs in normal order (forward) from q_1 to q_n * each q_i consist of applying V to a block of col E(:, col_i,:) and the applies are overlapped meaning * that q_i+1 overlap a portion of the E(:, col_i). * IN parallel E is splitten in horizontal block over the threads */ #ifdef ENABLE_DEBUG if ((core_id == 0) || (core_id == 1)) printf(" APPLY Q2_cpu cbulge_back_m N %d N_loc %d nbchunk %d NB %d Vblksiz %d SIDE %c \n", n, n_loc, nbchunk, nb, Vblksiz, side); #endif for (magma_int_t i = 0; i < nbchunk; i++) { magma_int_t ib_loc = min(nb_loc, (n_loc - i*nb_loc)); if (side == MagmaLeft) { for (bg = nbGblk; bg > 0; bg--) { firstcolj = (bg-1)*Vblksiz + 1; rownbm = magma_ceildiv((n-(firstcolj+1)),nb); if (bg == nbGblk) rownbm = magma_ceildiv((n-(firstcolj)),nb); // last blk has size=1 used for complex to handle A(N,N-1) for (magma_int_t j = rownbm; j > 0; j--) { vlen = 0; vnb = 0; colj = (bg-1)*Vblksiz; // for k=0; I compute the fst and then can remove it from the loop fst = (rownbm -j)*nb+colj +1; for (magma_int_t k=0; k < Vblksiz; k++) { colj = (bg-1)*Vblksiz + k; st = (rownbm -j)*nb+colj +1; ed = min(st+nb-1,n-1); if (st > ed) break; if ((st == ed) && (colj != n-2)) break; vlen=ed-fst+1; vnb=k+1; } colst = (bg-1)*Vblksiz; magma_bulge_findVTpos(n, nb, Vblksiz, colst, fst, ldv, ldt, &vpos, &tpos); if ((vlen > 0) && (vnb > 0)) { lapackf77_clarfb( "L", "N", "F", "C", &vlen, &ib_loc, &vnb, V(vpos), &ldv, T(tpos), &ldt, E(fst,i*nb_loc), &lde, work, &ib_loc); } if (INFO != 0) printf("ERROR CUNMQR INFO %d \n", (int) INFO); } } } else if (side == MagmaRight) { rownbm = magma_ceildiv((n-1),nb); for (magma_int_t k = 1; k <= rownbm; k++) { ncolinvolvd = min(n-1, k*nb); avai_blksiz=min(Vblksiz,ncolinvolvd); nbgr = magma_ceildiv(ncolinvolvd,avai_blksiz); for (magma_int_t j = 1; j <= nbgr; j++) { vlen = 0; vnb = 0; cur_blksiz = min(ncolinvolvd-(j-1)*avai_blksiz, avai_blksiz); colst = (j-1)*avai_blksiz; coled = colst + cur_blksiz -1; fst = (rownbm -k)*nb+colst +1; for (colj=colst; colj <= coled; colj++) { st = (rownbm -k)*nb+colj +1; ed = min(st+nb-1,n-1); if (st > ed) break; if ((st == ed) && (colj != n-2)) break; vlen=ed-fst+1; vnb=vnb+1; } magma_bulge_findVTpos(n, nb, Vblksiz, colst, fst, ldv, ldt, &vpos, &tpos); if ((vlen > 0) && (vnb > 0)) { lapackf77_clarfb( "R", "N", "F", "C", &ib_loc, &vlen, &vnb, V(vpos), &ldv, T(tpos), &ldt, E(i*nb_loc,fst), &lde, work, &ib_loc); } } } } else { printf("ERROR SIDE %d \n",side); } } // END loop over the chunks magma_free_cpu(work); magma_free_cpu(work2); }
{ NULL, NULL, 0, 0}, }; /*XXXX these next two are duplicates or near-duplicates from config.c */ #define VAR(name,conftype,member,initvalue) \ { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \ initvalue } /** As VAR, but the option name and member name are the same. */ #define V(member,conftype,initvalue) \ VAR(#member, conftype, member, initvalue) /** Array of "state" variables saved to the ~/.tor/state file. */ static config_var_t state_vars_[] = { /* Remember to document these in state-contents.txt ! */ V(AccountingBytesReadInInterval, MEMUNIT, NULL), V(AccountingBytesWrittenInInterval, MEMUNIT, NULL), V(AccountingExpectedUsage, MEMUNIT, NULL), V(AccountingIntervalStart, ISOTIME, NULL), V(AccountingSecondsActive, INTERVAL, NULL), V(AccountingSecondsToReachSoftLimit,INTERVAL, NULL), V(AccountingSoftLimitHitAt, ISOTIME, NULL), V(AccountingBytesAtSoftLimit, MEMUNIT, NULL), VAR("EntryGuard", LINELIST_S, EntryGuards, NULL), VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL), VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL), VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL), VAR("EntryGuardPathBias", LINELIST_S, EntryGuards, NULL), VAR("EntryGuardPathUseBias", LINELIST_S, EntryGuards, NULL), V(EntryGuards, LINELIST_V, NULL),
void read_in_map ( const cv::FileNode& node, V &result ) { if(DEBUG_YML_IO) cout << "reading a value" << endl; read(node,result,V()); }
int main(int argc, char *argv[]) { //定义共享缓冲区及其信号灯 int readbuf_id = shmget(IPC_PRIVATE, CACHE_LENGTH + sizeof(unsigned), IPC_CREAT | IPC_EXCL | 0666); int rbuf_empty = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666); int rbuf_max = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666); int writebuf_id = shmget(IPC_PRIVATE, CACHE_LENGTH + sizeof(unsigned), IPC_CREAT | IPC_EXCL | 0666); int wbuf_empty = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666); int wbuf_max = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666); int finish_id = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666); int get_id = 0; int put_id = 0; int copy_id = 0; union semun semopts; FILE *out; FILE *in; int n; //打开源和目标文件 if (argc != 3) { puts("arguments error"); return 0; } if ((in = fopen(argv[1], "rb")) == NULL) { puts("can't open input file"); return 0; } if ((out = fopen(argv[2], "wb")) == NULL) { puts("can't open output file"); fclose(in); return 0; } //信号灯赋值 semopts.val = 1; semctl(rbuf_empty, 0, SETVAL, semopts); semctl(wbuf_empty, 0, SETVAL, semopts); semopts.val = 0; semctl(rbuf_max, 0, SETVAL, semopts); semctl(wbuf_max, 0, SETVAL, semopts); semctl(finish_id, 0, SETVAL, semopts); /*semctl(part_over, 0, SETVAL, semopts);*/ /*semctl(over, 0, SETVAL, semopts);*/ // get if ((get_id = fork()) == 0) { unsigned char *s = shmat(readbuf_id, 0, 0); puts("get:start to get"); do { P(rbuf_empty, 0); //加入copy n = fread(s + sizeof(unsigned), 1, CACHE_LENGTH, in); /*n = fread(s + sizeof(unsigned), 1, 2, in);*/ printf("read: %d\n", n); /*putchar('\n');*/ *(unsigned *)s = n; /*fwrite(s + sizeof(unsigned), 1, *(unsigned *)s, stdout);*/ V(rbuf_max, 0); if (*(unsigned *)s == 0) break; } while (1); fclose(in); /*sleep(5);*/ P(finish_id, 0); shmdt(s); //请加入保证三个进程同步结束的机制 puts("get: get ended"); return 0; } // copy if ((copy_id = fork()) == 0) { unsigned char *s1 = shmat(readbuf_id, 0, 0); unsigned char *s2 = shmat(writebuf_id, 0, 0); char buf[CACHE_LENGTH + sizeof(unsigned)]; puts("copy: start to copy"); do { P(rbuf_max, 0); //加入内容 n = *(unsigned *)s1; printf("copy: %d\n", n); memcpy(buf, s1, CACHE_LENGTH + sizeof(unsigned)); /*fwrite(s1 + sizeof(unsigned), 1, *(unsigned*)s1, stdout);*/ V(rbuf_empty, 0); P(wbuf_empty, 0); //加入内容 /**(unsigned *)s2 = n;*/ memcpy(s2, buf, CACHE_LENGTH + sizeof(unsigned)); printf("\ncopy: \n"); /*fwrite(s2 + sizeof(unsigned), 1, *(unsigned*)s2, stdout);*/ printf("\n\n"); V(wbuf_max, 0); if (*(unsigned *)s2 == 0) break; } while (1); P(finish_id, 0); shmdt(s1); shmdt(s2); //请加入保证三个进程同步结束的机制 puts("copy: copy ended"); /*sleep(5);*/ return 0; } // put if ((put_id = fork()) == 0) { unsigned char *s = shmat(writebuf_id, 0, 0); puts("put: start to put"); char buf_put[CACHE_LENGTH + sizeof(unsigned)]; do { P(wbuf_max, 0); //加入内容 /*memcpy(buf_put, s, CACHE_LENGTH + sizeof(unsigned));*/ printf("put: %d\n", *(unsigned *)s); /*if (*(unsigned*)s > 0)*/ /*{*/ fwrite(s + sizeof(unsigned), 1, *(unsigned *)s, out); fwrite(s + sizeof(unsigned), 1, *(unsigned *)s, stdout); /*}*/ fflush(out); V(wbuf_empty, 0); if (*(unsigned *)s == 0) { V(finish_id, 0); break; } } while (1); shmdt(s); fclose(out); //请加入保证三个进程同步结束的机制 puts("put: put ended"); return 0; } //请加入保证三个进程同步结束的机制 //请加入释放缓冲区和信号灯的机制 /*int status;*/ P(finish_id, 0); shmctl(readbuf_id, IPC_RMID, 0); shmctl(writebuf_id, IPC_RMID, 0); return 0; }
int CORE_zgblrx(int uplo, int N, PLASMA_desc *A, PLASMA_Complex64_t *V, PLASMA_Complex64_t *TAU, int st, int ed, int eltsize) { int NB, J1, J2; int len1, len2, t1ed, t2st; int i; PLASMA_desc vA=*A; /* Check input arguments */ if (N < 0) { coreblas_error(2, "Illegal value of N"); return -2; } if (ed <= st) { coreblas_error(6, "Illegal value of st and ed (internal)"); return -6; } /* Quick return */ if (N == 0) return PLASMA_SUCCESS; NB = A->mb; if( uplo == PlasmaLower ){ /* ======================== * LOWER CASE * ========================*/ for (i = ed; i >= st+1 ; i--){ /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/ J1 = st; J2 = i-2; t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_zlarfx2(PlasmaLeft, len1 , *V(i), conj(*TAU(i)), A(i-1, J1 ), ELTLDD(vA, (i-1)), A(i, J1 ), ELTLDD(vA, i) ); if(len2>0)CORE_zlarfx2(PlasmaLeft, len2 , *V(i), conj(*TAU(i)), A(i-1, t2st), ELTLDD(vA, (i-1)), A(i, t2st), ELTLDD(vA, i) ); CORE_zlarfx2ce(PlasmaLower, V(i), TAU(i), A(i-1,i-1), A(i,i-1), A(i,i)); } /* APPLY RIGHT ON THE REMAINING ELEMENT OF KERNEL 1 */ for (i = ed; i >= st+1 ; i--){ J1 = i+1; J2 = min(ed,N); t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_zlarfx2(PlasmaRight, len1, conj(*V(i)), conj(*TAU(i)), A(J1,i-1), ELTLDD(vA, J1) , A(J1 , i), ELTLDD(vA, J1) ); if(len2>0)CORE_zlarfx2(PlasmaRight, len2, conj(*V(i)), conj(*TAU(i)), A(t2st,i-1), ELTLDD(vA, t2st), A(t2st, i), ELTLDD(vA, t2st) ); } } else { /* ======================== * UPPER CASE * ========================*/ for (i = ed; i >= st+1 ; i--){ /* apply reflector from the left (horizontal row) and from the right for only the diagonal 2x2.*/ J1 = st; J2 = i-2; t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_zlarfx2(PlasmaRight, len1, conj(*V(i)), conj(*TAU(i)), A(J1,i-1), ELTLDD(vA, J1) , A(J1 , i), ELTLDD(vA, J1) ); if(len2>0)CORE_zlarfx2(PlasmaRight, len2, conj(*V(i)), conj(*TAU(i)), A(t2st,i-1), ELTLDD(vA, t2st), A(t2st, i), ELTLDD(vA, t2st) ); CORE_zlarfx2ce(PlasmaUpper, V(i), TAU(i), A(i-1,i-1), A(i-1, i), A(i,i)); } /* APPLY LEFT ON THE REMAINING ELEMENT OF KERNEL 1 */ for (i = ed; i >= st+1 ; i--){ J1 = i+1; J2 = min(ed,N); t1ed = (J2/NB)*NB; t2st = max(t1ed+1,J1); len1 = t1ed-J1+1; len2 = J2-t2st+1; if(len1>0)CORE_zlarfx2(PlasmaLeft, len1 , *V(i), conj(*TAU(i)), A(i-1, J1 ), ELTLDD(vA, (i-1)), A(i, J1 ), ELTLDD(vA, i) ); if(len2>0)CORE_zlarfx2(PlasmaLeft, len2 , *V(i), conj(*TAU(i)), A(i-1, t2st), ELTLDD(vA, (i-1)), A(i, t2st), ELTLDD(vA, i) ); } } /* end of else for the upper case */ return PLASMA_SUCCESS; }
void D3D9statemanager::setSamplerStateBlock( DWORD stage, Texture::ClampMode clampmode, Texture::FilterMode filtermode ) { int hash = stage << 24 | clampmode << 16 | filtermode; HRESULT hr; Dict<int,IDirect3DStateBlock9*>::const_iterator it = m_states.find(hash); if (it != m_states.end()) { if (m_stageSamplerStates[stage] != it->second) { V(it->second->Apply()); m_stageSamplerStates[stage] = it->second; } return; } IDirect3DStateBlock9* state = 0; d3d9Device->BeginStateBlock(); switch (clampmode) { case Texture::CM_Clamp: case Texture::CM_ClampToEdge: d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSW, D3DTADDRESS_CLAMP); break; case Texture::CM_ClampToBorder: d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSU, D3DTADDRESS_BORDER); d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSV, D3DTADDRESS_BORDER); d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSW, D3DTADDRESS_BORDER); d3d9StateManager->SetSamplerState(stage, D3DSAMP_BORDERCOLOR, 0); break; case Texture::CM_Repeat: d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); d3d9StateManager->SetSamplerState(stage, D3DSAMP_ADDRESSW, D3DTADDRESS_WRAP); } switch (filtermode) { case Texture::FM_Nearest: d3d9StateManager->SetSamplerState(stage, D3DSAMP_MINFILTER, D3DTEXF_POINT); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MAGFILTER, D3DTEXF_POINT); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MIPFILTER, D3DTEXF_NONE); break; case Texture::FM_Linear: d3d9StateManager->SetSamplerState(stage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MIPFILTER, D3DTEXF_NONE); break; case Texture::FM_Bilinear: d3d9StateManager->SetSamplerState(stage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MIPFILTER, D3DTEXF_POINT); break; case Texture::FM_Trilinear: d3d9StateManager->SetSamplerState(stage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); d3d9StateManager->SetSamplerState(stage, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); break; } d3d9Device->EndStateBlock(&state); m_states[hash] = state; state->Apply(); m_stageSamplerStates[stage] = state; }
// From http://www.gamedev.net/community/forums/topic.asp?topic_id=467789 - // intersection of cylinder with ray void Foam::searchableCylinder::findLineAll ( const point& start, const point& end, pointIndexHit& near, pointIndexHit& far ) const { near.setMiss(); far.setMiss(); vector point1Start(start-point1_); vector point2Start(start-point2_); vector point1End(end-point1_); // Quick rejection of complete vector outside endcaps scalar s1 = point1Start&unitDir_; scalar s2 = point1End&unitDir_; if ((s1 < 0 && s2 < 0) || (s1 > magDir_ && s2 > magDir_)) { return; } // Line as P = start+t*V where V is unit vector and t=[0..mag(end-start)] vector V(end-start); scalar magV = mag(V); if (magV < ROOTVSMALL) { return; } V /= magV; // We now get the nearest intersections to start. This can either be // the intersection with the end plane or with the cylinder side. // Get the two points (expressed in t) on the end planes. This is to // clip any cylinder intersection against. scalar tPoint1; scalar tPoint2; // Maintain the two intersections with the endcaps scalar tNear = VGREAT; scalar tFar = VGREAT; { scalar s = (V&unitDir_); if (mag(s) > VSMALL) { tPoint1 = -s1/s; tPoint2 = -(point2Start&unitDir_)/s; if (tPoint2 < tPoint1) { Swap(tPoint1, tPoint2); } if (tPoint1 > magV || tPoint2 < 0) { return; } // See if the points on the endcaps are actually inside the cylinder if (tPoint1 >= 0 && tPoint1 <= magV) { if (radius2(start+tPoint1*V) <= sqr(radius_)) { tNear = tPoint1; } } if (tPoint2 >= 0 && tPoint2 <= magV) { if (radius2(start+tPoint2*V) <= sqr(radius_)) { // Check if already have a near hit from point1 if (tNear <= 1) { tFar = tPoint2; } else { tNear = tPoint2; } } } } else { // Vector perpendicular to cylinder. Check for outside already done // above so just set tpoint to allow all. tPoint1 = -VGREAT; tPoint2 = VGREAT; } } const vector x = point1Start ^ unitDir_; const vector y = V ^ unitDir_; const scalar d = sqr(radius_); // Second order equation of the form a*t^2 + b*t + c const scalar a = (y&y); const scalar b = 2*(x&y); const scalar c = (x&x)-d; const scalar disc = b*b-4*a*c; scalar t1 = -VGREAT; scalar t2 = VGREAT; if (disc < 0) { // Fully outside return; } else if (disc < ROOTVSMALL) { // Single solution if (mag(a) > ROOTVSMALL) { t1 = -b/(2*a); //Pout<< "single solution t:" << t1 // << " for start:" << start << " end:" << end // << " c:" << c << endl; if (t1 >= 0 && t1 <= magV && t1 >= tPoint1 && t1 <= tPoint2) { // valid. Insert sorted. if (t1 < tNear) { tFar = tNear; tNear = t1; } else if (t1 < tFar) { tFar = t1; } } else { return; } } else { // Aligned with axis. Check if outside radius //Pout<< "small discriminant:" << disc // << " for start:" << start << " end:" << end // << " magV:" << magV // << " c:" << c << endl; if (c > 0) { return; } } } else { if (mag(a) > ROOTVSMALL) { scalar sqrtDisc = sqrt(disc); t1 = (-b - sqrtDisc)/(2*a); t2 = (-b + sqrtDisc)/(2*a); if (t2 < t1) { Swap(t1, t2); } if (t1 >= 0 && t1 <= magV && t1 >= tPoint1 && t1 <= tPoint2) { // valid. Insert sorted. if (t1 < tNear) { tFar = tNear; tNear = t1; } else if (t1 < tFar) { tFar = t1; } } if (t2 >= 0 && t2 <= magV && t2 >= tPoint1 && t2 <= tPoint2) { // valid. Insert sorted. if (t2 < tNear) { tFar = tNear; tNear = t2; } else if (t2 < tFar) { tFar = t2; } } //Pout<< "two solutions t1:" << t1 << " t2:" << t2 // << " for start:" << start << " end:" << end // << " magV:" << magV // << " c:" << c << endl; } else { // Aligned with axis. Check if outside radius //Pout<< "large discriminant:" << disc // << " small a:" << a // << " for start:" << start << " end:" << end // << " magV:" << magV // << " c:" << c << endl; if (c > 0) { return; } } } // Check tNear, tFar if (tNear >= 0 && tNear <= magV) { near.setPoint(start+tNear*V); near.setHit(); near.setIndex(0); if (tFar <= magV) { far.setPoint(start+tFar*V); far.setHit(); far.setIndex(0); } } else if (tFar >= 0 && tFar <= magV) { near.setPoint(start+tFar*V); near.setHit(); near.setIndex(0); } }
void dnp3_p_init_counter(void) { H_RULE (bit, h_bits(1,false)); H_RULE (ignore, h_ignore(bit)); H_RULE (reserved, dnp3_p_reserved(1)); H_ARULE(flags, h_sequence(bit, // ONLINE bit, // RESTART bit, // COMM_LOST bit, // REMOTE_FORCED bit, // LOCAL_FORCED ignore, // (ROLLOVER - obsolete) bit, // DISCONTINUITY reserved, NULL)); H_RULE (val32, h_uint32()); H_RULE (val16, h_uint16()); H_ARULE(ctr32, val32); H_ARULE(ctr16, val16); H_ARULE(ctr32_flag, h_sequence(flags, val32, NULL)); H_ARULE(ctr16_flag, h_sequence(flags, val16, NULL)); H_ARULE(ctr32_flag_t, h_sequence(flags, val32, dnp3_p_dnp3time, NULL)); H_ARULE(ctr16_flag_t, h_sequence(flags, val16, dnp3_p_dnp3time, NULL)); // group 20: counters... H_RULE(oblock_32bit_flag, dnp3_p_oblock(G_V(CTR, 32BIT), ctr32_flag)); H_RULE(oblock_16bit_flag, dnp3_p_oblock(G_V(CTR, 16BIT), ctr16_flag)); H_RULE(oblock_32bit_noflag, dnp3_p_oblock(G_V(CTR, 32BIT_NOFLAG), ctr32)); H_RULE(oblock_16bit_noflag, dnp3_p_oblock(G_V(CTR, 16BIT_NOFLAG), ctr16)); dnp3_p_ctr_rblock = dnp3_p_rblock(G(CTR), V(CTR, 32BIT), V(CTR, 16BIT), V(CTR, 32BIT_NOFLAG), V(CTR, 32BIT_NOFLAG), 0); dnp3_p_ctr_fblock = dnp3_p_specific_rblock(G(CTR), DNP3_VARIATION_ANY); dnp3_p_ctr_oblock = h_choice(oblock_32bit_flag, oblock_16bit_flag, oblock_32bit_noflag, oblock_16bit_noflag, NULL); // group 21: frozen counters... H_RULE(oblock_frz32bit_flag, dnp3_p_oblock(G_V(FROZENCTR, 32BIT), ctr32_flag)); H_RULE(oblock_frz16bit_flag, dnp3_p_oblock(G_V(FROZENCTR, 16BIT), ctr16_flag)); H_RULE(oblock_frz32bit_flag_t, dnp3_p_oblock(G_V(FROZENCTR, 32BIT_TIME), ctr32_flag_t)); H_RULE(oblock_frz16bit_flag_t, dnp3_p_oblock(G_V(FROZENCTR, 16BIT_TIME), ctr16_flag_t)); H_RULE(oblock_frz32bit_noflag, dnp3_p_oblock(G_V(FROZENCTR, 32BIT_NOFLAG), ctr32)); H_RULE(oblock_frz16bit_noflag, dnp3_p_oblock(G_V(FROZENCTR, 16BIT_NOFLAG), ctr16)); dnp3_p_frozenctr_rblock = dnp3_p_rblock(G(FROZENCTR), V(FROZENCTR, 32BIT), V(FROZENCTR, 16BIT), V(FROZENCTR, 32BIT_TIME), V(FROZENCTR, 16BIT_TIME), V(FROZENCTR, 32BIT_NOFLAG), V(FROZENCTR, 32BIT_NOFLAG), 0); dnp3_p_frozenctr_oblock = h_choice(oblock_frz32bit_flag, oblock_frz16bit_flag, oblock_frz32bit_flag_t, oblock_frz16bit_flag_t, oblock_frz32bit_noflag, oblock_frz16bit_noflag, NULL); // group 22: counter events... H_RULE(oblock_ev32bit_flag, dnp3_p_oblock(G_V(CTREV, 32BIT), ctr32_flag)); H_RULE(oblock_ev16bit_flag, dnp3_p_oblock(G_V(CTREV, 16BIT), ctr16_flag)); H_RULE(oblock_ev32bit_flag_t, dnp3_p_oblock(G_V(CTREV, 32BIT_TIME), ctr32_flag_t)); H_RULE(oblock_ev16bit_flag_t, dnp3_p_oblock(G_V(CTREV, 16BIT_TIME), ctr16_flag_t)); dnp3_p_ctrev_rblock = dnp3_p_rblock(G(CTREV), V(CTREV, 32BIT), V(CTREV, 16BIT), V(CTREV, 32BIT_TIME), V(CTREV, 16BIT_TIME), 0); dnp3_p_ctrev_oblock = h_choice(oblock_ev32bit_flag, oblock_ev16bit_flag, oblock_ev32bit_flag_t, oblock_ev16bit_flag_t, NULL); // group 21: frozen counter events... H_RULE(oblock_frzev32bit_flag, dnp3_p_oblock(G_V(FROZENCTREV, 32BIT), ctr32_flag)); H_RULE(oblock_frzev16bit_flag, dnp3_p_oblock(G_V(FROZENCTREV, 16BIT), ctr16_flag)); H_RULE(oblock_frzev32bit_flag_t, dnp3_p_oblock(G_V(FROZENCTREV, 32BIT_TIME), ctr32_flag_t)); H_RULE(oblock_frzev16bit_flag_t, dnp3_p_oblock(G_V(FROZENCTREV, 16BIT_TIME), ctr16_flag_t)); dnp3_p_frozenctrev_rblock = dnp3_p_rblock(G(FROZENCTREV), V(FROZENCTREV, 32BIT), V(FROZENCTREV, 16BIT), V(FROZENCTREV, 32BIT_TIME), V(FROZENCTREV, 16BIT_TIME), 0); dnp3_p_frozenctrev_oblock = h_choice(oblock_frzev32bit_flag, oblock_frzev16bit_flag, oblock_frzev32bit_flag_t, oblock_frzev16bit_flag_t, NULL); }
//---------------------------------------------------------------------------------------------- /// Examine the chi squared as a function of fitting parameters and estimate /// errors for each parameter. void CalculateChiSquared::estimateErrors() { // Number of fiting parameters auto nParams = m_function->nParams(); // Create an output table for displaying slices of the chi squared and // the probabilitydensity function auto pdfTable = API::WorkspaceFactory::Instance().createTable(); std::string baseName = getProperty("Output"); if (baseName.empty()) { baseName = "CalculateChiSquared"; } declareProperty(make_unique<API::WorkspaceProperty<API::ITableWorkspace>>( "PDFs", "", Kernel::Direction::Output), "The name of the TableWorkspace in which to store the " "pdfs of fit parameters"); setPropertyValue("PDFs", baseName + "_pdf"); setProperty("PDFs", pdfTable); // Create an output table for displaying the parameter errors. auto errorsTable = API::WorkspaceFactory::Instance().createTable(); auto nameColumn = errorsTable->addColumn("str", "Parameter"); auto valueColumn = errorsTable->addColumn("double", "Value"); auto minValueColumn = errorsTable->addColumn("double", "Value at Min"); auto leftErrColumn = errorsTable->addColumn("double", "Left Error"); auto rightErrColumn = errorsTable->addColumn("double", "Right Error"); auto quadraticErrColumn = errorsTable->addColumn("double", "Quadratic Error"); auto chiMinColumn = errorsTable->addColumn("double", "Chi2 Min"); errorsTable->setRowCount(nParams); declareProperty(make_unique<API::WorkspaceProperty<API::ITableWorkspace>>( "Errors", "", Kernel::Direction::Output), "The name of the TableWorkspace in which to store the " "values and errors of fit parameters"); setPropertyValue("Errors", baseName + "_errors"); setProperty("Errors", errorsTable); // Calculate initial values double chiSquared = 0.0; double chiSquaredWeighted = 0.0; double dof = 0; API::FunctionDomain_sptr domain; API::FunctionValues_sptr values; m_domainCreator->createDomain(domain, values); calcChiSquared(*m_function, nParams, *domain, *values, chiSquared, chiSquaredWeighted, dof); // Value of chi squared for current parameters in m_function double chi0 = chiSquared; // Fit data variance double sigma2 = chiSquared / dof; bool useWeighted = getProperty("Weighted"); if (useWeighted) { chi0 = chiSquaredWeighted; sigma2 = 0.0; } if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "chi0=" << chi0 << '\n'; g_log.debug() << "sigma2=" << sigma2 << '\n'; g_log.debug() << "dof=" << dof << '\n'; } // Parameter bounds that define a volume in the parameter // space within which the chi squared is being examined. GSLVector lBounds(nParams); GSLVector rBounds(nParams); // Number of points in lines for plotting size_t n = 100; pdfTable->setRowCount(n); const double fac = 1e-4; // Loop over each parameter for (size_t ip = 0; ip < nParams; ++ip) { // Add columns for the parameter to the pdf table. auto parName = m_function->parameterName(ip); nameColumn->read(ip, parName); // Parameter values auto col1 = pdfTable->addColumn("double", parName); col1->setPlotType(1); // Chi squared values auto col2 = pdfTable->addColumn("double", parName + "_chi2"); col2->setPlotType(2); // PDF values auto col3 = pdfTable->addColumn("double", parName + "_pdf"); col3->setPlotType(2); double par0 = m_function->getParameter(ip); double shift = fabs(par0 * fac); if (shift == 0.0) { shift = fac; } // Make a slice along this parameter GSLVector dir(nParams); dir.zero(); dir[ip] = 1.0; ChiSlice slice(*m_function, dir, *domain, *values, chi0, sigma2); // Find the bounds withn which the PDF is significantly above zero. // The bounds are defined relative to par0: // par0 + lBound is the lowest value of the parameter (lBound <= 0) // par0 + rBound is the highest value of the parameter (rBound >= 0) double lBound = slice.findBound(-shift); double rBound = slice.findBound(shift); lBounds[ip] = lBound; rBounds[ip] = rBound; // Approximate the slice with a polynomial. // P is a vector of values of the polynomial at special points. // A is a vector of Chebyshev expansion coefficients. // The polynomial is defined on interval [lBound, rBound] // The value of the polynomial at 0 == chi squared at par0 std::vector<double> P, A; bool ok = true; auto base = slice.makeApprox(lBound, rBound, P, A, ok); if (!ok) { g_log.warning() << "Approximation failed for parameter " << ip << '\n'; } if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "Parameter " << ip << '\n'; g_log.debug() << "Slice approximated by polynomial of order " << base->size() - 1; g_log.debug() << " between " << lBound << " and " << rBound << '\n'; } // Write n slice points into the output table. double dp = (rBound - lBound) / static_cast<double>(n); for (size_t i = 0; i < n; ++i) { double par = lBound + dp * static_cast<double>(i); double chi = base->eval(par, P); col1->fromDouble(i, par0 + par); col2->fromDouble(i, chi); } // Check if par0 is a minimum point of the chi squared std::vector<double> AD; // Calculate the derivative polynomial. // AD are the Chebyshev expansion of the derivative. base->derivative(A, AD); // Find the roots of the derivative polynomial std::vector<double> minima = base->roots(AD); if (minima.empty()) { minima.push_back(par0); } if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "Minima: "; } // If only 1 extremum is found assume (without checking) that it's a // minimum. // If there are more than 1, find the one with the smallest chi^2. double chiMin = std::numeric_limits<double>::max(); double parMin = par0; for (double minimum : minima) { double value = base->eval(minimum, P); if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << minimum << " (" << value << ") "; } if (value < chiMin) { chiMin = value; parMin = minimum; } } if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << '\n'; g_log.debug() << "Smallest minimum at " << parMin << " is " << chiMin << '\n'; } // Points of intersections with line chi^2 = 1/2 give an estimate of // the standard deviation of this parameter if it's uncorrelated with the // others. A[0] -= 0.5; // Now A are the coefficients of the original polynomial // shifted down by 1/2. std::vector<double> roots = base->roots(A); std::sort(roots.begin(), roots.end()); if (roots.empty()) { // Something went wrong; use the whole interval. roots.resize(2); roots[0] = lBound; roots[1] = rBound; } else if (roots.size() == 1) { // Only one root found; use a bound for the other root. if (roots.front() < 0) { roots.push_back(rBound); } else { roots.insert(roots.begin(), lBound); } } else if (roots.size() > 2) { // More than 2 roots; use the smallest and the biggest auto smallest = roots.front(); auto biggest = roots.back(); roots.resize(2); roots[0] = smallest; roots[1] = biggest; } if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "Roots: "; for (double root : roots) { g_log.debug() << root << ' '; } g_log.debug() << '\n'; } // Output parameter info to the table. valueColumn->fromDouble(ip, par0); minValueColumn->fromDouble(ip, par0 + parMin); leftErrColumn->fromDouble(ip, roots[0] - parMin); rightErrColumn->fromDouble(ip, roots[1] - parMin); chiMinColumn->fromDouble(ip, chiMin); // Output the PDF for (size_t i = 0; i < n; ++i) { double chi = col2->toDouble(i); col3->fromDouble(i, exp(-chi + chiMin)); } // make sure function parameters don't change. m_function->setParameter(ip, par0); } // Improve estimates for standard deviations. // If parameters are correlated the found deviations // most likely underestimate the true values. unfixParameters(); GSLJacobian J(*m_function, values->size()); m_function->functionDeriv(*domain, J); refixParameters(); // Calculate the hessian at the current point. GSLMatrix H; if (useWeighted) { H.resize(nParams, nParams); for (size_t i = 0; i < nParams; ++i) { for (size_t j = i; j < nParams; ++j) { double h = 0.0; for (size_t k = 0; k < values->size(); ++k) { double w = values->getFitWeight(k); h += J.get(k, i) * J.get(k, j) * w * w; } H.set(i, j, h); if (i != j) { H.set(j, i, h); } } } } else { H = J.matrix().tr() * J.matrix(); } // Square roots of the diagonals of the covariance matrix give // the standard deviations in the quadratic approximation of the chi^2. GSLMatrix V(H); if (!useWeighted) { V *= 1. / sigma2; } V.invert(); // In a non-quadratic asymmetric case the following procedure can give a // better result: // Find the direction in which the chi^2 changes slowest and the positive and // negative deviations in that direction. The change in a parameter at those // points can be a better estimate for the standard deviation. GSLVector v(nParams); GSLMatrix Q(nParams, nParams); // One of the eigenvectors of the hessian is the direction of the slowest // change. H.eigenSystem(v, Q); // Loop over the eigenvectors for (size_t i = 0; i < nParams; ++i) { auto dir = Q.copyColumn(i); if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "Direction " << i << '\n'; g_log.debug() << dir << '\n'; } // Make a slice in that direction ChiSlice slice(*m_function, dir, *domain, *values, chi0, sigma2); double rBound0 = dir.dot(rBounds); double lBound0 = dir.dot(lBounds); if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "lBound " << lBound0 << '\n'; g_log.debug() << "rBound " << rBound0 << '\n'; } double lBound = slice.findBound(lBound0); double rBound = slice.findBound(rBound0); std::vector<double> P, A; // Use a polynomial approximation bool ok = true; auto base = slice.makeApprox(lBound, rBound, P, A, ok); if (!ok) { g_log.warning() << "Approximation failed in direction " << i << '\n'; } // Find the deviation points where the chi^2 = 1/2 A[0] -= 0.5; std::vector<double> roots = base->roots(A); std::sort(roots.begin(), roots.end()); // Sort out the roots auto nRoots = roots.size(); if (nRoots == 0) { roots.resize(2, 0.0); } else if (nRoots == 1) { if (roots.front() > 0.0) { roots.insert(roots.begin(), 0.0); } else { roots.push_back(0.0); } } else if (nRoots > 2) { roots[1] = roots.back(); roots.resize(2); } if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "Roots " << roots[0] << " (" << slice(roots[0]) << ") " << roots[1] << " (" << slice(roots[1]) << ") \n"; } // Loop over the parameters and see if there deviations along // this direction is greater than any previous value. for (size_t ip = 0; ip < nParams; ++ip) { auto lError = roots.front() * dir[ip]; auto rError = roots.back() * dir[ip]; if (lError > rError) { std::swap(lError, rError); } if (lError < leftErrColumn->toDouble(ip)) { if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << " left for " << ip << ' ' << lError << ' ' << leftErrColumn->toDouble(ip) << '\n'; } leftErrColumn->fromDouble(ip, lError); } if (rError > rightErrColumn->toDouble(ip)) { if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << " right for " << ip << ' ' << rError << ' ' << rightErrColumn->toDouble(ip) << '\n'; } rightErrColumn->fromDouble(ip, rError); } } // Output the quadratic estimate for comparrison. quadraticErrColumn->fromDouble(i, sqrt(V.get(i, i))); } }
/* The following #define specifies the packing of the four components * into the compact INT32 representation. * Note that this formula must match the actual arithmetic encoder * and decoder implementation. The implementation has to be changed * if this formula is changed. * The current organization is leaned on Markus Kuhn's JBIG * implementation (jbig_tab.c). */ #define V(i,a,b,c,d) (((INT32)a << 16) | ((INT32)c << 8) | ((INT32)d << 7) | b) const INT32 jpeg_aritab[113+1] = { /* * Index, Qe_Value, Next_Index_LPS, Next_Index_MPS, Switch_MPS */ V( 0, 0x5a1d, 1, 1, 1 ), V( 1, 0x2586, 14, 2, 0 ), V( 2, 0x1114, 16, 3, 0 ), V( 3, 0x080b, 18, 4, 0 ), V( 4, 0x03d8, 20, 5, 0 ), V( 5, 0x01da, 23, 6, 0 ), V( 6, 0x00e5, 25, 7, 0 ), V( 7, 0x006f, 28, 8, 0 ), V( 8, 0x0036, 30, 9, 0 ), V( 9, 0x001a, 33, 10, 0 ), V( 10, 0x000d, 35, 11, 0 ), V( 11, 0x0006, 9, 12, 0 ), V( 12, 0x0003, 10, 13, 0 ), V( 13, 0x0001, 12, 13, 0 ), V( 14, 0x5a7f, 15, 15, 1 ), V( 15, 0x3f25, 36, 16, 0 ),
RcppExport SEXP nsem3b(SEXP data, SEXP theta, SEXP Sigma, SEXP modelpar, SEXP control ) { // srand ( time(NULL) ); /* initialize random seed: */ Rcpp::NumericVector Theta(theta); Rcpp::NumericMatrix D(data); unsigned nobs = D.nrow(), k = D.ncol(); mat Data(D.begin(), nobs, k, false); // Avoid copying Rcpp::NumericMatrix V(Sigma); mat S(V.begin(), V.nrow(), V.ncol()); S(0,0) = 1; mat iS = inv(S); double detS = det(S); Rcpp::List Modelpar(modelpar); Rcpp::IntegerVector _nlatent = Modelpar["nlatent"]; unsigned nlatent = _nlatent[0]; Rcpp::IntegerVector _ny0 = Modelpar["nvar0"]; unsigned ny0 = _ny0[0]; Rcpp::IntegerVector _ny1 = Modelpar["nvar1"]; unsigned ny1 = _ny1[0]; Rcpp::IntegerVector _ny2 = Modelpar["nvar2"]; unsigned ny2 = _ny2[0]; Rcpp::IntegerVector _npred0 = Modelpar["npred0"]; unsigned npred0 = _npred0[0]; Rcpp::IntegerVector _npred1 = Modelpar["npred1"]; unsigned npred1 = _npred1[0]; Rcpp::IntegerVector _npred2 = Modelpar["npred2"]; unsigned npred2 = _npred2[0]; Rcpp::List Control(control); Rcpp::NumericVector _lambda = Control["lambda"]; double lambda = _lambda[0]; Rcpp::NumericVector _niter = Control["niter"]; double niter = _niter[0]; Rcpp::NumericVector _Dtol = Control["Dtol"]; double Dtol = _Dtol[0]; rowvec mu0(ny0), lambda0(ny0); rowvec mu1(ny1), lambda1(ny1); rowvec mu2(ny2), lambda2(ny2); rowvec beta0(npred0); rowvec beta1(npred1); rowvec beta2(npred2); rowvec gamma(2); rowvec gamma2(2); unsigned pos=0; for (unsigned i=0; i<ny0; i++) { mu0(i) = Theta[pos]; pos++; } for (unsigned i=0; i<ny1; i++) { mu1(i) = Theta[pos]; pos++; } for (unsigned i=0; i<ny2; i++) { mu2(i) = Theta[pos]; pos++; } for (unsigned i=0; i<ny0; i++) { lambda0(i) = Theta[pos]; pos++; } lambda1(0) = 1; for (unsigned i=1; i<ny1; i++) { lambda1(i) = Theta[pos]; pos++; } lambda2(0) = 1; for (unsigned i=1; i<ny2; i++) { lambda2(i) = Theta[pos]; pos++; } for (unsigned i=0; i<npred0; i++) { beta0(i) = Theta[pos]; pos++; } for (unsigned i=0; i<npred1; i++) { beta1(i) = Theta[pos]; pos++; } for (unsigned i=0; i<npred2; i++) { beta2(i) = Theta[pos]; pos++; } gamma(0) = Theta[pos]; gamma(1) = Theta[pos+1]; gamma2(0) = Theta[pos+2]; gamma2(1) = Theta[pos+3]; // cerr << "mu0=" << mu0 << endl; // cerr << "mu1=" << mu1 << endl; // cerr << "mu2=" << mu2 << endl; // cerr << "lambda0=" << lambda0 << endl; // cerr << "lambda1=" << lambda1 << endl; // cerr << "lambda2=" << lambda2 << endl; // cerr << "beta0=" << beta0 << endl; // cerr << "beta1=" << beta1 << endl; // cerr << "beta2=" << beta2 << endl; // cerr << "gamma=" << gamma << endl; // cerr << "gamma2=" << gamma2 << endl; mat lap(nobs,4); for (unsigned i=0; i<nobs; i++) { rowvec newlap = laNRb(Data.row(i), iS, detS, mu0, mu1, mu2, lambda0, lambda1, lambda2, beta0,beta1, beta2, gamma, gamma2, Dtol,niter,lambda); lap.row(i) = newlap; } List res; res["indiv"] = lap; res["logLik"] = sum(lap.col(0)) + (3-V.nrow())*log(2.0*math::pi())*nobs/2; res["norm0"] = (3-V.nrow())*log(2*math::pi())/2; return res; }
int L(Shape s, int i,int* oTable) { return V(s,oTable[P(i)]); }
/** * * MFSL_setattrs : posts an asynchronous setattr and sets the cached attributes in return. * * Posts an asynchronous setattr and sets the cached attributes in return. * If the object is not asynchronous, then the content of object attributes will be used to populate it. * * @param filehandle [IN] mfsl object to be operated on. * @param p_context [IN] associated fsal context * @param p_mfsl_context [INOUT] associated mfsl context * @param attrib_set [IN] attributes to be set * @param object_attributes [INOUT] resulting attributes * * @return the same as FSAL_setattrs */ fsal_status_t MFSL_setattrs(mfsl_object_t * filehandle, /* IN */ fsal_op_context_t * p_context, /* IN */ mfsl_context_t * p_mfsl_context, /* IN */ fsal_attrib_list_t * attrib_set, /* IN */ fsal_attrib_list_t * object_attributes /* [ IN/OUT ] */ ) { fsal_status_t fsal_status; mfsl_async_op_desc_t *pasyncopdesc = NULL; mfsl_object_specific_data_t *pasyncdata = NULL; P(p_mfsl_context->lock); GetFromPool(pasyncopdesc, &p_mfsl_context->pool_async_op, mfsl_async_op_desc_t); V(p_mfsl_context->lock); if(pasyncopdesc == NULL) MFSL_return(ERR_FSAL_INVAL, 0); if(gettimeofday(&pasyncopdesc->op_time, NULL) != 0) { /* Could'not get time of day... Stopping, this may need a major failure */ LogMajor(COMPONENT_MFSL, "MFSL_setattrs: cannot get time of day... exiting"); exit(1); } /* Is the object asynchronous ? */ if(!mfsl_async_get_specdata(filehandle, &pasyncdata)) { /* Not yet asynchronous object */ P(p_mfsl_context->lock); GetFromPool(pasyncdata, &p_mfsl_context->pool_spec_data, mfsl_object_specific_data_t); V(p_mfsl_context->lock); /* In this case use object_attributes parameter to initiate asynchronous object */ pasyncdata->async_attr = *object_attributes; } fsal_status = MFSL_setattrs_check_perms(filehandle, pasyncdata, p_context, p_mfsl_context, attrib_set); if(FSAL_IS_ERROR(fsal_status)) return fsal_status; LogDebug(COMPONENT_MFSL, "Creating asyncop %p", pasyncopdesc); pasyncopdesc->op_type = MFSL_ASYNC_OP_SETATTR; pasyncopdesc->op_mobject = filehandle; pasyncopdesc->op_args.setattr.pmobject = filehandle; pasyncopdesc->op_args.setattr.attr = *attrib_set; pasyncopdesc->op_res.setattr.attr = *attrib_set; pasyncopdesc->op_func = MFSL_setattr_async_op; pasyncopdesc->fsal_op_context = *p_context; pasyncopdesc->ptr_mfsl_context = (caddr_t) p_mfsl_context; fsal_status = MFSL_async_post(pasyncopdesc); if(FSAL_IS_ERROR(fsal_status)) return fsal_status; /* Update the associated times for this object */ pasyncdata->async_attr.ctime.seconds = pasyncopdesc->op_time.tv_sec; pasyncdata->async_attr.ctime.nseconds = pasyncopdesc->op_time.tv_usec; /** @todo: there may be a coefficient to be applied here */ filehandle->health = MFSL_ASYNC_ASYNCHRONOUS; /* merge the attributes to the asynchronous attributes */ if((attrib_set->asked_attributes & FSAL_ATTR_SIZE) || (attrib_set->asked_attributes & FSAL_ATTR_SPACEUSED)) { /* Operation on a non data cached file */ pasyncdata->async_attr.filesize = attrib_set->filesize; pasyncdata->async_attr.spaceused = attrib_set->spaceused; } if(attrib_set->asked_attributes & (FSAL_ATTR_MODE | FSAL_ATTR_OWNER | FSAL_ATTR_GROUP)) { if(attrib_set->asked_attributes & FSAL_ATTR_MODE) pasyncdata->async_attr.mode = attrib_set->mode; if(attrib_set->asked_attributes & FSAL_ATTR_OWNER) pasyncdata->async_attr.owner = attrib_set->owner; if(attrib_set->asked_attributes & FSAL_ATTR_GROUP) pasyncdata->async_attr.group = attrib_set->group; } if(attrib_set->asked_attributes & (FSAL_ATTR_ATIME | FSAL_ATTR_MTIME)) { if(attrib_set->asked_attributes & FSAL_ATTR_ATIME) pasyncdata->async_attr.atime = attrib_set->atime; if(attrib_set->asked_attributes & FSAL_ATTR_MTIME) pasyncdata->async_attr.mtime = attrib_set->mtime; } /* Set output attributes */ *object_attributes = pasyncdata->async_attr; if(!mfsl_async_set_specdata(filehandle, pasyncdata)) MFSL_return(ERR_FSAL_SERVERFAULT, 0); MFSL_return(ERR_FSAL_NO_ERROR, 0); } /* MFSL_setattr */
int R(Shape s, int i,int *oTable) { return V(s,oTable[N(i)]); }
//#define DEBUG void ProgResolutionIBW::run() { V.read(fnVol); //Mask generation Image<double> aux; double bg_mean; MultidimArray<double> Vmask; detectBackground(V(),aux(),0.1,bg_mean); #ifdef DEBUG aux.write("PPPmask_no_ero_03.vol"); #endif //Mask volume erosion to expand the mask boundaries Vmask.initZeros(V()); erode3D(aux(),Vmask, 18,0,2); //Correction of some flaws produced in the edges of the mask volume FOR_ALL_DIRECT_ELEMENTS_IN_ARRAY3D(Vmask) if (k<=4 || i<=4 || j<=4 || k>=ZSIZE(Vmask)-4 || i>=YSIZE(Vmask)-4 || j>=XSIZE(Vmask)-4) DIRECT_A3D_ELEM(Vmask,k,i,j)=1; aux()=Vmask; #ifdef DEBUG aux.write("PPPmask_ero_03.vol"); #endif //Sobel edge detection applied to original volume Image<double> Vedge; computeEdges(V(),Vedge()); #ifdef DEBUG Vedge.write("PPPvolume_sobel_unmask_03.vol"); #endif //Masked volume generation const MultidimArray<double> &mVedge=Vedge(); FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(mVedge) if (DIRECT_MULTIDIM_ELEM(Vmask,n)==1) DIRECT_MULTIDIM_ELEM(mVedge,n)=0; #ifdef DEBUG Vedge.write("volume_sobel_mask_03.vol"); #endif double minval, maxval, avg, stddev; //Invert the mask to meet computeStats_within_binary_mask requirements FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(Vmask) if (DIRECT_MULTIDIM_ELEM(Vmask,n)==1) DIRECT_MULTIDIM_ELEM(Vmask,n)=0; else DIRECT_MULTIDIM_ELEM(Vmask,n)=1; //Threshold is 3 times the standard deviation of unmasked pixel values double thresh; computeStats_within_binary_mask(Vmask,mVedge,minval, maxval, avg, stddev); thresh=3*stddev; //Final edge volume generated by setting to 1 positions with values > threshold Image<double> Vaux; Vaux().initZeros(mVedge); FOR_ALL_DIRECT_ELEMENTS_IN_MULTIDIMARRAY(mVedge) if (DIRECT_MULTIDIM_ELEM(mVedge,n)>=thresh) DIRECT_MULTIDIM_ELEM(Vaux(),n)=1; #ifdef DEBUG Vaux.write("volumen_bordes_definitivo_03.vol"); #endif const MultidimArray<double> &mVaux=Vaux(); //Spline coefficient volume from original volume, to allow <1 step sizes MultidimArray<double> Volcoeffs; Volcoeffs.initZeros(V()); produceSplineCoefficients(3,Volcoeffs,V()); //Width parameter volume initialization Image<double> widths; widths().resizeNoCopy(V()); widths().initConstant(1e5); double step=0.25; Matrix1D<double> direction(3); //Calculation of edge width for 10 different directions, if a smaller value is found for a different //direction on a given position the former value is overwritten //Direction (1,0,0) VECTOR_R3(direction,1,0,0); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (0,1,0) VECTOR_R3(direction,0,1,0); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (0,0,1) VECTOR_R3(direction,0,0,1); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (1,1,0) VECTOR_R3(direction,(1/sqrt(2)),(1/sqrt(2)),0); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (1,0,1) VECTOR_R3(direction,(1/sqrt(2)),0,(1/sqrt(2))); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (0,1,1) VECTOR_R3(direction,0,(1/sqrt(2)),(1/sqrt(2))); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (1,1,1) VECTOR_R3(direction,(1/sqrt(3)),(1/sqrt(3)),(1/sqrt(3))); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (-1,1,1) VECTOR_R3(direction,-(1/sqrt(3)),(1/sqrt(3)),(1/sqrt(3))); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (1,1,-1) VECTOR_R3(direction,(1/sqrt(3)),(1/sqrt(3)),-(1/sqrt(3))); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); //Direction (1,-1,1) VECTOR_R3(direction,(1/sqrt(3)),-(1/sqrt(3)),(1/sqrt(3))); edgeWidth(Volcoeffs, mVaux, widths(), direction, step); #ifdef DEBUG std::cout << "width stats: "; widths().printStats(); std::cout << std::endl; widths.write("PPPwidths.vol"); #endif double ibw=calculateIBW(widths()); std::cout << "Resolution ibw= " << ibw << std::endl; if (fnOut!="") widths.write(fnOut); }
int main(int argc, char** argv) { Shape inShape = NULL; Shape outShape= NULL; int i,c; int doVTable=0; int *oTable, *mTable; float *vTable; int counter; float tester; if(argc != 3) { fprintf(stderr,"Usage:\n\t%s inFile outFile.\n",argv[0]); return 1; } inShape = readShapeFromFile(argv[1]); if(inShape == NULL) return 1; /* printf("Let's see what's in the inShape!\n");*/ #ifdef DEBUG printf("There are %d vertices.\n",inShape->numVertices); #endif /*printf("The vTable contains:\n");*/ for(c=0;c<inShape->numVertices*3;c+=3) { /* printf("%d => %f %f %f\n",c,inShape->vTable[c], inShape->vTable[c+1], inShape->vTable[c+2]);*/ } //printf("The tTable contains %d triangles\n\n",numTriangles(inShape)); // for(c=0;c<numTriangles(inShape)*3;c+=3) // { // printf("%d => %d %d %d\n", c,inShape->tTable[c], // inShape->tTable[c+1], // inShape->tTable[c+2]); // } oTable = malloc(sizeof(int)*numTriangles(inShape)*3); /*oTable = malloc(sizeof(int)*99999);*/ /* for(c=0;c<inShape->numVertices*3;c++)*/ for(c=0;c<numTriangles(inShape)*3;c++) { oTable[c] = -1; } /* for(c=0;c<numTriangles(inShape)*3;c++) for(i=c+1;i<inShape->numVertices*3;i++)*/ // printf("There are %d iterations of c and i\n",numTriangles(inShape)*3); for(c=0;c<numTriangles(inShape)*3;c++) for(i=c+1;i<numTriangles(inShape)*3;i++) { // if(c<10) // printf("Trying to match %d and %d..V(N(c))=%d, V(P(i))=%d, V(P(c)=%d,v(N(i))=%d\n",c,i,V(inShape,N(c)),V(inShape,P(i)),V(inShape,P(c)),V(inShape,N(i))); if((V(inShape,N(c)) == V(inShape,P(i))) &&(V(inShape,P(c)) == V(inShape,N(i)))) { // printf("Match found!\n"); oTable[c] = i; oTable[i] = c; } } printf("This is the oTable:\n"); for(c=0;c<numTriangles(inShape)*3;c++) { printf("%d => %d\n",c,oTable[c]); } for(c=0;c<numTriangles(inShape)*3;c++) if(oTable[c] == -1) { printf("MISALIGNMENT in corner %d!!!\n",c); printf("Cannot find a corner (opposite than at %d) with N(c)=%d and P(c)=%d\n", V(inShape,c),V(inShape,P(c)),V(inShape,N(c))); return 1; } /*mTable = malloc(sizeof(int)*inShape->numVertices*3);*/ mTable = malloc(sizeof(int)*numTriangles(inShape)*3); /* for(c=0;c<inShape->numVertices*3;c++)*/ for(c=0;c<numTriangles(inShape)*3;c++) mTable[c] = -1; /*outShape = createShape(4*inShape->numVertices-6);*/ outShape = createShape(4*inShape->numVertices,4*numTriangles(inShape)); printf("outShape has %d vertices\n",outShape->numVertices); printf("outShape has %d Triangles\n",numTriangles(outShape)); if(outShape == NULL) return 5; for(doVTable = 0;doVTable < inShape->numTables; doVTable++) { outShape->vTable = outShape->vTables[doVTable]; inShape->vTable = inShape->vTables[doVTable]; for(c=0;c<inShape->numVertices*3;c++) /* for(c=0;c<numTriangles(inShape)*3;c++)*/ { outShape->vTable[c] = inShape->vTable[c]; } } counter = inShape->numVertices - 1; printf("Counter starts at: %d\n",counter); /*for(c=0;c<inShape->numVertices*3;c++)*/ for(c=0;c<numTriangles(inShape)*3;c++) { if(mTable[c] == -1) { counter++; for(doVTable=0;doVTable<inShape->numTables;doVTable++) { outShape->vTable = outShape->vTables[doVTable]; inShape->vTable = inShape->vTables[doVTable]; vTable = inShape->vTable; outShape->vTable[counter*3]=0; outShape->vTable[counter*3]= (vTable[3*V(inShape,N(c))]+ vTable[3*V(inShape,P(c))])/2; outShape->vTable[counter*3]+= ( ( vTable[3*V(inShape,c)] + vTable[3*V(inShape,oTable[c])] )/2 - ( vTable[3*L(inShape,c,oTable)] + vTable[3*R(inShape,c,oTable)] +vTable[3*L(inShape,oTable[c],oTable)] + vTable[3*R(inShape,oTable[c],oTable)] )/4 )/4; outShape->vTable[counter*3+1]= (vTable[3*(V(inShape,N(c)))+1]+ vTable[3*(V(inShape,P(c)))+1])/2 + ( ( vTable[3*(V(inShape,c))+1] + vTable[3*(V(inShape,oTable[c]))+1] )/2 - ( vTable[3*(L(inShape,c,oTable))+1] + vTable[3*(R(inShape,c,oTable))+1] +vTable[3*(L(inShape,oTable[c],oTable))+1] + vTable[3*(R(inShape,oTable[c],oTable))+1] )/4 )/4; outShape->vTable[counter*3+2]= (vTable[3*(V(inShape,N(c)))+2]+ vTable[3*(V(inShape,P(c)))+2])/2 + ( ( vTable[3*(V(inShape,c))+2] + vTable[3*(V(inShape,oTable[c]))+2] )/2 - ( vTable[3*(L(inShape,c,oTable))+2] + vTable[3*(R(inShape,c,oTable))+2] +vTable[3*(L(inShape,oTable[c],oTable))+2] + vTable[3*(R(inShape,oTable[c],oTable))+2] )/4 )/4; } /* outShape->vTable[counter*3] = (vTable[3*V(inShape,N(c))] + vTable[3*V(inShape,P(c))])/2; outShape->vTable[counter*3+1] = (vTable[3*(V(inShape,N(c)))+1] + vTable[3*(V(inShape,P(c)))+1])/2; outShape->vTable[counter*3+2] = (vTable[3*(V(inShape,N(c)))+2] + vTable[3*(V(inShape,P(c)))+2])/2; */ printf("counter is %d\n",counter); printf("----\n"); mTable[c] = counter; mTable[oTable[c]] = counter; } } outShape->numVertices = counter+1; printf("outShape has %d vertices\n",outShape->numVertices); /* printf("mTable:\n"); for(c=0;c<inShape->numVertices*3;c++) printf("\t%d => %d\n",c,mTable[c]);*/ /*printf("new vTable:\n");*/ /* for(c=0;c<outShape->numVertices;c++) printf("\t%d => %f %f %f\n",c,outShape->vTable[c*3], outShape->vTable[c*3+1], outShape->vTable[c*3+2]);*/ /* printf("Counter finishes at: %d\n",counter);*/ printf("there are %d triangles\n",numTriangles(inShape)); for(c=0;c<numTriangles(inShape)*3;c+=3) { printf("Triangle %d %d %d becomes: \n",V(inShape,c),V(inShape,c+1), V(inShape,c+2)); outShape->tTable[c*4] = V(inShape,c); outShape->tTable[c*4+1]=mTable[c+2]; outShape->tTable[c*4+2]=mTable[c+1]; /* printf("\tTriangle %d %d %d\n", outShape->tTable[c*4], outShape->tTable[c*4+1], outShape->tTable[c*4+2]);*/ outShape->tTable[c*4+3]=mTable[c+1]; outShape->tTable[c*4+4]=mTable[c]; outShape->tTable[c*4+5]=V(inShape,c+2); /* printf("\tTriangle %d %d %d\n", outShape->tTable[c*4+3], outShape->tTable[c*4+4], outShape->tTable[c*4+5]);*/ outShape->tTable[c*4+6]=mTable[c+2]; outShape->tTable[c*4+7]=V(inShape,c+1); outShape->tTable[c*4+8]=mTable[c]; /* printf("\tTriangle %d %d %d\n", outShape->tTable[c*4+6], outShape->tTable[c*4+7], outShape->tTable[c*4+8]);*/ outShape->tTable[c*4+9]=mTable[c]; outShape->tTable[c*4+10]=mTable[c+1]; outShape->tTable[c*4+11]=mTable[c+2]; /* printf("\tTriangle %d %d %d\n", outShape->tTable[c*4+9], outShape->tTable[c*4+10], outShape->tTable[c*4+11]);*/ } printf("new tTable:\n"); for(c=0;c<numTriangles(outShape);c++) { printf("%d => %d %d %d\n",c,outShape->tTable[c*3], outShape->tTable[c*3+1], outShape->tTable[c*3+2]); } writeShapeToFile(outShape,argv[2]); printf("Hey there!!!!!\n\n\n");fflush(stdout); destroyShape(inShape); destroyShape(outShape); printf("Hey there!!!!!\n\n\n");fflush(stdout); return 0; }
/** * * MFSL_create : posts an asynchronous create and sets the cached attributes in return. * * Posts an asynchronous create and sets the cached attributes in return. * If an object is not asynchronous, then the content of object attributes structure for result will be used to populate it. * * @param parent_directory_handle [IN] mfsl object to be operated on (parent dir for the new file). * @param p_dirname [IN] new file's name * @param p_context [IN] associated fsal context * @param p_mfsl_context [INOUT] associated mfsl context * @param accessmode [IN] access mode for file create * @param object_handle [INOUT] new mfsl object * @param object_attributes [INOUT] resulting attributes for new object * @param parent_attributes [IN] attributes of the parent entry * * @return the same as FSAL_link */ fsal_status_t MFSL_create(mfsl_object_t * parent_directory_handle, /* IN */ fsal_name_t * p_dirname, /* IN */ fsal_op_context_t * p_context, /* IN */ mfsl_context_t * p_mfsl_context, /* IN */ fsal_accessmode_t accessmode, /* IN */ mfsl_object_t * object_handle, /* OUT */ fsal_attrib_list_t * object_attributes, /* [ IN/OUT ] */ fsal_attrib_list_t * parent_attributes /* IN */ ) { fsal_status_t fsal_status; mfsl_async_op_desc_t *pasyncopdesc = NULL; mfsl_object_specific_data_t *newfile_pasyncdata = NULL; mfsl_object_t *pnewfile_handle = NULL; mfsl_precreated_object_t *pprecreated = NULL; fsal_status = MFSAL_create_check_perms(parent_directory_handle, p_dirname, p_context, p_mfsl_context, parent_attributes); if(FSAL_IS_ERROR(fsal_status)) return fsal_status; P(p_mfsl_context->lock); GET_PREALLOC(pasyncopdesc, p_mfsl_context->pool_async_op, mfsl_param.nb_pre_async_op_desc, mfsl_async_op_desc_t, next_alloc); GET_PREALLOC(newfile_pasyncdata, p_mfsl_context->pool_spec_data, mfsl_param.nb_pre_async_op_desc, mfsl_object_specific_data_t, next_alloc); V(p_mfsl_context->lock); if(pasyncopdesc == NULL) MFSL_return(ERR_FSAL_INVAL, 0); if(gettimeofday(&pasyncopdesc->op_time, NULL) != 0) { /* Could'not get time of day... Stopping, this may need a major failure */ LogMajor(COMPONENT_MFSL, "MFSL_create: cannot get time of day... exiting"); exit(1); } /* Now get a pre-allocated directory from the synclet data */ P(p_mfsl_context->lock); GET_PREALLOC_CONSTRUCT(pprecreated, p_mfsl_context->pool_files, mfsl_param.nb_pre_create_files, mfsl_precreated_object_t, next_alloc, constructor_preacreated_entries); p_mfsl_context->avail_pool_files -= 1; V(p_mfsl_context->lock); pnewfile_handle = &(pprecreated->mobject); LogDebug(COMPONENT_MFSL, "Creating asyncop %p", pasyncopdesc); pasyncopdesc->op_type = MFSL_ASYNC_OP_CREATE; pasyncopdesc->op_args.create.pmfsl_obj_dirdest = parent_directory_handle; pasyncopdesc->op_args.create.precreate_name = pprecreated->name; pasyncopdesc->op_args.create.filename = *p_dirname; pasyncopdesc->op_args.create.owner = FSAL_OP_CONTEXT_TO_UID(p_context); pasyncopdesc->op_args.create.group = FSAL_OP_CONTEXT_TO_GID(p_context); pasyncopdesc->op_args.create.mode = accessmode; pasyncopdesc->op_res.create.attr.asked_attributes = object_attributes->asked_attributes; pasyncopdesc->op_res.create.attr.supported_attributes = object_attributes->supported_attributes; pasyncopdesc->ptr_mfsl_context = (caddr_t) p_mfsl_context; if(FSAL_IS_ERROR(fsal_status)) return fsal_status; pasyncopdesc->op_func = MFSL_create_async_op; //pasyncopdesc->fsal_op_context = p_context ; pasyncopdesc->fsal_op_context = synclet_data[pasyncopdesc->related_synclet_index].root_fsal_context; fsal_status = MFSL_async_post(pasyncopdesc); if(FSAL_IS_ERROR(fsal_status)) return fsal_status; /* Update the asynchronous metadata */ newfile_pasyncdata->async_attr = pprecreated->attr; newfile_pasyncdata->async_attr.type = FSAL_TYPE_FILE; newfile_pasyncdata->async_attr.filesize = 0; /* New file */ newfile_pasyncdata->async_attr.spaceused = 0; newfile_pasyncdata->async_attr.numlinks = 1; /* New file */ newfile_pasyncdata->async_attr.owner = pasyncopdesc->op_args.create.owner; newfile_pasyncdata->async_attr.group = pasyncopdesc->op_args.create.group; newfile_pasyncdata->async_attr.ctime.seconds = pasyncopdesc->op_time.tv_sec; newfile_pasyncdata->async_attr.ctime.nseconds = pasyncopdesc->op_time.tv_usec; /** @todo: there may be a coefficient to be applied here */ newfile_pasyncdata->deleted = FALSE; if(!mfsl_async_set_specdata(pnewfile_handle, newfile_pasyncdata)) MFSL_return(ERR_FSAL_SERVERFAULT, 0); /* Return the correct attributes */ *object_attributes = newfile_pasyncdata->async_attr; *object_handle = pprecreated->mobject; object_handle->health = MFSL_ASYNC_NEVER_SYNCED; /* Do not forget that the parent directory becomes asynchronous too */ parent_directory_handle->health = MFSL_ASYNC_ASYNCHRONOUS; MFSL_return(ERR_FSAL_NO_ERROR, 0); } /* MFSL_create */
static int nsv_parse_NSVf_header(AVFormatContext *s, AVFormatParameters *ap) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; unsigned int av_unused file_size; unsigned int size; int64_t duration; int strings_size; int table_entries; int table_entries_used; av_dlog(s, "%s()\n", __FUNCTION__); nsv->state = NSV_UNSYNC; /* in case we fail */ size = avio_rl32(pb); if (size < 28) return -1; nsv->NSVf_end = size; //s->file_size = (uint32_t)avio_rl32(pb); file_size = (uint32_t)avio_rl32(pb); av_dlog(s, "NSV NSVf chunk_size %u\n", size); av_dlog(s, "NSV NSVf file_size %u\n", file_size); nsv->duration = duration = avio_rl32(pb); /* in ms */ av_dlog(s, "NSV NSVf duration %"PRId64" ms\n", duration); // XXX: store it in AVStreams strings_size = avio_rl32(pb); table_entries = avio_rl32(pb); table_entries_used = avio_rl32(pb); av_dlog(s, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n", strings_size, table_entries, table_entries_used); if (pb->eof_reached) return -1; av_dlog(s, "NSV got header; filepos %"PRId64"\n", avio_tell(pb)); if (strings_size > 0) { char *strings; /* last byte will be '\0' to play safe with str*() */ char *p, *endp; char *token, *value; char quote; p = strings = av_mallocz(strings_size + 1); endp = strings + strings_size; avio_read(pb, strings, strings_size); while (p < endp) { while (*p == ' ') p++; /* strip out spaces */ if (p >= endp-2) break; token = p; p = strchr(p, '='); if (!p || p >= endp-2) break; *p++ = '\0'; quote = *p++; value = p; p = strchr(p, quote); if (!p || p >= endp) break; *p++ = '\0'; av_dlog(s, "NSV NSVf INFO: %s='%s'\n", token, value); av_dict_set(&s->metadata, token, value, 0); } av_free(strings); } if (pb->eof_reached) return -1; av_dlog(s, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb)); if (table_entries_used > 0) { int i; nsv->index_entries = table_entries_used; if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t)) return -1; nsv->nsvs_file_offset = av_malloc((unsigned)table_entries_used * sizeof(uint32_t)); for(i=0;i<table_entries_used;i++) nsv->nsvs_file_offset[i] = avio_rl32(pb) + size; if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { nsv->nsvs_timestamps = av_malloc((unsigned)table_entries_used*sizeof(uint32_t)); for(i=0;i<table_entries_used;i++) { nsv->nsvs_timestamps[i] = avio_rl32(pb); } } } av_dlog(s, "NSV got index; filepos %"PRId64"\n", avio_tell(pb)); #ifdef DEBUG_DUMP_INDEX #define V(v) ((v<0x20 || v > 127)?'.':v) /* dump index */ av_dlog(s, "NSV %d INDEX ENTRIES:\n", table_entries); av_dlog(s, "NSV [dataoffset][fileoffset]\n", table_entries); for (i = 0; i < table_entries; i++) { unsigned char b[8]; avio_seek(pb, size + nsv->nsvs_file_offset[i], SEEK_SET); avio_read(pb, b, 8); av_dlog(s, "NSV [0x%08lx][0x%08lx]: %02x %02x %02x %02x %02x %02x %02x %02x" "%c%c%c%c%c%c%c%c\n", nsv->nsvs_file_offset[i], size + nsv->nsvs_file_offset[i], b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], V(b[0]), V(b[1]), V(b[2]), V(b[3]), V(b[4]), V(b[5]), V(b[6]), V(b[7]) ); } //avio_seek(pb, size, SEEK_SET); /* go back to end of header */ #undef V #endif avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */ if (pb->eof_reached) return -1; nsv->state = NSV_HAS_READ_NSVF; return 0; }
static void cat_simulation(void * unusedpointer, unsigned long catnumber) { int i; unsigned int bowl; /* avoid unused variable warnings. */ (void) unusedpointer; (void) catnumber; /* your simulated cat must iterate NumLoops times, * sleeping (by calling cat_sleep() and eating * (by calling cat_eat()) on each iteration */ for(i=0;i<NumLoops;i++) { /* do not synchronize calls to cat_sleep(). Any number of cats (and mice) should be able sleep at the same time. */ cat_sleep(); #if OPT_A1 lock_acquire(turnDecision); bowl = nextBowlCatCanUse; nextBowlCatCanUse = (nextBowlCatCanUse % NumBowls) + 1; while (mice_eating > 0 || ((int)cats_eating >= NumBowls && mice_waiting > 0)) { cats_waiting++; cv_wait(CatsAreWelcome, turnDecision); cats_waiting--; } cats_eating++; lock_release(turnDecision); lock_acquire(BowlLocks[bowl]); cat_eat(bowl); lock_release(BowlLocks[bowl]); lock_acquire(turnDecision); cats_eating--; if (cats_eating == 0) { cv_broadcast(MiceAreWelcome, turnDecision); } lock_release(turnDecision); #else /* for now, this cat chooses a random bowl from * which to eat, and it is not synchronized with * other cats and mice. * * you will probably want to control which bowl this * cat eats from, and you will need to provide * synchronization so that the cat does not violate * the rules when it eats */ /* legal bowl numbers range from 1 to NumBowls */ bowl = ((unsigned int)random() % NumBowls) + 1; cat_eat(bowl); #endif } /* indicate that this cat simulation is finished */ V(CatMouseWait); }
/* * Print a running summary of interface statistics. * Repeat display every interval seconds, showing statistics * collected over that interval. Assumes that interval is non-zero. * First line printed at top of screen is always cumulative. */ void intpr(void) { register int line = 0; sigset_t oldmask, mask; struct ppp_stats cur, old; struct ppp_comp_stats ccs, ocs; memset(&old, 0, sizeof(old)); memset(&ocs, 0, sizeof(ocs)); while (1) { get_ppp_stats(&cur); if (cflag || rflag) get_ppp_cstats(&ccs); (void)signal(SIGALRM, catchalarm); signalled = 0; (void)alarm(interval); if ((line % 20) == 0) { if (line > 0) putchar('\n'); if (cflag) { printf("%6.6s %6.6s %6.6s %6.6s %6.6s %6.6s %6.6s", "ubyte", "upack", "cbyte", "cpack", "ibyte", "ipack", "ratio"); printf(" | %6.6s %6.6s %6.6s %6.6s %6.6s %6.6s %6.6s", "ubyte", "upack", "cbyte", "cpack", "ibyte", "ipack", "ratio"); putchar('\n'); } else { printf("%6.6s %6.6s %6.6s %6.6s %6.6s", "in", "pack", "comp", "uncomp", "err"); if (vflag) printf(" %6.6s %6.6s", "toss", "ip"); if (rflag) printf(" %6.6s %6.6s", "ratio", "ubyte"); printf(" | %6.6s %6.6s %6.6s %6.6s %6.6s", "out", "pack", "comp", "uncomp", "ip"); if (vflag) printf(" %6.6s %6.6s", "search", "miss"); if(rflag) printf(" %6.6s %6.6s", "ratio", "ubyte"); putchar('\n'); } memset(&old, 0, sizeof(old)); memset(&ocs, 0, sizeof(ocs)); } if (cflag) { printf("%6d %6d %6d %6d %6d %6d %6.2f", W(d.unc_bytes), W(d.unc_packets), W(d.comp_bytes), W(d.comp_packets), W(d.inc_bytes), W(d.inc_packets), W(d.ratio) == 0? 0.0: 1 - 1.0 / W(d.ratio) * 256.0); printf(" | %6d %6d %6d %6d %6d %6d %6.2f", W(c.unc_bytes), W(c.unc_packets), W(c.comp_bytes), W(c.comp_packets), W(c.inc_bytes), W(c.inc_packets), W(d.ratio) == 0? 0.0: 1 - 1.0 / W(d.ratio) * 256.0); putchar('\n'); } else { printf("%6d %6d %6d %6d %6d", V(p.ppp_ibytes), V(p.ppp_ipackets), V(vj.vjs_compressedin), V(vj.vjs_uncompressedin), V(vj.vjs_errorin)); if (vflag) printf(" %6d %6d", V(vj.vjs_tossed), V(p.ppp_ipackets) - V(vj.vjs_compressedin) - V(vj.vjs_uncompressedin) - V(vj.vjs_errorin)); if (rflag) printf(" %6.2f %6d", CRATE(W(d.comp_bytes), W(d.unc_bytes), W(d.unc_bytes)), W(d.unc_bytes)); printf(" | %6d %6d %6d %6d %6d", V(p.ppp_obytes), V(p.ppp_opackets), V(vj.vjs_compressed), V(vj.vjs_packets) - V(vj.vjs_compressed), V(p.ppp_opackets) - V(vj.vjs_packets)); if (vflag) printf(" %6d %6d", V(vj.vjs_searches), V(vj.vjs_misses)); if (rflag) printf(" %6.2f %6d", CRATE(W(d.comp_bytes), W(d.unc_bytes), W(d.unc_bytes)), W(c.unc_bytes)); putchar('\n'); } fflush(stdout); line++; if (interval == 0) exit(0); sigemptyset(&mask); sigaddset(&mask, SIGALRM); sigprocmask(SIG_BLOCK, &mask, &oldmask); if (! signalled) { sigemptyset(&mask); sigsuspend(&mask); } sigprocmask(SIG_SETMASK, &oldmask, NULL); signalled = 0; (void)alarm(interval); if (aflag==0) { old = cur; ocs = ccs; } } }
int main(){ int n = 200; double N = (double) n; double rho_max = 10.; double rho_min = 0.; double h = (rho_max - rho_min)/N; double omega_r = 1.; double TIME1, TIME2; vec rho(n), V(n-2), eigval; mat A = zeros<mat>(n-2,n-2); mat eigvec; clock_t start, finish, start2, finish2; // Declare start and finish time for(int i=1; i<n-1; i++){ rho[i] = rho_min + (i+1)*h; V[i] = omega_r*omega_r*rho[i]*rho[i] + 1./rho[i]; } rho[0] = 0.; rho[n-1] = rho_max; //Initializes the matrix A: A.diag(-1) += -1./(h*h); A.diag(+1) += -1./(h*h); A.diag() = (2./(h*h)) + V; // Eigenvector matrix: mat R = eye<mat>(n-2,n-2); // Built in eigenvalue/eigenvector procedure in armadillo: start2 = clock(); eig_sym(eigval, eigvec, A); finish2 = clock(); // Jacobi method: start = clock(); Jacobi(&A, &R, (n-2)); finish = clock(); TIME1 = (finish - start)/(double)CLOCKS_PER_SEC; TIME2 = (finish2 - start2)/(double)CLOCKS_PER_SEC; vec l; l = A.diag(); // Wavefunction for the lowest energy level: double MIN = max(l); int index = 0; for(int i=0; i<n-2; i++){ if(l(i) <= MIN){ MIN = l(i); index = i; } } vec u_1 = R.col(index); vec wave(n); for(int i=1; i<n-1; i++){ wave(i) = u_1(i-1); } // Dirichlet boundary conditions wave(0) = 0; wave(n-1) = 0; //Writing wave and rho to file: string filename; string Omega = static_cast<ostringstream*>( \ &(ostringstream() << omega_r*100) )->str(); filename = "wavefunc2_omega"+Omega+".dat"; ofile.open(filename.c_str(), ios::out); for(int i=0; i<n; i++){ ofile << rho[i] << ' ' << wave[i] << endl; } ofile.close(); vec lam = sort(l); cout << "omega_r = " << omega_r << endl; cout << "three lowest eigenvalues:" << endl; for(int i=0;i<3;i++){ cout << "lambda = " << lam(i) << endl; } cout << "computation time for jacobi.cpp with n = " << n << ": " << TIME1 << " s" << endl; cout << "computation time for built in procedure with n = " << n << ": " << TIME2 << " s" << endl; return 0; }
// Polar decomponsition of F through left stretch matrix // F = VR = Q Lambda (QTR) // The target matrix is assumed to be F // Function returns V and optionally R = V^-1 F (if pointer is not NULL) // and optionally (lam1,lam2,lam3) in stretches (if not NULL) // It does not get Q, but if needed, they are eigenvectors of the // returned V matrix Matrix3 Matrix3::LeftDecompose(Matrix3 *R,Vector *stretches) const { if(is2D) { // 2D has simple formulae for R = ((Fsum,Fdif),(-Fdif,Fsum)) double Fsum = m[0][0]+m[1][1]; double Fdif = m[0][1]-m[1][0]; double denom = sqrt(Fsum*Fsum+Fdif*Fdif); Fsum /= denom; Fdif /= denom; // V is F* R*T Matrix3 V(m[0][0]*Fsum+m[0][1]*Fdif,-m[0][0]*Fdif+m[0][1]*Fsum, m[1][0]*Fsum+m[1][1]*Fdif,-m[1][0]*Fdif+m[1][1]*Fsum,m[2][2]); // if R pointer not NULL, return it too if(R!=NULL) { R->set(Fsum,Fdif,-Fdif,Fsum,1.); } // Return Eigenvalues of V if asked if(stretches!=NULL) { *stretches = V.Eigenvalues(); } return V; } // rest is for 3D matrix // Get B=FF^T and B^2 Matrix3 B = (*this)*Transpose(); Matrix3 B2 = B*B; // Eigenvalues of B are lamda^2 Vector Eigenvals = B.Eigenvalues(); double lam1 = sqrt(Eigenvals.x); double lam2 = sqrt(Eigenvals.y); double lam3 = sqrt(Eigenvals.z); // invariants of V double i1 = lam1+lam2+lam3; double i2 = lam1*lam2+lam1*lam3+lam2*lam3; double i3 = lam1*lam2*lam3; // set coefficients double d1 = 1./(i1*i2-i3); double c2 = -d1; // coefficient of B2 double c1 = (i1*i1-i2)*d1; // coefficient of B double cI = i1*i3*d1; // coefficient of I // Get V = (1/d1)*(-B^2 + (i1*i1-i2)*B + i1*i3*I) Matrix3 V(c2*B2(0,0)+c1*B(0,0)+cI, c2*B2(0,1)+c1*B(0,1), c2*B2(0,2)+c1*B(0,2), c2*B2(1,0)+c1*B(1,0), c2*B2(1,1)+c1*B(1,1)+cI, c2*B2(1,2)+c1*B(1,2), c2*B2(2,0)+c1*B(2,0), c2*B2(2,1)+c1*B(2,1), c2*B2(2,2)+c1*B(2,2)+cI); // if R pointer not NULL, find R too if(R!=NULL) { c1 = 1/i3; // coefficient of B double cV = -i1*c1; // coefficient of V cI = i2*c1; // coefficient of I // Get Vinv = (1/i3)*(B - i1*V + i2*I) Matrix3 Vinv(c1*B(0,0)+cV*V(0,0)+cI, c1*B(0,1)+cV*V(0,1), c1*B(0,2)+cV*V(0,2), c1*B(1,0)+cV*V(1,0), c1*B(1,1)+cV*V(1,1)+cI, c1*B(1,2)+cV*V(1,2), c1*B(2,0)+cV*V(2,0), c1*B(2,1)+cV*V(2,1), c1*B(2,2)+cV*V(2,2)+cI); // R = V^-1 F *R = Vinv*(*this); } // Return Eigenvalues of U if asked if(stretches!=NULL) { stretches->x = lam1; stretches->y = lam2; stretches->z = lam3; } return V; }
int Stokhos::GMRESDivisionExpansionStrategy<ordinal_type,value_type,node_type>:: GMRES(const Teuchos::SerialDenseMatrix<int, double> & A, Teuchos::SerialDenseMatrix<int,double> & X, const Teuchos::SerialDenseMatrix<int,double> & B, int max_iter, double tolerance, int prec_iter, int order, int dim, int PrecNum, const Teuchos::SerialDenseMatrix<int, double> & M, int diag) { int n = A.numRows(); int k = 1; double resid; Teuchos::SerialDenseMatrix<int, double> P(n,n); Teuchos::SerialDenseMatrix<int, double> Ax(n,1); Ax.multiply(Teuchos::NO_TRANS,Teuchos::NO_TRANS,1.0, A, X, 0.0); Teuchos::SerialDenseMatrix<int, double> r0(B); r0-=Ax; resid=r0.normFrobenius(); //define vector v=r/norm(r) where r=b-Ax Teuchos::SerialDenseMatrix<int, double> v(n,1); r0.scale(1/resid); Teuchos::SerialDenseMatrix<int, double> h(1,1); //Matrix of orthog basis vectors V Teuchos::SerialDenseMatrix<int, double> V(n,1); //Set v=r0/norm(r0) to be 1st col of V for (int i=0; i<n; i++) { V(i,0)=r0(i,0); } //right hand side Teuchos::SerialDenseMatrix<int, double> bb(1,1); bb(0,0)=resid; Teuchos::SerialDenseMatrix<int, double> w(n,1); Teuchos::SerialDenseMatrix<int, double> c; Teuchos::SerialDenseMatrix<int, double> s; while (resid > tolerance && k < max_iter) { h.reshape(k+1,k); //Arnoldi iteration(Gram-Schmidt ) V.reshape(n,k+1); //set vk to be kth col of V Teuchos::SerialDenseMatrix<int, double> vk(Teuchos::Copy, V, n,1,0,k-1); //Preconditioning step: solve Mz=vk Teuchos::SerialDenseMatrix<int, double> z(vk); if (PrecNum == 1) { Stokhos::DiagPreconditioner precond(M); precond.ApplyInverse(vk,z,prec_iter); } else if (PrecNum == 2) { Stokhos::JacobiPreconditioner precond(M); precond.ApplyInverse(vk,z,2); } else if (PrecNum == 3) { Stokhos::GSPreconditioner precond(M,1); precond.ApplyInverse(vk,z,1); } else if (PrecNum == 4) { Stokhos::SchurPreconditioner precond(M, order, dim, diag); precond.ApplyInverse(vk,z,prec_iter); } w.multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, 1, A, z, 0.0); Teuchos::SerialDenseMatrix<int, double> vi(n,1); Teuchos::SerialDenseMatrix<int, double> ip(1,1); for (int i=0; i<k; i++) { //set vi to be ith col of V Teuchos::SerialDenseMatrix<int, double> vi(Teuchos::Copy, V, n,1,0,i); //Calculate inner product ip.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, 1.0, vi, w, 0.0); h(i,k-1)= ip(0,0); //scale vi by h(i,k-1) vi.scale(ip(0,0)); w-=vi; } h(k,k-1)=w.normFrobenius(); w.scale(1.0/h(k,k-1)); //add column vk+1=w to V for (int i=0; i<n; i++) { V(i,k)=w(i,0); } //Solve upper hessenberg least squares problem via Givens rotations //Compute previous Givens rotations for (int i=0; i<k-1; i++) { double q=c(i,0)*h(i,k-1)+s(i,0)*h(i+1,k-1); h(i+1,k-1)=-1*s(i,0)*h(i,k-1)+c(i,0)*h(i+1,k-1); h(i,k-1)=q; } //Compute next Givens rotations c.reshape(k,1); s.reshape(k,1); bb.reshape(k+1,1); double l = sqrt(h(k-1,k-1)*h(k-1,k-1)+h(k,k-1)*h(k,k-1)); c(k-1,0)=h(k-1,k-1)/l; s(k-1,0)=h(k,k-1)/l; // Givens rotation on h and bb h(k-1,k-1)=l; h(k,k-1)=0; bb(k,0)=-s(k-1,0)*bb(k-1,0); bb(k-1,0)=c(k-1,0)*bb(k-1,0); //Determine residual resid = fabs(bb(k,0)); k++; } //Extract upper triangular square matrix bb.reshape(h.numRows()-1 ,1); //Solve linear system int info; Teuchos::LAPACK<int, double> lapack; lapack.TRTRS('U', 'N', 'N', h.numRows()-1, 1, h.values(), h.stride(), bb.values(), bb.stride(),&info); Teuchos::SerialDenseMatrix<int, double> ans(X); V.reshape(n,k-1); ans.multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, 1.0, V, bb, 0.0); if (PrecNum == 1) { Stokhos::DiagPreconditioner precond(M); precond.ApplyInverse(ans,ans,prec_iter); } else if (PrecNum == 2) { Stokhos::JacobiPreconditioner precond(M); precond.ApplyInverse(ans,ans,2); } else if (PrecNum == 3) { Stokhos::GSPreconditioner precond(M,1); precond.ApplyInverse(ans,ans,1); } else if (PrecNum == 4) { Stokhos::SchurPreconditioner precond(M, order, dim, diag); precond.ApplyInverse(ans,ans,prec_iter); } X+=ans; std::cout << "iteration count= " << k-1 << std::endl; return 0; }
static int far_load(struct xmp_context *ctx, FILE *f, const int start) { struct xmp_player_context *p = &ctx->p; struct xmp_mod_context *m = &p->m; int i, j, vib = 0; struct xxm_event *event; struct far_header ffh; struct far_header2 ffh2; struct far_instrument fih; uint8 sample_map[8]; LOAD_INIT(); read32b(f); /* File magic: 'FAR\xfe' */ fread(&ffh.name, 40, 1, f); /* Song name */ fread(&ffh.crlf, 3, 1, f); /* 0x0d 0x0a 0x1A */ ffh.headersize = read16l(f); /* Remaining header size in bytes */ ffh.version = read8(f); /* Version MSN=major, LSN=minor */ fread(&ffh.ch_on, 16, 1, f); /* Channel on/off switches */ fseek(f, 9, SEEK_CUR); /* Current editing values */ ffh.tempo = read8(f); /* Default tempo */ fread(&ffh.pan, 16, 1, f); /* Channel pan definitions */ read32l(f); /* Grid, mode (for editor) */ ffh.textlen = read16l(f); /* Length of embedded text */ fseek(f, ffh.textlen, SEEK_CUR); /* Skip song text */ fread(&ffh2.order, 256, 1, f); /* Orders */ ffh2.patterns = read8(f); /* Number of stored patterns (?) */ ffh2.songlen = read8(f); /* Song length in patterns */ ffh2.restart = read8(f); /* Restart pos */ for (i = 0; i < 256; i++) ffh2.patsize[i] = read16l(f); /* Size of each pattern in bytes */ m->xxh->chn = 16; /*m->xxh->pat=ffh2.patterns; (Error in specs? --claudio) */ m->xxh->len = ffh2.songlen; m->xxh->tpo = 6; m->xxh->bpm = 8 * 60 / ffh.tempo; memcpy (m->xxo, ffh2.order, m->xxh->len); for (m->xxh->pat = i = 0; i < 256; i++) { if (ffh2.patsize[i]) m->xxh->pat = i + 1; } m->xxh->trk = m->xxh->chn * m->xxh->pat; strncpy(m->name, (char *)ffh.name, 40); sprintf(m->type, "FAR (Farandole Composer %d.%d)", MSN(ffh.version), LSN(ffh.version)); MODULE_INFO(); PATTERN_INIT(); /* Read and convert patterns */ if (V(0)) { report("Comment bytes : %d\n", ffh.textlen); report("Stored patterns: %d ", m->xxh->pat); } for (i = 0; i < m->xxh->pat; i++) { uint8 brk, note, ins, vol, fxb; PATTERN_ALLOC(i); if (!ffh2.patsize[i]) continue; m->xxp[i]->rows = (ffh2.patsize[i] - 2) / 64; TRACK_ALLOC(i); brk = read8(f) + 1; read8(f); for (j = 0; j < m->xxp[i]->rows * m->xxh->chn; j++) { event = &EVENT(i, j % m->xxh->chn, j / m->xxh->chn); if ((j % m->xxh->chn) == 0 && (j / m->xxh->chn) == brk) event->f2t = FX_BREAK; note = read8(f); ins = read8(f); vol = read8(f); fxb = read8(f); if (note) event->note = note + 36; if (event->note || ins) event->ins = ins + 1; vol = 16 * LSN(vol) + MSN(vol); if (vol) event->vol = vol - 0x10; /* ? */ event->fxt = fx[MSN(fxb)]; event->fxp = LSN(fxb); switch (event->fxt) { case NONE: event->fxt = event->fxp = 0; break; case FX_FAR_PORTA_UP: event->fxt = FX_EXTENDED; event->fxp |= (EX_F_PORTA_UP << 4); break; case FX_FAR_PORTA_DN: event->fxt = FX_EXTENDED; event->fxp |= (EX_F_PORTA_DN << 4); break; case FX_FAR_RETRIG: event->fxt = FX_EXTENDED; event->fxp |= (EX_RETRIG << 4); break; case FX_FAR_DELAY: event->fxt = FX_EXTENDED; event->fxp |= (EX_DELAY << 4); break; case FX_FAR_SETVIBRATO: vib = event->fxp & 0x0f; event->fxt = event->fxp = 0; break; case FX_VIBRATO: event->fxp = (event->fxp << 4) + vib; break; case FX_PER_VIBRATO: event->fxp = (event->fxp << 4) + vib; break; case FX_FAR_VSLIDE_UP: /* Fine volume slide up */ event->fxt = FX_EXTENDED; event->fxp |= (EX_F_VSLIDE_UP << 4); break; case FX_FAR_VSLIDE_DN: /* Fine volume slide down */ event->fxt = FX_EXTENDED; event->fxp |= (EX_F_VSLIDE_DN << 4); break; case FX_TEMPO: event->fxp = 8 * 60 / event->fxp; break; } } reportv(ctx, 0, "."); } m->xxh->ins = -1; fread(sample_map, 1, 8, f); for (i = 0; i < 64; i++) { if (sample_map[i / 8] & (1 << (i % 8))) m->xxh->ins = i; } m->xxh->ins++; m->xxh->smp = m->xxh->ins; INSTRUMENT_INIT(); /* Read and convert instruments and samples */ reportv(ctx, 0, "\nInstruments : %d ", m->xxh->ins); for (i = 0; i < m->xxh->ins; i++) { if (!(sample_map[i / 8] & (1 << (i % 8)))) continue; m->xxi[i] = calloc (sizeof (struct xxm_instrument), 1); fread(&fih.name, 32, 1, f); /* Instrument name */ fih.length = read32l(f); /* Length of sample (up to 64Kb) */ fih.finetune = read8(f); /* Finetune (unsuported) */ fih.volume = read8(f); /* Volume (unsuported?) */ fih.loop_start = read32l(f); /* Loop start */ fih.loopend = read32l(f); /* Loop end */ fih.sampletype = read8(f); /* 1=16 bit sample */ fih.loopmode = read8(f); fih.length &= 0xffff; fih.loop_start &= 0xffff; fih.loopend &= 0xffff; m->xxih[i].nsm = !!(m->xxs[i].len = fih.length); m->xxs[i].lps = fih.loop_start; m->xxs[i].lpe = fih.loopend; m->xxs[i].flg = fih.sampletype ? WAVE_16_BITS : 0; m->xxs[i].flg |= fih.loopmode ? WAVE_LOOPING : 0; m->xxi[i][0].vol = 0xff; /* fih.volume; */ m->xxi[i][0].sid = i; copy_adjust(m->xxih[i].name, fih.name, 32); if (V(1) && (strlen((char *)m->xxih[i].name) || m->xxs[i].len) && m->xxs[i].lps != 0xffff) { report ("\n[%2X] %-32.32s %04x %04x %04x %c V%02x ", i, m->xxih[i].name, m->xxs[i].len, m->xxs[i].lps, m->xxs[i].lpe, fih.loopmode ? 'L' : ' ', m->xxi[i][0].vol); reportv(ctx, 0, "."); } xmp_drv_loadpatch(ctx, f, m->xxi[i][0].sid, m->c4rate, 0, &m->xxs[i], NULL); } reportv(ctx, 0, "\n"); m->volbase = 0xff; return 0; }