Example #1
0
int scs (int i, int j)
{
	if (memo[i][j]<0)
    {
		if (a[i]==0)
			memo[i][j] = strlen(b+j);
		else if (b[j]==0)
			memo[i][j] = strlen(a+i);
		else if (a[i]==b[j])
			memo[i][j] = scs(i+1,j+1) + 1;
		else
			memo[i][j] = (scs(i+1,j) < scs(i,j+1)?scs(i+1,j):scs(i,j+1)) + 1;
		
    }
	return memo[i][j];
}
Example #2
0
	SphereConstraintsSet SphereHelpers::getSphereConstraintsSet(std::vector<MedialSpherePtr>& spheres)
	{
		float minRadius = findMinSphereRadius(spheres);
		float maxRadius = findMaxSphereRadius(spheres);
		float minObjectAngle = findMinObjectAngleDegrees(spheres);
		float maxObjectAngle = findMaxObjectAngleDegrees(spheres);
		int numSpheres = spheres.size();

		SphereConstraintsSet scs(minRadius, maxRadius, minObjectAngle, maxObjectAngle, numSpheres);

		return scs;
	}
Example #3
0
int scs_reduce_expand(SequenceList list, int *super, int (*scs)(SequenceList , int *)) {
  int m;
  int len;
  int aux_seq[MAX_LEN], aux_len;
  SequenceList *rlist;

  rlist = reduce (list, &m);
  aux_len = scs (rlist[0], aux_seq);

  len = expand (rlist, m, aux_seq, aux_len, super);

  return len;
}
Example #4
0
File: draw.c Project: akat1/impala
void
draw_box_outline(BOX *box, int mark)
{
  int j;
  int tlc = (mark < 0) ? 'l' : mark;
  int trc = (mark < 0) ? 'k' : mark;
  int llc = (mark < 0) ? 'm' : mark;
  int lrc = (mark < 0) ? 'j' : mark;
  int vrt = (mark < 0) ? 'x' : mark;
  int hrz = (mark < 0) ? 'q' : mark;
  int dot;

  if (mark < 0)
    scs(0, '0');

  for (j = box->top, dot = tlc; j < box->bottom; j++) {
    __(cup(j, box->left), putchar(dot));
    dot = vrt;
  }
  for (j = box->top, dot = trc; j < box->bottom; j++) {
    __(cup(j, box->right), putchar(dot));
    dot = vrt;
  }

  cup(box->top, box->left + 1);
  for (j = box->left + 1; j < box->right; j++)
    putchar(hrz);

  cup(box->bottom, box->left + 1);
  for (j = box->left + 1; j < box->right; j++)
    putchar(hrz);

  __(cup(box->bottom, box->left), putchar(llc));
  __(cup(box->bottom, box->right), putchar(lrc));

  if (mark < 0)
    scs(0, 'B');
}
Example #5
0
void ProvReg_Dump(
    ProvReg* self,
    FILE* os)
{
    ProvRegEntry* p;

    for (p = self->head; p; p = p->next)
    {
        Ftprintf(os, PAL_T("==== ProvRegEntry\n"));
        Ftprintf(os, PAL_T("provInterface[%u]\n"), p->provInterface);
        Ftprintf(os, PAL_T("nameSpace[%T]\n"), tcs(p->nameSpace));
        Ftprintf(os, PAL_T("className[%T]\n"), tcs(p->className));
        Ftprintf(os, PAL_T("libraryName[%s]\n"), scs(p->libraryName));
    }
}
Example #6
0
File: demo.c Project: zhangrj7/scs
int main(int argc, char **argv) {
	FILE * fp;
	Cone * k;
	Data * d;
	Work * w;
	Sol * sol;
	Info info = { 0 };
	scs_int i;

	if (openFile(argc, argv, 1, DEMO_PATH, &fp) < 0)
		return -1;

	k = scs_calloc(1, sizeof(Cone));
	d = scs_calloc(1, sizeof(Data));
	sol = scs_calloc(1, sizeof(Sol));
	if (readInData(fp, d, k) == -1) {
		printf("Error reading in data, aborting.\n");
		return -1;
	}
	fclose(fp);
	scs_printf("solve once using scs\n");
	scs(d, k, sol, &info);

	if (TEST_WARM_START) {
		scs_printf("solve %i times with warm-start and (if applicable) factorization caching.\n", NUM_TRIALS);
		/* warm starts stored in Sol */
		w = scs_init(d, k, &info);
		if (w) {
			for (i = 0; i < NUM_TRIALS; i++) {
				/* perturb b and c */
				perturbVector(d->b, d->m);
				perturbVector(d->c, d->n);
				d->stgs->warm_start = 1;
				d->stgs->cg_rate = 4;
				scs_solve(w, d, k, sol, &info);
				d->stgs->warm_start = 0;
				d->stgs->cg_rate = 2;
				scs_solve(w, d, k, sol, &info);
			}
		}
		scs_printf("finished\n");
		scs_finish(w);
	}

	freeData(d, k);
	freeSol(sol);
	return 0;
}
Example #7
0
void AINodeStimulus::EnableNode()
{
	super::EnableNode();

	// Remove any previously existing stimulus.

	if( m_eStimulusID != kStimID_Invalid )
	{
		g_pAIStimulusMgr->RemoveStimulus( m_eStimulusID );
	}

	// Register the stimulus.

	EnumCharacterAlignment eAlignment = g_pCharacterDB->String2Alignment(g_pAIDB->GetAIConstantsRecord()->strObjectAlignmentName.c_str());
	StimulusRecordCreateStruct scs( m_eStimulusType, eAlignment, m_vPos, m_hObject );
	scs.m_flRadiusScalar = m_fRadius;
	scs.m_flDurationScalar = m_fStimulusDuration;
	m_eStimulusID = g_pAIStimulusMgr->RegisterStimulus( scs );
}
Example #8
0
void solve_case()
{
	int i,j;
	int lena,lenb;
	lena=strlen(a);
	lenb=strlen(b);
	for (i=0; i<=lena; i++){
		for (j=0; j<=lenb; j++)
			memo[i][j] = -1;
	}
	scs(0,0);
	for (i=j=0;;)
	{
		if (a[i]==0)
		{
			printf("%s\n",b+j);
			break;
		}
		else if (b[j]==0)
		{
			printf("%s\n",a+i);
			break;
		}
		else if (a[i]==b[j])
		{
			putchar(a[i]);
			i++; j++;
		}
		else if (memo[i+1][j] <= memo[i][j+1])
		{
			putchar(a[i]);
			i++;
		}
		else
		{
			putchar(b[j]);
			j++;
		}
	}
}
Example #9
0
/* Initialize ProvReg strucutre from given directory */
_Use_decl_annotations_
MI_Result ProvReg_Init(ProvReg* self, const char* directory)
{
    RegFile* reg = NULL;
    Dir* dir = NULL;
    Dir* dir2 = NULL;
    MI_Result r = MI_RESULT_FAILED;
    
    /* Zero-fill self */
    memset(self, 0, sizeof(*self));

    dir = Dir_Open(directory);
    if (!dir)
    {
        return r;
    }

    /* Initialize batch allocator */
    Batch_Init(&self->batch, BATCH_MAX_PAGES);

    /* For each namespace directory in 'omirgister' */
    for (;;)
    {
        DirEnt* ent = Dir_Read(dir);

        if (!ent)
        {
            break;
        }

        /* Ignore system directories */
        if (strcmp(ent->name, ".") == 0 || strcmp(ent->name, "..") == 0)
            continue;

        /* Skip 'CVS' directories */
        if (strcmp(ent->name, "CVS") == 0)
            continue;

        /* Scan .reg files in the current namespace directory */
        {
            char path[PAL_MAX_PATH_SIZE];

            Strlcpy(path, directory, sizeof(path));
            Strlcat(path, "/", sizeof(path));
            Strlcat(path, ent->name, sizeof(path));

            /* Skip if not a dir */
            if(!Isdir(path))
                continue;

            dir2 = Dir_Open(path);
            if (!dir2)
            {
                goto failed;
            }

            for (;;)
            {
                DirEnt* ent2 = Dir_Read(dir2);
                if (!ent2)
                {
                    break;
                }

                /* Ignore system directories */
                if (strcmp(ent2->name,".") == 0 || strcmp(ent2->name,"..") == 0)
                {
                    continue;
                }

                /* Skip non-reg file */
                {
                    char* affix = Strrchr(ent2->name, '.');
                    if (!affix || (Strcasecmp(&affix[1], "reg") != 0))
                        continue;
                }

                /* Load the reg file */
                {
                    char regPath[PAL_MAX_PATH_SIZE];

                    /* Form path to .reg file */
                    Strlcpy(regPath, path, sizeof(regPath));
                    Strlcat(regPath, "/", sizeof(regPath));
                    Strlcat(regPath, ent2->name, sizeof(regPath));

                    /* Create new reg file object */
                    reg = RegFile_New(regPath);
                    if (!reg)
                    {
                        trace_ProvReg_SkipRegFile(scs(regPath));
                        continue;
                    }

                    /* For each class in the reg file */
                    {
                        RegClass* rc;
                        char* p = ent->name;
                        
                        /* Transpose NAMESPACE_SEPARATOR characters to '/' 
                         * characters 
                         */
                        while (*p)
                        {
                            if (*p == NAMESPACE_SEPARATOR)
                                *p = '/';
                            p++;
                        }

                        for (rc = reg->classesHead; rc; rc = rc->next)
                        {
                            if (_AddEntry(self, ent->name, reg, rc) != 0)
                            {
                                goto failed;
                            }
                        }
                    }

                    /* For each extraClass in the reg file */
                    {
                        RegClass* rc;
                        char* p = ent->name;
                        
                        /* Transpose NAMESPACE_SEPARATOR characters to '/' 
                         * characters 
                         */
                        while (*p)
                        {
                            if (*p == NAMESPACE_SEPARATOR)
                                *p = '/';
                            p++;
                        }

                        for (rc = reg->extraClassesHead; rc; rc = rc->next)
                        {
                            if (_AddEntryForExtraClass(self, ent->name, reg, rc) != 0)
                            {
                                goto failed;
                            }
                        }
                    }

                    /* Delete the current entry */
                    RegFile_Delete(reg);
                    reg = NULL;
                }
            }

            /* Close the directory */
            Dir_Close(dir2);
            dir2 = NULL;
        }
    }
    r = MI_RESULT_OK;

failed:
    if (dir2)
    {
        Dir_Close(dir2);
    }
    if (dir)
    {
        Dir_Close(dir);
    }
    if (r != MI_RESULT_OK)
    {
        ProvReg_Destroy(self);
        memset(self, 0, sizeof(*self));
    }
    if(reg)
    {
        RegFile_Delete(reg);
        reg = NULL;
    }
    return r;
}
bool ServerPhysicsCollisionMgr::StartAIStimulusResponse( CollisionResponse& collisionResponse )
{
	// Get the aistimulus record struct.
	HATTRIBUTE hStruct = DATABASE_CATEGORY( CollisionProperty ).GETSTRUCTSTRUCT( Responses, 
		collisionResponse.GetResponses(), collisionResponse.GetResponsesIndex( ), AIStimulusRecord );
	if( !hStruct )
		return false;

	uint32 nIndexFound;
	uint32 nImpulseFound;
	if( !FindImpulseInTable( collisionResponse.GetImpulse( ), hStruct, AIStimulusRecordImpulseAccessCB, nIndexFound, nImpulseFound ))
		return false;

	// Determine the stimulus type.
	HRECORD hStimulus = DATABASE_CATEGORY( CollisionProperty ).GETSTRUCTATTRIB( AIStimulusRecord, hStruct, nIndexFound, Stimulus );
	if( !hStimulus )
		return false;
	const char* pszStimulus = g_pLTDatabase->GetRecordName( hStimulus );
	if( !pszStimulus || !pszStimulus[0] )
		return false;

	// Bail if stimulus does not exist.
	EnumAIStimulusType eStimulus = (EnumAIStimulusType)g_pAIDB->String2BitFlag( pszStimulus, kStim_Count, s_aszStimulusTypes );
	if( eStimulus == kStim_InvalidType )
		return false;

	// Use the generic object alignment set in GDBEdit under AI/Constants.
	EnumCharacterAlignment eAlignment = g_pCharacterDB->String2Alignment(g_pAIDB->GetAIConstantsRecord()->strObjectAlignmentName.c_str());

	// Interpolate the radius of the stimulus.
	float fRadius = FindStimulusRadius( collisionResponse );

	// Bail if either character has sound disabled.
	// This is a hack to prevent AI from generating stimuli.
	// (e.g. at the begining of the FEAR Docks level, where
	// we have a scripted execution scene, and do not want the
	// AI to start investigating when a body hits the ground).
	HOBJECT hActor = collisionResponse.GetCollisionActor()->GetObject();
	HOBJECT hOtherActor = collisionResponse.GetCollisionActor()->GetOtherCollisionActor()->GetObject();

	if( IsCharacter( hActor ) )
	{
		CCharacter* pChar = (CCharacter*)g_pLTServer->HandleToObject( hActor );
		if( pChar && pChar->GetSoundOuterRadius() == 0.f )
		{
			return false;
		}
	}
	if( IsCharacter( hOtherActor ) )
	{
		CCharacter* pChar = (CCharacter*)g_pLTServer->HandleToObject( hOtherActor );
		if( pChar && pChar->GetSoundOuterRadius() == 0.f )
		{
			return false;
		}
	}

	// Register the stimulus.
	StimulusRecordCreateStruct scs( eStimulus, eAlignment, collisionResponse.GetCollisionPoint( ), hActor );
	scs.m_hStimulusTarget = hOtherActor;
	scs.m_flRadiusScalar = fRadius;
	g_pAIStimulusMgr->RegisterStimulus( scs );

#ifndef _FINAL
	uint32 nStatsLevel;
	bool bServer;
	HRECORD hCollisionPropertyFilter = NULL;
	CollisionStatsLevel( nStatsLevel, bServer, hCollisionPropertyFilter );
	if( nStatsLevel > 0 &&
		( !hCollisionPropertyFilter || hCollisionPropertyFilter == collisionResponse.GetCollisionProperty()))
	{
		g_pLTBase->CPrint( "S:  AIStimulus(%s)", pszStimulus );
	}
#endif // _FINAL

	return true;
}
Example #11
0
static PyObject *csolve(PyObject *self, PyObject *args, PyObject *kwargs) {
    /* data structures for arguments */
    PyArrayObject *Ax, *Ai, *Ap, *c, *b;
    PyObject *cone, *warm = SCS_NULL;
    PyObject *verbose = SCS_NULL;
    PyObject *normalize = SCS_NULL;
    /* get the typenum for the primitive scs_int and scs_float types */
    int scs_intType = getIntType();
    int scs_floatType = getFloatType();
    struct ScsPyData ps = {
        SCS_NULL, SCS_NULL, SCS_NULL, SCS_NULL, SCS_NULL,
    };
    /* scs data structures */
    Data *d = scs_calloc(1, sizeof(Data));
    Cone *k = scs_calloc(1, sizeof(Cone));

    AMatrix *A;
    Sol sol = {0};
    Info info;
    char *kwlist[] = {"shape",     "Ax",    "Ai",   "Ap",      "b",
                      "c",         "cone",  "warm", "verbose", "normalize",
                      "max_iters", "scale", "eps",  "cg_rate", "alpha",
                      "rho_x",     SCS_NULL};

/* parse the arguments and ensure they are the correct type */
#ifdef DLONG
#ifdef FLOAT
    char *argparse_string = "(ll)O!O!O!O!O!O!|O!O!O!lfffff";
    char *outarg_string = "{s:l,s:l,s:f,s:f,s:f,s:f,s:f,s:f,s:f,s:f,s:f,s:s}";
#else
    char *argparse_string = "(ll)O!O!O!O!O!O!|O!O!O!lddddd";
    char *outarg_string = "{s:l,s:l,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:s}";
#endif
#else
#ifdef FLOAT
    char *argparse_string = "(ii)O!O!O!O!O!O!|O!O!O!ifffff";
    char *outarg_string = "{s:i,s:i,s:f,s:f,s:f,s:f,s:f,s:f,s:f,s:f,s:f,s:s}";
#else
    char *argparse_string = "(ii)O!O!O!O!O!O!|O!O!O!iddddd";
    char *outarg_string = "{s:i,s:i,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:s}";
#endif
#endif
    npy_intp veclen[1];
    PyObject *x, *y, *s, *returnDict, *infoDict;

    d->stgs = scs_malloc(sizeof(Settings));

    /* set defaults */
    setDefaultSettings(d);

    if (!PyArg_ParseTupleAndKeywords(
            args, kwargs, argparse_string, kwlist, &(d->m), &(d->n),
            &PyArray_Type, &Ax, &PyArray_Type, &Ai, &PyArray_Type, &Ap,
            &PyArray_Type, &b, &PyArray_Type, &c, &PyDict_Type, &cone,
            &PyDict_Type, &warm, &PyBool_Type, &verbose, &PyBool_Type,
            &normalize, &(d->stgs->max_iters), &(d->stgs->scale),
            &(d->stgs->eps), &(d->stgs->cg_rate), &(d->stgs->alpha),
            &(d->stgs->rho_x))) {
        PySys_WriteStderr("error parsing inputs\n");
        return SCS_NULL;
    }

    if (d->m < 0) {
        PyErr_SetString(PyExc_ValueError, "m must be a positive integer");
        return SCS_NULL;
    }

    if (d->n < 0) {
        PyErr_SetString(PyExc_ValueError, "n must be a positive integer");
        return SCS_NULL;
    }

    /* set A */
    if (!PyArray_ISFLOAT(Ax) || PyArray_NDIM(Ax) != 1) {
        return finishWithErr(d, k, &ps, "Ax must be a numpy array of floats");
    }
    if (!PyArray_ISINTEGER(Ai) || PyArray_NDIM(Ai) != 1) {
        return finishWithErr(d, k, &ps, "Ai must be a numpy array of ints");
    }
    if (!PyArray_ISINTEGER(Ap) || PyArray_NDIM(Ap) != 1) {
        return finishWithErr(d, k, &ps, "Ap must be a numpy array of ints");
    }
    ps.Ax = getContiguous(Ax, scs_floatType);
    ps.Ai = getContiguous(Ai, scs_intType);
    ps.Ap = getContiguous(Ap, scs_intType);

    A = scs_malloc(sizeof(AMatrix));
    A->n = d->n;
    A->m = d->m;
    A->x = (scs_float *)PyArray_DATA(ps.Ax);
    A->i = (scs_int *)PyArray_DATA(ps.Ai);
    A->p = (scs_int *)PyArray_DATA(ps.Ap);
    d->A = A;
    /*d->Anz = d->Ap[d->n]; */
    /*d->Anz = PyArray_DIM(Ai,0); */
    /* set c */
    if (!PyArray_ISFLOAT(c) || PyArray_NDIM(c) != 1) {
        return finishWithErr(
            d, k, &ps, "c must be a dense numpy array with one dimension");
    }
    if (PyArray_DIM(c, 0) != d->n) {
        return finishWithErr(d, k, &ps, "c has incompatible dimension with A");
    }
    ps.c = getContiguous(c, scs_floatType);
    d->c = (scs_float *)PyArray_DATA(ps.c);
    /* set b */
    if (!PyArray_ISFLOAT(b) || PyArray_NDIM(b) != 1) {
        return finishWithErr(
            d, k, &ps, "b must be a dense numpy array with one dimension");
    }
    if (PyArray_DIM(b, 0) != d->m) {
        return finishWithErr(d, k, &ps, "b has incompatible dimension with A");
    }
    ps.b = getContiguous(b, scs_floatType);
    d->b = (scs_float *)PyArray_DATA(ps.b);

    if (getPosIntParam("f", &(k->f), 0, cone) < 0) {
        return finishWithErr(d, k, &ps, "failed to parse cone field f");
    }
    if (getPosIntParam("l", &(k->l), 0, cone) < 0) {
        return finishWithErr(d, k, &ps, "failed to parse cone field l");
    }
    if (getConeArrDim("q", &(k->q), &(k->qsize), cone) < 0) {
        return finishWithErr(d, k, &ps, "failed to parse cone field q");
    }
    if (getConeArrDim("s", &(k->s), &(k->ssize), cone) < 0) {
        return finishWithErr(d, k, &ps, "failed to parse cone field s");
    }
    if (getConeFloatArr("p", &(k->p), &(k->psize), cone) < 0) {
        return finishWithErr(d, k, &ps, "failed to parse cone field p");
    }
    if (getPosIntParam("ep", &(k->ep), 0, cone) < 0) {
        return finishWithErr(d, k, &ps, "failed to parse cone field ep");
    }
    if (getPosIntParam("ed", &(k->ed), 0, cone) < 0) {
        return finishWithErr(d, k, &ps, "failed to parse cone field ed");
    }

    d->stgs->verbose = verbose ? (scs_int)PyObject_IsTrue(verbose) : VERBOSE;
    d->stgs->normalize =
        normalize ? (scs_int)PyObject_IsTrue(normalize) : NORMALIZE;
    if (d->stgs->max_iters < 0) {
        return finishWithErr(d, k, &ps, "max_iters must be positive");
    }
    if (d->stgs->scale < 0) {
        return finishWithErr(d, k, &ps, "scale must be positive");
    }
    if (d->stgs->eps < 0) {
        return finishWithErr(d, k, &ps, "eps must be positive");
    }
    if (d->stgs->cg_rate < 0) {
        return finishWithErr(d, k, &ps, "cg_rate must be positive");
    }
    if (d->stgs->alpha < 0) {
        return finishWithErr(d, k, &ps, "alpha must be positive");
    }
    if (d->stgs->rho_x < 0) {
        return finishWithErr(d, k, &ps, "rho_x must be positive");
    }
    /* parse warm start if set */
    d->stgs->warm_start = WARM_START;
    if (warm) {
        d->stgs->warm_start = getWarmStart("x", &(sol.x), d->n, warm);
        d->stgs->warm_start |= getWarmStart("y", &(sol.y), d->m, warm);
        d->stgs->warm_start |= getWarmStart("s", &(sol.s), d->m, warm);
    }

    Py_BEGIN_ALLOW_THREADS
        /* Solve! */
        scs(d, k, &sol, &info);
    Py_END_ALLOW_THREADS

        /* create output (all data is *deep copied*) */
        /* x */
        /* matrix *x; */
        /* if(!(x = Matrix_New(n,1,DOUBLE))) */
        /*   return PyErr_NoMemory(); */
        /* memcpy(MAT_BUFD(x), mywork->x, n*sizeof(scs_float)); */
        veclen[0] = d->n;
    x = PyArray_SimpleNewFromData(1, veclen, scs_floatType, sol.x);
    PyArray_ENABLEFLAGS((PyArrayObject *)x, NPY_ARRAY_OWNDATA);

    /* y */
    /* matrix *y; */
    /* if(!(y = Matrix_New(p,1,DOUBLE))) */
    /*   return PyErr_NoMemory(); */
    /* memcpy(MAT_BUFD(y), mywork->y, p*sizeof(scs_float)); */
    veclen[0] = d->m;
    y = PyArray_SimpleNewFromData(1, veclen, scs_floatType, sol.y);
    PyArray_ENABLEFLAGS((PyArrayObject *)y, NPY_ARRAY_OWNDATA);

    /* s */
    /* matrix *s; */
    /* if(!(s = Matrix_New(m,1,DOUBLE))) */
    /*   return PyErr_NoMemory(); */
    /* memcpy(MAT_BUFD(s), mywork->s, m*sizeof(scs_float)); */
    veclen[0] = d->m;
    s = PyArray_SimpleNewFromData(1, veclen, scs_floatType, sol.s);
    PyArray_ENABLEFLAGS((PyArrayObject *)s, NPY_ARRAY_OWNDATA);

    infoDict = Py_BuildValue(
        outarg_string, "statusVal", (scs_int)info.statusVal, "iter",
        (scs_int)info.iter, "pobj", (scs_float)info.pobj, "dobj",
        (scs_float)info.dobj, "resPri", (scs_float)info.resPri, "resDual",
        (scs_float)info.resDual, "relGap", (scs_float)info.relGap, "resInfeas",
        (scs_float)info.resInfeas, "resUnbdd", (scs_float)info.resUnbdd,
        "solveTime", (scs_float)(info.solveTime), "setupTime",
        (scs_float)(info.setupTime), "status", info.status);

    returnDict = Py_BuildValue("{s:O,s:O,s:O,s:O}", "x", x, "y", y, "s", s,
                               "info", infoDict);
    /* give up ownership to the return dictionary */
    Py_DECREF(x);
    Py_DECREF(y);
    Py_DECREF(s);
    Py_DECREF(infoDict);

    /* no longer need pointers to arrays that held primitives */
    freePyData(d, k, &ps);
    return returnDict;
}
Example #12
0
static void save_dasm_cat(FILE *f, const char *def, instr *il, int count)
{
  static const pdesc pp[] = {
    { "c", 0, PC },
    { "d", 0, PD },
    { "i", 0, PI },
    { 0 }
  };

  int i;
  fprintf(f, "#ifdef %s\n", def);
  for(i=0; i != count; i++)
    if(il[i].name) {
      int par[3];
      int pc = 0;
      int j;
      char buf[4096], *p = buf;
      parse(il[i].dasm, pp);
      for(j=0; j<parse_count;j++) {
	switch(parse_res[j].id) {
	case -1:
	  scp(&p, j);
	  break;
	case PC:
	  scs(&p, "%s");
	  par[pc++] = PC;
	  break;
	case PD:
	  scs(&p, "%s");
	  par[pc++] = PD;
	  break;
	case PI:
	  scs(&p, "%02x");
	  par[pc++] = PI;
	  break;
	}
      }
      *p = 0;

      fprintf(f, "    case 0x%02x:\n", i);
      fprintf(f, "      sprintf(buf, \"%s\"", buf);
      for(j=0; j != pc; j++)
	switch(par[j]) {
	case PC:
	  fprintf(f, ", tms57002_get_memadr(opcode, 'c')");
	  break;
	case PD:
	  fprintf(f, ", tms57002_get_memadr(opcode, 'd')");
	  break;
	case PI:
	  fprintf(f, ", opcode & 0xff");
	  break;
	}


      fprintf(f, ");\n");
      fprintf(f, "      break;\n");
      fprintf(f, "\n");
    }

  fprintf(f, "#endif\n\n");
}
Example #13
0
File: main.c Project: hharte/vttest
int
tst_doublesize(MENU_ARGS)
{
  /* Test of:
     DECSWL  (Single Width Line)
     DECDWL  (Double Width Line)
     DECDHL  (Double Height Line) (also implicit double width)
   */

  int col, i, w, w1;

  /* Print the test pattern in both 80 and 132 character width  */

  for (w = 0; w <= 1; w++) {
    w1 = 13 * w;

    ed(2);
    cup(1, 1);
    if (w) {
      deccolm(TRUE);
      printf("%3d column mode", max_cols);
    } else {
      deccolm(FALSE);
      printf("%3d column mode", min_cols);
    }

    cup(5, 3 + 2 * w1);
    printf("v------- left margin");

    cup(7, 3 + 2 * w1);
    printf("This is a normal-sized line");

    decdhl(0);
    decdhl(1);
    decdwl();
    decswl();
    cup(9, 2 + w1);
    printf("This is a Double-width line");

    decswl();
    decdhl(0);
    decdhl(1);
    decdwl();

    cup(11, 2 + w1);
    decdwl();
    decswl();
    decdhl(1);
    decdhl(0);
    printf("This is a Double-width-and-height line");

    cup(12, 2 + w1);
    decdwl();
    decswl();
    decdhl(0);
    decdhl(1);
    printf("This is a Double-width-and-height line");

    cup(14, 2 + w1);
    decdwl();
    decswl();
    decdhl(1);
    decdhl(0);
    el(2);
    printf("This is another such line");

    cup(15, 2 + w1);
    decdwl();
    decswl();
    decdhl(0);
    decdhl(1);
    printf("This is another such line");

    cup(17, 3 + 2 * w1);
    printf("^------- left margin");

    cup(21, 1);
    printf("This is not a double-width line");
    for (i = 0; i <= 1; i++) {
      cup(21, 6);
      if (i) {
        printf("**is**");
        decdwl();
      } else {
        printf("is not");
        decswl();
      }
      cup(max_lines - 1, 1);
      holdit();
    }
  }
  /* Set vanilla tabs for next test */
  cup(1, 1);
  tbc(3);
  for (col = 1; col <= max_cols; col += TABWIDTH) {
    cuf(TABWIDTH);
    hts();
  }
  deccolm(FALSE);
  ed(2);
  /* *INDENT-OFF* */
  scs_graphics();
  cup( 8,1); decdhl(0); printf("lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk");
  cup( 9,1); decdhl(1); printf("lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk");
  cup(10,1); decdhl(0); printf("x%c%c%c%c%cx",9,9,9,9,9);
  cup(11,1); decdhl(1); printf("x%c%c%c%c%cx",9,9,9,9,9);
  cup(12,1); decdhl(0); printf("x%c%c%c%c%cx",9,9,9,9,9);
  cup(13,1); decdhl(1); printf("x%c%c%c%c%cx",9,9,9,9,9);
  scs(1, '0');  /* should look the same as scs_graphics() */
  cup(14,1); decdhl(0); printf("x                                      x");
  cup(15,1); decdhl(1); printf("x                                      x");
  cup(16,1); decdhl(0); printf("mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj");
  cup(17,1); decdhl(1); printf("mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj");
  scs_normal();
  /* *INDENT-ON* */

  sgr("1;5");
  cup(12, 3);
  printf("* The mad programmer strikes again * ");

  cup(13, 3);
  printf("%c", 9);

  cub(6);
  printf("* The mad programmer strikes again *");
  sgr("0");

  cup(max_lines - 2, 1);
  println("Another test pattern...  a frame with blinking bold text,");
  printf("all in double-height double-width size. ");
  holdit();

  decstbm(8, max_lines);  /* Absolute origin mode, so cursor is set at (1,1) */
  cup(8, 1);
  for (i = 1; i <= 12; i++)
    ri();
  decstbm(0, 0);  /* No scroll region     */
  cup(1, 1);
  printf("%s", "Exactly half of the box should remain. ");
  return MENU_HOLD;
}
Example #14
0
File: scsr.c Project: akshayka/scs
SEXP scsr(SEXP data, SEXP cone, SEXP params) {
    scs_int len, num_protected = 0;
    SEXP ret, retnames, infor, xr, yr, sr;

    /* allocate memory */
    Data *d = scs_malloc(sizeof(Data));
    Cone *k = scs_malloc(sizeof(Cone));
    Settings *stgs = scs_malloc(sizeof(Settings));
    AMatrix *A = scs_malloc(sizeof(AMatrix));
    Info *info = scs_calloc(1, sizeof(Info));
    Sol *sol = scs_calloc(1, sizeof(Sol));

    d->b = getFloatVectorFromList(data, "b", &len);
    d->c = getFloatVectorFromList(data, "c", &len);
    d->n = getIntFromListWithDefault(data, "n", 0);
    d->m = getIntFromListWithDefault(data, "m", 0);

    A->m = d->m;
    A->n = d->n;
    A->x = getFloatVectorFromList(data, "Ax", &len);
    A->i = getIntVectorFromList(data, "Ai", &len);
    A->p = getIntVectorFromList(data, "Ap", &len);
    d->A = A;

    stgs->max_iters = getIntFromListWithDefault(params, "max_iters", MAX_ITERS);
    stgs->normalize = getIntFromListWithDefault(params, "normalize", NORMALIZE);
    stgs->verbose = getIntFromListWithDefault(params, "verbose", VERBOSE);
    stgs->cg_rate = getFloatFromListWithDefault(params, "cg_rate", CG_RATE);
    stgs->scale = getFloatFromListWithDefault(params, "scale", SCALE);
    stgs->rho_x = getFloatFromListWithDefault(params, "rho_x", RHO_X);
    stgs->alpha = getFloatFromListWithDefault(params, "alpha", ALPHA);
    stgs->eps = getFloatFromListWithDefault(params, "eps", EPS);
    /* TODO add warm starting */
    stgs->warm_start =
        getIntFromListWithDefault(params, "warm_start", WARM_START);
    d->stgs = stgs;

    k->f = getIntFromListWithDefault(cone, "f", 0);
    k->l = getIntFromListWithDefault(cone, "l", 0);
    k->ep = getIntFromListWithDefault(cone, "ep", 0);
    k->ed = getIntFromListWithDefault(cone, "ed", 0);
    k->q = getIntVectorFromList(cone, "q", &(k->qsize));
    k->s = getIntVectorFromList(cone, "s", &(k->ssize));
    k->p = getFloatVectorFromList(cone, "p", &(k->psize));

    /* solve! */
    scs(d, k, sol, info);

    infor = populateInfoR(info, &num_protected);

    PROTECT(ret = NEW_LIST(4));
    num_protected++;
    PROTECT(retnames = NEW_CHARACTER(4));
    num_protected++;
    SET_NAMES(ret, retnames);

    xr = floatVec2R(d->n, sol->x);
    num_protected++;
    yr = floatVec2R(d->m, sol->y);
    num_protected++;
    sr = floatVec2R(d->m, sol->s);
    num_protected++;

    SET_STRING_ELT(retnames, 0, mkChar("x"));
    SET_VECTOR_ELT(ret, 0, xr);
    SET_STRING_ELT(retnames, 1, mkChar("y"));
    SET_VECTOR_ELT(ret, 1, yr);
    SET_STRING_ELT(retnames, 2, mkChar("s"));
    SET_VECTOR_ELT(ret, 2, sr);
    SET_STRING_ELT(retnames, 3, mkChar("info"));
    SET_VECTOR_ELT(ret, 3, infor);

    /* free memory */
    scs_free(info);
    scs_free(d);
    scs_free(k);
    scs_free(stgs);
    scs_free(A);
    freeSol(sol);
    UNPROTECT(num_protected);
    return ret;
}
Example #15
0
int main(int argc, char **argv) {
	scs_int n, m, col_nnz, nnz, i, q_total, q_num_rows, max_q;
	Cone * k;
	Data * d;
	Sol * sol, * opt_sol;
	Info info = { 0 };
	scs_float p_f, p_l;
	int seed = 0;

	/* default parameters */
	p_f = 0.1;
	p_l = 0.3;
	seed = time(SCS_NULL);

	switch (argc) {
	case 5:
		seed = atoi(argv[4]);
		/* no break */
	case 4:
		p_f = atof(argv[2]);
		p_l = atof(argv[3]);
		/* no break */
	case 2:
		n = atoi(argv[1]);
		break;
	default:
		scs_printf("usage:\t%s n p_f p_l s\n"
				"\tcreates an SOCP with n variables where p_f fraction of rows correspond\n"
				"\tto equality constraints, p_l fraction of rows correspond to LP constraints,\n"
				"\tand the remaining percentage of rows are involved in second-order\n"
				"\tcone constraints. the random number generator is seeded with s.\n"
				"\tnote that p_f + p_l should be less than or equal to 1, and that\n"
				"\tp_f should be less than .33, since that corresponds to as many equality\n"
				"\tconstraints as variables.\n", argv[0]);
		scs_printf("\nusage:\t%s n p_f p_l\n"
				"\tdefaults the seed to the system time\n", argv[0]);
		scs_printf("\nusage:\t%s n\n"
				"\tdefaults to using p_f = 0.1 and p_l = 0.3\n", argv[0]);
		return 0;
	}
	srand(seed);
	scs_printf("seed : %i\n", seed);

    k = scs_calloc(1, sizeof(Cone));
    d = scs_calloc(1, sizeof(Data));
    d->stgs = scs_calloc(1, sizeof(Settings));
    sol = scs_calloc(1, sizeof(Sol));
    opt_sol = scs_calloc(1, sizeof(Sol));

	m = 3 * n;
	col_nnz = (int) ceil(sqrt(n));
	nnz = n * col_nnz;

	max_q = (scs_int) ceil(3 * n / log(3 * n));

	if (p_f + p_l > 1.0) {
		printf("error: p_f + p_l > 1.0!\n");
		return 1;
	}

	k->f = (scs_int) floor(3 * n * p_f);
	k->l = (scs_int) floor(3 * n * p_l);

	k->qsize = 0;
	q_num_rows = 3 * n - k->f - k->l;
	k->q = scs_malloc(q_num_rows * sizeof(scs_int));

	while (q_num_rows > max_q) {
		int size;
		size = (rand() % max_q) + 1;
		k->q[k->qsize] = size;
		k->qsize++;
		q_num_rows -= size;
	}
	if (q_num_rows > 0) {
		k->q[k->qsize] = q_num_rows;
		k->qsize++;
	}

	q_total = 0;
	for (i = 0; i < k->qsize; i++) {
		q_total += k->q[i];
	}

	k->s = SCS_NULL;
	k->ssize = 0;
	k->ep = 0;
	k->ed = 0;

	scs_printf("\nA is %ld by %ld, with %ld nonzeros per column.\n", (long) m, (long) n, (long) col_nnz);
	scs_printf("A has %ld nonzeros (%f%% dense).\n", (long) nnz, 100 * (scs_float) col_nnz / m);
	scs_printf("Nonzeros of A take %f GB of storage.\n", ((scs_float) nnz * sizeof(scs_float)) / POWF(2, 30));
	scs_printf("Row idxs of A take %f GB of storage.\n", ((scs_float) nnz * sizeof(scs_int)) / POWF(2, 30));
	scs_printf("Col ptrs of A take %f GB of storage.\n\n", ((scs_float) n * sizeof(scs_int)) / POWF(2, 30));

	printf("Cone information:\n");
	printf("Zero cone rows: %ld\n", (long) k->f);
	printf("LP cone rows: %ld\n", (long) k->l);
	printf("Number of second-order cones: %ld, covering %ld rows, with sizes\n[", (long) k->qsize, (long) q_total);
	for (i = 0; i < k->qsize; i++) {
		printf("%ld, ", (long) k->q[i]);
	}
	printf("]\n");
	printf("Number of rows covered is %ld out of %ld.\n\n", (long) (q_total + k->f + k->l), (long) m);

	/* set up SCS structures */
	d->m = m;
	d->n = n;
	genRandomProbData(nnz, col_nnz, d, k, opt_sol);
	setDefaultSettings(d);

	scs_printf("true pri opt = %4f\n", innerProd(d->c, opt_sol->x, d->n));
	scs_printf("true dua opt = %4f\n", -innerProd(d->b, opt_sol->y, d->m));
    /* solve! */
	scs(d, k, sol, &info);
	scs_printf("true pri opt = %4f\n", innerProd(d->c, opt_sol->x, d->n));
	scs_printf("true dua opt = %4f\n", -innerProd(d->b, opt_sol->y, d->m));

    if (sol->x) { scs_printf("scs pri obj= %4f\n", innerProd(d->c, sol->x, d->n)); }
    if (sol->y) { scs_printf("scs dua obj = %4f\n", -innerProd(d->b, sol->y, d->m)); }

    freeData(d, k);
	freeSol(sol);
    freeSol(opt_sol);

    return 0;
}
Example #16
0
static void cintrp_expand(char **p, int s, int e, const int *cv)
{
  int i;
  for(i=s; i<e;) {
    switch(parse_res[i].id) {
    case -1:
      scp(p, i);
      break;

    case PA:
      if(cv[IxSFAO])
	scs(p, "(s->aacc << 7)");
      else
	scs(p, "s->aacc");
      break;

    case PC: {
      const char *r = NULL;
      if(cv[IxCMODE] == 0)
	r = "s->cmem[i->param]";
      else if(cv[IxCMODE] == 1)
	r = "s->cmem[s->ca]";
      else if(cv[IxCMODE] == 2)
	r = "s->cmem[s->ca++]";
      else
	abort();

      if(cv[IxCRM] == 0 || cv[IxCRM] == 3)
	scs(p, r);
      else if(cv[IxCRM] == 1) {
	scs(p, "(");
	scs(p, r);
	scs(p, " & 0xffff0000)");
      } else if(cv[IxCRM] == 2) {
	scs(p, "(");
	scs(p, r);
	scs(p, " << 16)");
      } else
	abort();
      break;
    }

    case PD:
      if(cv[IxDMODE] == 0)
	if(cv[IxDBP])
	  scs(p, "(s->dmem1[(i->param + s->ba1) & 0x1f] << 8)");
	else
	  scs(p, "(s->dmem0[(i->param + s->ba0) & 0xff] << 8)");
      else if(cv[IxDMODE] == 1)
	if(cv[IxDBP])
	  scs(p, "(s->dmem1[(s->id + s->ba1) & 0x1f] << 8)");
	else
	  scs(p, "(s->dmem0[(s->id + s->ba0) & 0xff] << 8)");
      else if(cv[IxDMODE] == 2)
	if(cv[IxDBP])
	  scs(p, "(s->dmem1[((s->id++) + s->ba1) & 0x1f] << 8)");
	else
	  scs(p, "(s->dmem0[((s->id++) + s->ba0) & 0xff] << 8)");
      else
	abort();
      break;

    case PI:
      scs(p, "i->param");
      break;

    case PD24:
      if(cv[IxDMODE] == 0)
	if(cv[IxDBP])
	  scs(p, "s->dmem1[(i->param + s->ba1) & 0x1f]");
	else
	  scs(p, "s->dmem0[(i->param + s->ba0) & 0xff]");
      else if(cv[IxDMODE] == 1)
	if(cv[IxDBP])
	  scs(p, "s->dmem1[(s->id + s->ba1) & 0x1f]");
	else
	  scs(p, "s->dmem0[(s->id + s->ba0) & 0xff]");
      else if(cv[IxDMODE] == 2)
	if(cv[IxDBP])
	  scs(p, "s->dmem1[((s->id++) + s->ba1) & 0x1f]");
	else
	  scs(p, "s->dmem0[((s->id++) + s->ba0) & 0xff]");
      else
	abort();
      break;

    case PML:
      if(cv[IxSFMA] == 0)
	scs(p, "s->macc");
      else if(cv[IxSFMA] == 1)
	scs(p, "(s->macc << 2)");
      else if(cv[IxSFMA] == 2)
	scs(p, "(s->macc << 4)");
      else if(cv[IxSFMA] == 3)
	scs(p, "(s->macc >> 16)");
      else
	abort();
      break;

    case PMO: {
      static const long long rounding[8] = {
	0,
	1LL << (48-32-1),
	1LL << (48-24-1),
	1LL << (48-30-1),
	1LL << (48-16-1),
	0, 0, 0
      };
      static const unsigned long long rmask[8] = {
	~0ULL,
	(~0ULL) << (48-32),
	(~0ULL) << (48-24),
	(~0ULL) << (48-30),
	(~0ULL) << (48-16),
	~0ULL, ~0ULL, ~0ULL
      };

      char r[256];
      sprintf(r, "tms57002_macc_to_output_%d%s(s, 0x%016" I64FMT "xULL, 0x%016" I64FMT "xULL)", cv[IxSFMO], cv[IxMOVM] ? "s" : "", rounding[cv[IxRND]], rmask[cv[IxRND]]);
      scs(p, r);
      break;
    }

    case PMV: {
      char r[256];
      sprintf(r, "tms57002_check_macc_overflow_%d%s(s)", cv[IxSFMO], cv[IxMOVM] ? "s" : "");
      scs(p, r);
      break;
    }

    case PB:
      scs(p, "s->pc = ");
      cintrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1], cv);
      scs(p, ";\n");
      scs(p, "  s->sti |= S_BRANCH");
      break;

    case PWA:
      scs(p, "r = ");
      cintrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1], cv);
      scs(p, ";\n");
      scs(p, "  if(r < -0x80000000 || r > 0x7fffffff)\n");
      scs(p, "    s->st1 |= ST1_AOV;\n");
      scs(p, "  s->aacc = r");
      break;

    case PWC:
      if(cv[IxCMODE] == 0)
	scs(p, "s->cmem[i->param] = ");
      else if(cv[IxCMODE] == 1)
	scs(p, "s->cmem[s->ca] = ");
      else if(cv[IxCMODE] == 2)
	scs(p, "s->cmem[s->ca++] = ");
      else
	abort();

      cintrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1], cv);
      break;

    case PWD:
      if(cv[IxDMODE] == 0)
	if(cv[IxDBP])
	  scs(p, "s->dmem1[(i->param + s->ba1) & 0x1f] = ");
	else
	  scs(p, "s->dmem0[(i->param + s->ba0) & 0xff] = ");
      else if(cv[IxDMODE] == 1)
	if(cv[IxDBP])
	  scs(p, "s->dmem1[(s->id + s->ba1) & 0x1f] = ");
	else
	  scs(p, "s->dmem0[(s->id + s->ba0) & 0xff] = ");
      else if(cv[IxDMODE] == 2)
	if(cv[IxDBP])
	  scs(p, "s->dmem1[((s->id++) + s->ba1) & 0x1f] = ");
	else
	  scs(p, "s->dmem0[((s->id++) + s->ba0) & 0xff] = ");
      else
	abort();

      cintrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1], cv);
      break;

    case SFAI:
      cintrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1], cv);
      scs(p, " = ");
      if(cv[IxSFAI])
	scs(p, "((INT32)(");
      cintrp_expand(p, parse_res[i].ppos[1], parse_res[i].ppos[2], cv);
      if(cv[IxSFAI])
	scs(p, ")) >> 1");
      break;
    }

    if(parse_res[i].id == -1)
      i++;
    else
      i = parse_res[i].ppos[parse_res[i].pcount];
  }
}
Example #17
0
static void intrp_expand(char **p, int s, int e)
{
  int i;
  for(i=s; i<e;) {
    switch(parse_res[i].id) {
    case -1:
      scp(p, i);
      break;

    case PA:
      scs(p, "tms57002_aacc_to_output(s)");
      break;

    case PC:
      scs(p, "tms57002_opc_read_c(s, opcode)");
      break;

    case PD:
      scs(p, "(tms57002_opc_read_d(s, opcode) << 8)");
      break;

    case PI:
      scs(p, "(opcode & 0xff)");
      break;

    case PD24:
      scs(p, "tms57002_opc_read_d(s, opcode)");
      break;

    case PML:
      scs(p, "tms57002_macc_to_loop(s)");
      break;

    case PMO:
      scs(p, "tms57002_macc_to_output(s)");
      break;

    case PMV:
      scs(p, "tms57002_check_macc_overflow(s)");
      break;

    case PB:
      scs(p, "s->pc = ");
      intrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1]);
      scs(p, ";\n");
      scs(p, "  s->sti |= S_BRANCH");
      break;

    case PWA:
      scs(p, "r = ");
      intrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1]);
      scs(p, ";\n");
      scs(p, "  if(r < -0x80000000 || r > 0x7fffffff)\n");
      scs(p, "    s->st1 |= ST1_AOV;\n");
      scs(p, "  s->aacc = r");
      break;

    case PWC:
      scs(p, "tms57002_opc_write_c(s, opcode, ");
      intrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1]);
      scs(p, ")");
      break;

    case PWD:
      scs(p, "tms57002_opc_write_d(s, opcode, ");
      intrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1]);
      scs(p, ")");
      break;

    case SFAI:
      intrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1]);
      scs(p, " = ");
      intrp_expand(p, parse_res[i].ppos[1], parse_res[i].ppos[2]);
      scs(p, ";\n");
      scs(p, "  if(s->st1 & ST1_SFAI)\n");
      scs(p, "    ");
      intrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1]);
      scs(p, " = ((INT32)");
      intrp_expand(p, parse_res[i].ppos[0], parse_res[i].ppos[1]);
      scs(p, ") >> 1");
      break;
    }

    if(parse_res[i].id == -1)
      i++;
    else
      i = parse_res[i].ppos[parse_res[i].pcount];
  }
}