Example #1
0
bool LeastSquares(const vector<Vector>& data,int dependentVariable,
		  Vector& coeffs)
{
  assert(!data.empty());
  int n=data[0].n;
  assert((int)data.size() >= n);
  assert(dependentVariable >= 0 && dependentVariable < n);
  Matrix mdata((int)data.size(),n-1);
  Vector vdep((int)data.size());
  for(size_t i=0;i<data.size();i++) {
    assert(data[i].n == n);
    for(int j=0;j<n;j++) {
      if(j < dependentVariable)
	mdata(i,j) = data[i](j);
      else if(j > dependentVariable)
	mdata(i,j-1) = data[i](j);
      else
	vdep(i) = data[i](j);
    }
  }
  Vector tempcoeffs; Real offset;
  if(!LeastSquares(mdata,vdep,tempcoeffs,offset)) return false;
  coeffs.resize(n);
  for(int j=0;j<n;j++) {
    if(j < dependentVariable)
      coeffs(j) = tempcoeffs(j);
    else if(j > dependentVariable)
      coeffs(j) = tempcoeffs(j-1);
    else
      coeffs(j) = offset;
  }
  return true;
}
Example #2
0
int antLoop(ipc_t ipc, grid_t grid) {

    char stop;
    handler_f* handlers;
    ant_t ant;
    cmd_t cmd;
    message_t message, ret;

    srand(getpid());

    ant = antNew();
    ant->ahr = ant->r = grid->anthillRow;
    ant->ahc = ant->c = grid->anthillCol;
    LOGPID("Starting ant %d logic loop.\n", ipc->id);

    handlers = buildHandlerArray();
    antFillHandlerArray(handlers);

    sendMessage(ipc, message = mnew(ipc->id, 1, sizeof(struct cmd_start_t),
                                    (char*) (cmd = newStart())));

    mdel(message);
    free(cmd);
    
    stop = 0;

    while(!stop) {

        if (message = recvMessage(ipc)) {
            LOGPID("Ant %d received cmd type %d.\n", ipc->id, ((cmd_t) mdata(message))->type);
            if (cmd = dispatchCmd((void*) ant, (cmd_t) mdata(message), handlers)) {
                mdel(message);

                sendMessage(ipc, message = mnew(ipc->id, 1, cmdsize(cmd),
                                               (char*) cmd));
                    
                LOGPID("Ant %d sent cmd type %d.\n", ipc->id, ((cmd_t) mdata(message))->type);
                mdel(message);   
                free(cmd);                   
            }
        }
        
        stop = (ant->state == ANT_STATE_FINAL);
    
    }
    
    ipc->stop = 1;
    return 0;
}
Example #3
0
retval_t pf_mcontroller::transmit (const QByteArray& data)
{
    retval_t rv = RV_OK;

    QByteArray mdata(data);

    mdata.append(pf_crc::get(mdata));

    mdata.prepend(START_CHAR);

    mdata.append(END_CHAR);

    QDebug(QtDebugMsg) << "Writing data:" << mdata;

    m_tx_port->write(mdata);

    QByteArray echodata;
    if(RV_OK == m_buf.acquire(echodata, 100))
    {
        if(mdata != echodata)
        {
            rv = RV_NO_ECHO;
            QDebug(QtWarningMsg) << "Echo isn't received. Wrong data:" << echodata;
        }
    }
    else
    {
        rv = RV_NO_ECHO;
        QDebug(QtWarningMsg) << "Echo isn't received. Timeout";
    }

    return rv;
}
Example #4
0
void CText::ApplyAnimators(CRectangle& srcRect, CRectangle& dstRect) {
    m_pText->Lock();

    TextAnimatorData mdata(&srcRect, &dstRect);

    if(!m_vecAnimatorVault.empty()) {
        AnimatorStorage::iterator end = m_vecAnimatorVault.end();

        for(AnimatorStorage::iterator it = m_vecAnimatorVault.begin(); it < end; ++it)
        {
            (*it)(m_pText.get(), this, mdata);
            if(mdata.markedForDeletion) {
                TextAnimator* savedAnimator = (*it).nextAnimator;

                if(savedAnimator) {
                    //savedAnimator->x = (*it).x;
                    //savedAnimator->y = (*it).y;
                    (*it).nextAnimator = NULL;
                    m_vecAnimatorVault.erase(it);
                    mdata.markedForDeletion = false;
                    AddAnimator(savedAnimator);
                    break;
                }

                m_vecAnimatorVault.erase(it);
                mdata.markedForDeletion = false;
                // Todo: better fill a deleter list and erase after loop.
                break;
            }
        }
    }

    m_pText->Unlock();
} // CText::ApplyAnimators
Example #5
0
bool CCanvas::ApplyRenderers(CCanvasRendererStorage& storage,
        CCanvas* source,
        const CCanvas* target,
        const CRectangle* dstRect,
        const CRectangle* srcRect) const {
    if(!source->m_vecRendererVault.empty()) {
        std::vector<CCanvasRendererStorage::iterator> removeList;

        CCanvasRendererStorage::iterator end = storage.end();
        CRectangle rdstRect;
        CRectangle rsrcRect;

        if(dstRect) {
            rdstRect = CRectangle(*dstRect);
        }

        if(srcRect) {
            rsrcRect = CRectangle(*srcRect);
        }

        CCanvasRenderModifierData mdata(&rsrcRect, &rdstRect);

        for(CCanvasRendererStorage::iterator it = storage.begin(); it < end; ++it)
        {
            (*it)(target, const_cast<CCanvas *>(source), mdata);
            if(mdata.markedForDeletion) {
                CCanvasRendererStorage::iterator it2 = it;
                removeList.push_back(it2);
            }
        }
        BOOST_FOREACH(CCanvasRendererStorage::iterator itpos, removeList)
        {
            storage.erase(itpos);
        }
Example #6
0
bool LDACalc(string datafile,string labelfile,string fea_resfile,string projection_mat_resfile){
	if(fexist(fea_resfile)&&fexist(projection_mat_resfile))
		return true;
	if(!fexist(datafile)||!fexist(labelfile))
		return false;
	Matrix Fea;
	Fea.readfile(datafile);
	ifstream label_fin(labelfile.c_str());
	vector<int> label;
	int temp;
	double size = Fea.Getrows();
	while(!label_fin.eof()){
		label_fin>>temp;
		label.push_back(temp);
	}
	label_fin.close();
	
	//Sw computing
	Matrix Sw = zeros(Fea.Getcols(),Fea.Getcols());
	vector<bool> t_flag(label.size(),false);
	for(vector<int>::size_type n=0;n<label.size();n++){
		if(t_flag[n])
			continue;
		vector<int> id = findVec(label,label[n]);
		for(vector<int>::size_type j=0;j<id.size();j++)
			t_flag[id[j]] = true;
		Matrix fea = Fea.select(id,1);
		vector<vector<double>> tmdata(1,fea.mean(1));
		Matrix tmu(1,fea.Getcols());
		tmu.setdata(tmdata);
		fea = fea - ones(fea.Getrows(),1)*tmu;
		Sw = Sw + fea.trans()*fea;
	}
	Sw = Sw/size;

	//St computing
	vector<vector<double>> mdata(1,Fea.mean(1));
	Matrix mu(1,Fea.Getcols());
	mu.setdata(mdata);
	Matrix St = Fea.trans()*Fea/size-mu.trans()*mu;

	//Generalized Eigen problem.
	vector<double> D(Sw.Getrows(),0); 
	Matrix V(Sw.Getrows(),Sw.Getrows());
	if(generalized_sym_eig(St, Sw, D, V)){
		Matrix Fea_LDA = Fea * V;
		Fea_LDA.writefile(fea_resfile);
		V.writefile(projection_mat_resfile);
		return true;
	}
	else{
		cout<<"Eigen Module Malfunctions."<<endl;
		return false;
	}
}
/*!
  Returns a map with all properties of this text format.
 */
QVariantMap TAbstractModel::toVariantMap() const
{
    QVariantMap ret;

    QVariantMap map = mdata()->toVariantMap();
    for (QMapIterator<QString, QVariant> it(map); it.hasNext(); ) {
        it.next();
        ret.insert(fieldNameToVariableName(it.key()), it.value());
    }
    return ret;
}
/*!
  Sets the \a properties.
 */
void TAbstractModel::setProperties(const QVariantMap &properties)
{
    // Creates a map of the original property name and the converted name
    QStringList soprops = mdata()->propertyNames();
    QMap<QString, QString> sopropMap;
    for (QStringListIterator it(soprops); it.hasNext(); ) {
        const QString &orig = it.next();
        sopropMap.insert(fieldNameToVariableName(orig), orig);
    }

    QVariantMap props;
    for (QMapIterator<QString, QVariant> it(properties); it.hasNext(); ) {
        it.next();
        const QString &p = sopropMap[it.key()];
        if (!p.isEmpty()) {
            props.insert(p, it.value());
        }
    }

    mdata()->setProperties(props);
}
Example #9
0
void DecoderIOFactoryShoutCast::stop(void)
{
    if (m_timer)
        m_timer->disconnect();

    doOperationStop();

    Metadata mdata(getMetadata());
    mdata.setTitle("Stopped");
    mdata.setArtist("");
    mdata.setLength(-1);
    DecoderHandlerEvent ev(DecoderHandlerEvent::Meta, mdata);
    dispatch(ev);
}
Example #10
0
void DecoderIOFactoryShoutCast::shoutcastMeta(const QString &metadata)
{
    LOG(VB_PLAYBACK, LOG_INFO,
        QString("DecoderIOFactoryShoutCast: metadata changed - %1")
            .arg(metadata));
    ShoutCastMetaParser parser;
    parser.setMetaFormat(getMetadata().CompilationArtist());

    ShoutCastMetaMap meta_map = parser.parseMeta(metadata);

    Metadata mdata(getMetadata());
    mdata.setTitle(meta_map["title"]);
    mdata.setArtist(meta_map["artist"]);
    mdata.setAlbum(getMetadata().Album()); // meta_map["album"]
    mdata.setLength(-1);

    DecoderHandlerEvent ev(DecoderHandlerEvent::Meta, mdata);
    dispatch(ev);
}
Example #11
0
bool CCanvas::ApplyRenderers(CCanvasRendererStorage& storage,
        CCanvas* source,
        const CCanvas* target,
        const CRectangle* dstRect,
        const CRectangle* srcRect) const {
    if(!source->m_vecRendererVault.empty()) {
        std::vector<CCanvasRendererStorage::iterator> removeList;

        CCanvasRendererStorage::iterator end = storage.end();
        CRectangle rdstRect;
        CRectangle rsrcRect;

        if(dstRect) {
            rdstRect = CRectangle(*dstRect);
        }

        if(srcRect) {
            rsrcRect = CRectangle(*srcRect);
        }

        CCanvasRenderModifierData mdata(&rsrcRect, &rdstRect);

        for(CCanvasRendererStorage::iterator it = storage.begin(); it < end; ++it)
        {
            (*it)(target, const_cast<CCanvas *>(source), mdata);
            if(mdata.markedForDeletion) {
                CCanvasRendererStorage::iterator it2 = it;
                // it has to be checked, if removing has no side effects. see CSpriteManager::OnIdle
                // for a solution with "while".
                //removeList.push_back(it2);
                removeList.insert(removeList.begin(), it2);
            }
        }
        BOOST_FOREACH(CCanvasRendererStorage::iterator itpos, removeList)
        {
            storage.erase(itpos);
        }
Example #12
0
void CText::ApplyModifiers(CRectangle& srcRect, CRectangle& dstRect) {
    m_pText->Lock();

    TextAnimatorData mdata(&srcRect, &dstRect);

    if(!m_vecModifierVault.empty()) {
        TextModifierStorage::iterator end = m_vecModifierVault.end();

        for(TextModifierStorage::iterator it = m_vecModifierVault.begin(); it < end; ++it)
        {
            (*it)(m_pText.get(), this, mdata);
            if(mdata.markedForDeletion) {
                //m_vecModifierVault.pop_back();
                //TextModifierStorage::iterator ex;
                m_vecModifierVault.erase(it);
                mdata.markedForDeletion = false;
                // Todo: better fill a deleter list and erase after loop.
                break;
            }
        }
    }

    m_pText->Unlock();
} // CText::ApplyModifiers
/*!  \internal
  Returns the meta data of the slot with index \a index or 0 if no
  such slot exists.

  If  \a super is TRUE, inherited slots are included.
 */
QMetaData *QMetaObject::slot( int index, bool super ) const
{
    return mdata( SLOT_CODE, index, super );	// get slot meta data
}
/*!  \internal
  Returns the meta data of the signal with the name \a n or 0 if no
  such signal exists.

  If \a super is TRUE, include inherited signals.

 */
QMetaData *QMetaObject::signal( const char *n, bool super ) const
{
    return mdata( SIGNAL_CODE, n, super );	// get signal meta data
}
/*!  \internal
  Returns the meta data of the slot with the name \a n or 0 if no
  such slot exists.

  If \a super is TRUE,  inherited slots are included.
 */
QMetaData *QMetaObject::slot( const char *n, bool super ) const
{
    return mdata( SLOT_CODE, n, super );	// get slot meta data
}
Example #16
0
int gen_op ( )
{
    Matrix	a;
    Matrix	b;
    void       *ptr;
    descriptor *d;
    descriptor *v;
    descriptor *var;
    descriptor *index;
    descriptor *vector;
    descriptor	temp;
    double	value;
    Address	increment;
    Array	arr;
    int		fail;
    unsigned	offset;
    unsigned	i;
    unsigned	c;
    unsigned	r;


    index = ntop (0);
    vector = ntop (1);
    var = ntop (2);

    offset = fetch (pc ++).ival;


    if (D_Type (index) == T_Double) {
        if (!assignable (var)) {
            TypeError ("cannot assign to", NULL, var, NULL, F_False);
            return 1;
        }

        d = &temp;
        D_Type    (d) = T_Null;
        D_Temp    (d) = F_False;
        D_Trapped (d) = F_False;
        D_Pointer (d) = NULL;

        v = CoerceData (vector, T_Double);
        AssignData (d, &v);
        RecycleData (v);
        D_Temp (d) = F_False;

        d_printf ("d = %s %p\n", D_TypeName (d), D_Pointer (d));

        switch (D_Type (d)) {
        case T_Double:
        case T_Matrix:
        case T_Array:
        case T_Null:
            break;


        default:
            TypeError ("cannot index", NULL, d, NULL, F_False);
            return 1;
        }

        *vector = *d;

        D_Type (index) = T_Row;
        D_Row (index) = 0;
    }

    d_printf ("vector = %s %p\n", D_TypeName (vector), D_Pointer (vector));
    var = deref (var);
    fail = F_False;


    switch (D_Type (vector)) {
    case T_Double:
        if (D_Row (index) ++ == 0)
            AssignData (var, &vector);
        else
            fail = F_True;
        break;


    case T_Matrix:
        a = D_Matrix (vector);
        d = &temp;
        D_Temp	  (d) = F_False;
        D_Trapped (d) = F_False;

        if (Mrows (a) == 1) {
            if (++ D_Row (index) <= Mcols (a)) {
                D_Type   (d) = T_Double;
                D_Double (d) = &value;
                value = mdata (a, 1, D_Row (index));
                AssignData (var, &d);
            } else
                fail = F_True;

        } else if (Mcols (a) == 1) {
            if (++ D_Row (index) <= Mrows (a)) {
                D_Type   (d) = T_Double;
                D_Double (d) = &value;
                value = mdata (a, D_Row (index), 1);
                AssignData (var, &d);
            } else
                fail = F_True;

        } else {
            if (++ D_Row (index) <= Mcols (a)) {
                d_printf ("indexing matrix\n");
                r = Mrows (a);
                c = D_Row (index);

                FreeData (var);
                CreateData (var, NULL, NULL, T_Matrix, r, 1);
                D_Temp (var) = F_False;
                b = D_Matrix (var);

                for (i = 1; i <= r; i ++)
                    sdata (b, i, 1) = mdata (a, i, c);
            } else
                fail = F_True;
        }
        break;


    case T_Array:
        arr = D_Array (vector);
        d = &temp;

        if (++ D_Row (index) <= arr -> length) {
            increment = D_Row (index) * arr -> elt_size;
            ptr = (void *) ((char *) arr -> ptr + increment);

            D_Type    (d) = arr -> type;
            D_Temp    (d) = F_False;
            D_Trapped (d) = F_False;
            D_Pointer (d) = ptr;
            AssignData (var, &d);
        } else
            fail = F_True;
        break;


    case T_Null:
        fail = F_True;
        break;
    }


    /* After assignment the variable is certainly not temporary.  Its trapped
       status remains as before: if it was trapped then AssignData() called
       the trap handler which didn't change the status.  If it wasn't then
       AssignData() left the status alone. */

    D_Temp (var) = F_False;

    if (fail == F_True) {
        pop ( );
        FreeData (pop ( ));		/* free the privately owned vector */
        pop ( );

        d = push ( );
        D_Type	  (d) = T_Null;
        D_Temp	  (d) = F_False;
        D_Trapped (d) = F_False;
        D_Pointer (d) = NULL;

        pc += offset;
        d_printf ("failing\n");
    }

    return 0;
}
/*!
  Returns true if this model is not saved; otherwise returns false.
 */
bool TAbstractModel::isSaved() const
{
    return !mdata()->isNull();
}
/*!
  Creates the model as a new data to the data storage.
 */
bool TAbstractModel::create()
{
    return mdata()->create();
}
/*!
  Returns true if this model is new, not created; otherwise returns false.
 */
bool TAbstractModel::isNew() const
{
    return mdata()->isNull();
}
Example #20
0
bool Mole::getMData() {
    int datarate_raw = me_raw_value_to_datarate(this->datarate);

    int moduleCount = me_get_module_count(this->first_address, this->last_address);
    MData mdata(moduleCount, QVector< QVector<QPointF> >(this->channel_count));
    double data, sample_raw;

    int ret;
    uint16 samples = this->samplesSize;
    uint16 first_sample_to_print = 0;
    uint16 last_sample_to_print = 0;

    switch(this->modulesMode) {
        case ME_MMM_SLEEP:
        case ME_MMM_SEISMIC:
        case ME_MMM_COUNT: {
            first_sample_to_print = 0;
            last_sample_to_print = samples;
        } break;
        case ME_MMM_INCLINOMETER: {
            samples = 1;
            first_sample_to_print = 0;
            last_sample_to_print = 1;
        } break;
    }

    this->startConversion();
    uint8 *samples_data = new uint8[this->bytes_in_line * samples];
    ret =  me_host_get_samples_data(this->descriptor, samples, samples_data);
    if (ret < 0) {
        qDebug("[Error] Can't me_host_get_samples_data (ret = 0x%.2x)\n", -ret);
        return false;
    }
    else {
        qDebug() << "[Success] me_host_get_samples_data";
    }

    uint16 read_samples = 0;
    ret =  me_get_read_samples(this->descriptor, &read_samples);
    if (ret < 0) {
        qDebug("[Error] Can't me_get_read_samples (ret = 0x%.2x)\n", -ret);
        this->stopConversion();
        return false;
    }
    else {
        qDebug("[Success] me_get_read_samples = %u", read_samples);
        for(uint8 moduleIndex = 0; moduleIndex < me_get_module_count(this->first_address, this->last_address); ++moduleIndex) {
            for(uint8 channelIndex = 0; channelIndex < this->channel_count; ++channelIndex) {
                for(uint16 sample = first_sample_to_print; sample < last_sample_to_print; ++sample) {
                    switch(this->modulesMode) {
                        case ME_MMM_SLEEP:
                        case ME_MMM_SEISMIC:
                        case ME_MMM_COUNT: {

                        sample_raw = ((double) sample * (double) datarate_raw)/1000000;
                        data = me_get_seismic_sample_data(moduleIndex, sample, channelIndex,
                                                                 this->first_address, this->last_address,
                                                                 this->bytes_in_channel, this->bytes_in_module, this->bytes_in_line,
                                                                 samples_data);
                        mdata[moduleIndex][channelIndex].push_back(QPointF(sample_raw, data));
                        } break;
                        case ME_MMM_INCLINOMETER: {
                            angle_data_t angle_data = me_get_inclinometer_sample_data(moduleIndex, channelIndex,
                                                          this->first_address, this->last_address,
                                                          this->bytes_in_channel, this->bytes_in_module, this->bytes_in_line,
                                                          samples_data);
                        } break;
                    }
                }
            }
        }
        this->stopConversion();
        ptrMole->emitMDataDump(mdata);
    }
    return true;
}
/*!  \internal
  Returns the meta data of the signal with \a index index or 0 if no
  such signal exists.

  If  \a super is TRUE, inherited signals are included.
 */
QMetaData *QMetaObject::signal( int index, bool super ) const
{
    return mdata( SIGNAL_CODE, index, super );	// get signal meta data
}
/*!
  Removes the model from the data storage.
 */
bool TAbstractModel::remove()
{
    return mdata()->remove();
}
/*!
  Updates the model to the data storage.
 */
bool TAbstractModel::update()
{
    return mdata()->update();
}
/*!
  Saves the model to the data storage.

  If the model exists in the data storage, calls update();
  otherwise calls create().
 */
bool TAbstractModel::save()
{
    return (mdata()->isNull()) ? create() : update();
}
Example #25
0
void *
OPS_Tri31(const ID &info)
{
    if (num_Tri31 == 0) {
	num_Tri31++;
	opserr<<"Tri31 - Written by Roozbeh G. Mikola and N.Sitar, UC Berkeley\n";
	//OPS_Error("Tri31 - Written by Roozbeh G. Mikola and N.Sitar, UC Berkeley\n",1);
    }

    int iData[5];
    char *theType = (char*) "PlaneStress";
    double dData[5];
    dData[1] = 0.0;
    dData[2] = 0.0;
    dData[3] = 0.0;
    dData[4] = 0.0;
    int numData;

    // Pointer to an element that will be returned
    Element *theElement = 0;

    // regular element, not in a mesh, get tags
    if (info.Size() == 0) {
	int numRemainingInputArgs = OPS_GetNumRemainingInputArgs();

	if (numRemainingInputArgs < 4) {
	    opserr << "Invalid #args, want: element element Tri31 eleTag? iNode? jNode? kNode?\n";
	    return 0;
	}

	numData = 4;
	if (OPS_GetIntInput(&numData, iData) != 0) {
	    opserr << "WARNING invalid integer data: element Tri31\n";
	    return 0;
	}
    }

    // regular element, or in a mesh
    if (info.Size()==0 || info(0)==1) {
	if(OPS_GetNumRemainingInputArgs() < 3) {
	    opserr<<"insufficient arguments: thk? type? matTag? <pressure? rho? b1? b2?>\n";
	    return 0;
	}

	numData = 1;
	if (OPS_GetDoubleInput(&numData, dData) != 0) {
	    opserr << "WARNING invalid thickness data: element Tri31 " << endln;
	    return 0;
	}

	// if (OPS_GetStringCopy(&theType) != 0) {
	//   opserr << "WARNING invalid type, want: ""PlaneStress"" or ""PlaneStrain""  element SSPquad " << iData[0] << endln;
	//   return 0;
	// }
	theType = (char*)OPS_GetString();

	numData = 1;
	if (OPS_GetIntInput(&numData, &iData[4]) != 0) {
	    opserr << "WARNING invalid integer data: element Tri31\n";
	    return 0;
	}

	if (OPS_GetNumRemainingInputArgs() == 4) {
	    numData = 4;
	    if (OPS_GetDoubleInput(&numData, &dData[1]) != 0) {
		opserr << "WARNING invalid optional data: element Tri31 " << endln;
		return 0;
	    }
	}
    }

    // store data for different mesh
    static std::map<int, Vector> meshdata;
    if (info.Size()>0 && info(0)==1) {
	if (info.Size() < 2) {
	    opserr << "WARNING: need info -- inmesh, meshtag\n";
	    return 0;
	}

	// save the data for a mesh
	Vector& mdata = meshdata[info(1)];
	mdata.resize(7);
	for (int i=0; i<5; ++i) {
	    mdata(i) = dData[i];
	}
	mdata(5) = iData[4];
	if (strcmp(theType,"PlaneStrain") == 0 ||
	    strcmp(theType,"PlaneStrain2D") == 0) {
	    mdata(6) = 1;
	} else if (strcmp(theType,"PlaneStress") == 0 ||
		   strcmp(theType,"PlaneStress2D") == 0) {
	    mdata(6) = 2;
	}

	return &meshdata;

    } else if (info.Size()>0 && info(0)==2) {
	if (info.Size() < 6) {
	    opserr << "WARNING: need info -- inmesh, meshtag, eleTag, nd1, nd2, nd3\n";
	    return 0;
	}

	// get the data for a mesh
	Vector& mdata = meshdata[info(1)];
	if (mdata.Size() < 7) return 0;

	for (int i=0; i<5; ++i) {
	    dData[i] = mdata(i);
	}
	for (int i=0; i<4; ++i) {
	    iData[i] = info(2+i);
	}
	iData[4] = mdata(5);
	if (mdata(6) == 1) {
	    theType = (char*)"PlaneStrain";
	} else if (mdata(6) == 2) {
	    theType = (char*)"PlaneStress";
	}
    }

    int matID = iData[4];
    NDMaterial *theMaterial = OPS_getNDMaterial(matID);
    if (theMaterial == 0) {
	opserr << "WARNING element Tri31 " << iData[0] << endln;
	opserr << " Material: " << matID << "not found\n";
	return 0;
    }

    // parsing was successful, allocate the element
    theElement = new Tri31(iData[0], iData[1], iData[2], iData[3],
			   *theMaterial, theType,
			   dData[0], dData[1], dData[2], dData[3], dData[4]);

    if (theElement == 0) {
	opserr << "WARNING could not create element of type Tri31\n";
	return 0;
    }

    return theElement;
}
Example #26
0
int test_azoo_scaling(Epetra_CrsMatrix& A,
                      Epetra_Vector& x,
                      Epetra_Vector& b,
                      bool verbose)
{
  Epetra_Vector vec1(x);
  Epetra_Vector vec2(x);
  Epetra_Vector diag(x);
  Epetra_Vector vec3(x);
  Epetra_Vector vec4(x);
  Epetra_Vector rhs(x);
  Epetra_Vector soln_none(x);
  Epetra_Vector soln_jacobi(x);
  Epetra_Vector soln_rowsum(x);
  Epetra_Vector soln_symdiag(x);

  vec1.PutScalar(1.0);

  A.Multiply(false, vec1, vec2);

  A.ExtractDiagonalCopy(diag);

  double* diag_vals = NULL;
  diag.ExtractView(&diag_vals);

  int* options = new int[AZ_OPTIONS_SIZE];
  double* params = new double[AZ_PARAMS_SIZE];
  AZ_defaults(options, params);

  options[AZ_output] = verbose ? 1 : AZ_none;

  options[AZ_scaling] = AZ_Jacobi;
  AztecOO::MatrixData mdata(&A);
  AZ_MATRIX* Amat = AZ_matrix_create(vec1.Map().NumMyElements());
  AZ_set_MATFREE(Amat, (void*)(&mdata), Epetra_Aztec_matvec);

  AZ_SCALING* scaling = AZ_scaling_create();

  double* xvals = NULL, *bvals = NULL;
  x.ExtractView(&xvals);
  b.ExtractView(&bvals);

  int err = AztecOO_scale_epetra(AZ_SCALE_MAT_RHS_SOL, Amat,
                                 options, bvals, xvals, NULL, scaling);
  if (err != 0) {
    if (verbose) {
      cout << "AztecOO_scale_epetra returned err="<<err<<endl;
    }
    return(err);
  }

  A.Multiply(false, vec1, vec3);

  vec4.Multiply(1.0, diag, vec3, 0.0);

  double vec2nrm, vec4nrm;

  vec2.Norm2(&vec2nrm);
  vec4.Norm2(&vec4nrm);

  if (fabs(vec2nrm - vec4nrm) > 1.e-6) {
    return(-1);
  }

  //now call the scaling function again, just to allow for
  //testing memory-leak issues.
  err = AztecOO_scale_epetra(AZ_SCALE_MAT_RHS_SOL, Amat,
                             options, bvals, xvals, NULL, scaling);
  if (err != 0) {
    if (verbose) {
      cout << "AztecOO_scale_epetra returned err="<<err<<endl;
    }
    return(err);
  }

  AztecOO_scale_epetra(AZ_DESTROY_SCALING_DATA, Amat, options,
                       bvals, xvals, NULL, scaling);

  x.PutScalar(1.0);

  Epetra_CrsMatrix* Atmp = create_and_fill_crs_matrix(A.RowMap());
  Atmp->Multiply(false, x, rhs);

  x.PutScalar(0.0);

  AztecOO azoo(&A, &x, &b);

  azoo.SetAztecOption(AZ_scaling, AZ_Jacobi);
  if (verbose) {
    azoo.SetAztecOption(AZ_output, 1);
  }
  else {
    azoo.SetAztecOption(AZ_output, AZ_none);
  }

  azoo.Iterate(100, 1.e-6);

  delete Atmp;

  Epetra_CrsMatrix* Atmp1 = create_and_fill_crs_matrix(A.RowMap());

  x.PutScalar(1.0);

  Atmp1->Multiply(false, x, rhs);

  soln_rowsum.PutScalar(0.0);

  AztecOO azoo1(Atmp1, &soln_rowsum, &rhs);

  azoo1.SetAztecOption(AZ_scaling, AZ_row_sum);

  azoo1.Iterate(100, 1.e-8);

  delete Atmp1;

  Epetra_CrsMatrix* Atmp2 = create_and_fill_crs_matrix(A.RowMap());

  x.PutScalar(1.0);

  Atmp2->Multiply(false, x, rhs);

  soln_symdiag.PutScalar(0.0);

  AztecOO azoo2(Atmp2, &soln_symdiag, &rhs);

  azoo2.SetAztecOption(AZ_scaling, AZ_sym_diag);

  azoo2.Iterate(100, 1.e-8);

  delete Atmp2;

  Epetra_CrsMatrix* Atmp3 = create_and_fill_crs_matrix(A.RowMap());

  x.PutScalar(1.0);

  Atmp3->Multiply(false, x, rhs);

  soln_none.PutScalar(0.0);

  AztecOO azoo3(Atmp3, &soln_none, &rhs);

  azoo3.SetAztecOption(AZ_scaling, AZ_none);

  azoo3.Iterate(100, 1.e-8);

  delete Atmp3;


  Epetra_CrsMatrix* Atmp4 = create_and_fill_crs_matrix(A.RowMap());

  x.PutScalar(1.0);

  Atmp4->Multiply(false, x, rhs);

  soln_jacobi.PutScalar(0.0);

  AztecOO azoo4(Atmp4, &soln_jacobi, &rhs);

  azoo4.SetAztecOption(AZ_scaling, AZ_Jacobi);

  azoo4.Iterate(100, 1.e-8);

  delete Atmp4;

  //at this point, soln_none, soln_jacobi, soln_rowsum and soln_symdiag
  //should be the same or at least close to the same, since the
  //matrix used in the solution has well-behaved coefficients.
  
  //form vec1 = soln_none - soln_rowsum
  vec1.PutScalar(0.0);
  vec1.Update(1.0, soln_none, 0.0);
  vec1.Update(-1.0, soln_rowsum, 1.0);

  double norm_check1= 0.0;
  vec1.Norm2(&norm_check1);

  //form vec2 = soln_none - soln_symdiag
  vec2.PutScalar(0.0);
  vec2.Update(1.0, soln_none, 0.0);
  vec2.Update(-1.0, soln_symdiag, 1.0);

  double norm_check2= 0.0;
  vec2.Norm2(&norm_check2);

  //form vec3 = soln_none - soln_jacobi
  vec3.PutScalar(0.0);
  vec3.Update(1.0, soln_none, 0.0);
  vec3.Update(-1.0, soln_jacobi, 1.0);

  double norm_check3= 0.0;
  vec3.Norm2(&norm_check3);


  if (std::abs(norm_check1) > 1.e-6) {
    if (verbose) {
      cerr << "AZ_row_sum scaling produced bad soln"
      << endl;
    }
    return(-1);
  }

  if (std::abs(norm_check2) > 1.e-6) {
    if (verbose) {
      cerr << "AZ_sym_diag scaling produced bad soln"
      << endl;
    }
    return(-1);
  }

  if (std::abs(norm_check3) > 1.e-6) {
    if (verbose) {
      cerr << "AZ_Jacobi scaling produced bad soln"
      << endl;
    }
    return(-1);
  }

  options[AZ_pre_calc] = AZ_reuse;

  err = AztecOO_scale_epetra(AZ_SCALE_MAT_RHS_SOL, Amat,
                             options, bvals, xvals, NULL, scaling);
  if (err == 0) {
    if (verbose) {
      cerr << "AztecOO_scale_epetra failed to return err when"
        << " asked to reuse non-existent scaling data."<<endl;
    }
    return(-1);
  }

  options[AZ_keep_info] = 1;
  options[AZ_pre_calc] = AZ_calc;
  err = AztecOO_scale_epetra(AZ_SCALE_MAT_RHS_SOL, Amat,
                             options, bvals, xvals, NULL, scaling);
  if (err != 0) {
    if (verbose) {
      cerr << "AztecOO_scale_epetra returned err=="<<err<<endl;
    }
    return(err);
  }

  options[AZ_keep_info] = 0;
  options[AZ_pre_calc] = AZ_reuse;
  err = AztecOO_scale_epetra(AZ_SCALE_MAT_RHS_SOL, Amat,
                             options, bvals, xvals, NULL, scaling);
  if (err != 0) {
    if (verbose) {
      cerr << "AztecOO_scale_epetra returned err=="<<err
          <<" when asked to reuse scaling data"<<endl;
    }
    return(err);
  }

  options[AZ_pre_calc] = AZ_calc;
  err = AztecOO_scale_epetra(AZ_DESTROY_SCALING_DATA, Amat,
                             options, bvals, xvals, NULL, scaling);
  if (err != 0) {
    if (verbose) {
      std::cerr << "AztecOO_scale_epetra returned err=="<<err
      << " when asked to destroy scaling data."<<std::endl;
    }
    return(err);
  }

  AZ_matrix_destroy(&Amat);
  delete [] options; 
  delete [] params;
  AZ_scaling_destroy(&scaling);

  AZ_manage_memory(0, AZ_CLEAR_ALL, 0, 0, 0);

  return(0);
}
Example #27
0
int lt_op ( )
{
    Matrix	a;
    Matrix	b;
    Matrix	c;
    double	lvalue;
    double	rvalue;
    descriptor *left;
    descriptor *right;
    descriptor *result;
    descriptor	temp;
    int		type_error;
    int		status;
    int		cmp;
    unsigned	i;
    unsigned	j;


    right = pop ( );
    result = top ( );
    temp = *result;
    left = &temp;

    left = deref (left);
    right = deref (right);

    if (D_Type (left) != T_String || D_Type (right) != T_String) {
	left = CoerceData (left, T_Double);
	right = CoerceData (right, T_Double);
    }


    status = 0;
    type_error = F_False;


    switch (D_Type (left)) {
    case T_Double:
	switch (D_Type (right)) {
	case T_Double:
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (*D_Double (left) < *D_Double (right));
	    break;


	case T_Matrix:
	    a = D_Matrix (right);
	    CreateData (result, left, right, T_Matrix, Mrows (a), Mcols (a));
	    b = D_Matrix (result);
	    lvalue = *D_Double (left);
	    for (i = 1; i <= Mrows (a); i ++)
		for (j = 1; j <= Mcols (a); j ++)
		    sdata (b, i, j) = lvalue < mdata (a, i, j);
	    break;


	default:
	    type_error = F_True;
	    break;
	}
	break;


    case T_Matrix:
	switch (D_Type (right)) {
	case T_Double:
	    a = D_Matrix (left);
	    CreateData (result, left, right, T_Matrix, Mrows (a), Mcols (a));
	    b = D_Matrix (result);
	    rvalue = *D_Double (right);
	    for (i = 1; i <= Mrows (a); i ++)
		for (j = 1; j <= Mcols (a); j ++)
		    sdata (b, i, j) = mdata (a, i, j) < rvalue;
	    break;


	case T_Matrix:
	    a = D_Matrix (left);
	    b = D_Matrix (right);
	    CreateData (result, left, right, T_Matrix, Mrows (a), Mcols (a));
	    c = D_Matrix (result);
	    if ((status = CompareLTMatrices (c, a, b)))
		MatrixError ("<", a, b, status, F_False);
	    break;


	default:
	    type_error = F_True;
	    break;
	}
	break;


    case T_String:
	switch (D_Type (right)) {
	case T_String:
	    cmp = strcmp (*D_String (left), *D_String (right));
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (cmp < 0);
	    break;


	default:
	    type_error = F_True;
	    break;
	}
	break;


    default:
	type_error = F_True;
	break;
    }


    if (type_error == F_True)
	TypeError ("<", left, right, NULL, F_False);


    RecycleData (left);
    RecycleData (right);
    d_printf ("lt ans =\n");
    d_PrintData (result);

    return type_error == F_True || status != 0;
}
Example #28
0
int ne_op ( )
{
    Matrix	a;
    Matrix	b;
    Matrix	c;
    double	lvalue;
    double	rvalue;
    descriptor *left;
    descriptor *right;
    descriptor *result;
    descriptor	temp;
    int		type_error;
    int		status;
    int		cmp;
    unsigned	i;
    unsigned	j;


    right = pop ( );
    result = top ( );
    temp = *result;
    left = &temp;

    left = deref (left);
    right = deref (right);

    if (D_Type (left) != T_String || D_Type (right) != T_String) {
	left = CoerceData (left, T_Double);
	right = CoerceData (right, T_Double);
    }


    status = 0;
    type_error = F_False;


    switch (D_Type (left)) {
    case T_Double:
	switch (D_Type (right)) {
	case T_Double:
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (*D_Double (left) != *D_Double (right));
	    break;


	case T_Matrix:
	    a = D_Matrix (right);
	    CreateData (result, left, right, T_Matrix, Mrows (a), Mcols (a));
	    b = D_Matrix (result);
	    lvalue = *D_Double (left);
	    for (i = 1; i <= Mrows (a); i ++)
		for (j = 1; j <= Mcols (a); j ++)
		    sdata (b, i, j) = lvalue != mdata (a, i, j);
	    break;


	default:
	    type_error = F_True;
	    break;
	}
	break;


    case T_Matrix:
	switch (D_Type (right)) {
	case T_Double:
	    a = D_Matrix (left);
	    CreateData (result, left, right, T_Matrix, Mrows (a), Mcols (a));
	    b = D_Matrix (result);
	    rvalue = *D_Double (right);
	    for (i = 1; i <= Mrows (a); i ++)
		for (j = 1; j <= Mcols (a); j ++)
		    sdata (b, i, j) = mdata (a, i, j) != rvalue;
	    break;


	case T_Matrix:
	    a = D_Matrix (left);
	    b = D_Matrix (right);
	    CreateData (result, left, right, T_Matrix, Mrows (a), Mcols (a));
	    c = D_Matrix (result);
	    if ((status = CompareNEQMatrices (c, a, b)))
		MatrixError ("!=", a, b, status, F_False);
	    break;


	default:
	    type_error = F_True;
	    break;
	}
	break;


    case T_String:
	switch (D_Type (right)) {
	case T_String:
	    cmp = strcmp (*D_String (left), *D_String (right));
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (cmp != 0);
	    break;


	default:
	    type_error = F_True;
	    break;
	}
	break;


    case T_Function:
    case T_Intrinsic:
    case T_Array:
    case T_Pair:
	if (D_Type (left) == D_Type (right)) {
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (D_Pointer (left) == D_Pointer (right));
	} else
	    type_error = F_False;
	break;


    case T_Constraint:
    case T_Definition:
    case T_Element:
    case T_Force:
    case T_Load:
    case T_Material:
    case T_Node:
    case T_Stress:
    case T_External:
	if (D_Type (left) == D_Type (right)) {
	    cmp = *(void **) D_Pointer (left) != *(void **) D_Pointer (right);
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (cmp);
	} else if (D_Type (right) == T_Null) {
	    cmp = *(void **) D_Pointer (left) != NULL;
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (cmp);
	} else
	    type_error = F_True;
	break;


    case T_Null:
	switch (D_Type (right)) {
	case T_Constraint:
	case T_Definition:
	case T_Element:
	case T_Force:
	case T_Load:
	case T_Material:
	case T_Node:
	case T_Stress:
	case T_External:
	    cmp = *(void **) D_Pointer (right) != NULL;
	    D_Type    (result) = T_Double;
	    D_Temp    (result) = F_False;
	    D_Trapped (result) = F_False;
	    D_Double  (result) = dbllit (cmp);
	    break;


	default:
	    type_error = F_True;
	    break;
	}
	break;


    default:
	type_error = F_True;
	break;
    }


    if (type_error == F_True)
	TypeError ("!=", left, right, NULL, F_False);


    RecycleData (left);
    RecycleData (right);
    d_printf ("ne ans =\n");
    d_PrintData (result);

    return type_error == F_True || status != 0;
}