Exemple #1
0
 forceinline bool
 FloatVarImp::in(const FloatVal& n) const {
   return subset(n,dom);
 }
Exemple #2
0
/*
 - cdissect - check backrefs and determine subexpression matches
 * cdissect recursively processes a subre tree to check matching of backrefs
 * and/or identify submatch boundaries for capture nodes.  The proposed match
 * runs from "begin" to "end" (not including "end"), and we are basically
 * "dissecting" it to see where the submatches are.
 * Before calling any level of cdissect, the caller must have run the node's
 * DFA and found that the proposed substring satisfies the DFA.  (We make
 * the caller do that because in concatenation and iteration nodes, it's
 * much faster to check all the substrings against the child DFAs before we
 * recurse.)  Also, caller must have cleared subexpression match data via
 * zaptreesubs (or zapallsubs at the top level).
 ^ static int cdissect(struct vars *, struct subre *, chr *, chr *);
 */
static int			/* regexec return code */
cdissect(
    struct vars *v,
    struct subre *t,
    chr *begin,		/* beginning of relevant substring */
    chr *end)		/* end of same */
{
    int er;

    assert(t != NULL);
    MDEBUG(("cdissect %ld-%ld %c\n", LOFF(begin), LOFF(end), t->op));

    switch (t->op) {
    case '=':			/* terminal node */
	assert(t->left == NULL && t->right == NULL);
	er = REG_OKAY;		/* no action, parent did the work */
	break;
    case 'b':			/* back reference */
	assert(t->left == NULL && t->right == NULL);
	er = cbrdissect(v, t, begin, end);
	break;
    case '.':			/* concatenation */
	assert(t->left != NULL && t->right != NULL);
	if (t->left->flags & SHORTER) /* reverse scan */
	    er = crevcondissect(v, t, begin, end);
	else
	    er = ccondissect(v, t, begin, end);
	break;
    case '|':			/* alternation */
	assert(t->left != NULL);
	er = caltdissect(v, t, begin, end);
	break;
    case '*':			/* iteration */
	assert(t->left != NULL);
	if (t->left->flags & SHORTER) /* reverse scan */
	    er = creviterdissect(v, t, begin, end);
	else
	    er = citerdissect(v, t, begin, end);
	break;
    case '(':			/* capturing */
	assert(t->left != NULL && t->right == NULL);
	assert(t->subno > 0);
	er = cdissect(v, t->left, begin, end);
	if (er == REG_OKAY) {
	    subset(v, t, begin, end);
	}
	break;
    default:
	er = REG_ASSERT;
	break;
    }

    /*
     * We should never have a match failure unless backrefs lurk below;
     * otherwise, either caller failed to check the DFA, or there's some
     * inconsistency between the DFA and the node's innards.
     */
    assert(er != REG_NOMATCH || (t->flags & BACKR));

    return er;
}
Exemple #3
0
void test_subset()
{
    int a[] = {1,2,3,4,5};
    int x[5];
    subset(a, 5, 0, 0, x);
}
    void
    StandardWellsSolvent::
    computePropertiesForWellConnectionPressures(const SolutionState& state,
                                                const WellState& xw,
                                                std::vector<double>& b_perf,
                                                std::vector<double>& rsmax_perf,
                                                std::vector<double>& rvmax_perf,
                                                std::vector<double>& surf_dens_perf)
    {
        // 1. Compute properties required by computeConnectionPressureDelta().
        //    Note that some of the complexity of this part is due to the function
        //    taking std::vector<double> arguments, and not Eigen objects.
        const int nperf = wells().well_connpos[wells().number_of_wells];
        const int nw = wells().number_of_wells;

        // Compute the average pressure in each well block
        const Vector perf_press = Eigen::Map<const V>(xw.perfPress().data(), nperf);
        Vector avg_press = perf_press*0;
        for (int w = 0; w < nw; ++w) {
            for (int perf = wells().well_connpos[w]; perf < wells().well_connpos[w+1]; ++perf) {
                const double p_above = perf == wells().well_connpos[w] ? state.bhp.value()[w] : perf_press[perf - 1];
                const double p_avg = (perf_press[perf] + p_above)/2;
                avg_press[perf] = p_avg;
            }
        }

        const std::vector<int>& well_cells = wellOps().well_cells;

        // Use cell values for the temperature as the wells don't knows its temperature yet.
        const ADB perf_temp = subset(state.temperature, well_cells);

        // Compute b, rsmax, rvmax values for perforations.
        // Evaluate the properties using average well block pressures
        // and cell values for rs, rv, phase condition and temperature.
        const ADB avg_press_ad = ADB::constant(avg_press);
        std::vector<PhasePresence> perf_cond(nperf);
        for (int perf = 0; perf < nperf; ++perf) {
            perf_cond[perf] = (*phase_condition_)[well_cells[perf]];
        }

        const PhaseUsage& pu = fluid_->phaseUsage();
        DataBlock b(nperf, pu.num_phases);

        const Vector bw = fluid_->bWat(avg_press_ad, perf_temp, well_cells).value();
        if (pu.phase_used[BlackoilPhases::Aqua]) {
            b.col(pu.phase_pos[BlackoilPhases::Aqua]) = bw;
        }

        assert((*active_)[Oil]);
        assert((*active_)[Gas]);
        const ADB perf_rv = subset(state.rv, well_cells);
        const ADB perf_rs = subset(state.rs, well_cells);
        const Vector perf_so =  subset(state.saturation[pu.phase_pos[Oil]].value(), well_cells);
        if (pu.phase_used[BlackoilPhases::Liquid]) {
            const Vector bo = fluid_->bOil(avg_press_ad, perf_temp, perf_rs, perf_cond, well_cells).value();
            //const V bo_eff = subset(rq_[pu.phase_pos[Oil] ].b , well_cells).value();
            b.col(pu.phase_pos[BlackoilPhases::Liquid]) = bo;
            // const Vector rssat = fluidRsSat(avg_press, perf_so, well_cells);
            const Vector rssat = fluid_->rsSat(ADB::constant(avg_press), ADB::constant(perf_so), well_cells).value();
            rsmax_perf.assign(rssat.data(), rssat.data() + nperf);
        } else {
            rsmax_perf.assign(0.0, nperf);
        }
        V surf_dens_copy = superset(fluid_->surfaceDensity(0, well_cells), Span(nperf, pu.num_phases, 0), nperf*pu.num_phases);
        for (int phase = 1; phase < pu.num_phases; ++phase) {
            if ( phase == pu.phase_pos[BlackoilPhases::Vapour]) {
                continue; // the gas surface density is added after the solvent is accounted for.
            }
            surf_dens_copy += superset(fluid_->surfaceDensity(phase, well_cells), Span(nperf, pu.num_phases, phase), nperf*pu.num_phases);
        }

        if (pu.phase_used[BlackoilPhases::Vapour]) {
            // Unclear wether the effective or the pure values should be used for the wells
            // the current usage of unmodified properties values gives best match.
            //V bg_eff = subset(rq_[pu.phase_pos[Gas]].b,well_cells).value();
            Vector bg = fluid_->bGas(avg_press_ad, perf_temp, perf_rv, perf_cond, well_cells).value();
            Vector rhog = fluid_->surfaceDensity(pu.phase_pos[BlackoilPhases::Vapour], well_cells);
            // to handle solvent related
            if (has_solvent_) {

                const Vector bs = solvent_props_->bSolvent(avg_press_ad,well_cells).value();
                //const V bs_eff = subset(rq_[solvent_pos_].b,well_cells).value();

                // number of cells
                const int nc = state.pressure.size();

                const ADB zero = ADB::constant(Vector::Zero(nc));
                const ADB& ss = state.solvent_saturation;
                const ADB& sg = ((*active_)[ Gas ]
                                 ? state.saturation[ pu.phase_pos[ Gas ] ]
                                 : zero);

                Selector<double> zero_selector(ss.value() + sg.value(), Selector<double>::Zero);
                Vector F_solvent = subset(zero_selector.select(ss, ss / (ss + sg)),well_cells).value();

                Vector injectedSolventFraction = Eigen::Map<const Vector>(&xw.solventFraction()[0], nperf);

                Vector isProducer = Vector::Zero(nperf);
                Vector ones = Vector::Constant(nperf,1.0);
                for (int w = 0; w < nw; ++w) {
                    if(wells().type[w] == PRODUCER) {
                        for (int perf = wells().well_connpos[w]; perf < wells().well_connpos[w+1]; ++perf) {
                            isProducer[perf] = 1;
                        }
                    }
                }

                F_solvent = isProducer * F_solvent + (ones - isProducer) * injectedSolventFraction;

                bg = bg * (ones - F_solvent);
                bg = bg + F_solvent * bs;

                const Vector& rhos = solvent_props_->solventSurfaceDensity(well_cells);
                rhog = ( (ones - F_solvent) * rhog ) + (F_solvent * rhos);
            }
            b.col(pu.phase_pos[BlackoilPhases::Vapour]) = bg;
            surf_dens_copy += superset(rhog, Span(nperf, pu.num_phases, pu.phase_pos[BlackoilPhases::Vapour]), nperf*pu.num_phases);

            // const Vector rvsat = fluidRvSat(avg_press, perf_so, well_cells);
            const Vector rvsat = fluid_->rvSat(ADB::constant(avg_press), ADB::constant(perf_so), well_cells).value();
            rvmax_perf.assign(rvsat.data(), rvsat.data() + nperf);
        } else {
            rvmax_perf.assign(0.0, nperf);
        }

        // b and surf_dens_perf is row major, so can just copy data.
        b_perf.assign(b.data(), b.data() + nperf * pu.num_phases);
        surf_dens_perf.assign(surf_dens_copy.data(), surf_dens_copy.data() + nperf * pu.num_phases);
    }
