コード例 #1
0
ファイル: collada_utils.cpp プロジェクト: diekev/blender
void BoneExtended::set_bone_layers(std::string layerString, std::vector<std::string> &layer_labels)
{
	std::stringstream ss(layerString);
	std::string layer;
	int pos;

	while (ss >> layer) {

		/* Blender uses numbers to specify layers*/
		if (isInteger(layer))
		{
			pos = atoi(layer.c_str());
			if (pos >= 0 && pos < 32) {
				this->bone_layers = bc_set_layer(this->bone_layers, pos);
				continue;
			}
		}

		/* layer uses labels (not supported by blender). Map to layer numbers:*/
		pos = find(layer_labels.begin(), layer_labels.end(), layer) - layer_labels.begin();
		if (pos >= layer_labels.size()) {
			layer_labels.push_back(layer); /* remember layer number for future usage*/
		}

		if (pos > 31)
		{
			fprintf(stderr, "Too many layers in Import. Layer %s mapped to Blender layer 31\n", layer.c_str());
			pos = 31;
		}

		/* If numeric layers and labeled layers are used in parallel (unlikely),
		 * we get a potential mixup. Just leave as is for now.
		 */
		this->bone_layers = bc_set_layer(this->bone_layers, pos);

	}
}
コード例 #2
0
ファイル: Numerics.cpp プロジェクト: jlfaucher/executor
/**
 * Convert an object into an unsigned number value.
 *
 * @param source   The source object.
 * @param result   The returned converted value.
 * @param maxValue The maximum range value for the target.
 *
 * @return true if the number converted properly, false for any
 *         conversion errors.
 */
bool Numerics::objectToUnsignedInteger(RexxObject *source, size_t &result, size_t maxValue)
{
    // is this an integer value (very common)
    if (isInteger(source))
    {
        // reject any signed values.
        if (((RexxInteger *)source)->wholeNumber() < 0)
        {
            return false;
        }

        result = ((RexxInteger *)source)->stringSize();
        return result <= maxValue ? true : false;
    }
    else
    {
        // get this as a numberstring (which it might already be)
        RexxNumberString *nString = source->numberString();
        // not convertible to number string?  get out now
        if (nString == OREF_NULL)
        {
            return false;
        }
        uint64_t temp;

        // if not valid or outside of the minimum range, reject this too
        if (nString->unsignedInt64Value(&temp, SIZE_DIGITS))
        {
            if ( temp <= maxValue )
            {
                result = (stringsize_t)temp;
                return true;
            }
        }
        return false;
    }
}
コード例 #3
0
bool Condition::compareNameLiteral(string name, string lit, string op) {
	// If comparing integers...
	if(isInteger(lit)) {
		int attrValue = stoi(name),
			litValue = stoi(lit);

		if(op.compare("==") == 0) {
			 return attrValue == litValue;
		} else if(op.compare("!=") == 0) {
			return attrValue != litValue;
		} else if(op.compare(">") == 0) {
			return attrValue > litValue;			
		} else if(op.compare("<") == 0) {
			return attrValue < litValue;
		} else if(op.compare(">=") == 0) {
			return attrValue >= litValue;
		} else if(op.compare("<=") == 0) {
			return attrValue <= litValue;
		}
	}
	
	// If comparing varchars...	
	else return compareNames(name, lit, op);
}
コード例 #4
0
/* Search the data based on the CCN (the user's input from keyboard)
   PRE:  hash - the pointer to the header of the hash table
   POST: data printed out if found
		 print the notification if wrong input
*/
void searchManager(HASH *hash)
{
	char target[20];

	do
	{
		printf("Enter the target (no space) or 0 to stop: ");
		scanf("%s", target);

		if(strcmp("0", target))
		{
			if(isInteger(target) && strlen(target) == 16)
			{
				convertStr(target);
				//printf("%s\n", target);
				searchHash(hash, target);
			}
			else
				printf ("Invalid input!!!\n");
		}
	}while(strcmp("0", target));

	return;
}
コード例 #5
0
ファイル: RJSON.c プロジェクト: cran/RJSONIO
/*
  The "simple"/standard callback to an R function.
 */
int
R_json_basicCallback(void* ctx, int type, const struct JSON_value_struct* value)
{
    RJSONParserInfo *info = ( RJSONParserInfo *) ctx;

    if(info->func != NULL) {
	SEXP result, tmp;
	tmp = CAR(CDR(info->func));

	INTEGER(tmp)[0] = type; /* Names too */

        SET_STRING_ELT(info->names, 0, mkChar(jsonTypeNames[type])); 

	if(value) 
	    SETCAR(CDR(CDR(info->func)), convertJSONValueToR(type, value, info->encoding));
	else if(type == JSON_T_TRUE)
	    SETCAR(CDR(CDR(info->func)), ScalarLogical(1));
	else if(type == JSON_T_FALSE)
	    SETCAR(CDR(CDR(info->func)), ScalarLogical(0));
	else
	    SETCAR(CDR(CDR(info->func)), R_NilValue);

	result = Rf_eval(info->func, R_GlobalEnv);

	if(isLogical(result))
	    return(LOGICAL(result)[0]);
	else if(isInteger(result))
	    return(INTEGER(result)[0]);
	else if(isNumeric(result))
	    return(REAL(result)[0]);
        else
	    return(1);
    }

    return(1);
}
コード例 #6
0
ファイル: print.c プロジェクト: radfordneal/pqR
/* PrintLanguage() or PrintClosure() : */
static void PrintLanguageEtc(SEXP s, Rboolean useSource, Rboolean isClosure)
{
    int i;
    SEXP t = getAttrib(s, R_SrcrefSymbol);
    Rboolean useSrc = useSource && isInteger(t);
    if (useSrc) {
	PROTECT(t = lang2(R_AsCharacterSymbol, t));
	t = eval(t, R_BaseEnv);
	UNPROTECT(1);
    } else {
	t = deparse1w(s, 0, useSource | DEFAULTDEPARSE);
    }
    PROTECT(t);
    for (i = 0; i < LENGTH(t); i++) {
 	Rprintf("%s\n", translateChar(STRING_ELT(t, i))); // translate: for srcref part (PR#16732)
    }
    UNPROTECT(1);
    if (isClosure) {
	if (isByteCode(BODY(s))) Rprintf("<bytecode: %p>\n", BODY(s));
	t = CLOENV(s);
	if (t != R_GlobalEnv)
	    Rprintf("%s\n", EncodeEnvironment(t));
    }
}
コード例 #7
0
/// Returns `true` if `Node` is a value which evaluates to a literal `0`.
bool IsLiteralZero(const MatchFinder::MatchResult &Result, const Expr &Node) {
  auto ZeroMatcher =
      anyOf(integerLiteral(equals(0)), floatLiteral(equals(0.0)));

  // Check to see if we're using a zero directly.
  if (selectFirst<const clang::Expr>(
          "val", match(expr(ignoringImpCasts(ZeroMatcher)).bind("val"), Node,
                       *Result.Context)) != nullptr)
    return true;

  // Now check to see if we're using a functional cast with a scalar
  // initializer expression, e.g. `int{0}`.
  if (selectFirst<const clang::Expr>(
          "val", match(cxxFunctionalCastExpr(
                           hasDestinationType(
                               anyOf(isInteger(), realFloatingPointType())),
                           hasSourceExpression(initListExpr(
                               hasInit(0, ignoringParenImpCasts(ZeroMatcher)))))
                           .bind("val"),
                       Node, *Result.Context)) != nullptr)
    return true;

  return false;
}
コード例 #8
0
/* From the MPFR (2.3.2, 2008) doc :
 -- Function:

 int mpfr_set_str (mpfr_t ROP, const char *S, int BASE, mpfr_rnd_t RND)

     Set ROP to the value of the whole string S in base BASE, rounded
     in the direction RND.  See the documentation of `mpfr_strtofr' for
     a detailed description of the valid string formats.  This function
     returns 0 if the entire string up to the final null character is a
     valid number in base BASE; otherwise it returns -1, and ROP may
     have changed.
*/
SEXP str2mpfr1_list(SEXP x, SEXP prec, SEXP base, SEXP rnd_mode)
{
/* NB: Both x and prec are "recycled" to the longer one if needed */
    int ibase = asInteger(base), *iprec,
	nx = LENGTH(x), np = LENGTH(prec),
	n = (nx == 0 || np == 0) ? 0 : imax2(nx, np),
	nprot = 1;
    SEXP val = PROTECT(allocVector(VECSXP, n));
    mpfr_rnd_t rnd = R_rnd2MP(rnd_mode);
    mpfr_t r_i;
    mpfr_init(r_i);

    if(!isString(x))     { PROTECT(x    = coerceVector(x,    STRSXP)); nprot++; }
    if(!isInteger(prec)) { PROTECT(prec = coerceVector(prec, INTSXP)); nprot++; }
    iprec = INTEGER(prec);

    for(int i = 0; i < n; i++) {
	int prec_i = iprec[i % np];
	R_mpfr_check_prec(prec_i);
	mpfr_set_prec(r_i, (mpfr_prec_t) prec_i);
	int ierr = mpfr_set_str(r_i, CHAR(STRING_ELT(x, i % nx)), ibase, rnd);
	if(ierr) {
	    if (!strcmp("NA", CHAR(STRING_ELT(x, i % nx))))
		mpfr_set_nan(r_i); // "NA" <=> "NaN" (which *are* treated well, by mpfr_set_str)
	    else
		error("str2mpfr1_list(x, *): x[%d] cannot be made into MPFR",
		      i+1);
	}
	/* FIXME: become more efficient by doing R_..._2R_init() only once*/
	SET_VECTOR_ELT(val, i, MPFR_as_R(r_i));
    }
    mpfr_clear (r_i);
    mpfr_free_cache();
    UNPROTECT(nprot);
    return val;
}
コード例 #9
0
ファイル: fmelt.c プロジェクト: kaybenleroll/datatable
// hack by calling paste using eval. could change this to strcat, but not sure about buffer size for large data.tables... Any ideas Matthew?
SEXP concat(SEXP vec, SEXP idx) {
    
    SEXP s, t, v;
    int i;
    
    if (TYPEOF(vec) != STRSXP) error("concat: 'vec must be a character vector");
    if (!isInteger(idx) || length(idx) < 0) error("concat: 'idx' must be an integer vector of length >= 0");
    for (i=0; i<length(idx); i++) {
        if (INTEGER(idx)[i] < 0 || INTEGER(idx)[i] > length(vec)) 
            error("concat: 'idx' must take values between 0 and length(vec); 0 <= idx <= length(vec)");
    }
    PROTECT(v = allocVector(STRSXP, length(idx)));
    for (i=0; i<length(idx); i++) {
        SET_STRING_ELT(v, i, STRING_ELT(vec, INTEGER(idx)[i]-1));
    }
    PROTECT(t = s = allocList(3));
    SET_TYPEOF(t, LANGSXP);
    SETCAR(t, install("paste")); t = CDR(t);
    SETCAR(t, v); t = CDR(t);
    SETCAR(t, mkString(", "));
    SET_TAG(t, install("collapse"));
    UNPROTECT(2); // v, (t,s)
    return(eval(s, R_GlobalEnv));
}
コード例 #10
0
ファイル: 65.cpp プロジェクト: SccsAtmtn/leetcode
    bool isNumber(string s) {
        int pos = 0;
        for (int i=0; i<s.length(); ++i)
            if (s[i]!=' ') {
                pos = i;
                break;
            }
        s = s.substr(pos);
        for (int i=s.length()-1; i>=0; --i)
            if (s[i]!=' ') {
                pos = i;
                break;
            }
        s = s.substr(0, pos+1);
        if (s.length()!=0 && (s[0]=='+' || s[0]=='-')) 
            s = s.substr(1);
        int n = s.length();
        if (isInteger(s))
            return true;
        auto ePos = s.find('e');
        if (ePos!=string::npos) {
            string left = s.substr(0, ePos);
            string right = s.substr(ePos+1);
            if (right.length()!=0 && (right[0]=='+' || right[0]=='-'))
                right = right.substr(1);
            auto dotPos = left.find('.');
            if (dotPos!=string::npos)
                return ((dotPos==0 || isInteger(left.substr(0, dotPos))) && (dotPos==left.length()-1 || isInteger(left.substr(dotPos+1))) && (left.length()!=1) && isInteger(right));
            else 
                return (isInteger(left) && isInteger(right));
        }

        auto dotPos = s.find('.');
        if (dotPos!=string::npos)
            return ((isInteger(s.substr(0, dotPos)) || dotPos==0) && (dotPos==n-1 || isInteger(s.substr(dotPos+1))) && (n!=1));        
        return false;
    }
