Ejemplo n.º 1
0
/*Movs to the top of natrix all columns with non-zero elements with intdex = number*/
void ConverterUV::sortColumn(int number)
{
    QVector<QVector<qreal> > sortedMatix = QVector<QVector<qreal> >();
    QVector<qreal> newRightPart = QVector<qreal>();
    if(number < matrix.size())
    {
        for(int i = 0; i < matrix.size(); i++)
        {
            if(i >= number)
            {
                if(matrix[i][number] == 0)
                {
                    sortedMatix.push_back(matrix[i]);
                    newRightPart.push_back(rightPart[i]);
                }
                else
                {
                    sortedMatix.push_front(matrix[i]);
                    newRightPart.push_front(rightPart[i]);
                }
            }
        }
        for(int i = number - 1; i >= 0; i--)
        {
            sortedMatix.push_front(matrix[i]);
            newRightPart.push_front(rightPart[i]);
        }
        matrix = sortedMatix;
        rightPart = newRightPart;
    }
}
Ejemplo n.º 2
0
QVector<Actions> Subsequence::findLCS() {
  QVector< QVector<int> > table;
  int FirstSize = left_text_.size();
  int SecondSize = right_text_.size();

  table.resize(FirstSize + 1);

  for (int i = 0; i <= FirstSize; i++) {
    table[i].resize(SecondSize + 1);
  }

  for (int i = 0; i <= FirstSize; i++) {
    table[i][0] = 0;
  }
  for (int i = 0; i <= SecondSize; i++) {
    table[0][i] = 0;
  }

  for (int i = 1; i <= FirstSize; i++) {
    for (int j = 1; j <= SecondSize; j++) {
      if (left_text_.at(i - 1) == right_text_.at(j - 1)) {
        table[i][j] = table[i - 1][j - 1] + 1;
      } else {
        table[i][j] = qMax(table[i - 1][j], table[i][j - 1]);
      }
    }
  }

  QVector<Actions> BackTrack;
  int k = left_text_.size();
  int l = right_text_.size();

  for (k, l; table[k][l] != 0 && k > 0 && l > 0; ) {
    if ((table[k][l] > table[k - 1][l]) && (table[k][l] > table[k][l - 1])) {
      BackTrack.push_front(none);
      k--;
      l--;
    } else {
      if (table[k][l] == table[k][l-1]) {
        BackTrack.push_front(insert);
        l--;
      } else {
        BackTrack.push_front(away);
        k--;
      }
    }
  }
  while ( k != 0 || l != 0) {
    if (l != 0) {
      BackTrack.push_front(insert);
      l--;
    } else if (k != 0) {
      BackTrack.push_front(away);
      k--;
    }
  }

  return BackTrack;
}
Ejemplo n.º 3
0
void RgShortestPathWidget::findingPath()
{
  QgsPoint p1, p2;
  QgsGraph *path = getPath( p1, p2 );
  if ( !path )
    return;

  mrbPath->reset( QgsWkbTypes::LineGeometry );
  double time = 0.0;
  double cost = 0.0;

  int startVertexIdx = path->findVertex( p1 );
  int stopVertexIdx  = path->findVertex( p2 );
  QVector< QgsPoint > p;
  while ( startVertexIdx != stopVertexIdx )
  {
    if ( stopVertexIdx < 0 )
      break;

    QgsGraphArcIdList l = path->vertex( stopVertexIdx ).inArc();
    if ( l.empty() )
      break;
    const QgsGraphArc& e = path->arc( l.front() );

    cost += e.property( 0 ).toDouble();
    time += e.property( 1 ).toDouble();

    p.push_front( path->vertex( e.inVertex() ).point() );

    stopVertexIdx = e.outVertex();
  }
  p.push_front( p1 );
  QVector< QgsPoint>::iterator it;
  for ( it = p.begin(); it != p.end(); ++it )
  {
    mrbPath->addPoint( *it );
  }

  Unit timeUnit = Unit::byName( mPlugin->timeUnitName() );
  Unit distanceUnit = Unit::byName( mPlugin->distanceUnitName() );

  mPathCostLineEdit->setText( QString().setNum( cost / distanceUnit.multipler() ) + distanceUnit.name() );
  mPathTimeLineEdit->setText( QString().setNum( time / timeUnit.multipler() ) + timeUnit.name() );

  mrbPath->setColor( Qt::red );

  delete path;
}
Ejemplo n.º 4
0
static void callback(
        float *f0p,
        float *vuvp,
        float *rms_speech,
        float *acpkp,
        int vecsize,
        void *userdata)
{
    Q_UNUSED(rms_speech);
    Q_UNUSED(acpkp);
    QVector<float> *v = (QVector<float>*) userdata;
    for (int i=0; i < vecsize; ++i) {
        v->push_front(vuvp[i]);
        v->push_front(f0p[i]);
    }
}
Ejemplo n.º 5
0
void Scene::addPowerup(Powerup *powerup)
{
    QVector<QString> graphics;
    graphics.push_front(QString("../textures/powerup_default.jpg"));
    PowerupGraphics *powerupGraphics = new PowerupGraphics(&graphics, powerup);
    powerups_.insert(powerupGraphics);
    this->addItem(powerupGraphics);
}
Ejemplo n.º 6
0
QVector<QString> CCFGRule::GetRevertedRightRule()
{
    QVector<QString> revertedVector;
    foreach(CSymbol symbol, m_rightString)
    {
        QString symbol_str = symbol.GetString();
        revertedVector.push_front(symbol_str);
    }
Ejemplo n.º 7
0
QVector<KontrData> XmlDataLayer::XmlDataLayer::kontrahenciSelectAllData() {
	QVector<KontrData> kontrVec;

	QDomDocument doc(sett().getCustomersDocName());
	QDomElement root;
	QDomElement office;
	QDomElement company;

	QFile file(sett().getCustomersXml());
	if (!file.open(QIODevice::ReadOnly)) {
		qDebug() << "File" << file.fileName() << "doesn't exists";
		return kontrVec;
	} else {
		QTextStream stream(&file);
		if (!doc.setContent(stream.readAll())) {
			qDebug("can not set content ");
			file.close();
			return kontrVec;
		} else {
			root = doc.documentElement();
			office = root.firstChild().toElement();
			company = root.lastChild().toElement();
		}

		for (QDomNode n = company.firstChild(); !n.isNull(); n = n.nextSibling()) {
			KontrData kontrData;
			kontrahenciElemToData(kontrData, n.toElement());
			kontrData.type = QObject::trUtf8("Firma");
			kontrVec.push_front(kontrData);
		}

		for (QDomNode n = office.firstChild(); !n.isNull(); n = n.nextSibling()) {
			KontrData kontrData;
			kontrahenciElemToData(kontrData, n.toElement());
			kontrData.type = QObject::trUtf8("Urząd");
			kontrVec.push_front(kontrData);
		}
	}

	return kontrVec;
}
Ejemplo n.º 8
0
QVector<ProductData> XmlDataLayer::productsSelectAllData() {
	QVector<ProductData> prodVec;

	QDomDocument doc(sett().getProdutcsDocName());
	QDomElement root;
	QDomElement products;
	QDomElement services;

	QFile file(sett().getProductsXml());
	if (!file.open(QIODevice::ReadOnly)) {
		qDebug() << "File" << file.fileName() << "doesn't exists";
		return prodVec;
	} else {
		QTextStream stream(&file);
		if (!doc.setContent(stream.readAll())) {
			qDebug("can't set content ");
			file.close();
			return prodVec;
		} else {
			root = doc.documentElement();
			products = root.firstChild().toElement();
			services = root.lastChild().toElement();
		}

		for (QDomNode n = products.firstChild(); !n.isNull(); n = n.nextSibling()) {
			ProductData prodData;
			productsElemToData(prodData, n.toElement());
			prodData.type = QObject::trUtf8("Towar");
			prodVec.push_front(prodData);
		}

		for (QDomNode n = services.firstChild(); !n.isNull(); n = n.nextSibling()) {
			ProductData prodData;
			productsElemToData(prodData, n.toElement());
			prodData.type = QObject::trUtf8("Usługa");
			prodVec.push_front(prodData);
		}
	}

	return prodVec;
}
Ejemplo n.º 9
0
void DistanceSlider::SplitterMoved(int pos, int index)
{
	if(layersCount > 0)
	{
		QList<int> sizes = splitter->sizes();
    
		double scaleSize = GetScaleSize();
		bool continious = false;

		Qt::MouseButtons mouseBtnState = QApplication::mouseButtons();
		if(mouseBtnState & Qt::LeftButton)
		{
			continious = true;
		}
    
		QVector<int> changedLayers;

		int fullSize = 0;
		int splitterWidth = splitter->geometry().width() - splitter->handleWidth() * (layersCount - 1);

		for(int i = 0; i < sizes.size(); ++i)
		{
			int sz = sizes.at(i);
			double value = fullSize * scaleSize / splitterWidth;

			if(stretchSize[i] != value)
			{
				stretchSize[i] = value;
				changedLayers.push_front(i);
			}

			fullSize += sz;
		}
    
		if(changedLayers.size() > 0)
		{
			emit DistanceChanged(changedLayers, continious);
		}
	}
}
QVariantMap QgsShortestPathPointToPointAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
  loadCommonParams( parameters, context, feedback );

  QgsFields fields;
  fields.append( QgsField( QStringLiteral( "start" ), QVariant::String ) );
  fields.append( QgsField( QStringLiteral( "end" ), QVariant::String ) );
  fields.append( QgsField( QStringLiteral( "cost" ), QVariant::Double ) );

  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, QgsWkbTypes::LineString, mNetwork->sourceCrs() ) );
  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  QgsPointXY startPoint = parameterAsPoint( parameters, QStringLiteral( "START_POINT" ), context, mNetwork->sourceCrs() );
  QgsPointXY endPoint = parameterAsPoint( parameters, QStringLiteral( "END_POINT" ), context, mNetwork->sourceCrs() );

  feedback->pushInfo( QObject::tr( "Building graph…" ) );
  QVector< QgsPointXY > points;
  points << startPoint << endPoint;
  QVector< QgsPointXY > snappedPoints;
  mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );

  feedback->pushInfo( QObject::tr( "Calculating shortest path…" ) );
  QgsGraph *graph = mBuilder->graph();
  int idxStart = graph->findVertex( snappedPoints[0] );
  int idxEnd = graph->findVertex( snappedPoints[1] );

  QVector< int > tree;
  QVector< double > costs;
  QgsGraphAnalyzer::dijkstra( graph, idxStart, 0, &tree, &costs );

  if ( tree.at( idxEnd ) == -1 )
  {
    throw QgsProcessingException( QObject::tr( "There is no route from start point to end point." ) );
  }

  QVector<QgsPointXY> route;
  route.push_front( graph->vertex( idxEnd ).point() );
  double cost = costs.at( idxEnd );
  while ( idxEnd != idxStart )
  {
    idxEnd = graph->edge( tree.at( idxEnd ) ).fromVertex();
    route.push_front( graph->vertex( idxEnd ).point() );
  }

  feedback->pushInfo( QObject::tr( "Writing results…" ) );
  QgsGeometry geom = QgsGeometry::fromPolylineXY( route );
  QgsFeature feat;
  feat.setFields( fields );
  QgsAttributes attributes;
  attributes << startPoint.toString() << endPoint.toString() << cost / mMultiplier;
  feat.setGeometry( geom );
  feat.setAttributes( attributes );
  sink->addFeature( feat, QgsFeatureSink::FastInsert );

  QVariantMap outputs;
  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
  outputs.insert( QStringLiteral( "TRAVEL_COST" ), cost / mMultiplier );
  return outputs;
}
QVariantMap QgsShortestPathPointToLayerAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
  loadCommonParams( parameters, context, feedback );

  QgsPointXY startPoint = parameterAsPoint( parameters, QStringLiteral( "START_POINT" ), context, mNetwork->sourceCrs() );

  std::unique_ptr< QgsFeatureSource > endPoints( parameterAsSource( parameters, QStringLiteral( "END_POINTS" ), context ) );
  if ( !endPoints )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "END_POINTS" ) ) );

  QgsFields fields = endPoints->fields();
  fields.append( QgsField( QStringLiteral( "start" ), QVariant::String ) );
  fields.append( QgsField( QStringLiteral( "end" ), QVariant::String ) );
  fields.append( QgsField( QStringLiteral( "cost" ), QVariant::Double ) );

  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, QgsWkbTypes::LineString, mNetwork->sourceCrs() ) );
  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  QVector< QgsPointXY > points;
  points.push_front( startPoint );
  QHash< int, QgsAttributes > sourceAttributes;
  loadPoints( endPoints.get(), points, sourceAttributes, context, feedback );

  feedback->pushInfo( QObject::tr( "Building graph…" ) );
  QVector< QgsPointXY > snappedPoints;
  mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );

  feedback->pushInfo( QObject::tr( "Calculating shortest paths…" ) );
  QgsGraph *graph = mBuilder->graph();
  int idxStart = graph->findVertex( snappedPoints[0] );
  int idxEnd;

  QVector< int > tree;
  QVector< double > costs;
  QgsGraphAnalyzer::dijkstra( graph, idxStart, 0, &tree, &costs );

  QVector<QgsPointXY> route;
  double cost;

  QgsFeature feat;
  feat.setFields( fields );
  QgsAttributes attributes;

  int step =  points.size() > 0 ? 100.0 / points.size() : 1;
  for ( int i = 1; i < points.size(); i++ )
  {
    if ( feedback->isCanceled() )
    {
      break;
    }

    idxEnd = graph->findVertex( snappedPoints[i] );
    if ( tree.at( idxEnd ) == -1 )
    {
      feedback->reportError( QObject::tr( "There is no route from start point (%1) to end point (%2)." )
                             .arg( startPoint.toString(),
                                   points[i].toString() ) );
      feat.clearGeometry();
      attributes = sourceAttributes.value( i );
      attributes.append( QVariant() );
      attributes.append( points[i].toString() );
      feat.setAttributes( attributes );
      sink->addFeature( feat, QgsFeatureSink::FastInsert );
      continue;
    }

    route.clear();
    route.push_front( graph->vertex( idxEnd ).point() );
    cost = costs.at( idxEnd );
    while ( idxEnd != idxStart )
    {
      idxEnd = graph->edge( tree.at( idxEnd ) ).fromVertex();
      route.push_front( graph->vertex( idxEnd ).point() );
    }

    QgsGeometry geom = QgsGeometry::fromPolylineXY( route );
    QgsFeature feat;
    feat.setFields( fields );
    attributes = sourceAttributes.value( i );
    attributes.append( startPoint.toString() );
    attributes.append( points[i].toString() );
    attributes.append( cost / mMultiplier );
    feat.setAttributes( attributes );
    feat.setGeometry( geom );
    sink->addFeature( feat, QgsFeatureSink::FastInsert );

    feedback->setProgress( i * step );
  }

  QVariantMap outputs;
  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
  return outputs;
}
Ejemplo n.º 12
0
void waves::set_p_end(QVector<double>& ecg,vector_it& r_peaks)
{
    double Rv;
    double mediana=0;
    double Pmax=0;
    int P_mid;
    int ipeak;
    QVector<int> P_end;
    QVector<int> P_middle;
    QVector<int> window_length;
    QVector<double> PTend;
    QVector<double> dPTend;
    QVector<double> window_signal;
    QVector<double> onset_signal;
    QVector<double> Pt;
    QVector<double> M;

    int p_one_end_window=20;
    for(int i=0;i<r_peaks.size()-1;i++)
    {
        window_length.push_back(ceil(0.25*((r_peaks.at(i+1)-ecg.begin())-(r_peaks.at(i)-ecg.begin()))));
    }
    for(int i=0;i<window_length.size()-1;i++)
    {
        Rv=0.003;

        for(int j=0;j<window_length.at(i);j++)
        {
            window_signal.push_back(ecg.at(qrs_onset_it.at(i+1)-ecg.begin()-window_length.at(i)-1+j));
        }
        for(int j=0;j<window_signal.size();j++)
        {
            mediana+=window_signal.at(j);
        }
        mediana/=window_length.at(i);
        for(int j=0;j<window_signal.size();j++)
        {
            window_signal.replace(j,window_signal.at(j)-mediana);
            Pt.push_back(atan(window_signal.at(j)/Rv));
            M.push_back(sqrt(pow(Rv,2)+ pow(window_signal.at(j),2)));
        }
        mediana=0;
        for(int j=0;j<Pt.size();j++)
        {
            if(Pmax<=Pt.at(j))
            {
                Pmax=Pt.at(j);
                ipeak=j;
            }
        }
        if (ipeak==0) ipeak=1;                          //analogicznie jak w p_onset
        if (ipeak==M.size()-1) ipeak=M.size()-2;        //
        if((M.at(ipeak-1)<M.at(ipeak))&&(M.at(ipeak)>M.at(ipeak+1)))
        {
            P_mid=ipeak+(qrs_onset_it.at(i+1)-ecg.begin()-window_length.at(i));
            P_middle.push_back(P_mid);
            Rv=0.005;
            for(int j=P_mid;j<P_mid+p_one_end_window;j++)
            {
                onset_signal.push_back(ecg.at(j));
                mediana+=onset_signal.last();
            }
            mediana/=onset_signal.size();

            for(int j=0;j<onset_signal.size();j++)
            {
                onset_signal.replace(j,onset_signal.at(j)-mediana);
                PTend.push_back(atan(onset_signal.at(j)/Rv));
            }
            for(int j=onset_signal.size()-1;j>0;j--)
            {
                if(j==(onset_signal.size()-1))
                    continue;
                else
                {

                    dPTend.push_front(PTend.at(j)-PTend.at(j+1));



                    if(dPTend.first()>0.01)
                    {
                        P_end.push_back(P_mid+j);

                        p_end_it.push_back(ecg.begin()+P_mid+j);
                        break;
                    }
                }
            }}
        window_signal.clear();
        onset_signal.clear();
        Pt.clear();
        M.clear();
        PTend.clear();
        dPTend.clear();
        Pmax=0;
    }
}
Ejemplo n.º 13
0
void main_loop_spe( struct plan7_s * hmm, const char * seq, int seqlen, struct threshold_s *thresh, int do_forward,
            	    int do_null2, int do_xnu, struct histogram_s * histogram, struct tophit_s * ghit, struct tophit_s * dhit, 
                    int * ret_nseq, U2::TaskStateInfo & ti)
{
    Q_UNUSED( do_xnu );
    Q_UNUSED( ret_nseq );
    Q_UNUSED( ti );
//    using namespace U2;

    int initBufSize = 1;
    int cushBufSize = initBufSize;
    struct dpmatrix_s * mx;               
    struct p7trace_s * tr;                

    float  sc = .0f;
    double pvalue = 0.;
    double evalue = 0.;		   
        
    int SPE_THREADS = 8;
    int i = 0;
    int l = 0;

#ifdef USE_SDK30
    spe_context_ptr_t spe_ids[SPE_THREADS];
    pthread_t threads[SPE_THREADS];
#else
    speid_t spe_ids[SPE_THREADS];
    spe_gid_t spe_gid;
#endif

    spe_initContextSB *  spe_contexts;
    spe_jobEntity     *  jobQueue;
    int                  jobQueueIndex;

    volatile int    nomoreSeqs_var    __attribute__ ((aligned (128)));
    atomic_ea_t     nomoreSeqs;
    addr64          long_addr_nomoreSeqs;

    volatile int    lastConsumed_var    __attribute__ ((aligned (128)));
    atomic_ea_t     lastConsumed;
    addr64          long_addr_lastConsumed;

    volatile int    bufferEntries_var    __attribute__ ((aligned (128)));
    atomic_ea_t     bufferEntries;
    addr64          long_addr_bufferEntries;

    volatile int    bufferMutex_var    __attribute__ ((aligned (128)));
    mutex_ea_t      bufferMutex;
    addr64          long_addr_bufferMutex;

    volatile int    bufferEmptyCond_var    __attribute__ ((aligned (128)));
    cond_ea_t       bufferEmptyCond;
    addr64          long_addr_bufferEmptyCond;

    int * scratchBuffer;
    hmm_offsets * offsets;

    int * sequencesMatrix;
    int * lengthMatrix;
    int   numSeqs = 0;
    int   numTracebacks = 0;

    char * mem_addr = NULL;
    unsigned char  * seqAddr;

    int   seqsFinished  = 0;
    int   numCushion    = 0;

    /*--------------1 - SETUP: ALLOCATE MEMORY FOR DATA STRUCTURES---------------------*/
    nomoreSeqs_var = 0;
    long_addr_nomoreSeqs.ui[0] = 0;
    long_addr_nomoreSeqs.ui[1] = (unsigned int) (&nomoreSeqs_var);
    nomoreSeqs = (atomic_ea_t) long_addr_nomoreSeqs.ull;

    lastConsumed_var = 0;
    long_addr_lastConsumed.ui[0] = 0;
    long_addr_lastConsumed.ui[1] = (unsigned int) (&lastConsumed_var);
    lastConsumed = (atomic_ea_t) long_addr_lastConsumed.ull;

    bufferEntries_var = 0;
    long_addr_bufferEntries.ui[0] = 0;
    long_addr_bufferEntries.ui[1] = (unsigned int) (&bufferEntries_var);
    bufferEntries = (atomic_ea_t) long_addr_bufferEntries.ull;

    bufferMutex_var = 0;
    long_addr_bufferMutex.ui[0] = 0;
    long_addr_bufferMutex.ui[1] = (unsigned int) (&bufferMutex_var);
    bufferMutex = (mutex_ea_t) long_addr_bufferMutex.ull;

    bufferEmptyCond_var = 0;
    long_addr_bufferEmptyCond.ui[0] = 0;
    long_addr_bufferEmptyCond.ui[1] = (unsigned int) (&bufferEmptyCond_var);
    bufferEmptyCond = (cond_ea_t) long_addr_bufferEmptyCond.ull;

#ifndef NO_HUGE_PAGES
    assert( false && "correct huge pages realization is not implemented yet" );
    //FIXME: implement correct 'huge pages' memory allocation    
#else
    mem_addr = (char *) memalign( 128, 0x09000000 );
    memset( mem_addr, 0, 0x09000000 );
#endif

    assert( NULL != mem_addr );
    //Allocate all data structures on mapped area
    scratchBuffer   = (int*)               (mem_addr + 0x0000000);
    offsets         = (hmm_offsets*)       (mem_addr + 0x0050000);
    spe_contexts    = (spe_initContextSB*) (mem_addr + 0x0051000);
    sequencesMatrix = (int*)               (mem_addr + 0x0400000);
    lengthMatrix    = (int*)               ((unsigned long)((char *)sequencesMatrix + NUM_OF_SEQS_UPPER_LIMIT * 4 + 127)&~0x7F);
    MakeHMMBuffer_Aligned(hmm, (void*) scratchBuffer, 0x0050000, offsets);  
        
    /*--------------2 - CREATE INITIAL BUFFER---------------------*/
    /* This stage is where we create a small preliminary buffer that will hold
    enough sequences to get the SPEs started. Once the SPE threads start fetching
    and processing sequences, we will be populating the buffer fully in Stage 4. */

    jobQueue = (spe_jobEntity*) ((unsigned long)((char*)lengthMatrix + NUM_OF_SEQS_UPPER_LIMIT * 4 + 127)&~0x7F);
    seqAddr  = (unsigned char *)jobQueue + NUM_OF_SEQS_UPPER_LIMIT * 128;

    jobQueueIndex = -1;
    atomic_set(bufferEntries,0);
    //Initialize mutexes etc.
    mutex_init(bufferMutex);
    cond_init(bufferEmptyCond);

    //FIXME refactoring needed
    //FIXME use non-constant chunk size
    U2Region wholeSeq( 0, seqlen );
//    int veryMaxChunkSize = MAX_SEQ_LENGTH - 100;
//    int approxChunkSize = seqlen / 24;
//    int maxChunkSize = qBound( hmm->M, approxChunkSize, veryMaxChunkSize );
    assert( hmm->M < MAX_HMM_LENGTH );
    int overlap = hmm->M * 2;
    int exOverlap = 0;
//    int chunkSize = qMax( hmm->M+2, maxChunkSize-1 - overlap );
    int chunkSize = qBound( hmm->M+2, MAX_SEQ_LENGTH-100, seqlen );
    if( chunkSize + overlap > MAX_SEQ_LENGTH - 100 ) {
	chunkSize -= overlap;
    }    
    int maxChunkSize = MAX_SEQ_LENGTH-100;

    QVector<U2Region> regions;
    regions = SequenceWalkerTask::splitRange( wholeSeq, chunkSize, overlap, 0, 1, false );
    assert( !regions.empty() );
    
    //hack caused by splitRange behaviour
    if( regions.first().length > maxChunkSize ) {
//        assert( 1 == regions.size() );
        U2Region r1st = regions.takeFirst();
        assert( r1st.length < 2 * maxChunkSize );
        
//        int len = chunkSize + overlap / 2;
	int len = chunkSize;
        int tail = r1st.length - len;
        int z = overlap/2 - tail;
        len -= qMax( 0, z );
                
        assert( 0 == r1st.startPos );
        U2Region r1( r1st.startPos, len );
        U2Region r2( len - overlap/2,  r1st.length-(len-overlap/2) );
        regions.push_front( r2 );
        regions.push_front( r1 );
    }

    foreach( U2Region r, regions ) {
        assert( r.length <= MAX_SEQ_LENGTH-100 );
    }
Ejemplo n.º 14
0
bool generatePreview(const QString& textureFilename, const QString& paletteFilename, const QString& previewFilename, const QString& codeUsageFilename) {
	char	magic[4];
	qint16	width, height;
	qint32	textureType;
	qint32	textureSize;
	quint8* data = NULL;

	const bool genPreview = !previewFilename.isEmpty();
	const bool genCodeUsage = !codeUsageFilename.isEmpty();

	if (textureFilename.isEmpty()) {
		qCritical() << "generatePreview requires a texture filename";
		return false;
	}

	if (!genPreview && !genCodeUsage) {
		qCritical() << "generatePreview requires either a preview filename or a code usage filename";
		return false;
	}

	// Open up an input stream to read the texture
	QFile in(textureFilename);
	if (!in.open(QIODevice::ReadOnly)) {
		qCritical() << "Failed to open" << textureFilename;
		return false;
	}
	QDataStream stream(&in);
	stream.setByteOrder(QDataStream::LittleEndian);

	// Read the header
	stream.readRawData(magic, 4);
	stream >> width;
	stream >> height;
	stream >> textureType;
	stream >> textureSize;

	// Verify the header
	if (memcmp(magic, TEXTURE_MAGIC, 4) != 0) {
		qCritical() << textureFilename << "is not a valid texture file";
		in.close();
		return false;
	}

	// Read the texture data and close the stream
	data = new quint8[textureSize];
	stream.readRawData((char*)data, textureSize);
	in.close();

	if (!genPreview && !(textureType & FLAG_COMPRESSED)) {
		qCritical() << "generatePreview was told to only generate code usage, but texture is not compressed";
		return false;
	}

	// Texture width for stride textures are stored in the stride setting, not in
	// the width field. So unpack that if neccessary.
	if (textureType & FLAG_STRIDED) {
		width = (textureType & 31) * 32;
	}

	const int pixelFormat = (textureType >> PIXELFORMAT_SHIFT) & PIXELFORMAT_MASK;
	QVector<QImage> decodedImages;
	QVector<QImage> codeUsageImages;

	/*qDebug() << "Loaded texture" << textureFilename;
	qDebug("Width        : %d", width);
	qDebug("Height       : %d", height);
	qDebug("TextureType  : %08x", textureType);
	qDebug("Pixel format : %d", pixelFormat);
	qDebug("Size (bytes) : %d", textureSize);*/

	if (textureType & FLAG_STRIDED) {
		QImage img(width, height, QImage::Format_ARGB32);
		img.fill(Qt::transparent);

		if (pixelFormat == PIXELFORMAT_YUV422) {
			for (int y=0; y<height; y++) {
				for (int x=0; x<width; x+=2) {
					const int i0 = (y * width + x + 0) * 2;
					const int i1 = (y * width + x + 1) * 2;
					const quint16 p0 = qFromLittleEndian<quint16>(&data[i0]);
					const quint16 p1 = qFromLittleEndian<quint16>(&data[i1]);
					QRgb rgb0, rgb1;
					YUV422toRGB(p0, p1, rgb0, rgb1);
					img.setPixel(x + 0, y, rgb0);
					img.setPixel(x + 1, y, rgb1);
				}
			}
		} else {
			for (int y=0; y<height; y++) {
				for (int x=0; x<width; x++) {
					const int index = (y * width + x) * 2;
					const quint16 pixel = qFromLittleEndian<quint16>(&data[index]);
					img.setPixel(x, y, to32BPP(pixel, pixelFormat));
				}
			}
		}

		decodedImages.push_back(img);
	} else if (is16BPP(textureType) && !(textureType & FLAG_COMPRESSED)) {
		int currentWidth = width;
		int currentHeight = height;
		int offset = 0;

		if (textureType & FLAG_MIPMAPPED) {
			currentWidth = 1;
			currentHeight = 1;
			offset = MIPMAP_OFFSET_16BPP;
		}

		while (currentWidth <= width && currentHeight <= height) {
			QImage img(currentWidth, currentHeight, QImage::Format_ARGB32);
			img.fill(Qt::transparent);
			const Twiddler twiddler(currentWidth, currentHeight);
			const int pixels = currentWidth * currentHeight;

			if (pixelFormat == PIXELFORMAT_YUV422) {
				if (pixels == 1) {
					// The 1x1 mipmap level for YUV textures is stored as RGB565
					const quint16 texel = qFromLittleEndian<quint16>(&data[offset]);
					img.setPixel(0, 0, to32BPP(texel, PIXELFORMAT_RGB565));
				} else {
					for (int i=0; i<pixels; i+=4) {
						quint16 texel[4];
						QRgb pixel[4];

						for (int j=0; j<4; j++)
							texel[j] = qFromLittleEndian<quint16>(&data[offset + (i+j)*2]);

						YUV422toRGB(texel[0], texel[2], pixel[0], pixel[2]);
						YUV422toRGB(texel[1], texel[3], pixel[1], pixel[3]);

						for (int j=0; j<4; j++) {
							const int twidx = twiddler.index(i+j);
							const int x = twidx % currentWidth;
							const int y = twidx / currentWidth;
							img.setPixel(x, y, pixel[j]);
						}
					}
				}
			} else {
				for (int i=0; i<pixels; i++) {
					const quint16 texel = qFromLittleEndian<quint16>(&data[offset + i*2]);
					const QRgb pixel = to32BPP(texel, pixelFormat);
					const int twidx = twiddler.index(i);
					const int x = twidx % currentWidth;
					const int y = twidx / currentWidth;
					img.setPixel(x, y, pixel);
				}
			}

			decodedImages.push_front(img);

			offset += (currentWidth * currentHeight * 2);
			currentWidth *= 2;
			currentHeight *= 2;
		}
	} else if (isPaletted(textureType) && !(textureType & FLAG_COMPRESSED)) {
		if (paletteFilename.isEmpty())
			return false;
		Palette palette;
		if (!palette.load(paletteFilename))
			return false;

		if (isFormat(textureType, PIXELFORMAT_PAL4BPP)) {
			int currentWidth = width;
			int currentHeight = height;
			int offset = 0;

			if (textureType & FLAG_MIPMAPPED) {
				currentWidth = 1;
				currentHeight = 1;
				offset = MIPMAP_OFFSET_4BPP;
			}

			while (currentWidth <= width && currentHeight <= height) {
				QImage img(currentWidth, currentHeight, QImage::Format_ARGB32);
				img.fill(Qt::transparent);
				const Twiddler twiddler(currentWidth, currentHeight);
				const int pixels = (currentWidth * currentHeight) / 2;

				if (currentWidth == 1 && currentHeight == 1) {
					img.setPixel(0, 0, palette.colorAt(data[offset] & 0xf));
					offset++;
				} else {
					for (int i=0; i<pixels; i++) {
						const QRgb pixel0 = palette.colorAt((data[offset + i] >> 0) & 0xf);
						const QRgb pixel1 = palette.colorAt((data[offset + i] >> 4) & 0xf);
						const int twidx0 = twiddler.index(i * 2 + 0);
						const int twidx1 = twiddler.index(i * 2 + 1);
						const int x0 = twidx0 % currentWidth;
						const int y0 = twidx0 / currentWidth;
						img.setPixel(x0, y0, pixel0);
						const int x1 = twidx1 % currentWidth;
						const int y1 = twidx1 / currentWidth;
						img.setPixel(x1, y1, pixel1);
					}

					offset += (currentWidth * currentHeight) / 2;
				}

				decodedImages.push_front(img);

				currentWidth *= 2;
				currentHeight *= 2;
			}

		} else if (isFormat(textureType, PIXELFORMAT_PAL8BPP)) {
			int currentWidth = width;
			int currentHeight = height;
			int offset = 0;

			if (textureType & FLAG_MIPMAPPED) {
				currentWidth = 1;
				currentHeight = 1;
				offset = MIPMAP_OFFSET_8BPP;
			}

			while (currentWidth <= width && currentHeight <= height) {
				QImage img(currentWidth, currentHeight, QImage::Format_ARGB32);
				img.fill(Qt::transparent);
				const Twiddler twiddler(currentWidth, currentHeight);
				const int pixels = currentWidth * currentHeight;

				for (int i=0; i<pixels; i++) {
					const QRgb pixel = palette.colorAt(data[offset + i]);
					const int twidx = twiddler.index(i);
					const int x = twidx % currentWidth;
					const int y = twidx / currentWidth;
					img.setPixel(x, y, pixel);
				}

				decodedImages.push_front(img);
				offset += (currentWidth * currentHeight);

				currentWidth *= 2;
				currentHeight *= 2;
			}
		}
	} else if (is16BPP(textureType) && (textureType & FLAG_COMPRESSED)) {
Ejemplo n.º 15
0
void MainWindow::on_startSimulationPushButton_clicked()
{
    QTime timer;
    timer.start();
	qDebug() << "loading parameters...";
	double alpha = ui->alpha_lineedit->text().toDouble();
	int minNumberOfBusStopsInRegion = ui->minbusstopsinregion->text().toInt();
	int maxNumberOfBusStopsInRegion = ui->maxbusstopsinregion->text().toInt();
	int minBuslineLength = ui->minlinelength->text().toInt();
	int maxBuslineLength = ui->maxlinelength->text().toInt();
	int populationMultiplier = ui->multiplier_lineedit->text().toInt();
	int percentageOfCrossedSolution = ui->crossed_lineedit->text().toInt();
    int iterationsForDifferentBaseSolutions = ui->iterations_for_diff->text().toInt();
	QVector<Parameters::MutationType> mutations;


	if ( ui->mutationType_simple->isChecked() )
		mutations.push_front(Parameters::SIMPLE_MUTATION);
	if ( ui->mutationType_random->isChecked() )
			mutations.push_front(Parameters::RANDOM_MUTATION);
	if ( ui->mutationType_moreRandom->isChecked() )
		mutations.push_front(Parameters::MORE_RANDOM_MUTATION);
	if ( ui->mutationType_evenMoreRandom->isChecked() )
		mutations.push_front(Parameters::EVEN_MORE_RANDOM_MUTATION);

	long numberOfIterations = ui->numofiterations->text().toInt();

	qDebug() << "Parameters loaded";
	qDebug() << "alpha" << alpha << endl
			 << "minNumberOfBusStopsInRegion" << minNumberOfBusStopsInRegion << endl
			 << "maxNumberOfBusStopsInRegion" << maxNumberOfBusStopsInRegion << endl
			 << "minBuslineLength" << minBuslineLength << endl
			 << "maxBuslineLength" << maxBuslineLength << endl
			 << "numberOfIterations" << numberOfIterations << endl
			 << "populationSizeMultiplier" << populationMultiplier << endl;

	Parameters::setAlpha(alpha);
	Parameters::setMinNumberOfBusStopsInRegion(minNumberOfBusStopsInRegion);
	Parameters::setMaxNumberOfBusStopsInRegion(maxNumberOfBusStopsInRegion);
	Parameters::setMinNumberOfBusStopsInBusline(minBuslineLength);
	Parameters::setMaxNumberOfBusStopsInBusLine(maxBuslineLength);
	Parameters::setPopulationSizeMultiplier(populationMultiplier);
	Parameters::setPercentageOfCrossedSolutions(percentageOfCrossedSolution);
	Parameters::setMutationOperators(mutations.toStdVector());
	// TODO : set the lambda parameter
	algorithm->setNumberOfIterations(numberOfIterations);
	if ( ! dataLoaded )
	{
		loadBusStops();
	}
	if ( ! dataLoaded ) return;
	Solution optimalSolution;
    Solution tempSolution;
    QVector<double> vectorOfValuesFromDifferentBaseSolutions;
    try
    {
        model->loadBusStopsFromFile(dataFileName.toStdString());
        qDebug() << "Before optimization";
        optimalSolution = algorithm->performOptimization();
        vectorOfValuesFromDifferentBaseSolutions.push_back(model->objectiveFunction(optimalSolution));
        for(int i = 1; i < iterationsForDifferentBaseSolutions; i++)
        {
            tempSolution = algorithm->performOptimization();
            if(model->objectiveFunction(tempSolution) > model->objectiveFunction(optimalSolution))
                optimalSolution = tempSolution;

            vectorOfValuesFromDifferentBaseSolutions.push_back(model->objectiveFunction(tempSolution));
        }
    } catch ( InvalidBoundsException * exc )
    {
        QMessageBox::warning(NULL, "Error", "Ograniczenia są nieprawidłowe. Przerwano optymalizację", QMessageBox::Ok);
        qDebug() << QString::fromStdString(exc->getMessage());
        qDebug() << "Skipping optimization due to invalid bounds" << endl;
        return;
    }
    saveResultsAndInvokeGnuplotIfRequested(QVector<double>::fromStdVector(algorithm->getValuesOfObjectiveFunction()),
                                           QVector<int>::fromStdVector(optimalSolution.toStdVector()));

    drawSolution(optimalSolution);
    ui->objectiveValueLabel->setText(QString::number(model->objectiveFunction(optimalSolution)));

    saveResultsFromDifferentBaseSolutions(vectorOfValuesFromDifferentBaseSolutions);

    qDebug() << "Przeprowadzenie optymalizacji zajęło " << timer.elapsed() << " ms." << endl;
    QApplication::beep();
    QThread::sleep(1);
    QApplication::beep();
    QThread::sleep(1);
    QApplication::beep();
    QThread::sleep(1);
    QApplication::beep();
}
Ejemplo n.º 16
0
void ViewWorkerThread::prepareImage(QList<QGraphicsItem*> items)
{
	stopLoading();

	QVector<CustomItem*> itemsNotLoaded;

	QVector<CustomItem*> itemsBeingProcessed;

	//Find all items whose images are not loaded.
	for (int index = 0; index < items.count(); index++)
	{
		CustomItem* item = dynamic_cast<CustomItem*> (items[index]);

		if ((true == item->pixmap().isNull())
						||
			((nItemWidth > (item->pixmap().width() + CustomItem::getItemMargin()))
						&&
			 (nItemHeight > (item->pixmap().height() + CustomItem::getItemMargin()))))
		{
			if (EProcessingState::eNone == item->processingState())
			{
				itemsNotLoaded.push_front(item);
			}
			else if (EProcessingState::eProcessed == item->processingState())
			{
				item->updateItem();

				item->setProcessing(EProcessingState::eRenderred);
			}
		}
		else if ((EProcessingState::eNone != item->processingState()) 
									&&
				(EProcessingState::eRenderred != item->processingState()))
		{
			item->updateItem();

			item->setProcessing(EProcessingState::eRenderred);
		}
	}

	CustomGraphicsView* parentView = dynamic_cast<CustomGraphicsView*> (parent());

	QList<QGraphicsItem *> viewItems = parentView->items();

	//Clear images from items that are not currently viewed. 
	//(To optimize memory consumption)
	for (int index = 0; index < viewItems.count(); index++)
	{
		if (!items.contains(viewItems[index]))
		{
			CustomItem* item = dynamic_cast<CustomItem*> (viewItems[index]);

			item->setPixmap(0);

			item->setProcessing(EProcessingState::eNone);
		}
	}

	if (itemsNotLoaded.isEmpty())
	{
		return;
	}

	m_ItemsNotLoaded.clear();

	m_ItemsNotLoaded = itemsNotLoaded;

	//Load images.
	m_pImageLoadThreadWatcher->setFuture(QtConcurrent::mapped(m_ItemsNotLoaded, readEmf));
}