size_t
wxPdfFontDataTrueType::WriteFontData(wxOutputStream* fontData, wxPdfSortedArrayInt* usedGlyphs, wxPdfChar2GlyphMap* subsetGlyphs)
{
  wxUnusedVar(subsetGlyphs);
  size_t fontSize1 = 0;
  bool compressed = false;
  wxFileName fileName;
  if (m_fontFileName.IsEmpty())
  {
    // Font data preprocessed by MakeFont
    compressed = m_file.Lower().Right(2) == wxT(".z");
    fileName = m_file;
    fileName.MakeAbsolute(m_path);
  }
  else
  {
    fileName = m_fontFileName;
  }

  // Open font file
  wxFileSystem fs;
  wxFSFile* fontFile = fs.OpenFile(wxFileSystem::FileNameToURL(fileName));
  wxInputStream* fontStream = NULL;
  if (fontFile)
  {
    fontStream = fontFile->GetStream();
  }
  else
  {
    // usually this should not happen since file accessability was already checked
    wxLogError(wxString(wxT("wxPdfFontDataTrueType::WriteFontData: ")) +
               wxString::Format(_("Font file '%s' not found."), fileName.GetFullPath().c_str()));
  }

  if (fontStream != NULL)
  {
    if (usedGlyphs != NULL)
    {
      if (compressed)
      {
        // Uncompress font file
        wxZlibInputStream zCompressed(*fontStream);
        wxMemoryOutputStream zUncompressed;
        zUncompressed.Write(zCompressed);
        zUncompressed.Close();
        fontStream = new wxMemoryInputStream(zUncompressed);
      }

      // Assemble subset
      wxPdfFontSubsetTrueType subset(fileName.GetFullPath(), m_fontIndex);
      wxMemoryOutputStream* subsetStream = subset.CreateSubset(fontStream, usedGlyphs, true);
      if (compressed)
      {
        delete fontStream;
      }

      // Write font subset data
      wxZlibOutputStream zFontData(*fontData);
      wxMemoryInputStream tmp(*subsetStream);
      fontSize1 = tmp.GetSize();
      zFontData.Write(tmp);
      zFontData.Close();
      delete subsetStream;
    }
    else
    {
      if (!compressed)
      {
        fontSize1 = fontStream->GetSize();
        wxZlibOutputStream zFontData(*fontData);
        zFontData.Write(*fontStream);
        zFontData.Close();
      }
      else
      {
        fontSize1 = GetSize1();
        fontData->Write(*fontStream);
      }
    }
  }

  if (fontFile != NULL)
  {
    delete fontFile;
  }

  return fontSize1;
}
void k_shell_snapshot(Graph& G, vector<int>& core, int core_num, string filename)
{
  srand(time(NULL));
  vector<int> keep_core;
  int size = num_vertices(G);
  //  long edgeCount = num_edges(G);
  vector<float> s(size,0);
  vector<float> p;
  vector<int> count(size,0);
  vector<int> indOrig(size,0);
  int ind;
  //float alpha = .2;
  //float eps   = .001;

  for(int i=0;i<core.size();i++)
    {
      if(core[i]==core_num)
	keep_core.push_back(i);
    }

  int r = 0;

  if(keep_core.size()>0)
    r = rand() % keep_core.size();
  else
    return;

  ind = keep_core[r];
  s[ind] = 1;
  /*
  p = approxPR(G,s,alpha,eps);

  for(int j=0; j<size; j++)
    {
      Vert v = vertex(j,G);
      count[j] = j;
      graph_traits<Graph>::degree_size_type outDegree = out_degree(v,G);
      p[j] = p[j]/outDegree;
    }
  

  sort(count.begin(),count.end(),compareInd<vector<float>&>(p));

  for(int j=0;j<size;j++)
    indOrig[count[j]] = j;

  long vol = 0;
  long out = 0;
  int maxC = 200;


  float c = 1.0;
  int cutInd = 0;
  for(int j=0; j<maxC; j++)
    {
      //   cout<<"Comm: "<<j<<"\n";
      vector<int>::iterator it;
	   
      Vert v    = vertex(count[j],G);
      //  cout<<"index: "<<index<<"\n";

      //Out edge iterators
      graph_traits<Graph>::out_edge_iterator out_i, out_e;

      //Create index map for Graph
      property_map<Graph, vertex_index_t>::type index = get(vertex_index, G);

      //Count outgoing edges for v
      graph_traits<Graph>::degree_size_type outDegree = out_degree(v,G);

      //update edges leaving cut set (out)
      out += outDegree;
      //update internal volume of cut set (vol)
      vol += outDegree;

      //Iterate over out going edges of v
      for(tie(out_i,out_e)=out_edges(v,G);out_i!=out_e;++out_i)
	{
	  Edge e = *out_i;
	  //	cout<<"node: "<<node1<<"\n";

	  Vert vt = target(e,G);

	  //Check if edge crosses set boundary, if so, update out and vol accordingly
	  if(indOrig[index[vt]]<j && indOrig[index[vt]]>=0)
	    {
	      out -= 2;  //note that 2 is due to outgoing/incoming edge as G is a directed graph representation of an undirected graph.
	      vol--;
	    }
	}
      //cout<<edgeCount<<"\n";
	
      //Pick minimum of cut set and complement volume
      if(vol>(edgeCount-vol))
	vol = edgeCount - vol;
      // cout<<"Comm size "<<j<<": "<<ctime2-ctime1<<"\n";
	    
	    
      //conductance c is now given by: c = out/vol
      float tempC = float(out)/vol;
	    
      //Check if this beats previous minimum
      if(tempC<c)
	{
	  c = tempC;
	  cutInd = j;
	}
    }

for(int j=0;j<=cutInd;j++)
    S.push_back(vertex(count[j],G));
  */
  vector<Vert> S;

  for(int j=0;j<=core.size();j++)
    {
      if(core[j]==core_num)
	S.push_back(vertex(j,G));
    }
  Graph localG = subset(G,S);
  //localG = connected(localG,-1);

  adjacency_list<vecS, vecS, undirectedS> localUGraph;

  copy_graph(localG,localUGraph);

  ofstream outViz;
  
  outViz.open(filename.c_str());


  write_graphviz(outViz,localUGraph);
  outViz.close();
}
Exemple #7
0
SkCodec::Result SkCodec::getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes,
                                   const Options* options, SkPMColor ctable[], int* ctableCount) {
    if (kUnknown_SkColorType == info.colorType()) {
        return kInvalidConversion;
    }
    if (nullptr == pixels) {
        return kInvalidParameters;
    }
    if (rowBytes < info.minRowBytes()) {
        return kInvalidParameters;
    }

    if (kIndex_8_SkColorType == info.colorType()) {
        if (nullptr == ctable || nullptr == ctableCount) {
            return kInvalidParameters;
        }
    } else {
        if (ctableCount) {
            *ctableCount = 0;
        }
        ctableCount = nullptr;
        ctable = nullptr;
    }

    if (!this->rewindIfNeeded()) {
        return kCouldNotRewind;
    }

    // Default options.
    Options optsStorage;
    if (nullptr == options) {
        options = &optsStorage;
    } else if (options->fSubset) {
        SkIRect subset(*options->fSubset);
        if (!this->onGetValidSubset(&subset) || subset != *options->fSubset) {
            // FIXME: How to differentiate between not supporting subset at all
            // and not supporting this particular subset?
            return kUnimplemented;
        }
    }

    // FIXME: Support subsets somehow? Note that this works for SkWebpCodec
    // because it supports arbitrary scaling/subset combinations.
    if (!this->dimensionsSupported(info.dimensions())) {
        return kInvalidScale;
    }

    // On an incomplete decode, the subclass will specify the number of scanlines that it decoded
    // successfully.
    int rowsDecoded = 0;
    const Result result = this->onGetPixels(info, pixels, rowBytes, *options, ctable, ctableCount,
            &rowsDecoded);

    if ((kIncompleteInput == result || kSuccess == result) && ctableCount) {
        SkASSERT(*ctableCount >= 0 && *ctableCount <= 256);
    }

    // A return value of kIncompleteInput indicates a truncated image stream.
    // In this case, we will fill any uninitialized memory with a default value.
    // Some subclasses will take care of filling any uninitialized memory on
    // their own.  They indicate that all of the memory has been filled by
    // setting rowsDecoded equal to the height.
    if (kIncompleteInput == result && rowsDecoded != info.height()) {
        this->fillIncompleteImage(info, pixels, rowBytes, options->fZeroInitialized, info.height(),
                rowsDecoded);
    }

    return result;
}
Exemple #8
0
int main()
{
	int m, head, tail;
	char *result, judge[10]="";
	
	scanf("%d\n",&m);
	
	while(m-- > 0)
	{
		fgets(judge,10,stdin);
		
		now = 1;
		news[0][0] = 1;
		
		while(news[now-1][0] != 0)
		{
			fgets(news[now],40,stdin);
			news[now][strlen(news[now])-1] = 0;
			now++;
		}
		
		now--;
		
		if(judge[0] == '*')
		{
			for(int i = 1; i < now; i++)
			{
				printf("Size %d\n", i);
				subset(1, 0, i);
				printf("\n");
			}
		}
		else if(strlen(judge) < 4)
		{
			head = atoi(judge);
			printf("Size %d\n", head);
			subset(1,0,head);
			printf("\n");
		}
		else
		{
			head = atoi(judge);
			result = strtok(judge," ");
			result = strtok(NULL," ");
			tail = atoi(result);
			
			for(int i = head; i <= tail; i++)
			{
				printf("Size %d\n",i);
				subset(1,0,i);
				printf("\n");
			}
		}
		
		if(m != 0) printf("\n");
		
		memset(news, 0, sizeof(news));
		memset(mark, 0, sizeof(mark));
		memset(ans,  0, sizeof(ans));
	}
	
	return 0;
}
std::vector<std::vector<cv::Point2f> > OutlierDetector::fitSubspace(const std::vector<std::vector<cv::Point2f> > &trajectories, std::vector<cv::Point2f> &outlier_points, int num_motions, double sigma)
{
    bool print = false;
    int subspace_dimensions = trajectories[0].size() * 2; // n
    int num_trajectories = trajectories.size();
    // each column in data represents one trajectory
    // even rows are x coordinates, odd rows are y coordinates
    Eigen::MatrixXf data(subspace_dimensions, num_trajectories);
    if (print) std::cout << "fill matrix " << std::endl;
    fillMatrix(trajectories, data);
    if (print) std::cout << "mean subtract " << std::endl;
    meanSubtract(data);

    int num_sample_points = 4 * num_motions; // d
    int num_iterations = 50;
    
    Eigen::VectorXf final_residual;
    std::vector<int> final_columns;
    int max_points = 0;

    if (print) std::cout << " start iterations " << std::endl;
    for (int i = 0; i < num_iterations; i++)
    {
        Eigen::MatrixXf subset(subspace_dimensions, num_sample_points); 
        if (print) std::cout << "file subset " << std::endl;
        std::vector<int> column_indices;
        column_indices = fillSubset(data, subset, num_sample_points);

        if (print) std::cout << "svd calculation " << std::endl;
//        Eigen::JacobiSVD<Eigen::MatrixXf> svd(subset, Eigen::ComputeFullU | Eigen::ComputeFullV);
        Eigen::JacobiSVD<Eigen::MatrixXf, Eigen::FullPivHouseholderQRPreconditioner> svd(subset,  Eigen::ComputeFullU | Eigen::ComputeFullV);

        if (print) std::cout << "init Pnd " << std::endl;
        Eigen::MatrixXf Pnd = Eigen::MatrixXf::Zero(subspace_dimensions, subspace_dimensions);
        //std::cout << "U" << std::endl;
        //std::cout << svd.matrixU() << std::endl;
        //std::cout << svd.singularValues() << std::endl;
        
        if (print) std::cout << "calc M " << std::endl;
        for (int idx = 0; idx < num_sample_points; idx++)
        {
            Eigen::VectorXf u = svd.matrixU().col(idx);
            Eigen::MatrixXf M = u*u.transpose();
            Pnd = Pnd + M;
        }
        if (print) std::cout << "calc Pnd " << std::endl;
        Pnd = Eigen::MatrixXf::Identity(subspace_dimensions, subspace_dimensions) - Pnd;

        Eigen::MatrixXf data_T = data.transpose();
        if (print) std::cout << "calc residual " << std::endl;
        Eigen::VectorXf residual = (data_T * (Pnd * data)).diagonal();
        if (print) std::cout << "residual : " << std::endl;
        if (print) std::cout << residual << std::endl;
        residual = residual.cwiseAbs();
        int num_points = 0;
        for (int idx = 0; idx < residual.size(); idx++)
        {
            if (print) std::cout << "threshold " << (subspace_dimensions - num_sample_points) * sigma * sigma << std::endl;
            if (residual(idx) < (subspace_dimensions - num_sample_points) * sigma * sigma)
            {
                if (print) std::cout << "adding  " << std::endl;
                num_points++;
            }
        }
        if (num_points > max_points)
        {
            if (print) std::cout << num_points << " to " << max_points << std::endl;
            if (print) std::cout << "copy residual" << residual << std::endl;
            max_points = num_points;
            final_residual = residual;
            final_columns = column_indices;
            if (print) std::cout << "copy final residual " << final_residual << std::endl;
        }
    }
    if (print) std::cout << "final residual " << std::endl;
    if (print) std::cout << final_residual << std::endl;
    double residual_threshold = 0.2;
    if (subspace_dimensions - num_sample_points < 11 && subspace_dimensions - num_sample_points > 0)
    {
        residual_threshold = sigma * sigma * chi_square_table.at(0).at(subspace_dimensions - num_sample_points);
        std::cout << "residual threshold: " << residual_threshold << std::endl;
    }
    for (int idx = 0; idx < final_residual.size(); idx++)
    {
        if (final_residual(idx) > residual_threshold)
        {
            outlier_points.push_back(trajectories.at(idx).at(trajectories.at(idx).size() - 2));
        }
    }
    std::vector<std::vector<cv::Point2f> > trajectory_subspace_vectors;
    for (int i = 0; i < final_columns.size(); i++)
    {
        trajectory_subspace_vectors.push_back(trajectories.at(final_columns.at(i)));
    }
    return trajectory_subspace_vectors;
}
Exemple #10
0
void  FluxBC::
applyBoundaryCondition( realCompositeGridFunction &q,
			int ic) 
{
  assert( pCg     != NULL ); CompositeGrid &cg          = *pCg;
  assert( pInterp != NULL ); Interpolant   &interp      = *pInterp;
  assert( pOp     != NULL ); CompositeGridOperators &op = *pOp;

  Display display; //David's display class

  realArray &qTemp = q[0];
  const int nComponents         = qTemp.getLength(3); // indices ( 0, 1, 2, --3-- ), 3=component
  const int nInterpComponents   =valuesInterpolate.getLength(1);
  assert( nComponents <= nInterpComponents );
  if(debug&4)printf("***FluxBC::applyBC: nComponents %d, nInterpComponents %d, fluxCoeff %g\n",
		    nComponents, nInterpComponents,  getFluxCoefficient());

  //printf("FluxBC::applyBoundaryCondition called...\n");

  timerInterpCode = getCPU();
  interpolator.interpolatePoints(q,valuesInterpolate);

  if(debug&8) {
    printf("-------------------DISPLAY: valuesInterpolate in FluxBC::applyBoundaryCondition %d  -------\n",
	   ic);
    display.display(valuesInterpolate,"valuesInterpolate");
  }

  for ( int ig=0; ig< cg.numberOfComponentGrids(); ++ig ) {
    MappedGrid & mg = cg[ig];
    MappedGridOperators    &opmg = op[ig];
    realMappedGridFunction &q_mg = q[ig];
    Index Ib1,Ib2,Ib3;
    Index Ig1,Ig2,Ig3;

    Index I1,I2,I3;
    getIndex( mg.dimension(), I1,I2,I3);
    
    //..flux/jump bc
    const int nAxes=cg.numberOfDimensions();
    int axis, side;
    for( axis=0; axis<mg.numberOfDimensions(); axis++ ) {
      for( side=0; side<=1; side++ ) {
	
	if( mg.boundaryCondition()(side,axis) == idFluxBoundary  ) {

	  //printf("FluxBC: grid, side, axis(%i,%i,%i) is a flux boundary (bc=%i)\n",
	  //        ig,side,axis,idFluxBoundary);
	  getBoundaryIndex(mg.gridIndexRange(),side,axis,Ib1,Ib2,Ib3);
	  getGhostIndex(mg.gridIndexRange(),side,axis,Ig1,Ig2,Ig3);
	  realArray       &qArray     = q[ig];

	  int nInterpPoints= edgeEnd(ig,axis,side) - edgeStart(ig,axis,side)+1;
	  Range dims(0,nAxes-1);
	  //Range subset(edgeStart(ig,axis,side,edgeEnd(ig, axis,side)));
	  Range subset(edgeStart(ig,axis,side),edgeEnd(ig, axis,side));

	  realArray jump(nInterpPoints);
	  jump.reshape(subset);

	  jump(subset) = valuesInterpolate(subset,ic);
	  jump.reshape(Ib1,Ib2,Ib3, Range(ic,ic));

	  if(debug&8) {
	    printf("..grid %d, side %d, axis %d, component %d, flux coeff %g-- JUMP\n", 
		   ig, side, axis, ic, getFluxCoefficient() );
	    display.display(jump,"jump: values for other grids");
	  }
	  jump = getFluxCoefficient()*( jump - qArray(Ib1,Ib2,Ib3,ic));

	  //if(debug&8  || (ic==1)) {
	  if(debug&8) {
	    printf("....Flux*[ jump ]\n");
	    display.display( jump, "flux coeff*[ other - this value]" );
	  }

	  //.. ibc chosen to set a specified boundary (side,axis)
	  // ... take jumps from unext --> impose as flux in u
	  const int ibc=BCTypes::boundary1+side+2*axis;
	  opmg.applyBoundaryCondition( q_mg, Range(ic,ic), BCTypes::neumann, ibc, jump ); 

	  if(debug&8)  display.display(jump,   "jump");
	  if(debug&16) display.display(qArray(I1,I2,I3,ic), "q function");

	} // end if ibc==fluxBoundaryID


      } 
    }
  }
  timerInterpCode = getCPU()-timerInterpCode;

}
Exemple #11
0
void  FluxBC::
setupInterpolation(const int numberOfOutputComponents /*=1 */)
  // sets up interpolation of bc id = idFluxBoundary
{
  //printf("FluxBC::applyBoundaryCondition called...\n");

  assert( pCg     != NULL ); CompositeGrid &cg          = *pCg;
  assert( pInterp != NULL ); Interpolant   &interp      = *pInterp;
  assert( pOp     != NULL ); CompositeGridOperators &op = *pOp;

  printf("***FluxBC::setupInterpolation: numComponents %d\n",
	 numberOfOutputComponents);

  //..interpolate in a two step process: 
  //   Collect data:
  //    *Step 1: setupInterpolation:
  //    (1) allocate the start/stop index arrays [ngrids][naxis][nsides]
  //    (2) loop through grids/edges; compute # points & collect xyz
  //    (3) form long xyzInterp array & set pointers to it

  //    *Step 2: applyBoundaryCondition -- see the next subroutine
  
  timerInterpSetupCode = getCPU();

  const int nGrids= cg.numberOfComponentGrids(); //shorthand
  const int nAxes = cg.numberOfDimensions();
  const int nSides= 2;

  // (1) allocate 
  edgeStart.redim(nGrids,nAxes,nSides);
  edgeEnd.redim(nGrids,nAxes,nSides);
  isInterpolatedEdge.redim(nGrids,nAxes,nSides);
  edgeCoords.redim(nGrids,nAxes,nSides);
  int totalNumberOfInterpolationPoints=0; //local counter, global count in xyzInterpolate

#define checkdim(X,n0,n1,n2) ( (n0<=X.size(0)) && (n1<=X.size(1)) && (n2<=X.size(2)))


  // (2) collect local xyz edge coordinates
  for ( int ig=0; ig< cg.numberOfComponentGrids(); ++ig ) {
    MappedGrid & mg = cg[ig];
    
    Index Ib1,Ib2,Ib3;
    Index Ig1,Ig2,Ig3;
    Index All;
    
    for( int axis=0; axis<mg.numberOfDimensions(); axis++ ) {
      for( int side=0; side<=1; side++ ) {
	edgeStart(ig,axis,side) = -1;
	edgeEnd(ig,axis,side)   = -1;

	isInterpolatedEdge(ig, axis,side) = false;
	if( mg.boundaryCondition()(side,axis) == idFluxBoundary  ) {
	  isInterpolatedEdge(ig,axis,side) = true;
	  getBoundaryIndex(mg.gridIndexRange(),side,axis,Ib1,Ib2,Ib3);
	  //getGhostIndex(mg.gridIndexRange(),side,axis,Ig1,Ig2,Ig3);
	  //const realArray &zz=mg.vertex();
	  int zaxis        =axis3;
	  if (nAxes==2) zaxis=axis2; // to make sure we don't seg.fault
	  const realArray &xb  = mg.vertex()(Ib1,Ib2,Ib3, axis1);
	  const realArray &yb  = mg.vertex()(Ib1,Ib2,Ib3, axis2);
	  const realArray &zb  = mg.vertex()(Ib1,Ib2,Ib3, zaxis);
	  
	  int axisLength[3]={xb.getLength(axis1),xb.getLength(axis2),xb.getLength(axis3)};
	  int nInterpPoints= axisLength[axis1]*axisLength[axis2];
	  if (cg.numberOfDimensions()==3) nInterpPoints = nInterpPoints* axisLength[axis3];
	  
	  //realArray xyInt( Ib1,Ib2,Ib3, nAxes );
	  edgeCoords(ig,axis,side).redim( Ib1,Ib2,Ib3, nAxes );
	  realArray &xyz = edgeCoords(ig,axis,side); //shorthand
	  xyz(All, All, All, axis1) = xb;
	  xyz(All, All, All, axis2) = yb;
	  if( nAxes == 3) {
	    xyz(All, All, All, axis3) = zb;
	  }
	  xyz.reshape(nInterpPoints, nAxes);
	  totalNumberOfInterpolationPoints += nInterpPoints;

	  //printf("..On (grid %d, axis %d,side %d); ",  ig,axis,side);
	  //printf("passing in xyz array of dimensions [%d, %d], ntotal=%d\n",
	  //	 edgeCoords(ig,axis,side).getLength(0), 
	  //	 edgeCoords(ig,axis,side).getLength(1), totalNumberOfInterpolationPoints);
	} // end if ibc==fluxBoundaryID
      }// end for side
    }//end for axis
  }//end for ig

  // (3) form long xyzInterp array & set start/end indices
  xyzInterpolate.redim(totalNumberOfInterpolationPoints, nAxes );
  //const int nComponents=1; //set bcs one component at a time for now.
  valuesInterpolate.redim(totalNumberOfInterpolationPoints, 
			  numberOfOutputComponents );
  valuesInterpolate=-981.;
  ignoreGrid.redim(totalNumberOfInterpolationPoints);
  xyzInterpolate=-99;
  ignoreGrid=-1;
  int iNextStart=0;
  for (int ig=0; ig< nGrids; ++ig ) {
    for( int axis=0; axis<nAxes; ++axis ) {
      for( int side=0; side<nSides; ++side ) {
	if( isInterpolatedEdge(ig,axis,side) ) {
	  //printf("--grid %3d, axis %d, side %d:\n", ig,axis,side);
	  realArray &xyz          = edgeCoords(ig,axis,side); //shorthand
	  const int nInterpPoints = xyz.getLength(0);	  
	  const int iThisEnd      = iNextStart+nInterpPoints-1;
	  edgeStart(ig,axis,side) = iNextStart;
	  edgeEnd(ig,axis,side)   = iThisEnd;

	  Range dims(0,nAxes-1);
	  Range subset(iNextStart,iThisEnd);

#if 0  //debug
	  std::string namexyz=          "xyz              ";
	  std::string namexyzreshape=   "xyz reshaped     ";
	  std::string namexyzInterp=    "xyzInterpolate   ";
	  std::string namexyzInterpSub= "xyzInterp(sub)   ";
	  std::string subsetname=       "range subset     ";
	  std::string dimsname=         "range dims       ";
	  printBaseBound(namexyz, xyz);
	  printBaseBound(subsetname, subset);
	  printBaseBound(dimsname, dims);
#endif
	  xyz.reshape(subset,dims);

#if 0 //debug
	  printBaseBound(namexyzreshape, xyz);
	  printBaseBound(namexyzInterp, xyzInterpolate);fflush(0);
	  printBaseBound(namexyzInterpSub, xyzInterpolate(subset,dims));fflush(0);
#endif

	  xyzInterpolate(subset, dims) = xyz;  //interp. points for this edge
	  ignoreGrid(subset)           = ig;   //do not interp 'xyz' from grid =ig

	  iNextStart += nInterpPoints;
	}
      }
    }
  }
  interpolator. buildInterpolationInfo(  xyzInterpolate, cg, ignoreGrid );
  timerInterpSetupCode = getCPU() - timerInterpSetupCode;

  //..CHECK -- if some 'ignoreGrid(index)' items were not set==> skipped some = problem
  printf("Checking 'ignoreGrid'...\n");
  bool igok=true;
  for(int i=0; i<totalNumberOfInterpolationPoints; ++i ) {
    int ig=ignoreGrid(i);
    if( ig<0 ) {
      printf("..bug: ignoreGrid[%5d] = %3d\n", i, ig);
      igok=false;
    }
  }	 
  printf("--> ignoreGrid is "); 
  if( igok ) printf("OK\n");    //covered all items
  else       printf("NOT OK\n");//skipped some=problem

}
Exemple #12
0
Query* Project::transform()
	{
	bool moved = false;
	// remove projects of all fields
	if (flds == source->columns())
		return source->transform();
	// combine projects
	if (Project* p = dynamic_cast<Project*>(source))
		{
		flds = intersect(flds, p->flds);
		source = p->source;
		return transform();
		}
	// move projects before renames, renaming
	else if (Rename* r = dynamic_cast<Rename*>(source))
		{
		// remove renames not in project
		Fields new_from;
		Fields new_to;
		Fields f = r->from;
		Fields t = r->to;
		for (; ! nil(f); ++f, ++t)
			if (member(flds, *t))
				{
				new_from.push(*f);
				new_to.push(*t);
				}
		r->from = new_from.reverse();
		r->to = new_to.reverse();

		// rename fields
		Fields new_fields;
		f = flds;
		int i;
		for (; ! nil(f); ++f)
			if (-1 == (i = search(r->to, *f)))
				new_fields.push(*f);
			else
				new_fields.push(r->from[i]);
		flds = new_fields.reverse();

		source = r->source;
		r->source = this;
		return r->transform();
		}
	// move projects before extends
	else if (Extend* e = dynamic_cast<Extend*>(source))
		{
		// remove portions of extend not included in project
		Fields new_flds;
		Lisp<Expr*> new_exprs;
		Lisp<Expr*> ex = e->exprs;
		for (Fields f = e->flds; ! nil(f); ++f, ++ex)
			if (member(flds, *f))
				{
				new_flds.push(*f);
				new_exprs.push(*ex);
				}
		Fields orig_flds = e->flds;
		e->flds = new_flds;
		Lisp<Expr*> orig_exprs = e->exprs;
		e->exprs = new_exprs;

		// project must include all fields required by extend
		// there must be no rules left
		// since we don't know what fields are required by rules
		if (! e->has_rules())
			{
			Fields eflds;
			for (ex = e->exprs; ! nil(ex); ++ex)
				eflds = set_union(eflds, (*ex)->fields());
			if (subset(flds, eflds))
				{
				// remove extend fields from project
				Fields new_fields;
				for (Fields f = flds; ! nil(f); ++f)
					if (! member(e->flds, *f))
						new_fields.push(*f);
				flds = new_fields.reverse();

				source = e->source;
				e->source = this;
				e->init();
				return e->transform();
				}
			}
		e->flds = orig_flds;
		e->exprs = orig_exprs;
		}
	// distribute project over union/intersect (NOT difference)
	else if (dynamic_cast<Difference*>(source))
		{
		}
	else if (Compatible* c = dynamic_cast<Compatible*>(source))
		{
		if (c->disjoint != "" && ! member(flds, c->disjoint))
			{
			Fields flds2 = flds.copy().push(c->disjoint);
			c->source = new Project(c->source,
				intersect(flds2, c->source->columns()));
			c->source2 = new Project(c->source2,
				intersect(flds2, c->source2->columns()));
			}
		else
			{
			c->source = new Project(c->source,
				intersect(flds, c->source->columns()));
			c->source2 = new Project(c->source2,
				intersect(flds, c->source2->columns()));
			return source->transform();
			}
		}
	// split project over product/join
	else if (Product* x = dynamic_cast<Product*>(source))
		{
		x->source = new Project(x->source,
			intersect(flds, x->source->columns()));
		x->source2 = new Project(x->source2,
			intersect(flds, x->source2->columns()));
		moved = true;
		}
	else if (Join* j = dynamic_cast<Join*>(source))
		{
		if (subset(flds, j->joincols))
			{
			j->source = new Project(j->source,
				intersect(flds, j->source->columns()));
			j->source2 = new Project(j->source2,
				intersect(flds, j->source2->columns()));
			moved = true;
			}
		}
	source = source->transform();
	return moved ? source : this;
	}