コード例 #11
0
bool TableCursorKey::putField(int i, double d) {
  DbFieldType keyType = m_keydef.getFieldDef(i).getType();
  int c = rangecmp(d,keyType);
  if(c == 0) {
    if(isIntegerType(keyType)) {
      if(isInteger(d))
        putNumberInKey(i,d);
      else {
        switch(m_relop) {
        case RELOP_EQ:
          m_key.init();
          m_fieldCount = 0;
          m_relop      = RELOP_FALSE;
          return true;
        case RELOP_GE:
        case RELOP_GT:
          putNumberInKey(i,roundup(d));
          m_relop      = RELOP_GE;
          m_fieldCount = i + 1;
          return true;
        case RELOP_LE:
        case RELOP_LT:
          putNumberInKey(i,floor(d));
          m_relop      = RELOP_LE;
          m_fieldCount = i + 1;
          return true;
        }
      }
    } else if(keyType == DBTYPE_FLOAT || keyType == DBTYPE_FLOATN) {
      if(validFloat(d)) {
        putNumberInKey(i,d);
      } else {
        switch(m_relop) {
        case RELOP_EQ:
          m_key.init();
          m_fieldCount = 0;
          m_relop      = RELOP_FALSE;
          return true;
        case RELOP_GE:
        case RELOP_GT:
          putNumberInKey(i,roundUpToNearestFloat(d));
          m_relop      = RELOP_GE;
          m_fieldCount = i + 1;
          return true;
        case RELOP_LE:
        case RELOP_LT:
          putNumberInKey(i,roundDownToNearestFloat(d));
          m_relop      = RELOP_LE;
          m_fieldCount = i + 1;
          return true;
        }
      }
    } else {
      putNumberInKey(i,d);
    }
  } else if(c < 0) {
    switch(m_relop) {
    case RELOP_EQ:
      m_key.init();
      m_fieldCount = 0;
      m_relop      = RELOP_FALSE;
      return true;
    case RELOP_GE:
    case RELOP_GT:
      m_fieldCount = i;
      return true;
    case RELOP_LE:
    case RELOP_LT:
      m_relop      = RELOP_LT;
      m_fieldCount = i;
      return true;
    }
  } else { // c > 0
    switch(m_relop) {
    case RELOP_EQ:
      m_key.init();
      m_fieldCount = 0;
      m_relop      = RELOP_FALSE;
      return true;
    case RELOP_GE:
    case RELOP_GT:
      m_relop      = RELOP_GT;
      m_fieldCount = i;
      return true;
    case RELOP_LE:
    case RELOP_LT:
      m_fieldCount = i;
      return true;
    }
  }
  return false;
}
コード例 #12
0
bool validUlong(double d) {
  return isInteger(d) && (rangecmp(d,DBTYPE_ULONG) == 0 );
}
コード例 #13
0
bool validUint(double d) {
  return isInteger(d) && (rangecmp(d,DBTYPE_UINT) == 0  );
}
コード例 #14
0
bool validUshort(double d) {
  return isInteger(d) && (rangecmp(d,DBTYPE_USHORT) == 0);
}
コード例 #15
0
ファイル: merge_windows.cpp プロジェクト: LTLA/csaw
SEXP merge_windows(SEXP chrs, SEXP start, SEXP end, SEXP sign, SEXP tolerance, SEXP max_size) try {
	if (!isInteger(chrs)) { throw std::runtime_error("chromosomes should be a integer vector"); }
	if (!isInteger(start)) { throw std::runtime_error("start vector should be integer"); }
	if (!isInteger(end)) { throw std::runtime_error("end vector should be integer"); }
	if (!isLogical(sign)) { throw std::runtime_error("sign vector should be logical"); }
	if (!isInteger(tolerance) || LENGTH(tolerance)!=1) { throw std::runtime_error("tolerance should be an integer scalar"); }

	// Setting up pointers.
	const int* cptr=INTEGER(chrs);
	const int* sptr=INTEGER(start);
	const int* eptr=INTEGER(end);
	const int* lptr=LOGICAL(sign);
	const int tol=asInteger(tolerance);
	
	// Checking whether we need to supply a maximum size.
	if (!isInteger(max_size) || LENGTH(max_size) > 1) { throw std::runtime_error("maximum size should be an integer scalar"); }
	const bool limit_size=(LENGTH(max_size)==1);
	const int maxs=(limit_size ? asInteger(max_size) : 0);
	
	// Providing some protection against an input empty list.
	const int n = LENGTH(chrs);
	if (n!=LENGTH(start) || n!=LENGTH(end) || n!=LENGTH(sign)) { throw std::runtime_error("lengths of vectors are not equal"); }
		
	// Proceeding with the merge operation.
	SEXP output=PROTECT(allocVector(VECSXP, 4));
	try {
		SET_VECTOR_ELT(output, 0, allocVector(INTSXP, n));
		if (n==0) {
			fillSEXP(output, 0);
			UNPROTECT(1);
			return output;
		}
		int* optr=INTEGER(VECTOR_ELT(output, 0));
		int start_index=0, last_end=*eptr;
		bool diffchr, diffsign, nested=false, warned=false;
        int last_sign=*lptr;
		int i, ngroups;
		*optr=ngroups=1;

		for (i=1; i<n; ++i) {
			diffchr=(cptr[i]!=cptr[i-1]);
            diffsign=(lptr[i]!=last_sign);

			/* Fully nested regions don't have a properly defined interpretation when it comes
 			 * to splitting things by sign. We only support consideration of nested regions where
 			 * either of the boundaries are the same. That can be considered to break the 
 			 * previous stretch if it had opposite sign. Otherwise, the next window would have to
 			 * make the decision to match the parent window or its nested child.
 			 *
 			 * If the start is the same, the window with the earlier end point should be ordered
 			 * first, so that won't pass the first 'if'. This means that it'll only enter with
 			 * a fully nested window. Start and end-point equality might be possible at the ends 
 			 * of chromosomes where trimming enforces sameness, but full nesting should not be observed.
 			 *
 			 * If the nested region has the same sign as the parent, then everything proceeds
 			 * normally i.e. same cluster. We make sure to keep 'last_end' as the parent end in
 			 * such cases. This ensures that the following windows get a change to compute
 			 * distances to the parent end (which should be closer).
 			 */
            nested=(!diffchr && eptr[i] < last_end);
 		    if (nested) { 
 			   	if (diffsign && !warned) { 
                    warning("fully nested windows of opposite sign are present and ignored"); 
                    warned=true;
                    diffsign=false;
                }
			} 

			if (diffchr 											// Obviously, changing if we're on a different chromosome.
				|| sptr[i]-last_end-1 > tol							// Space between windows, start anew if this is greater than the tolerance.
				|| diffsign 										// Checking if the sign is consistent.
		   	) {
 			    if (limit_size) { ngroups=split_cluster(sptr, eptr, last_end, start_index, i, maxs, optr); } // Splitting the cluster, if desired.
				++ngroups;
				optr[i]=ngroups; 
				start_index=i;
			} else {
				optr[i]=optr[i-1];
			}

            // Using the parent window as the endpoint if it's nested, but otherwise bumping up the last stats.
            if (!nested) { 
                last_end=eptr[i]; 
                last_sign=lptr[i];
            }
		}

		// Cleaning up the last cluster, if necessary.
  	  	if (limit_size) { ngroups=split_cluster(sptr, eptr, last_end, start_index, n, maxs, optr); }

		// Now, identifying the chromosome, start and end of each region.
		fillSEXP(output, ngroups);
		int* ocptr=INTEGER(VECTOR_ELT(output, 1));
		int* osptr=INTEGER(VECTOR_ELT(output, 2));
		int* oeptr=INTEGER(VECTOR_ELT(output, 3));
		for (i=0; i<ngroups; ++i) { ocptr[i] = -1; }

		int curgroup;
		for (i=0; i<n; ++i) { 
			curgroup=optr[i]-1;
			if (ocptr[curgroup]<0) { 
				ocptr[curgroup]=cptr[i];
				osptr[curgroup]=sptr[i]; // Sorted by start, remember; only need this once.
				oeptr[curgroup]=eptr[i];
			} else if (oeptr[curgroup] < eptr[i]) { 
				oeptr[curgroup]=eptr[i]; 
			}
		}
	} catch (std::exception& e){
		UNPROTECT(1);
		throw;
	}
	
	UNPROTECT(1);
	return output;		
} catch (std::exception& e) {
	return mkString(e.what());
}
コード例 #16
0
ファイル: rcatnet_search.cpp プロジェクト: cran/sdnet
SEXP RDagSearch::estimate(SEXP rSamples, SEXP rPerturbations, SEXP rClasses, SEXP rClsdist, 
			SEXP rMaxParents, SEXP rParentSizes, SEXP rMaxComplexity, SEXP rOrder, SEXP rNodeCats, 
			SEXP rParentsPool, SEXP rFixedParentsPool, SEXP rMatEdgeLiks, SEXP rUseCache, SEXP rEcho, int bIntSample = 0) {

	int i, j, k, len, maxParentSet, maxCategories, maxComplexity, bEqualCategories, node, echo, klmode;
 	int *pRperturbations, *pPerturbations, **parentsPool, **fixedParentsPool, *pPool, *pParentSizes;
	double *matEdgeLiks, *pMatEdgeLiks;
	SEXP dim, rnodecat, rparpool;

	int sampleline, *pNodeOffsets;
	int *pRsamples, *pSamples;
	double *pfRsamples, *pfSamples;
	DAG_LIST<double, int> *pDagList;
	int hasClasses, *pRclasses, *pClasses;

	if(!isMatrix(rSamples))
		error("Data is not a matrix");

	PROTECT(rMaxParents = AS_INTEGER(rMaxParents));
	maxParentSet = INTEGER_POINTER(rMaxParents)[0];
	UNPROTECT(1);

	PROTECT(rMaxComplexity = AS_INTEGER(rMaxComplexity));
	maxComplexity = INTEGER_POINTER(rMaxComplexity)[0];
	UNPROTECT(1);

	PROTECT(rEcho = AS_LOGICAL(rEcho));
	echo = LOGICAL(rEcho)[0];
	UNPROTECT(1);

	klmode = 0;
	PROTECT(rClsdist = AS_INTEGER(rClsdist));
	klmode = INTEGER_POINTER(rClsdist)[0];
	UNPROTECT(1);

	hasClasses = 0;
	if(!isNull(rClasses) && isInteger(rClasses))
		hasClasses = 1;

	sampleline = 0;
	if(bIntSample) {
		dim = GET_DIM(rSamples);
		m_numNodes = INTEGER(dim)[0];
		m_numSamples = INTEGER(dim)[1]; 
	}
	else {
		dim = GET_DIM(rSamples);
		sampleline = INTEGER(dim)[0];
		m_numSamples = INTEGER(dim)[1]; 
		if(isNull(rNodeCats)) 
			error("Node categories must be specified");
		m_numNodes = length(rNodeCats);
	}

	if(m_pRorder)
		CATNET_FREE(m_pRorder);
	m_pRorder = (int*)CATNET_MALLOC(m_numNodes*sizeof(int));
	if (!m_pRorder) {
		CATNET_MEM_ERR();
	}

	PROTECT(rOrder = AS_INTEGER(rOrder));
	if(length(rOrder) < m_numNodes) {
		warning("Invalid nodeOrder parameter - reset to default node order.");
		for(i = 0; i < m_numNodes; i++)
			m_pRorder[i] = i + 1;
	}
	else {
		memcpy(m_pRorder, INTEGER(rOrder), m_numNodes*sizeof(int));
	}
	UNPROTECT(1);

	if(m_pSearchParams)
		delete m_pSearchParams;
	m_pSearchParams = new SEARCH_PARAMETERS(
		m_numNodes, m_numSamples, 
		maxParentSet, maxComplexity, echo, 
		!isNull(rNodeCats), 
		!isNull(rParentSizes), !isNull(rPerturbations), 
		!isNull(rParentsPool), !isNull(rFixedParentsPool), 
		!isNull(rMatEdgeLiks), 0, 
		NULL, this, sampleline, 0, hasClasses, klmode);
	if (!m_pSearchParams) {
		CATNET_MEM_ERR();
	}

	pPerturbations = 0;
	if(!isNull(rPerturbations)) {
		PROTECT(rPerturbations = AS_INTEGER(rPerturbations));
		pPerturbations = m_pSearchParams->m_pPerturbations;
		pRperturbations = INTEGER_POINTER(rPerturbations);
		for(j = 0; j < m_numSamples; j++) {
			for(i = 0; i < m_numNodes; i++) {
				pPerturbations[j*m_numNodes + i] = pRperturbations[j*m_numNodes + m_pRorder[i] - 1];
			}
		}
		UNPROTECT(1);
	}

	if(hasClasses) {
		pClasses = (int*)m_pSearchParams->m_pClasses;
		PROTECT(rClasses = AS_INTEGER(rClasses));
		pRclasses = INTEGER(rClasses);
		memcpy(pClasses, pRclasses, m_numSamples*sizeof(int));
		UNPROTECT(1); // rClasses
	}

	parentsPool = 0;
	if(!isNull(rParentsPool)) {
		PROTECT(rParentsPool = AS_LIST(rParentsPool));
		parentsPool = m_pSearchParams->m_parentsPool;
		for(i = 0; i < m_numNodes; i++) {
			rparpool = AS_INTEGER(VECTOR_ELT(rParentsPool, (int)(m_pRorder[i] - 1)));
			len = length(rparpool);
			if(isVector(rparpool) && len > 0 && len <= m_numNodes) {
				parentsPool[i] = (int*)CATNET_MALLOC((len+1)*sizeof(int));
				pPool = INTEGER(rparpool);
				if (parentsPool[i] && pPool) {
					for(j = 0; j < len; j++) {
						if(pPool[j] > 0 && pPool[j] <= m_numNodes) {
							for(k = 0; k < m_numNodes; k++)
								if(pPool[j] == m_pRorder[k])
									break;
							if(k < m_numNodes)
								parentsPool[i][j] = k;
							else
								parentsPool[i][j] = -1;
						}
					}
					parentsPool[i][len] = -1;
				}
				if(m_pSearchParams->m_maxParentsPool < len)
					m_pSearchParams->m_maxParentsPool = len;
			}
		}
		UNPROTECT(1);
	}

	fixedParentsPool = 0;
	if(!isNull(rFixedParentsPool)) {
		PROTECT(rFixedParentsPool = AS_LIST(rFixedParentsPool));
		fixedParentsPool = m_pSearchParams->m_fixedParentsPool;
		for(i = 0; i < m_numNodes; i++) {
			rparpool = AS_INTEGER(VECTOR_ELT(rFixedParentsPool, (int)(m_pRorder[i] - 1)));
			len = length(rparpool);
			if(isVector(rparpool) && len > 0 && len <= m_numNodes) {
				fixedParentsPool[i] = (int*)CATNET_MALLOC((len+1)*sizeof(int));
			 	if(maxParentSet < len)
			    		maxParentSet = len;
				pPool = INTEGER(rparpool);
				if (fixedParentsPool[i] && pPool) {
					for(j = 0; j < len; j++) {
						if(pPool[j] > 0 && pPool[j] <= m_numNodes) {
							for(k = 0; k < m_numNodes; k++)
								if(pPool[j] == m_pRorder[k])
									break;
							if(k < m_numNodes)
								fixedParentsPool[i][j] = k;
							else
								fixedParentsPool[i][j] = -1;
						}
					}
					fixedParentsPool[i][len] = -1;
				}
				if(m_pSearchParams->m_maxParentsPool < len)
					m_pSearchParams->m_maxParentsPool = len;
			}
		}
		UNPROTECT(1);
	}

	if(!isNull(rMatEdgeLiks) && m_pSearchParams->m_matEdgeLiks) {
		PROTECT(rMatEdgeLiks = AS_NUMERIC(rMatEdgeLiks));
		matEdgeLiks = m_pSearchParams->m_matEdgeLiks;
		pMatEdgeLiks = REAL(rMatEdgeLiks);
		for(j = 0; j < m_numNodes; j++) {
			for(i = 0; i < m_numNodes; i++) {
				matEdgeLiks[j*m_numNodes + i] = pMatEdgeLiks[(m_pRorder[j] - 1)*m_numNodes + m_pRorder[i] - 1];
			}
		}
		UNPROTECT(1);
	}

	if(!isNull(rParentSizes)) {
		pParentSizes = m_pSearchParams->m_pParentSizes;
		PROTECT(rParentSizes = AS_INTEGER(rParentSizes));
		if(length(rParentSizes) == m_numNodes) { 
			for(i = 0; i < m_numNodes; i++)
				pParentSizes[i] = INTEGER(rParentSizes)[m_pRorder[i] - 1];
		}
		UNPROTECT(1);
	}

	pDagList = 0;

	if(bIntSample) {
		PROTECT(rSamples = AS_INTEGER(rSamples));
		pSamples = (int*)m_pSearchParams->m_pSamples;
		pRsamples = INTEGER(rSamples);
		for(j = 0; j < m_numSamples; j++) {
			for(i = 0; i < m_numNodes; i++) {
				pSamples[j*m_numNodes + i] = pRsamples[j*m_numNodes + m_pRorder[i] - 1];
				if(R_IsNA(pSamples[j*m_numNodes + i]) || pSamples[j*m_numNodes + i] < 1) {
					pSamples[j*m_numNodes + i] = CATNET_NAN;
				}
			}
		}
		UNPROTECT(1); // rSamples
		
		maxCategories = 0;
		if(!isNull(rNodeCats)) {
			PROTECT(rNodeCats = AS_LIST(rNodeCats));
			for(i = 0; i < m_numNodes; i++) {
				rnodecat = AS_INTEGER(VECTOR_ELT(rNodeCats, (int)(m_pRorder[i] - 1)));
				len = length(rnodecat);
				if(maxCategories < len)
					maxCategories = len;
				//if(maxCategories > 0 && maxCategories != len)
				//	CATNET_ERR("Nodes should have equal number of categories");
				if(isVector(rnodecat) && len > 0) {
					m_pSearchParams->m_pNodeNumCats[i] = len;
					m_pSearchParams->m_pNodeCats[i] = (int*)CATNET_MALLOC(len*sizeof(int));
					if (!m_pSearchParams->m_pNodeCats[i]) {
						CATNET_MEM_ERR();
					}
					for(j = 0; j < len; j++)
						m_pSearchParams->m_pNodeCats[i][j] = INTEGER(rnodecat)[j];
				}
			}
			UNPROTECT(1);
		}
		
		bEqualCategories = 1;
		for(i = 0; i < m_numNodes; i++) 
			if(i > 1 && m_pSearchParams->m_pNodeNumCats[i] != m_pSearchParams->m_pNodeNumCats[0])
				bEqualCategories = 0;

		if(bEqualCategories) { 

		switch(maxParentSet) {
		case 1: switch(maxCategories) {
			case 2: pDagList = new DAGD_SEARCH<double, int, int, 1, 2>; break;
			case 3: pDagList = new DAGD_SEARCH<double, int, int, 1, 3>; break;
			case 4: pDagList = new DAGD_SEARCH<double, int, int, 1, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		case 2: switch(maxCategories) {
			case 2: pDagList = new DAGD_SEARCH<double, int, int, 2, 2>; break;
			case 3: pDagList = new DAGD_SEARCH<double, int, int, 2, 3>; break;
			case 4: pDagList = new DAGD_SEARCH<double, int, int, 2, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		case 3: switch(maxCategories) {
			case 2: pDagList = new DAGD_SEARCH<double, int, int, 3, 2>; break;
			case 3: pDagList = new DAGD_SEARCH<double, int, int, 3, 3>; break;
			case 4: pDagList = new DAGD_SEARCH<double, int, int, 3, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		case 4: switch(maxCategories) {
			case 2: pDagList = new DAGD_SEARCH<double, int, int, 4, 2>; break;
			case 3: pDagList = new DAGD_SEARCH<double, int, int, 4, 3>; break;
			case 4: pDagList = new DAGD_SEARCH<double, int, int, 4, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		default: CATNET_NOTSUPP_ERR();break;
		}
		} /* bEqualCategories */
		else {
			switch(maxParentSet) {
			case 1: 
				pDagList = new DAGD_SEARCH_DC<double, int, int, 1>; break;
			case 2: 
				pDagList = new DAGD_SEARCH_DC<double, int, int, 2>; break;
			case 3: 
				pDagList = new DAGD_SEARCH_DC<double, int, int, 3>; break;
			case 4: 
				pDagList = new DAGD_SEARCH_DC<double, int, int, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		} /* !bEqualCategories */

	}
	else /* !bIntSample */ {
		pNodeOffsets = (int*)CATNET_MALLOC(m_numNodes*sizeof(int));
		if (!pNodeOffsets) {
			CATNET_MEM_ERR();
		}
		memset(pNodeOffsets, 0, m_numNodes*sizeof(int));

		maxCategories = 0;
		PROTECT(rNodeCats = AS_LIST(rNodeCats));
		for(i = 0; i < m_numNodes; i++) {
			//rnodecat = AS_INTEGER(VECTOR_ELT(rNodeCats, (int)(m_pRorder[i] - 1)));
			rnodecat = AS_INTEGER(VECTOR_ELT(rNodeCats, i));
			len = length(rnodecat);
			if(maxCategories < len)
				maxCategories = len;
			//if(maxCategories > 0 && maxCategories != len)
			//	CATNET_ERR("Nodes should have equal number of categories");
			pNodeOffsets[i] = len;
			if(i > 0)
				pNodeOffsets[i] = pNodeOffsets[i-1] + len;
			if(isVector(rnodecat) && len > 0) {
				m_pSearchParams->m_pNodeNumCats[i] = len;
				m_pSearchParams->m_pNodeCats[i] = (int*)CATNET_MALLOC(len*sizeof(int));
				if (m_pSearchParams->m_pNodeCats[i]) {
					for(j = 0; j < len; j++)
						m_pSearchParams->m_pNodeCats[i][j] = INTEGER(rnodecat)[j];
				}
			}
		}
		for(i = m_numNodes - 1; i > 0; i--) 
			pNodeOffsets[i] = pNodeOffsets[i-1];
		pNodeOffsets[0] = 0;
		UNPROTECT(1);

		PROTECT(rSamples = AS_NUMERIC(rSamples));
		pfSamples = (double*)m_pSearchParams->m_pSamples;
		pfRsamples = REAL(rSamples);
		int ii = 0;
		if (pfSamples && pfRsamples) {
			for(i = 0; i < m_numNodes; i++) {
				for(j = 0; j < m_numSamples; j++) {
					memcpy(pfSamples+j*sampleline + ii, 
						pfRsamples+j*sampleline + pNodeOffsets[m_pRorder[i] - 1], 
						m_pSearchParams->m_pNodeNumCats[i]*sizeof(double));
					if(R_IsNA(pfSamples[j*sampleline + ii]) || pfSamples[j*sampleline + ii] < 0) {
						pfSamples[j*sampleline + ii] = CATNET_NAN;
					}
				}
				ii += m_pSearchParams->m_pNodeNumCats[i];
			}
		}
		UNPROTECT(1); // rSamples

		CATNET_FREE(pNodeOffsets);
		pNodeOffsets = 0;

		bEqualCategories = 1;
		for(i = 0; i < m_numNodes; i++) 
			if(i > 1 && m_pSearchParams->m_pNodeNumCats[i] != m_pSearchParams->m_pNodeNumCats[0])
				bEqualCategories = 0;

		if(bEqualCategories) {

		switch(maxParentSet) {
		case 1: switch(maxCategories) {
			case 2: pDagList = new DAGP_SEARCH<double, int, 1, 2>; break;
			case 3: pDagList = new DAGP_SEARCH<double, int, 1, 3>; break;
			case 4: pDagList = new DAGP_SEARCH<double, int, 1, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		case 2: switch(maxCategories) {
			case 2: pDagList = new DAGP_SEARCH<double, int, 2, 2>; break;
			case 3: pDagList = new DAGP_SEARCH<double, int, 2, 3>; break;
			case 4: pDagList = new DAGP_SEARCH<double, int, 2, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		case 3: switch(maxCategories) {
			case 2: pDagList = new DAGP_SEARCH<double, int, 3, 2>; break;
			case 3: pDagList = new DAGP_SEARCH<double, int, 3, 3>; break;
			case 4: pDagList = new DAGP_SEARCH<double, int, 3, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		case 4: switch(maxCategories) {
			case 2: pDagList = new DAGP_SEARCH<double, int, 4, 2>; break;
			case 3: pDagList = new DAGP_SEARCH<double, int, 4, 3>; break;
			case 4: pDagList = new DAGP_SEARCH<double, int, 4, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		break;
		default: CATNET_NOTSUPP_ERR();break;
		}
		} /* bEqualCategories */
		else {
			switch(maxParentSet) {
			case 1: 
				pDagList = new DAGP_SEARCH_DC<double, int, 1>; break;
			case 2: 
				pDagList = new DAGP_SEARCH_DC<double, int, 2>; break;
			case 3: 
				pDagList = new DAGP_SEARCH_DC<double, int, 3>; break;
			case 4: 
				pDagList = new DAGP_SEARCH_DC<double, int, 4>; break;
			default: CATNET_NOTSUPP_ERR();break;
			}
		} /* !bEqualCategories */
	}

	if(!pDagList) 
		CATNET_MEM_ERR();

	pDagList->search(m_pSearchParams);

	if(m_pSearchParams)
		delete m_pSearchParams;
	m_pSearchParams = 0;

	if(!pDagList->m_dagPars || pDagList->m_numDags < 1) {
		warning("No networks are found");
		return R_NilValue;
	}

	int *pn;
	SEXP plist, pint, ppars, pLoglik, pComplx;
	SEXP daglist = PROTECT(NEW_OBJECT(MAKE_CLASS("dagEvaluate")));

	PROTECT(pint = NEW_INTEGER(1));
	INTEGER_POINTER(pint)[0] = m_numNodes;
	SET_SLOT(daglist, install("numnodes"), pint);
	UNPROTECT(1);

	PROTECT(pint = NEW_INTEGER(1));
	INTEGER_POINTER(pint)[0] = m_numSamples;
	SET_SLOT(daglist, install("numsamples"), pint);
	UNPROTECT(1);

	PROTECT(pint = NEW_INTEGER(1));
	INTEGER_POINTER(pint)[0] = maxCategories;
	SET_SLOT(daglist, install("maxcats"), pint);
	UNPROTECT(1);

	PROTECT(pint = NEW_INTEGER(1));
	INTEGER_POINTER(pint)[0] = maxParentSet;
	SET_SLOT(daglist, install("maxpars"), pint);
	UNPROTECT(1);

	PROTECT(plist = allocVector(VECSXP, m_numNodes));
	for(k = 0; k < m_numNodes; k++) {
		node = m_pRorder[k]-1;
		if(!pDagList->m_parSlots[k] || pDagList->m_numParSlots[k] <= 0) {
			SET_VECTOR_ELT(plist, node, R_NilValue);
			continue;
		}
		PROTECT(ppars = NEW_INTEGER(pDagList->m_numParSlots[k]/*maxParentSet*/*maxParentSet));
		pn = INTEGER_POINTER(ppars);
		for(j = 0; j < pDagList->m_numParSlots[k]/*maxParentSet*/; j++) {
			i = 0;
			while(i < maxParentSet && pDagList->m_parSlots[k][j*maxParentSet+i] >= 0) {
				pn[j*maxParentSet+i] = 
					m_pRorder[pDagList->m_parSlots[k][j*maxParentSet+i]];
				i++;
			}
			for(; i < maxParentSet; i++)
				pn[j*maxParentSet+i] = 0;
		}
		SET_VECTOR_ELT(plist, node, ppars);
		UNPROTECT(1);
	}
	SET_SLOT(daglist, install("parSlots"), plist);
	UNPROTECT(1);

	PROTECT(plist = allocVector(VECSXP, m_numNodes));
	for(k = 0; k < m_numNodes; k++) {
		node = m_pRorder[k]-1;
		if(!pDagList->m_parLogliks[k] || pDagList->m_numParSlots[k] <= 0) {
			SET_VECTOR_ELT(plist, node, R_NilValue);
			continue;
		}
		PROTECT(ppars = NEW_NUMERIC(pDagList->m_numParSlots[k]));
		memcpy(NUMERIC_POINTER(ppars), pDagList->m_parLogliks[k], pDagList->m_numParSlots[k]*sizeof(double));
		SET_VECTOR_ELT(plist, node, ppars);
		UNPROTECT(1);
	}
	SET_SLOT(daglist, install("parLogliks"), plist);
	UNPROTECT(1);

	PROTECT(plist = allocVector(VECSXP, m_numNodes));
	for(k = 0; k < m_numNodes; k++) {
		node = m_pRorder[k]-1;
		if(!pDagList->m_parComplx[k] || pDagList->m_numParSlots[k] <= 0) {
			SET_VECTOR_ELT(plist, node, R_NilValue);
			continue;
		}
		PROTECT(ppars = NEW_INTEGER(pDagList->m_numParSlots[k]));
		memcpy(INTEGER_POINTER(ppars), pDagList->m_parComplx[k], pDagList->m_numParSlots[k]*sizeof(int));
		SET_VECTOR_ELT(plist, node, ppars);
		UNPROTECT(1);
	}
	SET_SLOT(daglist, install("parComplx"), plist);
	UNPROTECT(1);

	PROTECT(plist = allocVector(VECSXP, m_numNodes));
	for(k = 0; k < m_numNodes; k++) {
		node = m_pRorder[k]-1;
		if(!pDagList->m_parSampleSize[k] || pDagList->m_numParSlots[k] <= 0) {
			SET_VECTOR_ELT(plist, node, R_NilValue);
			continue;
		}
		PROTECT(ppars = NEW_INTEGER(pDagList->m_numParSlots[k]));
		memcpy(INTEGER_POINTER(ppars), pDagList->m_parSampleSize[k], pDagList->m_numParSlots[k]*sizeof(int));
		SET_VECTOR_ELT(plist, node, ppars);
		UNPROTECT(1);
	}
	SET_SLOT(daglist, install("parSampleSize"), plist);
	UNPROTECT(1);

	PROTECT(pint = NEW_INTEGER(1));
	INTEGER_POINTER(pint)[0] = pDagList->m_numDags;
	SET_SLOT(daglist, install("numDags"), pint);
	UNPROTECT(1);

	PROTECT(plist =  allocVector(VECSXP, pDagList->m_numDags));
	PROTECT(pLoglik = NEW_NUMERIC(pDagList->m_numDags));
	PROTECT(pComplx = NEW_INTEGER(pDagList->m_numDags));
	DAG_PARS<double> *pDags = pDagList->m_dagPars;
	char *pParBuff = (char*)CATNET_MALLOC((m_numNodes+1)*sizeof(int));
	int  *pIntBuff =  (int*)CATNET_MALLOC((m_numNodes+1)*sizeof(int));
	int nParBuff;
	if (!pParBuff || !pIntBuff) {
		CATNET_MEM_ERR();
	}
	for(k = 0; k < pDagList->m_numDags && pDags; k++) {
		NUMERIC_POINTER(pLoglik)[k] = pDags->loglik;
		INTEGER_POINTER(pComplx)[k] = pDags->complx;
		if(pDags->numPars == 0) {
			SET_VECTOR_ELT(plist, k, R_NilValue);
			continue;
		}
		nParBuff = m_numNodes;
		if(pDags->compressNumPars(pIntBuff, pParBuff, nParBuff, m_pRorder) <= 0) {
			SET_VECTOR_ELT(plist, k, R_NilValue);
			continue;
		}
		nParBuff = 1 + (int)((nParBuff*sizeof(char))/sizeof(int));
		PROTECT(ppars = NEW_INTEGER(nParBuff));
		memcpy(INTEGER_POINTER(ppars), pParBuff, nParBuff*sizeof(int));
		SET_VECTOR_ELT(plist, k, ppars);
		UNPROTECT(1);
		pDags = pDags->next;
	}

	CATNET_FREE(pParBuff);
	CATNET_FREE(pIntBuff);
	SET_SLOT(daglist, install("numPars"), plist);
	SET_SLOT(daglist, install("loglik"), pLoglik);
	SET_SLOT(daglist, install("complx"), pComplx);
	UNPROTECT(3);

	UNPROTECT(1); // cnet

	delete pDagList;
	pDagList = 0;

	if(m_pRorder)
		CATNET_FREE(m_pRorder);
	m_pRorder = 0;

	return daglist;
}
コード例 #17
0
ファイル: braille.c プロジェクト: junwuwei/brltty
static int
setInetAddress (const char *string, struct sockaddr_in *address) {
  int ok = 1;
  char *hostName = strdup(string);

  if (hostName) {
    char *portNumber = strchr(hostName, ':');

    if (portNumber) {
      *portNumber++ = 0;
    } else {
      portNumber = "";
    }

    memset(address, 0, sizeof(*address));
    address->sin_family = AF_INET;

    if (*hostName) {
      const struct hostent *host = gethostbyname(hostName);
      if (host && (host->h_addrtype == AF_INET) && (host->h_length == sizeof(address->sin_addr))) {
        memcpy(&address->sin_addr, host->h_addr, sizeof(address->sin_addr));
      } else {
        ok = 0;
        logMessage(LOG_WARNING, "Unknown host name: %s", hostName);
      }
    } else {
      address->sin_addr.s_addr = INADDR_ANY;
    }

    if (*portNumber) {
      int port;

      if (isInteger(&port, portNumber)) {
        if ((port > 0) && (port <= 0XFFFF)) {
          address->sin_port = htons(port);
        } else {
          ok = 0;
          logMessage(LOG_WARNING, "Invalid port number: %s", portNumber);
        }
      } else {
        const struct servent *service = getservbyname(portNumber, "tcp");

        if (service) {
          address->sin_port = service->s_port;
        } else {
          ok = 0;
          logMessage(LOG_WARNING, "Unknown service: %s", portNumber);
        }
      }
    } else {
      address->sin_port = htons(VR_DEFAULT_PORT);
    }

    free(hostName);
  } else {
    ok = 0;
    logMallocError();
  }

  return ok;
}
コード例 #18
0
ファイル: freadR.c プロジェクト: franknarf1/data.table
_Bool userOverride(int8_t *type, lenOff *colNames, const char *anchor, int ncol)
{
  // use typeSize superfluously to avoid not-used warning; otherwise could move typeSize from fread.h into fread.c
  if (typeSize[CT_BOOL8]!=1) STOP("Internal error: typeSize[CT_BOOL8] != 1");
  if (typeSize[CT_STRING]!=8) STOP("Internal error: typeSize[CT_STRING] != 1");
  colNamesSxp = NULL;
  if (colNames!=NULL) {
    colNamesSxp = PROTECT(allocVector(STRSXP, ncol));
    protecti++;
    for (int i=0; i<ncol; i++) {
      SEXP this;
      if (colNames[i].len<=0) {
        char buff[10];
        sprintf(buff,"V%d",i+1);
        this = mkChar(buff);
      } else {
        this = mkCharLenCE(anchor+colNames[i].off, colNames[i].len, ienc);
      }
      SET_STRING_ELT(colNamesSxp, i, this);
    }
  }
  if (length(colClassesSxp)) {
    SEXP typeRName_sxp = PROTECT(allocVector(STRSXP, NUT));
    protecti++;
    for (int i=0; i<NUT; i++) SET_STRING_ELT(typeRName_sxp, i, mkChar(typeRName[i]));
    if (isString(colClassesSxp)) {
      SEXP typeEnum_idx = PROTECT(chmatch(colClassesSxp, typeRName_sxp, NUT, FALSE));
      protecti++;
      if (LENGTH(colClassesSxp)==1) {
        signed char newType = typeEnum[INTEGER(typeEnum_idx)[0]-1];
        if (newType == CT_DROP) STOP("colClasses='drop' is not permitted; i.e. to drop all columns and load nothing");
        for (int i=0; i<ncol; i++) type[i]=newType;   // freadMain checks bump up only not down
      } else if (LENGTH(colClassesSxp)==ncol) {
        for (int i=0; i<ncol; i++) {
          if (STRING_ELT(colClassesSxp,i)==NA_STRING) continue; // user is ok with inherent type for this column
          type[i] = typeEnum[INTEGER(typeEnum_idx)[i]-1];
        }
      } else {
        STOP("colClasses is an unnamed character vector but its length is %d. Must be length 1 or ncol (%d in this case) when unnamed. To specify types for a subset of columns you can either name the items with the column names or pass list() format to colClasses using column names or column numbers. See examples in ?fread.",
              LENGTH(colClassesSxp), ncol);
      }
    } else {
      if (!isNewList(colClassesSxp)) STOP("CfreadR: colClasses is not type list");
      if (!length(getAttrib(colClassesSxp, R_NamesSymbol))) STOP("CfreadR: colClasses is type list but has no names");
      SEXP typeEnum_idx = PROTECT(chmatch(getAttrib(colClassesSxp, R_NamesSymbol), typeRName_sxp, NUT, FALSE));
      protecti++;
      for (int i=0; i<LENGTH(colClassesSxp); i++) {
        SEXP items;
        signed char thisType = typeEnum[INTEGER(typeEnum_idx)[i]-1];
        items = VECTOR_ELT(colClassesSxp,i);
        if (thisType == CT_DROP) {
          if (!isNull(dropSxp) || !isNull(selectSxp)) STOP("Can't use NULL in colClasses when select or drop is used as well.");
          dropSxp = items;
          continue;
        }
        SEXP itemsInt;
        if (isString(items)) itemsInt = PROTECT(chmatch(items, colNamesSxp, NA_INTEGER, FALSE));
        else itemsInt = PROTECT(coerceVector(items, INTSXP));
        protecti++;
        for (int j=0; j<LENGTH(items); j++) {
          int k = INTEGER(itemsInt)[j];
          if (k==NA_INTEGER) {
            if (isString(items)) STOP("Column name '%s' in colClasses[[%d]] not found", CHAR(STRING_ELT(items, j)),i+1);
            else STOP("colClasses[[%d]][%d] is NA", i+1, j+1);
          } else {
            if (k<1 || k>ncol) STOP("Column number %d (colClasses[[%d]][%d]) is out of range [1,ncol=%d]",k,i+1,j+1,ncol);
            k--;
            if (type[k]<0) STOP("Column '%s' appears more than once in colClasses", CHAR(STRING_ELT(colNamesSxp,k)));
            type[k] = -thisType;
            // freadMain checks bump up only not down.  Deliberately don't catch here to test freadMain; e.g. test 959
          }
        }
      }
      for (int i=0; i<ncol; i++) if (type[i]<0) type[i] *= -1;  // undo sign; was used to detect duplicates
    }
  }
  if (readInt64As != CT_INT64) {
    for (int i=0; i<ncol; i++) if (type[i]==CT_INT64) type[i] = readInt64As;
  }
  if (length(dropSxp)) {
    SEXP itemsInt;
    if (isString(dropSxp)) itemsInt = PROTECT(chmatch(dropSxp, colNamesSxp, NA_INTEGER, FALSE));
    else itemsInt = PROTECT(coerceVector(dropSxp, INTSXP));
    protecti++;
    for (int j=0; j<LENGTH(itemsInt); j++) {
      int k = INTEGER(itemsInt)[j];
      if (k==NA_INTEGER) {
        if (isString(dropSxp)) {
          DTWARN("Column name '%s' in 'drop' not found", CHAR(STRING_ELT(dropSxp, j)));
        } else {
          DTWARN("drop[%d] is NA", j+1);
        }
      } else {
        if (k<1 || k>ncol) {
          DTWARN("Column number %d (drop[%d]) is out of range [1,ncol=%d]",k,j+1,ncol);
        } else {
          if (type[k-1] == CT_DROP) STOP("Duplicates detected in drop");
          type[k-1] = CT_DROP;
        }
      }
    }
  } else if (length(selectSxp)) {
    SEXP tt;
    if (isString(selectSxp)) {
      // invalid cols check part of #1445 moved here (makes sense before reading the file)
      tt = PROTECT(chmatch(selectSxp, colNamesSxp, NA_INTEGER, FALSE));
      protecti++;
      for (int i=0; i<length(selectSxp); i++) if (INTEGER(tt)[i]==NA_INTEGER)
        DTWARN("Column name '%s' not found in column name header (case sensitive), skipping.", CHAR(STRING_ELT(selectSxp, i)));
    } else tt = selectSxp;
    for (int i=0; i<LENGTH(tt); i++) {
      int k = isInteger(tt) ? INTEGER(tt)[i] : (int)REAL(tt)[i];
      if (k == NA_INTEGER) continue;
      if (k<1 || k>ncol) STOP("Column number %d (select[%d]) is out of range [1,ncol=%d]",k,i+1,ncol);
      if (type[k-1]<0) STOP("Column number %d ('%s') has been selected twice by select=", k, STRING_ELT(colNames,k-1));
      type[k-1] *= -1; // detect and error on duplicates on all types without calling duplicated() at all
    }
    for (int i=0; i<ncol; i++) {
      if (type[i]<0) type[i] *= -1;
      else type[i]=CT_DROP;
    }
  }
  return TRUE;  // continue
}
コード例 #19
0
ファイル: Parser.c プロジェクト: joshua-newhouse/nand2tetris
/* Parser_advance: parses the current line and stores the info in the Parser_command structure */
int Parser_advance(char *s, Parser_command *cmd, int *fIndex){
	int strPos = strlen(s);
	while(strPos > 0){
		switch(*s){
		case '\n':			/* Skip blank lines */
			return 0;
		case ' ':			/* Skip white space */
		case '\t':
		case '\0':
			skipWhiteSpace(s);
			break;
		case '/':			/* Ignore comments */
			if(*++s == '/')
				return 0;
			else
				errCMD(--s, nLine, 30);
		case '-':			/* Negative numbers not allowed */
			errCMD(s, nLine, 30);
		case '0': case '1': case '2': case '3': case '4':	/* Captures trailing number for certain commands */
		case '5': case '6': case '7': case '8': case '9':
			markStrEnd(s);
			if((cmd->commandType == C_PUSH || cmd->commandType == C_POP ||
			   cmd->commandType == C_FUNCTION || cmd->commandType == C_CALL) && isInteger(s)){
				cmd->arg2 = s;
				return 1;
			}
			else
				errCMD(s, nLine, 31);
		default:
			markStrEnd(s);
			int i;
			for(i = 0; stackOpsTab[i] && !cmd->arg1; i++){
				if(!strcmp(s, stackOpsTab[i])){		/* C_PUSH or C_POP */
					cmd->commandType = i + 1;
					moveToNextStr(s);
					skipWhiteSpace(s);
					markStrEnd(s);
					break;
				}
			}
			if(!(cmd->commandType == C_PUSH || cmd->commandType == C_POP || cmd->commandType == C_RETURN)){
				if((i = isArith(s)) && !cmd->arg1){	/* C_ARITHMETIC and assigns operation to arg 1 */
					cmd->commandType = C_ARITHMETIC;
					cmd->arg1 = arithTab[i-1];
					moveToNextStr(s);
				}
				else
					errCMD(s, nLine, 32);
				return 1;
			}
			for(i = 0; memSegTab[i] && (cmd->commandType == C_PUSH || cmd->commandType == C_POP)
				   && cmd->commandType != C_RETURN; i++)
				if(!strcmp(s, memSegTab[i])){		/* assigns memory segment to arg 1 */
					cmd->arg1 = memSegTab[i];
					moveToNextStr(s);
					break;
				}
			if(!cmd->arg1)
				errCMD(s, nLine, 33);
			break;
		}
	}
}
コード例 #20
0
ファイル: type.cpp プロジェクト: jinala/CVC4
IntegerType::IntegerType(const Type& t) throw(IllegalArgumentException) :
  Type(t) {
  PrettyCheckArgument(isNull() || isInteger(), this);
}
コード例 #21
0
ファイル: x_OP_y.c プロジェクト: umanwizard/matrixStats
SEXP x_OP_y(SEXP x, SEXP y, SEXP dim, SEXP operator, SEXP xrows, SEXP xcols, SEXP yidxs, SEXP commute, SEXP naRm, SEXP hasNA, SEXP byRow) {
  SEXP ans = NILSXP;
  int narm, hasna, byrow, commute2;
  int op;
  R_xlen_t nrow, ncol, ny;

  /* Argument 'x' and 'dim': */
  assertArgMatrix(x, dim, (R_TYPE_INT | R_TYPE_REAL), "x");
  nrow = asR_xlen_t(dim, 0);
  ncol = asR_xlen_t(dim, 1);

  /* Argument 'y': */
  assertArgVector(y, (R_TYPE_INT | R_TYPE_REAL), "y");
  ny = xlength(y);

  /* Argument 'byRow': */
  byrow = asLogicalNoNA(byRow, "byrow");

  /* Argument 'commute2': */
  commute2 = asLogicalNoNA(commute, "commute");

  /* Argument 'naRm': */
  narm = asLogicalNoNA(naRm, "na.rm");

  /* Argument 'hasNA': */
  hasna = asLogicalNoNA(hasNA, "hasNA");

  /* Argument 'xrows', 'xcols' and 'yidxs': */
  R_xlen_t nxrows, nxcols, nyidxs;
  int xrowsType, xcolsType, yidxsType;
  void *cxrows = validateIndices(xrows, nrow, 0, &nxrows, &xrowsType);
  void *cxcols = validateIndices(xcols, ncol, 0, &nxcols, &xcolsType);
  void *cyidxs = validateIndices(yidxs, ny, 1, &nyidxs, &yidxsType);

  /* Argument 'operator': */
  op = asInteger(operator);


  if (op == 1) {
    /* Addition */
    if (isReal(x) || isReal(y)) {
      PROTECT(ans = allocMatrix(REALSXP, nxrows, nxcols));
      if (isReal(x) && isReal(y)) {
        x_OP_y_Add_Real_Real[xrowsType][xcolsType][yidxsType](
            REAL(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      } else if (isReal(x) && isInteger(y)) {
        x_OP_y_Add_Real_Integer[xrowsType][xcolsType][yidxsType](
            REAL(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      } else if (isInteger(x) && isReal(y)) {
        x_OP_y_Add_Integer_Real[xrowsType][xcolsType][yidxsType](
            INTEGER(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      }
      UNPROTECT(1);
    } else {
      PROTECT(ans = allocMatrix(INTSXP, nxrows, nxcols));
      x_OP_y_Add_Integer_Integer[xrowsType][xcolsType][yidxsType](
          INTEGER(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, INTEGER(ans), xlength(ans));
      UNPROTECT(1);
    }
  } if (op == 2) {
    /* Subtraction */
    if (isReal(x) || isReal(y)) {
      PROTECT(ans = allocMatrix(REALSXP, nxrows, nxcols));
      if (isReal(x) && isReal(y)) {
        x_OP_y_Sub_Real_Real[xrowsType][xcolsType][yidxsType](
            REAL(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      } else if (isReal(x) && isInteger(y)) {
        x_OP_y_Sub_Real_Integer[xrowsType][xcolsType][yidxsType](
            REAL(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      } else if (isInteger(x) && isReal(y)) {
        x_OP_y_Sub_Integer_Real[xrowsType][xcolsType][yidxsType](
            INTEGER(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      }
      UNPROTECT(1);
    } else {
      PROTECT(ans = allocMatrix(INTSXP, nxrows, nxcols));
      x_OP_y_Sub_Integer_Integer[xrowsType][xcolsType][yidxsType](
          INTEGER(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, INTEGER(ans), xlength(ans));
      UNPROTECT(1);
    }
  } else if (op == 3) {
    /* Multiplication */
    if (isReal(x) || isReal(y)) {
      PROTECT(ans = allocMatrix(REALSXP, nxrows, nxcols));
      if (isReal(x) && isReal(y)) {
        x_OP_y_Mul_Real_Real[xrowsType][xcolsType][yidxsType](
            REAL(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      } else if (isReal(x) && isInteger(y)) {
        x_OP_y_Mul_Real_Integer[xrowsType][xcolsType][yidxsType](
            REAL(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      } else if (isInteger(x) && isReal(y)) {
        x_OP_y_Mul_Integer_Real[xrowsType][xcolsType][yidxsType](
            INTEGER(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
      }
      UNPROTECT(1);
    } else {
      PROTECT(ans = allocMatrix(INTSXP, nxrows, nxcols));
      x_OP_y_Mul_Integer_Integer[xrowsType][xcolsType][yidxsType](
          INTEGER(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, INTEGER(ans), xlength(ans));
      UNPROTECT(1);
    }
  } else if (op == 4) {
    /* Division */
    PROTECT(ans = allocMatrix(REALSXP, nxrows, nxcols));
    if (isReal(x) && isReal(y)) {
      x_OP_y_Div_Real_Real[xrowsType][xcolsType][yidxsType](
          REAL(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
    } else if (isReal(x) && isInteger(y)) {
      x_OP_y_Div_Real_Integer[xrowsType][xcolsType][yidxsType](
          REAL(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
    } else if (isInteger(x) && isReal(y)) {
      x_OP_y_Div_Integer_Real[xrowsType][xcolsType][yidxsType](
          INTEGER(x), nrow, ncol, REAL(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
    } else if (isInteger(x) && isInteger(y)) {
      x_OP_y_Div_Integer_Integer[xrowsType][xcolsType][yidxsType](
          INTEGER(x), nrow, ncol, INTEGER(y), ny, cxrows, nxrows, cxcols, nxcols, cyidxs, nyidxs, byrow, commute2, narm, hasna, REAL(ans), xlength(ans));
    }
    UNPROTECT(1);
  }

  return(ans);
} /* x_OP_y() */
コード例 #22
0
ファイル: fmelt.c プロジェクト: kaybenleroll/datatable
SEXP checkVars(SEXP DT, SEXP id, SEXP measure, Rboolean verbose) {
    int i, ncol=LENGTH(DT), targetcols=0, protecti=0, u=0, v=0;
    SEXP thiscol, idcols = R_NilValue, valuecols = R_NilValue, tmp, booltmp, unqtmp, ans;
    SEXP dtnames = getAttrib(DT, R_NamesSymbol);
    
    if (isNull(id) && isNull(measure)) {
        for (i=0; i<ncol; i++) {
            thiscol = VECTOR_ELT(DT, i);
            if ((isInteger(thiscol) || isNumeric(thiscol) || isLogical(thiscol)) && !isFactor(thiscol)) targetcols++;
        }
        PROTECT(idcols = allocVector(INTSXP, ncol-targetcols)); protecti++;
        PROTECT(valuecols = allocVector(INTSXP, targetcols)); protecti++;
        for (i=0; i<ncol; i++) {
            thiscol = VECTOR_ELT(DT, i);
            if ((isInteger(thiscol) || isNumeric(thiscol) || isLogical(thiscol)) && !isFactor(thiscol)) {
                INTEGER(valuecols)[u++] = i+1;
            } else
                INTEGER(idcols)[v++] = i+1;
        }
        warning("To be consistent with reshape2's melt, id.vars and measure.vars are internally guessed when both are 'NULL'. All non-numeric/integer/logical type columns are conisdered id.vars, which in this case are columns '%s'. Consider providing at least one of 'id' or 'measure' vars in future.", CHAR(STRING_ELT(concat(dtnames, idcols), 0)));
    } else if (!isNull(id) && isNull(measure)) {
        switch(TYPEOF(id)) {
            case STRSXP  : PROTECT(tmp = chmatch(id, dtnames, 0, FALSE)); protecti++; break;
            case REALSXP : PROTECT(tmp = coerceVector(id, INTSXP)); protecti++; break;
            case INTSXP  : PROTECT(tmp = id); protecti++; break;
            default : error("Unknown 'id.var' type %s, must be character or integer vector", type2char(TYPEOF(id)));
        }
        PROTECT(booltmp = duplicated(tmp, FALSE)); protecti++;
        for (i=0; i<length(tmp); i++) {
            if (INTEGER(tmp)[i] <= 0) error("Column '%s' not found in 'data'", CHAR(STRING_ELT(id, i)));
            else if (INTEGER(tmp)[i] > ncol) error("id.var value exceeds ncol(data)");
            else if (!LOGICAL(booltmp)[i]) targetcols++;
            else continue;
        }
        PROTECT(unqtmp = allocVector(INTSXP, targetcols)); protecti++;
        u = 0;
        for (i=0; i<length(booltmp); i++) {
            if (!LOGICAL(booltmp)[i]) {
                INTEGER(unqtmp)[u++] = INTEGER(tmp)[i];
            }
        }
        PROTECT(valuecols = set_diff(unqtmp, ncol)); protecti++;
        PROTECT(idcols = tmp); protecti++;
        if (verbose) Rprintf("'measure.var' is missing. Assigning all columns other than 'id.var' columns which are %s as 'measure.var'.\n", CHAR(STRING_ELT(concat(dtnames, idcols), 0)));
    } else if (isNull(id) && !isNull(measure)) {
        switch(TYPEOF(measure)) {
            case STRSXP  : PROTECT(tmp = chmatch(measure, dtnames, 0, FALSE)); protecti++; break;
            case REALSXP : PROTECT(tmp = coerceVector(measure, INTSXP)); protecti++; break;
            case INTSXP  : PROTECT(tmp = measure); protecti++; break;
            default : error("Unknown 'measure.var' type %s, must be character or integer vector", type2char(TYPEOF(measure)));
        }
        PROTECT(booltmp = duplicated(tmp, FALSE)); protecti++;
        for (i=0; i<length(tmp); i++) {
            if (INTEGER(tmp)[i] <= 0) error("Column '%s' not found in 'data'", CHAR(STRING_ELT(id, i)));
            else if (INTEGER(tmp)[i] > ncol) error("measure.var value exceeds ncol(data)");
            else if (!LOGICAL(booltmp)[i]) targetcols++;
            else continue;
        }
        PROTECT(unqtmp = allocVector(INTSXP, targetcols)); protecti++;
        u = 0;
        for (i=0; i<length(booltmp); i++) {
            if (!LOGICAL(booltmp)[i]) {
                INTEGER(unqtmp)[u++] = INTEGER(tmp)[i];
            }
        }
        PROTECT(idcols = set_diff(unqtmp, ncol)); protecti++;
        PROTECT(valuecols = tmp); protecti++;
        if (verbose) Rprintf("'id.var' is missing. Assigning all columns other than 'measure.var' columns as 'id.var'. Assigned 'id.var's are %s.\n", CHAR(STRING_ELT(concat(dtnames, idcols), 0)));
    } else if (!isNull(id) && !isNull(measure)) {
        switch(TYPEOF(id)) {
            case STRSXP  : PROTECT(tmp = chmatch(id, dtnames, 0, FALSE)); protecti++; break;
            case REALSXP : PROTECT(tmp = coerceVector(id, INTSXP)); protecti++; break;
            case INTSXP  : PROTECT(tmp = id); protecti++; break;
            default : error("Unknown 'id.var' type %s, must be character or integer vector", type2char(TYPEOF(id)));
        }
        for (i=0; i<length(tmp); i++) {
            if (INTEGER(tmp)[i] <= 0) error("Column '%s' or not found in 'data'", CHAR(STRING_ELT(id, i)));
            else if (INTEGER(tmp)[i] > ncol) error("measure.var value exceeds ncol(data)");
        }
        PROTECT(idcols = allocVector(INTSXP, length(tmp))); protecti++;
        idcols = tmp;
        switch(TYPEOF(measure)) {
            case STRSXP  : PROTECT(tmp = chmatch(measure, dtnames, 0, FALSE)); protecti++; break;
            case REALSXP : PROTECT(tmp = coerceVector(measure, INTSXP)); protecti++; break;
            case INTSXP  : PROTECT(tmp = measure); protecti++; break;
            default : error("Unknown 'measure.var' type %s, must be character or integer vector", type2char(TYPEOF(measure)));
        }
        for (i=0; i<length(tmp); i++) {
            if (INTEGER(tmp)[i] <= 0) error("Column '%s' not found in 'data'", CHAR(STRING_ELT(id, i)));
            else if (INTEGER(tmp)[i] > ncol) error("measure.var value exceeds ncol(data)");
        }
        PROTECT(valuecols = allocVector(INTSXP, length(measure))); protecti++;
        valuecols = tmp;
    }

    PROTECT(ans = allocVector(VECSXP, 2)); protecti++;
    SET_VECTOR_ELT(ans, 0, idcols);
    SET_VECTOR_ELT(ans, 1, valuecols);
    UNPROTECT(protecti);
    return(ans);
}
コード例 #23
0
ファイル: freadR.c プロジェクト: franknarf1/data.table
SEXP freadR(
  // params passed to freadMain
  SEXP inputArg,
  SEXP sepArg,
  SEXP decArg,
  SEXP quoteArg,
  SEXP headerArg,
  SEXP nrowLimitArg,
  SEXP skipArg,
  SEXP NAstringsArg,
  SEXP stripWhiteArg,
  SEXP skipEmptyLinesArg,
  SEXP fillArg,
  SEXP showProgressArg,
  SEXP nThreadArg,
  SEXP verboseArg,
  SEXP warnings2errorsArg,

  // extras needed by callbacks from freadMain
  SEXP selectArg,
  SEXP dropArg,
  SEXP colClassesArg,
  SEXP integer64Arg,
  SEXP encodingArg
) {
  verbose = LOGICAL(verboseArg)[0];
  warningsAreErrors = LOGICAL(warnings2errorsArg)[0];

  freadMainArgs args;
  protecti=0;
  ncol = 0;
  const char *ch, *ch2;
  if (!isString(inputArg) || LENGTH(inputArg)!=1)
    error("fread input must be a single character string: a filename or the data itself");
  ch = ch2 = (const char *)CHAR(STRING_ELT(inputArg,0));
  while (*ch2!='\n' && *ch2!='\0') ch2++;
  args.input = (*ch2=='\n') ? ch : R_ExpandFileName(ch); // for convenience so user doesn't have to call path.expand()

  ch = args.input;
  while (*ch!='\0' && *ch!='\n') ch++;
  if (*ch=='\n' || args.input[0]=='\0') {
    if (verbose) DTPRINT("Input contains a \\n (or is \"\"). Taking this to be text input (not a filename)\n");
    args.filename = NULL;
  } else {
    if (verbose) DTPRINT("Input contains no \\n. Taking this to be a filename to open\n");
    args.filename = args.input;
    args.input = NULL;
  }

  if (!isString(sepArg) || LENGTH(sepArg)!=1 || strlen(CHAR(STRING_ELT(sepArg,0)))>1)
    error("CfreadR: sep must be 'auto' or a single character ('\\n' is an acceptable single character)");
  args.sep = CHAR(STRING_ELT(sepArg,0))[0];   // '\0' when default "auto" was replaced by "" at R level

  if (!(isString(decArg) && LENGTH(decArg)==1 && strlen(CHAR(STRING_ELT(decArg,0)))==1))
    error("CfreadR: dec must be a single character such as '.' or ','");
  args.dec = CHAR(STRING_ELT(decArg,0))[0];

  if (!isString(quoteArg) || LENGTH(quoteArg)!=1 || strlen(CHAR(STRING_ELT(quoteArg,0))) > 1)
    error("CfreadR: quote must be a single character or empty \"\"");
  args.quote = CHAR(STRING_ELT(quoteArg,0))[0];

  // header is the only boolean where NA is valid and means 'auto'.
  // LOGICAL in R is signed 32 bits with NA_LOGICAL==INT_MIN, currently.
  args.header = FALSE;
  if (LOGICAL(headerArg)[0]==NA_LOGICAL) args.header = NA_BOOL8;
  else if (LOGICAL(headerArg)[0]==TRUE) args.header = TRUE;

  args.nrowLimit = INT64_MAX;
  // checked at R level
  if (isReal(nrowLimitArg)) {
    if (R_FINITE(REAL(nrowLimitArg)[0]) && REAL(nrowLimitArg)[0]>=0.0) args.nrowLimit = (int64_t)(REAL(nrowLimitArg)[0]);
  } else {
    if (INTEGER(nrowLimitArg)[0]>=0) args.nrowLimit = (int64_t)INTEGER(nrowLimitArg)[0];
  }

  args.skipNrow=0;
  args.skipString=NULL;
  if (isString(skipArg)) {
    args.skipString = CHAR(STRING_ELT(skipArg,0));  // LENGTH==1 was checked at R level
  } else if (isReal(skipArg)) {
    if (R_FINITE(REAL(skipArg)[0]) && REAL(skipArg)[0]>0.0) args.skipNrow = (uint64_t)REAL(skipArg)[0];
  } else if (isInteger(skipArg)) {
    if (INTEGER(skipArg)[0]>0) args.skipNrow = (uint64_t)INTEGER(skipArg)[0];
  } else error("skip must be a single positive numeric (integer or double), or a string to search for");

  if (!isNull(NAstringsArg) && !isString(NAstringsArg))
    error("'na.strings' is type '%s'.  Must be either NULL or a character vector.", type2char(TYPEOF(NAstringsArg)));
  int nnas = length(NAstringsArg);
  if (nnas>100)  // very conservative limit
    error("length(na.strings)==%d. This is too many to allocate pointers for on stack", nnas);
  const char **NAstrings = alloca((nnas + 1) * sizeof(char*));
  for (int i=0; i<nnas; i++)
    NAstrings[i] = CHAR(STRING_ELT(NAstringsArg,i));
  NAstrings[nnas] = NULL;
  args.NAstrings = NAstrings;


  // here we use _Bool and rely on fread at R level to check these do not contain NA_LOGICAL
  args.stripWhite = LOGICAL(stripWhiteArg)[0];
  args.skipEmptyLines = LOGICAL(skipEmptyLinesArg)[0];
  args.fill = LOGICAL(fillArg)[0];
  args.showProgress = LOGICAL(showProgressArg)[0];
  if (INTEGER(nThreadArg)[0]<1) error("nThread(%d)<1", INTEGER(nThreadArg)[0]);
  args.nth = (uint32_t)INTEGER(nThreadArg)[0];
  args.verbose = verbose;
  args.warningsAreErrors = warningsAreErrors;

  // === extras used for callbacks ===
  if (!isString(integer64Arg) || LENGTH(integer64Arg)!=1) error("'integer64' must be a single character string");
  const char *tt = CHAR(STRING_ELT(integer64Arg,0));
  if (strcmp(tt, "integer64")==0) {
    readInt64As = CT_INT64;
  } else if (strcmp(tt, "character")==0) {
    readInt64As = CT_STRING;
  } else if (strcmp(tt,"double")==0 || strcmp(tt,"numeric")==0) {
    readInt64As = CT_FLOAT64;
  } else STOP("Invalid value integer64='%s'. Must be 'integer64', 'character', 'double' or 'numeric'", tt);

  colClassesSxp = colClassesArg;   // checked inside userOverride where it is used.

  if (!isNull(selectArg) && !isNull(dropArg)) STOP("Use either select= or drop= but not both.");
  selectSxp = selectArg;
  dropSxp = dropArg;

  // Encoding, #563: Borrowed from do_setencoding from base R
  // https://github.com/wch/r-source/blob/ca5348f0b5e3f3c2b24851d7aff02de5217465eb/src/main/util.c#L1115
  // Check for mkCharLenCE function to locate as to where where this is implemented.
  tt = CHAR(STRING_ELT(encodingArg, 0));
  if (strcmp(tt, "unknown")==0) ienc = CE_NATIVE;
  else if (strcmp(tt, "Latin-1")==0) ienc = CE_LATIN1;
  else if (strcmp(tt, "UTF-8")==0) ienc = CE_UTF8;
  else STOP("encoding='%s' invalid. Must be 'unknown', 'Latin-1' or 'UTF-8'", tt);
  // === end extras ===

  DT = R_NilValue; // created by callback
  freadMain(args);
  UNPROTECT(protecti);
  return DT;
}
コード例 #24
0
        totalRows = properties.getPropInt64("@recordCount");
    else
        totalRows = UNKNOWN_NUM_ROWS;       // more: could probably count them

    isLocal = properties.hasProp("@local");

    diskMeta->extractKeyedInfo(keyedOffsets, keyedTypes);
    ForEachItemIn(i, keyedTypes)
    {
        IStringSet * set = createRtlStringSet(fieldSize(i));
        set->addAll();
        values.append(*set);
    }

    fileposFieldType = diskMeta->queryType(diskMeta->numColumns()-1);
    assertex(fileposFieldType && fileposFieldType->isInteger());

    //Now gather all the 

    //Default cursor if no filter is applied
    applyFilter();
    return true;
}

__int64 IndexDataSource::numRows(bool force)
{
    if (!filtered)
        return totalRows;

    //If leading component isn't filtered, then this can take a very long time...
    if (!force && values.item(0).isFullSet())
コード例 #25
0
ファイル: braille.c プロジェクト: junwuwei/brltty
static int
dimensionsChanged (BrailleDisplay *brl) {
  int ok = 1;
  const char *word;

  int columns1;
  int rows1;

  int columns2 = 0;
  int rows2 = 0;

  if ((word = nextWord())) {
    if (isInteger(&columns1, word) && (columns1 > 0)) {
      rows1 = 1;

      if ((word = nextWord())) {
        if (isInteger(&rows1, word) && (rows1 > 0)) {
          if ((word = nextWord())) {
            if (isInteger(&columns2, word) && (columns2 > 0)) {
              rows2 = 0;

              if ((word = nextWord())) {
                if (isInteger(&rows2, word) && (rows2 > 0)) {
                } else {
                  logMessage(LOG_WARNING, "invalid status row count: %s", word);
                  ok = 0;
                }
              }
            } else {
              logMessage(LOG_WARNING, "invalid status column count: %s", word);
              ok = 0;
            }
          }
        } else {
          logMessage(LOG_WARNING, "invalid text row count: %s", word);
          ok = 0;
        }
      }
    } else {
      logMessage(LOG_WARNING, "invalid text column count: %s", word);
      ok = 0;
    }
  } else {
    logMessage(LOG_WARNING, "missing text column count");
    ok = 0;
  }

  if (ok) {
    int count1 = columns1 * rows1;
    int count2 = columns2 * rows2;
    unsigned char *braille;
    wchar_t *text;
    unsigned char *status;

    if ((braille = calloc(count1, sizeof(*braille)))) {
      if ((text = calloc(count1, sizeof(*text)))) {
        if ((status = calloc(count2, sizeof(*status)))) {
          brailleColumns = columns1;
          brailleRows = rows1;
          brailleCount = count1;

          statusColumns = columns2;
          statusRows = rows2;
          statusCount = count2;

          if (brailleCells) free(brailleCells);
          brailleCells = braille;
          memset(brailleCells, 0, count1);

          if (textCharacters) free(textCharacters);
          textCharacters = text;
          wmemset(textCharacters, WC_C(' '), count1);

          if (statusCells) free(statusCells);
          statusCells = status;
          memset(statusCells, 0, count2);
          memset(genericCells, 0, GSC_COUNT);

          brl->textColumns = brailleColumns;
          brl->textRows = brailleRows;
          brl->statusColumns = statusColumns;
          brl->statusRows = statusRows;
          return 1;
        }

        free(text);
      }

      free(braille);
    }
  }

  return 0;
}
コード例 #26
0
ファイル: openmp-utils.c プロジェクト: franknarf1/data.table
SEXP setDTthreads(SEXP threads) {
    if (!isInteger(threads) || length(threads) != 1 || INTEGER(threads)[0] < 0) {
        // catches NA too since NA is -ve
        error("Argument to setDTthreads must be a single integer >= 0. \
            Default 0 is recommended to use all CPU.");
    }
コード例 #27
0
ファイル: rcatnet_search.cpp プロジェクト: cran/sdnet
SEXP RCatnetSearchP::estimate(SEXP rSamples, SEXP rPerturbations, SEXP rClasses, SEXP rClsdist, 
			SEXP rMaxParents, SEXP rParentSizes, SEXP rMaxComplexity, SEXP rOrder, SEXP rNodeCats, 
			SEXP rParentsPool, SEXP rFixedParentsPool, SEXP rMatEdgeLiks, SEXP rUseCache, SEXP rEcho) {

	int i, ii, j, k, len, sampleline, bUseCache, maxParentSet, maxComplexity, numnets, inet, echo, klmode;
 	int *pRperturbations, *pPerturbations, *pNodeOffsets, 
		**parentsPool, **fixedParentsPool, *pPool, *pParentSizes, 
		hasClasses, *pRclasses, *pClasses;
	double *pRsamples, *pSamples, *matEdgeLiks, *pMatEdgeLiks;

	RCatnetP rcatnet;
	SEXP dim, rnodecat, rparpool, cnetlist, cnetnode;

	if(!isMatrix(rSamples))
		error("Data is not a matrix");
Rprintf("RCatnetSearchP\n");
	PROTECT(rMaxParents = AS_INTEGER(rMaxParents));
	maxParentSet = INTEGER_POINTER(rMaxParents)[0];
	UNPROTECT(1);

	PROTECT(rMaxComplexity = AS_INTEGER(rMaxComplexity));
	maxComplexity = INTEGER_POINTER(rMaxComplexity)[0];
	UNPROTECT(1);

	PROTECT(rUseCache = AS_LOGICAL(rUseCache));
	bUseCache = LOGICAL(rUseCache)[0];
	//Rprintf("bUseCache = %d\n", bUseCache);
	UNPROTECT(1);

	PROTECT(rEcho = AS_LOGICAL(rEcho));
	echo = LOGICAL(rEcho)[0];
	UNPROTECT(1);

	klmode = 0;
	PROTECT(rClsdist = AS_INTEGER(rClsdist));
	klmode = INTEGER_POINTER(rClsdist)[0];
	UNPROTECT(1);

	hasClasses = 0;
	if(!isNull(rClasses) && isInteger(rClasses))
		hasClasses = 1;

	dim = GET_DIM(rSamples);
	sampleline = INTEGER(dim)[0];
	m_numSamples = INTEGER(dim)[1]; 

	if(isNull(rNodeCats)) 
		error("Node categories must be specified");
	m_numNodes = length(rNodeCats);

	if(m_pSearchParams)
		delete m_pSearchParams;
	m_pSearchParams = new SEARCH_PARAMETERS(
		m_numNodes, m_numSamples, 
		maxParentSet, maxComplexity, echo, 
		!isNull(rNodeCats), 
		!isNull(rParentSizes), !isNull(rPerturbations), 
		!isNull(rParentsPool), !isNull(rFixedParentsPool), 
		!isNull(rMatEdgeLiks), 0, 
		NULL, this, sampleline, 0, hasClasses, klmode);
	if (!m_pSearchParams) {
		CATNET_MEM_ERR();
	}

	if(m_pRorder)
		CATNET_FREE(m_pRorder);
	m_pRorder = (int*)CATNET_MALLOC(m_numNodes*sizeof(int));
	if(m_pRorderInverse)
		CATNET_FREE(m_pRorderInverse);
	m_pRorderInverse = (int*)CATNET_MALLOC(m_numNodes*sizeof(int));
	if (!m_pRorder || !m_pRorderInverse) {
		CATNET_MEM_ERR();
	}

	PROTECT(rOrder = AS_INTEGER(rOrder));
	if(length(rOrder) < m_numNodes) {
		warning("Invalid nodeOrder parameter - reset to default node order.");
		for(i = 0; i < m_numNodes; i++)
			m_pRorder[i] = i + 1;
	}
	else {
		memcpy(m_pRorder, INTEGER(rOrder), m_numNodes*sizeof(int));
	}
	for(i = 0; i < m_numNodes; i++) {
		if(m_pRorder[i] <= 0 || m_pRorder[i] > m_numNodes) {
			error("Invalid nodeOrder parameter");		
		}	
		else
			m_pRorderInverse[m_pRorder[i]-1] = i + 1;
	}
	UNPROTECT(1);

	pNodeOffsets = (int*)CATNET_MALLOC(m_numNodes*sizeof(int));
	if (!pNodeOffsets) {
		CATNET_MEM_ERR();
	}
	memset(pNodeOffsets, 0, m_numNodes*sizeof(int));

	PROTECT(rNodeCats = AS_LIST(rNodeCats));
	for(i = 0; i < m_numNodes; i++) {
		rnodecat = AS_INTEGER(VECTOR_ELT(rNodeCats, i));
		len = length(rnodecat);
		pNodeOffsets[i] = len;
		if(i > 0)
			pNodeOffsets[i] = pNodeOffsets[i-1] + len;
		if(isVector(rnodecat) && len > 0) {
			m_pSearchParams->m_pNodeNumCats[i] = len;
			m_pSearchParams->m_pNodeCats[i] = (int*)CATNET_MALLOC(len*sizeof(int));
			if (m_pSearchParams->m_pNodeCats[i]) {
				for(j = 0; j < len; j++)
					m_pSearchParams->m_pNodeCats[i][j] = INTEGER(rnodecat)[j];
			}
		}
	}
	for(i = m_numNodes - 1; i > 0; i--) 
		pNodeOffsets[i] = pNodeOffsets[i-1];
	pNodeOffsets[0] = 0;
	UNPROTECT(1);

	if(!isNull(rParentSizes)) {
		pParentSizes = m_pSearchParams->m_pParentSizes;
		PROTECT(rParentSizes = AS_INTEGER(rParentSizes));
		if(length(rParentSizes) == m_numNodes) { 
			for(i = 0; i < m_numNodes; i++)
				pParentSizes[i] = INTEGER(rParentSizes)[m_pRorder[i] - 1];
		}
		UNPROTECT(1);
	}
	
	PROTECT(rSamples = AS_NUMERIC(rSamples));
	pSamples  = (double*)m_pSearchParams->m_pSamples;
	pRsamples = REAL(rSamples);
	if (pSamples && pRsamples) {
		ii = 0;
		for(i = 0; i < m_numNodes; i++) {
			for(j = 0; j < m_numSamples; j++) {
				memcpy(pSamples+j*sampleline + ii, 
					pRsamples+j*sampleline + pNodeOffsets[m_pRorder[i] - 1], 
					m_pSearchParams->m_pNodeNumCats[i]*sizeof(double));
				if(R_IsNA(pSamples[j*sampleline + ii]) || pSamples[j*sampleline + ii] < 0) {
					pSamples[j*sampleline + ii] = CATNET_NAN;
				}
			}
			ii += m_pSearchParams->m_pNodeNumCats[i];
		}
	}
	UNPROTECT(1); // rSamples

	CATNET_FREE(pNodeOffsets);
	pNodeOffsets = 0;

	pPerturbations = 0;
	if(!isNull(rPerturbations)) {
		PROTECT(rPerturbations = AS_INTEGER(rPerturbations));
		pPerturbations = m_pSearchParams->m_pPerturbations;
		pRperturbations = INTEGER_POINTER(rPerturbations);
		for(j = 0; j < m_numSamples; j++) {
			for(i = 0; i < m_numNodes; i++) {
				pPerturbations[j*m_numNodes + i] = pRperturbations[j*m_numNodes + m_pRorder[i] - 1];
			}
		}
		UNPROTECT(1);
	}

	if(hasClasses) {
		PROTECT(rClasses = AS_INTEGER(rClasses));
		pClasses = (int*)m_pSearchParams->m_pClasses;
		pRclasses = INTEGER(rClasses);
		if (pClasses && pRclasses)
			memcpy(pClasses, pRclasses, m_numSamples*sizeof(int));
		UNPROTECT(1); // rClasses
	}

	parentsPool = 0;
	if(!isNull(rParentsPool)) {
		PROTECT(rParentsPool = AS_LIST(rParentsPool));
		parentsPool = m_pSearchParams->m_parentsPool;
		for(i = 0; i < m_numNodes; i++) {
			rparpool = AS_INTEGER(VECTOR_ELT(rParentsPool, (int)(m_pRorder[i] - 1)));
			len = length(rparpool);
			if(isVector(rparpool) && len > 0 && len <= m_numNodes) {
				parentsPool[i] = (int*)CATNET_MALLOC((len+1)*sizeof(int));
				pPool = INTEGER(rparpool);
				if (parentsPool[i] && pPool) {
					for(j = 0; j < len; j++) {
						if(pPool[j] > 0 && pPool[j] <= m_numNodes) {
							for(k = 0; k < m_numNodes; k++)
								if(pPool[j] == m_pRorder[k])
									break;
							if(k < m_numNodes)
								parentsPool[i][j] = k;
							else
								parentsPool[i][j] = -1;
						}
					}
					parentsPool[i][len] = -1;
				}
				if(m_pSearchParams->m_maxParentsPool < len)
					m_pSearchParams->m_maxParentsPool = len;
			}
		}
		UNPROTECT(1);
	}

	fixedParentsPool = 0;
	if(!isNull(rFixedParentsPool)) {
		PROTECT(rFixedParentsPool = AS_LIST(rFixedParentsPool));
		fixedParentsPool = m_pSearchParams->m_fixedParentsPool;
		for(i = 0; i < m_numNodes; i++) {
			rparpool = AS_INTEGER(VECTOR_ELT(rFixedParentsPool, (int)(m_pRorder[i] - 1)));
			len = length(rparpool);
			if(isVector(rparpool) && len > 0 && len <= m_numNodes) {
				fixedParentsPool[i] = (int*)CATNET_MALLOC((len+1)*sizeof(int));
			 	if(maxParentSet < len)
			    		maxParentSet = len;
				pPool = INTEGER(rparpool);
				if (fixedParentsPool[i] && pPool) {
					for(j = 0; j < len; j++) {
						if(pPool[j] > 0 && pPool[j] <= m_numNodes) {
							for(k = 0; k < m_numNodes; k++)
								if(pPool[j] == m_pRorder[k])
									break;
							if(k < m_numNodes)
								fixedParentsPool[i][j] = k;
							else
								fixedParentsPool[i][j] = -1;
						}
					}
				}
				fixedParentsPool[i][len] = -1;
				if(m_pSearchParams->m_maxParentsPool < len)
					m_pSearchParams->m_maxParentsPool = len;
			}
		}
		UNPROTECT(1);
	}

	if(!isNull(rMatEdgeLiks) && m_pSearchParams->m_matEdgeLiks) {
		PROTECT(rMatEdgeLiks = AS_NUMERIC(rMatEdgeLiks));
		matEdgeLiks = m_pSearchParams->m_matEdgeLiks;
		pMatEdgeLiks = REAL(rMatEdgeLiks);
		for(j = 0; j < m_numNodes; j++) {
			for(i = 0; i < m_numNodes; i++) {
				matEdgeLiks[j*m_numNodes + i] = pMatEdgeLiks[(m_pRorder[j] - 1)*m_numNodes + m_pRorder[i] - 1];
			}
		}
		UNPROTECT(1);
	}

	if(bUseCache)
		setCacheParams(m_numNodes, maxParentSet, m_pRorder, m_pRorderInverse);

	search(m_pSearchParams);

	if(m_pSearchParams)
		delete m_pSearchParams;
	m_pSearchParams = 0;

	if(!m_nCatnets || !m_pCatnets) {
		warning("No networks are found");
		return R_NilValue;
	}

	// create a R-list of catNetworks
	numnets = 0;
	for(i = 0; i < m_nCatnets; i++) {
		if(m_pCatnets[i]) {
			m_pCatnets[i]->setNodesOrder(m_pRorder);
			numnets++;
		}
	}

	PROTECT(cnetlist = allocVector(VECSXP, numnets));

	inet = 0;
	for(i = 0; i < m_nCatnets; i++) {
		if(!m_pCatnets[i])
			continue;

		rcatnet = *m_pCatnets[i];

		PROTECT(cnetnode = rcatnet.genRcatnet("catNetwork"));

		SET_VECTOR_ELT(cnetlist, inet, cnetnode);
		UNPROTECT(1);
		inet++;
	}

	UNPROTECT(1);

	if(m_pRorder)
		CATNET_FREE(m_pRorder);
	m_pRorder = 0;
	if(m_pRorderInverse)
		CATNET_FREE(m_pRorderInverse);
	m_pRorderInverse = 0;
Rprintf("estimate exit");
	return cnetlist;
}
コード例 #28
0
ファイル: pair_reads.cpp プロジェクト: LTLA/csaw
SEXP extract_pair_data(SEXP bam, SEXP index, SEXP chr, SEXP start, SEXP end, SEXP mapq, SEXP dedup, SEXP diagnostics) try {
    // Checking input values.
    if (!isInteger(mapq) || LENGTH(mapq)!=1) {
        throw std::runtime_error("mapping quality should be an integer scalar");
    }    
    const int minqual=asInteger(mapq);

    if (!isLogical(dedup) || LENGTH(dedup)!=1) {
        throw std::runtime_error("duplicate removal should be a logical scalar"); 
    }
    const bool rmdup=asLogical(dedup);

    if (!isLogical(diagnostics) || LENGTH(diagnostics)!=1) { 
        throw std::runtime_error("diagnostics specification should be a logical scalar"); 
    }
    const bool getnames=asLogical(diagnostics);

    // Initializing odds and ends.
    BamFile bf(bam, index);
    BamRead br;
    BamIterator biter(bf, chr, start, end);
    OutputContainer oc(getnames);
        
    typedef std::map<std::pair<int, std::string>, AlignData> Holder;
    std::deque<Holder> all_holders(4); // four holders, one for each strand/first combination; cut down searches.
    std::pair<int, std::string> current;
    Holder::iterator ith;
    int curpos, mate_pos;
    AlignData algn_data;
    bool am_mapped, is_first;

    bool mate_is_in;
    std::set<std::string> identical_pos;
    std::set<std::string>::iterator itip;
    int last_identipos=-1;

    while (bam_itr_next(bf.in, biter.iter, br.read) >= 0){
        ++oc.totals;
        curpos = (br.read->core).pos + 1; // Getting 1-indexed position.
        br.extract_data(algn_data);
        am_mapped=br.is_well_mapped(minqual, rmdup);

        /* Reasons to not add a read: */
       
//        // If we can see that it is obviously unmapped (IMPOSSIBLE for a sorted file).
//        if (((br.read -> core).flag & BAM_FUNMAP)!=0) { 
//            // We don't filter by additional mapping criteria, as we need to search 'holder' to pop out the partner and to store diagnostics.
//            continue;
//        } 
        
        // If it's a singleton.
        if (((br.read -> core).flag & BAM_FPAIRED)==0) {
            if (am_mapped) { oc.add_single(curpos, algn_data); }
            continue;
        }

        // Or, if we can see that its partner is obviously unmapped.
        if (((br.read -> core).flag & BAM_FMUNMAP)!=0) {
            if (am_mapped) { oc.add_onemapped(curpos, algn_data); }
            continue;
        }

        // Or if it's inter-chromosomal.
        is_first=(((br.read->core).flag & BAM_FREAD1)!=0);
        if (is_first==(((br.read->core).flag & BAM_FREAD2)!=0)) { 
            std::stringstream err;
            err << "read '" << bam_get_qname(br.read) << "' must be either first or second in the pair";
            throw std::runtime_error(err.str()); 
        }
      
        if ((br.read -> core).mtid!=(br.read -> core).tid) { 
            if (am_mapped) { oc.add_interchr(curpos, algn_data, bam_get_qname(br.read), is_first); } 
            continue;
        }

        /* Checking the map and adding it if it doesn't exist. */
        
        current.second.assign(bam_get_qname(br.read));
        mate_pos = (br.read -> core).mpos + 1; // 1-indexed position, again.
        mate_is_in=false;
        if (mate_pos < curpos) {
            mate_is_in=true;
        } else if (mate_pos == curpos) {
            // Identical mpos to curpos needs careful handling to figure out whether we've already seen it.
            if (curpos!=last_identipos) { 
                identical_pos.clear();
                last_identipos=curpos;
            }
            itip=identical_pos.lower_bound(current.second);
            if (itip!=identical_pos.end() && !(identical_pos.key_comp()(current.second, *itip))) {
                mate_is_in=true;
                identical_pos.erase(itip);
            } else {
                identical_pos.insert(itip, current.second);
            }
        }

        if (mate_is_in) {
            current.first = mate_pos;
            Holder& holder=all_holders[int(!is_first) + 2*int(bam_is_mrev(br.read))];
            ith=holder.find(current);

            if (ith != holder.end()) { 
                if (!am_mapped) {
                    // Searching to pop out the mate, to reduce the size of 'holder' for the remaining searches (and to store diagnostics).
                    oc.add_onemapped((ith->first).first, ith->second);
                    holder.erase(ith);
                    continue;
                }

                oc.add_genuine(curpos, algn_data, (ith->first).first, ith->second, is_first);
                holder.erase(ith);
            } else if (am_mapped) {
                // Only possible if the mate didn't get added because 'am_mapped' was false.
                oc.add_onemapped(curpos, algn_data);
            }
        } else if (am_mapped) {
            current.first = curpos;
            Holder& holder=all_holders[int(is_first) + 2*int(algn_data.is_reverse)];
            holder[current] = algn_data;
        }
    }

    // Leftovers treated as one_unmapped; marked as paired, but the mate is not in file.
    for (size_t h=0; h<all_holders.size(); ++h) { 
        Holder& holder=all_holders[h];
        for (ith=holder.begin(); ith!=holder.end(); ++ith) { 
            oc.add_onemapped((ith->first).first, ith->second);
        }
        holder.clear();
    }    

    // Storing all output.
    SEXP output=PROTECT(allocVector(VECSXP, getnames ? 9 : 2));
    try {
        SET_VECTOR_ELT(output, 0, allocVector(VECSXP, 2));
        SEXP left=VECTOR_ELT(output, 0);
        store_int_output(left, 0, oc.forward_pos_out);
        store_int_output(left, 1, oc.forward_len_out);
        
        SET_VECTOR_ELT(output, 1, allocVector(VECSXP, 2));
        SEXP right=VECTOR_ELT(output, 1);
        store_int_output(right, 0, oc.reverse_pos_out);
        store_int_output(right, 1, oc.reverse_len_out);
    
        if (getnames) {
            SET_VECTOR_ELT(output, 2, ScalarInteger(oc.totals));
            
            SET_VECTOR_ELT(output, 3, allocVector(VECSXP, 2));
            SEXP singles=VECTOR_ELT(output, 3);
            store_int_output(singles, 0, oc.single_pos);
            store_int_output(singles, 1, oc.single_len);

            SET_VECTOR_ELT(output, 4, allocVector(VECSXP, 2));
            SEXP first=VECTOR_ELT(output, 4);
            store_int_output(first, 0, oc.ufirst_pos);
            store_int_output(first, 1, oc.ufirst_len);
            
            SET_VECTOR_ELT(output, 5, allocVector(VECSXP, 2));
            SEXP second=VECTOR_ELT(output, 5);
            store_int_output(second, 0, oc.usecond_pos);
            store_int_output(second, 1, oc.usecond_len);

            SET_VECTOR_ELT(output, 6, allocVector(VECSXP, 2));
            SEXP onemap=VECTOR_ELT(output, 6);
            store_int_output(onemap, 0, oc.onemap_pos);
            store_int_output(onemap, 1, oc.onemap_len);

            SET_VECTOR_ELT(output, 7, allocVector(VECSXP, 3));
            SEXP interchr1=VECTOR_ELT(output, 7);
            store_int_output(interchr1, 0, oc.ifirst_pos);
            store_int_output(interchr1, 1, oc.ifirst_len);
            store_names(interchr1, 2, oc.interchr_names_1);

            SET_VECTOR_ELT(output, 8, allocVector(VECSXP, 3));
            SEXP interchr2=VECTOR_ELT(output, 8);
            store_int_output(interchr2, 0, oc.isecond_pos);
            store_int_output(interchr2, 1, oc.isecond_len);
            store_names(interchr2, 2, oc.interchr_names_2);
        }
    } catch (std::exception &e) {
        UNPROTECT(1);
        throw;
    }

    UNPROTECT(1);
    return output;
} catch (std::exception &e) {
    return mkString(e.what());
}
コード例 #29
0
ファイル: main.c プロジェクト: dylanzika/rodinia-1
int 
main(	int argc, 
		char *argv [])
{

	//======================================================================================================================================================150
	//	CPU/MCPU VARIABLES
	//======================================================================================================================================================150

	// timer
	long long time0;

	time0 = get_time();

	// timer
	long long time1;
	long long time2;
	long long time3;
	long long time4;
	long long time5;
	long long time6;
	long long time7;

	// counters
	int i, j, k, l, m, n;

	// system memory
	par_str par_cpu;
	dim_str dim_cpu;
	box_str* box_cpu;
	FOUR_VECTOR* rv_cpu;
	fp* qv_cpu;
	FOUR_VECTOR* fv_cpu;
	int nh;

	time1 = get_time();

	//======================================================================================================================================================150
	//	CHECK INPUT ARGUMENTS
	//======================================================================================================================================================150

	// assing default values
	dim_cpu.arch_arg = 0;
	dim_cpu.cores_arg = 1;
	dim_cpu.boxes1d_arg = 1;

	// go through arguments
	if(argc==3){
		for(dim_cpu.cur_arg=1; dim_cpu.cur_arg<argc; dim_cpu.cur_arg++){
			// check if -boxes1d
			if(strcmp(argv[dim_cpu.cur_arg], "-boxes1d")==0){
				// check if value provided
				if(argc>=dim_cpu.cur_arg+1){
					// check if value is a number
					if(isInteger(argv[dim_cpu.cur_arg+1])==1){
						dim_cpu.boxes1d_arg = atoi(argv[dim_cpu.cur_arg+1]);
						if(dim_cpu.boxes1d_arg<0){
							printf("ERROR: Wrong value to -boxes1d argument, cannot be <=0\n");
							return 0;
						}
						dim_cpu.cur_arg = dim_cpu.cur_arg+1;
					}
					// value is not a number
					else{
						printf("ERROR: Value to -boxes1d argument in not a number\n");
						return 0;
					}
				}
				// value not provided
				else{
					printf("ERROR: Missing value to -boxes1d argument\n");
					return 0;
				}
			}
			// unknown
			else{
				printf("ERROR: Unknown argument\n");
				return 0;
			}
		}
		// Print configuration
		printf("Configuration used: arch = %d, cores = %d, boxes1d = %d\n", dim_cpu.arch_arg, dim_cpu.cores_arg, dim_cpu.boxes1d_arg);
	}
	else{
		printf("Provide boxes1d argument, example: -boxes1d 16");
		return 0;
	}

	time2 = get_time();

	//======================================================================================================================================================150
	//	INPUTS
	//======================================================================================================================================================150

	par_cpu.alpha = 0.5;

	time3 = get_time();

	//======================================================================================================================================================150
	//	DIMENSIONS
	//======================================================================================================================================================150

	// total number of boxes
	dim_cpu.number_boxes = dim_cpu.boxes1d_arg * dim_cpu.boxes1d_arg * dim_cpu.boxes1d_arg; // 8*8*8=512

	// how many particles space has in each direction
	dim_cpu.space_elem = dim_cpu.number_boxes * NUMBER_PAR_PER_BOX;							//512*100=51,200
	dim_cpu.space_mem = dim_cpu.space_elem * sizeof(FOUR_VECTOR);
	dim_cpu.space_mem2 = dim_cpu.space_elem * sizeof(fp);

	// box array
	dim_cpu.box_mem = dim_cpu.number_boxes * sizeof(box_str);

	time4 = get_time();

	//======================================================================================================================================================150
	//	SYSTEM MEMORY
	//======================================================================================================================================================150

	//====================================================================================================100
	//	BOX
	//====================================================================================================100

	// allocate boxes
	box_cpu = (box_str*)malloc(dim_cpu.box_mem);

	// initialize number of home boxes
	nh = 0;

	// home boxes in z direction
	for(i=0; i<dim_cpu.boxes1d_arg; i++){
		// home boxes in y direction
		for(j=0; j<dim_cpu.boxes1d_arg; j++){
			// home boxes in x direction
			for(k=0; k<dim_cpu.boxes1d_arg; k++){

				// current home box
				box_cpu[nh].x = k;
				box_cpu[nh].y = j;
				box_cpu[nh].z = i;
				box_cpu[nh].number = nh;
				box_cpu[nh].offset = nh * NUMBER_PAR_PER_BOX;

				// initialize number of neighbor boxes
				box_cpu[nh].nn = 0;

				// neighbor boxes in z direction
				for(l=-1; l<2; l++){
					// neighbor boxes in y direction
					for(m=-1; m<2; m++){
						// neighbor boxes in x direction
						for(n=-1; n<2; n++){

							// check if (this neighbor exists) and (it is not the same as home box)
							if(		(((i+l)>=0 && (j+m)>=0 && (k+n)>=0)==true && ((i+l)<dim_cpu.boxes1d_arg && (j+m)<dim_cpu.boxes1d_arg && (k+n)<dim_cpu.boxes1d_arg)==true)	&&
									(l==0 && m==0 && n==0)==false	){

								// current neighbor box
								box_cpu[nh].nei[box_cpu[nh].nn].x = (k+n);
								box_cpu[nh].nei[box_cpu[nh].nn].y = (j+m);
								box_cpu[nh].nei[box_cpu[nh].nn].z = (i+l);
								box_cpu[nh].nei[box_cpu[nh].nn].number =	(box_cpu[nh].nei[box_cpu[nh].nn].z * dim_cpu.boxes1d_arg * dim_cpu.boxes1d_arg) + 
																			(box_cpu[nh].nei[box_cpu[nh].nn].y * dim_cpu.boxes1d_arg) + 
																			 box_cpu[nh].nei[box_cpu[nh].nn].x;
								box_cpu[nh].nei[box_cpu[nh].nn].offset = box_cpu[nh].nei[box_cpu[nh].nn].number * NUMBER_PAR_PER_BOX;

								// increment neighbor box
								box_cpu[nh].nn = box_cpu[nh].nn + 1;

							}

						} // neighbor boxes in x direction
					} // neighbor boxes in y direction
				} // neighbor boxes in z direction

				// increment home box
				nh = nh + 1;

			} // home boxes in x direction
		} // home boxes in y direction
	} // home boxes in z direction

	//====================================================================================================100
	//	PARAMETERS, DISTANCE, CHARGE AND FORCE
	//====================================================================================================100

	// random generator seed set to random value - time in this case
	srand(time(NULL));

	// input (distances)
	rv_cpu = (FOUR_VECTOR*)malloc(dim_cpu.space_mem);
	for(i=0; i<dim_cpu.space_elem; i=i+1){
		rv_cpu[i].v = (rand()%10 + 1) / 10.0;			// get a number in the range 0.1 - 1.0
		// rv_cpu[i].v = 0.1;			// get a number in the range 0.1 - 1.0
		rv_cpu[i].x = (rand()%10 + 1) / 10.0;			// get a number in the range 0.1 - 1.0
		// rv_cpu[i].x = 0.2;			// get a number in the range 0.1 - 1.0
		rv_cpu[i].y = (rand()%10 + 1) / 10.0;			// get a number in the range 0.1 - 1.0
		// rv_cpu[i].y = 0.3;			// get a number in the range 0.1 - 1.0
		rv_cpu[i].z = (rand()%10 + 1) / 10.0;			// get a number in the range 0.1 - 1.0
		// rv_cpu[i].z = 0.4;			// get a number in the range 0.1 - 1.0
	}

	// input (charge)
	qv_cpu = (fp*)malloc(dim_cpu.space_mem2);
	for(i=0; i<dim_cpu.space_elem; i=i+1){
		qv_cpu[i] = (rand()%10 + 1) / 10.0;			// get a number in the range 0.1 - 1.0
		// qv_cpu[i] = 0.5;			// get a number in the range 0.1 - 1.0
	}

	// output (forces)
	fv_cpu = (FOUR_VECTOR*)malloc(dim_cpu.space_mem);
	for(i=0; i<dim_cpu.space_elem; i=i+1){
		fv_cpu[i].v = 0;								// set to 0, because kernels keeps adding to initial value
		fv_cpu[i].x = 0;								// set to 0, because kernels keeps adding to initial value
		fv_cpu[i].y = 0;								// set to 0, because kernels keeps adding to initial value
		fv_cpu[i].z = 0;								// set to 0, because kernels keeps adding to initial value
	}

	time5 = get_time();

	//======================================================================================================================================================150
	//	KERNEL
	//======================================================================================================================================================150

	//====================================================================================================100
	//	GPU_OPENCL
	//====================================================================================================100

	kernel_gpu_opencl_wrapper(	par_cpu,
								dim_cpu,
								box_cpu,
								rv_cpu,
								qv_cpu,
								fv_cpu);

	time6 = get_time();

	//======================================================================================================================================================150
	//	SYSTEM MEMORY DEALLOCATION
	//======================================================================================================================================================150

	free(rv_cpu);
	free(qv_cpu);
	free(fv_cpu);
	free(box_cpu);

	time7 = get_time();

	//======================================================================================================================================================150
	//	DISPLAY TIMING
	//======================================================================================================================================================150

	// printf("Time spent in different stages of the application:\n");

	// printf("%15.12f s, %15.12f % : VARIABLES\n",						(float) (time1-time0) / 1000000, (float) (time1-time0) / (float) (time7-time0) * 100);
	// printf("%15.12f s, %15.12f % : INPUT ARGUMENTS\n", 					(float) (time2-time1) / 1000000, (float) (time2-time1) / (float) (time7-time0) * 100);
	// printf("%15.12f s, %15.12f % : INPUTS\n",							(float) (time3-time2) / 1000000, (float) (time3-time2) / (float) (time7-time0) * 100);
	// printf("%15.12f s, %15.12f % : dim_cpu\n", 							(float) (time4-time3) / 1000000, (float) (time4-time3) / (float) (time7-time0) * 100);
	// printf("%15.12f s, %15.12f % : SYS MEM: ALO\n",						(float) (time5-time4) / 1000000, (float) (time5-time4) / (float) (time7-time0) * 100);

	// printf("%15.12f s, %15.12f % : KERNEL: COMPUTE\n",					(float) (time6-time5) / 1000000, (float) (time6-time5) / (float) (time7-time0) * 100);

	// printf("%15.12f s, %15.12f % : SYS MEM: FRE\n", 					(float) (time7-time6) / 1000000, (float) (time7-time6) / (float) (time7-time0) * 100);

	// printf("Total time:\n");
	// printf("%.12f s\n", 												(float) (time7-time0) / 1000000);

	//======================================================================================================================================================150
	//	RETURN
	//======================================================================================================================================================150

	return 0.0;																					// always returns 0.0

}
コード例 #30
0
bool validUchar(double d) {
  return isInteger(d) && (rangecmp(d,DBTYPE_UCHAR) == 0 );
}