Exemple #13
0
 static constexpr auto apply(Xs xs, Ys ys)
 { return and_(subset(xs, ys), subset(ys, xs)); }
Exemple #14
0
int find_opt_du_copy(struct DotList *dots, int num_lines, int id, struct perm_pt *st, struct kdnode *tree, int size, int w_sid, int w_fid, int h_sid, int h_fid, int *cid, bool *x_ins, bool *f_is_x, int *t_ins, FILE *fp, struct DotList *init_dots)
{
	int i;
	int min_score = 1000;
	int max_id = -1;
	bool *is_x;
	int *sd;
	int d;
	struct gap_list gps;
	int temp_score;
	int y_cur, y_old;
	struct I temp;
	int closeness;
	int start, mid1 = -1, mid2 = -1, end;
	int len1, len2, len;
	int opt_cid;
	int op_len = 0, op_len_x, op_len_y;
	int m_th;
	int from = 0, to = 1;

	is_x = (bool *) ckalloc(sizeof(bool));
	sd = (int *) ckalloc(sizeof(int));

	if( w_sid < h_sid )
	{
		start = w_sid;
		if( w_fid < h_sid )
		{
			mid1 = w_fid;
			mid2 = h_sid;
			end = h_fid;
		}
		else 
		{
			if( w_fid < h_fid ) end = h_fid;
			else end = w_fid;
		}
	}
	else 
	{
		start = h_sid;
		if( h_fid < w_sid )
		{
			mid1 = h_fid;
			mid2 = w_sid;
			end = w_fid;
		}
		else
		{
			if( h_fid < w_fid ) end = w_fid;
			else end = h_fid;
		}
	}

	for( i = start; i <= end; i++ )
	{
		if( (mid1 != -1) && (i > mid1) && (i < mid2)) {}
		else
		{
			if( st[i].id == id ) {}
			else if( dots[st[i].id].sign == 2) {}
			else if( dots[st[i].id].x.lower > dots[id].x.lower ) {}
			else if( dots[st[i].id].ctg_id1 != dots[id].ctg_id1 ) {}
			else if( dots[st[i].id].ctg_id2 != dots[id].ctg_id2 ) {}
			else if( (dots[st[i].id].sign == 0) && (dots[st[i].id].y.lower > dots[id].y.lower )) {}
			else if( (dots[st[i].id].sign == 1) && (dots[st[i].id].y.lower < dots[id].y.lower )) {}
			else if( subset(dots[st[i].id].m_x, dots[id].x) || subset(dots[st[i].id].m_y, dots[id].y) || subset(dots[id].m_x, dots[st[i].id].x) || subset(dots[id].m_y, dots[st[i].id].y) ) {}
			else if( ((dots[st[i].id].pair_self == SELF) && (is_tandem(dots[st[i].id]) == true)) && ((dots[id].pair_self == SELF) && (is_tandem(dots[id]) == true))) {}
			else 
			{
				if((dots[st[i].id].sign != 2) && (dots[st[i].id].sign == dots[id].sign) && (dots[st[i].id].sp_id == dots[id].sp_id) && ((d = distance(dots, st[i].id, id, is_x, sd)) <= MDIS_THRESHOLD))
				{
					len1 = width(dots[st[i].id].x);
					len2 = width(dots[id].x);

					if( len1 > len2 ) len = len2;
					else len = len1;

					if( (len1 >= LG_TH) && (len2 >= LG_TH)) m_th = L_M_TH;
					else m_th = M_TH;

					if((*sd) <= len) 
					{
						op_len = 0;
						op_len_x = 0;
						op_len_y = 0;

						if( proper_overlap(dots[st[i].id].x, dots[id].x) == true )
						{
							op_len_x = width(intersect(dots[st[i].id].x, dots[id].x));
							op_len = op_len_x;
						}

						if( proper_overlap(dots[st[i].id].y, dots[id].y) == true )
						{
							op_len_y = width(intersect(dots[st[i].id].y, dots[id].y));
							if( op_len < op_len_y )
							{
								op_len = op_len_y;
							}
						}

						if( ((*sd) > m_th) || (op_len > m_th) )
						{
							if( (strict_almost_equal(dots[st[i].id].x, dots[id].x) == true) || (strict_almost_equal(dots[st[i].id].y, dots[id].y) == true ) ) gps.type = -1;
//            	else if( ((*sd) > m_th) && (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true )) {
            	else if( (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true ) && (tandem_exist(dots, st, tree, size, st[i].id, id) == false)) { 
              	gps.type = -1;            
							}
							else if( (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true) ) 
							{
          	    temp = intersect(dots[st[i].id].x, dots[id].x);
           	  	if( dots[id].sign == 0 ) {
									y_cur = init_dots[dots[id].index].y.lower + init_dots[dots[id].index].yl_diff;
             	  	y_old = find_yloc_one_ch(init_dots, dots[st[i].id], fp, width(temp), NO_GAP_INC);
									if( y_old == -1 ) {
										y_cur = dots[id].y.lower;
										y_old = dots[st[i].id].y.upper - width(temp);
									}
              	}
              	else if( dots[id].sign == 1 ) {
									y_old = init_dots[dots[id].index].y.upper - init_dots[dots[id].index].yr_diff;
                	y_cur = find_yloc_one_ch(init_dots, dots[st[i].id], fp, width(temp), NO_GAP_INC);
									if( y_cur == -1 ) {
										y_old = dots[id].y.upper;
										y_cur = dots[st[i].id].y.lower + width(temp);
									}
              	}

              	if( y_old >= y_cur ) {
									gps = define_gap_new_type(dots, st[i].id, id, false);
									if( gps.type == -1 ) gps = define_gap_new_type(dots, st[i].id, id, true);
								}
              	else {
									gps = define_gap_new_type(dots, st[i].id, id, true);
									if( gps.type == -1 ) gps = define_gap_new_type(dots, st[i].id, id, false);
								}				
							}
							else if( proper_overlap(dots[st[i].id].x, dots[id].x) == true ) 
							{
								gps = define_gap_new_type(dots, st[i].id, id, true);
							}
							else if( proper_overlap(dots[st[i].id].y, dots[id].y) == true ) 
							{
								gps = define_gap_new_type(dots, st[i].id, id, false);
							}
							else gps.type = -1;
						}
						else if( ((closeness = compute_closeness(dots, st[i].id, id)) > C_OP_TH) && (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true ))          
						{            
							if( ((subset(dots[st[i].id].x, dots[id].x) == true) || (subset(dots[id].x, dots[st[i].id].x) == true)) || ((subset(dots[st[i].id].y, dots[id].y) == true) || (subset(dots[id].y, dots[st[i].id].y) == true)) ) {
								gps.type = -1;
							}
							else {
								temp = intersect(dots[id].x, dots[st[i].id].x);
								if( dots[id].sign == 0 ) {              
									y_cur = init_dots[dots[id].index].y.lower + init_dots[dots[id].index].yl_diff;
									y_old = find_yloc_one_ch(init_dots, dots[st[i].id], fp, width(temp), NO_GAP_INC);            

									if( y_old == -1 ) {
										y_cur = dots[id].y.lower;
										y_old = dots[st[i].id].y.upper - width(temp);
									}
								}            
								else if( dots[id].sign == 1 ) {              
									y_cur = find_yloc_one_ch(init_dots, dots[st[i].id], fp, width(temp), NO_GAP_INC);              
									y_old = init_dots[dots[id].index].y.upper - init_dots[dots[id].index].yr_diff;
									if( y_cur == -1 ) {
										y_old = dots[id].y.upper;
										y_cur = dots[st[i].id].y.lower + width(temp);
									}
								}            
								else gps.type = -1;

								if( (dots[id].sign == 0) || (dots[id].sign == 1) ) {
									if( y_old >= y_cur ) gps = define_gap_new_type(dots, st[i].id, id, false);            
									else gps = define_gap_new_type(dots, st[i].id, id, true);          
 							
									if( debug_mode == TRUE ) printf("Gap: %d-%d, %d-%d\n", dots[st[i].id].x.lower, dots[st[i].id].x.upper, dots[st[i].id].y.lower, dots[st[i].id].y.upper);
								}
							}
						}          
						else if( (check_candi(dots, id, st[i].id, CHECK_INS_DUP) == false) && ( (*sd) > TD_TH)) gps.type = -1;          
						else          
						{            
							if( (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true ) ) 
							{              
								gps.type = -1;	
							}            
							else if( proper_overlap(dots[st[i].id].x, dots[id].x) == true )  
							{              
								gps = define_gap_new_type(dots, st[i].id, id, true);            
							}            
							else if( proper_overlap(dots[st[i].id].y, dots[id].y) == true )            
							{              
								gps = define_gap_new_type(dots, st[i].id, id, false);            
							}
							else gps = define_gap(dots, st[i].id, id, d, *sd, *is_x);
						}
					}
					else gps.type = -1;

					if((gps.type == -1) || (gps.type == 3) || (gps.type == 0))
					{
					}
					else
					{
						gps.gid = 0;

						temp_score = get_score_copy(dots, num_lines, gps, cid, x_ins);
						if( temp_score != -1 )
						{
							if( check_whole_regions_inclusion(dots, num_lines, *cid, st[i].id, id, *x_ins) == true )
							{
								temp_score = -1;	
							}			
						}

						if( (temp_score == -1) && (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true) && ((gps.type == 21) || (gps.type == 22) ) ) {
							from = gps.y1;
							to = gps.y2;
							gps.y1 = from - abs(to - from);
							gps.y2 = from;
							temp_score = get_score_copy(dots, num_lines, gps, cid, x_ins);
							if( temp_score != -1 )
							{
								if( check_whole_regions_inclusion(dots, num_lines, *cid, st[i].id, id, *x_ins) == true )
								{
									temp_score = -1;	
								}			
							}

							if( temp_score == -1 ) {
								gps.y1 = from - abs(to-from)/2;
								gps.y2 = from + abs(to-from)/2;
								temp_score = get_score_copy(dots, num_lines, gps, cid, x_ins);
								if( temp_score != -1 )
								{
									if( check_whole_regions_inclusion(dots, num_lines, *cid, st[i].id, id, *x_ins) == true )
									{
										temp_score = -1;	
									}			
								}
							}
						}

						if( temp_score == -1 ) {
							if( (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true) ) {
								if( (gps.type == 21) || (gps.type == 22) ){
									if( gps.type == 21 ) {
										gps = define_gap_new_type(dots, st[i].id, id, false);
									}
									else if( gps.type == 22 ) {
										gps = define_gap_new_type(dots, st[i].id, id, true);
									}

									if((gps.type == -1) || (gps.type == 3) || (gps.type == 0)) {}
									else {
										gps.gid = 0;
										temp_score = get_score_copy(dots, num_lines, gps, cid, x_ins);
										if( temp_score != -1 )
										{
											if( check_whole_regions_inclusion(dots, num_lines, *cid, st[i].id, id, *x_ins) == true )
											{
												temp_score = -1;	
											}			
										}
									}
								}
							}
						}

						if( temp_score != -1 )
						{
							if( min_score > temp_score )
							{
								min_score = temp_score;
								max_id = st[i].id;
								opt_cid = *cid;
								
								if( gps.type == 1 )
								{
									*f_is_x = false;
								}
								else if( gps.type == 2 )
								{
									*f_is_x = true;
								}

								if( (gps.type == 11) || (gps.type == 21) )
								{
									*f_is_x = false;
									*t_ins = gps.type;
								}
								else if( (gps.type == 12) || (gps.type == 22) )
								{
									*f_is_x = true;
									*t_ins = gps.type;
								}
								else
								{
									*t_ins = -1;
								}
							}
						}
					}
				}
			}
		}
	}

	free(sd);
	free(is_x);

	if( max_id == -1 ) return(-1);
	else 
	{
		*cid = opt_cid;
		return(max_id);
	}
}
Exemple #15
0
void CreateShape(int** VarSets,int* lenVarSets,int nVarSets,
				 int lenC,int* C,LPTable S,LPNTable shape)
{
	int i,k;
	const int SD = S->nDimens;
	int indexC[SD];
	int lenF;
	int lenD;
	double s;
	int okay;
	
	for(i=0;i<SD;i++)
	{
		indexC[i]=0;
	}
	for(i=0;i<lenC;i++)
	{
		indexC[C[i]] = 1;
	}
	
	for(i=0;i<shape->Total;i++)
	{
		shape->Data[i] = 0;
	}
			
	shape->GetFirst();
	s = 0.0;
	S->GetFirst();
	okay = 1;
	while(okay)
	{
		if(subset(SD,S->Index,indexC))
		{
			lenF = 0;
			for(k=0;k<SD;k++)
			{
				lenF += S->Index[k];
			}
			s += pow(-1.0,lenF)*S->Get();
		}
		okay = S->GetNext();
	}
	shape->Set(s);
	
	for(i=0;i<nVarSets;i++)
	{
		if(subset(SD,VarSets[i],indexC))
		{
			s = 0.0;
			S->GetFirst();
			okay = 1;
			while(okay)
			{
				if(subset(SD,S->Index,indexC))
				{
					if(subset(SD,VarSets[i],S->Index))
					{
						lenD = lenVarSets[i];
						lenF = 0;
						for(k=0;k<SD;k++)
						{
							lenF += S->Index[k];
						}
						s += pow(-1.0,lenF-lenD)*S->Get();
					}
				}
				okay = S->GetNext();
			}
			shape->SetIndex(VarSets[i]);
			shape->Set(s);
		}
	}
			
	return;
}
Exemple #16
0
void PMN::fillConfigs(){

	for(int i=0; i < (order/2); i++){

		int kappa = (i+1)*2;
		
		//First initialise all configurations, and add them to a vector. As there must be an equal number of p's and m's
		//there are binominal(n,n/2) of these.
		int validConfigs = Utility::BinomialCoefficients<int>(kappa, kappa/2);
		std::vector<PMConfig> allConfigs(validConfigs,PMConfig(kappa));

		//The configurations are filled using a recursive function fillAllConfigs, which is explained in more detail later.
		//After this the vector allConfigs should be filled. At e.q. k^4 it is filled with ppmm, pmpm, pmmp, mpmp, mmpp, mppm
		fillAllConfigs(0,(kappa/2+1),kappa/2,allConfigs,0);

		//Do a superficial ordering of all elements so that they all start with a p and end with an m
		for(auto &conf : allConfigs){
			conf.ordering();
		}

		//Add an emply std::vector<PMPair> to the back of the configurations-list
		//configurations.emplace_back;

		for(int j=0; j<validConfigs; j++){

			bool incr = false;
			//Check through the vector of PMPairs and see if the configuration is already present or not
			for(auto &conf : configurations[i]){

				//If it is present, add to the count and move on. The overloaded equality operator
				//also checks all permutations
				if(allConfigs[j] == conf){
					conf++;
					incr=true;
					break;
				}
			}

			//If it wasn't found, add it
			if(!incr){
				configurations[i].push_back(allConfigs[j]);
				configurations[i].back().finalise();
			}
		}

		//Then add its exponential combinatoric factor: -2/order, the 2 from the gamma-trace
		for(auto &conf : configurations[i]){
			conf *= (PM::pref_type)-2;
			conf /= kappa;
		}
	}

	//At order kappa^2 there are no multi-trace configurations
	if(order == 2){
		return;
	}

	int first_multi_trace = configurations.back().size(); //The number of single trace configurations

	//Here we use the subset_sum function defined in std_libs/std_funcs.h. It takes a list of positive integers to 
	//sum and a target, then it finds all possible ways to sum the numbers in the subset so that the result is the target.
	//E.g. {2,4} to 6 gives 2 lists: {2,2,2},{2,4}
	std::vector<int> subset(order/2 - 1);

	for(int i=0; i < (order/2-1); i++){
		subset[i] = (i+1)*2;
	}

	SubsetSum<> sumCreator(order, subset);
	std::list< std::vector<int> > combinations = sumCreator.calculate();

	//A comb is now a list of which PMConfig's we want to construct the multi-trace contrib
	for(auto &comb : combinations){
		configurations.back().emplace_back(order);
		
		std::list< std::vector<int> > send_set;    //This is a parameter sent between the recursive calls to calculate 
		fill_multi_config(comb,0,0,send_set); 		//the combinatoric factor in the end
	}

	//An iterator which starts at the first multi trace
	multi_trace_begin = configurations.back().begin();
	std::advance(multi_trace_begin, first_multi_trace);

	multi_trace_begin_const = multi_trace_begin;
}
Exemple #17
0
void getNextTheta(int** VarSets,int* lenVarSets,int nVarSets,
                  int* amodel,int lenCL,int* CL,LPNTable smalltheta,LPTable Theta,LPTable nextTheta)
{
	int i,iF;
	int okay1;
	int iE, iL, iC;
	const int NTD = nextTheta->nDimens;
	int* CLcomplement = new int[NTD];
	int* CLfull = new int[NTD];
	int* FunionL = new int[NTD];
	const int TT = Theta->Total;
	double g[TT];
	int len[TT];
	
	for(i=0;i<NTD;i++)
	{
		CLcomplement[i] = 1;
		CLfull[i] = 0;
	}
	for(i=0;i<lenCL;i++)
	{
		CLcomplement[CL[i]] = 0;
		CLfull[CL[i]] = 1;
	}
	
	for(i=0;i<nextTheta->Total;i++)
	{
		nextTheta->Data[i] = Theta->Data[i];
		g[i] = 0;
		len[i]=0;
	}
	
	////////////////////////////////////////////////
	Theta->GetFirst();
	okay1 = 1;
	iF = 0;
	while(okay1)
	{
		len[iF] = lenVarSets[iF];
										
		double s1 = 1.0;
		for(iL=1;iL<nVarSets;iL++)
		{	
			if(subset(Theta->nDimens,VarSets[iL],CLcomplement))
			{
				for(i=0;i<Theta->nDimens;i++)
				{
					FunionL[i] = 0;
					if(VarSets[iL][i]==1) FunionL[i] = 1;
					if(Theta->Index[i]==1) FunionL[i] = 1;
				}
				
				int thereisone = 0;
				double sC = 0.0;
				for(iC=1;iC<nVarSets;iC++)
				{
					if(0==subset(Theta->nDimens,VarSets[iC],Theta->Index))
					{
						if(1==subset(Theta->nDimens,VarSets[iC],FunionL))
						{
							sC += Theta->GetI(VarSets[iC]);
							thereisone = 1;
						}
					}
				}
				if(thereisone)
				{
					s1 += exp(sC);
				}
			}
		}
		g[iF]=log(s1);
		iF++;
		okay1 = Theta->GetNext();
	}
	////////////////////////////////////////////////
	
	nextTheta->GetFirst();
	nextTheta->Set(0);
	iE = 0;
	while(nextTheta->GetNext())
	{
	    iE++;
		if(amodel[iE])
		{
		    if(1==subset(Theta->nDimens,nextTheta->Index,CLfull))
			{
				double s0 = smalltheta->GetI(nextTheta->Index);
				int lenE = 0;
				for(i=0;i<NTD;i++) lenE+=nextTheta->Index[i];
		
				Theta->GetFirst();
				int okay1 = 1;
				iF = 0;
				while(okay1)
				{
					if(len[iF]>=0)
					{
						if(subset(Theta->nDimens,Theta->Index,nextTheta->Index))
						{
							s0 += pow(-1,lenE-len[iF]-1)*g[iF];
						}
					}
					iF++;
					okay1 = Theta->GetNext();
				}
				nextTheta->Set(s0);
			}
			else
			{
				Theta->SetIndex(nextTheta->Index);
				nextTheta->Set(Theta->Get());
			}
		}
		else
		{
			nextTheta->Set(0);
		}
	}

	delete[] CLcomplement; CLcomplement = NULL;
	delete[] CLfull; CLfull = NULL;
	delete[] FunionL; FunionL = NULL;
	return;
}
Exemple #18
0
 std::vector<std::vector<int>> subsets(std::vector<int>& nums) {
     std::sort(nums.begin(), nums.end());
     std::vector<std::vector<int>> r;
     subset(r, nums, 0, std::vector<int>());
     return r;
 }
Exemple #19
0
PdfFont* PdfFontCache::GetFontSubset( const char* pszFontName, bool bBold, bool bItalic, 
				      const PdfEncoding * const pEncoding,
				      const char* pszFileName )
{
    PdfFont*        pFont;
    PdfFontMetrics* pMetrics;
    std::pair<TISortedFontList,TCISortedFontList> it;

    // WARNING: The characters are completely ignored right now!

    it = std::equal_range( m_vecFontSubsets.begin(), m_vecFontSubsets.end(), 
			   TFontCacheElement( pszFontName, bBold, bItalic, pEncoding ) );
    if( it.first == it.second )
    {
	std::string sPath; 
	if( pszFileName == NULL ) 
	{
	    sPath = this->GetFontPath( pszFontName, bBold, bItalic );
	    if( sPath.empty() )
	    {
#ifdef _WIN32
		// TODO: GetWin32Font
		PODOFO_ASSERT( 0 );
#else	    
		PdfError::LogMessage( eLogSeverity_Critical, "No path was found for the specified fontname: %s\n", pszFontName );
		return NULL;
#endif // _WIN32
	    }
	}
	else
	    sPath = pszFileName;
	
	pMetrics = new PdfFontMetrics( &m_ftLibrary, sPath.c_str() );
	if( !(pMetrics && pMetrics->GetFontType() == ePdfFontType_TrueType ) )
	{
	    PODOFO_RAISE_ERROR_INFO( ePdfError_InvalidFontFile, "Subsetting is only supported for TrueType fonts." );
	}
	
	PdfInputDevice          input( sPath.c_str() );
	PdfRefCountedBuffer     buffer;
	PdfOutputDevice         output( &buffer );
	
	PdfFontTTFSubset        subset( &input, pMetrics, PdfFontTTFSubset::eFontFileType_TTF );
	PdfEncoding::const_iterator itChar
	    = pEncoding->begin();
	while( itChar != pEncoding->end() )
	{
	    subset.AddCharacter( *itChar );
	    ++itChar;
	}
	subset.BuildFont( &output );

	// Delete metrics object, as it was only used so that PdfFontTTFSubset could
	// match unicode character points to glyph indeces
	delete pMetrics;
	// TODO: Do not hardcode unique basenames...
	pMetrics = new PdfFontMetrics( &m_ftLibrary, buffer, "ABCDEF+" );
	pFont = this->CreateFontObject( it.first, m_vecFontSubsets, pMetrics, 
					true, bBold, bItalic, pszFontName, pEncoding );
    }
    else
	pFont = (*it.first).m_pFont;


    return pFont;
}
Exemple #20
0
int find_opt_fr(struct DotList *dots, int id, struct perm_pt *st, int w_sid, int w_fid, int h_sid, int h_fid, struct r_list *rp1, int num_rp1, struct r_list *rp2, int num_rp2, int *rp1_id, int *rp2_id, FILE *fp)
{
	int i = 0;
	int min_score = 1000;
	int max_id = -1;
	bool *is_x;
	int *sd;
	int d = 0;
	struct gap_list gps;
	int temp_score = 0;
	int start, mid1 = -1, mid2 = -1, end;
	float *d_rate;
	float min_rate = 100;
	int len1 = 0, len2 = 0, len = 0, m_th = 0;
	int op_len = 0, op_len_x = 0, op_len_y = 0;
	int closeness = 0;
	struct I temp;
	int y_cur = 0, y_old = 0;
	int *id1, *id2;
	
	is_x = (bool *) ckalloc(sizeof(bool));
	sd = (int *) ckalloc(sizeof(int));
	d_rate = (float *) ckalloc(sizeof(float));
	id1 = (int *) ckalloc(sizeof(int));
	id2 = (int *) ckalloc(sizeof(int));
	*rp1_id = -1;
	*rp2_id = -1;
	*id1 = -1;
	*id2 = -1;

	gps.type = -1;
	gps.id1 = -1;
	gps.id2 = -1;
	gps.x1 = 0;
	gps.x2 = 1;
	gps.y1 = 0;
	gps.y2 = 1;
	strcpy(gps.name1, "");
	strcpy(gps.name2, "");

	if( w_sid < h_sid )
	{
		start = w_sid;
		if( w_fid < h_sid )
		{
			mid1 = w_fid;
			mid2 = h_sid;
			end = h_fid;
		}
		else 
		{
			if( w_fid < h_fid ) end = h_fid;
			else end = w_fid;
		}
	}
	else 
	{
		start = h_sid;
		if( h_fid < w_sid )
		{
			mid1 = h_fid;
			mid2 = w_sid;
			end = w_fid;
		}
		else
		{
			if( h_fid < w_fid ) end = w_fid;
			else end = h_fid;
		}
	}

	// m_x and m_y save the coordinated of the initial alignment before getting chained
	for( i = start; i <= end; i++ )
	{
		if( st[i].id == id ) {}	
		else if( (strcmp(dots[st[i].id].name1, dots[id].name1) != 0) || (strcmp(dots[st[i].id].name2, dots[id].name2) != 0) ) {}
		else if( dots[st[i].id].x.lower > dots[id].x.lower ) {}
		else if( dots[st[i].id].x.lower > dots[id].m_x.lower ) {}
		else if( (dots[st[i].id].sign == 0) && (dots[st[i].id].y.lower > dots[id].y.lower )) {}
		else if( (dots[st[i].id].sign == 1) && (dots[st[i].id].y.lower < dots[id].y.lower )) {}
		else if( subset(dots[st[i].id].m_x, dots[id].x) || subset(dots[st[i].id].m_y, dots[id].y) || subset(dots[id].m_x, dots[st[i].id].x) || subset(dots[id].m_y, dots[st[i].id].y) ) {}
		else if( (mid1 != -1) && (i > mid1) && (i < mid2)) {}
		else
		{
// is_x of 'distance' function is true if x region is larger 
			if((dots[st[i].id].sign != 2) && (dots[st[i].id].sign == dots[id].sign) && ((d = distance(dots, st[i].id, id, is_x, sd)) <= MDIS_THRESHOLD))
			{
				len1 = width(dots[st[i].id].x);
				len2 = width(dots[id].x);

				if( len1 > len2 ) len = len2;
				else len = len1;

				if( (len1 >= LG_TH) && (len2 >= LG_TH ) ) m_th = L_M_TH;
				else m_th = M_TH;

				if((*sd) <= len)
				{
					op_len = 0;
					op_len_x = 0;
					op_len_y = 0;

       		if( proper_overlap(dots[st[i].id].x, dots[id].x) == true )
          {
            op_len_x = width(intersect(dots[st[i].id].x, dots[id].x));
            op_len = op_len_x;
          }

          if( proper_overlap(dots[st[i].id].y, dots[id].y) == true )
          {
            op_len_y = width(intersect(dots[st[i].id].y, dots[id].y));
            if( op_len < op_len_y ) op_len = op_len_y;
					}

          if( ((*sd) > m_th) || (op_len > m_th) )
          {
            if( (strict_almost_equal(dots[st[i].id].x, dots[id].x) == true) || (strict_almost_equal(dots[st[i].id].y, dots[id].y) == true) )
            {
              gps.type = -1;
            }
						else if( ((closeness = compute_closeness(dots, st[i].id, id)) <= C_OP_TH) && ((*sd) > m_th) && (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true )) {
							gps = define_gap(dots, st[i].id, id, d, *sd, *is_x);
						}
						else if( ((*sd) > m_th) && (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true )) {
							gps.type = -1;
						}
						else if((proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true ))
						{
							temp = intersect(dots[st[i].id].x, dots[id].x);
							if( dots[id].sign == 0 ) {
								y_cur = dots[id].y.lower;
								y_old = find_yloc_one(dots[st[i].id], fp, temp.lower-dots[st[i].id].x.lower, NO_GAP_INC);
							}
							else if( dots[id].sign == 1 ) {
								y_cur = find_yloc_one(dots[st[i].id], fp, temp.lower-dots[st[i].id].x.lower, NO_GAP_INC);
								y_old = dots[id].y.upper;
							}

							if( y_old >= y_cur ) {
								gps = define_gap_new_type(dots, st[i].id, id, false);
								if( gps.type == -1 ) gps = define_gap_new_type(dots, st[i].id, id, true);
							}
							else if( y_old < y_cur ) {
								gps = define_gap_new_type(dots, st[i].id, id, true);
								if( gps.type == -1 ) gps = define_gap_new_type(dots, st[i].id, id, false);
							}
						}
            else if( proper_overlap(dots[st[i].id].x, dots[id].x) == true )
            {
              gps = define_gap_new_type(dots, st[i].id, id, true);
            }
            else if( proper_overlap(dots[st[i].id].y, dots[id].y) == true )
            {
              gps = define_gap_new_type(dots, st[i].id, id, false);
            }
						else gps.type = -1;
					}
					else if( ((closeness = compute_closeness(dots, st[i].id, id)) > C_OP_TH) && (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true )) 
					{
						closeness = compute_closeness(dots, st[i].id, id);
						temp = intersect(dots[st[i].id].x, dots[id].x);
						if( dots[id].sign == 0 ) {
							y_cur = dots[id].y.lower;
							y_old = find_yloc_one(dots[st[i].id], fp, temp.lower-dots[st[i].id].x.lower, NO_GAP_INC);
						}
						else if( dots[id].sign == 1 ) {
							y_cur = find_yloc_one(dots[st[i].id], fp, temp.lower-dots[st[i].id].x.lower, NO_GAP_INC);
							y_old = dots[id].y.upper;
						}
						if( y_old >= y_cur ) {
							gps = define_gap_new_type(dots, st[i].id, id, false);
							if( gps.type == -1 ) gps = define_gap_new_type(dots, st[i].id, id, true);
						}
						else if( y_old < y_cur ) {
							gps = define_gap_new_type(dots, st[i].id, id, true);
							if( gps.type == -1 ) gps = define_gap_new_type(dots, st[i].id, id, false);
						}
					}
					else if( (check_candi(dots, id, st[i].id, *is_x) == false) && ( (*sd) > TD_TH)) gps.type = -1;
			  	else
					{
            if( (proper_overlap(dots[st[i].id].x, dots[id].x) == true) && (proper_overlap(dots[st[i].id].y, dots[id].y) == true ) ) {
							gps = define_gap(dots, st[i].id, id, d, *sd, *is_x);
						}
            else if( proper_overlap(dots[st[i].id].x, dots[id].x) == true )
            {
              gps = define_gap_new_type(dots, st[i].id, id, true);
            }
            else if( proper_overlap(dots[st[i].id].y, dots[id].y) == true )
            {

              gps = define_gap_new_type(dots, st[i].id, id, false);
            }
						else gps = define_gap(dots, st[i].id, id, d, *sd, *is_x);
					}

					if((gps.type == -1) || (gps.type == 3)) // this gap is meaningless
					{
					}
					else
					{
						gps.rp_id1 = -1;
						gps.rp_id2 = -1;
						if( abs(gps.y2 - gps.y1) < ERR_LG_TH ) {
							gps.type = 0;
						}
						temp_score = get_score(dots, gps, d_rate, rp1, num_rp1, rp2, num_rp2, id1, id2, fp);

						if( temp_score == -1 ) {
							if( (gps.type == 21) || (gps.type == 22) ) {
								if( gps.type == 21 ) {
									gps = define_gap_new_type(dots, st[i].id, id, false);
								}
								else if( gps.type == 22 ) {
									gps = define_gap_new_type(dots, st[i].id, id, true);
								}
					
								if((gps.type == -1) || (gps.type == 3)) {}// this gap is meaningless
								else temp_score = get_score(dots, gps, d_rate, rp1, num_rp1, rp2, num_rp2, id1, id2, fp);
							}
						}

					  if( temp_score != -1 )
						{
							if( min_score > temp_score )
							{
								min_score = temp_score;
								max_id = st[i].id;
								*rp1_id = *id1;
								*rp2_id = *id2;
							}
							else if( min_score == temp_score )
							{
								if( (*d_rate) <= min_rate ) 
								{
									min_rate = (*d_rate);
									min_score = temp_score;
									max_id = st[i].id;
									*rp1_id = *id1;
									*rp2_id = *id2;
								}
							}	
						}
					}
				}
			}
		}
	}

	free(id1);
	free(id2);
	free(d_rate);
	free(sd);
	free(is_x);
	if( max_id == -1 ) 
	{
		return(-1);
	}
	else 
	{
		return(max_id);
	}
}
Exemple #21
0
static bool test_sqrt(double al, double au) {
  I a(al, au);
  I b = square(sqrt(a));
  return subset(abs(a), b);
}
Exemple #22
0
void
DataLink::data_received_i(ReceivedDataSample& sample,
                          const RepoId& readerId,
                          const RepoIdSet& incl_excl,
                          ReceiveListenerSet::ConstrainReceiveSet constrain)
{
  DBG_ENTRY_LVL("DataLink", "data_received_i", 6);
  // Which remote publication sent this message?
  const RepoId& publication_id = sample.header_.publication_id_;

  // Locate the set of TransportReceiveListeners associated with this
  // DataLink that are interested in hearing about any samples received
  // from the remote publisher_id.
  if (DCPS_debug_level > 9) {
    const GuidConverter converter(publication_id);
    const GuidConverter reader(readerId);
    ACE_DEBUG((LM_DEBUG,
               ACE_TEXT("(%P|%t) DataLink::data_received_i: ")
               ACE_TEXT("from publication %C received sample: %C to readerId %C (%s).\n"),
               OPENDDS_STRING(converter).c_str(),
               to_string(sample.header_).c_str(),
               OPENDDS_STRING(reader).c_str(),
               constrain == ReceiveListenerSet::SET_EXCLUDED ? "SET_EXCLUDED" : "SET_INCLUDED"));
  }

  if (Transport_debug_level > 9) {
    const GuidConverter converter(publication_id);
    ACE_DEBUG((LM_DEBUG,
               ACE_TEXT("(%P|%t) DataLink::data_received_i: ")
               ACE_TEXT("from publication %C received sample: %C.\n"),
               OPENDDS_STRING(converter).c_str(),
               to_string(sample.header_).c_str()));
  }

  ReceiveListenerSet_rch listener_set;
  {
    GuardType guard(this->pub_sub_maps_lock_);
    AssocByRemote::iterator iter = assoc_by_remote_.find(publication_id);
    if (iter != assoc_by_remote_.end())
      listener_set = iter->second;

    if (listener_set.is_nil() && this->default_listener_) {
      this->default_listener_->data_received(sample);
      return;
    }
  }

  if (listener_set.is_nil()) {
    // Nobody has any interest in this message.  Drop it on the floor.
    if (Transport_debug_level > 4) {
      const GuidConverter converter(publication_id);
      ACE_DEBUG((LM_DEBUG,
                 ACE_TEXT("(%P|%t) DataLink::data_received_i: ")
                 ACE_TEXT(" discarding sample from publication %C due to no listeners.\n"),
                 OPENDDS_STRING(converter).c_str()));
    }

    return;
  }

  if (readerId != GUID_UNKNOWN) {
    listener_set->data_received(sample, readerId);
    return;
  }

#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE

  if (sample.header_.content_filter_
      && sample.header_.content_filter_entries_.length()) {
    ReceiveListenerSet subset(*listener_set.in());
    subset.remove_all(sample.header_.content_filter_entries_);
    subset.data_received(sample, incl_excl, constrain);

  } else {
#endif // OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE

    if (DCPS_debug_level > 9) {
      // Just get the set to do our dirty work by having it iterate over its
      // collection of TransportReceiveListeners, and invoke the data_received()
      // method on each one.
      OPENDDS_STRING included_ids;
      bool first = true;
      RepoIdSet::const_iterator iter = incl_excl.begin();
      while(iter != incl_excl.end()) {
        included_ids += (first ? "" : "\n") + OPENDDS_STRING(GuidConverter(*iter));
        first = false;
        ++iter;
      }
      ACE_DEBUG((LM_DEBUG, "(%P|%t) DataLink::data_received_i - normal data received to each subscription in listener_set %s ids:%C\n",
                 constrain == ReceiveListenerSet::SET_EXCLUDED ? "exclude" : "include", included_ids.c_str()));
    }
    listener_set->data_received(sample, incl_excl, constrain);
#ifndef OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
  }

#endif // OPENDDS_NO_CONTENT_SUBSCRIPTION_PROFILE
}
KrawczykResult Krawczyk<MapType>::proof (const typename MapType::VectorType &A_x0,
                                         const typename MapType::VectorType &A_X,
                                         int maxNumberOfIterations)
{

 x0 = A_x0;
 X = A_X;

 KrawczykResult exit_code = TooManyIterations;
 bool comp_F_x0 = true ;           // flag : true = computation of F(x_0) is needed

 for(numberOfIterations=1; numberOfIterations<maxNumberOfIterations; numberOfIterations++)  // iteration of taking intersection and Krawczyk metod
 {
    // Computation for a point x0
    if(comp_F_x0)
    {
       comp_F_x0 = false;

       typename MapType::MatrixType dF_x0(dim, dim);

       F_x0 = F(x0, dF_x0);

       // We take as matrix C for Krawczyk operator an inverse of Jacobi matrix at point x0
       C = midMatrix(capd::matrixAlgorithms::gaussInverseMatrix(midMatrix(dF_x0)));

       // We check if C is invertible. If it fails, an excepction will be thrown.
       capd::matrixAlgorithms::gaussInverseMatrix(C);

    }

    // computation for the set X
    dF_X = F[X];

    /*  KRAWCZYK OPERATOR   */
    K = x0 - C * F_x0 +(MapType::MatrixType::Identity(dim) - C * dF_X)*(X-x0);   //Krawczyk

    if( subsetInterior(K, X))
    {
        // K is subset of int X  - there exists exactly one zero of F in X
        exit_code = ZeroExists;
        break;
    }
    else
    {
       if(subset(X, K))
       {
           // K contains X - try to change parameters
         exit_code = ResultUndefined;
         break;
       }
       else
       {
          try
          {
            X=intersection(X, K);
            // X is partialy contained in K - we try to take intersection of X and K as new set X
            if( !subset(x0, X))
            {
                x0=midVector(X);
                comp_F_x0 = true;
            }
          }
          catch(std::runtime_error &e)
          {
             //Intersection of X and K is empty. There is no zeroes in set X";
             exit_code = NoZeroes;
             break;
          }
       }
    }
 }

 return exit_code;
}
Exemple #24
0
int
subsumes(const Clause &cl1, const Clause &cl2, Substitutions &s)
{
	// clear substitution list
	s.clear();

	// make sure the clauses are not the same one.
	// this check works since the index in literals
	// are never reassigned.
	//
	if (cl1 == cl2)
	{
		return(NOMATCH);
	}

	// check that every class in clause 1 exists in clause 2. 
	if (subset(cl1, cl2) != OK)
	{
		return(NOMATCH);
	}

	// now start the actual subsumption algorithm.
	Substitutions subs;
	Clause clause2(cl2);
	if (groundSubstitutions(clause2, subs) != OK)
	{
		ERROR("groundSubstitutions failed.", errno);
		return(NOTOK);
	}

	// convert second clause to a ground clause
	if (subs.applyTo(clause2) != OK)
	{
		ERROR("applyTo failed.", errno);
		return(NOTOK);
	}

	// copy clauses to arrays
	Array<Literal> clarray1(1, cl1.getTotalMembers());
	ClauseIterator cl1Iter(cl1);
	for (int i=1; !cl1Iter.done(); i++, cl1Iter++)
	{
		clarray1[i] = cl1Iter();
	}
	Array<Literal> clarray2(1, cl2.getTotalMembers());
	ClauseIterator cl2Iter(clause2);
#ifdef SC42
	for (i=1; !cl2Iter.done(); i++, cl2Iter++)
#else
	for (int i=1; !cl2Iter.done(); i++, cl2Iter++)
#endif
	{
		clarray2[i] = cl2Iter();
	}

	// use Stillman's algorithm
	statistics[AttemptedStillmanSubsumptionTests] += 1;
	totalstatistics[TotalAttemptedStillmanSubsumptionTests] += 1;
	int status = ST(clarray1, clarray2, 1, 1, s);
	if (status == OK && verbose)
	{
		cout << endl;
		cout << "clause1 subsumes clause2 ..." << endl;
		cout << "clause1: " << cl1 << endl;
		cout << "clause2: " << cl2 << endl;
	}
	return(status);
}
size_t
wxPdfFontDataTrueTypeUnicode::WriteFontData(wxOutputStream* fontData, wxPdfSortedArrayInt* usedGlyphs, wxPdfChar2GlyphMap* subsetGlyphs)
{
  bool isMacCoreText = false;
  bool deleteFontStream = false;
  wxUnusedVar(subsetGlyphs);
  size_t fontSize1 = 0;
  wxFSFile* fontFile = NULL;
  wxInputStream* fontStream = NULL;
  bool compressed = false;
  wxString fontFullPath = wxEmptyString;
  wxFileName fileName;
  if (m_fontFileName.IsEmpty())
  {
#if defined(__WXMSW__)
    if (m_file.IsEmpty() && m_font.IsOk())
    {
      fontStream = wxPdfFontParserTrueType::LoadTrueTypeFontStream(m_font);
      deleteFontStream = true;
    }
    else
#elif defined(__WXMAC__)
#if wxPDFMACOSX_HAS_CORE_TEXT
    if (m_file.IsEmpty() && m_font.IsOk())
    {
      fontStream = new wxMemoryInputStream("dummy", 5);
      deleteFontStream = true;
      isMacCoreText = true;
    }
    else
#endif
#endif
    {
      // Font data preprocessed by MakeFont
      compressed = m_file.Lower().Right(2) == wxT(".z");
      fileName = m_file;
      fileName.MakeAbsolute(m_path);
    }
  }
  else
  {
    fileName = m_fontFileName;
  }

  if (fileName.IsOk())
  {
    // Open font file
    wxFileSystem fs;
    fontFile = fs.OpenFile(wxFileSystem::FileNameToURL(fileName));
    if (fontFile)
    {
      fontStream = fontFile->GetStream();
      deleteFontStream = false;
      fontFullPath = fileName.GetFullPath();
    }
    else
    {
      // usually this should not happen since file accessability was already checked
      wxLogError(wxString(wxT("wxPdfFontDataTrueTypeUnicode::WriteFontData: ")) +
                 wxString::Format(_("Font file '%s' not found."), fileName.GetFullPath().c_str()));
    }
  }
  
  if (fontStream != NULL)
  {
    if (usedGlyphs != NULL)
    {
      if (compressed)
      {
        // Uncompress font file
        wxZlibInputStream zCompressed(*fontStream);
        wxMemoryOutputStream zUncompressed;
        zUncompressed.Write(zCompressed);
        zUncompressed.Close();
        fontStream = new wxMemoryInputStream(zUncompressed);
        deleteFontStream = true;
      }

      // Assemble subset
      wxPdfFontSubsetTrueType subset(fontFullPath, 0, isMacCoreText);
      wxMemoryOutputStream* subsetStream = subset.CreateSubset(fontStream, usedGlyphs, false);
      if (deleteFontStream && fontStream != NULL)
      {
        delete fontStream;
      }

      // Write font subset data
      wxZlibOutputStream zFontData(*fontData);
      wxMemoryInputStream tmp(*subsetStream);
      fontSize1 = tmp.GetSize();
      zFontData.Write(tmp);
      zFontData.Close();
      delete subsetStream;
    }
    else
    {
      if (!compressed)
      {
        fontSize1 = fontStream->GetSize();
        wxZlibOutputStream zFontData(*fontData);
        zFontData.Write(*fontStream);
        zFontData.Close();
      }
      else
      {
        fontSize1 = GetSize1();
        fontData->Write(*fontStream);
      }
    }
  }

  if (fontFile != NULL)
  {
    delete fontFile;
  }

  return fontSize1;
}
int main(int argc, char** argv){
	//srand will force the random numbers to be always the same, so we can verify that our code works
	//normally we would want them to be different.
	srand(100);
	struct DataSet* setA;
	setA = allocDataSet();

	struct DataSet* setB;
	setB = allocDataSet();


	int i = 0;
	for(i = 0; i < 30; ++i){
		Byte element = rand() % 20;
		appendDataSet(setA, element);
		Byte event = rand() % 100;
		if(event < 30){
			//30% of chance of repeating the same number
			appendDataSet(setB, element);
		}
		else if(event < 65){
			//65% of chance of adding a different element
			//event should be a number between 0 and 99
			//make it between 0 and 49 included
			appendDataSet(setB, event % 50);
		}
		else{
			//C requires an else, even if it is empty,
			//this else does nothing, so setB could be smaller than setA
		}
	}
	//Data has been initialized, now lets test the other methods
	//Print
	printf("SET A IS:\n");
	printDataSet(setA);
	printf("SET B IS:\n");
	printDataSet(setB);

	//Union (notice that union is another C keyword),
	//actually what is does is like a struct,
	//but guarantees the block will be put right after the other
	//in this class you dont need to know it, but once more, if you want to learn
	struct DataSet* unionSet;
	unionSet = unionDataSet(setA, setB);

	printf("A UNION B:\n");
	printDataSet(unionSet);

	//Intersection
	struct DataSet* intersectionSet;
	intersectionSet = intersectionDataSet(setA, setB);

	printf("A INTERSECTION B:\n");
	printDataSet(intersectionSet);

	//Set difference
	struct DataSet* diffSet;
	diffSet = diffDataSet(setA, setB);

	printf("A DIFF B:\n");
	printDataSet(diffSet);

	//Subset Test
	struct DataSet* subsetTest;
	subsetTest = subset(unionSet, 3, 7);

	printf("ORIGINAL SET:\n");
	printDataSet(unionSet);

	printf("SUBSET:\n");
	printDataSet(subsetTest);
	printf("subsetTest %s a subset of unionSet\n", isSubset(subsetTest, unionSet) ? "IS" : "IS NOT");
	printf("unionSet %s a subset of subsetSet\n", isSubset(unionSet, subsetTest) ? "IS" : "IS NOT");

	struct DataSet* emptySet = allocDataSet();
	//no data added so it should be the nullSet
	printf("THE EMPTY SET LOOKS LIKE:\n");
	printDataSet(emptySet);
	printf("emptySet %s equal to the NULL set\n", isNull(emptySet) ? "IS" : "IS NOT");

	struct DataSet* reverseSet = allocDataSet();
	for(i = unionSet->length - 1; i >= 0; --i){
		appendDataSet(reverseSet, unionSet->data[i]);
	}
	printf("reverseSet %s equal unionSet\n", equals(unionSet, reverseSet) ? "IS" : "IS NOT");
	printf("reverseSet %s %u\n", contains(reverseSet, unionSet->data[0]) ? "CONTAINSS" : "DOES NOT CONTAIN", unionSet->data[0]);
	printDataSet(reverseSet);

	//Statistics:
	printf("ORGINAL SET FOR STATISTICS:\n");
	printDataSet(unionSet);
	printf("Min value %u\n", unionSet->min);
	printf("Max value %u\n", unionSet->max);
	printf("Avg value %f\n", AverageDataSet(unionSet));
	printf("Range value %u\n", RangeDataSet(unionSet));

	//Release the DataSets resources after finish their usage.
	releaseDataSet(setA);
	releaseDataSet(setB);

	return 0;
}
Exemple #27
0
template<class T, class Policies1, class Policies2> inline
bool operator>=(const interval<T, Policies1>& x, const interval<T, Policies2>& y)
{
  return subset(y, x);
}
Exemple #28
0
static Array<Tuple<time_kind_t,event_t>> dependencies(const int direction, const time_kind_t kind, const event_t event) {
  GEODE_ASSERT(abs(direction)==1);
  static_assert(compress_kind==0,"Verify that -kind != kind for kinds we care about");

  // Parse event
  const section_t section = parse_section(event);
  const auto block = parse_block(event);
  const uint8_t dimensions = parse_dimensions(event),
                parent_to_child_symmetry = dimensions>>2,
                dimension = dimensions&3;
  const auto ekind = event&ekind_mask;

  // See mpi/graph for summarized explanation
  Array<Tuple<time_kind_t,event_t>> deps;
  switch (direction*kind) {
    case -allocate_line_kind: {
      GEODE_ASSERT(ekind==line_ekind);
      break; }
    case  response_recv_kind:
    case -request_send_kind: {
      GEODE_ASSERT(ekind==block_lines_ekind);
      const auto other_kind = kind==response_recv_kind ? schedule_kind : allocate_line_kind;
      const auto parent_section = section.parent(dimension).transform(symmetry_t::invert_global(parent_to_child_symmetry));
      const auto permutation = section_t::quadrant_permutation(parent_to_child_symmetry);
      const uint8_t parent_dimension = permutation.find(dimension);
      const auto block_base = Vector<uint8_t,4>(block.subset(permutation)).remove_index(parent_dimension);
      deps.append(tuple(other_kind,line_event(parent_section,parent_dimension,block_base)));
      break; }
    case  request_send_kind: {
      GEODE_ASSERT(ekind==block_lines_ekind);
      deps.append(tuple(response_send_kind,event));
      break; }
    case -response_send_kind:
    case  response_send_kind: {
      GEODE_ASSERT(ekind==block_lines_ekind);
      deps.append(tuple(direction<0?request_send_kind:response_recv_kind,event));
      break; }
    case -response_recv_kind: {
      GEODE_ASSERT(ekind==block_lines_ekind);
      deps.append(tuple(response_send_kind,event));
      break; }
    case  allocate_line_kind:
    case -schedule_kind: {
      GEODE_ASSERT(ekind==line_ekind);
      if (section.sum()!=35) {
        const auto other_kind = kind==allocate_line_kind ? request_send_kind : response_recv_kind;
        const auto child_section = section.child(dimension).standardize<8>();
        const auto permutation = section_t::quadrant_permutation(symmetry_t::invert_global(child_section.y));
        const uint8_t child_dimension = permutation.find(dimension);
        const dimensions_t dimensions(child_section.y,child_dimension);
        auto child_block = Vector<uint8_t,4>(block.slice<0,3>().insert(0,dimension).subset(permutation));
        for (const uint8_t b : range(section_blocks(child_section.x)[child_dimension])) {
          child_block[child_dimension] = b;
          deps.append(tuple(other_kind,block_lines_event(child_section.x,dimensions,child_block)));
        }
      }
      break; }
    case  schedule_kind: {
      GEODE_ASSERT(ekind==line_ekind);
      deps.append(tuple(compute_kind,event)); // Corresponds to many different microline compute events
      break; }
    case -compute_kind: // Note: all microline compute events have the same line event
    case  compute_kind: {
      GEODE_ASSERT(ekind==line_ekind);
      deps.append(tuple(direction<0?schedule_kind:wakeup_kind,event));
      break; }
    case -wakeup_kind: {
      GEODE_ASSERT(ekind==line_ekind);
      deps.append(tuple(compute_kind,event)); // Corresponds to many different microline compute events
      break; }
    case  wakeup_kind: {
      GEODE_ASSERT(ekind==line_ekind);
      const auto block_base = block.slice<0,3>();
      for (const uint8_t b : range(section_blocks(section)[dimension]))
        deps.append(tuple(output_send_kind,block_line_event(section,dimension,block_base.insert(b,dimension))));
      break; }
    case -output_send_kind:
    case  output_send_kind: {
      GEODE_ASSERT(ekind==block_line_ekind);
      if (direction<0)
        deps.append(tuple(wakeup_kind,line_event(section,dimension,block.remove_index(dimension))));
      else
        deps.append(tuple(output_recv_kind,event));
      break; }
    case -output_recv_kind:
    case  output_recv_kind: {
      GEODE_ASSERT(ekind==block_line_ekind);
      deps.append(tuple(direction<0?output_send_kind:snappy_kind,event));
      break; }
    case -snappy_kind:
    case  snappy_kind: {
      GEODE_ASSERT(ekind==block_line_ekind);
      if (direction<0)
        deps.append(tuple(output_recv_kind,event));
      break; }
    default:
      break;
  }
  return deps;
}
SpatiallySparseDataset SpatiallySparseDataset::subset(int n) {
  SpatiallySparseDataset subset(*this);
  subset.shuffle();
  subset.pictures.resize(n);
  return subset;
}
int main(int argc, char ** argv)
{
    clock_t t0;
    t0 = clock();
    bool print = true;

    if (argc==1)
    {
        help();
        exit(0);
    }

    std::string cmd(argv[1]);

    //primitive programs that do not require help pages and summary statistics by default
    if (argc>1 && cmd=="view")
    {
        print = view(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="index")
    {
        print = index(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="merge")
    {
        print = merge(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="paste")
    {
        print = paste(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="concat")
    {
        print = concat(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="subset")
    {
        subset(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="decompose")
    {
        decompose(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="normalize")
    {
        print = normalize(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="config")
    {
        config(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="mergedups")
    {
        merge_duplicate_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="remove_overlap")
    {
        remove_overlap(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="peek")
    {
        peek(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="partition")
    {
        partition(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_variants")
    {
        annotate_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_regions")
    {
        annotate_regions(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_dbsnp_rsid")
    {
        annotate_dbsnp_rsid(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="discover")
    {
        discover(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="merge_candidate_variants")
    {
        merge_candidate_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="union_variants")
    {
        union_variants(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="genotype")
    {
        genotype2(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="characterize")
    {
        genotype(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="construct_probes")
    {
        construct_probes(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_indels")
    {
        profile_indels(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_snps")
    {
        profile_snps(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_mendelian")
    {
        profile_mendelian(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_na12878")
    {
        profile_na12878(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_chrom")
    {
        profile_chrom(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="align")
    {
        align(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="compute_features")
    {
        compute_features(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_afs")
    {
        profile_afs(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_hwe")
    {
        profile_hwe(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="profile_len")
    {
        profile_len(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="annotate_str")
    {
        annotate_str(argc-1, ++argv);
    }
    else if (argc>1 && cmd=="consolidate_variants")
    {
        consolidate_variants(argc-1, ++argv);
    }
    else
    {
        std::clog << "Command not found: " << argv[1] << "\n\n";
        help();
        exit(1);
    }

    if (print)
    {
        clock_t t1;
        t1 = clock();
        print_time((float)(t1-t0)/CLOCKS_PER_SEC);
    }

    return 0;
}